Skip to content

Commit 7cc9edb

Browse files
authored
Fix parsing of PBES2 encrypted PKCS#8 keys (#78904)
This commit adds support for decrypting PKCS#8 encoded private keys that have been encrypted using a PBES2 based scheme (AES only). Unfortunately `java.crypto.EncryptedPrivateKeyInfo` doesn't make this easy as the underlying encryption algorithm is hidden within the `AlgorithmParameters`, and can only be extracted by calling `toString()` on the parameters object. See: https://datatracker.ietf.org/doc/html/rfc8018#appendix-A.4 See: AlgorithmParameters#toString() See: com.sun.crypto.provider.PBES2Parameters#toString() Resolves: #78901, #32021
1 parent 42fb4fb commit 7cc9edb

File tree

8 files changed

+313
-70
lines changed

8 files changed

+313
-70
lines changed

libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/DerParser.java

Lines changed: 45 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,22 @@ public final class DerParser {
3636
private static final int CONSTRUCTED = 0x20;
3737

3838
// Tag and data types
39-
private static final int INTEGER = 0x02;
40-
private static final int OCTET_STRING = 0x04;
41-
private static final int OBJECT_OID = 0x06;
42-
private static final int NUMERIC_STRING = 0x12;
43-
private static final int PRINTABLE_STRING = 0x13;
44-
private static final int VIDEOTEX_STRING = 0x15;
45-
private static final int IA5_STRING = 0x16;
46-
private static final int GRAPHIC_STRING = 0x19;
47-
private static final int ISO646_STRING = 0x1A;
48-
private static final int GENERAL_STRING = 0x1B;
49-
50-
private static final int UTF8_STRING = 0x0C;
51-
private static final int UNIVERSAL_STRING = 0x1C;
52-
private static final int BMP_STRING = 0x1E;
53-
39+
static final class Type {
40+
static final int INTEGER = 0x02;
41+
static final int OCTET_STRING = 0x04;
42+
static final int OBJECT_OID = 0x06;
43+
static final int SEQUENCE = 0x10;
44+
static final int NUMERIC_STRING = 0x12;
45+
static final int PRINTABLE_STRING = 0x13;
46+
static final int VIDEOTEX_STRING = 0x15;
47+
static final int IA5_STRING = 0x16;
48+
static final int GRAPHIC_STRING = 0x19;
49+
static final int ISO646_STRING = 0x1A;
50+
static final int GENERAL_STRING = 0x1B;
51+
static final int UTF8_STRING = 0x0C;
52+
static final int UNIVERSAL_STRING = 0x1C;
53+
static final int BMP_STRING = 0x1E;
54+
}
5455

5556
private InputStream derInputStream;
5657
private int maxAsnObjectLength;
@@ -60,6 +61,22 @@ public DerParser(byte[] bytes) {
6061
this.maxAsnObjectLength = bytes.length;
6162
}
6263

64+
/**
65+
* Read an object and verify its type
66+
* @param requiredType The expected type code
67+
* @throws IOException if data can not be parsed
68+
* @throws IllegalStateException if the parsed object is of the wrong type
69+
*/
70+
public Asn1Object readAsn1Object(int requiredType) throws IOException {
71+
final Asn1Object obj = readAsn1Object();
72+
if (obj.type != requiredType) {
73+
throw new IllegalStateException(
74+
"Expected ASN.1 object of type 0x" + Integer.toHexString(requiredType) + " but was 0x" + Integer.toHexString(obj.type)
75+
);
76+
}
77+
return obj;
78+
}
79+
6380
public Asn1Object readAsn1Object() throws IOException {
6481
int tag = derInputStream.read();
6582
if (tag == -1) {
@@ -207,7 +224,7 @@ public DerParser getParser() throws IOException {
207224
* @return BigInteger
208225
*/
209226
public BigInteger getInteger() throws IOException {
210-
if (type != DerParser.INTEGER)
227+
if (type != Type.INTEGER)
211228
throw new IOException("Invalid DER: object is not integer"); //$NON-NLS-1$
212229

213230
return new BigInteger(value);
@@ -218,28 +235,28 @@ public String getString() throws IOException {
218235
String encoding;
219236

220237
switch (type) {
221-
case DerParser.OCTET_STRING:
238+
case Type.OCTET_STRING:
222239
// octet string is basically a byte array
223240
return toHexString(value);
224-
case DerParser.NUMERIC_STRING:
225-
case DerParser.PRINTABLE_STRING:
226-
case DerParser.VIDEOTEX_STRING:
227-
case DerParser.IA5_STRING:
228-
case DerParser.GRAPHIC_STRING:
229-
case DerParser.ISO646_STRING:
230-
case DerParser.GENERAL_STRING:
241+
case Type.NUMERIC_STRING:
242+
case Type.PRINTABLE_STRING:
243+
case Type.VIDEOTEX_STRING:
244+
case Type.IA5_STRING:
245+
case Type.GRAPHIC_STRING:
246+
case Type.ISO646_STRING:
247+
case Type.GENERAL_STRING:
231248
encoding = "ISO-8859-1"; //$NON-NLS-1$
232249
break;
233250

234-
case DerParser.BMP_STRING:
251+
case Type.BMP_STRING:
235252
encoding = "UTF-16BE"; //$NON-NLS-1$
236253
break;
237254

238-
case DerParser.UTF8_STRING:
255+
case Type.UTF8_STRING:
239256
encoding = "UTF-8"; //$NON-NLS-1$
240257
break;
241258

242-
case DerParser.UNIVERSAL_STRING:
259+
case Type.UNIVERSAL_STRING:
243260
throw new IOException("Invalid DER: can't handle UCS-4 string"); //$NON-NLS-1$
244261

245262
default:
@@ -251,7 +268,7 @@ public String getString() throws IOException {
251268

252269
public String getOid() throws IOException {
253270

254-
if (type != DerParser.OBJECT_OID) {
271+
if (type != Type.OBJECT_OID) {
255272
throw new IOException("Ivalid DER: object is not object OID");
256273
}
257274
StringBuilder sb = new StringBuilder(64);

libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/PemUtils.java

Lines changed: 111 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.nio.file.Files;
2626
import java.nio.file.Path;
2727
import java.security.AccessControlException;
28+
import java.security.AlgorithmParameters;
2829
import java.security.GeneralSecurityException;
2930
import java.security.KeyFactory;
3031
import java.security.KeyPairGenerator;
@@ -68,6 +69,9 @@ public final class PemUtils {
6869
private static final String OPENSSL_EC_PARAMS_FOOTER = "-----END EC PARAMETERS-----";
6970
private static final String HEADER = "-----BEGIN";
7071

72+
private static final String PBES2_OID = "1.2.840.113549.1.5.13";
73+
private static final String AES_OID = "2.16.840.1.101.3.4.1";
74+
7175
private PemUtils() {
7276
throw new IllegalStateException("Utility class should not be instantiated");
7377
}
@@ -365,17 +369,70 @@ private static PrivateKey parsePKCS8Encrypted(BufferedReader bReader, char[] key
365369
}
366370
byte[] keyBytes = Base64.getDecoder().decode(sb.toString());
367371

368-
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(keyBytes);
369-
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
372+
final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = getEncryptedPrivateKeyInfo(keyBytes);
373+
String algorithm = encryptedPrivateKeyInfo.getAlgName();
374+
if (algorithm.equals("PBES2") || algorithm.equals("1.2.840.113549.1.5.13")) {
375+
algorithm = getPBES2Algorithm(encryptedPrivateKeyInfo);
376+
}
377+
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
370378
SecretKey secretKey = secretKeyFactory.generateSecret(new PBEKeySpec(keyPassword));
371-
Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
379+
Cipher cipher = Cipher.getInstance(algorithm);
372380
cipher.init(Cipher.DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters());
373381
PKCS8EncodedKeySpec keySpec = encryptedPrivateKeyInfo.getKeySpec(cipher);
374382
String keyAlgo = getKeyAlgorithmIdentifier(keySpec.getEncoded());
375383
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo);
376384
return keyFactory.generatePrivate(keySpec);
377385
}
378386

387+
private static EncryptedPrivateKeyInfo getEncryptedPrivateKeyInfo(byte[] keyBytes) throws IOException, GeneralSecurityException {
388+
try {
389+
return new EncryptedPrivateKeyInfo(keyBytes);
390+
} catch (IOException e) {
391+
// The Sun JCE provider can't handle non-AES PBES2 data (but it can handle PBES1 DES data - go figure)
392+
// It's not worth our effort to try and decrypt it ourselves, but we can detect it and give a good error message
393+
DerParser parser = new DerParser(keyBytes);
394+
final DerParser.Asn1Object rootSeq = parser.readAsn1Object(DerParser.Type.SEQUENCE);
395+
parser = rootSeq.getParser();
396+
final DerParser.Asn1Object algSeq = parser.readAsn1Object(DerParser.Type.SEQUENCE);
397+
parser = algSeq.getParser();
398+
final String algId = parser.readAsn1Object(DerParser.Type.OBJECT_OID).getOid();
399+
if (PBES2_OID.equals(algId)) {
400+
final DerParser.Asn1Object algData = parser.readAsn1Object(DerParser.Type.SEQUENCE);
401+
parser = algData.getParser();
402+
final DerParser.Asn1Object ignoreKdf = parser.readAsn1Object(DerParser.Type.SEQUENCE);
403+
final DerParser.Asn1Object cryptSeq = parser.readAsn1Object(DerParser.Type.SEQUENCE);
404+
parser = cryptSeq.getParser();
405+
final String encryptionId = parser.readAsn1Object(DerParser.Type.OBJECT_OID).getOid();
406+
if (encryptionId.startsWith(AES_OID) == false) {
407+
final String name = getAlgorithmNameFromOid(encryptionId);
408+
throw new GeneralSecurityException(
409+
"PKCS#8 Private Key is encrypted with unsupported PBES2 algorithm ["
410+
+ encryptionId
411+
+ "]"
412+
+ (name == null ? "" : " (" + name + ")"),
413+
e
414+
);
415+
}
416+
}
417+
throw e;
418+
}
419+
}
420+
421+
/**
422+
* This is horrible, but it's the only option other than to parse the encoded ASN.1 value ourselves
423+
* @see AlgorithmParameters#toString() and com.sun.crypto.provider.PBES2Parameters#toString()
424+
*/
425+
private static String getPBES2Algorithm(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) {
426+
final AlgorithmParameters algParameters = encryptedPrivateKeyInfo.getAlgParameters();
427+
if (algParameters != null) {
428+
return algParameters.toString();
429+
} else {
430+
// AlgorithmParameters can be null when running on BCFIPS.
431+
// However, since BCFIPS doesn't support any PBE specs, nothing we do here would work, so we just do enough to avoid an NPE
432+
return encryptedPrivateKeyInfo.getAlgName();
433+
}
434+
}
435+
379436
/**
380437
* Decrypts the password protected contents using the algorithm and IV that is specified in the PEM Headers of the file
381438
*
@@ -604,7 +661,7 @@ private static String getKeyAlgorithmIdentifier(byte[] keyBytes) throws IOExcept
604661
return "EC";
605662
}
606663
throw new GeneralSecurityException("Error parsing key algorithm identifier. Algorithm with OID [" + oidString +
607-
"] is not żsupported");
664+
"] is not supported");
608665
}
609666

610667
public static List<Certificate> readCertificates(Collection<Path> certPaths) throws CertificateException, IOException {
@@ -622,6 +679,56 @@ public static List<Certificate> readCertificates(Collection<Path> certPaths) thr
622679
return certificates;
623680
}
624681

682+
private static String getAlgorithmNameFromOid(String oidString) throws GeneralSecurityException {
683+
switch (oidString) {
684+
case "1.2.840.10040.4.1":
685+
return "DSA";
686+
case "1.2.840.113549.1.1.1":
687+
return "RSA";
688+
case "1.2.840.10045.2.1":
689+
return "EC";
690+
case "1.3.14.3.2.7":
691+
return "DES-CBC";
692+
case "2.16.840.1.101.3.4.1.1":
693+
return "AES-128_ECB";
694+
case "2.16.840.1.101.3.4.1.2":
695+
return "AES-128_CBC";
696+
case "2.16.840.1.101.3.4.1.3":
697+
return "AES-128_OFB";
698+
case "2.16.840.1.101.3.4.1.4":
699+
return "AES-128_CFB";
700+
case "2.16.840.1.101.3.4.1.6":
701+
return "AES-128_GCM";
702+
case "2.16.840.1.101.3.4.1.21":
703+
return "AES-192_ECB";
704+
case "2.16.840.1.101.3.4.1.22":
705+
return "AES-192_CBC";
706+
case "2.16.840.1.101.3.4.1.23":
707+
return "AES-192_OFB";
708+
case "2.16.840.1.101.3.4.1.24":
709+
return "AES-192_CFB";
710+
case "2.16.840.1.101.3.4.1.26":
711+
return "AES-192_GCM";
712+
case "2.16.840.1.101.3.4.1.41":
713+
return "AES-256_ECB";
714+
case "2.16.840.1.101.3.4.1.42":
715+
return "AES-256_CBC";
716+
case "2.16.840.1.101.3.4.1.43":
717+
return "AES-256_OFB";
718+
case "2.16.840.1.101.3.4.1.44":
719+
return "AES-256_CFB";
720+
case "2.16.840.1.101.3.4.1.46":
721+
return "AES-256_GCM";
722+
case "2.16.840.1.101.3.4.1.5":
723+
return "AESWrap-128";
724+
case "2.16.840.1.101.3.4.1.25":
725+
return "AESWrap-192";
726+
case "2.16.840.1.101.3.4.1.45":
727+
return "AESWrap-256";
728+
}
729+
return null;
730+
}
731+
625732
private static String getEcCurveNameFromOid(String oidString) throws GeneralSecurityException {
626733
switch (oidString) {
627734
// see https://tools.ietf.org/html/rfc5480#section-2.1.1.1

libs/ssl-config/src/test/java/org/elasticsearch/common/ssl/PemUtilsTests.java

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import java.nio.file.Files;
1616
import java.nio.file.Path;
1717
import java.security.AlgorithmParameters;
18+
import java.security.GeneralSecurityException;
1819
import java.security.Key;
1920
import java.security.KeyStore;
2021
import java.security.PrivateKey;
@@ -26,6 +27,7 @@
2627
import static org.hamcrest.Matchers.equalTo;
2728
import static org.hamcrest.Matchers.instanceOf;
2829
import static org.hamcrest.Matchers.notNullValue;
30+
import static org.hamcrest.Matchers.startsWith;
2931
import static org.hamcrest.core.StringContains.containsString;
3032

3133
public class PemUtilsTests extends ESTestCase {
@@ -79,17 +81,49 @@ public void testReadPKCS8EcKey() throws Exception {
7981
assertThat(privateKey, equalTo(key));
8082
}
8183

82-
public void testReadEncryptedPKCS8Key() throws Exception {
84+
public void testReadEncryptedPKCS8PBES1Key() throws Exception {
8385
assumeFalse("Can't run in a FIPS JVM, PBE KeySpec is not available", inFipsJvm());
8486
Key key = getKeyFromKeystore("RSA");
8587
assertThat(key, notNullValue());
8688
assertThat(key, instanceOf(PrivateKey.class));
87-
PrivateKey privateKey = PemUtils.parsePrivateKey(getDataPath
88-
("/certs/pem-utils/key_pkcs8_encrypted.pem"), TESTNODE_PASSWORD);
89+
PrivateKey privateKey = PemUtils.parsePrivateKey(
90+
getDataPath("/certs/pem-utils/key_pkcs8_encrypted_pbes1_des.pem"),
91+
TESTNODE_PASSWORD
92+
);
8993
assertThat(privateKey, notNullValue());
9094
assertThat(privateKey, equalTo(key));
9195
}
9296

97+
public void testReadEncryptedPKCS8PBES2AESKey() throws Exception {
98+
assumeFalse("Can't run in a FIPS JVM, PBE KeySpec is not available", inFipsJvm());
99+
Key key = getKeyFromKeystore("RSA");
100+
assertThat(key, notNullValue());
101+
assertThat(key, instanceOf(PrivateKey.class));
102+
PrivateKey privateKey = PemUtils.parsePrivateKey(
103+
getDataPath("/certs/pem-utils/key_pkcs8_encrypted_pbes2_aes.pem"),
104+
TESTNODE_PASSWORD
105+
);
106+
assertThat(privateKey, notNullValue());
107+
assertThat(privateKey, equalTo(key));
108+
}
109+
110+
public void testReadEncryptedPKCS8PBES2DESKey() throws Exception {
111+
assumeFalse("Can't run in a FIPS JVM, PBE KeySpec is not available", inFipsJvm());
112+
113+
// Sun JSE cannot read keys encrypted with PBES2 DES (but does support AES with PBES2 and DES with PBES1)
114+
// Rather than add our own support for this we just detect that our error message is clear and meaningful
115+
final GeneralSecurityException exception = expectThrows(
116+
GeneralSecurityException.class,
117+
() -> PemUtils.parsePrivateKey(getDataPath("/certs/pem-utils/key_pkcs8_encrypted_pbes2_des.pem"), TESTNODE_PASSWORD)
118+
);
119+
assertThat(
120+
exception.getMessage(),
121+
equalTo("PKCS#8 Private Key is encrypted with unsupported PBES2 algorithm [1.3.14.3.2.7] (DES-CBC)")
122+
);
123+
assertThat(exception.getCause(), instanceOf(IOException.class));
124+
assertThat(exception.getCause().getMessage(), startsWith("PBE parameter parsing error"));
125+
}
126+
93127
public void testReadDESEncryptedPKCS1Key() throws Exception {
94128
Key key = getKeyFromKeystore("RSA");
95129
assertThat(key, notNullValue());
@@ -134,8 +168,10 @@ public void testReadOpenSslDsaKeyWithParams() throws Exception {
134168
Key key = getKeyFromKeystore("DSA");
135169
assertThat(key, notNullValue());
136170
assertThat(key, instanceOf(PrivateKey.class));
137-
PrivateKey privateKey = PemUtils.parsePrivateKey(getDataPath("/certs/pem-utils/dsa_key_openssl_plain_with_params.pem"),
138-
EMPTY_PASSWORD);
171+
PrivateKey privateKey = PemUtils.parsePrivateKey(
172+
getDataPath("/certs/pem-utils/dsa_key_openssl_plain_with_params.pem"),
173+
EMPTY_PASSWORD
174+
);
139175

140176
assertThat(privateKey, notNullValue());
141177
assertThat(privateKey, equalTo(key));
@@ -165,8 +201,10 @@ public void testReadOpenSslEcKeyWithParams() throws Exception {
165201
Key key = getKeyFromKeystore("EC");
166202
assertThat(key, notNullValue());
167203
assertThat(key, instanceOf(PrivateKey.class));
168-
PrivateKey privateKey = PemUtils.parsePrivateKey(getDataPath("/certs/pem-utils/ec_key_openssl_plain_with_params.pem"),
169-
EMPTY_PASSWORD);
204+
PrivateKey privateKey = PemUtils.parsePrivateKey(
205+
getDataPath("/certs/pem-utils/ec_key_openssl_plain_with_params.pem"),
206+
EMPTY_PASSWORD
207+
);
170208

171209
assertThat(privateKey, notNullValue());
172210
assertThat(privateKey, equalTo(key));

0 commit comments

Comments
 (0)