Skip to content

Commit d489d4b

Browse files
improved exception handling during decryption
1 parent 9100bdd commit d489d4b

3 files changed

Lines changed: 81 additions & 4 deletions

File tree

‎src/main/java/org/cryptomator/jose/parser/ParsedJWE.java‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import com.google.gson.JsonObject;
55
import com.google.gson.JsonParser;
66
import org.cryptomator.jose.DecryptionAlg;
7+
import org.cryptomator.jose.IntegratedDecryptionAlg;
78
import org.cryptomator.jose.JoseDecryptException;
89
import org.cryptomator.jose.enc.DecryptCiphertextException;
910
import org.cryptomator.jose.util.Ascii;
@@ -75,15 +76,26 @@ private DecryptedJWE decrypt(Optional<String> kid, DecryptionAlg... algs) throws
7576
} catch (IllegalArgumentException e) {
7677
throw new JoseDecryptException("Malformed JWE: protected header and aad must be US-ASCII", e);
7778
}
78-
var decodedIv = base64url.decode(iv);
79-
var decodedCiphertext = base64url.decode(ciphertext);
80-
var decodedTag = base64url.decode(tag);
79+
final byte[] decodedIv, decodedCiphertext, decodedTag;
80+
try {
81+
decodedIv = base64url.decode(iv);
82+
decodedCiphertext = base64url.decode(ciphertext);
83+
decodedTag = base64url.decode(tag);
84+
} catch (IllegalArgumentException e) {
85+
throw new JoseDecryptException("Malformed JWE: iv, ciphertext and tag must be base64url", e); // shared by all recipients, so not worth retrying
86+
}
8187

8288
var candidates = kid.isPresent() ? recipientsWithKid(kid.get(), sharedHeader) : recipients.asList();
8389
var failure = new JoseDecryptException(kid.isPresent() ? "Recipient '" + kid.get() + "' could not be decrypted." : "No matching recipient found for decryption.");
8490
for (var recipient : candidates) {
8591
var recipientJson = recipient.getAsJsonObject();
86-
var encryptedKey = base64url.decode(recipientJson.get("encrypted_key").getAsString());
92+
final byte[] encryptedKey;
93+
try {
94+
encryptedKey = base64url.decode(recipientJson.get("encrypted_key").getAsString());
95+
} catch (IllegalArgumentException e) {
96+
failure.addSuppressed(new JoseDecryptException("Malformed encrypted_key: not base64url", e));
97+
continue;
98+
}
8799
var perRecipientUnprotectedHeader = recipientJson.has("header")
88100
? recipientJson.get("header").getAsJsonObject()
89101
: new JsonObject();
@@ -99,13 +111,20 @@ private DecryptedJWE decrypt(Optional<String> kid, DecryptionAlg... algs) throws
99111
if (!algValue.equals(alg.name())) {
100112
continue;
101113
}
114+
if (alg instanceof IntegratedDecryptionAlg && !parsedProtectedHeader.has("alg")) {
115+
// draft-ietf-jose-hpke-encrypt §5: for Integrated Encryption the protected header MUST contain alg (it is part of the HPKE aad)
116+
failure.addSuppressed(new JoseDecryptException("alg must be in the protected header for Integrated Encryption"));
117+
continue;
118+
}
102119
try {
103120
var payload = alg.decrypt(combinedHeader, parts);
104121
return new DecryptedJWE(new String(payload, StandardCharsets.UTF_8), parsedProtectedHeader, JsonHelper.union(unprotectedHeader, perRecipientUnprotectedHeader), aad);
105122
} catch (DecryptCiphertextException e) {
106123
throw e; // the key matched but the content is corrupt; other recipients share the same ciphertext and would fail identically
107124
} catch (JoseDecryptException e) {
108125
failure.addSuppressed(e); // this recipient/alg does not apply (wrong key, mode mismatch, malformed header); try the next candidate
126+
} catch (IllegalArgumentException | IllegalStateException e) {
127+
failure.addSuppressed(new JoseDecryptException("Malformed recipient: " + e.getMessage(), e)); // defense in depth: an alg tripping over a malformed header must not abort the loop
109128
}
110129
}
111130
}

‎src/test/java/org/cryptomator/jose/alg/HPKEIntegratedAlgTest.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
import org.junit.jupiter.api.Nested;
1616
import org.junit.jupiter.api.Test;
1717

18+
import java.nio.charset.StandardCharsets;
19+
import java.util.Base64;
20+
1821
import java.security.PrivateKey;
1922
import java.security.interfaces.ECPrivateKey;
2023

@@ -97,6 +100,23 @@ void rejectInjectedEncHeader() throws JoseParseException {
97100
Assertions.assertTrue(thrown.getSuppressed()[0].getMessage().contains("enc and ek headers must not be present"));
98101
}
99102

