Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
*/
public class MasterkeyFile {

static final int MAX_SCRYPT_COST_PARAM = 1 << 20;
static final int MAX_SCRYPT_BLOCK_SIZE = 64;


private static final Gson GSON = new GsonBuilder() //
.setPrettyPrinting() //
.disableHtmlEscaping() //
Expand Down Expand Up @@ -75,6 +79,9 @@ boolean isValid() {
&& scryptSalt != null
&& scryptCostParam > 1
&& scryptBlockSize > 0
&& scryptCostParam <= MAX_SCRYPT_COST_PARAM
&& scryptBlockSize <= MAX_SCRYPT_BLOCK_SIZE
&& !Scrypt.exceedsWorkingMemoryLimit(scryptCostParam, scryptBlockSize)
&& encMasterKey != null
&& macMasterKey != null
&& versionMac != null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ public void persist(Masterkey masterkey, OutputStream out, CharSequence passphra
// visible for testing
void persist(Masterkey masterkey, OutputStream out, CharSequence passphrase, @Deprecated int vaultVersion, int scryptCostParam) throws IOException {
Preconditions.checkArgument(!masterkey.isDestroyed(), "masterkey has been destroyed");
Preconditions.checkArgument(scryptCostParam <= MasterkeyFile.MAX_SCRYPT_COST_PARAM, "scryptCostParam out of accepted range");

MasterkeyFile fileContent = lock(masterkey, passphrase, vaultVersion, scryptCostParam);
try (Writer writer = new OutputStreamWriter(out, UTF_8)) {
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/org/cryptomator/cryptolib/common/Scrypt.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@

public class Scrypt {

/**
* Upper bound for the scrypt working memory (V + B + XY), in bytes.
* The default configuration is given in {@link MasterkeyFileAccess} and needs ~32MiB
*/
private static final long MAX_WORKING_MEMORY_BYTES = 1024L * 1024 * 1024; // 1 GiB
private static final int P = 1; // scrypt parallelization parameter

private Scrypt() {
Expand Down Expand Up @@ -71,6 +76,9 @@ public static byte[] scrypt(byte[] passphrase, byte[] salt, int costParam, int b
if (blockSize > Integer.MAX_VALUE / 128 / P) {
throw new IllegalArgumentException("Parameter r is too large");
}
if (exceedsWorkingMemoryLimit(costParam, blockSize)) {
throw new IllegalArgumentException("Parameter combination r * N requires too much memory");
}

try (DestroyableSecretKey key = new DestroyableSecretKey(passphrase, "HmacSHA256");
ObjectPool.Lease<Mac> mac = MacSupplier.HMAC_SHA256.keyed(key)) {
Expand All @@ -92,6 +100,17 @@ public static byte[] scrypt(byte[] passphrase, byte[] salt, int costParam, int b
}
}

/**
* Checks whether the working memory required by the given scrypt parameters exceeds the enforced upper bound.
*
* @param costParam Cost parameter <code>N</code>
* @param blockSize Block size <code>r</code>
* @return <code>true</code> if {@link #scrypt(byte[], byte[], int, int, int)} would reject this parameter combination due to its memory requirements
*/
static boolean exceedsWorkingMemoryLimit(int costParam, int blockSize) {
return (long) blockSize * costParam > MAX_WORKING_MEMORY_BYTES / 128;
Comment thread
infeo marked this conversation as resolved.
Resolved
Comment thread
infeo marked this conversation as resolved.
Resolved
}

/**
* Implementation of PBKDF2 (RFC2898).
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.Path;
import java.security.SecureRandom;

Expand Down Expand Up @@ -122,6 +126,61 @@ public void testLoadMalformed() {

}

/**
* Regression tests for <a href="https://github.com/cryptomator/cryptolib/issues/133">#133</a>:
* scrypt parameters read from an untrusted masterkey file must be range-checked before they reach the key derivation.
*/
@Nested
@DisplayName("load() with out of range scrypt parameters")
class LoadWithOutOfRangeScryptParams {

@ParameterizedTest(name = "scryptCostParam = {0}")
@DisplayName("rejects oversized scryptCostParam without deriving a key")
@ValueSource(ints = {MasterkeyFile.MAX_SCRYPT_COST_PARAM << 1, 1 << 30, Integer.MAX_VALUE})
public void testLoadWithOversizedCostParam(int scryptCostParam) throws IOException, InvalidPassphraseException {
keyFile.scryptCostParam = scryptCostParam;
InputStream in = new ByteArrayInputStream(serialize(keyFile));

Assertions.assertThrows(IOException.class, () -> {
masterkeyFileAccess.load(in, "asd");
});
Mockito.verify(masterkeyFileAccess, Mockito.never()).unlock(ArgumentMatchers.any(), ArgumentMatchers.any());
}

@ParameterizedTest(name = "scryptBlockSize = {0}")
@DisplayName("rejects oversized scryptBlockSize without deriving a key")
@ValueSource(ints = {MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE << 1, 1 << 20, Integer.MAX_VALUE})
public void testLoadWithOversizedBlockSize(int scryptBlockSize) throws IOException, InvalidPassphraseException {
keyFile.scryptBlockSize = scryptBlockSize;
InputStream in = new ByteArrayInputStream(serialize(keyFile));

Assertions.assertThrows(IOException.class, () -> {
masterkeyFileAccess.load(in, "asd");
});
Mockito.verify(masterkeyFileAccess, Mockito.never()).unlock(ArgumentMatchers.any(), ArgumentMatchers.any());
}

@Test
@DisplayName("rejects scryptCostParam * scryptBlockSize exceeding the memory limit without deriving a key")
public void testLoadWithOversizedMemoryRequirement() throws IOException, InvalidPassphraseException {
keyFile.scryptCostParam = MasterkeyFile.MAX_SCRYPT_COST_PARAM;
keyFile.scryptBlockSize = MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE; // 2^20 * 64 * 128 = 8 GiB
InputStream in = new ByteArrayInputStream(serialize(keyFile));

Assertions.assertThrows(IOException.class, () -> {
masterkeyFileAccess.load(in, "asd");
});
Mockito.verify(masterkeyFileAccess, Mockito.never()).unlock(ArgumentMatchers.any(), ArgumentMatchers.any());
}

private byte[] serialize(MasterkeyFile keyFile) throws IOException {
StringWriter writer = new StringWriter();
keyFile.write(writer);
return writer.toString().getBytes(UTF_8);
}

}

@Nested
@DisplayName("unlock()")
class Unlock {
Expand All @@ -134,6 +193,26 @@ public void testUnlockWithCorrectPassword() throws CryptoException {
Assertions.assertNotNull(key);
}

@Test
@DisplayName("with oversized scryptCostParam")
public void testUnlockWithOversizedCostParam() {
keyFile.scryptCostParam = MasterkeyFile.MAX_SCRYPT_COST_PARAM << 1;

Assertions.assertThrows(IllegalArgumentException.class, () -> {
masterkeyFileAccess.unlock(keyFile, "asd");
});
}

@Test
@DisplayName("with oversized scryptBlockSize")
public void testUnlockWithOversizedBlockSize() {
keyFile.scryptBlockSize = MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE << 1;

Assertions.assertThrows(IllegalArgumentException.class, () -> {
masterkeyFileAccess.unlock(keyFile, "asd");
});
}

@Test
@DisplayName("with invalid password")
public void testUnlockWithIncorrectPassword() {
Expand Down Expand Up @@ -197,6 +276,18 @@ public void testLockWithDifferentPeppers() {

}

@Test
@DisplayName("persist() with oversized scryptCostParam")
public void testPersistWithOversizedCostParam() {
ByteArrayOutputStream out = new ByteArrayOutputStream();

Assertions.assertThrows(IllegalArgumentException.class, () -> {
masterkeyFileAccess.persist(key, out, "asd", 999, MasterkeyFile.MAX_SCRYPT_COST_PARAM << 1);
});
Mockito.verify(masterkeyFileAccess, Mockito.never()).lock(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt());
Assertions.assertEquals(0, out.size());
}

@Test
@DisplayName("persist and load")
public void testPersistAndLoad(@TempDir Path tmpDir) throws IOException, MasterkeyLoadingFailedException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,106 @@
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class MasterkeyFileTest {

@Nested
@DisplayName("isValid()")
class IsValid {

private MasterkeyFile masterkeyFile;

@BeforeEach
public void setup() {
masterkeyFile = new MasterkeyFile();
masterkeyFile.version = 999;
masterkeyFile.scryptSalt = new byte[8];
masterkeyFile.scryptCostParam = 32768;
masterkeyFile.scryptBlockSize = 8;
masterkeyFile.encMasterKey = new byte[40];
masterkeyFile.macMasterKey = new byte[40];
masterkeyFile.versionMac = new byte[32];
}

@Test
@DisplayName("default parameters are valid")
public void testDefaultsAreValid() {
Assertions.assertTrue(masterkeyFile.isValid());
}

@Test
@DisplayName("scryptCostParam at the upper bound is valid")
public void testMaxCostParamIsValid() {
masterkeyFile.scryptCostParam = MasterkeyFile.MAX_SCRYPT_COST_PARAM;

Assertions.assertTrue(masterkeyFile.isValid());
}

@Test
@DisplayName("scryptBlockSize at the upper bound is valid")
public void testMaxBlockSizeIsValid() {
masterkeyFile.scryptBlockSize = MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE;

Assertions.assertTrue(masterkeyFile.isValid());
}

@Test
@DisplayName("scryptCostParam * scryptBlockSize at the memory limit is valid")
public void testProductAtMemoryLimitIsValid() {
masterkeyFile.scryptCostParam = 1 << 19;
masterkeyFile.scryptBlockSize = 16; // 2^19 * 16 * 128 = 1 GiB

Assertions.assertTrue(masterkeyFile.isValid());
}

@Test
@DisplayName("scryptCostParam * scryptBlockSize exceeding the memory limit is invalid")
public void testProductExceedingMemoryLimitIsInvalid() {
masterkeyFile.scryptCostParam = 1 << 20;
masterkeyFile.scryptBlockSize = 16; // 2^20 * 16 * 128 = 2 GiB, while both factors are within their individual bounds

Assertions.assertFalse(masterkeyFile.isValid());
}

@Test
@DisplayName("both scrypt parameters at their upper bounds are invalid")
public void testBothUpperBoundsAreInvalid() {
masterkeyFile.scryptCostParam = MasterkeyFile.MAX_SCRYPT_COST_PARAM;
masterkeyFile.scryptBlockSize = MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE; // 2^20 * 64 * 128 = 8 GiB

Assertions.assertFalse(masterkeyFile.isValid());
}

@ParameterizedTest(name = "scryptCostParam = {0}")
@DisplayName("out of range scryptCostParam is invalid")
@ValueSource(ints = {Integer.MIN_VALUE, -1, 0, 1, MasterkeyFile.MAX_SCRYPT_COST_PARAM + 1, MasterkeyFile.MAX_SCRYPT_COST_PARAM << 1, Integer.MAX_VALUE})
public void testOutOfRangeCostParamIsInvalid(int scryptCostParam) {
masterkeyFile.scryptCostParam = scryptCostParam;

Assertions.assertFalse(masterkeyFile.isValid());
}

@ParameterizedTest(name = "scryptBlockSize = {0}")
@DisplayName("out of range scryptBlockSize is invalid")
@ValueSource(ints = {Integer.MIN_VALUE, -1, 0, MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE + 1, MasterkeyFile.MAX_SCRYPT_BLOCK_SIZE << 1, Integer.MAX_VALUE})
public void testOutOfRangeBlockSizeIsInvalid(int scryptBlockSize) {
masterkeyFile.scryptBlockSize = scryptBlockSize;

Assertions.assertFalse(masterkeyFile.isValid());
}

}

@Test
public void testRead() throws IOException {
MasterkeyFile masterkeyFile = MasterkeyFile.read(new StringReader("{\"scryptSalt\": \"Zm9v\"}"));
Expand Down
37 changes: 37 additions & 0 deletions src/test/java/org/cryptomator/cryptolib/common/ScryptTest.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
package org.cryptomator.cryptolib.common;

import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import static java.nio.charset.StandardCharsets.US_ASCII;

Expand All @@ -10,6 +15,38 @@
*/
public class ScryptTest {

/**
* Regression test for <a href="https://github.com/cryptomator/cryptolib/issues/133">#133</a>:
* Parameter combinations that pass the individual int-overflow checks on N and r but would allocate more than the working memory limit must be rejected up front instead of running into an OutOfMemoryError.
*/
@ParameterizedTest(name = "N = {0}, r = {1}")
@DisplayName("reject parameter combinations exceeding the working memory limit")
@CsvSource({ //
"1048576, 9", // 2^20 * 9 * 128 = 1152 MiB
"2097152, 5", // 2^21 * 5 * 128 = 1280 MiB
"4194304, 3", // 2^22 * 3 * 128 = 1536 MiB
})
public void testRejectTooMuchMemory(int costParam, int blockSize) {
IllegalArgumentException e = Assertions.assertThrows(IllegalArgumentException.class, () -> {
Scrypt.scrypt("pw", "salt".getBytes(US_ASCII), costParam, blockSize, 64);
});
MatcherAssert.assertThat(e.getMessage(), CoreMatchers.containsString("too much memory"));
}

@ParameterizedTest(name = "N = {0}, r = {1} -> {2}")
@DisplayName("exceedsWorkingMemoryLimit() boundary")
@CsvSource({ //
"32768, 8, false", // default parameters, 32 MiB
"8388608, 1, false", // 2^23 * 1 * 128 = 1 GiB, exactly at the limit
"524288, 16, false", // 2^19 * 16 * 128 = 1 GiB, exactly at the limit
"1048576, 9, true", // 2^20 * 9 * 128 = 1152 MiB
"16777216, 1, true", // 2^24 * 1 * 128 = 2 GiB
"2147483647, 2147483647, true", // int overflow of r * N must not wrap around
})
public void testExceedsWorkingMemoryLimit(int costParam, int blockSize, boolean expected) {
Assertions.assertEquals(expected, Scrypt.exceedsWorkingMemoryLimit(costParam, blockSize));
}

@Test
public void testEmptyString() {
byte[] key = Scrypt.scrypt("", "".getBytes(US_ASCII), 16, 1, 64);
Expand Down
Loading