From e0c79ce598f62f4a4404124a5abf1bde04b49057 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 11 Oct 2022 22:40:18 -0700 Subject: [PATCH] Support PEM formatted elliptic-curve TLS keys Update `PrivateKeyParser` to support loading PEM formatted elliptic-curve keys. We need to do a similar trick to the PKCS1 keys and convert them to a `PKCS8EncodedKeySpec`. Fixes gh-32646 --- .../platform/docker/ssl/PrivateKeyParser.java | 233 +++++++++++++----- .../docker/ssl/KeyStoreFactoryTests.java | 6 +- .../platform/docker/ssl/PemFileWriter.java | 9 +- .../docker/ssl/PrivateKeyParserTests.java | 46 +++- .../docker/ssl/SslContextFactoryTests.java | 4 +- 5 files changed, 225 insertions(+), 73 deletions(-) diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParser.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParser.java index 63e870b28df2..002791a88de9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParser.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,11 @@ import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -43,21 +46,68 @@ final class PrivateKeyParser { private static final String PKCS1_FOOTER = "-+END\\s+RSA\\s+PRIVATE\\s+KEY[^-]*-+"; + private static final String PKCS8_HEADER = "-+BEGIN\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+"; + private static final String PKCS8_FOOTER = "-+END\\s+PRIVATE\\s+KEY[^-]*-+"; - private static final String PKCS8_HEADER = "-+BEGIN\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+"; + private static final String EC_HEADER = "-+BEGIN\\s+EC\\s+PRIVATE\\s+KEY[^-]*-+(?:\\s|\\r|\\n)+"; + + private static final String EC_FOOTER = "-+END\\s+EC\\s+PRIVATE\\s+KEY[^-]*-+"; private static final String BASE64_TEXT = "([a-z0-9+/=\\r\\n]+)"; - private static final Pattern PKCS1_PATTERN = Pattern.compile(PKCS1_HEADER + BASE64_TEXT + PKCS1_FOOTER, - Pattern.CASE_INSENSITIVE); + private static final List PEM_PARSERS; + static { + List parsers = new ArrayList<>(); + parsers.add(new PemParser(PKCS1_HEADER, PKCS1_FOOTER, "RSA", PrivateKeyParser::createKeySpecForPkcs1)); + parsers.add(new PemParser(EC_HEADER, EC_FOOTER, "EC", PrivateKeyParser::createKeySpecForEc)); + parsers.add(new PemParser(PKCS8_HEADER, PKCS8_FOOTER, "RSA", PKCS8EncodedKeySpec::new)); + PEM_PARSERS = Collections.unmodifiableList(parsers); + } + + /** + * ASN.1 encoded object identifier {@literal 1.2.840.113549.1.1.1}. + */ + private static final int[] RSA_ALGORITHM = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 }; - private static final Pattern PKCS8_KEY_PATTERN = Pattern.compile(PKCS8_HEADER + BASE64_TEXT + PKCS8_FOOTER, - Pattern.CASE_INSENSITIVE); + /** + * ASN.1 encoded object identifier {@literal 1.2.840.10045.2.1}. + */ + private static final int[] EC_ALGORITHM = { 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01 }; + + /** + * ASN.1 encoded object identifier {@literal 1.3.132.0.34}. + */ + private static final int[] EC_PARAMETERS = { 0x2b, 0x81, 0x04, 0x00, 0x22 }; private PrivateKeyParser() { } + private static PKCS8EncodedKeySpec createKeySpecForPkcs1(byte[] bytes) { + return createKeySpecForAlgorithm(bytes, RSA_ALGORITHM, null); + } + + private static PKCS8EncodedKeySpec createKeySpecForEc(byte[] bytes) { + return createKeySpecForAlgorithm(bytes, EC_ALGORITHM, EC_PARAMETERS); + } + + private static PKCS8EncodedKeySpec createKeySpecForAlgorithm(byte[] bytes, int[] algorithm, int[] parameters) { + try { + DerEncoder encoder = new DerEncoder(); + encoder.integer(0x00); // Version 0 + DerEncoder algorithmIdentifier = new DerEncoder(); + algorithmIdentifier.objectIdentifier(algorithm); + algorithmIdentifier.objectIdentifier(parameters); + byte[] byteArray = algorithmIdentifier.toByteArray(); + encoder.sequence(byteArray); + encoder.octetString(bytes); + return new PKCS8EncodedKeySpec(encoder.toSequence()); + } + catch (IOException ex) { + throw new IllegalStateException(ex); + } + } + /** * Load a private key from the specified file paths. * @param path the path to the private key file @@ -66,80 +116,137 @@ private PrivateKeyParser() { static PrivateKey parse(Path path) { try { String text = readText(path); - Matcher matcher = PKCS1_PATTERN.matcher(text); - if (matcher.find()) { - return parsePkcs1(decodeBase64(matcher.group(1))); + for (PemParser pemParser : PEM_PARSERS) { + PrivateKey privateKey = pemParser.parse(text); + if (privateKey != null) { + return privateKey; + } } - matcher = PKCS8_KEY_PATTERN.matcher(text); - if (matcher.find()) { - return parsePkcs8(decodeBase64(matcher.group(1))); - } - throw new IllegalStateException("Unrecognized private key format in " + path); + throw new IllegalStateException("Unrecognized private key format"); } - catch (GeneralSecurityException | IOException ex) { + catch (Exception ex) { throw new IllegalStateException("Error loading private key file " + path, ex); } } - private static PrivateKey parsePkcs1(byte[] privateKeyBytes) throws GeneralSecurityException { - byte[] pkcs8Bytes = convertPkcs1ToPkcs8(privateKeyBytes); - return parsePkcs8(pkcs8Bytes); + private static String readText(Path path) throws IOException { + byte[] bytes = Files.readAllBytes(path); + return new String(bytes, StandardCharsets.UTF_8); } - private static byte[] convertPkcs1ToPkcs8(byte[] pkcs1) { - try { - ByteArrayOutputStream result = new ByteArrayOutputStream(); - int pkcs1Length = pkcs1.length; - int totalLength = pkcs1Length + 22; - // Sequence + total length - result.write(bytes(0x30, 0x82)); - result.write((totalLength >> 8) & 0xff); - result.write(totalLength & 0xff); - // Integer (0) - result.write(bytes(0x02, 0x01, 0x00)); - // Sequence: 1.2.840.113549.1.1.1, NULL - result.write( - bytes(0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00)); - // Octet string + length - result.write(bytes(0x04, 0x82)); - result.write((pkcs1Length >> 8) & 0xff); - result.write(pkcs1Length & 0xff); - // PKCS1 - result.write(pkcs1); - return result.toByteArray(); + /** + * Parser for a specific PEM format. + */ + private static class PemParser { + + private final Pattern pattern; + + private final String algorithm; + + private final Function keySpecFactory; + + PemParser(String header, String footer, String algorithm, + Function keySpecFactory) { + this.pattern = Pattern.compile(header + BASE64_TEXT + footer, Pattern.CASE_INSENSITIVE); + this.algorithm = algorithm; + this.keySpecFactory = keySpecFactory; } - catch (IOException ex) { - throw new IllegalStateException(ex); + + PrivateKey parse(String text) { + Matcher matcher = this.pattern.matcher(text); + return (!matcher.find()) ? null : parse(decodeBase64(matcher.group(1))); } - } - private static byte[] bytes(int... elements) { - byte[] result = new byte[elements.length]; - for (int i = 0; i < elements.length; i++) { - result[i] = (byte) elements[i]; + private static byte[] decodeBase64(String content) { + byte[] contentBytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes(); + return Base64Utils.decode(contentBytes); } - return result; + + private PrivateKey parse(byte[] bytes) { + try { + PKCS8EncodedKeySpec keySpec = this.keySpecFactory.apply(bytes); + KeyFactory keyFactory = KeyFactory.getInstance(this.algorithm); + return keyFactory.generatePrivate(keySpec); + } + catch (GeneralSecurityException ex) { + throw new IllegalArgumentException("Unexpected key format", ex); + } + } + } - private static PrivateKey parsePkcs8(byte[] privateKeyBytes) throws GeneralSecurityException { - try { - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - return keyFactory.generatePrivate(keySpec); + /** + * Simple ASN.1 DER encoder. + */ + static class DerEncoder { + + private final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + void objectIdentifier(int... encodedObjectIdentifier) throws IOException { + int code = (encodedObjectIdentifier != null) ? 0x06 : 0x05; + codeLengthBytes(code, bytes(encodedObjectIdentifier)); } - catch (InvalidKeySpecException ex) { - throw new IllegalArgumentException("Unexpected key format", ex); + + void integer(int... encodedInteger) throws IOException { + codeLengthBytes(0x02, bytes(encodedInteger)); } - } - private static String readText(Path path) throws IOException { - byte[] bytes = Files.readAllBytes(path); - return new String(bytes, StandardCharsets.UTF_8); - } + void octetString(byte[] bytes) throws IOException { + codeLengthBytes(0x04, bytes); + } + + void sequence(int... elements) throws IOException { + sequence(bytes(elements)); + } + + void sequence(byte[] bytes) throws IOException { + codeLengthBytes(0x30, bytes); + } + + void codeLengthBytes(int code, byte[] bytes) throws IOException { + this.stream.write(code); + int length = (bytes != null) ? bytes.length : 0; + if (length <= 127) { + this.stream.write(length & 0xFF); + } + else { + ByteArrayOutputStream lengthStream = new ByteArrayOutputStream(); + while (length != 0) { + lengthStream.write(length & 0xFF); + length = length >> 8; + } + byte[] lengthBytes = lengthStream.toByteArray(); + this.stream.write(0x80 | lengthBytes.length); + for (int i = lengthBytes.length - 1; i >= 0; i--) { + this.stream.write(lengthBytes[i]); + } + } + if (bytes != null) { + this.stream.write(bytes); + } + } + + private static byte[] bytes(int... elements) { + if (elements == null) { + return null; + } + byte[] result = new byte[elements.length]; + for (int i = 0; i < elements.length; i++) { + result[i] = (byte) elements[i]; + } + return result; + } + + byte[] toSequence() throws IOException { + DerEncoder sequenceEncoder = new DerEncoder(); + sequenceEncoder.sequence(toByteArray()); + return sequenceEncoder.toByteArray(); + } + + byte[] toByteArray() { + return this.stream.toByteArray(); + } - private static byte[] decodeBase64(String content) { - byte[] contentBytes = content.replaceAll("\r", "").replaceAll("\n", "").getBytes(); - return Base64Utils.decode(contentBytes); } } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/KeyStoreFactoryTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/KeyStoreFactoryTests.java index 083f5d9b0431..b294b8d4c8a9 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/KeyStoreFactoryTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/KeyStoreFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,10 +64,10 @@ void createKeyStoreWithCertChain() } @Test - void createKeyStoreWithCertChainAndPrivateKey() + void createKeyStoreWithCertChainAndRsaPrivateKey() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException { Path certPath = this.fileWriter.writeFile("cert.pem", PemFileWriter.CA_CERTIFICATE, PemFileWriter.CERTIFICATE); - Path keyPath = this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_KEY); + Path keyPath = this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_RSA_KEY); KeyStore keyStore = KeyStoreFactory.create(certPath, keyPath, "test-alias"); assertThat(keyStore.containsAlias("test-alias")).isTrue(); assertThat(keyStore.getCertificate("test-alias")).isNotNull(); diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PemFileWriter.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PemFileWriter.java index 39f3c19ccc91..05888b14401f 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PemFileWriter.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PemFileWriter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ public class PemFileWriter { + "a/OsPdOw0j+NqFDBd3mSMhSVgfvXdK6j9WaxY1VGXyaidLARgvn63wfzgr857sQW\n" + "c8eSxbwEQxwlMvVxW6Os4VhCfUQr8VrBrvPa2zs+6IlK+Ug=\n" + "-----END CERTIFICATE-----\n"; - public static final String PRIVATE_KEY = EXAMPLE_SECRET_QUALIFIER + "-----BEGIN RSA PRIVATE KEY-----\n" + public static final String PRIVATE_RSA_KEY = EXAMPLE_SECRET_QUALIFIER + "-----BEGIN RSA PRIVATE KEY-----\n" + "MIICXAIBAAKBgQDO5HdnIxePcJtfjkO0ORhPenF7nljT6/zcHou9bX+huAZhNAfr\n" + "LlxxL5y6R04/aXV/2cwSCvIyGf8fEZ0nbivysvs5tUDGFFmbVggIAlvFs4AevQp/\n" + "4UBvCkl90vW6jg7kALz+eBkCQ+/uJFbjQRoxW+A2g+J7zJj7QC0mX/GQmQIDAQAB\n" @@ -96,6 +96,11 @@ public class PemFileWriter { + "8bbHWILSIhFJHg0V7skCQDa8/YkRWF/3pwIZNWQr4ce4OzvYsFMkRvGRdX8B2a0p\n" + "wSKcVTdEdO2DhBlYddN0zG0rjq4vDMtdmldEl4BdldQ=\n" + "-----END RSA PRIVATE KEY-----\n"; + public static final String PRIVATE_EC_KEY = EXAMPLE_SECRET_QUALIFIER + "-----BEGIN EC PRIVATE KEY-----\n" + + "MHcCAQEEIIwZkO8Zjbggzi8wwrk5rzSPzUX31gqTRhBYw4AL6w44oAoGCCqGSM49\n" + + "AwEHoUQDQgAE8y28khug747bA68M90IAMCPHAYyen+RsN6i84LORpNDUhv00QZWd\n" + + "hOhjWFCQjnewR98Y8pEb1fnORll4LhHPlQ==\n" + "-----END EC PRIVATE KEY-----"; + private final Path tempDir; public PemFileWriter() throws IOException { diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java index 10896e86f77a..f55f79aaf3e0 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/PrivateKeyParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,11 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; +import org.springframework.boot.buildpack.platform.docker.ssl.PrivateKeyParser.DerEncoder; + import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; @@ -35,6 +38,7 @@ * Tests for {@link PrivateKeyParser}. * * @author Scott Frederick + * @author Phillip Webb */ class PrivateKeyParserTests { @@ -60,8 +64,18 @@ void parsePkcs8KeyFile() throws IOException { } @Test - void parsePkcs1KeyFile() throws IOException { - Path path = this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_KEY); + void parsePkcs1RsaKeyFile() throws IOException { + Path path = this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_RSA_KEY); + PrivateKey privateKey = PrivateKeyParser.parse(path); + assertThat(privateKey).isNotNull(); + // keys in PKCS#1 format are converted to PKCS#8 for parsing + assertThat(privateKey.getFormat()).isEqualTo("PKCS#8"); + Files.delete(path); + } + + @Test + void parsePkcs1EcKeyFile() throws IOException { + Path path = this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_EC_KEY); PrivateKey privateKey = PrivateKeyParser.parse(path); assertThat(privateKey).isNotNull(); // keys in PKCS#1 format are converted to PKCS#8 for parsing @@ -84,4 +98,30 @@ void parseWithInvalidPathWillThrowException() throws URISyntaxException { .withMessageContaining(path.toString()); } + @Nested + class DerEncoderTests { + + @Test + void codeLengthBytesShort() throws Exception { + DerEncoder encoder = new DerEncoder(); + encoder.codeLengthBytes(0, new byte[127]); + assertThat(encoder.toByteArray()).startsWith(0x0, 0x7F); + } + + @Test + void codeLengthBytesMedium() throws Exception { + DerEncoder encoder = new DerEncoder(); + encoder.codeLengthBytes(0, new byte[130]); + assertThat(encoder.toByteArray()).startsWith(0x0, 0x81, 0x82); + } + + @Test + void codeLengthBytesLong() throws Exception { + DerEncoder encoder = new DerEncoder(); + encoder.codeLengthBytes(0, new byte[258]); + assertThat(encoder.toByteArray()).startsWith(0x0, 0x82, 0x01, 0x02); + } + + } + } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/SslContextFactoryTests.java b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/SslContextFactoryTests.java index 0f370d5a8e53..964529b4de31 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/SslContextFactoryTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/docker/ssl/SslContextFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ void tearDown() throws IOException { @Test void createKeyStoreWithCertChain() throws IOException { this.fileWriter.writeFile("cert.pem", PemFileWriter.CERTIFICATE); - this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_KEY); + this.fileWriter.writeFile("key.pem", PemFileWriter.PRIVATE_RSA_KEY); this.fileWriter.writeFile("ca.pem", PemFileWriter.CA_CERTIFICATE); SSLContext sslContext = new SslContextFactory().forDirectory(this.fileWriter.getTempDir().toString()); assertThat(sslContext).isNotNull();