Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -44,7 +44,6 @@ 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 final byte[] pepper;
private final SecureRandom csprng;

Expand Down Expand Up @@ -92,6 +91,7 @@ public void changePassphrase(InputStream oldIn, OutputStream newOut, CharSequenc
try (Reader reader = new InputStreamReader(oldIn, UTF_8);
Writer writer = new OutputStreamWriter(newOut, UTF_8)) {
MasterkeyFile original = MasterkeyFile.read(reader);
MasterkeyFileValidator.DEFAULT.validate(original);
MasterkeyFile updated = changePassphrase(original, oldPassphrase, newPassphrase);
updated.write(writer);
}
Expand All @@ -105,29 +105,72 @@ MasterkeyFile changePassphrase(MasterkeyFile masterkey, CharSequence oldPassphra
}

/**
* Loads the JSON contents from the given file and derives a KEK from the given passphrase to
* Loads the JSON contents from the given file, validates it using {@link MasterkeyFileValidator#DEFAULT} and derives a KEK from the given passphrase to
* unwrap the contained keys.
*
* @param filePath Which file to load
* @param passphrase The passphrase used during key derivation
* @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
* @throws MasterkeyLoadingFailedException If reading or validating the masterkey file fails
*/
public Masterkey load(Path filePath, CharSequence passphrase) throws MasterkeyLoadingFailedException {
return load(filePath, passphrase, MasterkeyFileValidator.DEFAULT);
}

/**
* 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.
* It replaces {@link MasterkeyFileValidator#DEFAULT}, so a custom validator can apply both tighter and looser limits:
* <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 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, MasterkeyFileValidator.DEFAULT);
}

/**
* 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 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.cryptomator.cryptolib.common;

import java.io.IOException;

/**
* 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 {

/**
* Upper bound of the scrypt cost parameter <code>N</code> accepted by {@link #DEFAULT}.
*/
public static final int DEFAULT_MAX_SCRYPT_COST_PARAM = 1 << 20;

/**
* Upper bound of the scrypt block size <code>r</code> accepted by {@link #DEFAULT}.
*/
public static final int DEFAULT_MAX_SCRYPT_BLOCK_SIZE = 64;

/**
* Upper bound of the working memory in bytes the scrypt key derivation may require for files accepted by {@link #DEFAULT}.
*/
public static final long DEFAULT_MAX_SCRYPT_WORKING_MEMORY = 1024L * 1024 * 1024 + 3072; // 1 GiB for V plus 3 KiB for B and XY, allowing N=2^20, r=8

/**
* Rejects masterkey files whose scrypt parameters exceed {@link #DEFAULT_MAX_SCRYPT_COST_PARAM}, {@link #DEFAULT_MAX_SCRYPT_BLOCK_SIZE} or {@link #DEFAULT_MAX_SCRYPT_WORKING_MEMORY}.
*/
public static final MasterkeyFileValidator DEFAULT = file -> {
if (file.scryptCostParam > DEFAULT_MAX_SCRYPT_COST_PARAM
|| file.scryptBlockSize > DEFAULT_MAX_SCRYPT_BLOCK_SIZE
|| Scrypt.workingMemoryBytes(file.scryptCostParam, file.scryptBlockSize) > DEFAULT_MAX_SCRYPT_WORKING_MEMORY) {
throw new IOException("scrypt parameters out of accepted range");
}
};


/**
* 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;

}
29 changes: 26 additions & 3 deletions src/main/java/org/cryptomator/cryptolib/common/Scrypt.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,17 @@ public static byte[] scrypt(byte[] passphrase, byte[] salt, int costParam, int b
ObjectPool.Lease<Mac> mac = MacSupplier.HMAC_SHA256.keyed(key)) {

byte[] DK = new byte[keyLengthInBytes];
byte[] B = new byte[128 * blockSize * P];
byte[] XY = new byte[256 * blockSize];
byte[] V = new byte[128 * blockSize * costParam];
byte[] B;
byte[] XY;
byte[] V;
try {
B = new byte[128 * blockSize * P];
XY = new byte[256 * blockSize];
V = new byte[128 * blockSize * costParam];
} catch (OutOfMemoryError e) {
// a failed allocation leaves the heap untouched, so it is safe to recover from it
throw new IllegalArgumentException("Insufficient memory for parameters N and r", e);
}

pbkdf2(mac.get(), salt, 1, B, P * 128 * blockSize);

Expand All @@ -92,6 +100,21 @@ public static byte[] scrypt(byte[] passphrase, byte[] salt, int costParam, int b
}
}

/**
* Computes the working memory (V + B + XY) that {@link #scrypt(byte[], byte[], int, int, int)} allocates for the given parameters.
*
* @param costParam Cost parameter <code>N</code>
* @param blockSize Block size <code>r</code>
* @return Required working memory in bytes, saturated at {@link Long#MAX_VALUE}
*/
static long workingMemoryBytes(int costParam, int blockSize) {
try {
return Math.multiplyExact(128L * blockSize, costParam + 2L + P);
} catch (ArithmeticException e) {
return Long.MAX_VALUE;
}
}

/**
* 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.CsvSource;
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,125 @@ public void testLoadMalformed() {
});
}

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

@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("passing validator receives the parsed file and allows loading the key")
public void testLoadWithPassingValidator() throws IOException {
InputStream in = new ByteArrayInputStream(serializedKeyFile);
MasterkeyFileValidator validator = Mockito.mock(MasterkeyFileValidator.class);

Masterkey loaded = masterkeyFileAccess.load(in, "asd", validator);

Assertions.assertArrayEquals(key.getEncoded(), loaded.getEncoded());
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 test 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.
* The individual bounds are covered by {@link MasterkeyFileValidatorTest}.
*/
@ParameterizedTest(name = "scryptCostParam = {0}, scryptBlockSize = {1}")
@DisplayName("load() rejects out of range scrypt parameters without deriving a key")
@CsvSource({ //
"2097152, 8", // scryptCostParam > DEFAULT_MAX_SCRYPT_COST_PARAM
"2, 128", // scryptBlockSize > DEFAULT_MAX_SCRYPT_BLOCK_SIZE
"1048576, 64", // both within their bounds, but 2^20 * 64 * 128 = 8 GiB
})
public void testLoadWithOutOfRangeScryptParams(int scryptCostParam, int scryptBlockSize) throws IOException, InvalidPassphraseException {
keyFile.scryptCostParam = scryptCostParam;
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("load() with custom validator replaces the default scrypt parameter bounds")
public void testLoadWithCustomValidatorReplacesDefault() throws IOException, InvalidPassphraseException {
keyFile.scryptCostParam = MasterkeyFileValidator.DEFAULT_MAX_SCRYPT_COST_PARAM << 1;
keyFile.scryptBlockSize = 1; // 2^21 * 1 * 128 = 256 MiB, accepted by a looser custom validator
InputStream in = new ByteArrayInputStream(serialize(keyFile));
Mockito.doReturn(key).when(masterkeyFileAccess).unlock(ArgumentMatchers.any(), ArgumentMatchers.any());

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

Assertions.assertSame(key, loaded);
}

@Test
@DisplayName("changePassphrase(byte[], ...) rejects out of range scrypt parameters without deriving a key")
public void testChangePassphraseWithOutOfRangeScryptParams() throws IOException, InvalidPassphraseException {
keyFile.scryptCostParam = MasterkeyFileValidator.DEFAULT_MAX_SCRYPT_COST_PARAM << 1;
byte[] serialized = serialize(keyFile);

Assertions.assertThrows(IOException.class, () -> {
masterkeyFileAccess.changePassphrase(serialized, "asd", "qwe");
});
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 +259,16 @@ public void testUnlockWithCorrectPassword() throws CryptoException {
Assertions.assertNotNull(key);
}

@Test
@DisplayName("with scrypt parameters exceeding the maximum array size")
public void testUnlockWithOutOfRangeScryptParams() {
keyFile.scryptCostParam = MasterkeyFileValidator.DEFAULT_MAX_SCRYPT_COST_PARAM << 1; // 2^21 * 8 * 128 = 2 GiB, rejected by Scrypt's int overflow check

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

@Test
@DisplayName("with invalid password")
public void testUnlockWithIncorrectPassword() {
Expand Down
Loading