diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c75d06f08..2b32e71c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ permissions: contents: read env: - BORINGSSL_VERSION: 0.20260929.0 + BORINGSSL_VERSION: 0.20261105.0 jobs: boringssl_version_check: @@ -445,7 +445,7 @@ jobs: strategy: fail-fast: false matrix: - platform: [ubuntu-22.04, ubuntu-22.04-arm, ubuntu-latest, macos-14, macos-latest, windows-latest] + platform: [ubuntu-22.04, ubuntu-22.04-arm, ubuntu-latest, macos-15, macos-latest, windows-latest] java: [8, 11, 17, 21, 25, EA] dist: ['temurin', 'zulu'] include: @@ -457,7 +457,7 @@ jobs: separator: ':' - platform: macos-latest separator: ':' - - platform: macos-14 + - platform: macos-15 separator: ':' - platform: windows-latest separator: ';' @@ -465,7 +465,7 @@ jobs: - platform: macos-latest java: 8 dist: 'temurin' - - platform: macos-14 + - platform: macos-15 java: 8 dist: 'temurin' @@ -514,6 +514,9 @@ jobs: if [ "${{ matrix.java }}" != "8" ]; then EXTRA_FLAGS="--add-opens=java.base/java.net=ALL-UNNAMED" fi + if [ "${{ matrix.java }}" = "EA" ]; then + EXTRA_FLAGS="$EXTRA_FLAGS -Djdk.reflect.allowNonSerializableConstruction=true" + fi # SIGTERM handler, e.g. for when tests hang and time out. # Send SIGQUIT to test process to get thread dump, give it # a few seconds to complete and then kill it. diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 81968eac5..d68527320 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -251,6 +251,7 @@ Conscrypt's EC AlgorithmParameters implementation only supports named curves. * `SHA-256` * `SHA-384` * `SHA-512` +* `SHAKE256-512` ### SecretKeyFactory @@ -286,8 +287,19 @@ Conscrypt's EC AlgorithmParameters implementation only supports named curves. * `ML-DSA-44` * `ML-DSA-65` * `ML-DSA-87` +* `EXTERNAL-MU-ML-DSA` +* `EXTERNAL-MU-ML-DSA-44` +* `EXTERNAL-MU-ML-DSA-65` +* `EXTERNAL-MU-ML-DSA-87` * `SLH-DSA-SHA2-128S` +Conscrypt's `EXTERNAL-MU-ML-DSA` signatures take the 64-byte ML-DSA message +representative mu as input instead of the message (FIPS 204, Algorithm 7, +line 6, with an empty context string), which the caller computes as +`SHAKE256-512(SHAKE256-512(rawPublicKey) || 0x00 || 0x00 || message)`. They +only support signing; the result is a regular ML-DSA signature of the message, +which is verified with `ML-DSA`. Context strings are currently not supported. + ### ECDSA Elliptic Curves Conscrypt supports the following curves in ECDSA signatures: diff --git a/android/src/main/java/org/conscrypt/Platform.java b/android/src/main/java/org/conscrypt/Platform.java index af7c82353..7dbb42244 100644 --- a/android/src/main/java/org/conscrypt/Platform.java +++ b/android/src/main/java/org/conscrypt/Platform.java @@ -908,10 +908,24 @@ public static void setPqcDefaultEnabledForTesting(boolean enabled) { pqcDefaultEnabled = enabled; } + private static volatile boolean pqcDefaultSignatureAlgorithmsEnabled = true; + + public static boolean isPqcDefaultSignatureAlgorithmsEnabled() { + return pqcDefaultSignatureAlgorithmsEnabled; + } + + public static void setPqcDefaultSignatureAlgorithmsEnabledForTesting(boolean enabled) { + pqcDefaultSignatureAlgorithmsEnabled = enabled; + } + public static boolean isSdkGreater(int sdk) { return Build.VERSION.SDK_INT > sdk; } + public static boolean isMerkleTreeCertsEnabled() { + return false; + } + private static class X509NativeAllocationRegistryHolder { private static final Object REGISTRY; private static final Method REGISTER_METHOD; diff --git a/build.gradle b/build.gradle index 32229c00a..43b73732c 100644 --- a/build.gradle +++ b/build.gradle @@ -2,5 +2,5 @@ description = 'Conscrypt is an alternate Java Security Provider that uses Boring subprojects { // Keep this in `subprojects` for scripts and ease of use. Migrate to properties later. - version = "2.9-SNAPSHOT" + version = "2.10.0" } diff --git a/common/src/jni/main/cpp/conscrypt/native_crypto.cc b/common/src/jni/main/cpp/conscrypt/native_crypto.cc index 427dff728..3ab0c132d 100644 --- a/common/src/jni/main/cpp/conscrypt/native_crypto.cc +++ b/common/src/jni/main/cpp/conscrypt/native_crypto.cc @@ -3472,6 +3472,125 @@ static jbyteArray NativeCrypto_MLDSA87_public_key_from_seed(JNIEnv* env, jclass, return publicKeyRef.release(); } +/* + * Signs the ML-DSA message representative |mu| with the ML-DSA private key |pkey| and returns the + * encoded signature, or nullptr after throwing a Java exception. |privateKeyFromSeed| and + * |signMessageRepresentative| must be the BoringSSL functions for the parameter set of |pkey|, + * i.e. MLDSA{44,65,87}_private_key_from_seed and MLDSA{44,65,87}_sign_message_representative from + * , and |signatureLength| the matching MLDSA{44,65,87}_SIGNATURE_BYTES. + * BoringSSL's EVP layer only signs whole messages, so the private key is re-expanded from its seed + * (EVP_PKEY_get_private_seed from ) for the low-level signing function. + */ +template +static jbyteArray mldsaSignMessageRepresentative( + JNIEnv* env, EVP_PKEY* pkey, const uint8_t* mu, size_t signatureLength, + int (*privateKeyFromSeed)(PrivateKey*, const uint8_t*, size_t), + int (*signMessageRepresentative)(uint8_t*, const PrivateKey*, const uint8_t*)) { + ScopedLocalRef signatureRef(env, + env->NewByteArray(static_cast(signatureLength))); + if (signatureRef.get() == nullptr) { + return nullptr; + } + ScopedByteArrayRW signature(env, signatureRef.get()); + if (signature.get() == nullptr) { + return nullptr; + } + + // The seed and the expanded private key are secrets, so they are cleansed as soon as they are + // no longer needed, on both the success and the failure paths. + // MLDSA_SEED_BYTES is defined in . + uint8_t seed[MLDSA_SEED_BYTES]; + size_t seedLength = sizeof(seed); + if (!EVP_PKEY_get_private_seed(pkey, seed, &seedLength)) { + OPENSSL_cleanse(seed, sizeof(seed)); + JNI_TRACE("MLDSA_sign_message_representative(%p) => EVP_PKEY_get_private_seed failed", + pkey); + conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_PKEY_get_private_seed"); + return nullptr; + } + + PrivateKey privateKey; + int expanded = privateKeyFromSeed(&privateKey, seed, seedLength); + OPENSSL_cleanse(seed, sizeof(seed)); + if (!expanded) { + OPENSSL_cleanse(&privateKey, sizeof(privateKey)); + JNI_TRACE("MLDSA_sign_message_representative(%p) => private_key_from_seed failed", pkey); + conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "MLDSA_private_key_from_seed"); + return nullptr; + } + + int signed_ = + signMessageRepresentative(reinterpret_cast(signature.get()), &privateKey, mu); + OPENSSL_cleanse(&privateKey, sizeof(privateKey)); + if (!signed_) { + JNI_TRACE("MLDSA_sign_message_representative(%p) => sign_message_representative failed", + pkey); + conscrypt::jniutil::throwExceptionFromBoringSSLError(env, + "MLDSA_sign_message_representative"); + return nullptr; + } + return signatureRef.release(); +} + +/* + * static native byte[] MLDSA_sign_message_representative(NativeRef.EVP_PKEY, byte[]) + */ +static jbyteArray NativeCrypto_MLDSA_sign_message_representative(JNIEnv* env, jclass, + jobject pkeyRef, jbyteArray mu) { + CHECK_ERROR_QUEUE_ON_RETURN; + EVP_PKEY* pkey = fromContextObject(env, pkeyRef); + JNI_TRACE("MLDSA_sign_message_representative(%p, %p)", pkey, mu); + + // fromContextObject has already thrown a NullPointerException if |pkey| is null, whereas |mu| + // is a plain Java array, so the exception for it is thrown here. + if (pkey == nullptr) { + return nullptr; + } + if (mu == nullptr) { + conscrypt::jniutil::throwNullPointerException(env, "mu == null"); + return nullptr; + } + ScopedByteArrayRO muBytes(env, mu); + if (muBytes.get() == nullptr) { + return nullptr; + } + // MLDSA_MU_BYTES (64) is defined in . + if (muBytes.size() != MLDSA_MU_BYTES) { + JNI_TRACE("MLDSA_sign_message_representative(%p, %p) => invalid mu length %zu", pkey, mu, + muBytes.size()); + conscrypt::jniutil::throwIllegalArgumentException(env, "mu must be 64 bytes long"); + return nullptr; + } + const uint8_t* muData = reinterpret_cast(muBytes.get()); + + // The per-parameter-set types, constants and functions are declared in . + jbyteArray signature; + switch (EVP_PKEY_id(pkey)) { + case EVP_PKEY_ML_DSA_44: + signature = mldsaSignMessageRepresentative( + env, pkey, muData, MLDSA44_SIGNATURE_BYTES, MLDSA44_private_key_from_seed, + MLDSA44_sign_message_representative); + break; + case EVP_PKEY_ML_DSA_65: + signature = mldsaSignMessageRepresentative( + env, pkey, muData, MLDSA65_SIGNATURE_BYTES, MLDSA65_private_key_from_seed, + MLDSA65_sign_message_representative); + break; + case EVP_PKEY_ML_DSA_87: + signature = mldsaSignMessageRepresentative( + env, pkey, muData, MLDSA87_SIGNATURE_BYTES, MLDSA87_private_key_from_seed, + MLDSA87_sign_message_representative); + break; + default: + JNI_TRACE("MLDSA_sign_message_representative(%p, %p) => not an ML-DSA key", pkey, mu); + conscrypt::jniutil::throwInvalidKeyException(env, "Not an ML-DSA private key"); + return nullptr; + } + + JNI_TRACE("MLDSA_sign_message_representative(%p, %p) => %p", pkey, mu, signature); + return signature; +} + static void NativeCrypto_SLHDSA_SHA2_128S_generate_key(JNIEnv* env, jclass, jbyteArray outPublicArray, jbyteArray outPrivateArray) { @@ -4317,16 +4436,35 @@ static jint NativeCrypto_EVP_MD_CTX_copy_ex(JNIEnv* env, jclass, jobject dstCtxR } /* - * public static native int EVP_DigestFinal_ex(long, byte[], int) + * Returns the EVP_MD_CTX referenced by |ctxRef| if it has a digest configured, or nullptr after + * throwing a Java exception otherwise. A freshly created or cleaned-up EVP_MD_CTX has no digest + * configured, and BoringSSL's EVP_DigestUpdate, EVP_DigestFinal_ex and EVP_DigestFinalXOF would + * dereference the null EVP_MD rather than report an error. + */ +static EVP_MD_CTX* evpMdCtxWithDigest(JNIEnv* env, jobject ctxRef, const char* jniName) { + EVP_MD_CTX* ctx = fromContextObject(env, ctxRef); + if (ctx == nullptr) { + JNI_TRACE("%s => ctx == null", jniName); + return nullptr; + } + if (EVP_MD_CTX_get0_md(ctx) == nullptr) { + JNI_TRACE("%s(%p) => ctx not initialized", jniName, ctx); + conscrypt::jniutil::throwIllegalStateException(env, "EVP_MD_CTX is not initialized"); + return nullptr; + } + return ctx; +} + +/* + * static native int EVP_DigestFinal_ex(NativeRef.EVP_MD_CTX, byte[], int) */ static jint NativeCrypto_EVP_DigestFinal_ex(JNIEnv* env, jclass, jobject ctxRef, jbyteArray hash, jint offset) { CHECK_ERROR_QUEUE_ON_RETURN; - EVP_MD_CTX* ctx = fromContextObject(env, ctxRef); + EVP_MD_CTX* ctx = evpMdCtxWithDigest(env, ctxRef, "EVP_DigestFinal_ex"); JNI_TRACE_MD("EVP_DigestFinal_ex(%p, %p, %d)", ctx, hash, offset); if (ctx == nullptr) { - JNI_TRACE("EVP_DigestFinal_ex => ctx == null"); return -1; } else if (hash == nullptr) { conscrypt::jniutil::throwNullPointerException(env, "hash == null"); @@ -4349,6 +4487,44 @@ static jint NativeCrypto_EVP_DigestFinal_ex(JNIEnv* env, jclass, jobject ctxRef, return static_cast(bytesWritten); } +/* + * static native void EVP_DigestFinalXOF(NativeRef.EVP_MD_CTX, byte[], int, int) + */ +static void NativeCrypto_EVP_DigestFinalXOF(JNIEnv* env, jclass, jobject ctxRef, jbyteArray out, + jint offset, jint length) { + CHECK_ERROR_QUEUE_ON_RETURN; + EVP_MD_CTX* ctx = evpMdCtxWithDigest(env, ctxRef, "EVP_DigestFinalXOF"); + JNI_TRACE_MD("EVP_DigestFinalXOF(%p, %p, %d, %d)", ctx, out, offset, length); + + if (ctx == nullptr) { + return; + } else if (out == nullptr) { + conscrypt::jniutil::throwNullPointerException(env, "out == null"); + return; + } + + ScopedByteArrayRW outBytes(env, out); + if (outBytes.get() == nullptr) { + return; + } + if (ARRAY_OFFSET_LENGTH_INVALID(outBytes, offset, length)) { + conscrypt::jniutil::throwException(env, "java/lang/ArrayIndexOutOfBoundsException", "out"); + return; + } + + // EVP_DigestFinalXOF squeezes |length| bytes of output and then clears |ctx|, zeroing its + // digest state and detaching its EVP_MD, so the caller must call EVP_DigestInit_ex again before + // the next digest operation. It fails, leaving |ctx| untouched, if the digest in |ctx| is not + // an extendable-output function. + if (!EVP_DigestFinalXOF(ctx, reinterpret_cast(outBytes.get() + offset), + static_cast(length))) { + conscrypt::jniutil::throwExceptionFromBoringSSLError(env, "EVP_DigestFinalXOF"); + return; + } + + JNI_TRACE_MD("EVP_DigestFinalXOF(%p, %p, %d, %d) => success", ctx, out, offset, length); +} + static jint NativeCrypto_EVP_DigestInit_ex(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong evpMdRef) { CHECK_ERROR_QUEUE_ON_RETURN; @@ -4409,6 +4585,8 @@ static jlong NativeCrypto_EVP_get_digestbyname(JNIEnv* env, jclass, jstring algo md = EVP_sha384(); } else if (strcasecmp(alg, "sha512") == 0) { md = EVP_sha512(); + } else if (strcasecmp(alg, "shake256") == 0) { + md = EVP_shake256(); } else { JNI_TRACE("NativeCrypto_EVP_get_digestbyname(%s) => error", alg); conscrypt::jniutil::throwRuntimeException(env, "Hash algorithm not found"); @@ -4599,12 +4777,20 @@ static void evpUpdate(JNIEnv* env, jobject evpMdCtxRef, jbyteArray inJavaBytes, static void NativeCrypto_EVP_DigestUpdateDirect(JNIEnv* env, jclass, jobject evpMdCtxRef, jlong inPtr, jint inLength) { CHECK_ERROR_QUEUE_ON_RETURN; + // Unlike the EVP_DigestSign/Verify variants, which may legitimately have no EVP_MD (e.g. for + // Ed25519), a plain digest context must have been initialized with EVP_DigestInit_ex. + if (evpMdCtxWithDigest(env, evpMdCtxRef, "EVP_DigestUpdateDirect") == nullptr) { + return; + } evpUpdate(env, evpMdCtxRef, inPtr, inLength, "EVP_DigestUpdateDirect", EVP_DigestUpdate); } static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, jobject evpMdCtxRef, jbyteArray inJavaBytes, jint inOffset, jint inLength) { CHECK_ERROR_QUEUE_ON_RETURN; + if (evpMdCtxWithDigest(env, evpMdCtxRef, "EVP_DigestUpdate") == nullptr) { + return; + } evpUpdate(env, evpMdCtxRef, inJavaBytes, inOffset, inLength, "EVP_DigestUpdate", EVP_DigestUpdate); } @@ -10343,7 +10529,7 @@ static jlongArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jlong ssl_ad return nullptr; } - STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl); + const STACK_OF(SSL_CIPHER)* cipherStack = SSL_get_ciphers(ssl); size_t count = (cipherStack != nullptr) ? sk_SSL_CIPHER_num(cipherStack) : 0; ScopedLocalRef ciphersArray(env, env->NewLongArray(static_cast(count))); ScopedLongArrayRW ciphers(env, ciphersArray.get()); @@ -10535,6 +10721,38 @@ static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass, jlong ssl_address, ret); } +static void NativeCrypto_setSessionIdContextSha256(JNIEnv* env, jclass, jlong ssl_address, + CONSCRYPT_UNUSED jobject ssl_holder, + jbyteArray context) { + CHECK_ERROR_QUEUE_ON_RETURN; + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_setSessionIdContextSha256 context=%p", ssl, context); + if (ssl == nullptr) { + return; + } + + if (context == nullptr) { + conscrypt::jniutil::throwNullPointerException( + env, "NativeCrypto_setSessionIdContextSha256 context == null"); + return; + } + ScopedByteArrayRO buf(env, context); + if (buf.get() == nullptr) { + JNI_TRACE("ssl=%p NativeCrypto_setSessionIdContextSha256 => threw exception", ssl); + return; + } + + uint8_t digest[EVP_MAX_MD_SIZE]; + unsigned int digest_len = 0; + if (!EVP_Digest(buf.get(), buf.size(), digest, &digest_len, EVP_sha256(), nullptr) || + !SSL_set_session_id_context(ssl, digest, digest_len)) { + conscrypt::jniutil::throwExceptionFromBoringSSLError( + env, "NativeCrypto_setSessionIdContextSha256"); + return; + } + JNI_TRACE("ssl=%p NativeCrypto_setSessionIdContextSha256 => ok", ssl); +} + /** * Sets the ciphers suites that are enabled in the SSL */ @@ -10657,11 +10875,16 @@ static int selectApplicationProtocol(SSL* ssl, unsigned char** out, unsigned cha static int selectApplicationProtocol(SSL* ssl, JNIEnv* env, jobject sslHandshakeCallbacks, unsigned char** out, unsigned char* outLen, const unsigned char* in, const unsigned int inLen) { + if (env->ExceptionCheck()) { + JNI_TRACE("ssl=%p selectApplicationProtocol already pending exception", ssl); + return SSL_TLSEXT_ERR_ALERT_FATAL; + } + // Copy the input array. ScopedLocalRef protocols(env, env->NewByteArray(static_cast(inLen))); if (protocols.get() == nullptr) { JNI_TRACE("ssl=%p selectApplicationProtocol failed allocating array", ssl); - return SSL_TLSEXT_ERR_NOACK; + return SSL_TLSEXT_ERR_ALERT_FATAL; } env->SetByteArrayRegion(protocols.get(), 0, (static_cast(inLen)), reinterpret_cast(in)); @@ -10669,15 +10892,34 @@ static int selectApplicationProtocol(SSL* ssl, JNIEnv* env, jobject sslHandshake // Invoke the selection method. jmethodID methodID = conscrypt::jniutil::sslHandshakeCallbacks_selectApplicationProtocol; jint offset = env->CallIntMethod(sslHandshakeCallbacks, methodID, protocols.get()); + if (env->ExceptionCheck()) { + JNI_TRACE("ssl=%p selectApplicationProtocol exception", ssl); + return SSL_TLSEXT_ERR_ALERT_FATAL; + } if (offset < 0) { JNI_TRACE("ssl=%p selectApplicationProtocol selection failed", ssl); return SSL_TLSEXT_ERR_NOACK; } + size_t uOffset = static_cast(offset); + if (uOffset >= inLen) { + JNI_TRACE("ssl=%p selectApplicationProtocol out-of-bounds offset=%d inLen=%u", ssl, offset, + inLen); + return SSL_TLSEXT_ERR_ALERT_FATAL; + } + + unsigned char protoLen = in[uOffset]; + if (protoLen == 0 || uOffset + 1 + protoLen > inLen) { + JNI_TRACE( + "ssl=%p selectApplicationProtocol invalid protocol length=%u at offset=%d inLen=%u", + ssl, protoLen, offset, inLen); + return SSL_TLSEXT_ERR_ALERT_FATAL; + } + // Point the output to the selected protocol. - *outLen = *(in + offset); - *out = const_cast(in + offset + 1); + *outLen = protoLen; + *out = const_cast(in + uOffset + 1); return SSL_TLSEXT_ERR_OK; } @@ -10861,6 +11103,39 @@ static void NativeCrypto_SSL_set1_groups(JNIEnv* env, jclass, jlong sslAddress, } } +static void NativeCrypto_SSL_set_verify_algorithm_prefs(JNIEnv* env, jclass, jlong sslAddress, + CONSCRYPT_UNUSED jobject sslHolder, + jintArray prefs) { + CHECK_ERROR_QUEUE_ON_RETURN; + SSL* ssl = to_SSL(env, sslAddress, /* throwIfNull= */ true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify_algorithm_prefs prefs=%p", ssl, prefs); + if (ssl == nullptr) { + // to_SSL already called conscrypt::jniutil::throwNullPointerException + return; + } + if (prefs == nullptr) { + conscrypt::jniutil::throwNullPointerException(env, "prefs == null"); + return; + } + ScopedIntArrayRO prefs_ro(env, prefs); + if (prefs_ro.get() == nullptr) { + JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify_algorithm_prefs => threw exception", ssl); + return; + } + std::vector prefs_vector; + prefs_vector.reserve(prefs_ro.size()); + const jint* prefs_ptr = prefs_ro.get(); + for (size_t i = 0; i < prefs_ro.size(); i++) { + prefs_vector.push_back(static_cast(prefs_ptr[i])); + } + + if (!SSL_set_verify_algorithm_prefs(ssl, prefs_vector.data(), prefs_vector.size())) { + conscrypt::jniutil::throwSSLExceptionStr(env, "Error setting verify algorithm prefs"); + ERR_clear_error(); + return; + } +} + static jstring NativeCrypto_SSL_get_curve_name(JNIEnv* env, jclass, jlong sslAddress, CONSCRYPT_UNUSED jobject sslHolder) { CHECK_ERROR_QUEUE_ON_RETURN; @@ -11304,7 +11579,7 @@ static jobjectArray NativeCrypto_get_cipher_names(JNIEnv* env, jclass, jstring s ERR_clear_error(); return nullptr; } - STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl.get()); + const STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(ssl.get()); size_t size = sk_SSL_CIPHER_num(ciphers); ScopedLocalRef cipherNamesArray( @@ -12327,6 +12602,75 @@ static void NativeCrypto_SSL_CTX_set_spake_credential( return; } +/* + * Trust Anchor Identifiers (draft-ietf-tls-trust-anchor-ids). + * + * Trust anchor ID lists are passed in wire format: a series of non-empty, 8-bit length-prefixed + * trust anchor IDs, each of which is the binary (DER RELATIVE-OID contents) representation. + */ + +static void NativeCrypto_SSL_set1_requested_trust_anchors(JNIEnv* env, jclass, jlong ssl_address, + CONSCRYPT_UNUSED jobject ssl_holder, + jbyteArray idsJavaBytes) { + CHECK_ERROR_QUEUE_ON_RETURN; + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_set1_requested_trust_anchors(%p)", ssl, idsJavaBytes); + if (ssl == nullptr) { + return; + } + if (idsJavaBytes == nullptr) { + conscrypt::jniutil::throwNullPointerException(env, "ids == null"); + return; + } + ScopedByteArrayRO ids(env, idsJavaBytes); + if (ids.get() == nullptr) { + JNI_TRACE("ssl=%p NativeCrypto_SSL_set1_requested_trust_anchors => could not read ids", + ssl); + return; + } + if (!SSL_set1_requested_trust_anchors(ssl, reinterpret_cast(ids.get()), + ids.size())) { + // A malformed list is a caller error rather than a TLS failure, so report it as an + // IllegalArgumentException. Anything else is unexpected and reported as an SSLException. + const uint32_t error = ERR_peek_error(); + const bool invalid_list = ERR_GET_LIB(error) == ERR_LIB_SSL && + ERR_GET_REASON(error) == SSL_R_INVALID_TRUST_ANCHOR_LIST; + conscrypt::jniutil::throwExceptionFromBoringSSLError( + env, "SSL_set1_requested_trust_anchors", + invalid_list ? conscrypt::jniutil::throwIllegalArgumentException + : conscrypt::jniutil::throwSSLExceptionStr); + JNI_TRACE("ssl=%p NativeCrypto_SSL_set1_requested_trust_anchors => error", ssl); + return; + } + JNI_TRACE("ssl=%p NativeCrypto_SSL_set1_requested_trust_anchors => success", ssl); +} + +static jbyteArray NativeCrypto_SSL_get0_peer_available_trust_anchors( + JNIEnv* env, jclass, jlong ssl_address, CONSCRYPT_UNUSED jobject ssl_holder) { + CHECK_ERROR_QUEUE_ON_RETURN; + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_peer_available_trust_anchors", ssl); + if (ssl == nullptr) { + return nullptr; + } + const uint8_t* ids; + size_t ids_len; + SSL_get0_peer_available_trust_anchors(ssl, &ids, &ids_len); + if (ids_len == 0) { + JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_peer_available_trust_anchors => nullptr", ssl); + return nullptr; + } + jbyteArray result = env->NewByteArray(static_cast(ids_len)); + if (result == nullptr) { + JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_peer_available_trust_anchors => alloc failed", ssl); + return nullptr; + } + env->SetByteArrayRegion(result, 0, static_cast(ids_len), + reinterpret_cast(ids)); + JNI_TRACE("ssl=%p NativeCrypto_SSL_get0_peer_available_trust_anchors => %p", ssl, result); + return result; +} + // TESTING METHODS BEGIN static int NativeCrypto_BIO_read(JNIEnv* env, jclass, jlong bioRef, jbyteArray outputJavaBytes) { @@ -12786,6 +13130,7 @@ static JNINativeMethod sNativeCryptoMethods[] = { CONSCRYPT_NATIVE_METHOD(MLDSA44_public_key_from_seed, "([B)[B"), CONSCRYPT_NATIVE_METHOD(MLDSA65_public_key_from_seed, "([B)[B"), CONSCRYPT_NATIVE_METHOD(MLDSA87_public_key_from_seed, "([B)[B"), + CONSCRYPT_NATIVE_METHOD(MLDSA_sign_message_representative, "(" REF_EVP_PKEY "[B)[B"), CONSCRYPT_NATIVE_METHOD(SLHDSA_SHA2_128S_generate_key, "([B[B)V"), CONSCRYPT_NATIVE_METHOD(SLHDSA_SHA2_128S_sign, "([BI[B)[B"), CONSCRYPT_NATIVE_METHOD(SLHDSA_SHA2_128S_prehash_sign, "([BII[B)[B"), @@ -12809,6 +13154,7 @@ static JNINativeMethod sNativeCryptoMethods[] = { CONSCRYPT_NATIVE_METHOD(EVP_DigestUpdate, "(" REF_EVP_MD_CTX "[BII)V"), CONSCRYPT_NATIVE_METHOD(EVP_DigestUpdateDirect, "(" REF_EVP_MD_CTX "JI)V"), CONSCRYPT_NATIVE_METHOD(EVP_DigestFinal_ex, "(" REF_EVP_MD_CTX "[BI)I"), + CONSCRYPT_NATIVE_METHOD(EVP_DigestFinalXOF, "(" REF_EVP_MD_CTX "[BII)V"), CONSCRYPT_NATIVE_METHOD(EVP_get_digestbyname, "(Ljava/lang/String;)J"), CONSCRYPT_NATIVE_METHOD(EVP_MD_size, "(J)I"), CONSCRYPT_NATIVE_METHOD(EVP_DigestSignInit, "(" REF_EVP_MD_CTX "J" REF_EVP_PKEY ")J"), @@ -13021,6 +13367,7 @@ static JNINativeMethod sNativeCryptoMethods[] = { CONSCRYPT_NATIVE_METHOD(SSL_set_connect_state, "(J" REF_SSL ")V"), CONSCRYPT_NATIVE_METHOD(SSL_set_verify, "(J" REF_SSL "I)V"), CONSCRYPT_NATIVE_METHOD(SSL_set_session, "(J" REF_SSL "J)V"), + CONSCRYPT_NATIVE_METHOD(setSessionIdContextSha256, "(J" REF_SSL "[B)V"), CONSCRYPT_NATIVE_METHOD(SSL_set_session_creation_enabled, "(J" REF_SSL "Z)V"), CONSCRYPT_NATIVE_METHOD(SSL_session_reused, "(J" REF_SSL ")Z"), CONSCRYPT_NATIVE_METHOD(SSL_accept_renegotiations, "(J" REF_SSL ")V"), @@ -13028,6 +13375,7 @@ static JNINativeMethod sNativeCryptoMethods[] = { CONSCRYPT_NATIVE_METHOD(SSL_get_servername, "(J" REF_SSL ")Ljava/lang/String;"), CONSCRYPT_NATIVE_METHOD(SSL_get_current_cipher, "(J" REF_SSL ")Ljava/lang/String;"), CONSCRYPT_NATIVE_METHOD(SSL_set1_groups, "(J" REF_SSL "[I)V"), + CONSCRYPT_NATIVE_METHOD(SSL_set_verify_algorithm_prefs, "(J" REF_SSL "[I)V"), CONSCRYPT_NATIVE_METHOD(SSL_get_curve_name, "(J" REF_SSL ")Ljava/lang/String;"), CONSCRYPT_NATIVE_METHOD(SSL_get_version, "(J" REF_SSL ")Ljava/lang/String;"), CONSCRYPT_NATIVE_METHOD(SSL_get0_peer_certificates, "(J" REF_SSL ")[[B"), @@ -13073,6 +13421,8 @@ static JNINativeMethod sNativeCryptoMethods[] = { CONSCRYPT_NATIVE_METHOD(usesBoringSsl_FIPS_mode, "()Z"), CONSCRYPT_NATIVE_METHOD(Scrypt_generate_key, "([B[BIIII)[B"), CONSCRYPT_NATIVE_METHOD(SSL_CTX_set_spake_credential, "([B[B[B[BZIJ" REF_SSL_CTX ")V"), + CONSCRYPT_NATIVE_METHOD(SSL_set1_requested_trust_anchors, "(J" REF_SSL "[B)V"), + CONSCRYPT_NATIVE_METHOD(SSL_get0_peer_available_trust_anchors, "(J" REF_SSL ")[B"), // FOR ECH TESTING CONSCRYPT_NATIVE_METHOD(SSL_set_enable_ech_grease, "(J" REF_SSL "Z)V"), diff --git a/common/src/main/java/org/conscrypt/AbstractSessionContext.java b/common/src/main/java/org/conscrypt/AbstractSessionContext.java index 04ff91843..e1b86aee4 100644 --- a/common/src/main/java/org/conscrypt/AbstractSessionContext.java +++ b/common/src/main/java/org/conscrypt/AbstractSessionContext.java @@ -275,7 +275,8 @@ protected void finalize() throws Throwable { /** * Adds the given session to the cache. */ - final void cacheSession(NativeSslSession session) { + @Internal + public final void cacheSession(NativeSslSession session) { byte[] id = session.getId(); if (id == null || id.length == 0) { return; @@ -314,7 +315,8 @@ final void removeSession(NativeSslSession session) { * Called for server sessions only. Retrieves the session by its ID. Overridden by * {@link ServerSessionContext} to */ - final NativeSslSession getSessionFromCache(byte[] sessionId) { + @Internal + public final NativeSslSession getSessionFromCache(byte[] sessionId) { if (sessionId == null) { return null; } diff --git a/common/src/main/java/org/conscrypt/ActiveSession.java b/common/src/main/java/org/conscrypt/ActiveSession.java index 7fea51028..56bb27a7c 100644 --- a/common/src/main/java/org/conscrypt/ActiveSession.java +++ b/common/src/main/java/org/conscrypt/ActiveSession.java @@ -137,6 +137,13 @@ public String getRequestedServerName() { } } + @Override + public String getEchNameOverride() { + synchronized (ssl) { + return ssl.getEchNameOverride(); + } + } + @Override public void invalidate() { synchronized (ssl) { @@ -320,6 +327,7 @@ private void configurePeer(String peerHost, int peerPort, X509Certificate[] peer void onPeerCertificateAvailable(String peerHost, int peerPort) throws CertificateException { synchronized (ssl) { id = null; + this.protocol = null; if (localCertificates == null) { this.localCertificates = ssl.getLocalCertificates(); } diff --git a/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java b/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java index 36c534f6b..8cc5059f3 100644 --- a/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java +++ b/common/src/main/java/org/conscrypt/ApplicationProtocolSelectorAdapter.java @@ -28,7 +28,7 @@ * An adapter to bridge between the native code and the {@link ApplicationProtocolSelector} API. */ final class ApplicationProtocolSelectorAdapter { - private static final int NO_PROTOCOL_SELECTED = -1; + static final int NO_PROTOCOL_SELECTED = -1; private final SSLEngine engine; private final SSLSocket socket; diff --git a/common/src/main/java/org/conscrypt/ConscryptEngine.java b/common/src/main/java/org/conscrypt/ConscryptEngine.java index 61486908b..6417d8ef5 100644 --- a/common/src/main/java/org/conscrypt/ConscryptEngine.java +++ b/common/src/main/java/org/conscrypt/ConscryptEngine.java @@ -1727,7 +1727,7 @@ void setApplicationProtocolSelector(ApplicationProtocolSelectorAdapter adapter) public int selectApplicationProtocol(byte[] protocols) { ApplicationProtocolSelectorAdapter adapter = sslParameters.getApplicationProtocolSelector(); if (adapter == null) { - return NativeConstants.SSL_TLSEXT_ERR_NOACK; + return ApplicationProtocolSelectorAdapter.NO_PROTOCOL_SELECTED; } return adapter.selectApplicationProtocol(protocols); } diff --git a/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java b/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java index 3725755d7..cb720946c 100644 --- a/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java +++ b/common/src/main/java/org/conscrypt/ConscryptEngineSocket.java @@ -143,51 +143,71 @@ public void onHandshakeFinished() { // references to the given ConscryptEngineSocket. Our internal engine will call // the SSLEngine-receiving methods, but our callers expect the SSLSocket-receiving // methods to get called. - @SuppressWarnings("CustomX509TrustManager") private static X509TrustManager getDelegatingTrustManager(final X509TrustManager delegate, final ConscryptEngineSocket socket) { if (delegate instanceof X509ExtendedTrustManager) { - final X509ExtendedTrustManager extendedDelegate = (X509ExtendedTrustManager) delegate; - return new X509ExtendedTrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s, - Socket socket) throws CertificateException { - throw new AssertionError("Should not be called"); - } - @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s, - Socket socket) throws CertificateException { - throw new AssertionError("Should not be called"); - } - @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s, - SSLEngine sslEngine) throws CertificateException { - extendedDelegate.checkClientTrusted(x509Certificates, s, socket); - } - @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s, - SSLEngine sslEngine) throws CertificateException { - extendedDelegate.checkServerTrusted(x509Certificates, s, socket); - } - @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) - throws CertificateException { - extendedDelegate.checkClientTrusted(x509Certificates, s); - } - @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) - throws CertificateException { - extendedDelegate.checkServerTrusted(x509Certificates, s); - } - @Override - public X509Certificate[] getAcceptedIssuers() { - return extendedDelegate.getAcceptedIssuers(); - } - }; + return new DelegatingTrustManager((X509ExtendedTrustManager) delegate, socket); } return delegate; } + @SuppressWarnings("CustomX509TrustManager") + static final class DelegatingTrustManager extends X509ExtendedTrustManager { + private final X509ExtendedTrustManager extendedDelegate; + private final ConscryptEngineSocket socket; + + DelegatingTrustManager(X509ExtendedTrustManager extendedDelegate, + ConscryptEngineSocket socket) { + this.extendedDelegate = extendedDelegate; + this.socket = socket; + } + + X509ExtendedTrustManager getDelegate() { + return extendedDelegate; + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) + throws CertificateException { + throw new AssertionError("Should not be called"); + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) + throws CertificateException { + throw new AssertionError("Should not be called"); + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s, + SSLEngine sslEngine) throws CertificateException { + extendedDelegate.checkClientTrusted(x509Certificates, s, socket); + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s, + SSLEngine sslEngine) throws CertificateException { + extendedDelegate.checkServerTrusted(x509Certificates, s, socket); + } + + @Override + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { + extendedDelegate.checkClientTrusted(x509Certificates, s); + } + + @Override + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { + extendedDelegate.checkServerTrusted(x509Certificates, s); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return extendedDelegate.getAcceptedIssuers(); + } + } + @Override public final SSLParameters getSSLParameters() { return engine.getSSLParameters(); diff --git a/common/src/main/java/org/conscrypt/ConscryptSession.java b/common/src/main/java/org/conscrypt/ConscryptSession.java index 77af0ff88..f655713f9 100644 --- a/common/src/main/java/org/conscrypt/ConscryptSession.java +++ b/common/src/main/java/org/conscrypt/ConscryptSession.java @@ -57,4 +57,12 @@ interface ConscryptSession extends SSLSession { public String[] getPeerSupportedSignatureAlgorithms(); public String[] getLocalSupportedSignatureAlgorithms(); + + /** + * Returns the ECH public name that the peer certificate must be authenticated against if + * this client offered ECH and the server rejected it, or {@code null} otherwise. When + * non-null, the handshake will never complete; it only authenticates the server's retry + * configs (RFC 9849, section 6.1.7). + */ + String getEchNameOverride(); } diff --git a/common/src/main/java/org/conscrypt/EvpMdRef.java b/common/src/main/java/org/conscrypt/EvpMdRef.java index 349157a97..e9e0d98e8 100644 --- a/common/src/main/java/org/conscrypt/EvpMdRef.java +++ b/common/src/main/java/org/conscrypt/EvpMdRef.java @@ -154,5 +154,23 @@ static final class SHA512 { private SHA512() {} } + /** + * SHAKE256 with a fixed 512-bit output, i.e. the "SHAKE256-512" JCA algorithm. + * + *

