Skip to content

Commit fde78f2

Browse files
committed
allow custom masterkeyfile validation
to address custom JVM max heap size
1 parent b932eee commit fde78f2

3 files changed

Lines changed: 148 additions & 6 deletions

File tree

‎src/main/java/org/cryptomator/cryptolib/common/MasterkeyFileAccess.java‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ public class MasterkeyFileAccess {
4444
private static final int DEFAULT_SCRYPT_SALT_LENGTH = 8;
4545
private static final int DEFAULT_SCRYPT_COST_PARAM = 1 << 15; // 2^15
4646
private static final int DEFAULT_SCRYPT_BLOCK_SIZE = 8;
47+
private static final MasterkeyFileValidator NO_ADDITIONAL_VALIDATION = file -> {
48+
};
4749

4850
private final byte[] pepper;
4951
private final SecureRandom csprng;
@@ -115,19 +117,61 @@ MasterkeyFile changePassphrase(MasterkeyFile masterkey, CharSequence oldPassphra
115117
* @throws MasterkeyLoadingFailedException If reading the masterkey file fails
116118
*/
117119
public Masterkey load(Path filePath, CharSequence passphrase) throws MasterkeyLoadingFailedException {
120+
return load(filePath, passphrase, NO_ADDITIONAL_VALIDATION);
121+
}
122+
123+
/**
124+
* Loads the JSON contents from the given file, runs the parsed content through <code>validator</code>
125+
* and derives a KEK from the given passphrase to unwrap the contained keys.
126+
* <p>
127+
* The validator runs before any key derivation happens and is meant to reject files that are structurally valid but unsuitable for the calling environment,
128+
* e.g. because their scrypt parameters require more memory than the caller is willing to spend:
129+
* <pre>
130+
* masterkeyFileAccess.load(path, passphrase, file -&gt; {
131+
* if (128L * file.scryptBlockSize * file.scryptCostParam &gt; 256 * 1024 * 1024) {
132+
* throw new IOException("scrypt parameters exceed memory limit");
133+
* }
134+
* });
135+
* </pre>
136+
*
137+
* @param filePath Which file to load
138+
* @param passphrase The passphrase used during key derivation
139+
* @param validator Additional validation the parsed masterkey file must pass
140+
* @return A new masterkey. Should be used in a try-with-resource statement.
141+
* @throws InvalidPassphraseException If the provided passphrase can not be used to unwrap the stored keys.
142+
* @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.
143+
*/
144+
public Masterkey load(Path filePath, CharSequence passphrase, MasterkeyFileValidator validator) throws MasterkeyLoadingFailedException {
118145
try (InputStream in = Files.newInputStream(filePath, StandardOpenOption.READ)) {
119-
return load(in, passphrase);
146+
return load(in, passphrase, validator);
120147
} catch (IOException e) {
121148
throw new MasterkeyLoadingFailedException("I/O error", e);
122149
}
123150
}
124151

125152
public Masterkey load(InputStream in, CharSequence passphrase) throws IOException {
153+
return load(in, passphrase, NO_ADDITIONAL_VALIDATION);
154+
}
155+
156+
/**
157+
* Reads the JSON contents from the given stream, runs the parsed content through <code>validator</code>
158+
* and derives a KEK from the given passphrase to unwrap the contained keys.
159+
*
160+
* @param in Stream to read the masterkey file from
161+
* @param passphrase The passphrase used during key derivation
162+
* @param validator Additional validation the parsed masterkey file must pass, see {@link #load(Path, CharSequence, MasterkeyFileValidator)}
163+
* @return A new masterkey. Should be used in a try-with-resource statement.
164+
* @throws InvalidPassphraseException If the provided passphrase can not be used to unwrap the stored keys.
165+
* @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.
166+
*/
167+
public Masterkey load(InputStream in, CharSequence passphrase, MasterkeyFileValidator validator) throws IOException {
168+
Preconditions.checkNotNull(validator);
126169
try (Reader reader = new InputStreamReader(in, UTF_8)) {
127170
MasterkeyFile parsedFile = MasterkeyFile.read(reader);
128171
if (!parsedFile.isValid()) {
129172
throw new IOException("Invalid key file");
130173
} else {
174+
validator.validate(parsedFile);
131175
return unlock(parsedFile, passphrase);
132176
}
133177
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.cryptomator.cryptolib.common;
2+
3+
import java.io.IOException;
4+
5+
/**
6+
* Additional, caller-defined validation of a parsed {@link MasterkeyFile} before any key derivation happens.
7+
* <p>
8+
* Used by {@link MasterkeyFileAccess#load(java.nio.file.Path, CharSequence, MasterkeyFileValidator)} to reject files that are structurally valid
9+
* but unsuitable for the calling environment, e.g. because their scrypt parameters require more memory than the caller is willing to spend.
10+
*/
11+
@FunctionalInterface
12+
public interface MasterkeyFileValidator {
13+
14+
/**
15+
* Validates the given, structurally valid masterkey file.
16+
*
17+
* @param masterkeyFile The parsed masterkey file
18+
* @throws IOException If the file is rejected. The exception is propagated to the caller of {@link MasterkeyFileAccess#load(java.io.InputStream, CharSequence, MasterkeyFileValidator)}
19+
*/
20+
void validate(MasterkeyFile masterkeyFile) throws IOException;
21+
22+
}

‎src/test/java/org/cryptomator/cryptolib/common/MasterkeyFileAccessTest.java‎

Lines changed: 81 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import org.junit.jupiter.api.io.TempDir;
1515
import org.junit.jupiter.params.ParameterizedTest;
1616
import org.junit.jupiter.params.provider.ValueSource;
17+
import org.mockito.ArgumentCaptor;
1718
import org.mockito.ArgumentMatchers;
1819
import org.mockito.Mockito;
1920

@@ -22,6 +23,7 @@
2223
import java.io.IOException;
2324
import java.io.InputStream;
2425
import java.io.StringWriter;
26+
import java.nio.file.Files;
2527
import java.nio.file.Path;
2628
import java.security.SecureRandom;
2729

@@ -124,6 +126,80 @@ public void testLoadMalformed() {
124126
});
125127
}
126128

129+
@Nested
130+
@DisplayName("load() with validator")
131+
class LoadWithValidator {
132+
133+
@Test
134+
@DisplayName("all-passing validator allows loading the key")
135+
public void testLoadWithPassingValidator() throws IOException {
136+
InputStream in = new ByteArrayInputStream(serializedKeyFile);
137+
138+
Masterkey loaded = masterkeyFileAccess.load(in, "asd", file -> {
139+
});
140+
141+
Assertions.assertArrayEquals(key.getEncoded(), loaded.getEncoded());
142+
}
143+
144+
@Test
145+
@DisplayName("all-rejecting validator throws exception, no key derivation happens")
146+
public void testLoadWithRejectingValidator() throws InvalidPassphraseException {
147+
InputStream in = new ByteArrayInputStream(serializedKeyFile);
148+
IOException rejection = new IOException("scrypt parameters exceed memory limit");
149+
150+
IOException thrown = Assertions.assertThrows(IOException.class, () -> {
151+
masterkeyFileAccess.load(in, "asd", file -> {
152+
throw rejection;
153+
});
154+
});
155+
Assertions.assertSame(rejection, thrown);
156+
Mockito.verify(masterkeyFileAccess, Mockito.never()).unlock(ArgumentMatchers.any(), ArgumentMatchers.any());
157+
}
158+
159+
@Test
160+
@DisplayName("validator receives the parsed file")
161+
public void testValidatorReceivesParsedFile() throws IOException {
162+
InputStream in = new ByteArrayInputStream(serializedKeyFile);
163+
MasterkeyFileValidator validator = Mockito.mock(MasterkeyFileValidator.class);
164+
165+
masterkeyFileAccess.load(in, "asd", validator);
166+
167+
ArgumentCaptor<MasterkeyFile> captor = ArgumentCaptor.forClass(MasterkeyFile.class);
168+
Mockito.verify(validator).validate(captor.capture());
169+
Assertions.assertEquals(999, captor.getValue().version);
170+
Assertions.assertEquals(2, captor.getValue().scryptCostParam);
171+
Assertions.assertEquals(8, captor.getValue().scryptBlockSize);
172+
}
173+
174+
@Test
175+
@DisplayName("validator is not invoked for structurally invalid files")
176+
public void testValidatorNotInvokedForInvalidFile() {
177+
InputStream in = new ByteArrayInputStream("{\"foo\": 42}".getBytes(UTF_8));
178+
MasterkeyFileValidator validator = Mockito.mock(MasterkeyFileValidator.class);
179+
180+
Assertions.assertThrows(IOException.class, () -> {
181+
masterkeyFileAccess.load(in, "asd", validator);
182+
});
183+
Mockito.verifyNoInteractions(validator);
184+
}
185+
186+
@Test
187+
@DisplayName("load(Path, ...) with rejecting validator -> MasterkeyLoadingFailedException caused by validator's exception")
188+
public void testLoadPathWithRejectingValidator(@TempDir Path tmpDir) throws IOException {
189+
Path masterkeyFile = tmpDir.resolve("masterkey.cryptomator");
190+
Files.write(masterkeyFile, serializedKeyFile);
191+
IOException rejection = new IOException("scrypt parameters exceed memory limit");
192+
193+
MasterkeyLoadingFailedException thrown = Assertions.assertThrows(MasterkeyLoadingFailedException.class, () -> {
194+
masterkeyFileAccess.load(masterkeyFile, "asd", file -> {
195+
throw rejection;
196+
});
197+
});
198+
Assertions.assertSame(rejection, thrown.getCause());
199+
}
200+
201+
}
202+
127203
}
128204

129205
/**
@@ -173,12 +249,12 @@ public void testLoadWithOversizedMemoryRequirement() throws IOException, Invalid
173249
Mockito.verify(masterkeyFileAccess, Mockito.never()).unlock(ArgumentMatchers.any(), ArgumentMatchers.any());
174250
}
175251

176-
private byte[] serialize(MasterkeyFile keyFile) throws IOException {
177-
StringWriter writer = new StringWriter();
178-
keyFile.write(writer);
179-
return writer.toString().getBytes(UTF_8);
180-
}
252+
}
181253

254+
private static byte[] serialize(MasterkeyFile keyFile) throws IOException {
255+
StringWriter writer = new StringWriter();
256+
keyFile.write(writer);
257+
return writer.toString().getBytes(UTF_8);
182258
}
183259

184260
@Nested

0 commit comments

Comments
 (0)