diff --git a/src/hotspot/share/classfile/classFileParser.cpp b/src/hotspot/share/classfile/classFileParser.cpp index 20de43ad835d..31cb81ca2384 100644 --- a/src/hotspot/share/classfile/classFileParser.cpp +++ b/src/hotspot/share/classfile/classFileParser.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -3350,8 +3350,7 @@ u2 ClassFileParser::parse_classfile_record_attribute(const ClassFileStream* cons CHECK_0); RecordComponent* record_component = - RecordComponent::allocate(_loader_data, name_index, descriptor_index, - attributes_count, generic_sig_index, + RecordComponent::allocate(_loader_data, name_index, descriptor_index, generic_sig_index, annotations, type_annotations, CHECK_0); record_components->at_put(x, record_component); } // End of component processing loop diff --git a/src/hotspot/share/oops/recordComponent.cpp b/src/hotspot/share/oops/recordComponent.cpp index 5d4d072a7e00..5007bebfb9b5 100644 --- a/src/hotspot/share/oops/recordComponent.cpp +++ b/src/hotspot/share/oops/recordComponent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,12 +33,11 @@ RecordComponent* RecordComponent::allocate(ClassLoaderData* loader_data, u2 name_index, u2 descriptor_index, - u2 attributes_count, u2 generic_signature_index, AnnotationArray* annotations, AnnotationArray* type_annotations, TRAPS) { return new (loader_data, size(), MetaspaceObj::RecordComponentType, THREAD) - RecordComponent(name_index, descriptor_index, attributes_count, + RecordComponent(name_index, descriptor_index, generic_signature_index, annotations, type_annotations); } @@ -65,7 +64,6 @@ void RecordComponent::print_value_on(outputStream* st) const { void RecordComponent::print_on(outputStream* st) const { st->print("name_index: %d", _name_index); st->print(" - descriptor_index: %d", _descriptor_index); - st->print(" - attributes_count: %d", _attributes_count); if (_generic_signature_index != 0) { st->print(" - generic_signature_index: %d", _generic_signature_index); } diff --git a/src/hotspot/share/oops/recordComponent.hpp b/src/hotspot/share/oops/recordComponent.hpp index fa5e4ff20639..f9f4cdb5ee46 100644 --- a/src/hotspot/share/oops/recordComponent.hpp +++ b/src/hotspot/share/oops/recordComponent.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -36,25 +36,21 @@ class RecordComponent: public MetaspaceObj { AnnotationArray* _type_annotations; u2 _name_index; u2 _descriptor_index; - u2 _attributes_count; // generic_signature_index gets set if the Record component has a Signature // attribute. A zero value indicates that there was no Signature attribute. u2 _generic_signature_index; public: - RecordComponent(u2 name_index, u2 descriptor_index, u2 attributes_count, - u2 generic_signature_index, AnnotationArray* annotations, - AnnotationArray* type_annotations): + RecordComponent(u2 name_index, u2 descriptor_index, u2 generic_signature_index, + AnnotationArray* annotations, AnnotationArray* type_annotations): _annotations(annotations), _type_annotations(type_annotations), _name_index(name_index), _descriptor_index(descriptor_index), - _attributes_count(attributes_count), _generic_signature_index(generic_signature_index) { } // Allocate instance of this class static RecordComponent* allocate(ClassLoaderData* loader_data, u2 name_index, u2 descriptor_index, - u2 attributes_count, u2 generic_signature_index, AnnotationArray* annotations, AnnotationArray* type_annotations, TRAPS); @@ -69,8 +65,6 @@ class RecordComponent: public MetaspaceObj { _descriptor_index = descriptor_index; } - u2 attributes_count() const { return _attributes_count; } - u2 generic_signature_index() const { return _generic_signature_index; } void set_generic_signature_index(u2 generic_signature_index) { _generic_signature_index = generic_signature_index; diff --git a/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp b/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp index ccebb272fa50..523fc30e0064 100644 --- a/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp +++ b/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp @@ -492,7 +492,6 @@ void JvmtiClassFileReconstituter::write_record_attribute() { RecordComponent* component = components->at(x); if (component->generic_signature_index() != 0) { length += 8; // Signature attribute size - assert(component->attributes_count() > 0, "Bad component attributes count"); } if (component->annotations() != nullptr) { length += 6 + component->annotations()->length(); @@ -509,7 +508,11 @@ void JvmtiClassFileReconstituter::write_record_attribute() { RecordComponent* component = components->at(i); write_u2(component->name_index()); write_u2(component->descriptor_index()); - write_u2(component->attributes_count()); + u2 attributes_count = (component->generic_signature_index() != 0 ? 1 : 0) + + (component->annotations() != nullptr ? 1 : 0) + + (component->type_annotations() != nullptr ? 1 : 0); + + write_u2(attributes_count); if (component->generic_signature_index() != 0) { write_signature_attribute(component->generic_signature_index()); } diff --git a/src/java.base/share/classes/sun/security/pkcs/PKCS7.java b/src/java.base/share/classes/sun/security/pkcs/PKCS7.java index 5f05af1c07e7..015bc72e9509 100644 --- a/src/java.base/share/classes/sun/security/pkcs/PKCS7.java +++ b/src/java.base/share/classes/sun/security/pkcs/PKCS7.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -530,8 +530,23 @@ public void encodeSignedData(DerOutputStream out) * @exception SignatureException on signature handling errors. */ public SignerInfo verify(SignerInfo info, byte[] bytes) - throws NoSuchAlgorithmException, SignatureException { - return info.verify(this, bytes); + throws NoSuchAlgorithmException, SignatureException { + return info.verify(this, bytes, null); + } + + /** + * This verifies a given SignerInfo. + * + * @param info the signer information. + * @param bytes the DER encoded content information. + * @param cert certificate used to verify; find one inside the block if null + * + * @exception NoSuchAlgorithmException on unrecognized algorithms. + * @exception SignatureException on signature handling errors. + */ + public SignerInfo verify(SignerInfo info, byte[] bytes, X509Certificate cert) + throws NoSuchAlgorithmException, SignatureException { + return info.verify(this, bytes, cert); } /** @@ -726,6 +741,19 @@ public boolean isOldStyle() { return this.oldStyle; } + // Generate signed data without a specified digAlgID. + public static byte[] generateNewSignedData( + String sigalg, Provider sigProvider, + PrivateKey privateKey, X509Certificate[] signerChain, + byte[] content, boolean internalsf, boolean directsign, + Function ts) + throws SignatureException, InvalidKeyException, IOException, + NoSuchAlgorithmException { + return generateSignedData(sigalg, sigProvider, privateKey, signerChain, + content, internalsf, directsign, + null, ts); + } + /** * Generate a PKCS7 data block. * @@ -736,6 +764,7 @@ public boolean isOldStyle() { * @param content the content to sign * @param internalsf whether the content should be included in output * @param directsign if the content is signed directly or through authattrs + * @param digAlgID digest alg to use; derive from other arguments if null * @param ts (optional) timestamper * @return the pkcs7 output in an array * @throws SignatureException if signing failed @@ -743,18 +772,21 @@ public boolean isOldStyle() { * @throws IOException should not happen here, all byte array * @throws NoSuchAlgorithmException if siglag is bad */ - public static byte[] generateNewSignedData( + public static byte[] generateSignedData( String sigalg, Provider sigProvider, PrivateKey privateKey, X509Certificate[] signerChain, byte[] content, boolean internalsf, boolean directsign, + AlgorithmId digAlgID, Function ts) throws SignatureException, InvalidKeyException, IOException, NoSuchAlgorithmException { Signature signer = SignatureUtil.fromKey(sigalg, privateKey, sigProvider); - AlgorithmId digAlgID = SignatureUtil.getDigestAlgInPkcs7SignerInfo( - signer, sigalg, privateKey, directsign); + if (digAlgID == null) { + digAlgID = SignatureUtil.getDigestAlgInPkcs7SignerInfo( + signer, sigalg, privateKey, directsign); + } AlgorithmId sigAlgID = SignatureUtil.fromSignature(signer, privateKey); PKCS9Attributes authAttrs = null; @@ -762,8 +794,9 @@ public static byte[] generateNewSignedData( // MessageDigest byte[] md; String digAlgName = digAlgID.getName(); - if (digAlgName.equals("SHAKE256") || digAlgName.equals("SHAKE256-LEN")) { - // No MessageDigest impl for SHAKE256 yet + if (digAlgName.equals("SHAKE256-LEN")) { + // We don't check the LEN here. Usually it is returned + // by SignatureUtil.getDigestAlgInPkcs7SignerInfo var shaker = new SHAKE256(64); shaker.update(content, 0, content.length); md = shaker.digest(); diff --git a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java index 6151069ea9a5..a386d285239b 100644 --- a/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java +++ b/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java @@ -303,15 +303,20 @@ public ArrayList getCertificateChain(PKCS7 block) return certList; } - /* Returns null if verify fails, this signerInfo if - verify succeeds. */ - SignerInfo verify(PKCS7 block, byte[] data) - throws NoSuchAlgorithmException, SignatureException { + /** + * Verify this signerInfo in a PKCS7 block. + * + * @param block the PKCS7 object + * @param data the content to verify against; read from block if null + * @param cert certificate to verify with; read from block if null + * @return null if verify fails, this signerInfo if verify succeeds. + */ + SignerInfo verify(PKCS7 block, byte[] data, X509Certificate cert) + throws NoSuchAlgorithmException, SignatureException { try { - Timestamp timestamp = null; try { - timestamp = getTimestamp(); + getTimestamp(); } catch (Exception e) { // Log exception and continue. This allows for the case // where, if there are no other errors, the code is @@ -371,22 +376,19 @@ SignerInfo verify(PKCS7 block, byte[] data) return null; byte[] computedMessageDigest; - if (digestAlgName.equals("SHAKE256") - || digestAlgName.equals("SHAKE256-LEN")) { - if (digestAlgName.equals("SHAKE256-LEN")) { - // RFC8419: for EdDSA in CMS, the id-shake256-len - // algorithm id must contain parameter value 512 - // encoded as a positive integer value - byte[] params = digestAlgorithmId.getEncodedParams(); - if (params == null) { - throw new SignatureException( - "id-shake256-len oid missing length"); - } - int v = new DerValue(params).getInteger(); - if (v != 512) { - throw new SignatureException( - "Unsupported id-shake256-" + v); - } + if (digestAlgName.equals("SHAKE256-LEN")) { + // RFC8419: for EdDSA in CMS, the id-shake256-len + // algorithm id must contain parameter value 512 + // encoded as a positive integer value + byte[] params = digestAlgorithmId.getEncodedParams(); + if (params == null) { + throw new SignatureException( + "id-shake256-len oid missing length"); + } + int v = new DerValue(params).getInteger(); + if (v != 512) { + throw new SignatureException( + "Unsupported id-shake256-" + v); } var md = new SHAKE256(64); md.update(data, 0, data.length); @@ -426,9 +428,11 @@ SignerInfo verify(PKCS7 block, byte[] data) "SignerInfo digestEncryptionAlgorithm field", true)); } - X509Certificate cert = getCertificate(block); if (cert == null) { - return null; + cert = getCertificate(block); + if (cert == null) { + return null; + } } PublicKey key = cert.getPublicKey(); @@ -492,9 +496,9 @@ SignerInfo verify(PKCS7 block, byte[] data) * The digest algorithm is in the form "DIG", and the encryption * algorithm can be in any of the 3 forms: * - * 1. Old style key algorithm like RSA, DSA, EC, this method returns + * 1. Simple key algorithm like RSA, DSA, EC, this method returns * DIGwithKEY. - * 2. New style signature algorithm in the form of HASHwithKEY, this + * 2. Traditional signature algorithm in the form of HASHwithKEY, this * method returns DIGwithKEY. Please note this is not HASHwithKEY. * 3. Modern signature algorithm like RSASSA-PSS and EdDSA, this method * returns the signature algorithm itself but ensures digAlgId is @@ -522,53 +526,77 @@ public static String makeSigAlg(AlgorithmId digAlgId, AlgorithmId encAlgId, } if (!AlgorithmId.get(spec.getDigestAlgorithm()).equals(digAlgId)) { - throw new NoSuchAlgorithmException("Incompatible digest algorithm"); + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); } return encAlg; case "Ed25519": - if (!digAlgId.equals(SignatureUtil.EdDSADigestAlgHolder.sha512)) { - throw new NoSuchAlgorithmException("Incompatible digest algorithm"); + if (!digAlgId.equalsOID(AlgorithmId.SHA512_oid)) { + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); } return encAlg; case "Ed448": if (directSign) { - if (!digAlgId.equals(SignatureUtil.EdDSADigestAlgHolder.shake256)) { - throw new NoSuchAlgorithmException("Incompatible digest algorithm"); + if (!digAlgId.equalsOID(AlgorithmId.SHAKE256_512_oid)) { + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); } } else { - if (!digAlgId.equals(SignatureUtil.EdDSADigestAlgHolder.shake256$512)) { - throw new NoSuchAlgorithmException("Incompatible digest algorithm"); + if (!digAlgId.equals(SignatureUtil.DigestAlgHolder.shake256lenWith512)) { + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); } } return encAlg; + case "ML-DSA-44": + // Following 3 from Table 1 inside + // https://datatracker.ietf.org/doc/html/rfc9882#name-signerinfo-content + if (!digAlgId.equalsOID(AlgorithmId.SHA256_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA384_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA512_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA3_256_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA3_384_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA3_512_oid) + && !digAlgId.equalsOID(AlgorithmId.SHAKE128_256_oid) + && !digAlgId.equalsOID(AlgorithmId.SHAKE256_512_oid)) { + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); + } + return encAlg; + case "ML-DSA-65": + if (!digAlgId.equalsOID(AlgorithmId.SHA384_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA512_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA3_384_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA3_512_oid) + && !digAlgId.equalsOID(AlgorithmId.SHAKE256_512_oid)) { + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); + } + return encAlg; + case "ML-DSA-87": + if (!digAlgId.equalsOID(AlgorithmId.SHA512_oid) + && !digAlgId.equalsOID(AlgorithmId.SHA3_512_oid) + && !digAlgId.equalsOID(AlgorithmId.SHAKE256_512_oid)) { + throw new NoSuchAlgorithmException("Incompatible digest algorithm " + digAlgId); + } + return encAlg; default: - String digAlg = digAlgId.getName(); String keyAlg = SignatureUtil.extractKeyAlgFromDwithE(encAlg); - if (keyAlg == null) { - // The encAlg used to be only the key alg - keyAlg = encAlg; + if (keyAlg == null) { // No "WITH" inside + if (encAlg.equals("RSA") || encAlg.equals("DSA") || encAlg.equals("EC")) { + keyAlg = encAlg; // Sometimes encAlgId is just the enc alg + } else { + return encAlg; // Must be a modern algorithm like EdDSA or ML-DSA + } } + String digAlg = digAlgId.getName(); if (digAlg.startsWith("SHA-")) { digAlg = "SHA" + digAlg.substring(4); } if (keyAlg.equals("EC")) keyAlg = "ECDSA"; - String sigAlg = digAlg + "with" + keyAlg; - try { - Signature.getInstance(sigAlg); - return sigAlg; - } catch (NoSuchAlgorithmException e) { - // Possibly an unknown modern signature algorithm, - // in this case, encAlg should already be a signature - // algorithm. - return encAlg; - } + return digAlg + "with" + keyAlg; } } /* Verify the content of the pkcs7 block. */ SignerInfo verify(PKCS7 block) throws NoSuchAlgorithmException, SignatureException { - return verify(block, null); + return verify(block, null, null); } public BigInteger getVersion() { diff --git a/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java b/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java index 62776f0be1f4..31922ca6baf2 100644 --- a/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java +++ b/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java @@ -189,21 +189,20 @@ public static boolean isBlockOrSF(String s) { /** * Returns the signed JAR block file extension for a key. * + * Returns "DSA" for unknown algorithms. This is safe because the + * signature verification process does not require the extension to + * match the key algorithm as long as it is "RSA", "DSA", or "EC." + * * @param key the key used to sign the JAR file * @return the extension * @see #isBlockOrSF(String) */ public static String getBlockExtension(PrivateKey key) { - String keyAlgorithm = key.getAlgorithm().toUpperCase(Locale.ENGLISH); - if (keyAlgorithm.equals("RSASSA-PSS")) { - return "RSA"; - } else if (keyAlgorithm.equals("EDDSA") - || keyAlgorithm.equals("ED25519") - || keyAlgorithm.equals("ED448")) { - return "EC"; - } else { - return keyAlgorithm; - } + return switch (key.getAlgorithm().toUpperCase(Locale.ENGLISH)) { + case "RSA", "RSASSA-PSS" -> "RSA"; + case "EC", "EDDSA", "ED25519", "ED448" -> "EC"; + default -> "DSA"; + }; } /** diff --git a/src/java.base/share/classes/sun/security/util/SignatureUtil.java b/src/java.base/share/classes/sun/security/util/SignatureUtil.java index 73fe6a167062..31d1b8f6209b 100644 --- a/src/java.base/share/classes/sun/security/util/SignatureUtil.java +++ b/src/java.base/share/classes/sun/security/util/SignatureUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -191,16 +191,16 @@ public static void initSignWithParam(Signature s, PrivateKey key, SharedSecrets.getJavaSecuritySignatureAccess().initSign(s, key, params, sr); } - public static class EdDSADigestAlgHolder { + public static class DigestAlgHolder { public static final AlgorithmId sha512; - public static final AlgorithmId shake256; - public static final AlgorithmId shake256$512; + public static final AlgorithmId shake256_512; + public static final AlgorithmId shake256lenWith512; static { try { - sha512 = new AlgorithmId(ObjectIdentifier.of(KnownOIDs.SHA_512)); - shake256 = new AlgorithmId(ObjectIdentifier.of(KnownOIDs.SHAKE256_512)); - shake256$512 = new AlgorithmId( + sha512 = new AlgorithmId(AlgorithmId.SHA512_oid); + shake256_512 = new AlgorithmId(AlgorithmId.SHAKE256_512_oid); + shake256lenWith512 = new AlgorithmId( ObjectIdentifier.of(KnownOIDs.SHAKE256_LEN), new DerValue((byte) 2, new byte[]{2, 0})); // int 512 } catch (IOException e) { @@ -233,18 +233,22 @@ public static AlgorithmId getDigestAlgInPkcs7SignerInfo( // https://www.rfc-editor.org/rfc/rfc8419.html#section-3 switch (kAlg.toUpperCase(Locale.ENGLISH)) { case "ED25519": - digAlgID = EdDSADigestAlgHolder.sha512; + digAlgID = DigestAlgHolder.sha512; break; case "ED448": if (directsign) { - digAlgID = EdDSADigestAlgHolder.shake256; + digAlgID = DigestAlgHolder.shake256_512; } else { - digAlgID = EdDSADigestAlgHolder.shake256$512; + digAlgID = DigestAlgHolder.shake256lenWith512; } break; default: throw new AssertionError("Unknown curve name: " + kAlg); } + } else if (kAlg.toUpperCase(Locale.ENGLISH).startsWith("ML-DSA")) { + // https://datatracker.ietf.org/doc/html/rfc9882#name-signerinfo-content + // Just use SHA-512 + digAlgID = DigestAlgHolder.sha512; } else { if (sigalg.equalsIgnoreCase("RSASSA-PSS")) { try { @@ -494,14 +498,17 @@ public static void checkKeyAndSigAlgMatch(PrivateKey key, String sAlg) { public static String getDefaultSigAlgForKey(PrivateKey k) { String kAlg = k.getAlgorithm().toUpperCase(Locale.ENGLISH); return switch (kAlg) { + case "DH", "XDH", "X25519", "X448" -> null; case "DSA" -> "SHA256withDSA"; case "RSA" -> ifcFfcStrength(KeyUtil.getKeySize(k)) + "withRSA"; case "EC" -> ecStrength(KeyUtil.getKeySize(k)) + "withECDSA"; case "EDDSA" -> k instanceof EdECPrivateKey ? ((EdECPrivateKey) k).getParams().getName() : kAlg; - case "RSASSA-PSS", "ED25519", "ED448" -> kAlg; - default -> null; + default -> kAlg.contains("KEM") ? null : kAlg; + // All modern signature algorithms use the same name across + // key algorithms and signature algorithms, for example, + // RSASSA-PSS, ED25519, ED448, HSS/LMS, etc }; } diff --git a/src/java.base/share/classes/sun/security/validator/EntrustTLSPolicy.java b/src/java.base/share/classes/sun/security/validator/EntrustTLSPolicy.java index efb84ac8bc99..ae1bcb8be9f3 100644 --- a/src/java.base/share/classes/sun/security/validator/EntrustTLSPolicy.java +++ b/src/java.base/share/classes/sun/security/validator/EntrustTLSPolicy.java @@ -40,12 +40,6 @@ final class EntrustTLSPolicy { // SHA-256 certificate fingerprints of distrusted roots private static final Set FINGERPRINTS = Set.of( - // cacerts alias: entrustevca - // DN: CN=Entrust Root Certification Authority, - // OU=(c) 2006 Entrust, Inc., - // OU=www.entrust.net/CPS is incorporated by reference, - // O=Entrust, Inc., C=US - "73C176434F1BC6D5ADF45B0E76E727287C8DE57616C1E6E6141A2B2CBC7D8E4C", // cacerts alias: entrustrootcaec1 // DN: CN=Entrust Root Certification Authority - EC1, // OU=(c) 2012 Entrust, Inc. - for authorized use only, diff --git a/src/java.base/share/classes/sun/security/x509/AlgorithmId.java b/src/java.base/share/classes/sun/security/x509/AlgorithmId.java index 9fd03e76bdb1..4115443c2625 100644 --- a/src/java.base/share/classes/sun/security/x509/AlgorithmId.java +++ b/src/java.base/share/classes/sun/security/x509/AlgorithmId.java @@ -306,6 +306,14 @@ public boolean equals(AlgorithmId other) { Arrays.equals(encodedParams, other.encodedParams); } + /** + * Returns true if this AlgorithmID only has the specified ObjectIdentifier + * and a NULL params. Note the encoded params might be ASN.1 NULL or absent. + */ + public boolean equalsOID(ObjectIdentifier oid) { + return algid.equals(oid) && encodedParams == null; + } + /** * Compares this AlgorithmID to another. If algorithm parameters are * available, they are compared. Otherwise, just the object IDs @@ -629,6 +637,12 @@ private static ConcurrentHashMap collectOIDAliases() { public static final ObjectIdentifier SHA3_512_oid = ObjectIdentifier.of(KnownOIDs.SHA3_512); + public static final ObjectIdentifier SHAKE128_256_oid = + ObjectIdentifier.of(KnownOIDs.SHAKE128_256); + + public static final ObjectIdentifier SHAKE256_512_oid = + ObjectIdentifier.of(KnownOIDs.SHAKE256_512); + public static final ObjectIdentifier DSA_oid = ObjectIdentifier.of(KnownOIDs.DSA); diff --git a/src/java.base/share/data/cacerts/entrustevca b/src/java.base/share/data/cacerts/entrustevca deleted file mode 100644 index 6c2c50968b96..000000000000 --- a/src/java.base/share/data/cacerts/entrustevca +++ /dev/null @@ -1,34 +0,0 @@ -Owner: CN=Entrust Root Certification Authority, OU="(c) 2006 Entrust, Inc.", OU=www.entrust.net/CPS is incorporated by reference, O="Entrust, Inc.", C=US -Issuer: CN=Entrust Root Certification Authority, OU="(c) 2006 Entrust, Inc.", OU=www.entrust.net/CPS is incorporated by reference, O="Entrust, Inc.", C=US -Serial number: 456b5054 -Valid from: Mon Nov 27 20:23:42 GMT 2006 until: Fri Nov 27 20:53:42 GMT 2026 -Signature algorithm name: SHA1withRSA -Subject Public Key Algorithm: 2048-bit RSA key -Version: 3 ------BEGIN CERTIFICATE----- -MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC -VVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0 -Lm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW -KGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl -cnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw -NTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw -NwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy -ZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV -BAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ -KoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo -Nu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4 -4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9 -KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI -rb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi -94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB -sDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi -gA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo -kORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE -vW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA -A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t -O1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua -AGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP -9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/ -eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m -0vdXcDazv/wor3ElhVsT/h5/WrQ8 ------END CERTIFICATE----- diff --git a/src/jdk.jartool/share/man/jarsigner.1 b/src/jdk.jartool/share/man/jarsigner.1 index 2e70778f8550..8a8bff491a71 100644 --- a/src/jdk.jartool/share/man/jarsigner.1 +++ b/src/jdk.jartool/share/man/jarsigner.1 @@ -374,7 +374,7 @@ SHA512withECDSA T}@T{ T} T{ -RSASSA-PSS +RSASSA-PSS[1] T}@T{ < 624 T}@T{ @@ -397,23 +397,24 @@ RSASSA-PSS (with SHA-512) T}@T{ T} T{ -EdDSA +EdDSA[2] T}@T{ -255 T}@T{ -Ed25519 +EdDSA T}@T{ \&.EC T} T{ +ML-DSA[2] T}@T{ -448 T}@T{ -Ed448 +ML-DSA T}@T{ +\&.DSA T} .TE -.IP \[bu] 2 +.PP +1. If an RSASSA-PSS key is encoded with parameters, then jarsigner will use the same parameters in the signature. Otherwise, jarsigner will use parameters that are determined by the size @@ -421,6 +422,17 @@ of the key as specified in the table above. For example, an 3072-bit RSASSA-PSS key will use RSASSA-PSS as the signature algorithm and SHA-384 as the hash and MGF1 algorithms. .PP +2. +Modern digital signature algorithms such as EdDSA and ML-DSA use the same +name for both the key and signature algorithms. +Only the signature algorithm with the same name can be used with a given +key algorithm. +The specific signature parameter set (for example, Ed25519 or Ed448 for +EdDSA) is the same as that of the key. +.PP +If a key algorithm is not listed in this table, the \f[V].DSA\f[R] block +file extension is always used. +.PP These default signature algorithms can be overridden by using the \f[V]-sigalg\f[R] option. .PP diff --git a/test/jdk/java/lang/instrument/RetransformRecordAnnotation.java b/test/jdk/java/lang/instrument/RetransformRecordAnnotation.java new file mode 100644 index 000000000000..522a26092907 --- /dev/null +++ b/test/jdk/java/lang/instrument/RetransformRecordAnnotation.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8315575 + * @summary test that records with invisible annotation can be retransformed + * + * @library /test/lib + * @run shell MakeJAR.sh retransformAgent + * @run main/othervm -javaagent:retransformAgent.jar -Xlog:redefine+class=trace RetransformRecordAnnotation + */ + +import java.io.File; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.instrument.ClassFileTransformer; +import java.nio.file.Files; +import java.security.ProtectionDomain; + +public class RetransformRecordAnnotation extends AInstrumentationTestCase { + + @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) + @Retention(RetentionPolicy.RUNTIME) + @interface RuntimeTypeAnno {} + + @Retention(RetentionPolicy.RUNTIME) + @interface RuntimeParamAnno { + String s() default "foo"; + } + + @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) + @Retention(RetentionPolicy.CLASS) + @interface ClassTypeAnno {} + + @Retention(RetentionPolicy.CLASS) + @interface ClassParamAnno { + String s() default "bar"; + } + + @RuntimeTypeAnno + @RuntimeParamAnno(s = "1") + public record VisibleAnnos(@RuntimeTypeAnno @RuntimeParamAnno(s = "2") Object o, Object other) { + } + + @ClassTypeAnno + @ClassParamAnno(s = "3") + public record InvisibleAnnos(@ClassTypeAnno @ClassParamAnno(s = "4") Object o, Object other) { + } + + @RuntimeTypeAnno + @RuntimeParamAnno(s = "5") + @ClassTypeAnno + @ClassParamAnno(s = "6") + public record MixedAnnos(@RuntimeTypeAnno @RuntimeParamAnno(s = "7") + @ClassTypeAnno @ClassParamAnno(s = "8") Object o, Object other) { + } + + public static void main (String[] args) throws Throwable { + ATestCaseScaffold test = new RetransformRecordAnnotation(); + test.beVerbose(); + test.runTest(); + } + + private Transformer transformer; + + public RetransformRecordAnnotation() throws Throwable { + super("RetransformRecordAnnotation"); + } + + private void log(Object o) { + System.out.println(String.valueOf(o)); + } + + // Retransforms target class using provided class bytes; + private void retransform(Class targetClass, byte[] classBytes) throws Throwable { + transformer.prepare(targetClass, classBytes); + fInst.retransformClasses(targetClass); + assertTrue(targetClass.getName() + " was not seen by transform()", + transformer.getSeenClassBytes() != null); + } + + protected final void doRunTest() throws Throwable { + transformer = new Transformer(); + fInst.addTransformer(transformer, true); + + { + log("Sanity: retransform to original class bytes"); + retransform(InvisibleAnnos.class, loadClassBytes(InvisibleAnnos.class)); + log(""); + } + + // The following testcases use null as new class bytes (i.e. no transform is performed). + // However, it is enough for testing purposes as the JvmtiClassFileReconstituter is still involved + // in preparation of the initial class bytes. + { + log("Test: retransform VisibleAnnos to null"); + retransform(VisibleAnnos.class, null); + log(""); + } + + { + log("Test: retransform InvisibleAnnos to null"); + retransform(InvisibleAnnos.class, null); + log(""); + } + + { + log("Test: retransform MixedAnnos to null"); + retransform(MixedAnnos.class, null); + log(""); + } + } + + private byte[] loadClassBytes(Class cls) throws Exception { + String classFileName = cls.getName() + ".class"; + File classFile = new File(System.getProperty("test.classes", "."), classFileName); + log("Reading test class from " + classFile); + byte[] classBytes = Files.readAllBytes(classFile.toPath()); + log("Read " + classBytes.length + " bytes."); + return classBytes; + } + + public class Transformer implements ClassFileTransformer { + private String targetClassName; + private byte[] seenClassBytes; + private byte[] newClassBytes; + + public Transformer() { + } + + // Prepares transformer for Instrumentation.retransformClasses. + public void prepare(Class targetClass, byte[] classBytes) { + targetClassName = targetClass.getName(); + newClassBytes = classBytes; + seenClassBytes = null; + } + + byte[] getSeenClassBytes() { + return seenClassBytes; + } + + public String toString() { + return Transformer.this.getClass().getName(); + } + + public byte[] transform(ClassLoader loader, String className, + Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) { + + if (className.equals(targetClassName)) { + log(this + ".transform() sees '" + className + + "' of " + classfileBuffer.length + " bytes."); + seenClassBytes = classfileBuffer; + if (newClassBytes != null) { + log(this + ".transform() sets new classbytes for '" + className + + "' of " + newClassBytes.length + " bytes."); + } + return newClassBytes; + } + + return null; + } + } +} diff --git a/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java b/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java index beb128d1f9d4..f27cfac425f3 100644 --- a/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java +++ b/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java @@ -29,7 +29,7 @@ * 8243559 8225072 8258630 8259312 8256421 8225081 8225082 8225083 8245654 * 8305975 8304760 8307134 8295894 8314960 8317373 8317374 8318759 8319187 * 8321408 8316138 8341057 8303770 8350498 8359170 8361212 8372351 8387123 - * 8386371 8392771 8395690 + * 8386371 8392771 8395690 8303772 * @summary Check root CA entries in cacerts file */ import java.io.ByteArrayInputStream; @@ -49,13 +49,13 @@ public class VerifyCACerts { // The numbers of certs now. // SapMachine 2021-09-23: Additional certificate for SAP - private static final int COUNT = 108; + private static final int COUNT = 107; // SHA-256 of cacerts, can be generated with // shasum -a 256 cacerts | sed -e 's/../&:/g' | tr '[:lower:]' '[:upper:]' | cut -c1-95 // SapMachine 2021-09-23: Additional certificate for SAP private static final String CHECKSUM - = "0F:BA:3F:6E:A4:03:73:53:98:EF:29:3B:16:E8:8D:79:DF:7D:1D:FC:E6:D7:77:D1:5C:E6:B6:06:55:6B:6C:A8"; + = "D2:0F:82:AA:2B:F0:CF:CB:08:81:1B:91:22:92:93:9C:07:2D:2E:53:64:44:11:3F:3E:7E:AF:7E:A0:47:A0:D4"; // Hex formatter to upper case with ":" delimiter private static final HexFormat HEX = HexFormat.ofDelimiter(":").withUpperCase(); @@ -192,8 +192,6 @@ public class VerifyCACerts { "6D:C4:71:72:E0:1C:BC:B0:BF:62:58:0D:89:5F:E2:B8:AC:9A:D4:F8:73:80:1E:0C:10:B9:C8:37:D2:1E:B1:77"); put("entrustrootcag2 [jdk]", "43:DF:57:74:B0:3E:7F:EF:5F:E4:0D:93:1A:7B:ED:F1:BB:2E:6B:42:73:8C:4E:6D:38:41:10:3D:3A:A7:F3:39"); - put("entrustevca [jdk]", - "73:C1:76:43:4F:1B:C6:D5:AD:F4:5B:0E:76:E7:27:28:7C:8D:E5:76:16:C1:E6:E6:14:1A:2B:2C:BC:7D:8E:4C"); put("ttelesecglobalrootclass3ca [jdk]", "FD:73:DA:D3:1C:64:4F:F1:B4:3B:EF:0C:CD:DA:96:71:0B:9C:D9:87:5E:CA:7E:31:70:7A:F3:E9:6D:52:2B:BD"); put("ttelesecglobalrootclass2ca [jdk]", diff --git a/test/jdk/sun/security/pkcs/pkcs7/MLDSADigestConformance.java b/test/jdk/sun/security/pkcs/pkcs7/MLDSADigestConformance.java new file mode 100644 index 000000000000..80aa0c96281b --- /dev/null +++ b/test/jdk/sun/security/pkcs/pkcs7/MLDSADigestConformance.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8349732 + * @summary ML-DSA digest alg conformance check + * @modules java.base/sun.security.pkcs + * java.base/sun.security.tools.keytool + * java.base/sun.security.x509 + * @library /test/lib + */ + +import jdk.test.lib.Asserts; +import sun.security.pkcs.PKCS7; +import sun.security.tools.keytool.CertAndKeyGen; +import sun.security.x509.AlgorithmId; +import sun.security.x509.X500Name; + +import java.nio.charset.StandardCharsets; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.Map; + +public class MLDSADigestConformance { + + static String[] ALL_KEY_ALGS = {"ML-DSA-44", "ML-DSA-65", "ML-DSA-87"}; + static String[] ALL_DIGEST_ALGS = { + "SHA-1", "SHA-224", "SHA-256", "SHA-384", "SHA-512", + "SHA3-224", "SHA3-256", "SHA3-384", "SHA3-512", + "SHAKE128-256", "SHAKE256-512"}; + static Map> SUPPORTED = Map.of( + "ML-DSA-44", List.of("SHA-256", "SHA-384", "SHA-512", + "SHA3-256", "SHA3-384", "SHA3-512", + "SHAKE128-256", "SHAKE256-512"), + "ML-DSA-65", List.of("SHA-384", "SHA-512", + "SHA3-384", "SHA3-512", "SHAKE256-512"), + "ML-DSA-87", List.of("SHA-512", "SHA3-512", "SHAKE256-512") + ); + + public static void main(String[] args) throws Exception { + testSig("ML-DSA-44"); + testSig("ML-DSA-65"); + testSig("ML-DSA-87"); + } + + static void testSig(String keyAlg) throws Exception { + System.out.println("Testing " + keyAlg); + var cag = new CertAndKeyGen(keyAlg, keyAlg); + cag.generate(keyAlg); + var sk = cag.getPrivateKey(); + var certs = new X509Certificate[] { + cag.getSelfCertificate(new X500Name("CN=Me"), 1000) + }; + var count = testDigest(keyAlg, sk, certs, null); + System.out.println(" digestAlg default: " + count); + Asserts.assertEQ(count, 1); + for (var da : ALL_DIGEST_ALGS) { + count = testDigest(keyAlg, sk, certs, da); + System.out.println(" digestAlg " + da + ": " + count); + if (SUPPORTED.get(keyAlg).contains(da)) { + Asserts.assertEQ(count, 1); + } else { + Asserts.assertEQ(count, 0); + } + } + } + + static int testDigest(String keyAlg, PrivateKey sk, + X509Certificate[] certs, String digestAlg) throws Exception { + var content = "hello".getBytes(StandardCharsets.UTF_8); + var p7 = PKCS7.generateSignedData(keyAlg, null, + sk, certs, + content, true, false, + digestAlg == null ? null : AlgorithmId.get(digestAlg), + null); + try { + return new PKCS7(p7).verify(null).length; + } catch (NoSuchAlgorithmException e) { + return 0; + } + } +} diff --git a/test/jdk/sun/security/provider/acvp/Launcher.java b/test/jdk/sun/security/provider/acvp/Launcher.java index 799f145bb26c..2ee0ff96bd1b 100644 --- a/test/jdk/sun/security/provider/acvp/Launcher.java +++ b/test/jdk/sun/security/provider/acvp/Launcher.java @@ -37,6 +37,8 @@ /* * @test * @bug 8342442 8345057 + * @summary Test default implementation. Use othervm because + * ML_DSA_Impls.version might be modified * @library /test/lib * @modules java.base/sun.security.provider * java.base/sun.security.util @@ -46,8 +48,8 @@ /* * @test - * @summary Test verifying the intrinsic implementation. * @bug 8342442 8345057 + * @summary Test verifying the intrinsic implementation. * @library /test/lib * @modules java.base/sun.security.provider * java.base/sun.security.util diff --git a/test/jdk/sun/security/provider/pqc/ML_DSA_CMS.java b/test/jdk/sun/security/provider/pqc/ML_DSA_CMS.java new file mode 100644 index 000000000000..f7469847b3fa --- /dev/null +++ b/test/jdk/sun/security/provider/pqc/ML_DSA_CMS.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8349732 + * @library /test/lib + * @summary Add support for JARs signed with ML-DSA + * @modules java.base/sun.security.pkcs + */ +import jdk.test.lib.Asserts; +import jdk.test.lib.security.RepositoryFileReader; +import sun.security.pkcs.PKCS7; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Base64; +import java.util.stream.Collectors; + +import static jdk.test.lib.security.RepositoryFileReader.*; + +public class ML_DSA_CMS { + public static void main(String[] args) throws Exception { + // Example signed-data encodings from RFC 9882, Appendix B + // (https://datatracker.ietf.org/doc/html/rfc9882#name-examples), which + // can be verified by example certificates from RFC 9881, Appendix C.3 + // (https://datatracker.ietf.org/doc/html/rfc9881#name-example-certificates) + // + // These data can be retrieved from the following GitHub releases: + // https://github.com/lamps-wg/cms-ml-dsa/releases/tag/draft-ietf-lamps-cms-ml-dsa-07 + // https://github.com/lamps-wg/dilithium-certificates/releases/tag/draft-ietf-lamps-dilithium-certificates-13 + // + // Although the release tags include "draft", these values are the + // same as those in the final RFCs 9881 and 9882. + try (var cmsReader = RepositoryFileReader.of(CMS_ML_DSA.class, + "cms-ml-dsa-draft-ietf-lamps-cms-ml-dsa-07/"); + var dsaReader = RepositoryFileReader.of(DILITHIUM_CERTIFICATES.class, + "dilithium-certificates-draft-ietf-lamps-dilithium-certificates-13/")) { + test(readCMS(cmsReader, "mldsa44-signed-attrs.pem"), + readCert(dsaReader, "ML-DSA-44.crt")); + test(readCMS(cmsReader, "mldsa65-signed-attrs.pem"), + readCert(dsaReader, "ML-DSA-65.crt")); + test(readCMS(cmsReader, "mldsa87-signed-attrs.pem"), + readCert(dsaReader, "ML-DSA-87.crt")); + } + } + + /// Verifies a signed file. + /// @param data the signed data in PKCS #7 format + /// @param cert the certificate used to verify + static void test(byte[] data, X509Certificate cert) throws Exception { + var p7 = new PKCS7(data); + for (var si : p7.getSignerInfos()) { + Asserts.assertTrue(p7.verify(si, null, cert).getIssuerName() != null); + } + } + + // Read data in https://datatracker.ietf.org/doc/html/rfc9882#name-examples + static byte[] readCMS(RepositoryFileReader f, String entry) throws IOException { + var data = f.read("examples/" + entry); + var pem = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data))) + .lines() + .filter(s -> !s.contains("-----")) + .collect(Collectors.joining()); + return Base64.getMimeDecoder().decode(pem); + } + + // Read data in https://datatracker.ietf.org/doc/html/rfc9881#name-example-certificates + static X509Certificate readCert(RepositoryFileReader f, String entry) throws Exception { + var data = f.read("examples/" + entry); + var cf = CertificateFactory.getInstance("X.509"); + return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(data)); + } +} diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java index 3f25ab4a2132..837de29d66d1 100644 --- a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java +++ b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Entrust.java @@ -28,7 +28,7 @@ /** * @test - * @bug 8337664 8341059 8361212 8386371 + * @bug 8337664 8341059 8361212 8386371 8303772 * @summary Check that TLS Server certificates chaining back to distrusted * Entrust roots are invalid * @library /test/lib @@ -46,7 +46,7 @@ public class Entrust { // Each of the roots have a test certificate chain stored in a file // named "-chain.pem". private static final String[] ROOTS_TO_TEST = new String[]{ - "entrustevca", "entrustrootcaec1", "entrustrootcag2", "entrust2048ca"}; + "entrustrootcaec1", "entrustrootcag2", "entrust2048ca"}; // Date after the restrictions took effect when distrust was first announced private static final ZonedDateTime DISTRUST_DATE = diff --git a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustevca-chain.pem b/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustevca-chain.pem deleted file mode 100644 index e9c06b19c694..000000000000 --- a/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/entrust/entrustevca-chain.pem +++ /dev/null @@ -1,79 +0,0 @@ -Root Certificate: - Version: 3 (0x2) - Serial Number: 1164660820 (0x456b5054) - Signature Algorithm: sha1WithRSAEncryption - Issuer: C=US, O=Entrust, Inc., OU=www.entrust.net/CPS is incorporated by reference, OU=(c) 2006 Entrust, Inc., CN=Entrust Root Certification Authority - Validity - Not Before: Nov 27 20:23:42 2006 GMT - Not After : Nov 27 20:53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OIOmwwnT ------END CERTIFICATE----- diff --git a/test/jdk/sun/security/tools/jarsigner/ML_DSA.java b/test/jdk/sun/security/tools/jarsigner/ML_DSA.java new file mode 100644 index 000000000000..55758b761b3e --- /dev/null +++ b/test/jdk/sun/security/tools/jarsigner/ML_DSA.java @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8298387 + * @summary signing with ML-DSA + * @library /test/lib + * @modules java.base/sun.security.util + */ + +import jdk.security.jarsigner.JarSigner; +import jdk.test.lib.Asserts; +import jdk.test.lib.SecurityTools; +import jdk.test.lib.process.Proc; +import jdk.test.lib.security.DerUtils; +import jdk.test.lib.util.JarUtils; +import sun.security.util.KnownOIDs; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.util.List; +import java.util.jar.JarFile; +import java.util.zip.ZipFile; + +public class ML_DSA { + + static List SIGNERS = List.of("44", "65", "87"); + + public static void main(String[] args) throws Exception { + if (args.length > 0) { + // Launched by testDisabled() in a sub-process to count signers + var expectedCount = Integer.parseInt(args[0]); + try (var jf = new JarFile("a.jar")) { + var je = jf.getJarEntry("a"); + jf.getInputStream(je).readAllBytes(); + var signers = je.getCodeSigners(); + var count = signers == null ? 0 : signers.length; + if (expectedCount != count) { + throw new RuntimeException("Expected: " + expectedCount + + ", actual " + count); + } + } + } else { + prepare(); + testAPI(); + testTool(); // call this last, as it modifies a.jar. + testDisabled(); + } + } + + private static void prepare() throws Exception { + for (var signer : SIGNERS) { + SecurityTools.keytool("-keystore ks -storepass changeit -genkeypair -alias " + + signer + " -keyalg ML-DSA-" + signer + " -dname CN=" + signer) + .shouldHaveExitValue(0); + } + JarUtils.createJarFile(Path.of("a.jar"), Path.of("."), + Files.write(Path.of("a"), new byte[10])); + } + + static void testAPI() throws Exception { + var pass = "changeit".toCharArray(); + var ks = KeyStore.getInstance(new File("ks"), pass); + for (var signer : SIGNERS) { + var jsb = new JarSigner.Builder((KeyStore.PrivateKeyEntry) + ks.getEntry(signer, new KeyStore.PasswordProtection(pass))); + try (var zf = new ZipFile("a.jar"); + var of = Files.newOutputStream(Path.of(signer + ".jar"))) { + jsb.signerName(signer).build().sign(zf, of); + } + try (var jf = new JarFile(signer + ".jar")) { + var je = jf.getJarEntry("a"); + jf.getInputStream(je).readAllBytes(); + Asserts.assertEquals(1, je.getCodeSigners().length); + checkDigestAlgorithm(jf, signer, KnownOIDs.SHA_512); + } + } + } + + static void testTool() throws Exception { + for (var signer : SIGNERS) { + SecurityTools.jarsigner("-keystore ks -storepass changeit a.jar " + signer) + .shouldHaveExitValue(0); + } + SecurityTools.jarsigner("-verify a.jar -verbose -certs") + .shouldHaveExitValue(0) + .shouldContain("jar verified"); + + try (var jf = new JarFile("a.jar")) { + var je = jf.getJarEntry("a"); + jf.getInputStream(je).readAllBytes(); + Asserts.assertEquals(3, je.getCodeSigners().length); + for (var signer : SIGNERS) { + checkDigestAlgorithm(jf, signer, KnownOIDs.SHA_512); + } + } + } + + static void testDisabled() throws Exception { + + // All disabled + Files.writeString(Paths.get("my.security"), + "jdk.jar.disabledAlgorithms=ML-DSA"); + SecurityTools.jarsigner("-J-Djava.security.properties=my.security" + + " -keystore ks -storepass changeit" + + " -verify a.jar -verbose -certs -strict") + .shouldHaveExitValue(16) + .shouldContain("ML-DSA-44 key (disabled)") + .shouldContain("ML-DSA-65 key (disabled)") + .shouldContain("ML-DSA-87 key (disabled)") + .shouldContain("The jar will be treated as unsigned"); + // Need to launch in a new process because security property is + // read at the beginning + Proc.create("ML_DSA") + .secprop("jdk.jar.disabledAlgorithms", "ML-DSA") + .args("0") + .start() + .waitFor(0); + + // One disabled, one made weak + Files.writeString(Paths.get("my.security"), """ + jdk.jar.disabledAlgorithms=ML-DSA-44 + jdk.security.legacyAlgorithms=ML-DSA-65 + """); + SecurityTools.jarsigner("-J-Djava.security.properties=my.security" + + " -keystore ks -storepass changeit" + + " -verify a.jar -verbose -certs -strict") + .shouldHaveExitValue(0) + .shouldContain("ML-DSA-44 key (disabled)") + .shouldContain("ML-DSA-65 key (weak)") + .shouldContain("ML-DSA-87 key") + .shouldNotContain("ML-DSA-87 key (disabled)") + .shouldContain("jar verified."); + Proc.create("ML_DSA") + .secprop("jdk.jar.disabledAlgorithms", "ML-DSA-44") + .secprop("jdk.security.legacyAlgorithms", "ML-DSA-65") + .args("2") // weak still considered signer, disabled not + .start() + .waitFor(0); + } + + static void checkDigestAlgorithm(JarFile jf, String alias, KnownOIDs digAlg) + throws Exception { + var p7 = jf.getInputStream(jf.getEntry("META-INF/" + alias + ".DSA")) + .readAllBytes(); + // SignedData - digestAlgorithms + DerUtils.checkAlg(p7, "10100", digAlg); + // SignedData - signerInfos - digestAlgorithm + DerUtils.checkAlg(p7, "104020", digAlg); + // SignedData - signerInfos - signatureAlgorithm + DerUtils.checkAlg(p7, "104040", KnownOIDs.valueOf("ML_DSA_" + alias)); + // SignedData - signerInfos - signedAttrs - CMSAlgorithmProtection - digestAlgorithm + DerUtils.checkAlg(p7, "1040321000", digAlg); + // SignedData - signerInfos - signedAttrs - CMSAlgorithmProtection - signatureAlgorithm + DerUtils.checkAlg(p7, "1040321010", KnownOIDs.valueOf("ML_DSA_" + alias)); + } +}