Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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 @@ -44,6 +44,8 @@ public class MasterkeyFileAccess {
private static final int DEFAULT_SCRYPT_SALT_LENGTH = 8;
private static final int DEFAULT_SCRYPT_COST_PARAM = 1 << 15; // 2^15
private static final int DEFAULT_SCRYPT_BLOCK_SIZE = 8;
private static final MasterkeyFileValidator NO_ADDITIONAL_VALIDATION = file -> {
};

private final byte[] pepper;
private final SecureRandom csprng;
Expand Down Expand Up @@ -115,19 +117,61 @@ MasterkeyFile changePassphrase(MasterkeyFile masterkey, CharSequence oldPassphra
* @throws MasterkeyLoadingFailedException If reading the masterkey file fails
*/
public Masterkey load(Path filePath, CharSequence passphrase) throws MasterkeyLoadingFailedException {
return load(filePath, passphrase, NO_ADDITIONAL_VALIDATION);
}

/**
* Loads the JSON contents from the given file, runs the parsed content through <code>validator</code>
* and derives a KEK from the given passphrase to unwrap the contained keys.
* <p>
* The validator runs before any key derivation happens and is meant to reject files that are structurally valid but unsuitable for the calling environment,
* e.g. because their scrypt parameters require more memory than the caller is willing to spend:
* <pre>
* masterkeyFileAccess.load(path, passphrase, file -&gt; {
* if (128L * file.scryptBlockSize * file.scryptCostParam &gt; 256 * 1024 * 1024) {
* throw new IOException("scrypt parameters exceed memory limit");
* }
* });
* </pre>
*
* @param filePath Which file to load
* @param passphrase The passphrase used during key derivation
* @param validator Additional validation the parsed masterkey file must pass
* @return A new masterkey. Should be used in a try-with-resource statement.
* @throws InvalidPassphraseException If the provided passphrase can not be used to unwrap the stored keys.
* @throws MasterkeyLoadingFailedException If reading the masterkey file fails or the <code>validator</code> rejects the parsed content. In the latter case the validator's exception is the cause.
*/
public Masterkey load(Path filePath, CharSequence passphrase, MasterkeyFileValidator validator) throws MasterkeyLoadingFailedException {
try (InputStream in = Files.newInputStream(filePath, StandardOpenOption.READ)) {
return load(in, passphrase);
return load(in, passphrase, validator);
} catch (IOException e) {
throw new MasterkeyLoadingFailedException("I/O error", e);
}
}

public Masterkey load(InputStream in, CharSequence passphrase) throws IOException {
return load(in, passphrase, NO_ADDITIONAL_VALIDATION);
}

/**
* Reads the JSON contents from the given stream, runs the parsed content through <code>validator</code>
* and derives a KEK from the given passphrase to unwrap the contained keys.
*
* @param in Stream to read the masterkey file from
* @param passphrase The passphrase used during key derivation
* @param validator Additional validation the parsed masterkey file must pass, see {@link #load(Path, CharSequence, MasterkeyFileValidator)}
* @return A new masterkey. Should be used in a try-with-resource statement.
* @throws InvalidPassphraseException If the provided passphrase can not be used to unwrap the stored keys.
* @throws IOException If reading the masterkey file fails or the <code>validator</code> rejects the parsed content. In the latter case the validator's exception is rethrown as is.
*/
public Masterkey load(InputStream in, CharSequence passphrase, MasterkeyFileValidator validator) throws IOException {
Preconditions.checkNotNull(validator);
try (Reader reader = new InputStreamReader(in, UTF_8)) {
MasterkeyFile parsedFile = MasterkeyFile.read(reader);
if (!parsedFile.isValid()) {
throw new IOException("Invalid key file");
} else {
validator.validate(parsedFile);
return unlock(parsedFile, passphrase);
}
Comment thread
infeo marked this conversation as resolved.
Resolved
}
Expand Down Expand Up @@ -177,6 +221,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
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.cryptomator.cryptolib.common;

import java.io.IOException;

/**
* Additional, caller-defined validation of a parsed {@link MasterkeyFile} before any key derivation happens.
* <p>
* Used by {@link MasterkeyFileAccess#load(java.nio.file.Path, CharSequence, MasterkeyFileValidator)} to reject files that are structurally valid
* but unsuitable for the calling environment, e.g. because their scrypt parameters require more memory than the caller is willing to spend.
*/
@FunctionalInterface
public interface MasterkeyFileValidator {

/**
* Validates the given, structurally valid masterkey file.
*
* @param masterkeyFile The parsed masterkey file
* @throws IOException If the file is rejected. The exception is propagated to the caller of {@link MasterkeyFileAccess#load(java.io.InputStream, CharSequence, MasterkeyFileValidator)}
*/
void validate(MasterkeyFile masterkeyFile) throws IOException;

}
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 + 3072; // ~1 GiB, allowing r=8, N=(1<<20)
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,18 @@
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.ArgumentCaptor;
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.Files;
import java.nio.file.Path;
import java.security.SecureRandom;

Expand Down Expand Up @@ -120,6 +126,135 @@ public void testLoadMalformed() {
});
}

@Nested
@DisplayName("load() with validator")
class LoadWithValidator {

@Test
@DisplayName("all-passing validator allows loading the key")
public void testLoadWithPassingValidator() throws IOException {
InputStream in = new ByteArrayInputStream(serializedKeyFile);

Masterkey loaded = masterkeyFileAccess.load(in, "asd", file -> {
});

Assertions.assertArrayEquals(key.getEncoded(), loaded.getEncoded());
}

@Test
@DisplayName("all-rejecting validator throws exception, no key derivation happens")
public void testLoadWithRejectingValidator() throws InvalidPassphraseException {
InputStream in = new ByteArrayInputStream(serializedKeyFile);
IOException rejection = new IOException("scrypt parameters exceed memory limit");

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

@Test
@DisplayName("validator receives the parsed file")
public void testValidatorReceivesParsedFile() throws IOException {
InputStream in = new ByteArrayInputStream(serializedKeyFile);
MasterkeyFileValidator validator = Mockito.mock(MasterkeyFileValidator.class);

masterkeyFileAccess.load(in, "asd", validator);

ArgumentCaptor<MasterkeyFile> captor = ArgumentCaptor.forClass(MasterkeyFile.class);
Mockito.verify(validator).validate(captor.capture());
Assertions.assertEquals(999, captor.getValue().version);
Assertions.assertEquals(2, captor.getValue().scryptCostParam);
Assertions.assertEquals(8, captor.getValue().scryptBlockSize);
}

@Test
@DisplayName("validator is not invoked for structurally invalid files")
public void testValidatorNotInvokedForInvalidFile() {
InputStream in = new ByteArrayInputStream("{\"foo\": 42}".getBytes(UTF_8));
MasterkeyFileValidator validator = Mockito.mock(MasterkeyFileValidator.class);

Assertions.assertThrows(IOException.class, () -> {
masterkeyFileAccess.load(in, "asd", validator);
});
Mockito.verifyNoInteractions(validator);
}

@Test
@DisplayName("load(Path, ...) with rejecting validator -> MasterkeyLoadingFailedException caused by validator's exception")
public void testLoadPathWithRejectingValidator(@TempDir Path tmpDir) throws IOException {
Path masterkeyFile = tmpDir.resolve("masterkey.cryptomator");
Files.write(masterkeyFile, serializedKeyFile);
IOException rejection = new IOException("scrypt parameters exceed memory limit");

MasterkeyLoadingFailedException thrown = Assertions.assertThrows(MasterkeyLoadingFailedException.class, () -> {
masterkeyFileAccess.load(masterkeyFile, "asd", file -> {
throw rejection;
});
});
Assertions.assertSame(rejection, thrown.getCause());
}

}

}

/**
* 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 static byte[] serialize(MasterkeyFile keyFile) throws IOException {
StringWriter writer = new StringWriter();
keyFile.write(writer);
return writer.toString().getBytes(UTF_8);
}

@Nested
Expand All @@ -134,6 +269,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 +352,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
Loading
Loading