Skip to content

Ghidra is a software reverse engineering (SRE) framework

GP-7380 Corrected CertTool issue related to PKCS7 processing.

ghidra1a7b3152712a8
diff --git a/Ghidra/Features/GhidraServer/src/main/java/ghidra/server/remote/GhidraServer.java b/Ghidra/Features/GhidraServer/src/main/java/ghidra/server/remote/GhidraServer.java
index 5299b6a0a3..e8070b6ca7 100644
--- a/Ghidra/Features/GhidraServer/src/main/java/ghidra/server/remote/GhidraServer.java
+++ b/Ghidra/Features/GhidraServer/src/main/java/ghidra/server/remote/GhidraServer.java
@@ -960,18 +960,18 @@ public class GhidraServer extends UnicastRemoteObject implements GhidraServerHan
Collection<List<?>> sanList = x509Cert.getSubjectAlternativeNames();
if (sanList != null) {
for (List<?> sanEntry : sanList) {
- Integer type = (Integer) sanEntry.get(0);
- Object value = sanEntry.get(1);
- if (type == GeneralName.iPAddress || type == GeneralName.dNSName) {
- if (!foundSANEntries) {
- log.info(pad + "Subject Alternative Names:");
+ Integer type = (Integer) sanEntry.get(0);
+ Object value = sanEntry.get(1);
+ if (type == GeneralName.iPAddress || type == GeneralName.dNSName) {
+ if (!foundSANEntries) {
+ log.info(pad + "Subject Alternative Names:");
+ }
+ foundSANEntries = true;
+ log.info(pad + " " + value);
}
- foundSANEntries = true;
- log.info(pad + " " + value);
}
}
}
- }
catch (Exception e) {
log.fatal("Error reading certificate SANs: " + e.getMessage());
System.exit(-1);
diff --git a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/remote/SignatureCallback.java b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/remote/SignatureCallback.java
index f236552604..c45ff29996 100644
--- a/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/remote/SignatureCallback.java
+++ b/Ghidra/Framework/FileSystem/src/main/java/ghidra/framework/remote/SignatureCallback.java
@@ -92,7 +92,8 @@ public class SignatureCallback implements Callback, Serializable {
}
/**
- * {@return certificate chain used to sign token}
+ * {@return certificate chain used to sign token, with the signing identity first and its
+ * issuing CAs following it; the root certificate may be omitted}
*/
public X509Certificate[] getCertificateChain() {
return certChain;
@@ -101,7 +102,10 @@ public class SignatureCallback implements Callback, Serializable {
/**
* Set token signature data. Method must be invoked by
* callback handler.
- * @param sigCertChain certificate chain used to sign token.
+ * @param sigCertChain certificate chain used to sign token, ordered with the signing identity
+ * first and its issuing CAs following it. The root certificate may be omitted. The receiver
+ * must validate the chain and verify the token signature using that same first certificate;
+ * certificate positions must not be inferred from the presence of a self-signed CA.
* @param certSignature token signature
*/
public void sign(X509Certificate[] sigCertChain, byte[] certSignature) {
diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/net/CertTool.java b/Ghidra/Framework/Generic/src/main/java/ghidra/net/CertTool.java
index 8eeb7b05f4..710ce71433 100644
--- a/Ghidra/Framework/Generic/src/main/java/ghidra/net/CertTool.java
+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/net/CertTool.java
@@ -336,70 +336,23 @@ public class CertTool implements GhidraLaunchable {
return -1;
}
- // Load the private key
- // PrivateKey privateKey = loadPrivateKey(keyFile);
KeyPair keyPair = loadKeyPair(keyFile);
- // Load the certificate
- X509Certificate[] certChain = loadCertificateChain(certFile);
-
- // Verify corresponding key
- X509Certificate subjectCert = certChain[0];
- if (!keyPair.getPublic().equals(subjectCert.getPublicKey())) {
- System.err.println("Certificate file does not correspond to key file!");
- return -1;
- }
-
+ // Certificate files (especially PKCS#7) contain collections, not ordered chains.
+ List<X509Certificate> certificates = Arrays.asList(loadCertificates(certFile));
+ List<X509Certificate> caCertificates = Collections.emptyList();
if (caFile != null) {
-
- if (certChain.length != 1) {
- System.err.println(
- "Expected only one certificate in -cert file when -caFile specified.");
- return -1;
- }
-
- X509Certificate[] caChain = null;
-
- // Try as simple concatenation of certificates
+ X509Certificate[] caCerts;
try {
- caChain = loadCertificateChain(caFile);
+ caCerts = loadCertificates(caFile);
}
catch (Exception e) {
- // ignore
+ caCerts = loadPkcs7Certificates(caFile);
}
-
- if (caChain == null) {
- try {
- caChain = loadPkcs7CAChain(caFile);
- }
- catch (Exception e) {
- // ignore
- }
- }
-
- if (caChain == null) {
- System.err.println("Failed to load CA Chain file.");
- return -1;
- }
-
- // If supplied CA chain file contains subject certificate - certChain[0]
- // use it as the complete certChain, otherwise concatenate.
- if (caChain[0].getSubjectX500Principal()
- .equals(certChain[0].getSubjectX500Principal()) &&
- caChain[0].getSerialNumber().equals(certChain[0].getSerialNumber())) {
- certChain = caChain;
- }
- else {
- X509Certificate[] chain = new X509Certificate[caChain.length + 1];
- chain[0] = certChain[0];
- System.arraycopy(caChain, 0, chain, 1, caChain.length);
- certChain = chain;
- }
- }
-
- if (!verifyChainWithStrictRoot(certChain)) {
- return -1;
+ caCertificates = Arrays.asList(caCerts);
}
+ X509Certificate[] certChain =
+ buildCertificateChain(keyPair.getPublic(), certificates, caCertificates);
char[] pwd = promptForNewPassword("Enter new keystore password:");
if (pwd == null) {
@@ -418,64 +371,85 @@ public class CertTool implements GhidraLaunchable {
return 0;
}
- private static boolean verifyChainWithStrictRoot(X509Certificate[] fullChain) {
- if (fullChain == null || fullChain.length <= 1) {
- System.err.println("Incomplete certificate chain!");
- System.err.println("Concatenate all CAs in chain with Root last.");
- if (fullChain.length == 1) {
- String issuerDN = fullChain[0].getIssuerX500Principal().getName();
- System.err.println("Subject certificate issued by: " + issuerDN);
+ /**
+ * Select the certificate matching the key and build a validated, leaf-first chain from
+ * unordered certificate bundles. Identical certificates are deduplicated; distinct
+ * certificates matching the key are ambiguous and require a more specific -cert file.
+ * Unrelated certificates are ignored and any valid issuer path may be selected by PKIX.
+ * <p>
+ * This import operation requires an included, valid self-signed CA root. Using that root as
+ * a path-building anchor checks chain consistency only; it does not establish external trust
+ * in the supplied CA. Revocation checking remains disabled for this offline import operation.
+ *
+ * @param publicKey public key corresponding to the supplied private key
+ * @param certificates certificates from the -cert file, including the desired identity
+ * @param caCertificates optional additional certificates from the -cachain file
+ * @return validated chain with the identity first and the self-signed root last
+ * @throws GeneralSecurityException if the identity is missing or ambiguous, or no complete
+ * validated path to an included self-signed CA root can be built
+ */
+ static X509Certificate[] buildCertificateChain(PublicKey publicKey,
+ Collection<X509Certificate> certificates, Collection<X509Certificate> caCertificates)
+ throws GeneralSecurityException {
+ Set<X509Certificate> candidates = new LinkedHashSet<>(certificates);
+ X509Certificate subjectCert = null;
+ for (X509Certificate cert : candidates) {
+ if (publicKey.equals(cert.getPublicKey())) {
+ if (subjectCert != null) {
+ throw new CertificateException(
+ "Multiple certificates in -cert file correspond to key file; " +
+ "specify only the intended identity certificate.");
+ }
+ subjectCert = cert;
}
- return false;
}
+ if (subjectCert == null) {
+ throw new CertificateException("Certificate file does not correspond to key file!");
+ }
+ subjectCert.checkValidity();
+ candidates.addAll(caCertificates);
- try {
- // Isolate and verify the assumed root certificate (end of chain)
- X509Certificate rootCert = fullChain[fullChain.length - 1];
- rootCert.checkValidity();
- if (!rootCert.getSubjectX500Principal().equals(rootCert.getIssuerX500Principal())) {
- System.err.println(
- "Root verification failed: The last certificate is not self-signed.");
- return false;
+ Set<TrustAnchor> anchors = new HashSet<>();
+ for (X509Certificate cert : candidates) {
+ // Do not allow the identity to become its own trust anchor and bypass validation.
+ if (cert.equals(subjectCert) || cert.getBasicConstraints() < 0 ||
+ !cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
+ continue;
}
- try {
- rootCert.verify(rootCert.getPublicKey()); // Check its signature
+ boolean[] usage = cert.getKeyUsage();
+ if (usage != null && !usage[5]) { // keyCertSign
+ continue;
}
- catch (Exception e) {
- System.err.println(
- "Root verification failed: Signature does not match its public key.");
- return false;
+ try {
+ // PKIX does not validate the trust anchor itself.
+ cert.checkValidity();
+ cert.verify(cert.getPublicKey());
+ anchors.add(new TrustAnchor(cert, null));
}
- if (rootCert.getBasicConstraints() < 0) {
- System.err.println(
- "Root verification failed: Certificate lacks CA basic constraints.");
- return false;
+ catch (GeneralSecurityException e) {
+ // An invalid or merely self-issued certificate is not a usable root.
}
-
- // Isolate the remainder of the chain and establish trust root
- // Subject certificate is first and must be removed from trust chain
- List<X509Certificate> validationPath =
- Arrays.asList(fullChain).subList(1, fullChain.length - 1);
- TrustAnchor anchor = new TrustAnchor(rootCert, null);
- Set<TrustAnchor> trustAnchors = new HashSet<>(Collections.singletonList(anchor));
-
- // Run standard PKIX path validation on the remaining chain
- PKIXParameters params = new PKIXParameters(trustAnchors);
- params.setRevocationEnabled(false);
-
- CertificateFactory factory = CertificateFactory.getInstance("X.509");
- CertPath certPath = factory.generateCertPath(validationPath);
-
- CertPathValidator validator = CertPathValidator.getInstance("PKIX");
- validator.validate(certPath, params);
-
- return true;
-
- }
- catch (Exception e) {
- System.err.println("Incomplete or invalid certificate chain: " + e.getMessage());
- return false;
}
+ if (anchors.isEmpty()) {
+ throw new CertificateException(
+ "Incomplete certificate chain: include a valid self-signed CA root.");
+ }
+
+ X509CertSelector target = new X509CertSelector();
+ target.setCertificate(subjectCert);
+ PKIXBuilderParameters params = new PKIXBuilderParameters(anchors, target);
+ params.setRevocationEnabled(false);
+ params.setMaxPathLength(-1);
+ params.addCertStore(CertStore.getInstance("Collection",
+ new CollectionCertStoreParameters(candidates)));
+
+ // Building validates the entire path, INCLUDING the subject certificate. Only the root
+ // is excluded from the PKIX path; append it to the chain stored in the key store.
+ PKIXCertPathBuilderResult result =
+ (PKIXCertPathBuilderResult) CertPathBuilder.getInstance("PKIX").build(params);
+ List<Certificate> chain = new ArrayList<>(result.getCertPath().getCertificates());
+ chain.add(result.getTrustAnchor().getTrustedCert());
+ return chain.toArray(new X509Certificate[0]);
}
private boolean savePrivateKey(String keyFile, PrivateKey privateKey) throws Exception {
@@ -537,7 +511,8 @@ public class CertTool implements GhidraLaunchable {
}
}
- private X509Certificate[] loadCertificateChain(String certFile) throws Exception {
+ // Parsing preserves no chain-ordering contract; buildCertificateChain establishes the order.
+ static X509Certificate[] loadCertificates(String certFile) throws Exception {
try (FileInputStream fis = new FileInputStream(certFile)) {
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
Collection<? extends java.security.cert.Certificate> certs =
@@ -546,7 +521,7 @@ public class CertTool implements GhidraLaunchable {
}
}
- private static X509Certificate[] loadPkcs7CAChain(String filePath) throws Exception {
+ static X509Certificate[] loadPkcs7Certificates(String filePath) throws Exception {
try (InputStream fis = new FileInputStream(filePath)) {
// Read the full stream bytes
byte[] p7bBytes = fis.readAllBytes();
@@ -763,7 +738,9 @@ public class CertTool implements GhidraLaunchable {
" pkcs12 -inkey <key-filename> -cert <cert-filename> [-cachain <cachain-file>] -out <keystore-filename>");
System.err.println(
" Generate a pkcs12 (p12) keystore from a private key and signed-certificate\n" +
- " chain (omit -out file extension)");
+ " chain (omit -out file extension). Certificates may be in any order;\n" +
+ " include all issuing CAs and a self-signed root. The -cert file must\n" +
+ " contain exactly one distinct certificate matching the private key.");
System.err.println(" pkcs12 -self-signed -out <keystore/cert-filename>");
System.err.println(
" Generate a new self-signed certificate and private key (omit -out file extension)");
diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultKeyManagerFactory.java b/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultKeyManagerFactory.java
index 001e6c04f4..b7876ee895 100644
--- a/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultKeyManagerFactory.java
+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultKeyManagerFactory.java
@@ -726,7 +726,7 @@ public class DefaultKeyManagerFactory {
certificateChain = x509KeyManager.getCertificateChain(alias);
}
}
- if (privateKey == null || certificateChain == null) {
+ if (privateKey == null || certificateChain == null || certificateChain.length == 0) {
CertificateException e =
new CertificateException("suitable PKI certificate not found");
throw e;
@@ -737,6 +737,7 @@ public class DefaultKeyManagerFactory {
// IdentityScope classes
//
+ // X509KeyManager returns the identity certificate first; never infer order from a CA.
String algorithm = certificateChain[0].getSigAlgName();
Signature sig = Signature.getInstance(algorithm);
try {
diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultTrustManagerFactory.java b/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultTrustManagerFactory.java
index 87c8c28282..75549d96f9 100644
--- a/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultTrustManagerFactory.java
+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/net/DefaultTrustManagerFactory.java
@@ -189,7 +189,8 @@ public class DefaultTrustManagerFactory {
/**
* Validate a client certificate ensuring that it is not expired and is
* trusted based upon the active trust managers.
- * @param certChain X509 certificate chain
+ * @param certChain X509 certificate chain with the client identity first, followed by its
+ * issuing CAs; the root certificate may be omitted
* @param authType authentication type (i.e., "RSA")
* @throws CertificateException if certificate validation fails
*/
diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/net/ServerCertificateException.java b/Ghidra/Framework/Generic/src/main/java/ghidra/net/ServerCertificateException.java
index 3bd0d1747e..8197eb63db 100644
--- a/Ghidra/Framework/Generic/src/main/java/ghidra/net/ServerCertificateException.java
+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/net/ServerCertificateException.java
@@ -30,7 +30,7 @@ public class ServerCertificateException extends CertificateException {
/**
* Constructor
- * @param serverCertChain server certificate chain
+ * @param serverCertChain TLS peer certificate chain, with the server identity first
* @param cause underlying validation cause
*/
public ServerCertificateException(X509Certificate[] serverCertChain, CertificateException cause) {
@@ -48,6 +48,9 @@ public class ServerCertificateException extends CertificateException {
}
private static String getServerInfo(X509Certificate[] serverCertChain) {
+ if (serverCertChain == null || serverCertChain.length == 0 || serverCertChain[0] == null) {
+ return ": server certificate unavailable";
+ }
X500Principal subject = serverCertChain[0].getSubjectX500Principal();
X500Principal issuer = serverCertChain[0].getIssuerX500Principal();
@@ -56,7 +59,8 @@ public class ServerCertificateException extends CertificateException {
buf.append(subject.getName());
buf.append(" [");
if (issuer.equals(subject)) {
- buf.append("self-signed");
+ // Equal names establish self-issued status, not a verified self-signature.
+ buf.append("self-issued");
}
else {
buf.append("issued by: ");
diff --git a/Ghidra/Framework/Generic/src/main/java/ghidra/net/SignedToken.java b/Ghidra/Framework/Generic/src/main/java/ghidra/net/SignedToken.java
index 50e045d013..5c8d7b02d2 100644
--- a/Ghidra/Framework/Generic/src/main/java/ghidra/net/SignedToken.java
+++ b/Ghidra/Framework/Generic/src/main/java/ghidra/net/SignedToken.java
@@ -1,13 +1,12 @@
/* ###
* IP: GHIDRA
- * REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,7 +38,8 @@ public class SignedToken {
public final String algorithm;
/**
- * Identity which corresponds to signature
+ * Certificate chain with the signing identity first, followed by its issuing CAs.
+ * The root certificate may be omitted.
*/
public final X509Certificate[] certChain;
@@ -47,7 +47,7 @@ public class SignedToken {
* SignedToken constructor
* @param token token byte array
* @param signature token byte array signature
- * @param certChain identity which corresponds to signature
+ * @param certChain certificate chain with the signing identity first
* @param algorithm algorithm used for signing
*/
SignedToken(byte[] token, byte[] signature, X509Certificate[] certChain, String algorithm) {
diff --git a/Ghidra/Framework/Generic/src/test/java/ghidra/net/CertToolTest.java b/Ghidra/Framework/Generic/src/test/java/ghidra/net/CertToolTest.java
new file mode 100644
index 0000000000..869f7b7d63
--- /dev/null
+++ b/Ghidra/Framework/Generic/src/test/java/ghidra/net/CertToolTest.java
@@ -0,0 +1,298 @@
+/* ###
+ * IP: GHIDRA
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package ghidra.net;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.math.BigInteger;
+import java.nio.file.Files;
+import java.security.*;
+import java.security.cert.X509Certificate;
+import java.util.*;
+
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.KeyUsage;
+import org.bouncycastle.cert.jcajce.JcaCertStore;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.cms.CMSAbsentContent;
+import org.bouncycastle.cms.CMSSignedDataGenerator;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+import org.junit.*;
+import org.junit.rules.TemporaryFolder;
+
+public class CertToolTest {
+
+ private static KeyPair rootKey;
+ private static KeyPair intermediateKey;
+ private static KeyPair leafKey;
+ private static KeyPair otherKey;
+ private static X509Certificate root;
+ private static X509Certificate intermediate;
+ private static X509Certificate leaf;
+ private static X509Certificate otherRoot;
+ private static long serial;
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @BeforeClass
+ public static void createCertificates() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ rootKey = generator.generateKeyPair();
+ intermediateKey = generator.generateKeyPair();
+ leafKey = generator.generateKeyPair();
+ otherKey = generator.generateKeyPair();
+ root = certificate("Root", rootKey, "Root", rootKey, true, false);
+ intermediate = certificate("Intermediate", intermediateKey, "Root", rootKey, true, false);
+ leaf = certificate("Leaf", leafKey, "Intermediate", intermediateKey, false, false);
+ otherRoot = certificate("Other", otherKey, "Other", otherKey, true, false);
+ }
+
+ private static X509Certificate certificate(String subject, KeyPair key, String issuer,
+ KeyPair signer, boolean ca, boolean expired) throws Exception {
+ return certificate(subject, key, issuer, signer, new BasicConstraints(ca),
+ ca ? KeyUsage.keyCertSign : KeyUsage.digitalSignature, expired);
+ }
+
+ private static X509Certificate certificate(String subject, KeyPair key, String issuer,
+ KeyPair signer, BasicConstraints constraints, int usage, boolean expired)
+ throws Exception {
+ long now = System.currentTimeMillis();
+ Date start = new Date(now - 86400000L);
+ Date end = new Date(now + (expired ? -3600000L : 86400000L));
+ JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
+ new X500Name("CN=" + issuer), BigInteger.valueOf(++serial), start, end,
+ new X500Name("CN=" + subject), key.getPublic());
+ builder.addExtension(Extension.basicConstraints, true, constraints);
+ builder.addExtension(Extension.keyUsage, true, new KeyUsage(usage));
+ return new JcaX509CertificateConverter().getCertificate(builder.build(
+ new JcaContentSignerBuilder("SHA256withRSA").build(signer.getPrivate())));
+ }
+
+ private X509Certificate[] build(X509Certificate... certs) throws GeneralSecurityException {
+ return CertTool.buildCertificateChain(leafKey.getPublic(), Arrays.asList(certs), List.of());
+ }
+
+ private void assertRejected(X509Certificate... certs) {
+ assertThrows(GeneralSecurityException.class, () -> build(certs));
+ }
+
+ @Test
+ public void testAllCertificateOrders() throws Exception {
+ X509Certificate[][] orders = {
+ { leaf, intermediate, root }, { leaf, root, intermediate },
+ { intermediate, leaf, root }, { intermediate, root, leaf },
+ { root, leaf, intermediate }, { root, intermediate, leaf }
+ };
+ for (X509Certificate[] order : orders) {
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root }, build(order));
+ }
+ }
+
+ @Test
+ public void testDuplicatesAndUnrelatedCertificates() throws Exception {
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ build(otherRoot, root, leaf, root, intermediate, leaf, intermediate));
+ }
+
+ @Test
+ public void testSeparateCaBundleMayContainDuplicateLeafAnywhere() throws Exception {
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ CertTool.buildCertificateChain(leafKey.getPublic(), List.of(leaf),
+ List.of(root, leaf, intermediate, leaf)));
+ }
+
+ @Test
+ public void testDirectlyIssuedLeaf() throws Exception {
+ X509Certificate direct = certificate("Leaf", leafKey, "Root", rootKey, false, false);
+ assertArrayEquals(new X509Certificate[] { direct, root }, build(root, direct));
+ }
+
+ @Test
+ public void testEmptyOrMismatchedIdentityBundle() {
+ assertRejected();
+ assertRejected(root, intermediate);
+ assertThrows(GeneralSecurityException.class, () -> CertTool.buildCertificateChain(
+ leafKey.getPublic(), List.of(root), List.of(leaf, intermediate)));
+ }
+
+ @Test
+ public void testAmbiguousIdentityCertificates() throws Exception {
+ X509Certificate renewed =
+ certificate("Leaf", leafKey, "Intermediate", intermediateKey, false, false);
+ assertRejected(root, intermediate, leaf, renewed);
+ }
+
+ @Test
+ public void testExplicitIdentityDisambiguatesCaBundle() throws Exception {
+ X509Certificate renewed =
+ certificate("Leaf", leafKey, "Intermediate", intermediateKey, false, false);
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ CertTool.buildCertificateChain(leafKey.getPublic(), List.of(leaf),
+ List.of(root, renewed, intermediate)));
+ }
+
+ @Test
+ public void testMissingRootOrIntermediate() {
+ assertRejected(leaf);
+ assertRejected(leaf, intermediate);
+ assertRejected(leaf, root);
+ }
+
+ @Test
+ public void testUnrelatedRootDoesNotValidateLeaf() throws Exception {
+ X509Certificate direct = certificate("Leaf", leafKey, "Root", rootKey, false, false);
+ assertRejected(direct, otherRoot);
+ }
+
+ @Test
+ public void testExpiredLeaf() throws Exception {
+ assertRejected(certificate("Leaf", leafKey, "Root", rootKey, false, true), root);
+ }
+
+ @Test
+ public void testForgedLeafSignatureWithMatchingIssuerName() throws Exception {
+ assertRejected(certificate("Leaf", leafKey, "Root", otherKey, false, false), root);
+ assertRejected(certificate("Leaf", leafKey, "Intermediate", otherKey, false, false),
+ intermediate, root);
+ }
+
+ @Test
+ public void testExpiredIntermediate() throws Exception {
+ assertRejected(leaf,
+ certificate("Intermediate", intermediateKey, "Root", rootKey, true, true), root);
+ }
+
+ @Test
+ public void testNonCaIntermediate() throws Exception {
+ assertRejected(leaf,
+ certificate("Intermediate", intermediateKey, "Root", rootKey, false, false), root);
+ }
+
+ @Test
+ public void testExpiredRoot() throws Exception {
+ assertRejected(leaf, intermediate,
+ certificate("Root", rootKey, "Root", rootKey, true, true));
+ }
+
+ @Test
+ public void testSelfIssuedRootWithoutValidSelfSignature() throws Exception {
+ assertRejected(leaf, intermediate,
+ certificate("Root", rootKey, "Root", otherKey, true, false));
+ }
+
+ @Test
+ public void testNonCaRoot() throws Exception {
+ assertRejected(leaf, intermediate,
+ certificate("Root", rootKey, "Root", rootKey, false, false));
+ }
+
+ @Test
+ public void testIdentityCannotBeItsOwnAnchor() throws Exception {
+ assertRejected(certificate("Leaf", leafKey, "Leaf", leafKey, false, false), root);
+ assertRejected(certificate("Leaf", leafKey, "Leaf", leafKey, true, false), root);
+ }
+
+ @Test
+ public void testIssuerCycleCannotReachUnrelatedRoot() throws Exception {
+ X509Certificate cycleA =
+ certificate("Intermediate", intermediateKey, "Cycle", otherKey, true, false);
+ X509Certificate cycleB =
+ certificate("Cycle", otherKey, "Intermediate", intermediateKey, true, false);
+ assertRejected(leaf, cycleA, cycleB, root);
+ }
+
+ @Test
+ public void testAlternateCrossSignedIssuerPaths() throws Exception {
+ X509Certificate crossSigned =
+ certificate("Intermediate", intermediateKey, "Other", otherKey, true, false);
+ // The original issuer's root is absent, but the cross-signed path is complete.
+ assertArrayEquals(new X509Certificate[] { leaf, crossSigned, otherRoot },
+ build(intermediate, leaf, otherRoot, crossSigned));
+ // With both roots present, either validated path is acceptable.
+ X509Certificate[] chain = build(intermediate, root, leaf, otherRoot, crossSigned);
+ assertEquals(leaf, chain[0]);
+ assertEquals(3, chain.length);
+ assertTrue(Arrays.equals(chain, new X509Certificate[] { leaf, intermediate, root }) ||
+ Arrays.equals(chain, new X509Certificate[] { leaf, crossSigned, otherRoot }));
+ }
+
+ @Test
+ public void testCaKeyUsageMustPermitCertificateSigning() throws Exception {
+ assertRejected(leaf, intermediate, certificate("Root", rootKey, "Root", rootKey,
+ new BasicConstraints(true), KeyUsage.digitalSignature, false));
+ assertRejected(leaf, root, certificate("Intermediate", intermediateKey, "Root", rootKey,
+ new BasicConstraints(true), KeyUsage.digitalSignature, false));
+ }
+
+ @Test
+ public void testIntermediatePathLengthConstraint() throws Exception {
+ X509Certificate restricted = certificate("Intermediate", intermediateKey, "Root", rootKey,
+ new BasicConstraints(0), KeyUsage.keyCertSign, false);
+ X509Certificate subordinate =
+ certificate("Subordinate", otherKey, "Intermediate", intermediateKey, true, false);
+ X509Certificate endEntity =
+ certificate("Leaf", leafKey, "Subordinate", otherKey, false, false);
+ assertRejected(endEntity, subordinate, restricted, root);
+ }
+
+ @Test
+ public void testPemBundleImport() throws Exception {
+ File file = temporaryFolder.newFile("bundle.pem");
+ StringBuilder pem = new StringBuilder();
+ for (X509Certificate cert : List.of(root, leaf, intermediate, leaf)) {
+ pem.append("-----BEGIN CERTIFICATE-----\n");
+ pem.append(Base64.getMimeEncoder().encodeToString(cert.getEncoded()));
+ pem.append("\n-----END CERTIFICATE-----\n");
+ }
+ Files.writeString(file.toPath(), pem);
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ build(CertTool.loadCertificates(file.getPath())));
+ }
+
+ @Test
+ public void testPkcs7BundleImport() throws Exception {
+ File file = temporaryFolder.newFile("bundle.p7b");
+ CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
+ generator.addCertificates(new JcaCertStore(List.of(root, leaf, intermediate)));
+ Files.write(file.toPath(), generator.generate(new CMSAbsentContent()).getEncoded());
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ build(CertTool.loadCertificates(file.getPath())));
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ build(CertTool.loadPkcs7Certificates(file.getPath())));
+ }
+
+ @Test
+ public void testNormalizedChainCanBeStoredAndRecovered() throws Exception {
+ KeyStore store = KeyStore.getInstance("PKCS12");
+ store.load(null, null);
+ char[] password = "test-password".toCharArray();
+ store.setKeyEntry("identity", leafKey.getPrivate(), password,
+ build(root, leaf, intermediate));
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ store.store(bytes, password);
+ KeyStore recovered = KeyStore.getInstance("PKCS12");
+ recovered.load(new ByteArrayInputStream(bytes.toByteArray()), password);
+ assertArrayEquals(new X509Certificate[] { leaf, intermediate, root },
+ recovered.getCertificateChain("identity"));
+ assertEquals(leafKey.getPrivate(), recovered.getKey("identity", password));
+ }
+}