103+
@Test
104+
@DisplayName("reject alg outside the protected header")
105+
void rejectUnprotectedAlg() throws JoseParseException {
106+
// draft §5: the protected header MUST contain alg; moving it to the unprotected header would take it out of the HPKE aad
107+
var json = JsonParser.parseString(FLATTENED_JWE).getAsJsonObject();
108+
var protectedHeader = JWE.parse(FLATTENED_JWE).parsedProtectedHeader();
109+
var algValue = protectedHeader.remove("alg");
110+
json.addProperty("protected", Base64.getUrlEncoder().withoutPadding().encodeToString(protectedHeader.toString().getBytes(StandardCharsets.UTF_8)));
111+
var unprotected = new JsonObject();
112+
unprotected.add("alg", algValue);
113+
json.add("unprotected", unprotected);
114+
var parsed = JWE.parse(json.toString());
115+
var thrown = Assertions.assertThrows(JoseDecryptException.class, () -> parsed.decrypt(alg));
116+
Assertions.assertEquals(1, thrown.getSuppressed().length);
117+
Assertions.assertTrue(thrown.getSuppressed()[0].getMessage().contains("protected header"));
118+
}
119+
100120
@Test
101121
@DisplayName("reject non-empty iv/tag")
102122
void rejectNonEmptyIv() throws JoseParseException {

‎src/test/java/org/cryptomator/jose/parser/ParsedJWETest.java‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
import org.cryptomator.jose.JoseException;
1111
import org.cryptomator.jose.JoseParseException;
1212
import org.cryptomator.jose.Recipient;
13+
import org.cryptomator.jose.alg.EcdhEsAlg;
1314
import org.cryptomator.jose.hpke.XwingProvider;
15+
import org.cryptomator.jose.util.Curve;
1416
import org.junit.jupiter.api.Assertions;
1517
import org.junit.jupiter.api.BeforeEach;
1618
import org.junit.jupiter.api.DisplayName;
@@ -22,7 +24,9 @@
2224
import java.nio.charset.StandardCharsets;
2325
import java.security.KeyPairGenerator;
2426
import java.security.NoSuchAlgorithmException;
27+
import java.security.spec.ECGenParameterSpec;
2528
import java.util.Base64;
29+
import java.util.List;
2630

2731
class ParsedJWETest {
2832

@@ -72,6 +76,40 @@ void testNonStringEnc() {
7276
Assertions.assertThrows(JoseDecryptException.class, () -> malformed.decrypt(Alg.pbes2(PASSWORD)));
7377
}
7478

79+
@Test
80+
@DisplayName("non-base64url iv, ciphertext or tag fail with a checked exception")
81+
void testMalformedBase64Parts() {
82+
for (var field : List.of("iv", "ciphertext", "tag")) {
83+
var malformed = new ParsedJWE(valid.protectedHeader(), valid.unprotectedHeader(), valid.recipients(),
84+
field.equals("iv") ? "!" : valid.iv(), field.equals("ciphertext") ? "!" : valid.ciphertext(), field.equals("tag") ? "!" : valid.tag(), valid.aad());
85+
Assertions.assertThrows(JoseDecryptException.class, () -> malformed.decrypt(Alg.pbes2(PASSWORD)), field);
86+
}
87+
}
88+
89+
@Test
90+
@DisplayName("a non-base64url encrypted_key is skipped in favor of a later valid recipient")
91+
void testMalformedEncryptedKeyIsSkipped() throws JoseDecryptException {
92+
var broken = valid.recipients().get(0).getAsJsonObject().deepCopy();
93+
broken.addProperty("encrypted_key", "!");
94+
var recipients = new JsonArray();
95+
recipients.add(broken);
96+
recipients.add(valid.recipients().get(0));
97+
var withBrokenFirst = new ParsedJWE(valid.protectedHeader(), valid.unprotectedHeader(), recipients, valid.iv(), valid.ciphertext(), valid.tag(), valid.aad());
98+
Assertions.assertEquals("payload", withBrokenFirst.decrypt(Alg.pbes2(PASSWORD)).payload());
99+
}
100+
101+
@Test
102+
@DisplayName("an alg throwing an unchecked exception on a recipient does not abort the loop")
103+
void testUncheckedAlgFailureIsSkipped() throws Exception {
104+
var ecKeyGen = KeyPairGenerator.getInstance("EC");
105+
ecKeyGen.initialize(new ECGenParameterSpec("secp384r1"));
106+
var ecKeyPair = ecKeyGen.generateKeyPair();
107+
var jwe = JWE.build("payload").encrypt(Enc.A256GCM, Alg.ecdhEs(ecKeyPair.getPublic()), Alg.pbes2(PASSWORD, 10)).toJsonSerialization();
108+
var misconfigured = new EcdhEsAlg(EcdhEsAlg.Type.ECDH_ES_A256KW, Curve.P384, null, null); // matches the first recipient's alg, throws IllegalStateException (no private key)
109+
110+
Assertions.assertEquals("payload", JWE.parse(jwe).decrypt(misconfigured, Alg.pbes2(PASSWORD)).payload());
111+
}
112+
75113
@Test
76114
@DisplayName("a non-string ek fails with a checked exception")
77115
void testNonStringEk() throws NoSuchAlgorithmException {

0 commit comments

Comments
 (0)