SHAKE256 is an extendable-output function (XOF), so its output length is not a property + * of the underlying {@code EVP_MD}. The output must therefore be produced with + * {@link NativeCrypto#EVP_DigestFinalXOF} rather than {@link NativeCrypto#EVP_DigestFinal_ex}, + * and {@link #SIZE_BYTES} is the fixed output length of this JCA algorithm rather than + * {@code EVP_MD_size(EVP_MD)}. + */ + static final class Shake256_512 { + static final String JCA_NAME = "SHAKE256-512"; + static final String OID = "2.16.840.1.101.3.4.2.12"; + static final long EVP_MD = NativeCrypto.EVP_get_digestbyname("shake256"); + static final int SIZE_BYTES = 64; + + private Shake256_512() {} + } + private EvpMdRef() {} } diff --git a/common/src/main/java/org/conscrypt/ExternalSession.java b/common/src/main/java/org/conscrypt/ExternalSession.java index 3e60c5d08..62517c60d 100644 --- a/common/src/main/java/org/conscrypt/ExternalSession.java +++ b/common/src/main/java/org/conscrypt/ExternalSession.java @@ -69,6 +69,11 @@ public byte[] getPeerSignedCertificateTimestamp() { return provider.provideSession().getPeerSignedCertificateTimestamp(); } + @Override + public String getEchNameOverride() { + return provider.provideSession().getEchNameOverride(); + } + @Override public byte[] getId() { return provider.provideSession().getId(); diff --git a/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java b/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java index 879730422..fe46c06bb 100644 --- a/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java +++ b/common/src/main/java/org/conscrypt/Java7ExtendedSSLSession.java @@ -64,6 +64,11 @@ public final byte[] getPeerSignedCertificateTimestamp() { return delegate.getPeerSignedCertificateTimestamp(); } + @Override + public final String getEchNameOverride() { + return delegate.getEchNameOverride(); + } + @Override public final byte[] getId() { return delegate.getId(); diff --git a/common/src/main/java/org/conscrypt/NativeCrypto.java b/common/src/main/java/org/conscrypt/NativeCrypto.java index cd8642c88..4f88790d4 100644 --- a/common/src/main/java/org/conscrypt/NativeCrypto.java +++ b/common/src/main/java/org/conscrypt/NativeCrypto.java @@ -309,6 +309,22 @@ static native int ECDH_compute_key(byte[] out, int outOffset, NativeRef.EVP_PKEY // android-add: @FastNative static native byte[] MLDSA87_public_key_from_seed(byte[] privateKeySeed); + // --- MLDSA (all parameter sets) --------------------------------------------- + + /** + * Signs the 64-byte ML-DSA message representative {@code mu} with the ML-DSA private key + * {@code pkey} and returns the encoded signature. This is the "external mu" variant of + * ML-DSA.Sign (FIPS 204, Algorithm 2): {@code mu} must have been computed as + * {@code SHAKE256(SHAKE256(pk, 64) || 0x00 || |ctx| || ctx || M, 64)} for the public key + * {@code pk} of the same key pair, so the resulting signature verifies as a regular ML-DSA + * signature of the message {@code M} under the context string {@code ctx}. Throws an + * {@link InvalidKeyException} if {@code pkey} is not an ML-DSA private key and an + * {@link IllegalArgumentException} if {@code mu} is not 64 bytes long. + */ + // android-add: @FastNative + static native byte[] MLDSA_sign_message_representative(NativeRef.EVP_PKEY pkey, byte[] mu) + throws InvalidKeyException; + // --- SLHDSA_SHA2_128S -------------------------------------------------------------- static native void SLHDSA_SHA2_128S_generate_key(byte[] outPublicKey, byte[] outPrivateKey); @@ -403,6 +419,16 @@ static native void EVP_DigestUpdate(NativeRef.EVP_MD_CTX ctx, byte[] buffer, int // android-add: @FastNative static native int EVP_DigestFinal_ex(NativeRef.EVP_MD_CTX ctx, byte[] hash, int offset); + /** + * Writes {@code length} bytes of output from the extendable-output function (XOF) in + * {@code ctx} to {@code out} and then cleanses and resets {@code ctx}, which must be + * re-initialized with {@link #EVP_DigestInit_ex} before it can be used again. Throws if the + * digest in {@code ctx} is not an XOF (e.g. SHAKE256). + */ + // android-add: @FastNative + static native void EVP_DigestFinalXOF(NativeRef.EVP_MD_CTX ctx, byte[] out, int offset, + int length); + // --- Signature handling functions ---------------------------------------- // android-add: @FastNative @@ -1607,7 +1633,7 @@ static String[] checkEnabledProtocols(String[] protocols) { if (!Arrays.asList(SUPPORTED_PROTOCOLS).contains(protocol)) { String message = "protocol " + protocol + " is not supported"; if (protocol.equals(DEPRECATED_PROTOCOL_TLSV1) - || protocol.equals(DEPRECATED_PROTOCOL_TLSV1_1)) { + || protocol.equals(DEPRECATED_PROTOCOL_TLSV1_1)) { message += Platform.getTlsV1DeprecationNote(); } throw new IllegalArgumentException(message); @@ -1699,6 +1725,9 @@ static String[] checkEnabledCipherSuites(String[] cipherSuites) { static native void SSL_set_session(long ssl, NativeSsl ssl_holder, long sslSessionNativePointer) throws SSLException; + // android-add: @FastNative + static native void setSessionIdContextSha256(long ssl, NativeSsl ssl_holder, byte[] context); + // android-add: @FastNative static native void SSL_set_session_creation_enabled(long ssl, NativeSsl ssl_holder, boolean creationEnabled) @@ -1726,6 +1755,9 @@ static native void SSL_set_tlsext_host_name(long ssl, NativeSsl ssl_holder, Stri public static native void SSL_set1_groups(long ssl, NativeSsl sslHolder, int[] groups); + public static native void SSL_set_verify_algorithm_prefs(long ssl, NativeSsl sslHolder, + int[] prefs); + public static native String SSL_get_curve_name(long ssl, NativeSsl sslHolder); /** @@ -2029,6 +2061,32 @@ static native byte[] Scrypt_generate_key(byte[] password, byte[] salt, int n, in // android-add: @CriticalNative static native boolean usesBoringSsl_FIPS_mode(); + /* Trust Anchor Identifiers (draft-ietf-tls-trust-anchor-ids) */ + + /* + * All trust anchor ID lists below are in wire format: a series of non-empty, 8-bit + * length-prefixed binary trust anchor IDs. See TrustAnchorIds for encoding helpers. + */ + + /** + * Client: configures the trust anchor IDs to request in the {@code trust_anchors} ClientHello + * extension. An empty list still sends the extension, signalling support for the retry flow. + * + * @throws IllegalArgumentException if {@code ids} is not a valid wire-format trust anchor ID + * list (e.g. a truncated length prefix, or an ID that is not a valid RELATIVE-OID of at + * most 32 bytes) + */ + // android-add: @FastNative + static native void SSL_set1_requested_trust_anchors(long ssl, NativeSsl ssl_holder, byte[] ids) + throws SSLException; + + /** + * Client: returns the server's available trust anchor IDs in wire format, or {@code null} if + * the server did not send any. Only meaningful during certificate verification. + */ + // android-add: @FastNative + static native byte[] SSL_get0_peer_available_trust_anchors(long ssl, NativeSsl ssl_holder); + /* ECH */ static native void SSL_set_enable_ech_grease(long ssl, NativeSsl ssl_holder, boolean enable); diff --git a/common/src/main/java/org/conscrypt/NativeSsl.java b/common/src/main/java/org/conscrypt/NativeSsl.java index d9d61c30e..9e4c09d66 100644 --- a/common/src/main/java/org/conscrypt/NativeSsl.java +++ b/common/src/main/java/org/conscrypt/NativeSsl.java @@ -31,6 +31,7 @@ import org.conscrypt.metrics.TlsEncryptedClientHelloHandshake; import java.io.IOException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.PrivateKey; @@ -40,6 +41,7 @@ import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.HashSet; +import java.util.Locale; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -55,6 +57,10 @@ * A utility wrapper that abstracts operations on the underlying native SSL instance. */ final class NativeSsl { + private static final byte CLIENT_AUTH_NONE = 0; + private static final byte CLIENT_AUTH_WANT = 1; + private static final byte CLIENT_AUTH_NEED = 2; + private final SSLParametersImpl parameters; private final SSLHandshakeCallbacks handshakeCallbacks; private final AliasChooser aliasChooser; @@ -62,6 +68,7 @@ final class NativeSsl { private X509Certificate[] localCertificates; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private volatile long ssl; + private volatile byte serverClientAuthMode = CLIENT_AUTH_NONE; private final TlsEncryptedClientHelloHandshake.Builder echHandshakeBuilder = new TlsEncryptedClientHelloHandshake.Builder(); @@ -412,21 +419,173 @@ static int[] parseNamedGroupsProperty(String namedGroupsProperty) { return toBoringSslGroups(namedGroups); } - private static final int[] DEFAULT_BORINGSSL_NAMED_GROUPS = new int[0]; + // IMPLEMENTATION NOTE: Default named groups (key exchange curves and KEMs) are explicitly + // pinned in Java rather than inherited from BoringSSL's C++ defaults + // (DefaultSupportedGroupIds()). Modifying this list alters the TLS ClientHello + // (supported_groups and key_share extensions) on the wire, which can break handshakes with + // non-compliant middleboxes or servers. On Android, any change to the default named groups + // MUST be gated behind an aconfig feature flag and an AppCompat (@ChangeId) gate via + // Platform.isPqcDefaultEnabled() and NativeSsl.getDefaultNamedGroups(). - private static final int[] DEFAULT_CLASSICAL_NAMED_GROUPS = - toBoringSslGroups(new String[] {"X25519", "P-256", "P-384"}); + /** + * Default TLS named groups with Post-Quantum Cryptography (X25519MLKEM768) enabled, in + * preference order. + */ + static final String[] DEFAULT_PQC_NAMED_GROUPS = new String[] { + "X25519MLKEM768", + "X25519", + "P-256", + "P-384", + }; + + /** Classical-only default TLS named groups, in preference order. */ + static final String[] DEFAULT_CLASSICAL_NAMED_GROUPS = new String[] { + "X25519", + "P-256", + "P-384", + }; + + private static final int[] DEFAULT_PQC_GROUP_IDS = + toBoringSslGroups(DEFAULT_PQC_NAMED_GROUPS); + private static final int[] DEFAULT_CLASSICAL_GROUP_IDS = + toBoringSslGroups(DEFAULT_CLASSICAL_NAMED_GROUPS); + + static int[] getDefaultNamedGroups() { + // Must stay dynamic: isPqcDefaultEnabled() is per-app / post-fork on Android. + return (Platform.isPqcDefaultEnabled() ? DEFAULT_PQC_GROUP_IDS + : DEFAULT_CLASSICAL_GROUP_IDS) + .clone(); + } private static void setDefaultNamedGroups(long ssl, NativeSsl sslHolder) { - if (Platform.isPqcDefaultEnabled()) { - // When the groups list is empty, BoringSSL's default named groups - // (DefaultSupportedGroupIds()) are used as the single source of truth. - NativeCrypto.SSL_set1_groups(ssl, sslHolder, DEFAULT_BORINGSSL_NAMED_GROUPS); - } else { - NativeCrypto.SSL_set1_groups(ssl, sslHolder, DEFAULT_CLASSICAL_NAMED_GROUPS); + // Explicitly configure the platform's pinned default named groups rather than passing + // an empty array (which would implicitly inherit BoringSSL's C++ defaults). + NativeCrypto.SSL_set1_groups(ssl, sslHolder, getDefaultNamedGroups()); + } + + private static int toBoringSslSignatureAlgorithm(String signatureAlgorithm) { + switch (signatureAlgorithm) { + case "mldsa44": + case "ML-DSA-44": + return NativeConstants.SSL_SIGN_ML_DSA_44; + case "mldsa65": + case "ML-DSA-65": + return NativeConstants.SSL_SIGN_ML_DSA_65; + case "mldsa87": + case "ML-DSA-87": + return NativeConstants.SSL_SIGN_ML_DSA_87; + case "ecdsa_secp256r1_sha256": + return NativeConstants.SSL_SIGN_ECDSA_SECP256R1_SHA256; + case "ecdsa_secp384r1_sha384": + return NativeConstants.SSL_SIGN_ECDSA_SECP384R1_SHA384; + case "ecdsa_secp521r1_sha512": + return NativeConstants.SSL_SIGN_ECDSA_SECP521R1_SHA512; + case "ecdsa_sha1": + return NativeConstants.SSL_SIGN_ECDSA_SHA1; + case "rsa_pss_rsae_sha256": + return NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA256; + case "rsa_pss_rsae_sha384": + return NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA384; + case "rsa_pss_rsae_sha512": + return NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA512; + case "rsa_pkcs1_sha256": + return NativeConstants.SSL_SIGN_RSA_PKCS1_SHA256; + case "rsa_pkcs1_sha384": + return NativeConstants.SSL_SIGN_RSA_PKCS1_SHA384; + case "rsa_pkcs1_sha512": + return NativeConstants.SSL_SIGN_RSA_PKCS1_SHA512; + case "rsa_pkcs1_sha1": + return NativeConstants.SSL_SIGN_RSA_PKCS1_SHA1; + case "ed25519": + return NativeConstants.SSL_SIGN_ED25519; + default: + return -1; // Unknown signature algorithm. } } + static int[] toBoringSslSignatureAlgorithms(String[] signatureAlgorithms) { + int[] outputAlgs = new int[signatureAlgorithms.length]; + int i = 0; + for (String signatureAlgorithm : signatureAlgorithms) { + int alg = toBoringSslSignatureAlgorithm(signatureAlgorithm); + if (alg > 0) { + outputAlgs[i] = alg; + i++; + } + } + if (i == 0) { + throw new IllegalArgumentException( + "No valid known signature algorithm found in: " + + Arrays.toString(signatureAlgorithms)); + } + if (i < signatureAlgorithms.length) { + return Arrays.copyOf(outputAlgs, i); + } + return outputAlgs; + } + + // IMPLEMENTATION NOTE: Default signature verification algorithms (signature_algorithms + // extension) are explicitly pinned in Java rather than inherited from BoringSSL's C++ defaults + // (kVerifySignatureAlgorithms). Modifying this list alters the TLS ClientHello + // (signature_algorithms extension) and CertificateRequest on the wire, which can break + // handshakes with non-compliant middleboxes or peers. On Android, any change to the default + // signature algorithms MUST be gated behind an aconfig feature flag and an AppCompat + // (@ChangeId) gate via Platform.isPqcDefaultSignatureAlgorithmsEnabled() and + // NativeSsl.getDefaultSignatureAlgorithms(). + + /** + * Default TLS signature verification algorithms with Post-Quantum Cryptography (ML-DSA) + * enabled, in preference order. + */ + static final String[] DEFAULT_PQC_SIGNATURE_ALGORITHMS = new String[] { + "mldsa44", + "mldsa65", + "mldsa87", + "ecdsa_secp256r1_sha256", + "rsa_pss_rsae_sha256", + "rsa_pkcs1_sha256", + "ecdsa_secp384r1_sha384", + "rsa_pss_rsae_sha384", + "rsa_pkcs1_sha384", + "rsa_pss_rsae_sha512", + "rsa_pkcs1_sha512", + "rsa_pkcs1_sha1", + }; + + /** Classical-only default TLS signature verification algorithms, in preference order. */ + static final String[] DEFAULT_CLASSICAL_SIGNATURE_ALGORITHMS = new String[] { + "ecdsa_secp256r1_sha256", + "rsa_pss_rsae_sha256", + "rsa_pkcs1_sha256", + "ecdsa_secp384r1_sha384", + "rsa_pss_rsae_sha384", + "rsa_pkcs1_sha384", + "rsa_pss_rsae_sha512", + "rsa_pkcs1_sha512", + "rsa_pkcs1_sha1", + }; + + private static final int[] DEFAULT_PQC_SIGNATURE_ALGORITHM_IDS = + toBoringSslSignatureAlgorithms(DEFAULT_PQC_SIGNATURE_ALGORITHMS); + + private static final int[] DEFAULT_CLASSICAL_SIGNATURE_ALGORITHM_IDS = + toBoringSslSignatureAlgorithms(DEFAULT_CLASSICAL_SIGNATURE_ALGORITHMS); + + static int[] getDefaultSignatureAlgorithms() { + // Must stay dynamic: isPqcDefaultSignatureAlgorithmsEnabled() is per-app / post-fork on + // Android. + return Platform.isPqcDefaultSignatureAlgorithmsEnabled() + ? DEFAULT_PQC_SIGNATURE_ALGORITHM_IDS + : DEFAULT_CLASSICAL_SIGNATURE_ALGORITHM_IDS; + } + + private static void setDefaultSignatureAlgorithms(long ssl, NativeSsl sslHolder) { + // Explicitly configure the platform's pinned default signature verification algorithms + // rather than implicitly inheriting BoringSSL's C++ defaults (kVerifySignatureAlgorithms). + NativeCrypto.SSL_set_verify_algorithm_prefs(ssl, sslHolder, + getDefaultSignatureAlgorithms()); + } + void initialize(String hostname) throws IOException { boolean enableSessionCreation = parameters.getEnableSessionCreation(); if (!enableSessionCreation) { @@ -491,6 +650,8 @@ void initialize(String hostname) throws IOException { } } + setDefaultSignatureAlgorithms(ssl, this); + if (parameters.applicationProtocols.length > 0) { NativeCrypto.setApplicationProtocols(ssl, this, isClient(), parameters.applicationProtocols); @@ -535,8 +696,12 @@ void initialize(String hostname) throws IOException { } } + private static final byte[] SERVER_SID_CTX_DOMAIN = + "ConscryptServerSidCtx-v1\0".getBytes(StandardCharsets.US_ASCII); + void configureServerCertificate() throws IOException { - verifyWithSniMatchers(getRequestedServerName()); + String requestedServerName = getRequestedServerName(); + verifyWithSniMatchers(requestedServerName); if (isClient()) { return; } @@ -550,6 +715,56 @@ void configureServerCertificate() throws IOException { } } } + updateServerSessionIdContext(requestedServerName); + } + + private void updateServerSessionIdContext(String requestedServerName) { + // Resumed handshakes skip requesting and verifying the client certificate, so bind + // BoringSSL's session ID context to the per-connection settings that determine whether a + // client is accepted. Variable-length fields are length-prefixed to avoid collisions. + byte[] sniBytes = (requestedServerName == null) + ? null + : requestedServerName.toLowerCase(Locale.US).getBytes(StandardCharsets.UTF_8); + String endpointIdAlg = parameters.getEndpointIdentificationAlgorithm(); + byte[] endpointIdBytes = (endpointIdAlg == null || endpointIdAlg.isEmpty()) + ? null + : endpointIdAlg.toLowerCase(Locale.US).getBytes(StandardCharsets.UTF_8); + + // Allocate buffer for session ID context. + int length = SERVER_SID_CTX_DOMAIN.length + lengthPrefixedSize(sniBytes) + + 1 // serverClientAuthMode + + lengthPrefixedSize(endpointIdBytes); + ByteBuffer buf = ByteBuffer.allocate(length); + + // Write to session ID context buffer. + buf.put(SERVER_SID_CTX_DOMAIN); + putLengthPrefixedBytes(buf, sniBytes); + buf.put(serverClientAuthMode); + putLengthPrefixedBytes(buf, endpointIdBytes); + + // Set session ID context. + lock.readLock().lock(); + try { + if (!isClosed()) { + NativeCrypto.setSessionIdContextSha256(ssl, this, buf.array()); + } + } finally { + lock.readLock().unlock(); + } + } + + private static int lengthPrefixedSize(byte[] bytes) { + return 4 // size of bytes.length or size of -1 + + (bytes == null ? 0 : bytes.length); + } + + private static void putLengthPrefixedBytes(ByteBuffer buf, byte[] bytes) { + if (bytes == null) { + buf.putInt(-1); + } else { + buf.putInt(bytes.length); + buf.put(bytes); + } } private void verifyWithSniMatchers(String serverName) throws SSLHandshakeException { @@ -666,14 +881,17 @@ private void setCertificateValidation() throws SSLException { if (parameters.getNeedClientAuth()) { NativeCrypto.SSL_set_verify(ssl, this, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + serverClientAuthMode = CLIENT_AUTH_NEED; certRequested = true; // ... over just wanting it... } else if (parameters.getWantClientAuth()) { NativeCrypto.SSL_set_verify(ssl, this, SSL_VERIFY_PEER); + serverClientAuthMode = CLIENT_AUTH_WANT; certRequested = true; // ... and we must disable verification if we don't want client auth. } else { NativeCrypto.SSL_set_verify(ssl, this, SSL_VERIFY_NONE); + serverClientAuthMode = CLIENT_AUTH_NONE; certRequested = false; } diff --git a/common/src/main/java/org/conscrypt/NativeSslSession.java b/common/src/main/java/org/conscrypt/NativeSslSession.java index 078830004..899eabaf8 100644 --- a/common/src/main/java/org/conscrypt/NativeSslSession.java +++ b/common/src/main/java/org/conscrypt/NativeSslSession.java @@ -42,9 +42,12 @@ *

* This is abstract only to support mocking for tests. */ -abstract class NativeSslSession { +@Internal +public abstract class NativeSslSession { private static final Logger logger = Logger.getLogger(NativeSslSession.class.getName()); + NativeSslSession() {} + /** * Creates a new instance. Since BoringSSL does not provide an API to get access to all * session information via the SSL_SESSION, we get some values (e.g. peer certs) from @@ -78,6 +81,12 @@ private static byte[] getOcspResponse(ConscryptSession session) { * @return The new instance if successful. If unable to parse the bytes for any reason, returns * {@code null}. */ + @Internal + public static NativeSslSession newInstance(ClientSessionContext context, byte[] data, + String host, int port) { + return newInstance((AbstractSessionContext) context, data, host, port); + } + static NativeSslSession newInstance(AbstractSessionContext context, byte[] data, String host, int port) { ByteBuffer buf = ByteBuffer.wrap(data); @@ -200,7 +209,7 @@ static NativeSslSession newInstance(AbstractSessionContext context, byte[] data, * * @return session data as bytes or null if the session can't be converted */ - abstract byte[] toBytes(); + @Internal public abstract byte[] toBytes(); /** * Converts this object to a {@link SSLSession}. The returned session will support only a @@ -301,7 +310,7 @@ byte[] getPeerSignedCertificateTimestamp() { } @Override - byte[] toBytes() { + public byte[] toBytes() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos); diff --git a/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java b/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java index 1b744ed7d..6a6dffc30 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java +++ b/common/src/main/java/org/conscrypt/OpenSSLMessageDigestJDK.java @@ -37,6 +37,14 @@ public class OpenSSLMessageDigestJDK extends MessageDigestSpi implements Cloneab */ private final int size; + /** + * Whether the digest is an extendable-output function (XOF), such as SHAKE256. For an XOF, + * {@link #size} is the fixed output length of the JCA algorithm (e.g. 64 bytes for + * "SHAKE256-512") rather than a property of the EVP_MD, and the output is produced with + * EVP_DigestFinalXOF instead of EVP_DigestFinal_ex. + */ + private final boolean xof; + /** * Holds a dummy buffer for writing single bytes to the digest. */ @@ -50,17 +58,28 @@ public class OpenSSLMessageDigestJDK extends MessageDigestSpi implements Cloneab /** * Creates a new OpenSSLMessageDigest instance for the given algorithm name. */ - private OpenSSLMessageDigestJDK(long evp_md, int size) throws NoSuchAlgorithmException { - this.evp_md = evp_md; + private OpenSSLMessageDigestJDK(long evpMd, int size) { + this(evpMd, size, /* xof= */ false); + } + + /** + * Creates a new OpenSSLMessageDigest instance for the given algorithm name, producing + * {@code size} bytes of output. If {@code xof} is true, the algorithm is an extendable-output + * function and {@code size} may differ from the native EVP_MD size. + */ + private OpenSSLMessageDigestJDK(long evpMd, int size, boolean xof) { + this.evp_md = evpMd; this.size = size; + this.xof = xof; NativeRef.EVP_MD_CTX ctxLocal = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); this.ctx = ctxLocal; } - private OpenSSLMessageDigestJDK(long evp_md, int size, NativeRef.EVP_MD_CTX ctx, + private OpenSSLMessageDigestJDK(long evpMd, int size, boolean xof, NativeRef.EVP_MD_CTX ctx, boolean digestInitializedInContext) { - this.evp_md = evp_md; + this.evp_md = evpMd; this.size = size; + this.xof = xof; this.ctx = ctx; this.digestInitializedInContext = digestInitializedInContext; } @@ -143,11 +162,15 @@ protected synchronized void engineUpdate(ByteBuffer input) { protected synchronized byte[] engineDigest() { ensureDigestInitializedInContext(); final byte[] result = new byte[size]; - NativeCrypto.EVP_DigestFinal_ex(ctx, result, 0); + if (xof) { + NativeCrypto.EVP_DigestFinalXOF(ctx, result, 0, size); + } else { + NativeCrypto.EVP_DigestFinal_ex(ctx, result, 0); + } // Optimized reset path: - // 1. No need to wipe EVP_MD_CTX because EVP_DigestFinal_ex has already cleansed any - // sensitive state from it. + // 1. No need to wipe EVP_MD_CTX because EVP_DigestFinal_ex (or EVP_DigestFinalXOF) has + // already cleansed any sensitive state from it. // 2. Require EVP_DigestInit_ex to be invoked before this MessageDigestSpi starts computing // a new digest. digestInitializedInContext = false; @@ -191,6 +214,17 @@ public SHA512() throws NoSuchAlgorithmException { } } + /** + * SHAKE256 with a fixed 512-bit (64-byte) output. SHAKE256 is an extendable-output function, + * but the {@code MessageDigest} API only supports a fixed output length, so the length is part + * of the algorithm name ("SHAKE256-512"), consistent with the OpenJDK provider. + */ + public static final class Shake256_512 extends OpenSSLMessageDigestJDK { + public Shake256_512() { + super(EvpMdRef.Shake256_512.EVP_MD, EvpMdRef.Shake256_512.SIZE_BYTES, /* xof= */ true); + } + } + @Override public Object clone() { NativeRef.EVP_MD_CTX ctxCopy = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); @@ -199,6 +233,6 @@ public Object clone() { if (digestInitializedInContext) { NativeCrypto.EVP_MD_CTX_copy_ex(ctxCopy, ctx); } - return new OpenSSLMessageDigestJDK(evp_md, size, ctxCopy, digestInitializedInContext); + return new OpenSSLMessageDigestJDK(evp_md, size, xof, ctxCopy, digestInitializedInContext); } } diff --git a/common/src/main/java/org/conscrypt/OpenSSLProvider.java b/common/src/main/java/org/conscrypt/OpenSSLProvider.java index 295434d40..00fdb665b 100644 --- a/common/src/main/java/org/conscrypt/OpenSSLProvider.java +++ b/common/src/main/java/org/conscrypt/OpenSSLProvider.java @@ -176,6 +176,12 @@ public OpenSSLProvider(String providerName) { put("Alg.Alias.MessageDigest.SHA512", "SHA-512"); put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.3", "SHA-512"); + // SHAKE256 is an extendable-output function; "SHAKE256-512" is the fixed 512-bit output + // variant, named as in the OpenJDK provider. The OID is id-shake256 (RFC 8702), which + // denotes SHAKE256 with a 512-bit output when used as a message digest. + put("MessageDigest.SHAKE256-512", PREFIX + "OpenSSLMessageDigestJDK$Shake256_512"); + put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.12", "SHAKE256-512"); + // iso(1) member-body(2) US(840) rsadsi(113549) digestAlgorithm(2) md5(5) put("MessageDigest.MD5", PREFIX + "OpenSSLMessageDigestJDK$MD5"); put("Alg.Alias.MessageDigest.1.2.840.113549.2.5", "MD5"); @@ -305,7 +311,11 @@ public OpenSSLProvider(String providerName) { put("KeyPairGenerator.ML-KEM", PREFIX + "OpenSslMlKemKeyPairGenerator$MlKem"); put("KeyPairGenerator.ML-KEM-768", PREFIX + "OpenSslMlKemKeyPairGenerator$MlKem768"); + put("Alg.Alias.KeyPairGenerator.2.16.840.1.101.3.4.4.2", "ML-KEM-768"); + put("Alg.Alias.KeyPairGenerator.OID.2.16.840.1.101.3.4.4.2", "ML-KEM-768"); put("KeyPairGenerator.ML-KEM-1024", PREFIX + "OpenSslMlKemKeyPairGenerator$MlKem1024"); + put("Alg.Alias.KeyPairGenerator.2.16.840.1.101.3.4.4.3", "ML-KEM-1024"); + put("Alg.Alias.KeyPairGenerator.OID.2.16.840.1.101.3.4.4.3", "ML-KEM-1024"); put("KeyPairGenerator.XWING", PREFIX + "OpenSslXwingKeyPairGenerator"); @@ -389,7 +399,11 @@ public OpenSSLProvider(String providerName) { put("KeyFactory.ML-KEM", PREFIX + "OpenSslMlKemKeyFactory$MlKem"); put("KeyFactory.ML-KEM-768", PREFIX + "OpenSslMlKemKeyFactory$MlKem768"); + put("Alg.Alias.KeyFactory.2.16.840.1.101.3.4.4.2", "ML-KEM-768"); + put("Alg.Alias.KeyFactory.OID.2.16.840.1.101.3.4.4.2", "ML-KEM-768"); put("KeyFactory.ML-KEM-1024", PREFIX + "OpenSslMlKemKeyFactory$MlKem1024"); + put("Alg.Alias.KeyFactory.2.16.840.1.101.3.4.4.3", "ML-KEM-1024"); + put("Alg.Alias.KeyFactory.OID.2.16.840.1.101.3.4.4.3", "ML-KEM-1024"); put("KeyFactory.XWING", PREFIX + "OpenSslXwingKeyFactory"); @@ -523,6 +537,17 @@ public OpenSSLProvider(String providerName) { putSignatureImplClass("ML-DSA-87", "OpenSslSignatureMlDsa$MlDsa87"); put("Alg.Alias.Signature.2.16.840.1.101.3.4.3.19", "ML-DSA-87"); put("Alg.Alias.Signature.OID.2.16.840.1.101.3.4.3.19", "ML-DSA-87"); + // "External mu" ML-DSA signs a precomputed 64-byte ML-DSA message representative mu + // (FIPS 204, Algorithm 7, line 6) instead of the message itself; see + // OpenSslSignatureExternalMuMlDsa for how mu is computed (e.g. with the "SHAKE256-512" + // MessageDigest). It only supports signing: the result is a regular ML-DSA signature, which + // is verified with "ML-DSA" and the original message. Context strings are currently not + // supported (mu must be computed with an empty context string). There are no OID aliases + // because no OIDs are assigned to external-mu ML-DSA. + putSignatureImplClass("EXTERNAL-MU-ML-DSA", "OpenSslSignatureExternalMuMlDsa$MlDsa"); + putSignatureImplClass("EXTERNAL-MU-ML-DSA-44", "OpenSslSignatureExternalMuMlDsa$MlDsa44"); + putSignatureImplClass("EXTERNAL-MU-ML-DSA-65", "OpenSslSignatureExternalMuMlDsa$MlDsa65"); + putSignatureImplClass("EXTERNAL-MU-ML-DSA-87", "OpenSslSignatureExternalMuMlDsa$MlDsa87"); putSignatureImplClass("MLDSA44-RSA2048-PSS-SHA256", "OpenSslSignatureCompositeMlDsa$Mldsa44Rsa2048PssSha256"); put("Alg.Alias.Signature.1.3.6.1.5.5.7.6.37", "MLDSA44-RSA2048-PSS-SHA256"); @@ -806,7 +831,11 @@ public OpenSSLProvider(String providerName) { // Standard JCA KEM algorithm names per Java Security Standard Algorithm Names spec. put("KEM.ML-KEM", PREFIX + "OpenSslMlKem$MlKem"); put("KEM.ML-KEM-768", PREFIX + "OpenSslMlKem$MlKem768"); + put("Alg.Alias.KEM.2.16.840.1.101.3.4.4.2", "ML-KEM-768"); + put("Alg.Alias.KEM.OID.2.16.840.1.101.3.4.4.2", "ML-KEM-768"); put("KEM.ML-KEM-1024", PREFIX + "OpenSslMlKem$MlKem1024"); + put("Alg.Alias.KEM.2.16.840.1.101.3.4.4.3", "ML-KEM-1024"); + put("Alg.Alias.KEM.OID.2.16.840.1.101.3.4.4.3", "ML-KEM-1024"); } } diff --git a/common/src/main/java/org/conscrypt/OpenSslSignatureExternalMuMlDsa.java b/common/src/main/java/org/conscrypt/OpenSslSignatureExternalMuMlDsa.java new file mode 100644 index 000000000..bec174de4 --- /dev/null +++ b/common/src/main/java/org/conscrypt/OpenSslSignatureExternalMuMlDsa.java @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * 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 org.conscrypt; + +import java.security.InvalidKeyException; +import java.security.InvalidParameterException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SignatureException; +import java.security.SignatureSpi; + +/** + * Implements the JDK Signature interface for "external mu" ML-DSA signature generation using + * BoringSSL. + * + *

Instead of the message itself, the data passed to {@code update} must be the 64-byte ML-DSA + * message representative mu of the message (FIPS 204, Algorithm 7, line 6), which the caller + * computes with an empty context string as {@code SHAKE256-512(tr || 0x00 || 0x00 || message)}, + * where {@code tr = SHAKE256-512(rawPublicKey)} is the hash of the raw encoding of the signer's + * public key, for example with Conscrypt's {@code "SHAKE256-512"} {@code MessageDigest}. This lets + * resource-constrained signers delegate the hashing of long messages to another party. Context + * strings are currently not supported: mu must be computed with an empty context string. + * + *

The resulting signature is a regular ML-DSA signature of the message, so it is verified with + * the {@code "ML-DSA"} {@code Signature} and the original message. Verification is therefore not + * supported by this class: {@code initVerify} and {@code verify} always throw an {@link + * UnsupportedOperationException}. + */ +@Internal +public abstract class OpenSslSignatureExternalMuMlDsa extends SignatureSpi { + /** The length in bytes of an ML-DSA message representative mu. */ + private static final int MU_LENGTH = 64; + + private static final OpenSslMlDsaKeyFactory keyFactory = new OpenSslMlDsaKeyFactory.MlDsa(); + + /** + * The current OpenSSL key we're operating on. + */ + private OpenSSLKey key; + + /** + * Buffer to hold the message representative to be signed. + */ + private final ExposedByteArrayOutputStream buffer = new ExposedByteArrayOutputStream(); + + abstract boolean supportsAlgorithm(MlDsaAlgorithm algorithm); + + /** EXTERNAL-MU-ML-DSA */ + public static class MlDsa extends OpenSslSignatureExternalMuMlDsa { + public MlDsa() { + super(); + } + @Override + boolean supportsAlgorithm(MlDsaAlgorithm algorithm) { + return algorithm.equals(MlDsaAlgorithm.ML_DSA_44) + || algorithm.equals(MlDsaAlgorithm.ML_DSA_65) + || algorithm.equals(MlDsaAlgorithm.ML_DSA_87); + } + } + + /** EXTERNAL-MU-ML-DSA-44 */ + public static class MlDsa44 extends OpenSslSignatureExternalMuMlDsa { + public MlDsa44() { + super(); + } + @Override + boolean supportsAlgorithm(MlDsaAlgorithm algorithm) { + return algorithm.equals(MlDsaAlgorithm.ML_DSA_44); + } + } + + /** EXTERNAL-MU-ML-DSA-65 */ + public static class MlDsa65 extends OpenSslSignatureExternalMuMlDsa { + public MlDsa65() { + super(); + } + @Override + boolean supportsAlgorithm(MlDsaAlgorithm algorithm) { + return algorithm.equals(MlDsaAlgorithm.ML_DSA_65); + } + } + + /** EXTERNAL-MU-ML-DSA-87 */ + public static class MlDsa87 extends OpenSslSignatureExternalMuMlDsa { + public MlDsa87() { + super(); + } + @Override + boolean supportsAlgorithm(MlDsaAlgorithm algorithm) { + return algorithm.equals(MlDsaAlgorithm.ML_DSA_87); + } + } + + @Override + protected void engineUpdate(byte input) { + buffer.write(input); + } + + @Override + protected void engineUpdate(byte[] input, int offset, int len) { + buffer.write(input, offset, len); + } + + @Override + // engineGetParameter is deprecated in SignatureSpi, but abstract, so it must be implemented. + @SuppressWarnings("deprecation") + protected Object engineGetParameter(String param) throws InvalidParameterException { + return null; + } + + @Override + protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException { + OpenSslMlDsaPrivateKey conscryptPrivateKey = + (OpenSslMlDsaPrivateKey) keyFactory.engineTranslateKey(privateKey); + MlDsaAlgorithm algorithm = conscryptPrivateKey.getMlDsaAlgorithm(); + if (!supportsAlgorithm(algorithm)) { + throw new InvalidKeyException("Key version mismatch: " + algorithm); + } + OpenSSLKey keyLocal = conscryptPrivateKey.getOpenSSLKey(); + if (keyLocal == null) { + throw new InvalidKeyException("Key is destroyed"); + } + this.key = keyLocal; + buffer.reset(); + } + + @Override + protected void engineInitVerify(PublicKey publicKey) { + throw new UnsupportedOperationException( + "EXTERNAL-MU-ML-DSA does not support verification. Verify the signature with " + + "ML-DSA and the original message."); + } + + @Override + // engineSetParameter is deprecated in SignatureSpi, but abstract, so it must be implemented. + @SuppressWarnings("deprecation") + protected void engineSetParameter(String param, Object value) throws InvalidParameterException { + } + + @Override + protected byte[] engineSign() throws SignatureException { + if (key == null) { + throw new SignatureException("No key provided"); + } + if (buffer.size() != MU_LENGTH) { + buffer.reset(); + throw new SignatureException("The input must be the " + MU_LENGTH + + "-byte ML-DSA message representative mu"); + } + byte[] mu = buffer.toByteArray(); + buffer.reset(); + try { + return NativeCrypto.MLDSA_sign_message_representative(key.getNativeRef(), mu); + } catch (InvalidKeyException e) { + // Cannot happen, since engineInitSign only accepts ML-DSA private keys. + throw new SignatureException(e); + } + } + + @Override + protected boolean engineVerify(byte[] sigBytes) { + throw new UnsupportedOperationException( + "EXTERNAL-MU-ML-DSA does not support verification. Verify the signature with " + + "ML-DSA and the original message."); + } +} diff --git a/common/src/main/java/org/conscrypt/SSLNullSession.java b/common/src/main/java/org/conscrypt/SSLNullSession.java index e6c8fad32..436d994b7 100644 --- a/common/src/main/java/org/conscrypt/SSLNullSession.java +++ b/common/src/main/java/org/conscrypt/SSLNullSession.java @@ -71,6 +71,11 @@ public byte[] getPeerSignedCertificateTimestamp() { return EmptyArray.BYTE; } + @Override + public String getEchNameOverride() { + return null; + } + @Override public int getApplicationBufferSize() { return NativeConstants.SSL3_RT_MAX_PLAIN_LENGTH; diff --git a/common/src/main/java/org/conscrypt/SSLParametersImpl.java b/common/src/main/java/org/conscrypt/SSLParametersImpl.java index 18467f7c6..4cb69f315 100644 --- a/common/src/main/java/org/conscrypt/SSLParametersImpl.java +++ b/common/src/main/java/org/conscrypt/SSLParametersImpl.java @@ -261,12 +261,20 @@ void initSpake() throws KeyManagementException { } } + private static X509TrustManager unwrapTrustManager(X509TrustManager tm) { + if (tm instanceof ConscryptEngineSocket.DelegatingTrustManager) { + return ((ConscryptEngineSocket.DelegatingTrustManager) tm).getDelegate(); + } + return tm; + } + private Method getNetworkSecurityPolicyMethod(X509TrustManager tm) { - if (tm == null) { + X509TrustManager unwrapped = unwrapTrustManager(tm); + if (unwrapped == null) { return null; } try { - return tm.getClass().getMethod("getNetworkSecurityPolicy"); + return unwrapped.getClass().getMethod("getNetworkSecurityPolicy"); } catch (NoSuchMethodException ignored) { return null; } @@ -841,7 +849,8 @@ NetworkSecurityPolicy getPolicy() { // NetworkSecurityTrustManager), which we need to query. if (getNetworkSecurityPolicy != null) { try { - Object objPolicy = getNetworkSecurityPolicy.invoke(x509TrustManager); + Object objPolicy = + getNetworkSecurityPolicy.invoke(unwrapTrustManager(x509TrustManager)); if (objPolicy instanceof NetworkSecurityPolicy) { return (NetworkSecurityPolicy) objPolicy; } diff --git a/common/src/main/java/org/conscrypt/SessionSnapshot.java b/common/src/main/java/org/conscrypt/SessionSnapshot.java index 96c496218..5756a99f5 100644 --- a/common/src/main/java/org/conscrypt/SessionSnapshot.java +++ b/common/src/main/java/org/conscrypt/SessionSnapshot.java @@ -45,6 +45,7 @@ final class SessionSnapshot implements ConscryptSession { private X509Certificate[] peerCertificates; private final String[] peerSupportedSignatureAlgorithms; private final String[] localSupportedSignatureAlgorithms; + private final String echNameOverride; SessionSnapshot(ConscryptSession session) { sessionContext = session.getSessionContext(); @@ -66,6 +67,7 @@ final class SessionSnapshot implements ConscryptSession { } peerSupportedSignatureAlgorithms = session.getPeerSupportedSignatureAlgorithms(); localSupportedSignatureAlgorithms = session.getLocalSupportedSignatureAlgorithms(); + echNameOverride = session.getEchNameOverride(); } @Override @@ -87,6 +89,11 @@ public byte[] getPeerSignedCertificateTimestamp() { return peerTlsSctData != null ? peerTlsSctData.clone() : null; } + @Override + public String getEchNameOverride() { + return echNameOverride; + } + @Override public byte[] getId() { return id; diff --git a/common/src/main/java/org/conscrypt/TrustManagerImpl.java b/common/src/main/java/org/conscrypt/TrustManagerImpl.java index ff2d55ac4..b5f649225 100644 --- a/common/src/main/java/org/conscrypt/TrustManagerImpl.java +++ b/common/src/main/java/org/conscrypt/TrustManagerImpl.java @@ -35,6 +35,8 @@ package org.conscrypt; import org.conscrypt.metrics.CertificateValidationFailureReason; +import org.conscrypt.pqc.MtcUtils; +import org.conscrypt.pqc.MtcVerifier; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -56,6 +58,7 @@ import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -66,7 +69,6 @@ import java.util.function.Supplier; import java.util.logging.Logger; -import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; @@ -419,14 +421,31 @@ private List checkTrusted(X509Certificate[] certs, String authT String identificationAlgorithm = parameters.getEndpointIdentificationAlgorithm(); if ("HTTPS".equalsIgnoreCase(identificationAlgorithm)) { ConscryptHostnameVerifier verifier = getHttpsVerifier(); - if (!verifier.verify(certs, hostname, session)) { + String expectedHostname = getHostnameForHttpsVerification(session, hostname); + if (!verifier.verify(certs, expectedHostname, session)) { throw new CertificateException("No subjectAltNames on the certificate match"); } } } + // Pinning and CT intentionally continue to use the session's peer host. return checkTrusted(certs, ocspData, tlsSctData, authType, hostname, clientAuth); } + /** + * Returns the name to match against the leaf certificate for HTTPS endpoint identification. + * If the server rejected ECH, RFC 9849 section 6.1.7 requires authenticating the ECH public + * name instead of the true server name. + */ + private static String getHostnameForHttpsVerification(SSLSession session, String peerHost) { + if (session instanceof ConscryptSession) { + String echNameOverride = ((ConscryptSession) session).getEchNameOverride(); + if (echNameOverride != null) { + return echNameOverride; + } + } + return peerHost; + } + @SuppressWarnings("unchecked") private static byte[] getOcspDataFromSession(SSLSession session) { List ocspResponses = null; @@ -490,6 +509,14 @@ private List checkTrusted(X509Certificate[] certs, byte[] ocspD if (err != null) { throw new CertificateException(err); } + if (Platform.isMerkleTreeCertsEnabled()) { + TrustAnchor mtcAnchor = MtcUtils.findIssuingCaTrustAnchor(certs[0], acceptedIssuers, + trustedCertificateStore); + if (mtcAnchor != null) { + MtcVerifier.verifyMTC(certs[0], mtcAnchor); + return Arrays.asList(certs[0], mtcAnchor.getTrustedCert()); + } + } Set used = new HashSet<>(); List untrustedChain = new ArrayList<>(); List trustedChain = new ArrayList<>(); @@ -505,9 +532,9 @@ private List checkTrusted(X509Certificate[] certs, byte[] ocspD untrustedChain.add(leaf); } used.add(leaf); - int[] budget = { MAX_PATH_BUILD_ITERATIONS }; - return checkTrustedRecursive(certs, ocspData, tlsSctData, host, clientAuth, - untrustedChain, trustedChain, used, budget); + int[] budget = {MAX_PATH_BUILD_ITERATIONS}; + return checkTrustedRecursive(certs, ocspData, tlsSctData, host, clientAuth, untrustedChain, + trustedChain, used, budget); } /** @@ -538,8 +565,7 @@ private List checkTrustedRecursive(X509Certificate[] certs, byt boolean clientAuth, List untrustedChain, List trustAnchorChain, - Set used, - int[] budget) + Set used, int[] budget) throws CertificateException { if (--budget[0] < 0) { throw new CertificateException("Path-building iteration limit exceeded"); diff --git a/common/src/main/java/org/conscrypt/util/MtcUtils.java b/common/src/main/java/org/conscrypt/pqc/MtcUtils.java similarity index 86% rename from common/src/main/java/org/conscrypt/util/MtcUtils.java rename to common/src/main/java/org/conscrypt/pqc/MtcUtils.java index 6883d2803..937a11733 100644 --- a/common/src/main/java/org/conscrypt/util/MtcUtils.java +++ b/common/src/main/java/org/conscrypt/pqc/MtcUtils.java @@ -14,10 +14,12 @@ * limitations under the License. */ -package org.conscrypt.util; +package org.conscrypt.pqc; import org.conscrypt.ConscryptCertStore; import org.conscrypt.Internal; +import org.conscrypt.util.DerUtils; +import org.conscrypt.util.SerializationException; import java.io.ByteArrayOutputStream; import java.math.BigInteger; @@ -37,24 +39,24 @@ import javax.security.auth.x500.X500Principal; /** - * Utility methods for draft-ietf-plants-merkle-tree-certs-06 (MTC) ID parsing and message + * Utility methods for draft-ietf-plants-merkle-tree-certs-07 (MTC) ID parsing and message * construction. */ @Internal public final class MtcUtils { - private static final String MTC_PROOF_SIG_ALG_OID = "1.3.6.1.4.1.44363.47.0"; - private static final String MTC_CA_ID_OID = "1.3.6.1.4.1.44363.47.3"; - private static final String MTC_CA_EXT_SHA256_OID = "1.3.6.1.4.1.44363.47.4"; + static final String MTC_PROOF_SIG_ALG_OID = "1.3.6.1.5.5.7.6.67"; + private static final String MTC_CA_ID_OID = "1.3.6.1.5.5.7.25.3"; + private static final String MTC_CA_EXT_SHA256_OID = "1.3.6.1.5.5.7.1.38"; private static final String ML_DSA_44_OID = "2.16.840.1.101.3.4.3.17"; private static final String ML_DSA_65_OID = "2.16.840.1.101.3.4.3.18"; private static final String ML_DSA_87_OID = "2.16.840.1.101.3.4.3.19"; - public static final int MTC_INDEX_BITS = 48; - public static final long MTC_INDEX_MASK = (1L << MTC_INDEX_BITS) - 1; + static final int MTC_INDEX_BITS = 48; + static final long MTC_INDEX_MASK = (1L << MTC_INDEX_BITS) - 1; private static final BigInteger MIN_MTC_SERIAL = BigInteger.ONE.shiftLeft(MTC_INDEX_BITS); private static final BigInteger MAX_MTC_SERIAL = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); - public static final byte MTC_LEAF_PREFIX = 0x00; - public static final short ENTRY_TYPE_TBS_CERT = 0x0001; + static final byte MTC_LEAF_PREFIX = 0x00; + static final short ENTRY_TYPE_TBS_CERT = 0x0001; private static final String MTC_TAI_PREFIX = "oid/1.3.6.1.4.1."; private static final byte[] MTC_SUBTREE_V1_LABEL = @@ -64,10 +66,10 @@ private MtcUtils() {} /** * Checks whether the given certificate uses the MTC proof signature algorithm per - * {@code draft-ietf-plants-merkle-tree-certs-06 Section 6.2}. + * {@code draft-ietf-plants-merkle-tree-certs-07 Section 6.2}. * *

An MTC signature is identified by having a synthesized signature algorithm indicating - * an MTC proof (OID {@code 1.3.6.1.4.1.44363.47.0}, {@code id-alg-mtcProof}) with omitted + * an MTC proof (OID {@code 1.3.6.1.5.5.7.6.67}, {@code id-alg-mtcProof}) with omitted * parameters. * *

Note: Per Section 7.2, dispatching between classic X.509 signature verification and @@ -83,10 +85,10 @@ public static boolean hasMtcSignatureAlgorithm(X509Certificate cert) { /** * Checks whether the given certificate is an MTC CA / Trust Anchor certificate per - * {@code draft-ietf-plants-merkle-tree-certs-06 Section 5.5}. + * {@code draft-ietf-plants-merkle-tree-certs-07 Section 5.5}. * *

An MTC CA certificate is identified by the presence of the MTC CA extension - * (OID {@code 1.3.6.1.4.1.44363.47.4}, {@code id-pe-mtcCertificationAuthority-SHA256}). + * (OID {@code 1.3.6.1.5.5.7.1.38}, {@code id-pe-mtcCertificationAuthority-SHA256}). * Structural validity of the extension (such as criticality and serial bounds) and the * Subject DN (Trust Anchor ID) is enforced separately during verification so that a * malformed MTC CA certificate never falls back to classic X.509 verification. @@ -101,11 +103,11 @@ public static boolean isMtcCaCertificate(X509Certificate cert) { /** * Extracts the CA Trust Anchor ID bytes (raw DER {@code RELATIVE-OID} content) from the * trust anchor's Subject Distinguished Name per - * {@code draft-ietf-plants-merkle-tree-certs-06 Section 5.1}. + * {@code draft-ietf-plants-merkle-tree-certs-07 Section 5.1}. * *

The Subject DN must consist of a single {@code RelativeDistinguishedName} containing a * single {@code AttributeTypeAndValue} with type {@code id-rdna-trustAnchorID} - * ({@code 1.3.6.1.4.1.44363.47.3}) and value encoded as an ASN.1 {@code RELATIVE-OID}. + * ({@code 1.3.6.1.5.5.7.25.3}) and value encoded as an ASN.1 {@code RELATIVE-OID}. */ public static byte[] extractCaId(TrustAnchor anchor) throws CertificateException { X509Certificate cert = (anchor != null) ? anchor.getTrustedCert() : null; @@ -183,7 +185,7 @@ public static void validateSerialInCaRange(TrustAnchor anchor, BigInteger serial /** * Extracts the signature algorithm OID string ({@code sigAlg.algorithm}) from the trust * anchor's critical {@code id-pe-mtcCertificationAuthority-SHA256} extension per - * {@code draft-ietf-plants-merkle-tree-certs-06 Section 5.5}. + * {@code draft-ietf-plants-merkle-tree-certs-07 Section 5.5}. * *

Only ML-DSA algorithms ({@code ML-DSA-44}, {@code ML-DSA-65}, {@code ML-DSA-87}) with * omitted {@code AlgorithmIdentifier} parameters (RFC 9881 Section 2) are supported. @@ -246,7 +248,7 @@ private static ByteBuffer readCaExtensionSequence(TrustAnchor anchor) /** * Computes the Subtree v1 Log ID bytes ({@code .0.}) as a base-128 - * {@code RELATIVE-OID} byte array per draft-ietf-plants-merkle-tree-certs-06 Section 5.2. + * {@code RELATIVE-OID} byte array per draft-ietf-plants-merkle-tree-certs-07 Section 5.2. * * @param caId the issuing CA Trust Anchor ID bytes * @param logNumber the log number from the MTC proof @@ -283,7 +285,7 @@ private static void appendBase128(ByteArrayOutputStream out, long val) { /** * Constructs the CosignedMessage structure for signature verification, per - * draft-ietf-plants-merkle-tree-certs-06 Section 5.3.1 and Section 7.2 Step 12. + * draft-ietf-plants-merkle-tree-certs-07 Section 5.3.1 and Section 7.2 Step 12. */ private static byte[] constructCosignedMessage(byte[] cosignerId, byte[] logId, long start, long end, byte[] expectedSubtreeHash) @@ -318,6 +320,26 @@ private static byte[] constructCosignedMessage(byte[] cosignerId, byte[] logId, return buf.array(); } + /** + * Validates that the {@code MTCLogEntryExtension} list is well-formed and that extensions + * appear in strictly ascending order by {@code extension_type} without duplicates per + * Section 5.2.1. + */ + public static void validateExtensions(byte[] extensions) throws CertificateException { + ByteBuffer extBuf = ByteBuffer.wrap(extensions); + int prevType = -1; + while (extBuf.hasRemaining()) { + int extType = readUint16(extBuf); + if (extType <= prevType) { + throw new CertificateException( + "Malformed MTC proof: extensions are duplicate or out of order"); + } + prevType = extType; + int extDataLen = readUint16(extBuf); + readBytes(extBuf, extDataLen); + } + } + /** * Finds and extracts the signature bytes for the specified cosigner / issuing CA Trust Anchor * ID from the signatures payload, while validating that all {@code cosigner_id} entries are @@ -372,19 +394,19 @@ private static int compareCosignerIds(byte[] a, byte[] b) { } /** - * Verifies the issuing CA's signature over the signed tree root for the specified log ID. + * Verifies the issuing CA's signature over the signed subtree root for the specified log ID. * * @throws CertificateException if the signature is invalid */ - public static void verifySignedTreeRoot(PublicKey publicKey, String sigAlg, byte[] caId, - byte[] logId, long start, long end, - byte[] expectedSubtreeHash, byte[] caSignature) + static void verifySignedSubtreeRoot(PublicKey publicKey, String sigAlg, byte[] caId, + byte[] logId, long start, long end, + byte[] expectedSubtreeHash, byte[] caSignature) throws CertificateException { byte[] msg = constructCosignedMessage(caId, logId, start, end, expectedSubtreeHash); try { verifySignatureWithKey(publicKey, sigAlg, msg, caSignature); } catch (Exception e) { - throw new CertificateException("MTC CA signed tree root verification failed", e); + throw new CertificateException("MTC CA signed subtree root verification failed", e); } } @@ -401,17 +423,27 @@ private static int readUint8(ByteBuffer buffer) throws CertificateException { /** * Reads a 16-bit unsigned integer from the buffer in big-endian order. */ - public static int readUint16(ByteBuffer buffer) throws CertificateException { + static int readUint16(ByteBuffer buffer) throws CertificateException { if (buffer.remaining() < 2) { throw new CertificateException("Malformed MTC proof: unexpected end of data"); } return Short.toUnsignedInt(buffer.getShort()); } + /** + * Reads a 24-bit unsigned integer from the buffer in big-endian order. + */ + public static int readUint24(ByteBuffer buffer) throws CertificateException { + if (buffer.remaining() < 3) { + throw new CertificateException("Malformed MTC proof: unexpected end of data"); + } + return (Byte.toUnsignedInt(buffer.get()) << 16) | Short.toUnsignedInt(buffer.getShort()); + } + /** * Reads a 48-bit unsigned integer from the buffer in big-endian order. */ - public static long readUint48(ByteBuffer buffer) throws CertificateException { + static long readUint48(ByteBuffer buffer) throws CertificateException { if (buffer.remaining() < 6) { throw new CertificateException("Malformed MTC proof: unexpected end of data"); } @@ -422,7 +454,7 @@ public static long readUint48(ByteBuffer buffer) throws CertificateException { /** * Reads a byte array of the specified length from the buffer. */ - public static byte[] readBytes(ByteBuffer buffer, int length) throws CertificateException { + static byte[] readBytes(ByteBuffer buffer, int length) throws CertificateException { if (buffer.remaining() < length) { throw new CertificateException("Malformed MTC proof: unexpected end of data"); } @@ -434,7 +466,7 @@ public static byte[] readBytes(ByteBuffer buffer, int length) throws Certificate /** * Obtains a thread-safe / clean instance of SHA-256 {@link MessageDigest}. */ - public static MessageDigest getSha256Digest() throws CertificateException { + static MessageDigest getSha256Digest() throws CertificateException { try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { @@ -445,7 +477,7 @@ public static MessageDigest getSha256Digest() throws CertificateException { /** * Computes the SHA-256 digest of the given data. */ - public static byte[] sha256(byte[] data) throws CertificateException { + static byte[] sha256(byte[] data) throws CertificateException { return getSha256Digest().digest(data); } @@ -505,7 +537,7 @@ public static TrustAnchor findIssuingCaTrustAnchor(X509Certificate leaf, /** * Checks whether the interval {@code [start, end)} defines a valid subtree per - * draft-ietf-plants-merkle-tree-certs-06 Section 4.1: + * draft-ietf-plants-merkle-tree-certs-07 Section 4.1: *

    *
  • {@code 0 <= start <= end <= 2^48}
  • *
  • {@code start} is a multiple of {@code BIT_CEIL(end - start)}
  • diff --git a/common/src/main/java/org/conscrypt/pqc/MtcVerifier.java b/common/src/main/java/org/conscrypt/pqc/MtcVerifier.java new file mode 100644 index 000000000..089e94d73 --- /dev/null +++ b/common/src/main/java/org/conscrypt/pqc/MtcVerifier.java @@ -0,0 +1,423 @@ +/* + * Copyright 2026 The Android Open Source Project + * + * 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 org.conscrypt.pqc; + +import org.conscrypt.Internal; +import org.conscrypt.util.DerUtils; +import org.conscrypt.util.SerializationException; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.cert.CertificateException; +import java.security.cert.TrustAnchor; +import java.security.cert.X509Certificate; +import java.util.Objects; + +/** + * Verifies Merkle Tree Certificates (MTC) per IETF draft + * {@code draft-ietf-plants-merkle-tree-certs-07} + * (https://datatracker.ietf.org/doc/html/draft-ietf-plants-merkle-tree-certs-07). + */ +@Internal +public final class MtcVerifier { + private MtcVerifier() {} + + /** + * Verifies Merkle Tree Certificates (MTC) per draft-ietf-plants-merkle-tree-certs-07 + * Section 7.2 + * (https://datatracker.ietf.org/doc/html/draft-ietf-plants-merkle-tree-certs-07#section-7.2). + * Validates that the leaf certificate is authenticated via a Merkle inclusion proof + * rooted at a trusted log checkpoint or cosigned subtree. + */ + public static void verifyMTC(X509Certificate leaf, TrustAnchor anchor) + throws CertificateException { + if (leaf == null) { + throw new CertificateException("MTC leaf certificate is null"); + } + + // ===================================================================== + // Step 1: Signature Algorithm Verification (Section 6.2) + // Ensure the certificate indicates MTC proof-based authentication. + // ===================================================================== + if (!MtcUtils.hasMtcSignatureAlgorithm(leaf)) { + throw new CertificateException("Unacceptable signature algorithm for MTC: " + + leaf.getSigAlgOID()); + } + + // ===================================================================== + // Step 2: Proof Parsing (Section 6.2) + // Unpack the MTCProof structure (extensions, subtree interval [start, end), + // inclusion proof, and signatures) from the signature field. + // ===================================================================== + byte[] sigBytes = leaf.getSignature(); + if (sigBytes == null) { + throw new CertificateException("Missing MTC proof"); + } + + ByteBuffer buffer = ByteBuffer.wrap(sigBytes); + int extLen = MtcUtils.readUint16(buffer); + byte[] extensions = MtcUtils.readBytes(buffer, extLen); + MtcUtils.validateExtensions(extensions); + long start = MtcUtils.readUint48(buffer); + long end = MtcUtils.readUint48(buffer); + int proofLen = MtcUtils.readUint16(buffer); + byte[] inclusionProof = MtcUtils.readBytes(buffer, proofLen); + int sigsLen = MtcUtils.readUint24(buffer); + byte[] signatures = MtcUtils.readBytes(buffer, sigsLen); + if (buffer.hasRemaining()) { + throw new CertificateException("Trailing data in MTC proof"); + } + + // ===================================================================== + // Step 3: Serial Number Validation + // Validate that the certificate contains a valid 64-bit positive serial number. + // ===================================================================== + BigInteger serial = leaf.getSerialNumber(); + if (serial == null || serial.signum() <= 0 || serial.bitLength() > 64) { + throw new CertificateException("Invalid or missing serial number in MTC certificate"); + } + + // ===================================================================== + // Step 4: Revocation Status Check (Section 7.5) + // Check if the serial number falls within any revoked ranges. + // ===================================================================== + if (anchor == null || anchor.getTrustedCert() == null) { + throw new CertificateException("No issuing CA trust anchor found for MTC certificate: " + + leaf.getIssuerX500Principal()); + } + MtcUtils.validateSerialInCaRange(anchor, serial); + // TODO: Check that the serial is not contained in out-of-band revoked ranges. + + // ===================================================================== + // Step 5: Decompose Serial & Validate Subtree Interval (Section 4.3.2) + // Decompose serial into 16-bit log number and 48-bit index, and validate that + // the subtree interval [start, end) is valid and contains the index. + // ===================================================================== + int logNumber = extractLogNumber(serial); + validateSubtreeInterval(start, end, proofLen); + long index = extractIndex(serial, start, end); + + // ===================================================================== + // Step 6: Derive Log ID (Section 5.2) + // Find the issuing CA trust anchor and derive the log ID from the CA ID and log number. + // ===================================================================== + if (!Objects.equals(leaf.getIssuerX500Principal(), + anchor.getTrustedCert().getSubjectX500Principal())) { + throw new CertificateException( + "MTC leaf issuer does not match CA trust anchor subject"); + } + byte[] caId = MtcUtils.extractCaId(anchor); + byte[] logId = MtcUtils.getLogId(caId, logNumber); + + // ===================================================================== + // Steps 7 to 9: Leaf Entry Construction & Leaf Hash + // Reconstruct the MerkleTreeCertEntry payload (type 0x0001: tbs_cert_entry) wrapping the + // proof extensions and TBSCertificate, then compute the leaf digest MTH({entry}) = + // SHA-256(0x00 || entry). + // ===================================================================== + byte[] tbsCertEntryData = constructTbsCertEntryData(leaf); + byte[] entry = constructMerkleTreeCertEntry(extensions, tbsCertEntryData); + byte[] entryHash = computeLeafHash(entry); + + // ===================================================================== + // Step 10: Merkle Tree Inclusion Proof Evaluation (Section 4.3.2) + // Walk up the Merkle tree from the leaf hash using the sibling hashes in inclusion_proof + // to reconstruct the expected subtree root hash. + // ===================================================================== + byte[] expectedSubtreeHash = + evaluateInclusionProof(inclusionProof, index, start, end, entryHash); + + // ===================================================================== + // Step 11: Trusted Subtree Verification (Section 7.4) + // TODO: Check if the trust anchor has a pre-configured trusted subtree matching + // (log_number, [start, end)) and verify expectedSubtreeHash against its root hash. + // ===================================================================== + + // ===================================================================== + // Step 12: Issuing CA Signed Subtree Root Signature + // ===================================================================== + verifyMtcCaSignedSubtreeRoot(signatures, anchor, caId, logId, start, end, + expectedSubtreeHash); + + // ===================================================================== + // Step 13: Cosigner Checkpoint Signatures (Section 7.3) + // TODO: Implement third-party cosigners verification and witness quorum policy + // per draft-ietf-plants-merkle-tree-certs Section 7.3. + // ===================================================================== + + // ===================================================================== + // Path Validation Checks (Section 5.5 & Section 7.2) + // Verify CA and leaf certificate validity periods and CA constraints. + // ===================================================================== + X509Certificate caCert = anchor.getTrustedCert(); + caCert.checkValidity(); + if (caCert.getBasicConstraints() == -1) { + throw new CertificateException("MTC CA certificate missing BasicConstraints cA=TRUE"); + } + boolean[] keyUsage = caCert.getKeyUsage(); + if (keyUsage != null && (keyUsage.length <= 5 || !keyUsage[5])) { + throw new CertificateException("MTC CA certificate missing keyCertSign KeyUsage"); + } + leaf.checkValidity(); + } + + /** + * Validates that the subtree range [start, end) is a valid subtree interval + * (either power-of-two full subtree or partial subtree) and that the proof length + * is valid (a non-negative multiple of 32 bytes), per + * draft-ietf-plants-merkle-tree-certs Section 4.1 and Section 4.3.2. + */ + private static void validateSubtreeInterval(long start, long end, int proofLen) + throws CertificateException { + if (start >= end) { + throw new CertificateException("Invalid MTC proof subtree interval: start >= end"); + } + if (!MtcUtils.isValidSubtree(start, end)) { + throw new CertificateException("Invalid MTC proof subtree interval [" + start + ", " + + end + ")"); + } + if (proofLen < 0 || (proofLen % 32) != 0) { + throw new CertificateException("Invalid MTC inclusion proof length: " + proofLen); + } + } + + /** + * Extracts and validates the 16-bit log number from an MTC serial number (upper 16 bits). + * Spec: log_number = floor(serialNumber / 2^48) per draft-ietf-plants-merkle-tree-certs + * Section 7.2 Step 5. + */ + private static int extractLogNumber(BigInteger serial) throws CertificateException { + int logNumber = (int) (serial.longValue() >>> MtcUtils.MTC_INDEX_BITS); + if (logNumber == 0) { + throw new CertificateException("Invalid log_number 0 in MTC serial number"); + } + return logNumber; + } + + /** + * Extracts and validates the 48-bit certificate index from an MTC serial number (lower 48 + * bits), ensuring it falls within the subtree interval [start, end). Spec: index = serialNumber + * mod 2^48 per draft-ietf-plants-merkle-tree-certs Section 7.2 Step 5. + */ + private static long extractIndex(BigInteger serial, long start, long end) + throws CertificateException { + long index = serial.longValue() & MtcUtils.MTC_INDEX_MASK; + if (index < start || index >= end) { + throw new CertificateException("Certificate index " + index + + " is outside MTC proof subtree range [" + start + + ", " + end + ")"); + } + return index; + } + + /** + * Constructs a MerkleTreeCertEntry of type tbs_cert_entry (0x0001) per Section 7.2 Step 8. + * Entry format: extensions (u16 length-prefixed) || type (u16 = 0x0001) || tbs_cert_entry_data. + */ + private static byte[] constructMerkleTreeCertEntry(byte[] extensions, byte[] tbsCertEntryData) + throws CertificateException { + int totalLen = 2 + extensions.length + 2 + tbsCertEntryData.length; + if (totalLen > 65535) { + throw new CertificateException("MTCLogEntry exceeds maximum size of 65535 bytes"); + } + ByteBuffer buffer = ByteBuffer.allocate(totalLen); + buffer.putShort((short) extensions.length); + buffer.put(extensions); + buffer.putShort(MtcUtils.ENTRY_TYPE_TBS_CERT); + buffer.put(tbsCertEntryData); + return buffer.array(); + } + + /** + * Constructs the DER-encoded contents of the TBSCertificateLogEntry structure from the + * leaf X.509 certificate's TBSCertificate, per draft-ietf-plants-merkle-tree-certs Section 7.2 + * Step 8. + */ + private static byte[] constructTbsCertEntryData(X509Certificate leaf) + throws CertificateException { + try { + ByteBuffer tbsOuter = ByteBuffer.wrap(leaf.getTBSCertificate()); + ByteBuffer tbs = DerUtils.readSequence(tbsOuter); + if (tbsOuter.hasRemaining()) { + throw new CertificateException("Trailing data outside TBSCertificate SEQUENCE"); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // 1. Version [0] EXPLICIT Version (tag 0xA0) - optional + byte[] version = DerUtils.readOptionalElement(tbs, DerUtils.TAG_CONTEXT_EXPLICIT_0); + if (version != null) { + out.write(version, 0, version.length); + } + + // 2. Serial Number (tag 0x02) & 3. Signature Algorithm (tag 0x30) - omitted + DerUtils.readBigInteger(tbs); + ByteBuffer sigAlgSeq = DerUtils.readSequence(tbs); + String innerSigAlgOid = DerUtils.readOid(sigAlgSeq); + if (!MtcUtils.MTC_PROOF_SIG_ALG_OID.equals(innerSigAlgOid) + || sigAlgSeq.hasRemaining()) { + throw new CertificateException( + "Invalid TBSCertificate.signature AlgorithmIdentifier"); + } + + // 4. Issuer (tag 0x30) + byte[] issuer = DerUtils.readSequenceElement(tbs); + out.write(issuer, 0, issuer.length); + + // 5. Validity (tag 0x30) + byte[] validity = DerUtils.readSequenceElement(tbs); + out.write(validity, 0, validity.length); + + // 6. Subject (tag 0x30) + byte[] subject = DerUtils.readSequenceElement(tbs); + out.write(subject, 0, subject.length); + + // 7. SubjectPublicKeyInfo (tag 0x30) -> extract algorithm + SHA-256 hash of SPKI + byte[] spki = DerUtils.readSequenceElement(tbs); + ByteBuffer spkiOuter = ByteBuffer.wrap(spki); + ByteBuffer spkiBuf = DerUtils.readSequence(spkiOuter); + byte[] spkiAlg = DerUtils.readSequenceElement(spkiBuf); + out.write(spkiAlg, 0, spkiAlg.length); + + // SubjectPublicKeyInfoHash as OCTET STRING + byte[] spkiHash = MtcUtils.sha256(spki); + out.write(0x04); + out.write(spkiHash.length); + out.write(spkiHash, 0, spkiHash.length); + + // 8. Remaining elements (extensions [3] tag 0xA3, unique identifiers, etc.) + byte[] remaining = new byte[tbs.remaining()]; + tbs.get(remaining); + out.write(remaining, 0, remaining.length); + + return out.toByteArray(); + } catch (SerializationException e) { + throw new CertificateException("Failed to parse TBSCertificate DER", e); + } + } + + /** + * Computes the leaf node hash MTH({entry}) = SHA-256(0x00 || entry) per Section 7.2 Step 9. + */ + private static byte[] computeLeafHash(byte[] entry) throws CertificateException { + MessageDigest md = MtcUtils.getSha256Digest(); + md.update(MtcUtils.MTC_LEAF_PREFIX); + return md.digest(entry); + } + + /** + * Evaluates a Merkle subtree inclusion proof to calculate the expected subtree root hash, + * per draft-ietf-plants-merkle-tree-certs Section 4.3.2 and Section 7.2 Step 10. + * + *

    Assumes the caller has already validated that {@code [start, end)} is a valid non-empty + * subtree interval containing {@code index} ({@code 0 <= start <= index < end <= 2^48}) and + * that {@code inclusionProof.length} is a multiple of 32 bytes (see + * {@link #validateSubtreeInterval} and {@link #extractIndex}). + */ + private static byte[] evaluateInclusionProof(byte[] inclusionProof, long index, long start, + long end, byte[] leafHash) + throws CertificateException { + // fn: current node index within the subtree (0-based) + // sn: last node index in the subtree (when sn == 0, we have reached the root) + long fn = index - start; + long sn = end - start - 1; + byte[] currentHash = leafHash; + ByteBuffer buffer = ByteBuffer.wrap(inclusionProof); + + while (buffer.hasRemaining()) { + // If sn is already 0, we have reached the root and the proof contains extra hashes. + if (sn == 0) { + throw new CertificateException("Inclusion proof contains too many nodes"); + } + if (buffer.remaining() < 32) { + throw new CertificateException("Invalid inclusion proof node length"); + } + byte[] p = new byte[32]; + buffer.get(p); + + MessageDigest nodeDigest = MtcUtils.getSha256Digest(); + nodeDigest.update( + (byte) 0x01); // Domain separator for interior Merkle nodes (RFC 9162 § 2.1) + + // Determine if the adjacent hash p is on the left or right: + // - If fn is odd (a right-hand child) or fn == sn (the rightmost node of an unbalanced + // subtree), + // hash p is on the left. + // - Otherwise, hash p is on the right. + if ((fn & 1) != 0 || fn == sn) { + nodeDigest.update(p); + nodeDigest.update(currentHash); + currentHash = nodeDigest.digest(); + + // Advance past completed balanced subtrees to find the next ancestor. + while ((fn & 1) == 0) { + fn >>>= 1; + sn >>>= 1; + } + } else { + nodeDigest.update(currentHash); + nodeDigest.update(p); + currentHash = nodeDigest.digest(); + } + + // Move one level up the tree. + fn >>>= 1; + sn >>>= 1; + } + + // If sn is not 0, the proof ended before reaching the root. + if (sn != 0) { + throw new CertificateException("Inclusion proof incomplete: remaining sn=" + sn); + } + + return currentHash; + } + + /** + * Verifies that the signatures in an MTCProof contain a valid signature from the issuing CA + * over the computed Merkle subtree root hash, per draft-ietf-plants-merkle-tree-certs Section + * 7.2 Step 12. + */ + private static void verifyMtcCaSignedSubtreeRoot(byte[] signatures, TrustAnchor anchor, + byte[] caId, byte[] logId, long start, + long end, byte[] expectedSubtreeHash) + throws CertificateException { + if (signatures == null || signatures.length == 0) { + throw new CertificateException("MTC proof contains no signatures"); + } + + // 1. Resolve issuing CA public key + PublicKey publicKey = anchor.getTrustedCert().getPublicKey(); + if (publicKey == null) { + throw new CertificateException("No public key found for MTC trust anchor"); + } + + // 2. Extract the issuing CA signature from the signatures payload + byte[] caSignature = MtcUtils.findCaSignature(signatures, caId); + if (caSignature == null) { + throw new CertificateException("No signature from issuing CA found in MTC proof"); + } + + // 3. Verify the signed subtree root signature + String sigAlg = MtcUtils.extractCaSigAlg(anchor); + MtcUtils.verifySignedSubtreeRoot(publicKey, sigAlg, caId, logId, start, end, + expectedSubtreeHash, caSignature); + } +} diff --git a/common/src/test/java/org/conscrypt/MlDsaTest.java b/common/src/test/java/org/conscrypt/MlDsaTest.java index bf25d6f56..c6630a666 100644 --- a/common/src/test/java/org/conscrypt/MlDsaTest.java +++ b/common/src/test/java/org/conscrypt/MlDsaTest.java @@ -20,6 +20,7 @@ import static org.conscrypt.TestUtils.decodeHex; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; @@ -40,10 +41,12 @@ import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.MessageDigest; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.Signature; +import java.security.SignatureException; import java.security.spec.EncodedKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; @@ -974,6 +977,250 @@ public void testVectors() throws Exception { } } + /** + * Computes the ML-DSA message representative mu of {@code message} for {@code publicKey} with + * an empty context string, which is the input expected by the "EXTERNAL-MU-ML-DSA" signatures + * (FIPS 204, Algorithm 7, line 6): {@code mu = SHAKE256-512(tr || 0x00 || 0x00 || message)} + * with {@code tr = SHAKE256-512(rawPublicKey)}. + */ + // The algorithm name must be a compile-time constant for the crypto API lint checks. + private KeyPairGenerator mlDsaKeyPairGenerator(String algorithm) throws Exception { + switch (algorithm) { + case "ML-DSA": + return KeyPairGenerator.getInstance("ML-DSA", conscryptProvider); + case "ML-DSA-44": + return KeyPairGenerator.getInstance("ML-DSA-44", conscryptProvider); + case "ML-DSA-65": + return KeyPairGenerator.getInstance("ML-DSA-65", conscryptProvider); + case "ML-DSA-87": + return KeyPairGenerator.getInstance("ML-DSA-87", conscryptProvider); + default: + throw new IllegalArgumentException("Unknown ML-DSA algorithm: " + algorithm); + } + } + + private KeyFactory mlDsaKeyFactory(String algorithm) throws Exception { + switch (algorithm) { + case "ML-DSA": + return KeyFactory.getInstance("ML-DSA", conscryptProvider); + case "ML-DSA-44": + return KeyFactory.getInstance("ML-DSA-44", conscryptProvider); + case "ML-DSA-65": + return KeyFactory.getInstance("ML-DSA-65", conscryptProvider); + case "ML-DSA-87": + return KeyFactory.getInstance("ML-DSA-87", conscryptProvider); + default: + throw new IllegalArgumentException("Unknown ML-DSA algorithm: " + algorithm); + } + } + + private byte[] externalMu(PublicKey publicKey, byte[] message) throws Exception { + // The generic ML-DSA key factory exports the raw public key of all parameter sets. + KeyFactory keyFactory = KeyFactory.getInstance("ML-DSA", conscryptProvider); + byte[] rawPublicKey = keyFactory.getKeySpec(publicKey, RawKeySpec.class).getEncoded(); + + MessageDigest shake256 = MessageDigest.getInstance("SHAKE256-512", conscryptProvider); + byte[] tr = shake256.digest(rawPublicKey); + shake256.update(tr); + shake256.update(new byte[] {0, 0}); // Domain separator and length of the empty context. + return shake256.digest(message); + } + + @Test + public void externalMu_signVerify_works() throws Exception { + String[] algorithms = new String[] {"ML-DSA-44", "ML-DSA-65", "ML-DSA-87"}; + int[] signatureLengths = new int[] {2420, 3309, 4627}; + for (int i = 0; i < algorithms.length; i++) { + String algorithm = algorithms[i]; + KeyPairGenerator keyGen = mlDsaKeyPairGenerator(algorithm); + KeyPair keyPair = keyGen.generateKeyPair(); + byte[] message = ("External mu " + algorithm).getBytes(StandardCharsets.UTF_8); + byte[] mu = externalMu(keyPair.getPublic(), message); + assertEquals(64, mu.length); + + for (String signAlgorithm : + new String[] {"EXTERNAL-MU-" + algorithm, "EXTERNAL-MU-ML-DSA"}) { + Signature signer = Signature.getInstance(signAlgorithm, conscryptProvider); + assertEquals(signAlgorithm, signer.getAlgorithm()); + signer.initSign(keyPair.getPrivate()); + signer.update(mu); + byte[] sig = signer.sign(); + assertEquals(signatureLengths[i], sig.length); + + // The result is a regular ML-DSA signature of the message. + for (String verifyAlgorithm : new String[] {algorithm, "ML-DSA"}) { + Signature verifier = Signature.getInstance(verifyAlgorithm, conscryptProvider); + verifier.initVerify(keyPair.getPublic()); + verifier.update(message); + assertTrue(verifier.verify(sig)); + } + + // But not of a different message, nor of mu itself. + Signature verifier = Signature.getInstance(algorithm, conscryptProvider); + verifier.initVerify(keyPair.getPublic()); + verifier.update(message, 0, message.length - 1); + assertFalse(verifier.verify(sig)); + verifier.initVerify(keyPair.getPublic()); + verifier.update(mu); + assertFalse(verifier.verify(sig)); + } + } + } + + @Test + public void externalMu_signWithForeignKey_works() throws Exception { + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ML-DSA-65", conscryptProvider); + KeyPair keyPair = keyGen.generateKeyPair(); + PrivateKey privateKey = new TestPrivateKey(keyPair.getPrivate().getEncoded()); + PublicKey publicKey = new TestPublicKey(keyPair.getPublic().getEncoded()); + byte[] message = "External mu with a foreign key".getBytes(StandardCharsets.UTF_8); + byte[] mu = externalMu(keyPair.getPublic(), message); + + Signature signer = Signature.getInstance("EXTERNAL-MU-ML-DSA-65", conscryptProvider); + signer.initSign(privateKey); + signer.update(mu); + byte[] sig = signer.sign(); + + Signature verifier = Signature.getInstance("ML-DSA-65", conscryptProvider); + verifier.initVerify(publicKey); + verifier.update(message); + assertTrue(verifier.verify(sig)); + } + + @Test + public void externalMu_withTestVectors_works() throws Exception { + List vectors = TestUtils.readTestVectors("crypto/mldsa.txt"); + + for (TestVector vector : vectors) { + String errMsg = vector.getString("name"); + String algorithm = vector.getString("algorithm"); + byte[] seed = vector.getBytes("seed"); + byte[] publicKeyBytes = vector.getBytes("public_key"); + byte[] message = vector.getBytes("message"); + byte[] signature = vector.getBytes("signature"); + + KeyFactory keyFactory = mlDsaKeyFactory(algorithm); + PrivateKey privateKey = keyFactory.generatePrivate(new RawKeySpec(seed)); + PublicKey publicKey = keyFactory.generatePublic(new RawKeySpec(publicKeyBytes)); + byte[] mu = externalMu(publicKey, message); + + Signature signer = Signature.getInstance("EXTERNAL-MU-" + algorithm, conscryptProvider); + signer.initSign(privateKey); + signer.update(mu); + byte[] sig = signer.sign(); + assertEquals(errMsg + ", signature length mismatch", signature.length, sig.length); + + Signature verifier = Signature.getInstance(algorithm, conscryptProvider); + verifier.initVerify(publicKey); + verifier.update(message); + assertTrue(errMsg + ", external mu signature verification failed", + verifier.verify(sig)); + } + } + + @Test + public void externalMu_updateInChunks_works() throws Exception { + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ML-DSA-65", conscryptProvider); + KeyPair keyPair = keyGen.generateKeyPair(); + byte[] message = "External mu in chunks".getBytes(StandardCharsets.UTF_8); + byte[] mu = externalMu(keyPair.getPublic(), message); + + Signature signer = Signature.getInstance("EXTERNAL-MU-ML-DSA-65", conscryptProvider); + Signature verifier = Signature.getInstance("ML-DSA-65", conscryptProvider); + + // Byte by byte. + signer.initSign(keyPair.getPrivate()); + for (byte b : mu) { + signer.update(b); + } + byte[] sig = signer.sign(); + verifier.initVerify(keyPair.getPublic()); + verifier.update(message); + assertTrue(verifier.verify(sig)); + + // In two chunks, without calling initSign again. + signer.update(mu, 0, 10); + signer.update(mu, 10, mu.length - 10); + byte[] sig2 = signer.sign(); + verifier.initVerify(keyPair.getPublic()); + verifier.update(message); + assertTrue(verifier.verify(sig2)); + } + + @Test + public void externalMu_invalidMuLength_throws() throws Exception { + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ML-DSA-65", conscryptProvider); + KeyPair keyPair = keyGen.generateKeyPair(); + byte[] message = "External mu of the wrong length".getBytes(StandardCharsets.UTF_8); + byte[] mu = externalMu(keyPair.getPublic(), message); + + Signature signer = Signature.getInstance("EXTERNAL-MU-ML-DSA-65", conscryptProvider); + signer.initSign(keyPair.getPrivate()); + + // Nothing, too little, or too much input is rejected. + assertThrows(SignatureException.class, signer::sign); + signer.update(mu, 0, 63); + assertThrows(SignatureException.class, signer::sign); + signer.update(mu); + signer.update((byte) 0); + assertThrows(SignatureException.class, signer::sign); + signer.update(message); + assertThrows(SignatureException.class, signer::sign); + + // A failed sign() discards the buffered input, so the signer remains usable. + signer.update(mu); + byte[] sig = signer.sign(); + Signature verifier = Signature.getInstance("ML-DSA-65", conscryptProvider); + verifier.initVerify(keyPair.getPublic()); + verifier.update(message); + assertTrue(verifier.verify(sig)); + } + + @Test + public void externalMu_keyMismatch_throws() throws Exception { + KeyPair keyPair44 = + KeyPairGenerator.getInstance("ML-DSA-44", conscryptProvider).generateKeyPair(); + KeyPair keyPair65 = + KeyPairGenerator.getInstance("ML-DSA-65", conscryptProvider).generateKeyPair(); + KeyPair keyPair87 = + KeyPairGenerator.getInstance("ML-DSA-87", conscryptProvider).generateKeyPair(); + + Signature s44 = Signature.getInstance("EXTERNAL-MU-ML-DSA-44", conscryptProvider); + assertThrows(InvalidKeyException.class, () -> s44.initSign(keyPair65.getPrivate())); + assertThrows(InvalidKeyException.class, () -> s44.initSign(keyPair87.getPrivate())); + + Signature s65 = Signature.getInstance("EXTERNAL-MU-ML-DSA-65", conscryptProvider); + assertThrows(InvalidKeyException.class, () -> s65.initSign(keyPair44.getPrivate())); + assertThrows(InvalidKeyException.class, () -> s65.initSign(keyPair87.getPrivate())); + + Signature s87 = Signature.getInstance("EXTERNAL-MU-ML-DSA-87", conscryptProvider); + assertThrows(InvalidKeyException.class, () -> s87.initSign(keyPair44.getPrivate())); + assertThrows(InvalidKeyException.class, () -> s87.initSign(keyPair65.getPrivate())); + + // Keys of other algorithms are rejected too. + KeyPair ecKeyPair = KeyPairGenerator.getInstance("EC", conscryptProvider).generateKeyPair(); + Signature s = Signature.getInstance("EXTERNAL-MU-ML-DSA", conscryptProvider); + assertThrows(InvalidKeyException.class, () -> s.initSign(ecKeyPair.getPrivate())); + } + + @Test + public void externalMu_initVerify_throws() throws Exception { + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ML-DSA-65", conscryptProvider); + KeyPair keyPair = keyGen.generateKeyPair(); + PublicKey publicKey = keyPair.getPublic(); + PublicKey foreignPublicKey = new TestPublicKey(publicKey.getEncoded()); + + // External mu ML-DSA only signs; signatures are verified with the regular ML-DSA + // Signature and the original message. + for (String algorithm : new String[] {"EXTERNAL-MU-ML-DSA", "EXTERNAL-MU-ML-DSA-44", + "EXTERNAL-MU-ML-DSA-65", "EXTERNAL-MU-ML-DSA-87"}) { + Signature verifier = Signature.getInstance(algorithm, conscryptProvider); + assertThrows(UnsupportedOperationException.class, () -> verifier.initVerify(publicKey)); + assertThrows(UnsupportedOperationException.class, + () -> verifier.initVerify(foreignPublicKey)); + } + } + @Test public void serializeAndDeserialize_44_works() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ML-DSA-44", conscryptProvider); diff --git a/common/src/test/java/org/conscrypt/NativeCryptoArgTest.java b/common/src/test/java/org/conscrypt/NativeCryptoArgTest.java index 4f9cb7067..aa4894c71 100644 --- a/common/src/test/java/org/conscrypt/NativeCryptoArgTest.java +++ b/common/src/test/java/org/conscrypt/NativeCryptoArgTest.java @@ -129,7 +129,7 @@ public void sslMethods() throws Throwable { .hasArg(0, long.class) .hasArg(1, conscryptClass("NativeSsl")) .except(nonThrowingMethods) - .expectSize(60) + .expectSize(63) .build(); testMethods(filter, NullPointerException.class); @@ -150,6 +150,9 @@ public void sslMethods() throws Throwable { expectNPE("ENGINE_SSL_shutdown", NOT_NULL, null, null); expectVoid("SSL_set_session", NOT_NULL, null, NULL); + // A null ID list must throw before the (fake) SSL pointer is dereferenced. + expectNPE("SSL_set1_requested_trust_anchors", NOT_NULL, /* ssl_holder= */ null, + /* ids= */ null); checkMethodsTested(); } diff --git a/common/src/test/java/org/conscrypt/ServerSessionResumptionTest.java b/common/src/test/java/org/conscrypt/ServerSessionResumptionTest.java new file mode 100644 index 000000000..b165fa08d --- /dev/null +++ b/common/src/test/java/org/conscrypt/ServerSessionResumptionTest.java @@ -0,0 +1,577 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * 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 org.conscrypt; + +import static org.conscrypt.TestUtils.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import org.conscrypt.java.security.TestKeyStore; +import org.conscrypt.javax.net.ssl.ForwardingX509ExtendedKeyManager; +import org.conscrypt.javax.net.ssl.TestSSLEnginePair; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +import java.io.IOException; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.security.Principal; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.net.ssl.ExtendedSSLSession; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SNIHostName; +import javax.net.ssl.SNIServerName; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLEngineResult; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.StandardConstants; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509ExtendedKeyManager; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; + +/** + * Tests verifying that server-side TLS 1.2 and TLS 1.3 session resumption is partitioned across + * distinct SNI names, client authentication modes, and endpoint identification algorithms. + */ +@RunWith(Parameterized.class) +public class ServerSessionResumptionTest { + private static final String HOST_A = "a.example.com"; + private static final String HOST_B = "b.example.com"; + private static final String NO_SNI_HOST = "127.0.0.1"; + private static final int PORT = 8443; + + private static TestKeyStore caA; + private static TestKeyStore clientA; + private static TestKeyStore caB; + + @Parameters(name = "{0}") + public static Collection data() { + return Arrays.asList(new Object[][] { + {"TLSv1.2_SessionCache", "TLSv1.2", false}, + {"TLSv1.2_SessionTicket", "TLSv1.2", true}, + {"TLSv1.3_SessionTicket", "TLSv1.3", true}, + }); + } + + @Parameter(0) public String modeName; + @Parameter(1) public String protocol; + @Parameter(2) public boolean useSessionTickets; + + @Before + public void setUp() { + TestUtils.installConscryptAsDefaultProvider(); + TestUtils.assumeSNIHostnameAvailable(); + initFixtures(); + } + + private static synchronized void initFixtures() { + if (caA != null) { + return; + } + caA = buildCa("ca-a", "CN=Test CA A"); + clientA = buildLeaf("client-a", "CN=client-a.example.com", caA); + caB = buildCa("ca-b", "CN=Test CA B"); + } + + private static TestKeyStore buildCa(String prefix, String subject) { + return new TestKeyStore.Builder() + .aliasPrefix(prefix) + .keyAlgorithms("RSA") + .subject(subject) + .ca(true) + .build(); + } + + private static TestKeyStore buildLeaf(String prefix, String subject, TestKeyStore ca) { + return new TestKeyStore.Builder() + .aliasPrefix(prefix) + .keyAlgorithms("RSA") + .subject(subject) + .signer(ca.getPrivateKey("RSA", "RSA")) + .rootCa(ca.getRootCertificate("RSA")) + .build(); + } + + // Resuming onto the same SNI host skips TrustManager re-verification and preserves the + // authenticated client principal. + @Test + public void sameSniResumption_skipsReverificationAndPreservesPrincipal() throws Exception { + SniAwareClientTrustManager serverTm = new SniAwareClientTrustManager(); + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, serverTm); + ClientRig initialClient = new ClientRig(clientA.keyManagers); + runHandshake(initialClient, HOST_A, serverCtx, true); + ClientRig resumingClient = + new ClientRig(null).injectSession(initialClient.extractSessionBytes(), HOST_A); + + SSLSession resumed = runHandshake(resumingClient, HOST_A, serverCtx, true); + + assertEquals(0, resumingClient.serverAuthCalls.get()); + assertEquals(1, serverTm.clientAuthCalls.get()); + assertEquals("CN=client-a.example.com", resumed.getPeerPrincipal().getName()); + } + + // SNI hostnames are canonicalized case-insensitively, allowing a session from "A.EXAMPLE.COM" + // to resume onto "a.example.com". + @Test + public void mixedCaseSniResumption_skipsReverificationAndPreservesPrincipal() throws Exception { + SniAwareClientTrustManager serverTm = new SniAwareClientTrustManager(); + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, serverTm); + ClientRig initialClient = new ClientRig(clientA.keyManagers); + runHandshake(initialClient, "A.EXAMPLE.COM", serverCtx, true); + ClientRig resumingClient = + new ClientRig(null).injectSession(initialClient.extractSessionBytes(), HOST_A); + + SSLSession resumed = runHandshake(resumingClient, HOST_A, serverCtx, true); + + assertEquals(0, resumingClient.serverAuthCalls.get()); + assertEquals(1, serverTm.clientAuthCalls.get()); + assertEquals("CN=client-a.example.com", resumed.getPeerPrincipal().getName()); + } + + // Replaying a session from HOST_A against HOST_B declines resumption and rejects the client + // certificate under HOST_B's TrustManager policy. + @Test + public void crossSniResumption_wrongClientCert_rejected() throws Exception { + SniAwareClientTrustManager serverTm = new SniAwareClientTrustManager(); + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, serverTm); + ClientRig rigA = new ClientRig(clientA.keyManagers); + runHandshake(rigA, HOST_A, serverCtx, true); + ClientRig wrongCertClient = new ClientRig(clientA.keyManagers) + .injectSession(rigA.extractSessionBytes(), HOST_B); + + assertThrows(SSLHandshakeException.class, + () -> runHandshake(wrongCertClient, HOST_B, serverCtx, true)); + assertEquals(2, serverTm.clientAuthCalls.get()); + } + + // Replaying a session established with SNI on a connection without SNI declines resumption and + // forces client certificate verification. + @Test + public void sniToNoSniResumption_declinesResumption() throws Exception { + SniAwareClientTrustManager serverTm = new SniAwareClientTrustManager(); + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, serverTm); + ClientRig sniClient = new ClientRig(clientA.keyManagers); + runHandshake(sniClient, HOST_A, serverCtx, true); + // NO_SNI_HOST (127.0.0.1) omits SNI and trusts CA B. + ClientRig toNoSni = new ClientRig(clientA.keyManagers) + .injectSession(sniClient.extractSessionBytes(), NO_SNI_HOST); + + assertThrows(SSLHandshakeException.class, + () -> runHandshake(toNoSni, NO_SNI_HOST, serverCtx, true)); + assertEquals(2, serverTm.clientAuthCalls.get()); + } + + // An unauthenticated session from a needClientAuth=false engine cannot resume onto a + // needClientAuth=true engine even with the same SNI. + @Test + public void clientAuthNoneToNeed_declinesResumption() throws Exception { + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, caA.trustManager); + ClientRig unauthClient = new ClientRig(null); + runHandshake(unauthClient, HOST_A, serverCtx, false); + + assertThrows(SSLHandshakeException.class, + () -> runHandshake(unauthClient, HOST_A, serverCtx, true)); + } + + // An unauthenticated session from a wantClientAuth=true engine cannot resume onto a + // needClientAuth=true engine. + @Test + public void clientAuthWantToNeed_declinesResumption() throws Exception { + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, caA.trustManager); + ClientRig wantClient = new ClientRig(null); + SSLEngine wantServer = newServerEngine(serverCtx, false); + wantServer.setWantClientAuth(true); + handshake(wantClient.newEngine(HOST_A), wantServer); + + assertThrows(SSLHandshakeException.class, + () -> runHandshake(wantClient, HOST_A, serverCtx, true)); + } + + // Mutating setNeedClientAuth(true) mid-handshake inside KeyManager does not allow the + // unauthenticated session to resume onto a needClientAuth=true engine. + @Test + public void midHandshakeSetNeedClientAuth_doesNotTagSessionAsClientAuthenticated() + throws Exception { + AtomicBoolean mutatedInKeyManager = new AtomicBoolean(false); + X509ExtendedKeyManager baseKm = + (X509ExtendedKeyManager) TestKeyStore.getServer().keyManagers[0]; + X509ExtendedKeyManager mutatingKm = new ForwardingX509ExtendedKeyManager(baseKm) { + @Override + public String chooseEngineServerAlias(String keyType, Principal[] issuers, + SSLEngine engine) { + engine.setNeedClientAuth(true); + mutatedInKeyManager.set(true); + return super.chooseEngineServerAlias(keyType, issuers, engine); + } + }; + SSLContext serverCtx = newContext(new KeyManager[] {mutatingKm}, caA.trustManager); + // Initial connection enforces needClientAuth=false (set before beginHandshake); mutating + // needClientAuth inside KeyManager must not tag the session as client-authenticated. + ClientRig unauthClient = new ClientRig(null); + runHandshake(unauthClient, HOST_A, serverCtx, false); + + assertThrows(SSLHandshakeException.class, + () -> runHandshake(unauthClient, HOST_A, serverCtx, true)); + assertTrue(mutatedInKeyManager.get()); + } + + // Enabling endpoint identification on the server declines resumption of a session established + // without endpoint identification and re-runs TrustManager verification. + @Test + public void endpointIdentificationAlgorithmChange_declinesResumption() throws Exception { + TestUtils.assumeSetEndpointIdentificationAlgorithmAvailable(); + SniAwareClientTrustManager serverTm = new SniAwareClientTrustManager(); + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, serverTm); + ClientRig client = new ClientRig(clientA.keyManagers); + runHandshake(client, HOST_A, serverCtx, true); + SSLEngine serverWithHttpsId = newServerEngine(serverCtx, true); + SSLParameters params = serverWithHttpsId.getSSLParameters(); + params.setEndpointIdentificationAlgorithm("HTTPS"); + serverWithHttpsId.setSSLParameters(params); + + handshake(client.newEngine(HOST_A), serverWithHttpsId); + + assertEquals(2, client.serverAuthCalls.get()); + assertEquals(2, serverTm.clientAuthCalls.get()); + } + + // Cross-SNI session replay over SSLServerSocket and SSLSocket declines resumption and rejects + // the client certificate under HOST_B's TrustManager policy. + @Test + public void socketCrossSniResumption_wrongClientCert_rejected() throws Exception { + SniAwareClientTrustManager serverTm = new SniAwareClientTrustManager(); + SSLContext serverCtx = newContext(TestKeyStore.getServer().keyManagers, serverTm); + try (SSLServerSocket serverSocket = newServerSocket(serverCtx, true)) { + int port = serverSocket.getLocalPort(); + ClientRig rigA = new ClientRig(clientA.keyManagers); + runSocketHandshake(rigA, HOST_A, serverSocket); + ClientRig wrongCertClient = + new ClientRig(clientA.keyManagers) + .injectSession(rigA.extractSessionBytes(), HOST_B, port); + + assertThrows(SSLHandshakeException.class, + () -> runSocketHandshake(wrongCertClient, HOST_B, serverSocket)); + assertEquals(2, serverTm.clientAuthCalls.get()); + } + } + + private static SSLContext newContext(KeyManager[] keyManagers, TrustManager trustManager) + throws Exception { + SSLContext ctx = SSLContext.getInstance("TLS", TestUtils.getConscryptProvider()); + ctx.init(keyManagers, new TrustManager[] {trustManager}, null); + return ctx; + } + + private SSLEngine newServerEngine(SSLContext serverCtx, boolean needClientAuth) { + SSLEngine server = serverCtx.createSSLEngine(); + server.setUseClientMode(false); + server.setEnabledProtocols(new String[] {protocol}); + server.setNeedClientAuth(needClientAuth); + Conscrypt.setUseSessionTickets(server, useSessionTickets); + return server; + } + + private SSLServerSocket newServerSocket(SSLContext serverCtx, boolean needClientAuth) + throws IOException { + SSLServerSocket serverSocket = + (SSLServerSocket) serverCtx.getServerSocketFactory().createServerSocket( + 0, 50, TestUtils.getLoopbackAddress()); + serverSocket.setEnabledProtocols(new String[] {protocol}); + serverSocket.setNeedClientAuth(needClientAuth); + return serverSocket; + } + + private SSLSession runHandshake(ClientRig clientRig, String host, SSLContext serverCtx, + boolean needClientAuth) throws IOException { + SSLEngine server = newServerEngine(serverCtx, needClientAuth); + handshake(clientRig.newEngine(host), server); + return server.getSession(); + } + + private SSLSession runSocketHandshake(ClientRig clientRig, String host, + SSLServerSocket serverSocket) throws Exception { + int port = serverSocket.getLocalPort(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try (Socket rawClient = new Socket(TestUtils.getLoopbackAddress(), port); + SSLSocket client = clientRig.newSocket(rawClient, host, port); + SSLSocket server = (SSLSocket) serverSocket.accept()) { + Conscrypt.setUseSessionTickets(server, useSessionTickets); + Future serverFuture = executor.submit(() -> { + server.startHandshake(); + server.getOutputStream().write('K'); + server.getOutputStream().flush(); + return server.getSession(); + }); + Future clientFuture = executor.submit(() -> { + client.startHandshake(); + assertEquals('K', client.getInputStream().read()); + return null; + }); + try { + SSLSession session = serverFuture.get(30, TimeUnit.SECONDS); + clientFuture.get(30, TimeUnit.SECONDS); + return session; + } catch (ExecutionException e) { + closeQuietly(server); + closeQuietly(client); + try { + clientFuture.get(5, TimeUnit.SECONDS); + } catch (Exception ignored) { + // Expected when handshake fails. + } + if (e.getCause() instanceof Exception) { + throw (Exception) e.getCause(); + } + if (e.getCause() instanceof Error) { + throw (Error) e.getCause(); + } + throw e; + } + } finally { + executor.shutdownNow(); + } + } + + private static void handshake(SSLEngine client, SSLEngine server) throws IOException { + ByteBuffer c2s = ByteBuffer.allocate(64 * 1024); + ByteBuffer s2c = ByteBuffer.allocate(64 * 1024); + ByteBuffer scratch = ByteBuffer.allocate(64 * 1024); + boolean[] clientDoneFlag = new boolean[1]; + boolean[] serverDoneFlag = new boolean[1]; + client.beginHandshake(); + server.beginHandshake(); + try { + while (client.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING + || server.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING + || c2s.position() > 0 || s2c.position() > 0) { + boolean progress = + TestSSLEnginePair.handshakeStep(client, c2s, s2c, scratch, clientDoneFlag); + progress |= + TestSSLEnginePair.handshakeStep(server, s2c, c2s, scratch, serverDoneFlag); + if (!progress) { + throw new AssertionError("Handshake stalled"); + } + } + // Exchange one application record so post-handshake TLS 1.3 NewSessionTickets are read. + assertEquals(SSLEngineResult.Status.OK, + server.wrap(ByteBuffer.wrap("ok".getBytes(UTF_8)), s2c).getStatus()); + s2c.flip(); + while (s2c.hasRemaining()) { + assertEquals(SSLEngineResult.Status.OK, client.unwrap(s2c, scratch).getStatus()); + } + } finally { + closeQuietly(client); + closeQuietly(server); + } + } + + private static void closeQuietly(SSLEngine engine) { + try { + engine.closeOutbound(); + } catch (Exception ignored) { + // Ignored after failed handshake. + } + } + + private static void closeQuietly(Socket socket) { + try { + socket.close(); + } catch (Exception ignored) { + // Ignored after failed handshake. + } + } + + private final class ClientRig { + final SSLContext context; + final AtomicInteger serverAuthCalls = new AtomicInteger(); + + ClientRig(KeyManager[] keyManagers) throws Exception { + X509TrustManager baseTm = (X509TrustManager) TestKeyStore.getClient().trustManager; + TrustManager countingTm = new X509TrustManager() { + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + serverAuthCalls.incrementAndGet(); + baseTm.checkServerTrusted(chain, authType); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + throw new CertificateException("Unexpected checkClientTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return baseTm.getAcceptedIssuers(); + } + }; + this.context = newContext(keyManagers, countingTm); + } + + SSLEngine newEngine(String host) { + SSLEngine engine = context.createSSLEngine(host, PORT); + engine.setUseClientMode(true); + engine.setEnabledProtocols(new String[] {protocol}); + Conscrypt.setUseSessionTickets(engine, useSessionTickets); + Conscrypt.setHostname(engine, host); + return engine; + } + + SSLSocket newSocket(Socket rawSocket, String host, int port) throws IOException { + SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket(rawSocket, host, + port, true); + socket.setUseClientMode(true); + socket.setEnabledProtocols(new String[] {protocol}); + Conscrypt.setUseSessionTickets(socket, useSessionTickets); + Conscrypt.setHostname(socket, host); + return socket; + } + + byte[] extractSessionBytes() { + ClientSessionContext sessionCtx = + (ClientSessionContext) context.getClientSessionContext(); + Enumeration ids = sessionCtx.getIds(); + assertTrue(ids.hasMoreElements()); + NativeSslSession session = sessionCtx.getSessionFromCache(ids.nextElement()); + assertNotNull(session); + byte[] bytes = session.toBytes(); + assertNotNull(bytes); + return bytes; + } + + ClientRig injectSession(byte[] sessionBytes, String targetHost) { + return injectSession(sessionBytes, targetHost, PORT); + } + + ClientRig injectSession(byte[] sessionBytes, String targetHost, int port) { + ClientSessionContext sessionCtx = + (ClientSessionContext) context.getClientSessionContext(); + NativeSslSession transplanted = + NativeSslSession.newInstance(sessionCtx, sessionBytes, targetHost, port); + assertNotNull(transplanted); + sessionCtx.cacheSession(transplanted); + return this; + } + } + + private static final class SniAwareClientTrustManager extends X509ExtendedTrustManager { + private final X509TrustManager caATm = (X509TrustManager) caA.trustManager; + private final X509TrustManager caBTm = (X509TrustManager) caB.trustManager; + final AtomicInteger clientAuthCalls = new AtomicInteger(); + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + verifyClient(chain, authType, engine.getHandshakeSession()); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + if (!(socket instanceof SSLSocket)) { + throw new CertificateException("Expected SSLSocket"); + } + verifyClient(chain, authType, ((SSLSocket) socket).getHandshakeSession()); + } + + private void verifyClient(X509Certificate[] chain, String authType, SSLSession session) + throws CertificateException { + clientAuthCalls.incrementAndGet(); + if (!(session instanceof ExtendedSSLSession)) { + throw new CertificateException("Missing ExtendedSSLSession"); + } + String sni = null; + List names = ((ExtendedSSLSession) session).getRequestedServerNames(); + if (names != null) { + for (SNIServerName name : names) { + if (name.getType() == StandardConstants.SNI_HOST_NAME + && name instanceof SNIHostName) { + sni = ((SNIHostName) name).getAsciiName(); + break; + } + } + } + if (HOST_A.equalsIgnoreCase(sni)) { + caATm.checkClientTrusted(chain, authType); + } else if (sni == null || HOST_B.equalsIgnoreCase(sni)) { + caBTm.checkClientTrusted(chain, authType); + } else { + throw new CertificateException("Unknown SNI: " + sni); + } + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + throw new CertificateException("SNI unavailable in non-extended TrustManager"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + throw new CertificateException("Unexpected checkServerTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + throw new CertificateException("Unexpected checkServerTrusted"); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + throw new CertificateException("Unexpected checkServerTrusted"); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + List issuers = new ArrayList<>(); + Collections.addAll(issuers, caATm.getAcceptedIssuers()); + Collections.addAll(issuers, caBTm.getAcceptedIssuers()); + return issuers.toArray(new X509Certificate[0]); + } + } +} diff --git a/common/src/test/java/org/conscrypt/TrustManagerImplTest.java b/common/src/test/java/org/conscrypt/TrustManagerImplTest.java index 1771b4319..7c483a927 100644 --- a/common/src/test/java/org/conscrypt/TrustManagerImplTest.java +++ b/common/src/test/java/org/conscrypt/TrustManagerImplTest.java @@ -17,16 +17,24 @@ package org.conscrypt; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.conscrypt.java.security.TestKeyStore; import org.conscrypt.javax.net.ssl.TestHostnameVerifier; +import org.conscrypt.metrics.CertificateTransparencyVerificationReason; +import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; import java.security.KeyStore; import java.security.Principal; import java.security.cert.Certificate; @@ -36,11 +44,16 @@ import java.util.List; import javax.net.ssl.HandshakeCompletedListener; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509ExtendedTrustManager; import javax.net.ssl.X509TrustManager; @RunWith(JUnit4.class) @@ -230,6 +243,105 @@ public void testSetNetworkSecurityPolicy() throws Exception { assertEquals(nsp, tm.getNetworkSecurityPolicy()); } + @Test + public void testDelegatingTrustManagerPreservesNetworkSecurityPolicy() throws Exception { + TestUtils.assumeExtendedTrustManagerAvailable(); + // ConscryptAndroidWithoutTlsSuite runs against uninitialized Android stubs (SDK_INT == 0), + // where SSLSocket creation falls back to KitKat stub sockets and TLS is unsupported. + Assume.assumeTrue(!TestUtils.isAndroid() || TestUtils.isAndroidSdkGreater(23)); + + final NetworkSecurityPolicy requiredEchPolicy = new NetworkSecurityPolicy() { + @Override + public boolean isCertificateTransparencyVerificationRequired(String hostname) { + return false; + } + + @Override + public CertificateTransparencyVerificationReason + getCertificateTransparencyVerificationReason(String hostname) { + return CertificateTransparencyVerificationReason.UNKNOWN; + } + + @Override + public DomainEncryptionMode getDomainEncryptionMode(String hostname) { + return DomainEncryptionMode.REQUIRED; + } + }; + + X509ExtendedTrustManager tm = new X509ExtendedTrustManager() { + @SuppressWarnings("unused") + public NetworkSecurityPolicy getNetworkSecurityPolicy() { + return requiredEchPolicy; + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, + Socket socket) {} + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, + Socket socket) {} + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, + SSLEngine engine) {} + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, + SSLEngine engine) {} + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) {} + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) {} + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }; + + SSLContext sslContext = SSLContext.getInstance("TLS", Conscrypt.newProvider()); + sslContext.init(null, new TrustManager[] {tm}, null); + + final ByteArrayOutputStream clientOutbound = new ByteArrayOutputStream(); + Socket underlyingSocket = new Socket() { + private boolean closed = false; + + @Override + public boolean isConnected() { + return true; + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public void close() { + closed = true; + } + + @Override + public InputStream getInputStream() { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public OutputStream getOutputStream() { + return clientOutbound; + } + }; + + try (SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket( + underlyingSocket, "example.com", 443, true)) { + assertThrows(SSLHandshakeException.class, sslSocket::startHandshake); + assertEquals(0, clientOutbound.size()); + } + } + @Test public void testIntermediateExtendedKeyUsage() throws Exception { TestUtils.assumeExtendedTrustManagerAvailable(); diff --git a/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java b/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java index 82fe22cae..64dd63ff9 100644 --- a/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java +++ b/common/src/test/java/org/conscrypt/java/security/KeyFactoryTestRSA.java @@ -15,6 +15,7 @@ */ package org.conscrypt.java.security; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -22,6 +23,7 @@ // android-add: import libcore.junit.util.EnableDeprecatedBouncyCastleAlgorithmsRule; +import org.conscrypt.TestUtils; // android-add: import org.junit.ClassRule; import org.junit.Test; // android-add: import org.junit.rules.TestRule; @@ -32,6 +34,7 @@ import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -39,16 +42,22 @@ import java.security.Provider; import java.security.PublicKey; import java.security.Security; +import java.security.Signature; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Arrays; +import java.util.Base64; import java.util.List; +import javax.crypto.Cipher; + @RunWith(JUnit4.class) public class KeyFactoryTestRSA extends AbstractKeyFactoryTest { // android-add: Allow access to deprecated BC algorithms. @@ -57,6 +66,14 @@ public KeyFactoryTestRSA() { super("RSA", RSAPublicKeySpec.class, RSAPrivateKeySpec.class); } + private static Provider getConscryptProvider() { + Provider p = Security.getProvider(StandardNames.JSSE_PROVIDER_NAME); + if (p == null) { + p = Security.getProvider("Conscrypt"); + } + return (p != null) ? p : TestUtils.getConscryptProvider(); + } + @Override protected void check(KeyPair keyPair) throws Exception { new CipherAsymmetricCryptHelper("RSA").test(keyPair); @@ -85,7 +102,7 @@ public void testExtraBufferSpace_Public() throws Exception { @Test public void testInvalidKeySpec() throws Exception { - Provider p = Security.getProvider(StandardNames.JSSE_PROVIDER_NAME); + Provider p = getConscryptProvider(); final KeyFactory factory = KeyFactory.getInstance("RSA", p); try { @@ -128,6 +145,444 @@ public void javaSerialization() throws Exception { assertEquals(privatekey, copy); } + /** + * ANDROID COMPATIBILITY GATE (b/473446952, b/493922460): BoringSSL enforces the minimum RSA + * modulus size ({@code OPENSSL_RSA_MIN_MODULUS_BITS = 512}) at compile time in C++ + * ({@code rsa_check_public_key}), while {@code ChainStrengthAnalyzer} separately enforces a + * 1024-bit minimum on X.509 certificate chains validated via {@code TrustManager}. Legacy + * Android apps still rely on 512-bit RSA keys via {@code KeyFactory}, {@code Signature}, and + * {@code Cipher}. Do NOT raise this minimum key-size bound or relax/remove this test without + * an Android compatibility review and an associated AppCompat / aconfig flag. + */ + @Test + public void rsa512BitKeySupported() throws Exception { + Provider p = getConscryptProvider(); + KeyFactory factory = KeyFactory.getInstance("RSA", p); + + RSAPublicKey publicKey = (RSAPublicKey) factory.generatePublic( + new X509EncodedKeySpec(decodeBase64(RSA_512_PUBLIC_KEY_B64))); + assertEquals(512, publicKey.getModulus().bitLength()); + + RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) factory.generatePrivate( + new PKCS8EncodedKeySpec(decodeBase64(RSA_512_PRIVATE_KEY_B64))); + assertEquals(512, privateKey.getModulus().bitLength()); + + RSAPublicKeySpec publicKeySpec = factory.getKeySpec(publicKey, RSAPublicKeySpec.class); + RSAPublicKey publicKeyFromSpec = (RSAPublicKey) factory.generatePublic(publicKeySpec); + assertEquals(512, publicKeyFromSpec.getModulus().bitLength()); + + RSAPrivateCrtKeySpec privateKeySpec = + factory.getKeySpec(privateKey, RSAPrivateCrtKeySpec.class); + RSAPrivateCrtKey privateKeyFromSpec = + (RSAPrivateCrtKey) factory.generatePrivate(privateKeySpec); + assertEquals(512, privateKeyFromSpec.getModulus().bitLength()); + + Signature verifier = Signature.getInstance("SHA256withRSA", p); + verifier.initVerify(publicKey); + verifier.update(COMPAT_GATE_MESSAGE); + assertTrue(verifier.verify(decodeBase64(RSA_512_SHA256_SIG_B64))); + + Signature signer = Signature.getInstance("SHA256withRSA", p); + signer.initSign(privateKeyFromSpec); + signer.update(COMPAT_GATE_MESSAGE); + byte[] runtimeSig = signer.sign(); + + verifier.initVerify(publicKeyFromSpec); + verifier.update(COMPAT_GATE_MESSAGE); + assertTrue(verifier.verify(runtimeSig)); + + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", p); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] ciphertext = cipher.doFinal(COMPAT_GATE_MESSAGE); + cipher.init(Cipher.DECRYPT_MODE, privateKey); + assertArrayEquals(COMPAT_GATE_MESSAGE, cipher.doFinal(ciphertext)); + } + + /** + * ANDROID COMPATIBILITY GATE (b/434718345, b/475843783, b/493922460): BoringSSL enforces the + * maximum RSA modulus size ({@code OPENSSL_RSA_MAX_MODULUS_BITS = 16384}) at compile time in + * C++ ({@code rsa_check_public_key}). Android platform components + * ({@code recoverablekeystore}) and Play App Signing certificates rely on parsing and + * verifying 16384-bit RSA public keys. Lowering this bound previously broke + * {@code EVP_parse_public_key} in CTS and production apps. Do NOT lower this maximum + * key-size bound or relax/remove this test without an Android compatibility review and an + * associated AppCompat / aconfig flag. + */ + @Test + public void rsa16384BitPublicKeySupported() throws Exception { + Provider p = getConscryptProvider(); + KeyFactory factory = KeyFactory.getInstance("RSA", p); + + RSAPublicKey publicKey = (RSAPublicKey) factory.generatePublic( + new X509EncodedKeySpec(decodeBase64(RSA_16384_PUBLIC_KEY_B64))); + assertEquals(16384, publicKey.getModulus().bitLength()); + + RSAPublicKeySpec publicKeySpec = factory.getKeySpec(publicKey, RSAPublicKeySpec.class); + RSAPublicKey publicKeyFromSpec = (RSAPublicKey) factory.generatePublic(publicKeySpec); + assertEquals(16384, publicKeyFromSpec.getModulus().bitLength()); + + byte[] precomputedSig = decodeBase64(RSA_16384_SHA256_SIG_B64); + Signature verifier = Signature.getInstance("SHA256withRSA", p); + verifier.initVerify(publicKey); + verifier.update(COMPAT_GATE_MESSAGE); + assertTrue(verifier.verify(precomputedSig)); + + verifier.initVerify(publicKeyFromSpec); + verifier.update(COMPAT_GATE_MESSAGE); + assertTrue(verifier.verify(precomputedSig)); + } + + /** + * ANDROID COMPATIBILITY GATE (b/434718345, b/475843783, b/493922460): Guards 16384-bit RSA + * private-key parsing and signing separately from {@link #rsa16384BitPublicKeySupported()}, + * as BoringSSL notes that future changes may impose a tighter modulus limit specifically on + * private-key operations ({@code OPENSSL_RSA_MAX_MODULUS_BITS} in {@code openssl/rsa.h}). + * Uses a pre-computed 16384-bit CRT key to avoid slow runtime prime generation. Do NOT lower + * this bound or relax/remove this test without an Android compatibility review and an + * associated AppCompat / aconfig flag. + */ + @Test + public void rsa16384BitPrivateKeySupported() throws Exception { + Provider p = getConscryptProvider(); + KeyFactory factory = KeyFactory.getInstance("RSA", p); + + RSAPublicKey publicKey = (RSAPublicKey) factory.generatePublic( + new X509EncodedKeySpec(decodeBase64(RSA_16384_PUBLIC_KEY_B64))); + RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) factory.generatePrivate( + new PKCS8EncodedKeySpec(decodeBase64(RSA_16384_PRIVATE_KEY_B64))); + assertEquals(16384, privateKey.getModulus().bitLength()); + + RSAPrivateCrtKeySpec privateKeySpec = + factory.getKeySpec(privateKey, RSAPrivateCrtKeySpec.class); + RSAPrivateCrtKey privateKeyFromSpec = + (RSAPrivateCrtKey) factory.generatePrivate(privateKeySpec); + assertEquals(16384, privateKeyFromSpec.getModulus().bitLength()); + + Signature signer = Signature.getInstance("SHA256withRSA", p); + signer.initSign(privateKeyFromSpec); + signer.update(COMPAT_GATE_MESSAGE); + byte[] signature = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA", p); + verifier.initVerify(publicKey); + verifier.update(COMPAT_GATE_MESSAGE); + assertTrue(verifier.verify(signature)); + } + + private static byte[] decodeBase64(String base64) { + return Base64.getDecoder().decode(base64); + } + + private static final byte[] COMPAT_GATE_MESSAGE = + "conscrypt-rsa-compat-gate".getBytes(StandardCharsets.UTF_8); + + // Pre-computed 512-bit and 16384-bit RSA test vectors (X.509 SPKI public keys, PKCS#8 CRT + // private keys, and SHA256withRSA signatures over COMPAT_GATE_MESSAGE). + private static final String RSA_512_PUBLIC_KEY_B64 = + "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOeH8w1QI3HhVdj4az6CjYjMFjx1FzCh" + + "9hIXyPHaZf8NMVx17UAxRNKWyFbN0FtZADCNGJn50/MhYJUDQ7cVB0kCAwEAAQ=="; + + private static final String RSA_512_PRIVATE_KEY_B64 = + "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA54fzDVAjceFV2Phr" + + "PoKNiMwWPHUXMKH2EhfI8dpl/w0xXHXtQDFE0pbIVs3QW1kAMI0YmfnT8yFglQND" + + "txUHSQIDAQABAkAhJ9XFfUlmIHezt3dcH0P3aApzI+1rOHZNhvxurfDXQh2eETBO" + + "1V2SiGgcAAiIoK2UCPIGA++D3R4Elv3pjN5RAiEA/ImRhRXHGxCHHZHYO1dg/S4y" + + "Keja2UwdAeIypVJ3s/UCIQDqtKWMlKR4s721LaWP+nhtzwgks9mSDGP7JLLRYyXF" + + "hQIgaiEOTNXIJTGe9uhR7S5djkkZv88iGewIzL/Y9O1hbPkCIQC7mtPtT+87r+iG" + + "xsrdEEds9py6wau6iv7sA0SQDCFoBQIhALRwYAx9dnWzxuzrkF0S93mFbJqFpmq3" + + "IPGfkEasNW1P"; + + private static final String RSA_512_SHA256_SIG_B64 = + "kwDE3vqKil10xTa4QVEJU1g/5eCJ0Ljqk5W3EPCqgrQ5mOpwXw/j4Ls8P9M0IJcS" + + "tBaO16NQOyuiPyqyzpG2rA=="; + + private static final String RSA_16384_PUBLIC_KEY_B64 = + "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" + + "5RBxd/RUo3GAqjyJ2diODKkCAwEAAQ=="; + + private static final String RSA_16384_PRIVATE_KEY_B64 = + "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" + + "cl+Zj0ddpy18hqchi7iIro7c0iRRY/xmjzsNzbgY8BgOGvvnetldtV9ci8HclnEz" + + "L+MCD9fhgwRt8U2OsBgZuaYoAYH5x2+Zq3YVZ4c115TIa+5orhlKlqq4MLmVC+w2" + + "M+l7DmDCJuSsW3zHOvzXKA04dZbhKPN/o7NH2X1EOqtG714ZM3MGTBzoKgaLIQGA" + + "Ot7y363KtPMru02pUC1yi4ohJmJBqtllEkDzmb98Auf7AlcZK4tlYOwlIpTPy4e+" + + "BkIB98db5K4icrlVoQbQ1Q5yjT9PYH0Hcdlow8gPAeoB/sI76IklFhUt8Y3KLrPw" + + "kbQ0D5aEAbTtKJXuX7gw5LLcG6+0DhYOj9Xs5vqvjhXZpOsLAoIEAQDD6d7u1CDM" + + "gu/1L5ZN6cdZ8ISzyJf9elvoo9/P2EiiV9uX5p9UuGeP34tJorRiscNh/8elXiJA" + + "M9IbIEk9yyFTu+GaLzh/bopWNee8kU9zELts5wKWIxGh4FOQyOQUNZjlElu7OjA6" + + "Icxjf0TRyAIkJqr/w2PK7rfRdCYjJC6lozNqRTaUtwbPpvataIJjIV1LRcrl3IvE" + + "LXVMHLsV33sNiA9Dj7KJT9YL44u6fVNroz/7zxooGhWfgSBrZg9onUkRa2NkIhyt" + + "PMJjzUxSqNjvSZn4K4VORTPow3e6GXqNmbyc/ngGT6q/NhoKzwM2j6wCr4YnBEnl" + + "IFabVtYqowYY2yT6d3j6hvVH+yMT0y3/P24AMJe+LM25wln6XgB3tN9qGXd6lDUd" + + "sMq1tyCn2rZfZHvd3gl1ZoHMNgdlXfZ8b5xbbMUKWNATZ/JnTXiEUmGhj1I/JH79" + + "DaRYT2OWOPohUsjwGGG+iKAK2injIBJbDXXiwowPsXqc1L26Hdimxu45+UGFHHoi" + + "p+3aC4nTUl5O3hsQXdUhg22fjSpOIuRS/3vmtS8bWwVQstQMvyFlyDDTfhyEXqa8" + + "l3ZreFJVrLDY0msf3TY2pB8mpROdwOXWrf22k42A6XOUU/Bapx3IsACQQev9e9oV" + + "TEOW4BLL9xM63HYwiustApfBJ9iTKe+YTRZYILrDocwKNbxoQf42mQwwTXmEBuOe" + + "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" + + "zxwkKzfRtKPnvdf6dqkEGUpbtXiA9m0="; + + private static final String RSA_16384_SHA256_SIG_B64 = + "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"; + @Override protected List getKeys() throws NoSuchAlgorithmException, InvalidKeySpecException { return Arrays.asList(new KeyPair(DefaultKeys.getPublicKey(algorithmName), getPrivateKey())); diff --git a/common/src/test/java/org/conscrypt/java/security/KeyPairGeneratorTestRSA.java b/common/src/test/java/org/conscrypt/java/security/KeyPairGeneratorTestRSA.java index 04b0129b5..d02d860a3 100644 --- a/common/src/test/java/org/conscrypt/java/security/KeyPairGeneratorTestRSA.java +++ b/common/src/test/java/org/conscrypt/java/security/KeyPairGeneratorTestRSA.java @@ -15,12 +15,65 @@ */ package org.conscrypt.java.security; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.conscrypt.TestUtils; +import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Provider; +import java.security.Security; +import java.security.Signature; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; + @RunWith(JUnit4.class) public class KeyPairGeneratorTestRSA extends AbstractKeyPairGeneratorTest { public KeyPairGeneratorTestRSA() { super("RSA", new CipherAsymmetricCryptHelper("RSA")); } + + private static Provider getConscryptProvider() { + Provider p = Security.getProvider(StandardNames.JSSE_PROVIDER_NAME); + if (p == null) { + p = Security.getProvider("Conscrypt"); + } + return (p != null) ? p : TestUtils.getConscryptProvider(); + } + + /** + * ANDROID COMPATIBILITY GATE (b/473446952, b/493922460): BoringSSL enforces the minimum RSA + * modulus size ({@code OPENSSL_RSA_MIN_MODULUS_BITS = 512}) at compile time in C++ + * ({@code RSA_generate_key_ex}), and legacy Android apps still rely on 512-bit RSA keys. Do NOT + * raise this minimum key-size bound or relax/remove this test without an Android compatibility + * review and an associated AppCompat / aconfig flag. + */ + @Test + public void rsa512BitKeyGenerationSupported() throws Exception { + Provider p = getConscryptProvider(); + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", p); + generator.initialize(512); + KeyPair keyPair = generator.generateKeyPair(); + + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + assertEquals(512, publicKey.getModulus().bitLength()); + assertEquals(512, privateKey.getModulus().bitLength()); + + byte[] message = "conscrypt-rsa-compat-gate".getBytes(StandardCharsets.UTF_8); + Signature signer = Signature.getInstance("SHA256withRSA", p); + signer.initSign(privateKey); + signer.update(message); + byte[] signature = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA", p); + verifier.initVerify(publicKey); + verifier.update(message); + assertTrue(verifier.verify(signature)); + } } diff --git a/common/src/test/java/org/conscrypt/java/security/MessageDigestTest.java b/common/src/test/java/org/conscrypt/java/security/MessageDigestTest.java index 8801c70ac..892520c0f 100644 --- a/common/src/test/java/org/conscrypt/java/security/MessageDigestTest.java +++ b/common/src/test/java/org/conscrypt/java/security/MessageDigestTest.java @@ -16,10 +16,10 @@ package org.conscrypt.java.security; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; // android-add: import libcore.junit.util.EnableDeprecatedBouncyCastleAlgorithmsRule; - import org.conscrypt.TestUtils; // android-add: import org.junit.ClassRule; import org.junit.Test; @@ -27,8 +27,10 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.Provider; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; @@ -220,6 +222,54 @@ private void test_MessageDigest(MessageDigest md) throws Exception { } } + // SHAKE256 with 512-bit output of the 1600-bit message consisting of 200 bytes of 0xa3, from + // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHAKE256_Msg1600.pdf + private static final String SHAKE256_512_OF_MSG1600 = + "cd8a920ed141aa0407a22d59288652e9d9f1a7ee0c1e7c1ca699424da84a904d" + + "2d700caae7396ece96604440577da4f3aa22aeb8857f961c4cd8e06f0ae6610b"; + + /** + * SHAKE256 is an extendable-output function, which Conscrypt exposes through the fixed-length + * MessageDigest algorithm "SHAKE256-512". Checks that the fixed output length is applied + * consistently across one-shot, incremental, cloned, and reused digests. + */ + @Test + public void testShake256_512() throws Exception { + Provider conscrypt = TestUtils.getConscryptProvider(); + byte[] msg1600 = new byte[200]; + Arrays.fill(msg1600, (byte) 0xa3); + byte[] expectedMsg1600 = TestUtils.decodeHex(SHAKE256_512_OF_MSG1600); + byte[] expectedEmpty = getExpectations("SHAKE256-512").get(INPUT_EMPTY); + + MessageDigest md = MessageDigest.getInstance("SHAKE256-512", conscrypt); + assertEquals("SHAKE256-512", md.getAlgorithm()); + assertEquals(64, md.getDigestLength()); + assertArrayEquals(expectedMsg1600, md.digest(msg1600)); + + // digest() resets the state, so the same instance can be reused. + assertArrayEquals(expectedEmpty, md.digest()); + + // Incremental updates give the same result as the one-shot computation. + md.update(msg1600, 0, 100); + for (int i = 100; i < 150; i++) { + md.update(msg1600[i]); + } + md.update(ByteBuffer.wrap(msg1600, 150, 50)); + assertArrayEquals(expectedMsg1600, md.digest()); + + // A clone taken part-way through continues independently of the original. + md.update(msg1600, 0, 100); + MessageDigest copy = (MessageDigest) md.clone(); + md.reset(); + assertArrayEquals(expectedMsg1600, copy.digest(Arrays.copyOfRange(msg1600, 100, 200))); + assertArrayEquals(expectedEmpty, md.digest()); + + // The id-shake256 OID (RFC 8702) is an alias for SHAKE256-512. + MessageDigest byOid = MessageDigest.getInstance("2.16.840.1.101.3.4.2.12", conscrypt); + assertEquals(64, byOid.getDigestLength()); + assertArrayEquals(expectedMsg1600, byOid.digest(msg1600)); + } + private String javaBytes(byte[] bytes) { StringBuilder buf = new StringBuilder(); buf.append("new byte[] { "); diff --git a/common/src/test/java/org/conscrypt/java/security/SignatureTest.java b/common/src/test/java/org/conscrypt/java/security/SignatureTest.java index 11c977ef8..e24af6973 100644 --- a/common/src/test/java/org/conscrypt/java/security/SignatureTest.java +++ b/common/src/test/java/org/conscrypt/java/security/SignatureTest.java @@ -111,6 +111,12 @@ public void test_getInstance() throws Exception { .skipAlgorithm("ML-DSA-44") .skipAlgorithm("ML-DSA-65") .skipAlgorithm("ML-DSA-87") + // EXTERNAL-MU-ML-DSA is skipped because it only signs (a 64-byte message + // representative, not arbitrary data) and does not support initVerify(). + .skipAlgorithm("EXTERNAL-MU-ML-DSA") + .skipAlgorithm("EXTERNAL-MU-ML-DSA-44") + .skipAlgorithm("EXTERNAL-MU-ML-DSA-65") + .skipAlgorithm("EXTERNAL-MU-ML-DSA-87") // SLH-DSA-SHA2-128S is skipped because it doesn't yet support getFormat() and // getEncoded(). .skipAlgorithm("SLH-DSA-SHA2-128S") diff --git a/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketTest.java b/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketTest.java index 9472d3b7e..948ecde2f 100644 --- a/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketTest.java +++ b/common/src/test/java/org/conscrypt/javax/net/ssl/SSLSocketTest.java @@ -39,6 +39,7 @@ import org.conscrypt.tlswire.handshake.EllipticCurve; import org.conscrypt.tlswire.handshake.EllipticCurvesHelloExtension; import org.conscrypt.tlswire.handshake.HelloExtension; +import org.conscrypt.tlswire.handshake.SignatureAlgorithmsHelloExtension; import org.conscrypt.tlswire.util.TlsProtocolVersion; import org.junit.After; import org.junit.Before; @@ -149,6 +150,10 @@ public void teardown() throws InterruptedException { assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); } + // ANDROID COMPATIBILITY GATE: Guards the default SSLSocket configuration (enabled cipher + // suites, protocols, client mode, and session creation). Do NOT relax or update expected + // defaults for upstream changes without an Android compatibility review and an AppCompat / + // aconfig flag. @Test public void test_SSLSocket_defaultConfiguration() throws Exception { SSLConfigurationAsserts.assertSSLSocketDefaultConfiguration( @@ -1015,15 +1020,8 @@ public void handshake_noNamedGroupsProperty_usesDefaultGroups() throws Exception }); s.get(); c.get(); - // By default, BoringSSL uses X25519, P-256, and P-384, in this order. - // So X25519 gets priority. - // We also allow for X25519MLKEM768, as that may be the default in the future. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Unexpected client curve: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Unexpected server curve: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); client.close(); server.close(); context.close(); @@ -1132,6 +1130,13 @@ private static boolean isTlsPqcFlagEnabled() { } } + // ANDROID COMPATIBILITY GATE: Guards the top-priority default named group negotiated during a + // TLS handshake when no explicit namedGroups are configured. Do NOT modify without an Android + // compatibility review and an associated AppCompat / aconfig flag. + private static void assertDefaultCurveName(String actualCurve) { + assertEquals(TestUtils.isPqcDefaultEnabled() ? "X25519MLKEM768" : "X25519", actualCurve); + } + @Test public void defaultNamedGroups_compatChangeEnabled_includesPqcAndExpectedGroups() throws Exception { @@ -1217,6 +1222,164 @@ public void defaultNamedGroups_compatChangeDisabled_usesClassicalGroupsOnly() } } + private static final long ENABLE_TLS_PQC_DEFAULT_SIGNATURE_ALGORITHMS = 576621461L; + + private static void setSignatureAlgorithmsCompatChangeEnabled(boolean enabled) + throws Exception { + try { + Class platformClass = + Class.forName(TestUtils.class.getPackage().getName() + ".Platform"); + platformClass + .getMethod("setPqcDefaultSignatureAlgorithmsEnabledForTesting", boolean.class) + .invoke(null, enabled); + return; + } catch (ReflectiveOperationException ignored) { + // Platform module uses android.compat.Compatibility overrides instead. + } + setCompatChangeEnabled(ENABLE_TLS_PQC_DEFAULT_SIGNATURE_ALGORITHMS, enabled); + } + + private static void clearSignatureAlgorithmsCompatChangeOverrides() throws Exception { + try { + Class platformClass = + Class.forName(TestUtils.class.getPackage().getName() + ".Platform"); + platformClass + .getMethod("setPqcDefaultSignatureAlgorithmsEnabledForTesting", boolean.class) + .invoke(null, true); + return; + } catch (ReflectiveOperationException ignored) { + // Platform module uses android.compat.Compatibility overrides instead. + } + clearCompatChangeOverrides(); + } + + private static boolean isConscryptSignatureAlgorithmsCompatSupported() { + if (!isConscryptPqcCompatConfigPresent()) { + return false; + } + try { + Class platformClass = + Class.forName(TestUtils.class.getPackage().getName() + ".Platform"); + return platformClass.getDeclaredMethod("isPqcDefaultSignatureAlgorithmsEnabled") + != null; + } catch (ReflectiveOperationException | SecurityException e) { + return false; + } + } + + private static boolean isTlsPqcSignatureAlgorithmsFlagEnabled() { + String basePkg = TestUtils.class.getPackage().getName(); + try { + Class testFlagsClass = Class.forName(basePkg + ".test.flags.Flags"); + return (Boolean) testFlagsClass.getMethod("tlsPqcDefaultSignatureAlgorithms") + .invoke(null); + } catch (ClassNotFoundException ignored) { + // Fall back to non-repackaged Flags class when running outside conscrypt-tests. + } catch (ReflectiveOperationException e) { + return false; + } + try { + Class flagsClass = Class.forName(basePkg + ".flags.Flags"); + return (Boolean) flagsClass.getMethod("tlsPqcDefaultSignatureAlgorithms").invoke(null); + } catch (ClassNotFoundException e) { + return true; + } catch (ReflectiveOperationException e) { + return false; + } + } + + @Test + public void defaultSignatureAlgorithms_compatChangeEnabled_includesPqcAndExpectedAlgorithms() + throws Exception { + assumeTrue(isConscryptSignatureAlgorithmsCompatSupported()); + assumeTrue(isTlsPqcSignatureAlgorithmsFlagEnabled()); + TestSSLContext context = null; + try { + setSignatureAlgorithmsCompatChangeEnabled(true); + context = TestSSLContext.create(); + ClientHello clientHello = TlsTester.captureTlsHandshakeClientHello( + executor, context.clientContext.getSocketFactory()); + SignatureAlgorithmsHelloExtension sigAlgsExtension = + (SignatureAlgorithmsHelloExtension) clientHello.findExtensionByType( + HelloExtension.TYPE_SIGNATURE_ALGORITHMS); + assertNotNull(sigAlgsExtension); + assertTrue(sigAlgsExtension.wellFormed); + assertEquals(Arrays.asList("mldsa44", "mldsa65", "mldsa87", "ecdsa_secp256r1_sha256", + "rsa_pss_rsae_sha256", "rsa_pkcs1_sha256", + "ecdsa_secp384r1_sha384", "rsa_pss_rsae_sha384", + "rsa_pkcs1_sha384", "rsa_pss_rsae_sha512", + "rsa_pkcs1_sha512", "rsa_pkcs1_sha1"), + sigAlgsExtension.supported); + + final SSLSocket client = + (SSLSocket) context.clientContext.getSocketFactory().createSocket( + context.host, context.port); + final SSLSocket server = (SSLSocket) context.serverSocket.accept(); + Future s = runAsync(() -> { + server.startHandshake(); + return null; + }); + Future c = runAsync(() -> { + client.startHandshake(); + return null; + }); + s.get(); + c.get(); + client.close(); + server.close(); + } finally { + if (context != null) { + context.close(); + } + clearSignatureAlgorithmsCompatChangeOverrides(); + } + } + + @Test + public void defaultSignatureAlgorithms_compatChangeDisabled_usesClassicalAlgorithmsOnly() + throws Exception { + assumeTrue(isConscryptSignatureAlgorithmsCompatSupported()); + TestSSLContext context = null; + try { + setSignatureAlgorithmsCompatChangeEnabled(false); + context = TestSSLContext.create(); + ClientHello clientHello = TlsTester.captureTlsHandshakeClientHello( + executor, context.clientContext.getSocketFactory()); + SignatureAlgorithmsHelloExtension sigAlgsExtension = + (SignatureAlgorithmsHelloExtension) clientHello.findExtensionByType( + HelloExtension.TYPE_SIGNATURE_ALGORITHMS); + assertNotNull(sigAlgsExtension); + assertTrue(sigAlgsExtension.wellFormed); + assertEquals(Arrays.asList("ecdsa_secp256r1_sha256", "rsa_pss_rsae_sha256", + "rsa_pkcs1_sha256", "ecdsa_secp384r1_sha384", + "rsa_pss_rsae_sha384", "rsa_pkcs1_sha384", + "rsa_pss_rsae_sha512", "rsa_pkcs1_sha512", "rsa_pkcs1_sha1"), + sigAlgsExtension.supported); + + final SSLSocket client = + (SSLSocket) context.clientContext.getSocketFactory().createSocket( + context.host, context.port); + final SSLSocket server = (SSLSocket) context.serverSocket.accept(); + Future s = runAsync(() -> { + server.startHandshake(); + return null; + }); + Future c = runAsync(() -> { + client.startHandshake(); + return null; + }); + s.get(); + c.get(); + client.close(); + server.close(); + } finally { + if (context != null) { + context.close(); + } + clearSignatureAlgorithmsCompatChangeOverrides(); + } + } + @Test public void handshake_p256IsSupportedByDefault() throws Exception { TestSSLContext context = TestSSLContext.create(); @@ -1236,20 +1399,15 @@ public void handshake_p256IsSupportedByDefault() throws Exception { }); s.get(); c.get(); - // By default, BoringSSL uses X25519, P-256, and P-384. - // On newer versions of BoringSSL, X25519MLKEM768 is also a default. + // P-256 is included in Conscrypt's pinned default namedGroups list. if (sslParametersSupportsNamedGroups()) { // If the client requests P-256, it will be chosen. assertEquals("P-256", getCurveName(client)); assertEquals("P-256", getCurveName(server)); } else { - // Otherwise, X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // Otherwise, the platform's top-priority default namedGroup is negotiated. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1276,20 +1434,15 @@ public void handshake_p384IsSupportedByDefault() throws Exception { }); s.get(); c.get(); - // By default, BoringSSL uses X25519, P-256, and P-384. - // On newer versions of BoringSSL, X25519MLKEM768 is also a default. + // P-384 is included in Conscrypt's pinned default namedGroups list. if (sslParametersSupportsNamedGroups()) { // If the client requests P-384, it will be chosen. assertEquals("P-384", getCurveName(client)); assertEquals("P-384", getCurveName(server)); } else { - // Otherwise, X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // Otherwise, the platform's top-priority default namedGroup is negotiated. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1324,13 +1477,9 @@ public void handshake_setsNamedGroups_usesFirstServerNamedGroupThatClientSupport assertEquals("P-384", getCurveName(client)); assertEquals("P-384", getCurveName(server)); } else { - // The defaults are used, and X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // The platform's pinned default namedGroups are used. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1387,13 +1536,9 @@ public void handshake_setsNamedGroupsBeforeAccept_usesFirstServerNamedGroupThatC assertEquals("P-384", getCurveName(client)); assertEquals("P-384", getCurveName(server)); } else { - // The defaults are used, X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // The platform's pinned default namedGroups are used. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1426,13 +1571,9 @@ public void handshake_onlyX25519MLKEM768_works() throws Exception { assertEquals("X25519MLKEM768", getCurveName(client)); assertEquals("X25519MLKEM768", getCurveName(server)); } else { - // The defaults are used, and X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // The platform's pinned default namedGroups are used. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1465,13 +1606,9 @@ public void handshake_onlyMLKEM1024_works() throws Exception { assertEquals("MLKEM1024", getCurveName(client)); assertEquals("MLKEM1024", getCurveName(server)); } else { - // The defaults are used, and X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // The platform's pinned default namedGroups are used. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1506,13 +1643,9 @@ public void handshake_namedGroupsDontIntersect_throwsException() throws Exceptio } else { s.get(); c.get(); - // The defaults are used, and X25519 or X25519MLKEM768 gets priority. - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Curve is not X25519 or X25519MLKEM768: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + // The platform's pinned default namedGroups are used. + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); } client.close(); server.close(); @@ -1621,18 +1754,19 @@ public void setNamedGroupsProperty_invalidValue_isIgnored() throws Exception { }); s.get(); c.get(); - String clientCurve = getCurveName(client); - String serverCurve = getCurveName(server); - assertTrue("Unexpected client curve: " + clientCurve, - clientCurve.equals("X25519") || clientCurve.equals("X25519MLKEM768")); - assertTrue("Unexpected server curve: " + serverCurve, - serverCurve.equals("X25519") || serverCurve.equals("X25519MLKEM768")); + assertDefaultCurveName(getCurveName(client)); + assertDefaultCurveName(getCurveName(server)); client.close(); server.close(); context.close(); } } + // ANDROID COMPATIBILITY GATE: The ClientHello wire-format tests below + // (test_SSLSocket_ClientHello_supportedCurves, signatureAlgorithms, clientProtocolVersion, + // compressionMethods) guard Android app compatibility on the wire. Do NOT relax or update + // these assertions to accommodate upstream BoringSSL or Conscrypt changes without an Android + // compatibility review and an associated AppCompat / aconfig flag. @Test public void test_SSLSocket_ClientHello_supportedCurves() throws Exception { ForEachRunner.runNamed(sslSocketFactory -> { @@ -1656,6 +1790,26 @@ public void test_SSLSocket_ClientHello_supportedCurves() throws Exception { }, getSSLSocketFactoriesToTest()); } + @Test + public void test_SSLSocket_ClientHello_signatureAlgorithms() throws Exception { + ForEachRunner.runNamed(sslSocketFactory -> { + ClientHello clientHello = + TlsTester.captureTlsHandshakeClientHello(executor, sslSocketFactory); + SignatureAlgorithmsHelloExtension sigAlgsExtension = + (SignatureAlgorithmsHelloExtension) clientHello.findExtensionByType( + HelloExtension.TYPE_SIGNATURE_ALGORITHMS); + final String[] supportedSignatureAlgorithms; + if (sigAlgsExtension == null) { + supportedSignatureAlgorithms = new String[0]; + } else { + assertTrue(sigAlgsExtension.wellFormed); + supportedSignatureAlgorithms = + sigAlgsExtension.supported.toArray(new String[0]); + } + StandardNames.assertDefaultSignatureAlgorithms(supportedSignatureAlgorithms); + }, getSSLSocketFactoriesToTest()); + } + @Test public void test_SSLSocket_ClientHello_clientProtocolVersion() throws Exception { ForEachRunner.runNamed(sslSocketFactory -> { diff --git a/common/src/test/java/org/conscrypt/util/MtcUtilsTest.java b/common/src/test/java/org/conscrypt/pqc/MtcUtilsTest.java similarity index 61% rename from common/src/test/java/org/conscrypt/util/MtcUtilsTest.java rename to common/src/test/java/org/conscrypt/pqc/MtcUtilsTest.java index 237056ba0..989e2d341 100644 --- a/common/src/test/java/org/conscrypt/util/MtcUtilsTest.java +++ b/common/src/test/java/org/conscrypt/pqc/MtcUtilsTest.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.conscrypt.util; +package org.conscrypt.pqc; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -22,6 +22,7 @@ import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import org.conscrypt.util.DerUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -37,43 +38,42 @@ @RunWith(JUnit4.class) public class MtcUtilsTest { - // Valid MTC CA certificate (CA ID 32473.1, Subject RDN 1.3.6.1.4.1.44363.47.3=#0D0481FD5901, - // critical extension 1.3.6.1.4.1.44363.47.4 with minSerial=0x1000000000000, + // Valid MTC CA certificate (CA ID 32473.1, Subject RDN 1.3.6.1.5.5.7.25.3=#0D0481FD5901, + // critical extension 1.3.6.1.5.5.7.1.38 with minSerial=0x1000000000000, // maxSerial=0x5ffffffffffff). private static final String VALID_MTC_CA_PEM = "-----BEGIN CERTIFICATE-----\n" - + "MIIGADCCBe2gAwIBAgIBATAKBggrBgEFBQcGJDAQMQ4wDAYIKwYBBQUHGQEMADAe\n" - + "Fw0yMDAxMDEwMDAwMDBaFw0zMDEyMzEyMzU5NTlaMBYxFDASBgorBgEEAYLaSy8D\n" - + "DQSB/VkBMIIFMjALBglghkgBZQMEAxEDggUhAFzN/zgGMsaBJd+nNwxE0mZlxiSI\n" - + "OIrZwLSScveu9rIIIPfYjTEvKetlhX1W5quTKhFrZqvMzskfSBqUqMuqMCcykhiC\n" - + "5x5r4GVBvK2GCaP2sTCOM5kJ9hzwCevraUeClJhgDB8dRpYuJox68eNkNnfDsYTN\n" - + "pfB1HUey8jfDhI9+tGmtHC7apuIEyeYyAMwYobBeCquk4ikCb04KoYQRWkhPSDnN\n" - + "4XLfY+otOwXy4Ev96V6pK74UrTwHKSzMQPMTF0O8zsVJKgSSNfd1zJp+Tk/CHZDD\n" - + "2+ZcFMzcU2BdAO0QiMb6O3BOLK5eg1ZFcX/abzQyNcBo3hfuvHlSTsOezgh3u4/x\n" - + "q4zALLfVTcNQAqY0E6HTSrt+3K7MJhmRwQfr8IsyB+x8nAuesYGrzJbCzDq4Wmfu\n" - + "R+LCOujNQNT26yBwTIbEUCCRQAz6htYICqmW8jD6hjLnlizUE1lTG2kp/lvtqJj8\n" - + "AGu654MkUsxVOUAMP1LV3DTHq5RmhZd5oET63yQ/pj+CBzsZx9iJf3ovbNJ7LRGr\n" - + "nMba9L85KTIjF9vtJKdiQp5Td7gyUlDhKeajvk4VJ6baQa1xuYxa6thcBt18E8Jx\n" - + "OBvXO8qw+l3jOJnzZdDtnFg3TajfCb1OUZ5cpcEajPtT7IhgbGhKu1B8bcIynUy8\n" - + "N6Wb99SBdBn8xbaWJOdsq++Yi45VVBdlCL/4psXG6hRoot4V21yUO9xQCQCXYsSI\n" - + "EQwnUmOkoK82UQ3v0n5Z5K/KZhS6bIWc7zEAp5WU7DBAye8V+rSAoLvxeJE9uvMU\n" - + "2twQDBVOQAfqVSpskzMZpypMdPPjnBUk0vUaOIih2UuCqLooT/yL54PXO3WHLPj0\n" - + "G6XKmQ92ksFPyc7skwwnYSh2PDk879/m6i4/8s37i9e6T68O5oQWf7CMShV2z50w\n" - + "Dkuy34hzHQzCtJ0HWdH73q31etKfIvR11ni7aWVmRGlmU8xXjMATrgJ3w9I8aVY4\n" - + "M9LG0ykCJYhwZG74zr4WRTr/LEdr97H06D7TZKsBM/jdfHYKLu3VYciHAnwI7iAM\n" - + "htR3cw9lMGs1NLKdYi12vWdSIiSH//1o6Foa+Yej9j+h4LbNn0orlEZMLBPx+bAf\n" - + "OzYKIYegyAsxguFvDYDCIhOQ6ZuCD49RyXOKgcfgklFi2d3wiQSyPMAl8nGG1Hun\n" - + "PdJWVRx4tPx+8/SY8TVcFiTciW/Itdy8uytslOR0h5fB5dQFWxJXaClRzlvOqHXA\n" - + "bSthBETzCpMDkeRk4qg5MCmrTFepTeshtKC3cwRcPXQo0jys3VrVASLjQehcm7k1\n" - + "hFXo9TkfBY5hYShjOYoekIuy3wI3dr+SeARSJre2VMxdyd6ZEtQrfaz0pbQaOIr5\n" - + "CqcM7uyR/lycHlbnwsE2pKPubbFXev836BjfQItaIX2SExK/1rlbXs/rDAidw3Ts\n" - + "c2XO2Lh8AfG5SPgcJeo3cOQhjhywqECjwcPsTl0CwHDqiW++8wyBGPTyl5niOYPu\n" - + "VQhAF6wPYUQD8xBywy5QpgvRajWv7LZ0/wztQhkjSiAs453WwRn2WaDlXqAX3xjC\n" - + "p7UC5NCoB02LCE1xzQa++plEg5uvdMPyFeGRxqmBmU0jUH4PeJyEQJXj0lj2/W+y\n" - + "YyjbwO51qHyK6AuLyDexkLR2y/H2y+cG4LfRYpI4kmTTItPgzEqSbuhhEKIPZRGR\n" - + "y5p/8IJvwTDmjQ3H9FwJH9yKBxIoDJIB+9wYkumo/GbvyZ2m1lAVsxI6WqajVzBV\n" - + "MA4GA1UdDwEB/wQEAwICBDAPBgNVHRMBAf8EBTADAQH/MDIGCisGAQQBgtpLLwQB\n" - + "Af8EITAfMAsGCWCGSAFlAwQDEQIHAQAAAAAAAAIHBf///////zAKBggrBgEFBQcG\n" - + "JAMBAA==\n" + + "MIIF/DCCBemgAwIBAgIBATAKBggrBgEFBQcGJDAQMQ4wDAYIKwYBBQUHGQEMADAe\n" + + "Fw0yMDAxMDEwMDAwMDBaFw0zMDEyMzEyMzU5NTlaMBQxEjAQBggrBgEFBQcZAw0E\n" + + "gf1ZATCCBTIwCwYJYIZIAWUDBAMRA4IFIQBczf84BjLGgSXfpzcMRNJmZcYkiDiK\n" + + "2cC0knL3rvayCCD32I0xLynrZYV9VuarkyoRa2arzM7JH0galKjLqjAnMpIYguce\n" + + "a+BlQbythgmj9rEwjjOZCfYc8Anr62lHgpSYYAwfHUaWLiaMevHjZDZ3w7GEzaXw\n" + + "dR1HsvI3w4SPfrRprRwu2qbiBMnmMgDMGKGwXgqrpOIpAm9OCqGEEVpIT0g5zeFy\n" + + "32PqLTsF8uBL/eleqSu+FK08BykszEDzExdDvM7FSSoEkjX3dcyafk5Pwh2Qw9vm\n" + + "XBTM3FNgXQDtEIjG+jtwTiyuXoNWRXF/2m80MjXAaN4X7rx5Uk7Dns4Id7uP8auM\n" + + "wCy31U3DUAKmNBOh00q7ftyuzCYZkcEH6/CLMgfsfJwLnrGBq8yWwsw6uFpn7kfi\n" + + "wjrozUDU9usgcEyGxFAgkUAM+obWCAqplvIw+oYy55Ys1BNZUxtpKf5b7aiY/ABr\n" + + "uueDJFLMVTlADD9S1dw0x6uUZoWXeaBE+t8kP6Y/ggc7GcfYiX96L2zSey0Rq5zG\n" + + "2vS/OSkyIxfb7SSnYkKeU3e4MlJQ4Snmo75OFSem2kGtcbmMWurYXAbdfBPCcTgb\n" + + "1zvKsPpd4ziZ82XQ7ZxYN02o3wm9TlGeXKXBGoz7U+yIYGxoSrtQfG3CMp1MvDel\n" + + "m/fUgXQZ/MW2liTnbKvvmIuOVVQXZQi/+KbFxuoUaKLeFdtclDvcUAkAl2LEiBEM\n" + + "J1JjpKCvNlEN79J+WeSvymYUumyFnO8xAKeVlOwwQMnvFfq0gKC78XiRPbrzFNrc\n" + + "EAwVTkAH6lUqbJMzGacqTHTz45wVJNL1GjiIodlLgqi6KE/8i+eD1zt1hyz49Bul\n" + + "ypkPdpLBT8nO7JMMJ2Eodjw5PO/f5uouP/LN+4vXuk+vDuaEFn+wjEoVds+dMA5L\n" + + "st+Icx0MwrSdB1nR+96t9XrSnyL0ddZ4u2llZkRpZlPMV4zAE64Cd8PSPGlWODPS\n" + + "xtMpAiWIcGRu+M6+FkU6/yxHa/ex9Og+02SrATP43Xx2Ci7t1WHIhwJ8CO4gDIbU\n" + + "d3MPZTBrNTSynWItdr1nUiIkh//9aOhaGvmHo/Y/oeC2zZ9KK5RGTCwT8fmwHzs2\n" + + "CiGHoMgLMYLhbw2AwiITkOmbgg+PUclzioHH4JJRYtnd8IkEsjzAJfJxhtR7pz3S\n" + + "VlUceLT8fvP0mPE1XBYk3IlvyLXcvLsrbJTkdIeXweXUBVsSV2gpUc5bzqh1wG0r\n" + + "YQRE8wqTA5HkZOKoOTApq0xXqU3rIbSgt3MEXD10KNI8rN1a1QEi40HoXJu5NYRV\n" + + "6PU5HwWOYWEoYzmKHpCLst8CN3a/kngEUia3tlTMXcnemRLUK32s9KW0GjiK+Qqn\n" + + "DO7skf5cnB5W58LBNqSj7m2xV3r/N+gY30CLWiF9khMSv9a5W17P6wwIncN07HNl\n" + + "zti4fAHxuUj4HCXqN3DkIY4csKhAo8HD7E5dAsBw6olvvvMMgRj08peZ4jmD7lUI\n" + + "QBesD2FEA/MQcsMuUKYL0Wo1r+y2dP8M7UIZI0ogLOOd1sEZ9lmg5V6gF98Ywqe1\n" + + "AuTQqAdNiwhNcc0GvvqZRIObr3TD8hXhkcapgZlNI1B+D3ichECV49JY9v1vsmMo\n" + + "28Dudah8iugLi8g3sZC0dsvx9svnBuC30WKSOJJk0yLT4MxKkm7oYRCiD2URkcua\n" + + "f/CCb8Ew5o0Nx/RcCR/cigcSKAySAfvcGJLpqPxm78mdptZQFbMSOlqmo1UwUzAO\n" + + "BgNVHQ8BAf8EBAMCAgQwDwYDVR0TAQH/BAUwAwEB/zAwBggrBgEFBQcBJgEB/wQh\n" + + "MB8wCwYJYIZIAWUDBAMRAgcBAAAAAAAAAgcF////////MAoGCCsGAQUFBwYkAwEA\n" + "-----END CERTIFICATE-----\n"; private static X509Certificate parseCert(String pem) throws Exception { @@ -176,6 +176,44 @@ public void testIsValidSubtree() { assertFalse(MtcUtils.isValidSubtree(2, 6)); } + @Test + public void testReadUint24() throws Exception { + ByteBuffer buf = ByteBuffer.wrap( + new byte[] {0x00, 0x09, 0x7b, (byte) 0xff, (byte) 0xff, (byte) 0xff}); + assertEquals(0x00097b, MtcUtils.readUint24(buf)); + assertEquals(0xffffff, MtcUtils.readUint24(buf)); + + // Buffer with fewer than 3 bytes must throw CertificateException + ByteBuffer shortBuf = ByteBuffer.wrap(new byte[] {0x01, 0x02}); + assertThrows(CertificateException.class, () -> MtcUtils.readUint24(shortBuf)); + } + + @Test + public void testValidateExtensions() throws Exception { + // Empty extensions vector is valid + MtcUtils.validateExtensions(new byte[0]); + + // Strictly ascending extension_types (1, 2) with empty and 1-byte data are valid + MtcUtils.validateExtensions( + new byte[] {0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x42}); + + // Duplicate extension_type (1, 1) must be rejected + assertThrows(CertificateException.class, + () + -> MtcUtils.validateExtensions( + new byte[] {0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00})); + + // Out-of-order extension_type (2, 1) must be rejected + assertThrows(CertificateException.class, + () + -> MtcUtils.validateExtensions( + new byte[] {0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00})); + + // Truncated extension entry must be rejected + assertThrows(CertificateException.class, + () -> MtcUtils.validateExtensions(new byte[] {0x00, 0x01, 0x00, 0x02, 0x42})); + } + private static byte[] packSignatures(byte[][] cids, byte[][] sigs) { int total = 0; for (int i = 0; i < cids.length; i++) { diff --git a/constants/src/gen/cpp/generate_constants.cc b/constants/src/gen/cpp/generate_constants.cc index 6beea101d..770553c3c 100644 --- a/constants/src/gen/cpp/generate_constants.cc +++ b/constants/src/gen/cpp/generate_constants.cc @@ -116,6 +116,9 @@ int main(int argc, char** argv) { CONST(SSL_SIGN_RSA_PSS_RSAE_SHA384); CONST(SSL_SIGN_RSA_PSS_RSAE_SHA512); CONST(SSL_SIGN_ED25519); + CONST(SSL_SIGN_ML_DSA_44); + CONST(SSL_SIGN_ML_DSA_65); + CONST(SSL_SIGN_ML_DSA_87); CONST(SSL_VERIFY_NONE); CONST(SSL_VERIFY_PEER); diff --git a/openjdk/src/main/java/org/conscrypt/EchConfigMismatchException.java b/openjdk/src/main/java/org/conscrypt/EchConfigMismatchException.java index e9a7b874c..2a9e3ea5c 100644 --- a/openjdk/src/main/java/org/conscrypt/EchConfigMismatchException.java +++ b/openjdk/src/main/java/org/conscrypt/EchConfigMismatchException.java @@ -21,10 +21,24 @@ /** * Exception thrown when the provided ECH (Encrypted Client Hello) config does not match the server. * - *

    Before accessing the retry configuration, clients must call {@link #getPublicHostname()} - * and verify that the hostname matches the connection hostname (using their preferred {@link - * javax.net.ssl.HostnameVerifier}). If the returned hostname is {@code null}, any provided retry - * configuration must be ignored. + *

    Before accessing the retry configuration, clients must verify that the server's + * certificate is valid for the hostname returned by {@link #getPublicHostname()}. If the returned + * hostname is {@code null}, any provided retry configuration must be ignored. Whether the client + * has to perform this check itself depends on how the connection was configured: + * + *

      + *
    • If HTTPS endpoint identification was enabled, by calling {@link + * javax.net.ssl.SSLParameters#setEndpointIdentificationAlgorithm(String)} with {@code + * "HTTPS"}, and a Conscrypt {@link javax.net.ssl.TrustManager} is used, the certificate has + * already been verified against {@link #getPublicHostname()} during the handshake, so no + * further hostname check is needed. If the certificate is not valid for the public hostname, + * this exception is not thrown; the handshake instead fails with an {@link + * javax.net.ssl.SSLHandshakeException} whose cause is a {@link + * java.security.cert.CertificateException}. + *
    • Otherwise, clients must check the hostname themselves, for example by passing {@link + * #getPublicHostname()} and the connection's {@link javax.net.ssl.SSLSession} to their + * preferred {@link javax.net.ssl.HostnameVerifier}. + *
    * *

    Clients can then attempt to establish a new connection, using the provided retry {@link * EchConfigList}, if available. A retry {@link EchConfigList} may not be available if the server @@ -39,7 +53,8 @@ public class EchConfigMismatchException extends SSLException { * {@code null} if no retry configuration was set by the server. * * Prior to reading this value, the client must verify that the certificate is valid for - * the name returned by {@link #getPublicHostname()}. + * the name returned by {@link #getPublicHostname()}, unless that check was already performed + * during the handshake by HTTPS endpoint identification (see the class documentation). */ public EchConfigList getRetryConfigList() { if (publicName == null) { diff --git a/openjdk/src/main/java/org/conscrypt/Platform.java b/openjdk/src/main/java/org/conscrypt/Platform.java index e0bc75a09..d5f4fb53d 100644 --- a/openjdk/src/main/java/org/conscrypt/Platform.java +++ b/openjdk/src/main/java/org/conscrypt/Platform.java @@ -802,7 +802,6 @@ public static boolean isPqcKemKdfSupported() { return true; } - public static final long ENABLE_TLS_PQC_DEFAULT_GROUPS = 556729260L; private static volatile boolean pqcDefaultEnabled = true; public static boolean isPqcDefaultEnabled() { @@ -813,10 +812,24 @@ public static void setPqcDefaultEnabledForTesting(boolean enabled) { pqcDefaultEnabled = enabled; } + private static volatile boolean pqcDefaultSignatureAlgorithmsEnabled = true; + + public static boolean isPqcDefaultSignatureAlgorithmsEnabled() { + return pqcDefaultSignatureAlgorithmsEnabled; + } + + public static void setPqcDefaultSignatureAlgorithmsEnabledForTesting(boolean enabled) { + pqcDefaultSignatureAlgorithmsEnabled = enabled; + } + public static boolean isSdkGreater(int sdk) { return false; } + public static boolean isMerkleTreeCertsEnabled() { + return false; + } + public static boolean registerX509CertificateAllocation( OpenSSLX509Certificate cert, long nativePtr) { // On OpenJDK, finalize() is used as fallback. diff --git a/openjdk/src/test/java/org/conscrypt/ConscryptAndroidSuite.java b/openjdk/src/test/java/org/conscrypt/ConscryptAndroidSuite.java index 10fd9f9b9..46909bb5f 100644 --- a/openjdk/src/test/java/org/conscrypt/ConscryptAndroidSuite.java +++ b/openjdk/src/test/java/org/conscrypt/ConscryptAndroidSuite.java @@ -73,8 +73,8 @@ import org.conscrypt.metrics.CipherSuiteTest; import org.conscrypt.metrics.OptionalMethodTest; import org.conscrypt.metrics.ProtocolTest; +import org.conscrypt.pqc.MtcUtilsTest; import org.conscrypt.util.DerUtilsTest; -import org.conscrypt.util.MtcUtilsTest; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -125,6 +125,7 @@ OpenSslCompositeMlDsaPublicKeyTest.class, SignatureThreadMisuseTest.class, SSLUtilsTest.class, + ServerSessionResumptionTest.class, SlhDsaTest.class, TestSessionBuilderTest.class, TrustManagerImplTest.class, @@ -133,9 +134,10 @@ // org.conscrypt.ct tests VerifierTest.class, SerializationTest.class, + // org.conscrypt.pqc tests + MtcUtilsTest.class, // org.conscrypt.util tests DerUtilsTest.class, - MtcUtilsTest.class, // java.security tests CertificateFactoryTest.class, X509CertificateTest.class, diff --git a/openjdk/src/test/java/org/conscrypt/ConscryptAndroidWithoutTlsSuite.java b/openjdk/src/test/java/org/conscrypt/ConscryptAndroidWithoutTlsSuite.java index 297fed184..b8b9ac785 100644 --- a/openjdk/src/test/java/org/conscrypt/ConscryptAndroidWithoutTlsSuite.java +++ b/openjdk/src/test/java/org/conscrypt/ConscryptAndroidWithoutTlsSuite.java @@ -64,8 +64,8 @@ import org.conscrypt.metrics.CipherSuiteTest; import org.conscrypt.metrics.OptionalMethodTest; import org.conscrypt.metrics.ProtocolTest; +import org.conscrypt.pqc.MtcUtilsTest; import org.conscrypt.util.DerUtilsTest; -import org.conscrypt.util.MtcUtilsTest; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -124,9 +124,10 @@ // org.conscrypt.ct tests VerifierTest.class, SerializationTest.class, + // org.conscrypt.pqc tests + MtcUtilsTest.class, // org.conscrypt.util tests DerUtilsTest.class, - MtcUtilsTest.class, // java.security tests CertificateFactoryTest.class, X509CertificateTest.class, diff --git a/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java b/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java index 37db6ec32..63d85ad70 100644 --- a/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java +++ b/openjdk/src/test/java/org/conscrypt/ConscryptEngineTest.java @@ -384,6 +384,45 @@ public void alpnWithServerProtocolSelectorShouldFail() throws Exception { assertNull(Conscrypt.getApplicationProtocol(serverEngine)); } + @Test + public void alpnWithServerProtocolSelectorClearedAfterBeginHandshakeShouldNotSelect() + throws Exception { + setupEngines(TestKeyStore.getClient(), TestKeyStore.getServer()); + + // Configure two 1-byte client protocols ("a", "b" -> 4 wire bytes: 01 61 01 62) so + // misinterpreting SSL_TLSEXT_ERR_NOACK (3) as a wire offset would index in[3] out of + // bounds. + Conscrypt.setApplicationProtocols(clientEngine, new String[] {"a", "b"}); + + ApplicationProtocolSelector selector = Mockito.mock(ApplicationProtocolSelector.class); + Conscrypt.setApplicationProtocolSelector(serverEngine, selector); + clientEngine.beginHandshake(); + serverEngine.beginHandshake(); + Conscrypt.setApplicationProtocolSelector(serverEngine, null); + + doHandshake(false); + assertNull(Conscrypt.getApplicationProtocol(clientEngine)); + assertNull(Conscrypt.getApplicationProtocol(serverEngine)); + } + + @Test + public void alpnWithThrowingServerProtocolSelectorShouldAbortHandshake() throws Exception { + setupEngines(TestKeyStore.getClient(), TestKeyStore.getServer()); + + Conscrypt.setApplicationProtocols(clientEngine, new String[] {"http/1.1", "h2"}); + + RuntimeException selectorFailure = new RuntimeException("selector failure"); + ApplicationProtocolSelector selector = Mockito.mock(ApplicationProtocolSelector.class); + when(selector.selectApplicationProtocol(same(serverEngine), + ArgumentMatchers.anyList())) + .thenThrow(selectorFailure); + Conscrypt.setApplicationProtocolSelector(serverEngine, selector); + + Throwable thrown = assertThrows(Throwable.class, () -> doHandshake(true)); + assertTrue(thrown == selectorFailure || thrown.getCause() == selectorFailure); + assertNull(Conscrypt.getApplicationProtocol(serverEngine)); + } + /** * BoringSSL server doesn't support renegotiation. BoringSSL clients do not support * initiating a renegotiation, only processing a renegotiation initiated by the diff --git a/openjdk/src/test/java/org/conscrypt/ConscryptOpenJdkSuite.java b/openjdk/src/test/java/org/conscrypt/ConscryptOpenJdkSuite.java index 45f9fe312..761ab731d 100644 --- a/openjdk/src/test/java/org/conscrypt/ConscryptOpenJdkSuite.java +++ b/openjdk/src/test/java/org/conscrypt/ConscryptOpenJdkSuite.java @@ -80,8 +80,8 @@ import org.conscrypt.metrics.CipherSuiteTest; import org.conscrypt.metrics.OptionalMethodTest; import org.conscrypt.metrics.ProtocolTest; +import org.conscrypt.pqc.MtcUtilsTest; import org.conscrypt.util.DerUtilsTest; -import org.conscrypt.util.MtcUtilsTest; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; @@ -135,6 +135,7 @@ SignatureThreadMisuseTest.class, SSLUtilsTest.class, ServerSessionContextTest.class, + ServerSessionResumptionTest.class, SlhDsaTest.class, TestSessionBuilderTest.class, TrustManagerImplTest.class, @@ -143,9 +144,10 @@ // org.conscrypt.ct tests VerifierTest.class, SerializationTest.class, + // org.conscrypt.pqc tests + MtcUtilsTest.class, // org.conscrypt.util tests DerUtilsTest.class, - MtcUtilsTest.class, // java.security tests CertificateFactoryTest.class, X509CertificateTest.class, diff --git a/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java b/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java index 4d1122432..f2d778f16 100644 --- a/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java +++ b/openjdk/src/test/java/org/conscrypt/NativeCryptoTest.java @@ -734,6 +734,39 @@ public void test_SSL_CTX_set_session_id_context() throws Exception { } } + @Test + public void setSessionIdContextSha256_NullSslArgument() { + assertThrows(NullPointerException.class, + () -> NativeCrypto.setSessionIdContextSha256(NULL, null, new byte[0])); + } + + @Test + public void setSessionIdContextSha256_withNullShouldThrow() throws Exception { + long c = NativeCrypto.SSL_CTX_new(); + long s = NativeCrypto.SSL_new(c, null); + try { + assertThrows(NullPointerException.class, + () -> NativeCrypto.setSessionIdContextSha256(s, null, null)); + } finally { + NativeCrypto.SSL_free(s, null); + NativeCrypto.SSL_CTX_free(c, null); + } + } + + @Test + public void test_setSessionIdContextSha256() throws Exception { + long c = NativeCrypto.SSL_CTX_new(); + long s = NativeCrypto.SSL_new(c, null); + try { + NativeCrypto.setSessionIdContextSha256(s, null, new byte[0]); + NativeCrypto.setSessionIdContextSha256(s, null, new byte[32]); + NativeCrypto.setSessionIdContextSha256(s, null, new byte[128]); + } finally { + NativeCrypto.SSL_free(s, null); + NativeCrypto.SSL_CTX_free(c, null); + } + } + @Test public void test_SSL_new() throws Exception { long c = NativeCrypto.SSL_CTX_new(); @@ -1068,6 +1101,104 @@ public void test_SSL_ech_accepted() throws Exception { NativeCrypto.SSL_CTX_free(c, null); } + // Wire-format trust anchor ID lists containing 32473.1 and/or 32473.2. + private static final byte[] TRUST_ANCHOR_ID_LIST_1 = {0x04, (byte) 0x81, (byte) 0xfd, 0x59, + 0x01}; + private static final byte[] TRUST_ANCHOR_ID_LIST_1_2 = { + 0x04, (byte) 0x81, (byte) 0xfd, 0x59, 0x01, 0x04, (byte) 0x81, (byte) 0xfd, 0x59, 0x02}; + + @Test + public void test_SSL_set1_requested_trust_anchors() throws Exception { + long c = NativeCrypto.SSL_CTX_new(); + long s = NativeCrypto.SSL_new(c, /* holder= */ null); + + NativeCrypto.SSL_set1_requested_trust_anchors(s, /* ssl_holder= */ null, + TRUST_ANCHOR_ID_LIST_1_2); + // An empty list is valid and signals support for the retry flow. + NativeCrypto.SSL_set1_requested_trust_anchors(s, /* ssl_holder= */ null, new byte[0]); + + NativeCrypto.SSL_free(s, /* ssl_holder= */ null); + NativeCrypto.SSL_CTX_free(c, /* holder= */ null); + } + + @Test + public void test_SSL_set1_requested_trust_anchors_invalid() throws Exception { + long c = NativeCrypto.SSL_CTX_new(); + long s = NativeCrypto.SSL_new(c, /* holder= */ null); + + // Truncated ID. + assertThrows(IllegalArgumentException.class, + () + -> NativeCrypto.SSL_set1_requested_trust_anchors( + s, /* ssl_holder= */ null, + new byte[] {0x04, (byte) 0x81, (byte) 0xfd})); + // Not a valid RELATIVE-OID (last byte has the continuation bit set). + assertThrows(IllegalArgumentException.class, + () + -> NativeCrypto.SSL_set1_requested_trust_anchors( + s, /* ssl_holder= */ null, new byte[] {0x01, (byte) 0x81})); + assertThrows(NullPointerException.class, + () + -> NativeCrypto.SSL_set1_requested_trust_anchors( + s, /* ssl_holder= */ null, /* ids= */ null)); + + NativeCrypto.SSL_free(s, /* ssl_holder= */ null); + NativeCrypto.SSL_CTX_free(c, /* holder= */ null); + } + + @Test + public void test_SSL_trust_anchor_results_beforeHandshake() throws Exception { + long c = NativeCrypto.SSL_CTX_new(); + long s = NativeCrypto.SSL_new(c, /* holder= */ null); + + assertNull(NativeCrypto.SSL_get0_peer_available_trust_anchors(s, /* ssl_holder= */ null)); + + NativeCrypto.SSL_free(s, /* ssl_holder= */ null); + NativeCrypto.SSL_CTX_free(c, /* holder= */ null); + } + + @Test + public void test_SSL_do_handshake_trust_anchors() throws Exception { + final ServerSocket listener = newServerSocket(); + + Hooks cHooks = new ClientHooks() { + @Override + public long beforeHandshake(long c) throws SSLException { + long ssl = super.beforeHandshake(c); + assertEquals(1, + NativeCrypto.SSL_set_protocol_versions(ssl, /* ssl_holder= */ null, + TLS1_VERSION, TLS1_3_VERSION)); + NativeCrypto.SSL_set1_requested_trust_anchors(ssl, /* ssl_holder= */ null, + TRUST_ANCHOR_ID_LIST_1); + return ssl; + } + }; + Hooks sHooks = new ServerHooks(SERVER_PRIVATE_KEY, ENCODED_SERVER_CERTIFICATES) { + @Override + public long beforeHandshake(long c) throws SSLException { + long ssl = super.beforeHandshake(c); + assertEquals(1, + NativeCrypto.SSL_set_protocol_versions(ssl, /* ssl_holder= */ null, + TLS1_VERSION, TLS1_3_VERSION)); + return ssl; + } + }; + Future client = + handshake(listener, /* timeout= */ 0, /* client= */ true, cHooks, + /* alpnProtocols= */ null, /* alpnSelector= */ null); + Future server = + handshake(listener, /* timeout= */ 0, /* client= */ false, sHooks, + /* alpnProtocols= */ null, /* alpnSelector= */ null); + TestSSLHandshakeCallbacks clientCallback = client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + + assertTrue(clientCallback.verifyCertificateChainCalled); + assertTrue(clientCallback.handshakeCompletedCalled); + // The server's (legacy) credential has no trust anchor ID, so it doesn't advertise any + // available trust anchors. + assertNull(clientCallback.peerAvailableTrustAnchors); + } + @Test public void test_SSL_CTX_ech_enable_server() throws Exception { long c = NativeCrypto.SSL_CTX_new(); @@ -1239,20 +1370,19 @@ public void SSL_set_protocol_versions() throws Exception { @Test public void checkEnabledProtocols_deprecatedTlsV1Protocols_throwsWithExpectedMessage() { if (!Platform.isTlsV1Supported()) { - IllegalArgumentException e = assertThrows( - IllegalArgumentException.class, - () -> NativeCrypto.checkEnabledProtocols(new String[] {"TLSv1"})); + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, + () -> NativeCrypto.checkEnabledProtocols(new String[] {"TLSv1"})); assertEquals("protocol TLSv1 is not supported" + Platform.getTlsV1DeprecationNote(), e.getMessage()); - e = assertThrows( - IllegalArgumentException.class, - () -> NativeCrypto.checkEnabledProtocols(new String[] {"TLSv1.1"})); + e = assertThrows(IllegalArgumentException.class, + () -> NativeCrypto.checkEnabledProtocols(new String[] {"TLSv1.1"})); assertEquals("protocol TLSv1.1 is not supported" + Platform.getTlsV1DeprecationNote(), e.getMessage()); } - IllegalArgumentException e = assertThrows( - IllegalArgumentException.class, - () -> NativeCrypto.checkEnabledProtocols(new String[] {"SSLv3"})); + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, + () -> NativeCrypto.checkEnabledProtocols(new String[] {"SSLv3"})); assertEquals("protocol SSLv3 is not supported", e.getMessage()); } @@ -1460,6 +1590,8 @@ long getBioRef() { private long[] certificateChainRefs; private String authMethod; private boolean verifyCertificateChainCalled; + // Trust anchor negotiation result, which is only available during verification. + private byte[] peerAvailableTrustAnchors; @Override public void verifyCertificateChain(byte[][] certs, String authMethod) @@ -1474,6 +1606,10 @@ public void verifyCertificateChain(byte[][] certs, String authMethod) } } this.authMethod = authMethod; + if (sslNativePointer != NULL) { + this.peerAvailableTrustAnchors = NativeCrypto.SSL_get0_peer_available_trust_anchors( + sslNativePointer, /* ssl_holder= */ null); + } this.verifyCertificateChainCalled = true; } @@ -1603,8 +1739,17 @@ public void serverCertificateRequested(int[] signatureAlgs) { this.serverSignatureAlgs = signatureAlgs; } + private Integer selectApplicationProtocolResult; + private RuntimeException selectApplicationProtocolException; + @Override public int selectApplicationProtocol(byte[] protocols) { + if (selectApplicationProtocolException != null) { + throw selectApplicationProtocolException; + } + if (selectApplicationProtocolResult != null) { + return selectApplicationProtocolResult; + } if (alpnSelector == null) { fail("Should not be called when no alpnSelector"); } @@ -2918,6 +3063,66 @@ public void afterHandshake(long session, long ssl, long c, Socket sock, server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); } + @Test + public void alpnWithOutOfBoundsSelectorOffsetShouldAbortHandshake() throws Exception { + // 4 wire bytes: 01 61 01 62 + final byte[] clientAlpnProtocols = SSLUtils.encodeProtocols(new String[] {"a", "b"}); + ApplicationProtocolSelectorAdapter dummyAdapter = new ApplicationProtocolSelectorAdapter( + Mockito.mock(SSLEngine.class), Mockito.mock(ApplicationProtocolSelector.class)); + + for (final int badOffset : new int[] {3, clientAlpnProtocols.length, Integer.MAX_VALUE}) { + Hooks cHooks = new Hooks(); + Hooks sHooks = new ServerHooks(SERVER_PRIVATE_KEY, ENCODED_SERVER_CERTIFICATES) { + @Override + public void configureCallbacks(TestSSLHandshakeCallbacks callbacks) { + super.configureCallbacks(callbacks); + callbacks.selectApplicationProtocolResult = badOffset; + } + }; + + ServerSocket listener = newServerSocket(); + Future client = + handshake(listener, 0, true, cHooks, clientAlpnProtocols, null); + Future server = + handshake(listener, 0, false, sHooks, null, dummyAdapter); + ExecutionException serverEx = assertThrows( + ExecutionException.class, () -> server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertTrue(serverEx.getCause() instanceof SSLException); + assertThrows(ExecutionException.class, + () -> client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + listener.close(); + } + } + + @Test + public void alpnWithThrowingSelectorCallbackShouldPropagateException() throws Exception { + final byte[] clientAlpnProtocols = + SSLUtils.encodeProtocols(new String[] {"http/1.1", "h2"}); + final RuntimeException expected = new IllegalStateException("alpn selector threw"); + ApplicationProtocolSelectorAdapter dummyAdapter = new ApplicationProtocolSelectorAdapter( + Mockito.mock(SSLEngine.class), Mockito.mock(ApplicationProtocolSelector.class)); + + Hooks cHooks = new Hooks(); + Hooks sHooks = new ServerHooks(SERVER_PRIVATE_KEY, ENCODED_SERVER_CERTIFICATES) { + @Override + public void configureCallbacks(TestSSLHandshakeCallbacks callbacks) { + super.configureCallbacks(callbacks); + callbacks.selectApplicationProtocolException = expected; + } + }; + + ServerSocket listener = newServerSocket(); + Future client = + handshake(listener, 0, true, cHooks, clientAlpnProtocols, null); + Future server = + handshake(listener, 0, false, sHooks, null, dummyAdapter); + ExecutionException serverEx = assertThrows( + ExecutionException.class, () -> server.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(expected, serverEx.getCause()); + assertThrows(ExecutionException.class, () -> client.get(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + listener.close(); + } + @Test public void test_SSL_get_servername_withNullShouldThrow() throws Exception { assertThrows(NullPointerException.class, () -> NativeCrypto.SSL_get_servername(NULL, null)); @@ -3383,6 +3588,146 @@ public void test_EVP_get_digestbyname() throws Exception { assertTrue(NativeCrypto.EVP_get_digestbyname("sha256") != NULL); } + @Test + public void evpGetDigestByName_shake256() throws Exception { + assertTrue(NativeCrypto.EVP_get_digestbyname("shake256") != NULL); + } + + // SHAKE256 test vectors with 512-bit output, from + // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHAKE256_Msg0.pdf + // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHAKE256_Msg1600.pdf + private static final String SHAKE256_512_OF_EMPTY = + "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f" + + "d75dc4ddd8c0f200cb05019d67b592f6fc821c49479ab48640292eacb3b7c4be"; + private static final String SHAKE256_512_OF_MSG1600 = + "cd8a920ed141aa0407a22d59288652e9d9f1a7ee0c1e7c1ca699424da84a904d" + + "2d700caae7396ece96604440577da4f3aa22aeb8857f961c4cd8e06f0ae6610b"; + + @Test + public void evpDigestFinalXof_shake256() throws Exception { + long shake256 = NativeCrypto.EVP_get_digestbyname("shake256"); + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + + NativeCrypto.EVP_DigestInit_ex(ctx, shake256); + byte[] out = new byte[64]; + NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, out.length); + assertArrayEquals(decodeHex(SHAKE256_512_OF_EMPTY), out); + + // EVP_DigestFinalXOF resets the context, so it can be re-initialized and reused. Write the + // output into the middle of a larger buffer to exercise the offset handling. + byte[] msg1600 = new byte[200]; + Arrays.fill(msg1600, (byte) 0xa3); + NativeCrypto.EVP_DigestInit_ex(ctx, shake256); + NativeCrypto.EVP_DigestUpdate(ctx, msg1600, 0, msg1600.length); + byte[] padded = new byte[80]; + NativeCrypto.EVP_DigestFinalXOF(ctx, padded, 8, 64); + assertArrayEquals(decodeHex(SHAKE256_512_OF_MSG1600), Arrays.copyOfRange(padded, 8, 72)); + assertArrayEquals(new byte[8], Arrays.copyOf(padded, 8)); + assertArrayEquals(new byte[8], Arrays.copyOfRange(padded, 72, 80)); + + // The requested length is honoured: a shorter output is a prefix of the longer one. + NativeCrypto.EVP_DigestInit_ex(ctx, shake256); + byte[] shortOut = new byte[32]; + NativeCrypto.EVP_DigestFinalXOF(ctx, shortOut, 0, shortOut.length); + assertArrayEquals(Arrays.copyOf(decodeHex(SHAKE256_512_OF_EMPTY), 32), shortOut); + } + + @Test + public void evpDigestFinalXof_withNonXofDigestShouldThrow() throws Exception { + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("sha256")); + byte[] out = new byte[64]; + assertThrows(RuntimeException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, out.length)); + } + + @Test + public void evpDigestFinalXof_withNullOutputShouldThrow() throws Exception { + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("shake256")); + assertThrows(NullPointerException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, null, 0, 64)); + } + + @Test + public void evpDigestFinalXof_withUninitializedContextShouldThrow() throws Exception { + // A freshly created context has no digest configured. + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + byte[] out = new byte[64]; + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, out.length)); + + // EVP_DigestFinalXOF clears the context, so a second call without re-initializing fails + // the same way instead of crashing. + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("shake256")); + NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, out.length); + assertArrayEquals(decodeHex(SHAKE256_512_OF_EMPTY), out); + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, out.length)); + + // Likewise after an explicit EVP_MD_CTX_cleanup. + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("shake256")); + NativeCrypto.EVP_MD_CTX_cleanup(ctx); + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, out.length)); + } + + @Test + public void evpDigestFinalXof_withInvalidBoundsShouldThrow() throws Exception { + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("shake256")); + byte[] out = new byte[64]; + assertThrows(ArrayIndexOutOfBoundsException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 1, 64)); + assertThrows(ArrayIndexOutOfBoundsException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, -1, 64)); + assertThrows(ArrayIndexOutOfBoundsException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, 65)); + assertThrows(ArrayIndexOutOfBoundsException.class, + () -> NativeCrypto.EVP_DigestFinalXOF(ctx, out, 0, -1)); + } + + @Test + public void evpDigestUpdate_withUninitializedContextShouldThrow() throws Exception { + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + byte[] in = new byte[16]; + ByteBuffer direct = ByteBuffer.allocateDirect(in.length); + long directPtr = NativeCrypto.getDirectBufferAddress(direct); + + // A freshly created context has no digest configured. + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestUpdate(ctx, in, 0, in.length)); + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestUpdateDirect(ctx, directPtr, in.length)); + + // Likewise after an explicit EVP_MD_CTX_cleanup. + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("sha256")); + NativeCrypto.EVP_DigestUpdate(ctx, in, 0, in.length); + NativeCrypto.EVP_DigestUpdateDirect(ctx, directPtr, in.length); + NativeCrypto.EVP_MD_CTX_cleanup(ctx); + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestUpdate(ctx, in, 0, in.length)); + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestUpdateDirect(ctx, directPtr, in.length)); + } + + @Test + public void evpDigestFinalEx_withUninitializedContextShouldThrow() throws Exception { + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + byte[] out = new byte[32]; + + // A freshly created context has no digest configured. + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestFinal_ex(ctx, out, 0)); + + // Likewise after an explicit EVP_MD_CTX_cleanup. + NativeCrypto.EVP_DigestInit_ex(ctx, NativeCrypto.EVP_get_digestbyname("sha256")); + assertEquals(32, NativeCrypto.EVP_DigestFinal_ex(ctx, out, 0)); + NativeCrypto.EVP_MD_CTX_cleanup(ctx); + assertThrows(IllegalStateException.class, + () -> NativeCrypto.EVP_DigestFinal_ex(ctx, out, 0)); + } + @Test public void test_EVP_DigestSignInit() throws Exception { RSAPrivateCrtKey privKey = TEST_RSA_KEY; @@ -3797,6 +4142,157 @@ public void mldsa87_evpDigestSign_works() throws Exception { NativeConstants.EVP_PKEY_ML_DSA_65, rawPublicKey))); } + /** + * Computes the ML-DSA message representative mu of {@code message} under the context string + * {@code context} for the raw public key {@code rawPublicKey} (FIPS 204, Algorithms 2 and 7): + * {@code mu = SHAKE256(tr || 0x00 || |context| || context || message, 64)} with + * {@code tr = SHAKE256(rawPublicKey, 64)}. + */ + private static byte[] mldsaMessageRepresentative(byte[] rawPublicKey, byte[] context, + byte[] message) { + long shake256 = NativeCrypto.EVP_get_digestbyname("shake256"); + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + + NativeCrypto.EVP_DigestInit_ex(ctx, shake256); + NativeCrypto.EVP_DigestUpdate(ctx, rawPublicKey, 0, rawPublicKey.length); + byte[] tr = new byte[64]; + NativeCrypto.EVP_DigestFinalXOF(ctx, tr, 0, tr.length); + + NativeCrypto.EVP_DigestInit_ex(ctx, shake256); + NativeCrypto.EVP_DigestUpdate(ctx, tr, 0, tr.length); + NativeCrypto.EVP_DigestUpdate(ctx, new byte[] {0, (byte) context.length}, 0, 2); + NativeCrypto.EVP_DigestUpdate(ctx, context, 0, context.length); + NativeCrypto.EVP_DigestUpdate(ctx, message, 0, message.length); + byte[] mu = new byte[64]; + NativeCrypto.EVP_DigestFinalXOF(ctx, mu, 0, mu.length); + return mu; + } + + @Test + public void mldsaSignMessageRepresentative_works() throws Exception { + int[] keyTypes = + new int[] {NativeConstants.EVP_PKEY_ML_DSA_44, NativeConstants.EVP_PKEY_ML_DSA_65, + NativeConstants.EVP_PKEY_ML_DSA_87}; + int[] signatureLengths = new int[] {2420, 3309, 4627}; + for (int i = 0; i < keyTypes.length; i++) { + int keyType = keyTypes[i]; + byte[] seed = new byte[32]; + NativeCrypto.RAND_bytes(seed); + NativeRef.EVP_PKEY privateKey = + new NativeRef.EVP_PKEY(NativeCrypto.EVP_PKEY_from_private_seed(keyType, seed)); + byte[] rawPublicKey; + if (keyType == NativeConstants.EVP_PKEY_ML_DSA_44) { + rawPublicKey = NativeCrypto.MLDSA44_public_key_from_seed(seed); + } else if (keyType == NativeConstants.EVP_PKEY_ML_DSA_65) { + rawPublicKey = NativeCrypto.MLDSA65_public_key_from_seed(seed); + } else { + rawPublicKey = NativeCrypto.MLDSA87_public_key_from_seed(seed); + } + NativeRef.EVP_PKEY publicKey = new NativeRef.EVP_PKEY( + NativeCrypto.EVP_PKEY_from_raw_public_key(keyType, rawPublicKey)); + + byte[] message = new byte[100]; + NativeCrypto.RAND_bytes(message); + byte[] mu = mldsaMessageRepresentative(rawPublicKey, new byte[0], message); + + byte[] sig = NativeCrypto.MLDSA_sign_message_representative(privateKey, mu); + assertEquals(signatureLengths[i], sig.length); + + // The signature verifies as a regular ML-DSA signature of the message under the empty + // context string. + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + NativeCrypto.EVP_DigestVerifyInit(ctx, 0, publicKey); + assertTrue(NativeCrypto.EVP_DigestVerify(ctx, sig, 0, sig.length, message, 0, + message.length)); + + // But not of a different message. + byte[] otherMessage = message.clone(); + otherMessage[0] ^= 1; + NativeCrypto.EVP_DigestVerifyInit(ctx, 0, publicKey); + assertFalse(NativeCrypto.EVP_DigestVerify(ctx, sig, 0, sig.length, otherMessage, 0, + otherMessage.length)); + + // Signing the same mu again yields a different (randomized) but valid signature. + byte[] sig2 = NativeCrypto.MLDSA_sign_message_representative(privateKey, mu); + assertFalse(Arrays.equals(sig, sig2)); + NativeCrypto.EVP_DigestVerifyInit(ctx, 0, publicKey); + assertTrue(NativeCrypto.EVP_DigestVerify(ctx, sig2, 0, sig2.length, message, 0, + message.length)); + } + } + + @Test + public void mldsaSignMessageRepresentative_withContextString_works() throws Exception { + // Key and inputs from wycheproof/testvectors_v1/mldsa_44_sign_seed_test.json, see + // EVP_PKEY_CTX_set1_signature_context_string_works. + byte[] seed = TestUtils.decodeHex( + "2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a2a"); + byte[] contextStr = TestUtils.decodeHex("436f6e74657874"); + byte[] data = TestUtils.decodeHex("48656c6c6f20776f726c64"); + NativeRef.EVP_PKEY privateKey = new NativeRef.EVP_PKEY( + NativeCrypto.EVP_PKEY_from_private_seed(NativeConstants.EVP_PKEY_ML_DSA_44, seed)); + byte[] rawPublicKey = NativeCrypto.MLDSA44_public_key_from_seed(seed); + + // The context string is bound into mu, so the signature verifies under that context... + byte[] mu = mldsaMessageRepresentative(rawPublicKey, contextStr, data); + byte[] sig = NativeCrypto.MLDSA_sign_message_representative(privateKey, mu); + + NativeRef.EVP_MD_CTX ctx = new NativeRef.EVP_MD_CTX(NativeCrypto.EVP_MD_CTX_create()); + long pkeyCtx = NativeCrypto.EVP_DigestVerifyInit(ctx, 0, privateKey); + NativeCrypto.EVP_PKEY_CTX_set1_signature_context_string(pkeyCtx, contextStr); + assertTrue(NativeCrypto.EVP_DigestVerify(ctx, sig, 0, sig.length, data, 0, data.length)); + + // ... but not under the empty one. + NativeCrypto.EVP_DigestVerifyInit(ctx, 0, privateKey); + assertFalse(NativeCrypto.EVP_DigestVerify(ctx, sig, 0, sig.length, data, 0, data.length)); + } + + @Test + public void mldsaSignMessageRepresentative_withInvalidMuLengthShouldThrow() throws Exception { + NativeRef.EVP_PKEY privateKey = + new NativeRef.EVP_PKEY(NativeCrypto.EVP_PKEY_from_private_seed( + NativeConstants.EVP_PKEY_ML_DSA_65, new byte[32])); + assertThrows( + IllegalArgumentException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(privateKey, new byte[63])); + assertThrows( + IllegalArgumentException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(privateKey, new byte[65])); + assertThrows(IllegalArgumentException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(privateKey, new byte[0])); + } + + @Test + public void mldsaSignMessageRepresentative_withNullArgumentsShouldThrow() throws Exception { + NativeRef.EVP_PKEY privateKey = + new NativeRef.EVP_PKEY(NativeCrypto.EVP_PKEY_from_private_seed( + NativeConstants.EVP_PKEY_ML_DSA_65, new byte[32])); + assertThrows(NullPointerException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(null, new byte[64])); + assertThrows(NullPointerException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(privateKey, null)); + } + + @Test + public void mldsaSignMessageRepresentative_withPublicKeyShouldThrow() throws Exception { + byte[] seed = new byte[32]; + byte[] rawPublicKey = NativeCrypto.MLDSA65_public_key_from_seed(seed); + NativeRef.EVP_PKEY publicKey = + new NativeRef.EVP_PKEY(NativeCrypto.EVP_PKEY_from_raw_public_key( + NativeConstants.EVP_PKEY_ML_DSA_65, rawPublicKey)); + assertThrows(InvalidKeyException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(publicKey, new byte[64])); + } + + @Test + public void mldsaSignMessageRepresentative_withNonMldsaKeyShouldThrow() throws Exception { + NativeRef.EC_GROUP group = + new NativeRef.EC_GROUP(NativeCrypto.EC_GROUP_new_by_curve_name("prime256v1")); + NativeRef.EVP_PKEY ecKey = new NativeRef.EVP_PKEY(NativeCrypto.EC_KEY_generate_key(group)); + assertThrows(InvalidKeyException.class, + () -> NativeCrypto.MLDSA_sign_message_representative(ecKey, new byte[64])); + } + @Test public void get_RSA_private_params_NullArgument() throws Exception { assertThrows(NullPointerException.class, () -> NativeCrypto.get_RSA_private_params(null)); diff --git a/openjdk/src/test/java/org/conscrypt/NativeSslTest.java b/openjdk/src/test/java/org/conscrypt/NativeSslTest.java index 3cccda345..3706ed352 100644 --- a/openjdk/src/test/java/org/conscrypt/NativeSslTest.java +++ b/openjdk/src/test/java/org/conscrypt/NativeSslTest.java @@ -27,6 +27,7 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; +import java.lang.reflect.Method; @RunWith(JUnit4.class) public final class NativeSslTest { @@ -78,6 +79,177 @@ public void toBoringSslGroups_throwsIfNoKnownGroupsFound() { () -> NativeSsl.toBoringSslGroups(new String[] {"Unknown", "Unknown2"})); } + @Test + public void getDefaultNamedGroups_returnsExplicitlyPinnedGroups() throws Exception { + int[] pqcGroups = new int[] {NativeConstants.NID_X25519MLKEM768, NativeConstants.NID_X25519, + NativeConstants.NID_X9_62_prime256v1, + NativeConstants.NID_secp384r1}; + int[] classicalGroups = new int[] { + NativeConstants.NID_X25519, NativeConstants.NID_X9_62_prime256v1, + NativeConstants.NID_secp384r1}; + assertArrayEquals(pqcGroups, + NativeSsl.toBoringSslGroups(NativeSsl.DEFAULT_PQC_NAMED_GROUPS)); + assertArrayEquals(classicalGroups, + NativeSsl.toBoringSslGroups(NativeSsl.DEFAULT_CLASSICAL_NAMED_GROUPS)); + + int[] defaultGroups = NativeSsl.getDefaultNamedGroups(); + assertNotNull(defaultGroups); + assertArrayEquals(Platform.isPqcDefaultEnabled() ? pqcGroups : classicalGroups, + defaultGroups); + + try { + Method setPqcForTesting = Platform.class.getDeclaredMethod( + "setPqcDefaultEnabledForTesting", boolean.class); + boolean saved = Platform.isPqcDefaultEnabled(); + try { + setPqcForTesting.invoke(null, true); + assertArrayEquals(pqcGroups, NativeSsl.getDefaultNamedGroups()); + setPqcForTesting.invoke(null, false); + assertArrayEquals(classicalGroups, NativeSsl.getDefaultNamedGroups()); + } finally { + setPqcForTesting.invoke(null, saved); + } + } catch (NoSuchMethodException ignored) { + // android/Platform does not define setPqcDefaultEnabledForTesting. + } + } + + @Test + public void toBoringSslSignatureAlgorithms_convertsKnownValues() { + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_44}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"mldsa44"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_44}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"ML-DSA-44"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_65}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"mldsa65"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_65}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"ML-DSA-65"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_87}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"mldsa87"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_87}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"ML-DSA-87"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ECDSA_SECP256R1_SHA256}, + NativeSsl.toBoringSslSignatureAlgorithms( + new String[] {"ecdsa_secp256r1_sha256"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA256}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pss_rsae_sha256"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PKCS1_SHA256}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pkcs1_sha256"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ECDSA_SECP384R1_SHA384}, + NativeSsl.toBoringSslSignatureAlgorithms( + new String[] {"ecdsa_secp384r1_sha384"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA384}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pss_rsae_sha384"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PKCS1_SHA384}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pkcs1_sha384"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ECDSA_SECP521R1_SHA512}, + NativeSsl.toBoringSslSignatureAlgorithms( + new String[] {"ecdsa_secp521r1_sha512"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA512}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pss_rsae_sha512"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PKCS1_SHA512}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pkcs1_sha512"})); + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_RSA_PKCS1_SHA1}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"rsa_pkcs1_sha1"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ECDSA_SHA1}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"ecdsa_sha1"})); + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ED25519}, + NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"ed25519"})); + } + + @Test + public void toBoringSslSignatureAlgorithms_convertsLists() { + assertArrayEquals(new int[] {NativeConstants.SSL_SIGN_ML_DSA_65, + NativeConstants.SSL_SIGN_ECDSA_SECP256R1_SHA256}, + NativeSsl.toBoringSslSignatureAlgorithms( + new String[] {"mldsa65", "ecdsa_secp256r1_sha256"})); + } + + @Test + public void toBoringSslSignatureAlgorithms_ignoresUnknownValues() { + assertArrayEquals( + new int[] {NativeConstants.SSL_SIGN_ECDSA_SECP256R1_SHA256}, + NativeSsl.toBoringSslSignatureAlgorithms( + new String[] {"Unknown", "ecdsa_secp256r1_sha256", "Unknown2"})); + } + + @Test + public void toBoringSslSignatureAlgorithms_throwsIfNoKnownAlgorithmsFound() { + assertThrows(IllegalArgumentException.class, + () -> NativeSsl.toBoringSslSignatureAlgorithms(new String[] {})); + assertThrows(IllegalArgumentException.class, + () -> NativeSsl.toBoringSslSignatureAlgorithms(new String[] {"Unknown"})); + assertThrows(IllegalArgumentException.class, + () -> NativeSsl.toBoringSslSignatureAlgorithms( + new String[] {"Unknown", "Unknown2"})); + } + + @Test + public void getDefaultSignatureAlgorithms_returnsExplicitlyPinnedAlgorithms() throws Exception { + int[] pqcAlgs = new int[] { + NativeConstants.SSL_SIGN_ML_DSA_44, + NativeConstants.SSL_SIGN_ML_DSA_65, + NativeConstants.SSL_SIGN_ML_DSA_87, + NativeConstants.SSL_SIGN_ECDSA_SECP256R1_SHA256, + NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA256, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA256, + NativeConstants.SSL_SIGN_ECDSA_SECP384R1_SHA384, + NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA384, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA384, + NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA512, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA512, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA1, + }; + int[] classicalAlgs = new int[] { + NativeConstants.SSL_SIGN_ECDSA_SECP256R1_SHA256, + NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA256, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA256, + NativeConstants.SSL_SIGN_ECDSA_SECP384R1_SHA384, + NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA384, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA384, + NativeConstants.SSL_SIGN_RSA_PSS_RSAE_SHA512, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA512, + NativeConstants.SSL_SIGN_RSA_PKCS1_SHA1, + }; + assertArrayEquals( + pqcAlgs, + NativeSsl.toBoringSslSignatureAlgorithms( + NativeSsl.DEFAULT_PQC_SIGNATURE_ALGORITHMS)); + assertArrayEquals( + classicalAlgs, + NativeSsl.toBoringSslSignatureAlgorithms( + NativeSsl.DEFAULT_CLASSICAL_SIGNATURE_ALGORITHMS)); + + int[] defaultAlgs = NativeSsl.getDefaultSignatureAlgorithms(); + assertNotNull(defaultAlgs); + assertArrayEquals( + Platform.isPqcDefaultSignatureAlgorithmsEnabled() ? pqcAlgs : classicalAlgs, + defaultAlgs); + + try { + Method setPqcForTesting = Platform.class.getDeclaredMethod( + "setPqcDefaultSignatureAlgorithmsEnabledForTesting", boolean.class); + boolean saved = Platform.isPqcDefaultSignatureAlgorithmsEnabled(); + try { + setPqcForTesting.invoke(null, true); + assertArrayEquals(pqcAlgs, NativeSsl.getDefaultSignatureAlgorithms()); + setPqcForTesting.invoke(null, false); + assertArrayEquals(classicalAlgs, NativeSsl.getDefaultSignatureAlgorithms()); + } finally { + setPqcForTesting.invoke(null, saved); + } + } catch (NoSuchMethodException ignored) { + // platform/Platform does not define setPqcDefaultSignatureAlgorithmsEnabledForTesting. + } + } + @Test public void parseNamedGroupsProperty_parsesProperty() { assertArrayEquals(new int[] {NativeConstants.NID_X25519}, diff --git a/platform/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java b/platform/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java index 625d21e6c..99c6e8956 100644 --- a/platform/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java +++ b/platform/src/main/java/org/conscrypt/ConscryptNetworkSecurityPolicy.java @@ -83,7 +83,7 @@ public DomainEncryptionMode getDomainEncryptionMode(String hostname) { if (Platform.isSdkGreater(36)) { return platformToConscryptEncryptionMode(policy.getDomainEncryptionMode(hostname)); } - return DomainEncryptionMode.UNKNOWN; + return DomainEncryptionMode.DISABLED; } private static DomainEncryptionMode platformToConscryptEncryptionMode(int platformMode) { diff --git a/platform/src/main/java/org/conscrypt/Platform.java b/platform/src/main/java/org/conscrypt/Platform.java index 81b08c11b..d977a7241 100644 --- a/platform/src/main/java/org/conscrypt/Platform.java +++ b/platform/src/main/java/org/conscrypt/Platform.java @@ -683,6 +683,38 @@ public static boolean isPqcDefaultEnabled() { } } + /** + * Controls whether Post-Quantum Cryptography (ML-DSA) is enabled in the default TLS signature + * algorithms for this application. + */ + @ChangeId + public static final long ENABLE_TLS_PQC_DEFAULT_SIGNATURE_ALGORITHMS = 576621461L; + + /** + * Returns true if PQC signature algorithms (ML-DSA) should be enabled by default. + * + *

    Note: Do not cache the result of {@link Compatibility#isChangeEnabled(long)} in a static + * field. Conscrypt classes are preloaded in Zygote ({@link #RUNNING_IN_ZYGOTE}), where + * {@code Compatibility.isChangeEnabled} always returns true. This check must be evaluated + * dynamically per connection post-fork inside the application process. + * + *

    Unlike {@code @EnabledAfter}/{@code @EnabledSince} targetSdk-gated changes, + * {@link #ENABLE_TLS_PQC_DEFAULT_SIGNATURE_ALGORITHMS} is enabled by default across all + * targetSdkVersions, so {@code PlatformCompat} evaluates it to {@code true} for both app and + * non-app processes on older Android releases as well, while still allowing per-app overrides + * on debuggable builds and via Developer Options. + */ + public static boolean isPqcDefaultSignatureAlgorithmsEnabled() { + if (!Flags.tlsPqcDefaultSignatureAlgorithms()) { + return false; + } + try { + return Compatibility.isChangeEnabled(ENABLE_TLS_PQC_DEFAULT_SIGNATURE_ALGORITHMS); + } catch (Throwable ignored) { + return true; + } + } + private static boolean inZygote() { if (canCallZygoteMethod) { return ZygoteHooks.isInZygote(); @@ -739,6 +771,10 @@ public static boolean isSdkGreater(int sdk) { } } + public static boolean isMerkleTreeCertsEnabled() { + return com.android.org.conscrypt.net.flags.Flags.merkleTreeCertificates(); + } + private static class X509NativeAllocationRegistryHolder { private static final NativeAllocationRegistry REGISTRY; diff --git a/scripts/export_to_ag.py b/scripts/export_to_ag.py index c76580541..aabcc2223 100755 --- a/scripts/export_to_ag.py +++ b/scripts/export_to_ag.py @@ -1191,6 +1191,59 @@ def _fetch_android_clang_format() -> Tuple[Optional[str], Optional[str]]: return str(gcf_path), str(cf_path) +def _get_change_id_seeds( + android_dir: pathlib.Path, cl: Optional[str] = None +) -> List[str]: + """Returns an ordered list of deterministic seeds for Gerrit Change-Id.""" + base_res = subprocess.run( + ["git", "rev-parse", "HEAD~1"], + cwd=android_dir, + capture_output=True, + text=True, + check=False, + ) + seeds: List[str] = [] + if base_res.returncode == 0 and base_res.stdout.strip(): + base_sha = base_res.stdout.strip() + seeds.append(f"conscrypt-ag-export-base-{base_sha}") + for idx in range(1, 6): + seeds.append(f"conscrypt-ag-export-base-{base_sha}-r{idx}") + if cl: + seeds.append(f"conscrypt-ag-export-cl-{cl}") + head_sha = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=android_dir, text=True + ).strip() + seeds.append(f"conscrypt-ag-export-head-{head_sha}") + return seeds + + +def _set_commit_change_id( + android_dir: pathlib.Path, seed: str, reset_author: bool = False +) -> str: + """Sets or replaces the Change-Id footer on HEAD and amends the commit.""" + change_id = "I" + hashlib.sha1(seed.encode("utf-8")).hexdigest() + msg = subprocess.check_output( + ["git", "log", "-1", "--format=%B"], cwd=android_dir, text=True + ).strip() + if re.search(r"^Change-Id:\s*I[0-9a-fA-F]+", msg, flags=re.MULTILINE): + msg = re.sub( + r"^Change-Id:\s*I[0-9a-fA-F]+", + f"Change-Id: {change_id}", + msg, + flags=re.MULTILINE, + ) + else: + sep = "\n" if "PiperOrigin-RevId:" in msg.splitlines()[-1] else "\n\n" + msg = f"{msg}{sep}Change-Id: {change_id}\n" + + cmd = ["git", "commit", "--amend"] + if reset_author: + cmd.append("--reset-author") + cmd.extend(["--allow-empty", "-m", msg]) + run_cmd(cmd, cwd=android_dir, check=False) + return change_id + + def step_format_and_commit_android( android_dir: pathlib.Path, build_top: Optional[pathlib.Path], @@ -1300,47 +1353,13 @@ def step_format_and_commit_android( check=False, ) - msg = subprocess.check_output( - ["git", "log", "-1", "--format=%B"], cwd=android_dir, text=True - ).strip() - - # Ensure Gerrit Change-Id footer is present - if "Change-Id:" not in msg: - base_res = subprocess.run( - ["git", "rev-parse", "HEAD~1"], - cwd=android_dir, - capture_output=True, - text=True, - check=False, - ) - if base_res.returncode == 0 and base_res.stdout.strip(): - seed = f"conscrypt-export-base-{base_res.stdout.strip()}" - elif cl: - seed = f"conscrypt-export-{cl}" - else: - seed = subprocess.check_output( - ["git", "rev-parse", "HEAD"], cwd=android_dir, text=True - ).strip() - change_id = "I" + hashlib.sha1(seed.encode("utf-8")).hexdigest() - sep = "\n" if "PiperOrigin-RevId:" in msg.splitlines()[-1] else "\n\n" - msg = f"{msg}{sep}Change-Id: {change_id}\n" - - run_cmd( - [ - "git", - "commit", - "--amend", - "--reset-author", - "--allow-empty", - "-m", - msg, - ], - cwd=android_dir, - check=False, - ) + seeds = _get_change_id_seeds(android_dir, cl) + _set_commit_change_id(android_dir, seeds[0], reset_author=True) -def step_upload_gerrit(android_dir: pathlib.Path, upload: bool) -> None: +def step_upload_gerrit( + android_dir: pathlib.Path, upload: bool, cl: Optional[str] = None +) -> None: """Uploads to Gerrit directly.""" if upload: print("\n--- Step 6: Uploading complete change to Gerrit ---") @@ -1349,19 +1368,26 @@ def step_upload_gerrit(android_dir: pathlib.Path, upload: bool) -> None: else: push_urls = list(GERRIT_PUSH_URLS) + seeds = _get_change_id_seeds(android_dir, cl) + seed_idx = 0 + uploaded = False last_err = "" - label_opt_sets = [ + push_opt_sets = [ + ["-o", "r=miguelaranda@google.com", "-o", "l=Presubmit-Ready+1"], + ["-o", "r=miguelaranda@google.com"], ["-o", "l=Presubmit-Ready+1"], [], ] for url in push_urls: for target_branch in ("main", "master"): - for label_opts in label_opt_sets: - label_desc = " with Presubmit-Ready+1" if label_opts else "" + opt_idx = 0 + while opt_idx < len(push_opt_sets): + push_opts = push_opt_sets[opt_idx] + opts_desc = f" ({' '.join(push_opts)})" if push_opts else "" print( f"==> Attempting push to {url}" - f" (HEAD:refs/for/{target_branch}){label_desc}..." + f" (HEAD:refs/for/{target_branch}){opts_desc}..." ) res = subprocess.run( [ @@ -1369,7 +1395,7 @@ def step_upload_gerrit(android_dir: pathlib.Path, upload: bool) -> None: "push", "-o", "nokeycheck", - *label_opts, + *push_opts, url, f"HEAD:refs/for/{target_branch}", ], @@ -1386,11 +1412,38 @@ def step_upload_gerrit(android_dir: pathlib.Path, upload: bool) -> None: uploaded = True break last_err = res.stderr.strip() - if label_opts and "Presubmit-Ready" in last_err: + err_lower = last_err.lower() + if "no new changes" in err_lower: + print( + "Notice: Gerrit reported 'no new changes' — the open export CL" + " is already up to date with HEAD." + ) + uploaded = True + break + if ( + "closed" in err_lower or "abandoned" in err_lower + ) and seed_idx + 1 < len(seeds): + seed_idx += 1 + new_cid = _set_commit_change_id( + android_dir, seeds[seed_idx], reset_author=False + ) + print( + "Notice: Existing Gerrit change for previous Change-Id was" + f" closed/abandoned; rotated Change-Id to {new_cid} and" + " retrying..." + ) + continue + if push_opts and ( + "presubmit-ready" in err_lower + or "reviewer" in err_lower + or "restricted" in err_lower + or "not permitted" in err_lower + ): print( - "Notice: Presubmit-Ready+1 label not permitted yet for this" - " account; retrying upload without label..." + "Notice: Push options not permitted; retrying with fallback" + " options..." ) + opt_idx += 1 continue break if uploaded: @@ -1416,8 +1469,9 @@ def step_upload_gerrit(android_dir: pathlib.Path, upload: bool) -> None: ) print("To upload to Gerrit, run:") print( - f" cd {android_dir} && git push -o nokeycheck {GERRIT_SSO_URL}" - " HEAD:refs/for/main" + f" cd {android_dir} && git push -o nokeycheck" + " -o r=miguelaranda@google.com -o l=Presubmit-Ready+1" + f" {GERRIT_SSO_URL} HEAD:refs/for/main" ) @@ -1622,7 +1676,7 @@ def main() -> None: ) # Step 6: Upload to Gerrit - step_upload_gerrit(android_dir, upload=args.upload) + step_upload_gerrit(android_dir, upload=args.upload, cl=target_cl) finally: if temp_dir_holder: diff --git a/testing/src/main/java/org/conscrypt/TestUtils.java b/testing/src/main/java/org/conscrypt/TestUtils.java index c6a7897b9..018ea50f1 100644 --- a/testing/src/main/java/org/conscrypt/TestUtils.java +++ b/testing/src/main/java/org/conscrypt/TestUtils.java @@ -907,6 +907,10 @@ public static boolean isJavaxCertificateSupported() { return callPlatformMethod("isJavaxCertificateSupported", true); } + public static boolean isPqcDefaultEnabled() { + return callPlatformMethod("isPqcDefaultEnabled", false); + } + // Calls a boolean platform method by reflection. If the method is not present, e.g. // due to version skew etc then return the default value. public static boolean callPlatformMethod(String methodName, boolean defaultValue) { diff --git a/testing/src/main/java/org/conscrypt/java/security/StandardNames.java b/testing/src/main/java/org/conscrypt/java/security/StandardNames.java index af253646e..82033288f 100644 --- a/testing/src/main/java/org/conscrypt/java/security/StandardNames.java +++ b/testing/src/main/java/org/conscrypt/java/security/StandardNames.java @@ -344,13 +344,32 @@ private static void addOpenSsl(String cipherSuite) { "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", "TLS_PSK_WITH_AES_128_CBC_SHA", "TLS_PSK_WITH_AES_256_CBC_SHA"); - // Should be updated to match BoringSSL's defaults when they change. - // https://boringssl.googlesource.com/boringssl/+/main/ssl/extensions.cc#215 + // ANDROID COMPATIBILITY GATE: These default named group lists guard Android app compatibility + // on the wire (ClientHello supported_groups extension). Do NOT modify or relax these lists to + // accommodate upstream BoringSSL or Conscrypt changes without an Android compatibility review + // and an associated AppCompat / aconfig flag. + // Must mirror NativeSsl.DEFAULT_CLASSICAL_NAMED_GROUPS and + // NativeSsl.DEFAULT_PQC_NAMED_GROUPS. private static final List ELLIPTIC_CURVES_DEFAULT = Arrays.asList("x25519 (29)", "secp256r1 (23)", "secp384r1 (24)"); private static final List ELLIPTIC_CURVES_DEFAULT_PQC = Arrays.asList( "x25519mlkem768 (4588)", "x25519 (29)", "secp256r1 (23)", "secp384r1 (24)"); + // ANDROID COMPATIBILITY GATE: These default signature algorithm lists guard Android app + // compatibility on the wire (ClientHello signature_algorithms extension). Do NOT modify or + // relax these lists to accommodate upstream BoringSSL or Conscrypt changes without an Android + // compatibility review and an associated AppCompat / aconfig flag. + // Must mirror NativeSsl.DEFAULT_CLASSICAL_SIGNATURE_ALGORITHMS and + // NativeSsl.DEFAULT_PQC_SIGNATURE_ALGORITHMS. + private static final List SIGNATURE_ALGORITHMS_DEFAULT = Arrays.asList( + "ecdsa_secp256r1_sha256", "rsa_pss_rsae_sha256", "rsa_pkcs1_sha256", + "ecdsa_secp384r1_sha384", "rsa_pss_rsae_sha384", "rsa_pkcs1_sha384", + "rsa_pss_rsae_sha512", "rsa_pkcs1_sha512", "rsa_pkcs1_sha1"); + private static final List SIGNATURE_ALGORITHMS_DEFAULT_PQC = Arrays.asList( + "mldsa44", "mldsa65", "mldsa87", "ecdsa_secp256r1_sha256", "rsa_pss_rsae_sha256", + "rsa_pkcs1_sha256", "ecdsa_secp384r1_sha384", "rsa_pss_rsae_sha384", + "rsa_pkcs1_sha384", "rsa_pss_rsae_sha512", "rsa_pkcs1_sha512", "rsa_pkcs1_sha1"); + /** * Asserts that the cipher suites array is non-null and that it * all of its contents are cipher suites known to this @@ -460,6 +479,11 @@ public static void assertSupportedCipherSuites(String[] cipherSuites) { /** * Assert cipher suites match the default list in content and priority order and contain * only cipher suites permitted by default. + * + *

    ANDROID COMPATIBILITY GATE: This assertion guards the default cipher suites exposed to + * Android apps and sent in TLS ClientHello messages. Do NOT relax or update the expected + * default cipher suites to accommodate upstream changes without an Android compatibility + * review and an associated AppCompat / aconfig flag. */ public static void assertDefaultCipherSuites(String[] cipherSuites) { assertValidCipherSuites(cipherSuites); @@ -469,13 +493,67 @@ public static void assertDefaultCipherSuites(String[] cipherSuites) { assertEquals(expected, actual); } + /** + * Assert that the provided list of elliptic curves matches the default list. + * + *

    ANDROID COMPATIBILITY GATE: This assertion guards the default TLS namedGroups + * (supported_groups extension in ClientHello). Adding or reordering default groups can + * significantly increase ClientHello size (e.g. post-quantum key shares) or alter server + * negotiation and break middleboxes. Do NOT modify expected defaults without an Android + * compatibility review and an associated AppCompat / aconfig flag. + */ public static void assertDefaultEllipticCurves(String[] curves) { - List actualList = Arrays.asList(curves); - assertTrue("Unexpected default curves list: " + actualList, - actualList.equals(ELLIPTIC_CURVES_DEFAULT) - || actualList.equals(ELLIPTIC_CURVES_DEFAULT_PQC)); + List expected = TestUtils.isPqcDefaultEnabled() ? ELLIPTIC_CURVES_DEFAULT_PQC + : ELLIPTIC_CURVES_DEFAULT; + assertEquals("Unexpected default curves list", expected, Arrays.asList(curves)); + } + + /** + * Assert that the provided list of signature algorithms matches the default list. + * + *

    ANDROID COMPATIBILITY GATE: This assertion guards the default TLS signature algorithms + * (signature_algorithms extension in ClientHello). Adding or reordering default signature + * algorithms alters ClientHello wire format and peer certificate/key selection. Do NOT modify + * expected defaults without an Android compatibility review and an associated AppCompat / + * aconfig flag. + */ + public static void assertDefaultSignatureAlgorithms(String[] signatureAlgorithms) { + List actualList = Arrays.asList(signatureAlgorithms); + Boolean pqcEnabled = isPlatformPqcDefaultSignatureAlgorithmsEnabledOrNull(); + if (Boolean.TRUE.equals(pqcEnabled)) { + assertEquals("Unexpected default signature algorithms list when PQC is enabled", + SIGNATURE_ALGORITHMS_DEFAULT_PQC, actualList); + } else if (Boolean.FALSE.equals(pqcEnabled)) { + assertEquals("Unexpected default signature algorithms list when PQC is disabled", + SIGNATURE_ALGORITHMS_DEFAULT, actualList); + } else { + assertTrue("Unexpected default signature algorithms list: " + actualList, + actualList.equals(SIGNATURE_ALGORITHMS_DEFAULT) + || actualList.equals(SIGNATURE_ALGORITHMS_DEFAULT_PQC)); + } } + private static Boolean isPlatformPqcDefaultSignatureAlgorithmsEnabledOrNull() { + String stdNamesPkg = StandardNames.class.getPackage().getName(); + String basePkg = stdNamesPkg.substring(0, stdNamesPkg.length() - ".java.security".length()); + try { + Class platformClass = Class.forName(basePkg + ".Platform"); + java.lang.reflect.Method method = + platformClass.getDeclaredMethod("isPqcDefaultSignatureAlgorithmsEnabled"); + method.setAccessible(true); + return (Boolean) method.invoke(null); + } catch (ReflectiveOperationException | SecurityException e) { + return null; + } + } + + /** + * Assert that the enabled protocols on an {@code SSLContext} match the expected default list. + * + *

    ANDROID COMPATIBILITY GATE: This assertion guards default enabled TLS protocol versions. + * Do NOT change default enabled protocols without an Android compatibility review and an + * associated AppCompat / aconfig flag. + */ public static void assertSSLContextEnabledProtocols(String version, String[] protocols) { Set expected = new HashSet<>(Arrays.asList(SSL_CONTEXT_PROTOCOLS_ENABLED.get(version))); diff --git a/testing/src/main/java/org/conscrypt/javax/net/ssl/SSLConfigurationAsserts.java b/testing/src/main/java/org/conscrypt/javax/net/ssl/SSLConfigurationAsserts.java index 8cde2b07c..9772920b8 100644 --- a/testing/src/main/java/org/conscrypt/javax/net/ssl/SSLConfigurationAsserts.java +++ b/testing/src/main/java/org/conscrypt/javax/net/ssl/SSLConfigurationAsserts.java @@ -46,6 +46,11 @@ private SSLConfigurationAsserts() {} * {@link SSLSocketFactory}, {@link SSLServerSocketFactory}, {@link SSLSocket}, * {@link SSLServerSocket} and {@link SSLEngine} instances created from the context match the * configuration. + * + *

    ANDROID COMPATIBILITY GATE: These default configuration assertions guard Android app + * compatibility. Do NOT relax or update expected default protocols or cipher suites to + * accommodate upstream changes without an Android compatibility review and an associated + * AppCompat / aconfig flag. */ public static void assertSSLContextDefaultConfiguration(SSLContext sslContext) throws IOException { diff --git a/testing/src/main/java/org/conscrypt/tlswire/handshake/HelloExtension.java b/testing/src/main/java/org/conscrypt/tlswire/handshake/HelloExtension.java index 0451d35ff..cd08361b8 100644 --- a/testing/src/main/java/org/conscrypt/tlswire/handshake/HelloExtension.java +++ b/testing/src/main/java/org/conscrypt/tlswire/handshake/HelloExtension.java @@ -29,6 +29,7 @@ public class HelloExtension { public static final int TYPE_SERVER_NAME = 0; public static final int TYPE_ELLIPTIC_CURVES = 10; + public static final int TYPE_SIGNATURE_ALGORITHMS = 13; public static final int TYPE_APPLICATION_LAYER_PROTOCOL_NEGOTIATION = 16; public static final int TYPE_PADDING = 21; public static final int TYPE_SESSION_TICKET = 35; @@ -48,7 +49,7 @@ public class HelloExtension { TYPE_TO_NAME.put(TYPE_ELLIPTIC_CURVES, "elliptic_curves"); TYPE_TO_NAME.put(11, "ec_point_formats"); TYPE_TO_NAME.put(12, "srp"); - TYPE_TO_NAME.put(13, "signature_algorithms"); + TYPE_TO_NAME.put(TYPE_SIGNATURE_ALGORITHMS, "signature_algorithms"); TYPE_TO_NAME.put(14, "use_srtp"); TYPE_TO_NAME.put(15, "heartbeat"); TYPE_TO_NAME.put(TYPE_APPLICATION_LAYER_PROTOCOL_NEGOTIATION, @@ -77,6 +78,9 @@ public static HelloExtension read(DataInput in) throws IOException { case TYPE_ELLIPTIC_CURVES: result = new EllipticCurvesHelloExtension(); break; + case TYPE_SIGNATURE_ALGORITHMS: + result = new SignatureAlgorithmsHelloExtension(); + break; case TYPE_APPLICATION_LAYER_PROTOCOL_NEGOTIATION: result = new AlpnHelloExtension(); break; diff --git a/testing/src/main/java/org/conscrypt/tlswire/handshake/SignatureAlgorithmsHelloExtension.java b/testing/src/main/java/org/conscrypt/tlswire/handshake/SignatureAlgorithmsHelloExtension.java new file mode 100644 index 000000000..fe00e7dc9 --- /dev/null +++ b/testing/src/main/java/org/conscrypt/tlswire/handshake/SignatureAlgorithmsHelloExtension.java @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2026 The Android Open Source Project + * + * 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 org.conscrypt.tlswire.handshake; + +import org.conscrypt.tlswire.util.IoUtils; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * {@code signature_algorithms} {@link HelloExtension} from RFC 5246 section 7.4.1.4.1 and RFC 8446 + * section 4.2.3. + */ +public class SignatureAlgorithmsHelloExtension extends HelloExtension { + public List supported; + public boolean wellFormed; + + @Override + protected void parseData() throws IOException { + byte[] signatureAlgorithmsListBytes = IoUtils.readTlsVariableLengthByteVector( + new DataInputStream(new ByteArrayInputStream(data)), 0xffff); + ByteArrayInputStream signatureAlgorithmsListIn = + new ByteArrayInputStream(signatureAlgorithmsListBytes); + DataInputStream in = new DataInputStream(signatureAlgorithmsListIn); + wellFormed = (signatureAlgorithmsListIn.available() % 2) == 0; + supported = new ArrayList(signatureAlgorithmsListIn.available() / 2); + while (signatureAlgorithmsListIn.available() >= 2) { + int schemeId = in.readUnsignedShort(); + supported.add(signatureSchemeToName(schemeId)); + } + } + + private static String signatureSchemeToName(int schemeId) { + switch (schemeId) { + case 0x0201: + return "rsa_pkcs1_sha1"; + case 0x0203: + return "ecdsa_sha1"; + case 0x0401: + return "rsa_pkcs1_sha256"; + case 0x0403: + return "ecdsa_secp256r1_sha256"; + case 0x0501: + return "rsa_pkcs1_sha384"; + case 0x0503: + return "ecdsa_secp384r1_sha384"; + case 0x0601: + return "rsa_pkcs1_sha512"; + case 0x0603: + return "ecdsa_secp521r1_sha512"; + case 0x0804: + return "rsa_pss_rsae_sha256"; + case 0x0805: + return "rsa_pss_rsae_sha384"; + case 0x0806: + return "rsa_pss_rsae_sha512"; + case 0x0807: + return "ed25519"; + case 0x0808: + return "ed448"; + case 0x0809: + return "rsa_pss_pss_sha256"; + case 0x080a: + return "rsa_pss_pss_sha384"; + case 0x080b: + return "rsa_pss_pss_sha512"; + case 0x0904: + return "mldsa44"; + case 0x0905: + return "mldsa65"; + case 0x0906: + return "mldsa87"; + default: + return String.format("0x%04x", schemeId); + } + } + + @Override + public String toString() { + StringBuilder sb = + new StringBuilder("HelloExtension{type: signature_algorithms, wellFormed: "); + sb.append(wellFormed); + sb.append(", supported: "); + sb.append(supported); + sb.append('}'); + return sb.toString(); + } +}