summaryrefslogtreecommitdiffstats
path: root/security/nss/lib/ssl
diff options
context:
space:
mode:
Diffstat (limited to 'security/nss/lib/ssl')
-rw-r--r--security/nss/lib/ssl/Makefile63
-rw-r--r--security/nss/lib/ssl/SSLerrs.h602
-rw-r--r--security/nss/lib/ssl/authcert.c250
-rw-r--r--security/nss/lib/ssl/cmpcert.c64
-rw-r--r--security/nss/lib/ssl/config.mk51
-rw-r--r--security/nss/lib/ssl/dhe-param.c418
-rw-r--r--security/nss/lib/ssl/dtls13con.c608
-rw-r--r--security/nss/lib/ssl/dtls13con.h38
-rw-r--r--security/nss/lib/ssl/dtlscon.c1474
-rw-r--r--security/nss/lib/ssl/dtlscon.h51
-rw-r--r--security/nss/lib/ssl/exports.gyp30
-rw-r--r--security/nss/lib/ssl/manifest.mn73
-rw-r--r--security/nss/lib/ssl/notes.txt104
-rw-r--r--security/nss/lib/ssl/os2_err.c330
-rw-r--r--security/nss/lib/ssl/os2_err.h53
-rw-r--r--security/nss/lib/ssl/preenc.h113
-rw-r--r--security/nss/lib/ssl/prelib.c34
-rw-r--r--security/nss/lib/ssl/selfencrypt.c321
-rw-r--r--security/nss/lib/ssl/selfencrypt.h32
-rw-r--r--security/nss/lib/ssl/ssl.def255
-rw-r--r--security/nss/lib/ssl/ssl.gyp102
-rw-r--r--security/nss/lib/ssl/ssl.h1608
-rw-r--r--security/nss/lib/ssl/ssl.rc68
-rw-r--r--security/nss/lib/ssl/ssl3con.c14318
-rw-r--r--security/nss/lib/ssl/ssl3ecc.c965
-rw-r--r--security/nss/lib/ssl/ssl3ext.c1181
-rw-r--r--security/nss/lib/ssl/ssl3ext.h212
-rw-r--r--security/nss/lib/ssl/ssl3exthandle.c2004
-rw-r--r--security/nss/lib/ssl/ssl3exthandle.h133
-rw-r--r--security/nss/lib/ssl/ssl3gthr.c823
-rw-r--r--security/nss/lib/ssl/ssl3prot.h199
-rw-r--r--security/nss/lib/ssl/sslauth.c292
-rw-r--r--security/nss/lib/ssl/sslbloom.c94
-rw-r--r--security/nss/lib/ssl/sslbloom.h32
-rw-r--r--security/nss/lib/ssl/sslcert.c1016
-rw-r--r--security/nss/lib/ssl/sslcert.h67
-rw-r--r--security/nss/lib/ssl/sslcon.c248
-rw-r--r--security/nss/lib/ssl/ssldef.c226
-rw-r--r--security/nss/lib/ssl/sslencode.c383
-rw-r--r--security/nss/lib/ssl/sslencode.h94
-rw-r--r--security/nss/lib/ssl/sslenum.c157
-rw-r--r--security/nss/lib/ssl/sslerr.c41
-rw-r--r--security/nss/lib/ssl/sslerr.h298
-rw-r--r--security/nss/lib/ssl/sslerrstrs.c36
-rw-r--r--security/nss/lib/ssl/sslexp.h1087
-rw-r--r--security/nss/lib/ssl/sslgrp.c164
-rw-r--r--security/nss/lib/ssl/sslimpl.h2020
-rw-r--r--security/nss/lib/ssl/sslinfo.c578
-rw-r--r--security/nss/lib/ssl/sslinit.c60
-rw-r--r--security/nss/lib/ssl/sslmutex.c658
-rw-r--r--security/nss/lib/ssl/sslmutex.h129
-rw-r--r--security/nss/lib/ssl/sslnonce.c1228
-rw-r--r--security/nss/lib/ssl/sslprimitive.c482
-rw-r--r--security/nss/lib/ssl/sslproto.h294
-rw-r--r--security/nss/lib/ssl/sslreveal.c108
-rw-r--r--security/nss/lib/ssl/sslsecur.c1385
-rw-r--r--security/nss/lib/ssl/sslsnce.c2251
-rw-r--r--security/nss/lib/ssl/sslsock.c4635
-rw-r--r--security/nss/lib/ssl/sslspec.c277
-rw-r--r--security/nss/lib/ssl/sslspec.h200
-rw-r--r--security/nss/lib/ssl/sslt.h583
-rw-r--r--security/nss/lib/ssl/ssltrace.c114
-rw-r--r--security/nss/lib/ssl/sslver.c18
-rw-r--r--security/nss/lib/ssl/tls13con.c6568
-rw-r--r--security/nss/lib/ssl/tls13con.h177
-rw-r--r--security/nss/lib/ssl/tls13ech.c2818
-rw-r--r--security/nss/lib/ssl/tls13ech.h125
-rw-r--r--security/nss/lib/ssl/tls13echv.c167
-rw-r--r--security/nss/lib/ssl/tls13err.h28
-rw-r--r--security/nss/lib/ssl/tls13exthandle.c1802
-rw-r--r--security/nss/lib/ssl/tls13exthandle.h127
-rw-r--r--security/nss/lib/ssl/tls13hashstate.c332
-rw-r--r--security/nss/lib/ssl/tls13hashstate.h27
-rw-r--r--security/nss/lib/ssl/tls13hkdf.c305
-rw-r--r--security/nss/lib/ssl/tls13hkdf.h39
-rw-r--r--security/nss/lib/ssl/tls13psk.c219
-rw-r--r--security/nss/lib/ssl/tls13psk.h58
-rw-r--r--security/nss/lib/ssl/tls13replay.c285
-rw-r--r--security/nss/lib/ssl/tls13subcerts.c801
-rw-r--r--security/nss/lib/ssl/tls13subcerts.h56
-rw-r--r--security/nss/lib/ssl/unix_err.c837
-rw-r--r--security/nss/lib/ssl/unix_err.h57
-rw-r--r--security/nss/lib/ssl/win32err.c550
-rw-r--r--security/nss/lib/ssl/win32err.h51
84 files changed, 61261 insertions, 0 deletions
diff --git a/security/nss/lib/ssl/Makefile b/security/nss/lib/ssl/Makefile
new file mode 100644
index 0000000000..8a8b06f4b5
--- /dev/null
+++ b/security/nss/lib/ssl/Makefile
@@ -0,0 +1,63 @@
+#! gmake
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+#######################################################################
+# (1) Include initial platform-independent assignments (MANDATORY). #
+#######################################################################
+
+include manifest.mn
+
+#######################################################################
+# (2) Include "global" configuration information. (OPTIONAL) #
+#######################################################################
+
+include $(CORE_DEPTH)/coreconf/config.mk
+
+#######################################################################
+# (3) Include "component" configuration information. (OPTIONAL) #
+######################################################################
+#
+
+
+#######################################################################
+# (4) Include "local" platform-dependent assignments (OPTIONAL). #
+#######################################################################
+
+include config.mk
+
+ifeq (,$(filter-out WIN%,$(OS_TARGET)))
+CSRCS += win32err.c
+DEFINES += -DIN_LIBSSL
+else
+ifeq ($(OS_TARGET),OS2)
+CSRCS += os2_err.c
+else
+CSRCS += unix_err.c
+endif
+endif
+
+# Enable key logging by default in debug builds, but not opt builds.
+# Logging still needs to be enabled at runtime through env vars.
+NSS_ALLOW_SSLKEYLOGFILE ?= $(if $(BUILD_OPT),0,1)
+ifeq (1,$(NSS_ALLOW_SSLKEYLOGFILE))
+DEFINES += -DNSS_ALLOW_SSLKEYLOGFILE=1
+endif
+
+#######################################################################
+# (5) Execute "global" rules. (OPTIONAL) #
+#######################################################################
+
+include $(CORE_DEPTH)/coreconf/rules.mk
+
+#######################################################################
+# (6) Execute "component" rules. (OPTIONAL) #
+#######################################################################
+
+
+
+#######################################################################
+# (7) Execute "local" rules. (OPTIONAL). #
+#######################################################################
diff --git a/security/nss/lib/ssl/SSLerrs.h b/security/nss/lib/ssl/SSLerrs.h
new file mode 100644
index 0000000000..3c585c7d4f
--- /dev/null
+++ b/security/nss/lib/ssl/SSLerrs.h
@@ -0,0 +1,602 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#define UNUSED_ERROR(x) ER3(SSL_ERROR_UNUSED_##x, (SSL_ERROR_BASE + x), \
+ "Unrecognized SSL error_code.")
+
+/* SSL-specific security error codes */
+/* caller must include "sslerr.h" */
+
+ER3(SSL_ERROR_EXPORT_ONLY_SERVER, SSL_ERROR_BASE + 0,
+ "Unable to communicate securely. Peer does not support high-grade encryption.")
+
+ER3(SSL_ERROR_US_ONLY_SERVER, SSL_ERROR_BASE + 1,
+ "Unable to communicate securely. Peer requires high-grade encryption which is not supported.")
+
+ER3(SSL_ERROR_NO_CYPHER_OVERLAP, SSL_ERROR_BASE + 2,
+ "Cannot communicate securely with peer: no common encryption algorithm(s).")
+
+ER3(SSL_ERROR_NO_CERTIFICATE, SSL_ERROR_BASE + 3,
+ "Unable to find the certificate or key necessary for authentication.")
+
+ER3(SSL_ERROR_BAD_CERTIFICATE, SSL_ERROR_BASE + 4,
+ "Unable to communicate securely with peer: peers's certificate was rejected.")
+
+UNUSED_ERROR(5)
+
+ER3(SSL_ERROR_BAD_CLIENT, SSL_ERROR_BASE + 6,
+ "The server has encountered bad data from the client.")
+
+ER3(SSL_ERROR_BAD_SERVER, SSL_ERROR_BASE + 7,
+ "The client has encountered bad data from the server.")
+
+ER3(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE, SSL_ERROR_BASE + 8,
+ "Unsupported certificate type.")
+
+ER3(SSL_ERROR_UNSUPPORTED_VERSION, SSL_ERROR_BASE + 9,
+ "Peer using unsupported version of security protocol.")
+
+UNUSED_ERROR(10)
+
+ER3(SSL_ERROR_WRONG_CERTIFICATE, SSL_ERROR_BASE + 11,
+ "Client authentication failed: private key in key database does not match public key in certificate database.")
+
+ER3(SSL_ERROR_BAD_CERT_DOMAIN, SSL_ERROR_BASE + 12,
+ "Unable to communicate securely with peer: requested domain name does not match the server's certificate.")
+
+ER3(SSL_ERROR_POST_WARNING, SSL_ERROR_BASE + 13,
+ "Unrecognized SSL error code.")
+
+ER3(SSL_ERROR_SSL2_DISABLED, (SSL_ERROR_BASE + 14),
+ "Peer only supports SSL version 2, which is locally disabled.")
+
+ER3(SSL_ERROR_BAD_MAC_READ, (SSL_ERROR_BASE + 15),
+ "SSL received a record with an incorrect Message Authentication Code.")
+
+ER3(SSL_ERROR_BAD_MAC_ALERT, (SSL_ERROR_BASE + 16),
+ "SSL peer reports incorrect Message Authentication Code.")
+
+ER3(SSL_ERROR_BAD_CERT_ALERT, (SSL_ERROR_BASE + 17),
+ "SSL peer cannot verify your certificate.")
+
+ER3(SSL_ERROR_REVOKED_CERT_ALERT, (SSL_ERROR_BASE + 18),
+ "SSL peer rejected your certificate as revoked.")
+
+ER3(SSL_ERROR_EXPIRED_CERT_ALERT, (SSL_ERROR_BASE + 19),
+ "SSL peer rejected your certificate as expired.")
+
+ER3(SSL_ERROR_SSL_DISABLED, (SSL_ERROR_BASE + 20),
+ "Cannot connect: SSL is disabled.")
+
+ER3(SSL_ERROR_FORTEZZA_PQG, (SSL_ERROR_BASE + 21),
+ "Cannot connect: SSL peer is in another FORTEZZA domain.")
+
+ER3(SSL_ERROR_UNKNOWN_CIPHER_SUITE, (SSL_ERROR_BASE + 22),
+ "An unknown SSL cipher suite has been requested.")
+
+ER3(SSL_ERROR_NO_CIPHERS_SUPPORTED, (SSL_ERROR_BASE + 23),
+ "No cipher suites are present and enabled in this program.")
+
+ER3(SSL_ERROR_BAD_BLOCK_PADDING, (SSL_ERROR_BASE + 24),
+ "SSL received a record with bad block padding.")
+
+ER3(SSL_ERROR_RX_RECORD_TOO_LONG, (SSL_ERROR_BASE + 25),
+ "SSL received a record that exceeded the maximum permissible length.")
+
+ER3(SSL_ERROR_TX_RECORD_TOO_LONG, (SSL_ERROR_BASE + 26),
+ "SSL attempted to send a record that exceeded the maximum permissible length.")
+
+/*
+ * Received a malformed (too long or short or invalid content) SSL handshake.
+ */
+ER3(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST, (SSL_ERROR_BASE + 27),
+ "SSL received a malformed Hello Request handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, (SSL_ERROR_BASE + 28),
+ "SSL received a malformed Client Hello handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_SERVER_HELLO, (SSL_ERROR_BASE + 29),
+ "SSL received a malformed Server Hello handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_CERTIFICATE, (SSL_ERROR_BASE + 30),
+ "SSL received a malformed Certificate handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH, (SSL_ERROR_BASE + 31),
+ "SSL received a malformed Server Key Exchange handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_CERT_REQUEST, (SSL_ERROR_BASE + 32),
+ "SSL received a malformed Certificate Request handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_HELLO_DONE, (SSL_ERROR_BASE + 33),
+ "SSL received a malformed Server Hello Done handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_CERT_VERIFY, (SSL_ERROR_BASE + 34),
+ "SSL received a malformed Certificate Verify handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH, (SSL_ERROR_BASE + 35),
+ "SSL received a malformed Client Key Exchange handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_FINISHED, (SSL_ERROR_BASE + 36),
+ "SSL received a malformed Finished handshake message.")
+
+/*
+ * Received a malformed (too long or short) SSL record.
+ */
+ER3(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER, (SSL_ERROR_BASE + 37),
+ "SSL received a malformed Change Cipher Spec record.")
+
+ER3(SSL_ERROR_RX_MALFORMED_ALERT, (SSL_ERROR_BASE + 38),
+ "SSL received a malformed Alert record.")
+
+ER3(SSL_ERROR_RX_MALFORMED_HANDSHAKE, (SSL_ERROR_BASE + 39),
+ "SSL received a malformed Handshake record.")
+
+ER3(SSL_ERROR_RX_MALFORMED_APPLICATION_DATA, (SSL_ERROR_BASE + 40),
+ "SSL received a malformed Application Data record.")
+
+/*
+ * Received an SSL handshake that was inappropriate for the state we're in.
+ * E.g. Server received message from server, or wrong state in state machine.
+ */
+ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST, (SSL_ERROR_BASE + 41),
+ "SSL received an unexpected Hello Request handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO, (SSL_ERROR_BASE + 42),
+ "SSL received an unexpected Client Hello handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO, (SSL_ERROR_BASE + 43),
+ "SSL received an unexpected Server Hello handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE, (SSL_ERROR_BASE + 44),
+ "SSL received an unexpected Certificate handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH, (SSL_ERROR_BASE + 45),
+ "SSL received an unexpected Server Key Exchange handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, (SSL_ERROR_BASE + 46),
+ "SSL received an unexpected Certificate Request handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE, (SSL_ERROR_BASE + 47),
+ "SSL received an unexpected Server Hello Done handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, (SSL_ERROR_BASE + 48),
+ "SSL received an unexpected Certificate Verify handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH, (SSL_ERROR_BASE + 49),
+ "SSL received an unexpected Client Key Exchange handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_FINISHED, (SSL_ERROR_BASE + 50),
+ "SSL received an unexpected Finished handshake message.")
+
+/*
+ * Received an SSL record that was inappropriate for the state we're in.
+ */
+ER3(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, (SSL_ERROR_BASE + 51),
+ "SSL received an unexpected Change Cipher Spec record.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_ALERT, (SSL_ERROR_BASE + 52),
+ "SSL received an unexpected Alert record.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE, (SSL_ERROR_BASE + 53),
+ "SSL received an unexpected Handshake record.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA, (SSL_ERROR_BASE + 54),
+ "SSL received an unexpected Application Data record.")
+
+/*
+ * Received record/message with unknown discriminant.
+ */
+ER3(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE, (SSL_ERROR_BASE + 55),
+ "SSL received a record with an unknown content type.")
+
+ER3(SSL_ERROR_RX_UNKNOWN_HANDSHAKE, (SSL_ERROR_BASE + 56),
+ "SSL received a handshake message with an unknown message type.")
+
+ER3(SSL_ERROR_RX_UNKNOWN_ALERT, (SSL_ERROR_BASE + 57),
+ "SSL received an alert record with an unknown alert description.")
+
+/*
+ * Received an alert reporting what we did wrong. (more alerts above)
+ */
+ER3(SSL_ERROR_CLOSE_NOTIFY_ALERT, (SSL_ERROR_BASE + 58),
+ "SSL peer has closed this connection.")
+
+ER3(SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT, (SSL_ERROR_BASE + 59),
+ "SSL peer was not expecting a handshake message it received.")
+
+ER3(SSL_ERROR_DECOMPRESSION_FAILURE_ALERT, (SSL_ERROR_BASE + 60),
+ "SSL peer was unable to successfully decompress an SSL record it received.")
+
+ER3(SSL_ERROR_HANDSHAKE_FAILURE_ALERT, (SSL_ERROR_BASE + 61),
+ "SSL peer was unable to negotiate an acceptable set of security parameters.")
+
+ER3(SSL_ERROR_ILLEGAL_PARAMETER_ALERT, (SSL_ERROR_BASE + 62),
+ "SSL peer rejected a handshake message for unacceptable content.")
+
+ER3(SSL_ERROR_UNSUPPORTED_CERT_ALERT, (SSL_ERROR_BASE + 63),
+ "SSL peer does not support certificates of the type it received.")
+
+ER3(SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT, (SSL_ERROR_BASE + 64),
+ "SSL peer had some unspecified issue with the certificate it received.")
+
+ER3(SSL_ERROR_GENERATE_RANDOM_FAILURE, (SSL_ERROR_BASE + 65),
+ "SSL experienced a failure of its random number generator.")
+
+ER3(SSL_ERROR_SIGN_HASHES_FAILURE, (SSL_ERROR_BASE + 66),
+ "Unable to digitally sign data required to verify your certificate.")
+
+ER3(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE, (SSL_ERROR_BASE + 67),
+ "SSL was unable to extract the public key from the peer's certificate.")
+
+ER3(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE, (SSL_ERROR_BASE + 68),
+ "Unspecified failure while processing SSL Server Key Exchange handshake.")
+
+ER3(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE, (SSL_ERROR_BASE + 69),
+ "Unspecified failure while processing SSL Client Key Exchange handshake.")
+
+ER3(SSL_ERROR_ENCRYPTION_FAILURE, (SSL_ERROR_BASE + 70),
+ "Bulk data encryption algorithm failed in selected cipher suite.")
+
+ER3(SSL_ERROR_DECRYPTION_FAILURE, (SSL_ERROR_BASE + 71),
+ "Bulk data decryption algorithm failed in selected cipher suite.")
+
+ER3(SSL_ERROR_SOCKET_WRITE_FAILURE, (SSL_ERROR_BASE + 72),
+ "Attempt to write encrypted data to underlying socket failed.")
+
+ER3(SSL_ERROR_MD5_DIGEST_FAILURE, (SSL_ERROR_BASE + 73),
+ "MD5 digest function failed.")
+
+ER3(SSL_ERROR_SHA_DIGEST_FAILURE, (SSL_ERROR_BASE + 74),
+ "SHA-1 digest function failed.")
+
+ER3(SSL_ERROR_MAC_COMPUTATION_FAILURE, (SSL_ERROR_BASE + 75),
+ "MAC computation failed.")
+
+ER3(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE, (SSL_ERROR_BASE + 76),
+ "Failure to create Symmetric Key context.")
+
+ER3(SSL_ERROR_SYM_KEY_UNWRAP_FAILURE, (SSL_ERROR_BASE + 77),
+ "Failure to unwrap the Symmetric key in Client Key Exchange message.")
+
+ER3(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED, (SSL_ERROR_BASE + 78),
+ "SSL Server attempted to use domestic-grade public key with export cipher suite.")
+
+ER3(SSL_ERROR_IV_PARAM_FAILURE, (SSL_ERROR_BASE + 79),
+ "PKCS11 code failed to translate an IV into a param.")
+
+ER3(SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, (SSL_ERROR_BASE + 80),
+ "Failed to initialize the selected cipher suite.")
+
+ER3(SSL_ERROR_SESSION_KEY_GEN_FAILURE, (SSL_ERROR_BASE + 81),
+ "Client failed to generate session keys for SSL session.")
+
+ER3(SSL_ERROR_NO_SERVER_KEY_FOR_ALG, (SSL_ERROR_BASE + 82),
+ "Server has no key for the attempted key exchange algorithm.")
+
+ER3(SSL_ERROR_TOKEN_INSERTION_REMOVAL, (SSL_ERROR_BASE + 83),
+ "PKCS#11 token was inserted or removed while operation was in progress.")
+
+ER3(SSL_ERROR_TOKEN_SLOT_NOT_FOUND, (SSL_ERROR_BASE + 84),
+ "No PKCS#11 token could be found to do a required operation.")
+
+ER3(SSL_ERROR_NO_COMPRESSION_OVERLAP, (SSL_ERROR_BASE + 85),
+ "Cannot communicate securely with peer: no common compression algorithm(s).")
+
+ER3(SSL_ERROR_HANDSHAKE_NOT_COMPLETED, (SSL_ERROR_BASE + 86),
+ "Cannot perform the operation until the handshake is complete.")
+
+ER3(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE, (SSL_ERROR_BASE + 87),
+ "Received incorrect handshakes hash values from peer.")
+
+ER3(SSL_ERROR_CERT_KEA_MISMATCH, (SSL_ERROR_BASE + 88),
+ "The certificate provided cannot be used with the selected authentication type.")
+
+ER3(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA, (SSL_ERROR_BASE + 89),
+ "No certificate authority is trusted for SSL client authentication.")
+
+ER3(SSL_ERROR_SESSION_NOT_FOUND, (SSL_ERROR_BASE + 90),
+ "Client's SSL session ID not found in server's session cache.")
+
+ER3(SSL_ERROR_DECRYPTION_FAILED_ALERT, (SSL_ERROR_BASE + 91),
+ "Peer was unable to decrypt an SSL record it received.")
+
+ER3(SSL_ERROR_RECORD_OVERFLOW_ALERT, (SSL_ERROR_BASE + 92),
+ "Peer received an SSL record that was longer than is permitted.")
+
+ER3(SSL_ERROR_UNKNOWN_CA_ALERT, (SSL_ERROR_BASE + 93),
+ "Peer does not recognize and trust the CA that issued your certificate.")
+
+ER3(SSL_ERROR_ACCESS_DENIED_ALERT, (SSL_ERROR_BASE + 94),
+ "Peer received a valid certificate, but access was denied.")
+
+ER3(SSL_ERROR_DECODE_ERROR_ALERT, (SSL_ERROR_BASE + 95),
+ "Peer could not decode an SSL handshake message.")
+
+ER3(SSL_ERROR_DECRYPT_ERROR_ALERT, (SSL_ERROR_BASE + 96),
+ "Peer reports failure of signature verification or key exchange.")
+
+ER3(SSL_ERROR_EXPORT_RESTRICTION_ALERT, (SSL_ERROR_BASE + 97),
+ "Peer reports negotiation not in compliance with export regulations.")
+
+ER3(SSL_ERROR_PROTOCOL_VERSION_ALERT, (SSL_ERROR_BASE + 98),
+ "Peer reports incompatible or unsupported protocol version.")
+
+ER3(SSL_ERROR_INSUFFICIENT_SECURITY_ALERT, (SSL_ERROR_BASE + 99),
+ "Server requires ciphers more secure than those supported by client.")
+
+ER3(SSL_ERROR_INTERNAL_ERROR_ALERT, (SSL_ERROR_BASE + 100),
+ "Peer reports it experienced an internal error.")
+
+ER3(SSL_ERROR_USER_CANCELED_ALERT, (SSL_ERROR_BASE + 101),
+ "Peer user canceled handshake.")
+
+ER3(SSL_ERROR_NO_RENEGOTIATION_ALERT, (SSL_ERROR_BASE + 102),
+ "Peer does not permit renegotiation of SSL security parameters.")
+
+ER3(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED, (SSL_ERROR_BASE + 103),
+ "SSL server cache not configured and not disabled for this socket.")
+
+ER3(SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT, (SSL_ERROR_BASE + 104),
+ "SSL peer does not support requested TLS hello extension.")
+
+ER3(SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT, (SSL_ERROR_BASE + 105),
+ "SSL peer could not obtain your certificate from the supplied URL.")
+
+ER3(SSL_ERROR_UNRECOGNIZED_NAME_ALERT, (SSL_ERROR_BASE + 106),
+ "SSL peer has no certificate for the requested DNS name.")
+
+ER3(SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT, (SSL_ERROR_BASE + 107),
+ "SSL peer was unable to get an OCSP response for its certificate.")
+
+ER3(SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT, (SSL_ERROR_BASE + 108),
+ "SSL peer reported bad certificate hash value.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET, (SSL_ERROR_BASE + 109),
+ "SSL received an unexpected New Session Ticket handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET, (SSL_ERROR_BASE + 110),
+ "SSL received a malformed New Session Ticket handshake message.")
+
+ER3(SSL_ERROR_DECOMPRESSION_FAILURE, (SSL_ERROR_BASE + 111),
+ "SSL received a compressed record that could not be decompressed.")
+
+ER3(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED, (SSL_ERROR_BASE + 112),
+ "Renegotiation is not allowed on this SSL socket.")
+
+ER3(SSL_ERROR_UNSAFE_NEGOTIATION, (SSL_ERROR_BASE + 113),
+ "Peer attempted old style (potentially vulnerable) handshake.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD, (SSL_ERROR_BASE + 114),
+ "SSL received an unexpected uncompressed record.")
+
+ER3(SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY, (SSL_ERROR_BASE + 115),
+ "SSL received a weak ephemeral Diffie-Hellman key in Server Key Exchange handshake message.")
+
+ER3(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID, (SSL_ERROR_BASE + 116),
+ "SSL received invalid ALPN extension data.")
+
+ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2, (SSL_ERROR_BASE + 117),
+ "SSL feature not supported for SSL 2.0 connections.")
+
+ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS, (SSL_ERROR_BASE + 118),
+ "SSL feature not supported for servers.")
+
+ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS, (SSL_ERROR_BASE + 119),
+ "SSL feature not supported for clients.")
+
+ER3(SSL_ERROR_INVALID_VERSION_RANGE, (SSL_ERROR_BASE + 120),
+ "SSL version range is not valid.")
+
+ER3(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION, (SSL_ERROR_BASE + 121),
+ "SSL peer selected a cipher suite disallowed for the selected protocol version.")
+
+ER3(SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST, (SSL_ERROR_BASE + 122),
+ "SSL received a malformed Hello Verify Request handshake message.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST, (SSL_ERROR_BASE + 123),
+ "SSL received an unexpected Hello Verify Request handshake message.")
+
+ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION, (SSL_ERROR_BASE + 124),
+ "SSL feature not supported for the protocol version.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS, (SSL_ERROR_BASE + 125),
+ "SSL received an unexpected Certificate Status handshake message.")
+
+ER3(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM, (SSL_ERROR_BASE + 126),
+ "Unsupported hash algorithm used by TLS peer.")
+
+ER3(SSL_ERROR_DIGEST_FAILURE, (SSL_ERROR_BASE + 127),
+ "Digest function failed.")
+
+ER3(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 128),
+ "Incorrect signature algorithm specified in a digitally-signed element.")
+
+ER3(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK, (SSL_ERROR_BASE + 129),
+ "The next protocol negotiation extension was enabled, but the callback was cleared prior to being needed.")
+
+ER3(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL, (SSL_ERROR_BASE + 130),
+ "The server supports no protocols that the client advertises in the ALPN extension.")
+
+ER3(SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT, (SSL_ERROR_BASE + 131),
+ "The server rejected the handshake because the client downgraded to a lower "
+ "TLS version than the server supports.")
+
+ER3(SSL_ERROR_WEAK_SERVER_CERT_KEY, (SSL_ERROR_BASE + 132),
+ "The server certificate included a public key that was too weak.")
+
+ER3(SSL_ERROR_RX_SHORT_DTLS_READ, (SSL_ERROR_BASE + 133),
+ "Not enough room in buffer for DTLS record.")
+
+ER3(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 134),
+ "No supported TLS signature algorithm was configured.")
+
+ER3(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 135),
+ "The peer used an unsupported combination of signature and hash algorithm.")
+
+ER3(SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET, (SSL_ERROR_BASE + 136),
+ "The peer tried to resume without a correct extended_master_secret extension")
+
+ER3(SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET, (SSL_ERROR_BASE + 137),
+ "The peer tried to resume with an unexpected extended_master_secret extension")
+
+ER3(SSL_ERROR_RX_MALFORMED_KEY_SHARE, (SSL_ERROR_BASE + 138),
+ "SSL received a malformed Key Share extension.")
+
+ER3(SSL_ERROR_MISSING_KEY_SHARE, (SSL_ERROR_BASE + 139),
+ "SSL expected a Key Share extension.")
+
+ER3(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE, (SSL_ERROR_BASE + 140),
+ "SSL received a malformed ECDHE key share handshake extension.")
+
+ER3(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE, (SSL_ERROR_BASE + 141),
+ "SSL received a malformed DHE key share handshake extension.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS, (SSL_ERROR_BASE + 142),
+ "SSL received an unexpected Encrypted Extensions handshake message.")
+
+ER3(SSL_ERROR_MISSING_EXTENSION_ALERT, (SSL_ERROR_BASE + 143),
+ "SSL received a missing_extension alert.")
+
+ER3(SSL_ERROR_KEY_EXCHANGE_FAILURE, (SSL_ERROR_BASE + 144),
+ "SSL had an error performing key exchange.")
+
+ER3(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION, (SSL_ERROR_BASE + 145),
+ "SSL received an extension that is not permitted for this version.")
+
+ER3(SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS, (SSL_ERROR_BASE + 146),
+ "SSL received a malformed Encrypted Extensions handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_PRE_SHARED_KEY, (SSL_ERROR_BASE + 147),
+ "SSL received an invalid PreSharedKey extension.")
+
+ER3(SSL_ERROR_RX_MALFORMED_EARLY_DATA, (SSL_ERROR_BASE + 148),
+ "SSL received an invalid EarlyData extension.")
+
+UNUSED_ERROR(149)
+
+ER3(SSL_ERROR_MISSING_ALPN_EXTENSION, (SSL_ERROR_BASE + 150),
+ "SSL didn't receive an expected ALPN extension.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_EXTENSION, (SSL_ERROR_BASE + 151),
+ "SSL received an unexpected extension.")
+
+ER3(SSL_ERROR_MISSING_SUPPORTED_GROUPS, (SSL_ERROR_BASE + 152),
+ "SSL expected a supported groups extension.")
+
+ER3(SSL_ERROR_TOO_MANY_RECORDS, (SSL_ERROR_BASE + 153),
+ "SSL sent or received too many records with the same symmetric key.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST, (SSL_ERROR_BASE + 154),
+ "SSL received an unexpected Hello Retry Request handshake message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST, (SSL_ERROR_BASE + 155),
+ "SSL received a malformed Hello Retry Request handshake message.")
+
+ER3(SSL_ERROR_BAD_2ND_CLIENT_HELLO, (SSL_ERROR_BASE + 156),
+ "SSL received a second Client Hello message without a usable key share.")
+
+ER3(SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION, (SSL_ERROR_BASE + 157),
+ "SSL expected a signature algorithms extension.")
+
+ER3(SSL_ERROR_MALFORMED_PSK_KEY_EXCHANGE_MODES, (SSL_ERROR_BASE + 158),
+ "SSL received a malformed PSK key exchange modes extension.")
+
+ER3(SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES, (SSL_ERROR_BASE + 159),
+ "SSL expected a PSK key exchange modes extension.")
+
+ER3(SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA, (SSL_ERROR_BASE + 160),
+ "SSL got a pre-TLS 1.3 version even though we sent early data.")
+
+ER3(SSL_ERROR_TOO_MUCH_EARLY_DATA, (SSL_ERROR_BASE + 161),
+ "SSL received more early data than permitted.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA, (SSL_ERROR_BASE + 162),
+ "SSL received an unexpected End of Early Data message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA, (SSL_ERROR_BASE + 163),
+ "SSL received a malformed End of Early Data message.")
+
+ER3(SSL_ERROR_UNSUPPORTED_EXPERIMENTAL_API, (SSL_ERROR_BASE + 164),
+ "An experimental API was called, but not supported.")
+
+ER3(SSL_ERROR_APPLICATION_ABORT, (SSL_ERROR_BASE + 165),
+ "SSL handshake aborted by the application.")
+
+ER3(SSL_ERROR_APP_CALLBACK_ERROR, (SSL_ERROR_BASE + 166),
+ "An application callback produced an invalid response.")
+
+ER3(SSL_ERROR_NO_TIMERS_ERROR, (SSL_ERROR_BASE + 167),
+ "No timers are currently running.")
+
+ER3(SSL_ERROR_MISSING_COOKIE_EXTENSION, (SSL_ERROR_BASE + 168),
+ "A second ClientHello was received without a cookie extension.")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, (SSL_ERROR_BASE + 169),
+ "SSL received an unexpected key update message.")
+
+ER3(SSL_ERROR_RX_MALFORMED_KEY_UPDATE, (SSL_ERROR_BASE + 170),
+ "SSL received a malformed key update message.")
+
+ER3(SSL_ERROR_TOO_MANY_KEY_UPDATES, (SSL_ERROR_BASE + 171),
+ "SSL attempted too many key updates.")
+
+ER3(SSL_ERROR_HANDSHAKE_FAILED, (SSL_ERROR_BASE + 172),
+ "SSL handshake has already failed. No more operations possible.")
+
+ER3(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR, (SSL_ERROR_BASE + 173),
+ "SSL received an invalid resumption token.")
+
+ER3(SSL_ERROR_RX_MALFORMED_DTLS_ACK, (SSL_ERROR_BASE + 174),
+ "SSL received a malformed DTLS ACK")
+
+ER3(SSL_ERROR_DH_KEY_TOO_LONG, (SSL_ERROR_BASE + 175),
+ "SSL received a DH key share that's too long (>8192 bit).")
+
+ER3(SSL_ERROR_RX_MALFORMED_ESNI_KEYS, (SSL_ERROR_BASE + 176),
+ "SSL received a malformed ESNI keys structure")
+
+ER3(SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION, (SSL_ERROR_BASE + 177),
+ "SSL received a malformed ESNI extension")
+
+ER3(SSL_ERROR_MISSING_ESNI_EXTENSION, (SSL_ERROR_BASE + 178),
+ "SSL did not receive an ESNI extension")
+
+ER3(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE, (SSL_ERROR_BASE + 179),
+ "SSL received an unexpected record type.")
+
+ER3(SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION, (SSL_ERROR_BASE + 180),
+ "SSL cannot send a CertificateRequest because the client doesn't support post-handshake authentication.")
+
+ER3(SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT, (SSL_ERROR_BASE + 181),
+ "SSL received a certificate_required alert.")
+
+ER3(SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, (SSL_ERROR_BASE + 182),
+ "SSL received a delegated credential with unexpected certificate verification algorithm.")
+
+ER3(SSL_ERROR_DC_BAD_SIGNATURE, (SSL_ERROR_BASE + 183),
+ "SSL received a delegated credential with an invalid signature.")
+
+ER3(SSL_ERROR_DC_INVALID_KEY_USAGE, (SSL_ERROR_BASE + 184),
+ "SSL received a delegated credential from a certificate with invalid key usage.")
+
+ER3(SSL_ERROR_DC_EXPIRED, (SSL_ERROR_BASE + 185),
+ "SSL received a delegated credential that expired.")
+
+ER3(SSL_ERROR_DC_INAPPROPRIATE_VALIDITY_PERIOD, (SSL_ERROR_BASE + 186),
+ "SSL received a delegated credential with excessive TTL.")
+
+ER3(SSL_ERROR_FEATURE_DISABLED, (SSL_ERROR_BASE + 187),
+ "The requested feature is disabled.")
+
+ER3(SSL_ERROR_ECH_RETRY_WITH_ECH, (SSL_ERROR_BASE + 188),
+ "TLS ECH was rejected, but verification succeeded and compatible retry_configs are available.")
+
+ER3(SSL_ERROR_ECH_RETRY_WITHOUT_ECH, (SSL_ERROR_BASE + 189),
+ "TLS ECH was rejected, but verification succeeded and no compatible retry_configs were found.")
+
+ER3(SSL_ERROR_ECH_FAILED, (SSL_ERROR_BASE + 190),
+ "TLS ECH was rejected and verification failed.")
+
+ER3(SSL_ERROR_ECH_REQUIRED_ALERT, (SSL_ERROR_BASE + 191),
+ "SSL peer reported ECH required.")
diff --git a/security/nss/lib/ssl/authcert.c b/security/nss/lib/ssl/authcert.c
new file mode 100644
index 0000000000..3d64173b41
--- /dev/null
+++ b/security/nss/lib/ssl/authcert.c
@@ -0,0 +1,250 @@
+/*
+ * NSS utility functions
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <stdio.h>
+#include <string.h>
+#include "prerror.h"
+#include "secitem.h"
+#include "prnetdb.h"
+#include "cert.h"
+#include "nspr.h"
+#include "secder.h"
+#include "keyhi.h"
+#include "nss.h"
+#include "ssl.h"
+#include "pk11func.h" /* for PK11_ function calls */
+#include "sslimpl.h"
+
+/* convert a CERTDistNameStr to an array ascii strings.
+ * we ignore caNames which we can't convert, so n could be less than nnames
+ * n is always set, even on failure.
+ * This function allows us to use the existing CERT_FilterCertListByCANames. */
+static char **
+ssl_DistNamesToStrings(struct CERTDistNamesStr *caNames, int *n)
+{
+ char **names;
+ int i;
+ SECStatus rv;
+ PLArenaPool *arena;
+
+ *n = 0;
+ names = PORT_ZNewArray(char *, caNames->nnames);
+ if (names == NULL) {
+ return NULL;
+ }
+ arena = PORT_NewArena(2048);
+ if (arena == NULL) {
+ PORT_Free(names);
+ return NULL;
+ }
+ for (i = 0; i < caNames->nnames; ++i) {
+ CERTName dn;
+ rv = SEC_QuickDERDecodeItem(arena, &dn, SEC_ASN1_GET(CERT_NameTemplate),
+ caNames->names + i);
+ if (rv != SECSuccess) {
+ continue;
+ }
+ names[*n] = CERT_NameToAscii(&dn);
+ if (names[*n])
+ (*n)++;
+ }
+ PORT_FreeArena(arena, PR_FALSE);
+ return names;
+}
+
+/* free the dist names we allocated in the above function. n must be the
+ * returned n from that function. */
+static void
+ssl_FreeDistNamesStrings(char **strings, int n)
+{
+ int i;
+ for (i = 0; i < n; i++) {
+ PORT_Free(strings[i]);
+ }
+ PORT_Free(strings);
+}
+
+PRBool
+ssl_CertIsUsable(sslSocket *ss, CERTCertificate *cert)
+{
+ SECStatus rv;
+ SSLSignatureScheme scheme;
+
+ if ((ss == NULL) || (cert == NULL)) {
+ return PR_FALSE;
+ }
+ /* There are two ways of handling the old style handshake:
+ * 1) check the actual record we are using and return true,
+ * if (!ss->ssl3.hs.hashType == handshake_hash_record &&
+ * ss->ssl3.hs.hashType == handshake_hash_single) {
+ * return PR_TRUE;
+ * 2) assume if ss->ss->ssl3.hs.clientAuthSignatureSchemesLen == 0 we are using the
+ * old handshake.
+ * There is one case where using 2 will be wrong: we somehow call this
+ * function outside the case where of out GetClientAuthData context.
+ * In that case we don't know that the 'real' peerScheme list is, so the
+ * best we can do is either always assume good or always assume bad.
+ * I think the best results is to always assume good, so we use
+ * option 2 here to handle that case as well.*/
+ if (ss->ssl3.hs.clientAuthSignatureSchemesLen == 0) {
+ return PR_TRUE;
+ }
+ if (ss->ssl3.hs.clientAuthSignatureSchemes == NULL) {
+ return PR_FALSE; /* should this really be an assert? */
+ }
+ rv = ssl_PickClientSignatureScheme(ss, cert, NULL,
+ ss->ssl3.hs.clientAuthSignatureSchemes,
+ ss->ssl3.hs.clientAuthSignatureSchemesLen,
+ &scheme);
+ if (rv != SECSuccess) {
+ return PR_FALSE;
+ }
+ return PR_TRUE;
+}
+
+SECStatus
+ssl_FilterClientCertListBySSLSocket(sslSocket *ss, CERTCertList *certList)
+{
+ CERTCertListNode *node;
+ CERTCertificate *cert;
+
+ if (!certList) {
+ return SECFailure;
+ }
+
+ node = CERT_LIST_HEAD(certList);
+
+ while (!CERT_LIST_END(node, certList)) {
+ cert = node->cert;
+ if (PR_TRUE != ssl_CertIsUsable(ss, cert)) {
+ /* cert doesn't match the socket criteria, remove it */
+ CERTCertListNode *freenode = node;
+ node = CERT_LIST_NEXT(node);
+ CERT_RemoveCertListNode(freenode);
+ } else {
+ /* this cert is good, go to the next cert */
+ node = CERT_LIST_NEXT(node);
+ }
+ }
+
+ return (SECSuccess);
+}
+
+/* This function can be called by the application's custom GetClientAuthHook
+ * to filter out any certs in the cert list that doesn't match the negotiated
+ * requirements of the current SSL connection.
+ */
+SECStatus
+SSL_FilterClientCertListBySocket(PRFileDesc *fd, CERTCertList *certList)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (ss == NULL) {
+ return SECFailure;
+ }
+ return ssl_FilterClientCertListBySSLSocket(ss, certList);
+}
+
+/* This function can be called by the application's custom GetClientAuthHook
+ * to determine if a single certificate matches the negotiated requirements of
+ * the current SSL connection.
+ */
+PRBool
+SSL_CertIsUsable(PRFileDesc *fd, CERTCertificate *cert)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (ss == NULL) {
+ return PR_FALSE;
+ }
+ return ssl_CertIsUsable(ss, cert);
+}
+
+/*
+ * This callback used by SSL to pull client certificate upon
+ * server request
+ */
+SECStatus
+NSS_GetClientAuthData(void *arg,
+ PRFileDesc *fd,
+ struct CERTDistNamesStr *caNames,
+ struct CERTCertificateStr **pRetCert,
+ struct SECKEYPrivateKeyStr **pRetKey)
+{
+ CERTCertificate *cert = NULL;
+ CERTCertList *certList = NULL;
+ SECKEYPrivateKey *privkey = NULL;
+ char *chosenNickName = (char *)arg; /* CONST */
+ SECStatus rv = SECFailure;
+
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+ void *pw_arg = SSL_RevealPinArg(fd);
+
+ /* first, handle any token authentication that may be needed */
+ if (chosenNickName && pw_arg) {
+ certList = PK11_FindCertsFromNickname(chosenNickName, pw_arg);
+ if (certList) {
+ CERT_FilterCertListForUserCerts(certList);
+ rv = CERT_FilterCertListByUsage(certList, certUsageSSLClient,
+ PR_FALSE);
+ if ((rv != SECSuccess) || CERT_LIST_EMPTY(certList)) {
+ CERT_DestroyCertList(certList);
+ certList = NULL;
+ }
+ }
+ }
+
+ /* otherwise look through the cache based on usage
+ * if chosenNickname is set, we ignore the expiration date */
+ if (certList == NULL) {
+ certList = CERT_FindUserCertsByUsage(CERT_GetDefaultCertDB(),
+ certUsageSSLClient,
+ PR_FALSE, chosenNickName == NULL,
+ pw_arg);
+ if (certList == NULL) {
+ return SECFailure;
+ }
+ /* filter only the certs that meet the nickname requirements */
+ if (chosenNickName) {
+ rv = CERT_FilterCertListByNickname(certList, chosenNickName,
+ pw_arg);
+ } else {
+ int nnames = 0;
+ char **names = ssl_DistNamesToStrings(caNames, &nnames);
+ rv = CERT_FilterCertListByCANames(certList, nnames, names,
+ certUsageSSLClient);
+ ssl_FreeDistNamesStrings(names, nnames);
+ }
+ if ((rv != SECSuccess) || CERT_LIST_EMPTY(certList)) {
+ CERT_DestroyCertList(certList);
+ return SECFailure;
+ }
+ }
+
+ /* now remove any certs that can't meet the connection requirements */
+ rv = ssl_FilterClientCertListBySSLSocket(ss, certList);
+ if ((rv != SECSuccess) || CERT_LIST_EMPTY(certList)) {
+ // no certs left.
+ CERT_DestroyCertList(certList);
+ return SECFailure;
+ }
+
+ /* now return the top cert in the list. We've strived to make the
+ * list ordered by the most likely usable cert, so it should be the best
+ * match. */
+ cert = CERT_DupCertificate(CERT_LIST_HEAD(certList)->cert);
+ CERT_DestroyCertList(certList);
+ privkey = PK11_FindKeyByAnyCert(cert, pw_arg);
+ if (privkey == NULL) {
+ CERT_DestroyCertificate(cert);
+ return SECFailure;
+ }
+ *pRetCert = cert;
+ *pRetKey = privkey;
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/cmpcert.c b/security/nss/lib/ssl/cmpcert.c
new file mode 100644
index 0000000000..8ab4a7f8d9
--- /dev/null
+++ b/security/nss/lib/ssl/cmpcert.c
@@ -0,0 +1,64 @@
+/*
+ * NSS utility functions
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <stdio.h>
+#include <string.h>
+#include "prerror.h"
+#include "secitem.h"
+#include "prnetdb.h"
+#include "cert.h"
+#include "nspr.h"
+#include "secder.h"
+#include "keyhi.h"
+#include "nss.h"
+
+/*
+ * Look to see if any of the signers in the cert chain for "cert" are found
+ * in the list of caNames.
+ * Returns SECSuccess if so, SECFailure if not.
+ */
+SECStatus
+NSS_CmpCertChainWCANames(CERTCertificate *cert, CERTDistNames *caNames)
+{
+ SECItem *caname;
+ CERTCertificate *curcert;
+ CERTCertificate *oldcert;
+ int j;
+ int depth;
+ SECItem issuerName;
+
+ if (!cert || !caNames || !caNames->nnames || !caNames->names ||
+ !caNames->names->data)
+ return SECFailure;
+ depth = 0;
+ curcert = CERT_DupCertificate(cert);
+
+ while (curcert) {
+ issuerName = curcert->derIssuer;
+
+ for (j = 0; j < caNames->nnames; j++) {
+ caname = &caNames->names[j];
+ if (SECITEM_CompareItem(&issuerName, caname) == SECEqual) {
+ CERT_DestroyCertificate(curcert);
+ return SECSuccess;
+ }
+ }
+ if ((depth <= 20) &&
+ (SECITEM_CompareItem(&curcert->derIssuer, &curcert->derSubject) !=
+ SECEqual)) {
+ oldcert = curcert;
+ curcert = CERT_FindCertByName(curcert->dbhandle,
+ &curcert->derIssuer);
+ CERT_DestroyCertificate(oldcert);
+ depth++;
+ } else {
+ CERT_DestroyCertificate(curcert);
+ curcert = NULL;
+ }
+ }
+ return SECFailure;
+}
diff --git a/security/nss/lib/ssl/config.mk b/security/nss/lib/ssl/config.mk
new file mode 100644
index 0000000000..309c5bc177
--- /dev/null
+++ b/security/nss/lib/ssl/config.mk
@@ -0,0 +1,51 @@
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+ifdef NISCC_TEST
+DEFINES += -DNISCC_TEST
+endif
+
+ifeq (,$(filter-out WIN%,$(OS_TARGET)))
+
+ifdef NS_USE_GCC
+EXTRA_SHARED_LIBS += \
+ -L$(DIST)/lib \
+ -lnss3 \
+ -L$(NSSUTIL_LIB_DIR) \
+ -lnssutil3 \
+ -L$(NSPR_LIB_DIR) \
+ -lplc4 \
+ -lplds4 \
+ -lnspr4 \
+ $(NULL)
+else # ! NS_USE_GCC
+EXTRA_SHARED_LIBS += \
+ $(DIST)/lib/nss3.lib \
+ $(DIST)/lib/nssutil3.lib \
+ $(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)plc4.lib \
+ $(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)plds4.lib \
+ $(NSPR_LIB_DIR)/$(NSPR31_LIB_PREFIX)nspr4.lib \
+ $(NULL)
+endif # NS_USE_GCC
+
+else
+
+# $(EXTRA_SHARED_LIBS) come before $(OS_LIBS), except on AIX.
+EXTRA_SHARED_LIBS += \
+ -L$(DIST)/lib \
+ -lnss3 \
+ -L$(NSSUTIL_LIB_DIR) \
+ -lnssutil3 \
+ -L$(NSPR_LIB_DIR) \
+ -lplc4 \
+ -lplds4 \
+ -lnspr4 \
+ $(NULL)
+
+endif
+
+ifdef NSS_DISABLE_TLS_1_3
+DEFINES += -DNSS_DISABLE_TLS_1_3
+endif
diff --git a/security/nss/lib/ssl/dhe-param.c b/security/nss/lib/ssl/dhe-param.c
new file mode 100644
index 0000000000..32afa35206
--- /dev/null
+++ b/security/nss/lib/ssl/dhe-param.c
@@ -0,0 +1,418 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+static const unsigned char ff_dhe_g2[] = { 2 };
+
+static const unsigned char ff_dhe_2048_p[] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1,
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8,
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61,
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3,
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77,
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61,
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68,
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19,
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC,
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73,
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2,
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+};
+
+static const ssl3DHParams ff_dhe_2048_params = {
+ ssl_grp_ffdhe_2048,
+ { siBuffer, (unsigned char *)ff_dhe_2048_p, sizeof(ff_dhe_2048_p) },
+ { siBuffer, (unsigned char *)ff_dhe_g2, sizeof(ff_dhe_g2) },
+};
+
+static const unsigned char ff_dhe_3072_p[] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1,
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8,
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61,
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3,
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77,
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61,
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68,
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19,
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC,
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73,
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2,
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC,
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38,
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE,
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70,
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3,
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E,
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA,
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF,
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+};
+
+static const ssl3DHParams ff_dhe_3072_params = {
+ ssl_grp_ffdhe_3072,
+ { siBuffer, (unsigned char *)ff_dhe_3072_p, sizeof(ff_dhe_3072_p) },
+ { siBuffer, (unsigned char *)ff_dhe_g2, sizeof(ff_dhe_g2) },
+};
+
+static const unsigned char ff_dhe_4096_p[] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1,
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8,
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61,
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3,
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77,
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61,
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68,
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19,
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC,
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73,
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2,
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC,
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38,
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE,
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70,
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3,
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E,
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA,
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF,
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1,
+ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB,
+ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6,
+ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18,
+ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04,
+ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A,
+ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A,
+ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32,
+ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4,
+ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38,
+ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A,
+ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C,
+ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC,
+ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF,
+ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B,
+ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1,
+ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+};
+
+static const ssl3DHParams ff_dhe_4096_params = {
+ ssl_grp_ffdhe_4096,
+ { siBuffer, (unsigned char *)ff_dhe_4096_p, sizeof(ff_dhe_4096_p) },
+ { siBuffer, (unsigned char *)ff_dhe_g2, sizeof(ff_dhe_g2) },
+};
+
+static const unsigned char ff_dhe_6144_p[] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1,
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8,
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61,
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3,
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77,
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61,
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68,
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19,
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC,
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73,
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2,
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC,
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38,
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE,
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70,
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3,
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E,
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA,
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF,
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1,
+ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB,
+ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6,
+ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18,
+ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04,
+ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A,
+ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A,
+ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32,
+ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4,
+ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38,
+ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A,
+ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C,
+ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC,
+ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF,
+ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B,
+ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1,
+ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02,
+ 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A,
+ 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A,
+ 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6,
+ 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8,
+ 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C,
+ 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A,
+ 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71,
+ 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F,
+ 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77,
+ 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10,
+ 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8,
+ 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3,
+ 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E,
+ 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3,
+ 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4,
+ 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1,
+ 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92,
+ 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6,
+ 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82,
+ 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE,
+ 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C,
+ 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E,
+ 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46,
+ 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A,
+ 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17,
+ 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03,
+ 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04,
+ 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6,
+ 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69,
+ 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1,
+ 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4,
+ 0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+};
+
+static const ssl3DHParams ff_dhe_6144_params = {
+ ssl_grp_ffdhe_6144,
+ { siBuffer, (unsigned char *)ff_dhe_6144_p, sizeof(ff_dhe_6144_p) },
+ { siBuffer, (unsigned char *)ff_dhe_g2, sizeof(ff_dhe_g2) },
+};
+
+static const unsigned char ff_dhe_8192_p[] = {
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A,
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1,
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95,
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB,
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9,
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8,
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A,
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61,
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0,
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3,
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35,
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77,
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72,
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35,
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A,
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61,
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB,
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68,
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4,
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19,
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70,
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC,
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61,
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF,
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83,
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73,
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05,
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2,
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA,
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC,
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B,
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38,
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07,
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE,
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C,
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70,
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44,
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3,
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF,
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E,
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D,
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA,
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E,
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF,
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C,
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1,
+ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB,
+ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6,
+ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18,
+ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04,
+ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A,
+ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A,
+ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32,
+ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4,
+ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38,
+ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A,
+ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C,
+ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC,
+ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF,
+ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B,
+ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1,
+ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02,
+ 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A,
+ 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A,
+ 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6,
+ 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8,
+ 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C,
+ 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A,
+ 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71,
+ 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F,
+ 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77,
+ 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10,
+ 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8,
+ 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3,
+ 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E,
+ 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3,
+ 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4,
+ 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1,
+ 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92,
+ 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6,
+ 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82,
+ 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE,
+ 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C,
+ 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E,
+ 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46,
+ 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A,
+ 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17,
+ 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03,
+ 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04,
+ 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6,
+ 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69,
+ 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1,
+ 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4,
+ 0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA,
+ 0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38,
+ 0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64,
+ 0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43,
+ 0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E,
+ 0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF,
+ 0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29,
+ 0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65,
+ 0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02,
+ 0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4,
+ 0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82,
+ 0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C,
+ 0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51,
+ 0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22,
+ 0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74,
+ 0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE,
+ 0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C,
+ 0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC,
+ 0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B,
+ 0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9,
+ 0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0,
+ 0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31,
+ 0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57,
+ 0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8,
+ 0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E,
+ 0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30,
+ 0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E,
+ 0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE,
+ 0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D,
+ 0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D,
+ 0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E,
+ 0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C,
+ 0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+};
+
+static const ssl3DHParams ff_dhe_8192_params = {
+ ssl_grp_ffdhe_8192,
+ { siBuffer, (unsigned char *)ff_dhe_8192_p, sizeof(ff_dhe_8192_p) },
+ { siBuffer, (unsigned char *)ff_dhe_g2, sizeof(ff_dhe_g2) },
+};
diff --git a/security/nss/lib/ssl/dtls13con.c b/security/nss/lib/ssl/dtls13con.c
new file mode 100644
index 0000000000..a2cf4a8c67
--- /dev/null
+++ b/security/nss/lib/ssl/dtls13con.c
@@ -0,0 +1,608 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * DTLS 1.3 Protocol
+ */
+
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "keyhi.h"
+#include "pk11func.h"
+
+/*
+ * 0 1 2 3 4 5 6 7
+ * +-+-+-+-+-+-+-+-+
+ * |0|0|1|C|S|L|E E|
+ * +-+-+-+-+-+-+-+-+
+ * | Connection ID | Legend:
+ * | (if any, |
+ * / length as / C - CID present
+ * | negotiated) | S - Sequence number length
+ * +-+-+-+-+-+-+-+-+ L - Length present
+ * | 8 or 16 bit | E - Epoch
+ * |Sequence Number|
+ * +-+-+-+-+-+-+-+-+
+ * | 16 bit Length |
+ * | (if present) |
+ * +-+-+-+-+-+-+-+-+
+ */
+SECStatus
+dtls13_InsertCipherTextHeader(const sslSocket *ss, const ssl3CipherSpec *cwSpec,
+ sslBuffer *wrBuf, PRBool *needsLength)
+{
+ /* Avoid using short records for the handshake. We pack multiple records
+ * into the one datagram for the handshake. */
+ if (ss->opt.enableDtlsShortHeader &&
+ cwSpec->epoch > TrafficKeyHandshake) {
+ *needsLength = PR_FALSE;
+ /* The short header is comprised of two octets in the form
+ * 0b001000eessssssss where 'e' is the low two bits of the
+ * epoch and 's' is the low 8 bits of the sequence number. */
+ PRUint8 ct = 0x20 | ((uint64_t)cwSpec->epoch & 0x3);
+ if (sslBuffer_AppendNumber(wrBuf, ct, 1) != SECSuccess) {
+ return SECFailure;
+ }
+ PRUint8 seq = cwSpec->nextSeqNum & 0xff;
+ return sslBuffer_AppendNumber(wrBuf, seq, 1);
+ }
+
+ PRUint8 ct = 0x2c | ((PRUint8)cwSpec->epoch & 0x3);
+ if (sslBuffer_AppendNumber(wrBuf, ct, 1) != SECSuccess) {
+ return SECFailure;
+ }
+ if (sslBuffer_AppendNumber(wrBuf,
+ (cwSpec->nextSeqNum & 0xffff), 2) != SECSuccess) {
+ return SECFailure;
+ }
+ *needsLength = PR_TRUE;
+ return SECSuccess;
+}
+
+/* DTLS 1.3 Record map for ACK processing.
+ * This represents a single fragment, so a record which includes
+ * multiple fragments will have one entry for each fragment on the
+ * sender. We use the same structure on the receiver for convenience
+ * but the only value we actually use is |record|.
+ */
+typedef struct DTLSHandshakeRecordEntryStr {
+ PRCList link;
+ PRUint16 messageSeq; /* The handshake message sequence number. */
+ PRUint32 offset; /* The offset into the handshake message. */
+ PRUint32 length; /* The length of the fragment. */
+ sslSequenceNumber record; /* The record (includes epoch). */
+ PRBool acked; /* Has this packet been acked. */
+} DTLSHandshakeRecordEntry;
+
+/* Combine the epoch and sequence number into a single value. */
+static inline sslSequenceNumber
+dtls_CombineSequenceNumber(DTLSEpoch epoch, sslSequenceNumber seqNum)
+{
+ PORT_Assert(seqNum <= RECORD_SEQ_MAX);
+ return ((sslSequenceNumber)epoch << 48) | seqNum;
+}
+
+SECStatus
+dtls13_RememberFragment(sslSocket *ss,
+ PRCList *list,
+ PRUint32 sequence,
+ PRUint32 offset,
+ PRUint32 length,
+ DTLSEpoch epoch,
+ sslSequenceNumber record)
+{
+ DTLSHandshakeRecordEntry *entry;
+
+ PORT_Assert(IS_DTLS(ss));
+ /* We should never send an empty fragment with offset > 0. */
+ PORT_Assert(length || !offset);
+
+ if (!tls13_MaybeTls13(ss)) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(20, ("%d: SSL3[%d]: %s remembering %s record=%llx msg=%d offset=%d",
+ SSL_GETPID(), ss->fd,
+ SSL_ROLE(ss),
+ list == &ss->ssl3.hs.dtlsSentHandshake ? "sent" : "received",
+ dtls_CombineSequenceNumber(epoch, record), sequence, offset));
+
+ entry = PORT_ZAlloc(sizeof(DTLSHandshakeRecordEntry));
+ if (!entry) {
+ return SECFailure;
+ }
+
+ entry->messageSeq = sequence;
+ entry->offset = offset;
+ entry->length = length;
+ entry->record = dtls_CombineSequenceNumber(epoch, record);
+ entry->acked = PR_FALSE;
+
+ PR_APPEND_LINK(&entry->link, list);
+
+ return SECSuccess;
+}
+
+SECStatus
+dtls13_SendAck(sslSocket *ss)
+{
+ sslBuffer buf = SSL_BUFFER_EMPTY;
+ SECStatus rv = SECSuccess;
+ PRCList *cursor;
+ PRInt32 sent;
+ unsigned int offset;
+
+ SSL_TRC(10, ("%d: SSL3[%d]: Sending ACK",
+ SSL_GETPID(), ss->fd));
+
+ rv = sslBuffer_Skip(&buf, 2, &offset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ for (cursor = PR_LIST_HEAD(&ss->ssl3.hs.dtlsRcvdHandshake);
+ cursor != &ss->ssl3.hs.dtlsRcvdHandshake;
+ cursor = PR_NEXT_LINK(cursor)) {
+ DTLSHandshakeRecordEntry *entry = (DTLSHandshakeRecordEntry *)cursor;
+
+ SSL_TRC(10, ("%d: SSL3[%d]: ACK for record=%llx",
+ SSL_GETPID(), ss->fd, entry->record));
+ rv = sslBuffer_AppendNumber(&buf, entry->record, 8);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ rv = sslBuffer_InsertLength(&buf, offset, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ sent = ssl3_SendRecord(ss, NULL, ssl_ct_ack,
+ buf.buf, buf.len, 0);
+ ssl_ReleaseXmitBufLock(ss);
+ if (sent != buf.len) {
+ rv = SECFailure;
+ if (sent != -1) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ }
+ }
+
+loser:
+ sslBuffer_Clear(&buf);
+ return rv;
+}
+
+void
+dtls13_SendAckCb(sslSocket *ss)
+{
+ if (!IS_DTLS(ss)) {
+ return;
+ }
+ (void)dtls13_SendAck(ss);
+}
+
+/* Limits from draft-ietf-tls-dtls13-38; section 4.5.3. */
+PRBool
+dtls13_AeadLimitReached(ssl3CipherSpec *spec)
+{
+ if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ switch (spec->cipherDef->calg) {
+ case ssl_calg_chacha20:
+ case ssl_calg_aes_gcm:
+ return spec->deprotectionFailures >= (1ULL << 36);
+#ifdef UNSAFE_FUZZER_MODE
+ case ssl_calg_null:
+ return PR_FALSE;
+#endif
+ default:
+ PORT_Assert(0);
+ break;
+ }
+ }
+ return PR_FALSE;
+}
+
+/* Zero length messages are very simple to check. */
+static PRBool
+dtls_IsEmptyMessageAcknowledged(sslSocket *ss, PRUint16 msgSeq, PRUint32 offset)
+{
+ PRCList *cursor;
+
+ for (cursor = PR_LIST_HEAD(&ss->ssl3.hs.dtlsSentHandshake);
+ cursor != &ss->ssl3.hs.dtlsSentHandshake;
+ cursor = PR_NEXT_LINK(cursor)) {
+ DTLSHandshakeRecordEntry *entry = (DTLSHandshakeRecordEntry *)cursor;
+ if (!entry->acked || msgSeq != entry->messageSeq) {
+ continue;
+ }
+ /* Empty fragments are always offset 0. */
+ if (entry->length == 0) {
+ PORT_Assert(!entry->offset);
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+/* Take a range starting at |*start| and that start forwards based on the
+ * contents of the acknowedgement in |entry|. Only move if the acknowledged
+ * range overlaps |*start|. Return PR_TRUE if it moves. */
+static PRBool
+dtls_MoveUnackedStartForward(DTLSHandshakeRecordEntry *entry, PRUint32 *start)
+{
+ /* This entry starts too late. */
+ if (*start < entry->offset) {
+ return PR_FALSE;
+ }
+ /* This entry ends too early. */
+ if (*start >= entry->offset + entry->length) {
+ return PR_FALSE;
+ }
+ *start = entry->offset + entry->length;
+ return PR_TRUE;
+}
+
+/* Take a range ending at |*end| and move that end backwards based on the
+ * contents of the acknowedgement in |entry|. Only move if the acknowledged
+ * range overlaps |*end|. Return PR_TRUE if it moves. */
+static PRBool
+dtls_MoveUnackedEndBackward(DTLSHandshakeRecordEntry *entry, PRUint32 *end)
+{
+ /* This entry ends too early. */
+ if (*end > entry->offset + entry->length) {
+ return PR_FALSE;
+ }
+ /* This entry starts too late. */
+ if (*end <= entry->offset) {
+ return PR_FALSE;
+ }
+ *end = entry->offset;
+ return PR_TRUE;
+}
+
+/* Get the next contiguous range of unacknowledged bytes from the handshake
+ * message identified by |msgSeq|. The search starts at the offset in |offset|.
+ * |len| contains the full length of the message.
+ *
+ * Returns PR_TRUE if there is an unacknowledged range. In this case, values at
+ * |start| and |end| are modified to contain the range.
+ *
+ * Returns PR_FALSE if the message is entirely acknowledged from |offset|
+ * onwards.
+ */
+PRBool
+dtls_NextUnackedRange(sslSocket *ss, PRUint16 msgSeq, PRUint32 offset,
+ PRUint32 len, PRUint32 *startOut, PRUint32 *endOut)
+{
+ PRCList *cur_p;
+ PRBool done = PR_FALSE;
+ DTLSHandshakeRecordEntry *entry;
+ PRUint32 start;
+ PRUint32 end;
+
+ PORT_Assert(IS_DTLS(ss));
+
+ *startOut = offset;
+ *endOut = len;
+ if (!tls13_MaybeTls13(ss)) {
+ return PR_TRUE;
+ }
+
+ /* The message is empty. Use a simple search. */
+ if (!len) {
+ PORT_Assert(!offset);
+ return !dtls_IsEmptyMessageAcknowledged(ss, msgSeq, offset);
+ }
+
+ /* This iterates multiple times over the acknowledgments and only terminates
+ * when an entire iteration happens without start or end moving. If that
+ * happens without start and end crossing each other, then there is a range
+ * of unacknowledged data. If they meet, then the message is fully
+ * acknowledged. */
+ start = offset;
+ end = len;
+ while (!done) {
+ done = PR_TRUE;
+ for (cur_p = PR_LIST_HEAD(&ss->ssl3.hs.dtlsSentHandshake);
+ cur_p != &ss->ssl3.hs.dtlsSentHandshake;
+ cur_p = PR_NEXT_LINK(cur_p)) {
+ entry = (DTLSHandshakeRecordEntry *)cur_p;
+ if (!entry->acked || msgSeq != entry->messageSeq) {
+ continue;
+ }
+
+ if (dtls_MoveUnackedStartForward(entry, &start) ||
+ dtls_MoveUnackedEndBackward(entry, &end)) {
+ if (start >= end) {
+ /* The message is all acknowledged. */
+ return PR_FALSE;
+ }
+ /* Start over again and keep going until we don't move either
+ * start or end. */
+ done = PR_FALSE;
+ break;
+ }
+ }
+ }
+ PORT_Assert(start < end);
+
+ *startOut = start;
+ *endOut = end;
+ return PR_TRUE;
+}
+
+SECStatus
+dtls13_SetupAcks(sslSocket *ss)
+{
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ if (ss->ssl3.hs.endOfFlight) {
+ dtls_CancelTimer(ss, ss->ssl3.hs.ackTimer);
+
+ if (ss->ssl3.hs.ws == idle_handshake && ss->sec.isServer) {
+ SSL_TRC(10, ("%d: SSL3[%d]: dtls_HandleHandshake, sending ACK",
+ SSL_GETPID(), ss->fd));
+ return dtls13_SendAck(ss);
+ }
+ return SECSuccess;
+ }
+
+ /* We need to send an ACK. */
+ if (!ss->ssl3.hs.ackTimer->cb) {
+ /* We're not armed, so arm. */
+ SSL_TRC(10, ("%d: SSL3[%d]: dtls_HandleHandshake, arming ack timer",
+ SSL_GETPID(), ss->fd));
+ return dtls_StartTimer(ss, ss->ssl3.hs.ackTimer,
+ DTLS_RETRANSMIT_INITIAL_MS / 4,
+ dtls13_SendAckCb);
+ }
+ /* The ack timer is already armed, so just return. */
+ return SECSuccess;
+}
+
+/*
+ * Special case processing for out-of-epoch records.
+ * This can only handle ACKs for now and everything else generates
+ * an error. In future, may also handle KeyUpdate.
+ *
+ * The error checking here is as follows:
+ *
+ * - If it's not encrypted, out of epoch stuff is just discarded.
+ * - If it's encrypted, out of epoch stuff causes an error.
+ */
+SECStatus
+dtls13_HandleOutOfEpochRecord(sslSocket *ss, const ssl3CipherSpec *spec,
+ SSLContentType rType,
+ sslBuffer *databuf)
+{
+ SECStatus rv;
+ sslBuffer buf = *databuf;
+
+ databuf->len = 0; /* Discard data whatever happens. */
+ PORT_Assert(IS_DTLS(ss));
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ /* Can't happen, but double check. */
+ if (!IS_DTLS(ss) || (ss->version < SSL_LIBRARY_VERSION_TLS_1_3)) {
+ tls13_FatalError(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ SSL_TRC(10, ("%d: DTLS13[%d]: handle out of epoch record: type=%d", SSL_GETPID(),
+ ss->fd, rType));
+
+ if (rType == ssl_ct_ack) {
+ ssl_GetSSL3HandshakeLock(ss);
+ rv = dtls13_HandleAck(ss, &buf);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ PORT_Assert(databuf->len == 0);
+ return rv;
+ }
+
+ switch (spec->epoch) {
+ case TrafficKeyClearText:
+ /* Drop. */
+ return SECSuccess;
+
+ case TrafficKeyHandshake:
+ /* Drop out of order handshake messages, but if we are the
+ * server, we might have processed the client's Finished and
+ * moved on to application data keys, but the client has
+ * retransmitted Finished (e.g., because our ACK got lost.)
+ * We just retransmit the ACK to let the client complete. */
+ if (rType == ssl_ct_handshake) {
+ if ((ss->sec.isServer) &&
+ (ss->ssl3.hs.ws == idle_handshake)) {
+ PORT_Assert(dtls_TimerActive(ss, ss->ssl3.hs.hdTimer));
+ return dtls13_SendAck(ss);
+ }
+ return SECSuccess;
+ }
+
+ /* This isn't a handshake record, so shouldn't be encrypted
+ * under the handshake key. */
+ break;
+
+ default:
+ /* Any other epoch is forbidden. */
+ break;
+ }
+
+ SSL_TRC(10, ("%d: SSL3[%d]: unexpected out of epoch record type %d", SSL_GETPID(),
+ ss->fd, rType));
+
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
+ return SECFailure;
+}
+
+SECStatus
+dtls13_HandleAck(sslSocket *ss, sslBuffer *databuf)
+{
+ PRUint8 *b = databuf->buf;
+ PRUint32 l = databuf->len;
+ unsigned int length;
+ SECStatus rv;
+
+ /* Ensure we don't loop. */
+ databuf->len = 0;
+
+ PORT_Assert(IS_DTLS(ss));
+ if (!tls13_MaybeTls13(ss)) {
+ tls13_FatalError(ss, SSL_ERROR_RX_UNKNOWN_RECORD_TYPE, illegal_parameter);
+ return SECFailure;
+ }
+
+ SSL_TRC(10, ("%d: SSL3[%d]: Handling ACK", SSL_GETPID(), ss->fd));
+ rv = ssl3_ConsumeHandshakeNumber(ss, &length, 2, &b, &l);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (length != l) {
+ goto loser;
+ }
+
+ while (l > 0) {
+ PRUint64 seq;
+ PRCList *cursor;
+
+ rv = ssl3_ConsumeHandshakeNumber64(ss, &seq, 8, &b, &l);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ for (cursor = PR_LIST_HEAD(&ss->ssl3.hs.dtlsSentHandshake);
+ cursor != &ss->ssl3.hs.dtlsSentHandshake;
+ cursor = PR_NEXT_LINK(cursor)) {
+ DTLSHandshakeRecordEntry *entry = (DTLSHandshakeRecordEntry *)cursor;
+
+ if (entry->record == seq) {
+ SSL_TRC(10, (
+ "%d: SSL3[%d]: Marking record=%llx message %d offset %d length=%d as ACKed",
+ SSL_GETPID(), ss->fd,
+ seq, entry->messageSeq, entry->offset, entry->length));
+ entry->acked = PR_TRUE;
+ }
+ }
+ }
+
+ /* Try to flush. */
+ rv = dtls_TransmitMessageFlight(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Reset the retransmit timer. */
+ if (ss->ssl3.hs.rtTimer->cb) {
+ (void)dtls_RestartTimer(ss, ss->ssl3.hs.rtTimer);
+ }
+
+ /* If there are no more messages to send, cleanup. */
+ if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.lastMessageFlight)) {
+ SSL_TRC(10, ("%d: SSL3[%d]: No more unacked handshake messages",
+ SSL_GETPID(), ss->fd));
+
+ dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
+ ssl_ClearPRCList(&ss->ssl3.hs.dtlsSentHandshake, NULL);
+ /* If the handshake is finished, and we're the client then
+ * also clean up the handshake read cipher spec. Any ACKs
+ * we receive will be with the application data cipher spec.
+ * The server needs to keep the handshake cipher spec around
+ * for the holddown period to process retransmitted Finisheds.
+ */
+ if (!ss->sec.isServer && (ss->ssl3.hs.ws == idle_handshake)) {
+ ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
+ TrafficKeyHandshake);
+ }
+ }
+ return SECSuccess;
+
+loser:
+ /* Due to bug 1829391 we may incorrectly send an alert rather than
+ * ignore an invalid record here. */
+ SSL_TRC(11, ("%d: SSL3[%d]: Error processing DTLS1.3 ACK.",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_DTLS_ACK);
+ return SECFailure;
+}
+
+/* Clean up the read timer for the handshake cipher suites on the
+ * server.
+ *
+ * In DTLS 1.3, the client speaks last (Finished), and will retransmit
+ * until the server ACKs that message (using application data cipher
+ * suites). I.e.,
+ *
+ * - The client uses the retransmit timer and retransmits using the
+ * saved write handshake cipher suite.
+ * - The server keeps the saved read handshake cipher suite around
+ * for the holddown period in case it needs to read the Finished.
+ *
+ * After the holddown period, the server assumes the client is happy
+ * and discards the handshake read cipher suite.
+ */
+void
+dtls13_HolddownTimerCb(sslSocket *ss)
+{
+ SSL_TRC(10, ("%d: SSL3[%d]: holddown timer fired",
+ SSL_GETPID(), ss->fd));
+ ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyHandshake);
+ ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL);
+}
+
+SECStatus
+dtls13_MaskSequenceNumber(sslSocket *ss, ssl3CipherSpec *spec,
+ PRUint8 *hdr, PRUint8 *cipherText, PRUint32 cipherTextLen)
+{
+ PORT_Assert(IS_DTLS(ss));
+ if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ if (spec->maskContext) {
+#ifdef UNSAFE_FUZZER_MODE
+ /* Use a null mask. */
+ PRUint8 mask[2] = { 0 };
+#else
+ /* "This procedure requires the ciphertext length be at least 16 bytes.
+ * Receivers MUST reject shorter records as if they had failed
+ * deprotection, as described in Section 4.5.2." */
+ if (cipherTextLen < 16) {
+ PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+ return SECFailure;
+ }
+
+ PRUint8 mask[2];
+ SECStatus rv = ssl_CreateMaskInner(spec->maskContext, cipherText, cipherTextLen, mask, sizeof(mask));
+
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+ return SECFailure;
+ }
+#endif
+
+ hdr[1] ^= mask[0];
+ if (hdr[0] & 0x08) {
+ hdr[2] ^= mask[1];
+ }
+ }
+ return SECSuccess;
+}
+
+CK_MECHANISM_TYPE
+tls13_SequenceNumberEncryptionMechanism(SSLCipherAlgorithm bulkAlgorithm)
+{
+ switch (bulkAlgorithm) {
+ case ssl_calg_aes_gcm:
+ return CKM_AES_ECB;
+ case ssl_calg_chacha20:
+ return CKM_NSS_CHACHA20_CTR;
+ default:
+ PORT_Assert(PR_FALSE);
+ }
+ return CKM_INVALID_MECHANISM;
+}
diff --git a/security/nss/lib/ssl/dtls13con.h b/security/nss/lib/ssl/dtls13con.h
new file mode 100644
index 0000000000..bfe8d40204
--- /dev/null
+++ b/security/nss/lib/ssl/dtls13con.h
@@ -0,0 +1,38 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __dtls13con_h_
+#define __dtls13con_h_
+
+SECStatus dtls13_InsertCipherTextHeader(const sslSocket *ss,
+ const ssl3CipherSpec *cwSpec,
+ sslBuffer *wrBuf,
+ PRBool *needsLength);
+SECStatus dtls13_RememberFragment(sslSocket *ss, PRCList *list,
+ PRUint32 sequence, PRUint32 offset,
+ PRUint32 length, DTLSEpoch epoch,
+ sslSequenceNumber record);
+PRBool dtls_NextUnackedRange(sslSocket *ss, PRUint16 msgSeq, PRUint32 offset,
+ PRUint32 len, PRUint32 *startOut, PRUint32 *endOut);
+SECStatus dtls13_SetupAcks(sslSocket *ss);
+SECStatus dtls13_HandleOutOfEpochRecord(sslSocket *ss, const ssl3CipherSpec *spec,
+ SSLContentType rType,
+ sslBuffer *databuf);
+SECStatus dtls13_HandleAck(sslSocket *ss, sslBuffer *databuf);
+
+SECStatus dtls13_SendAck(sslSocket *ss);
+void dtls13_SendAckCb(sslSocket *ss);
+void dtls13_HolddownTimerCb(sslSocket *ss);
+void dtls_ReceivedFirstMessageInFlight(sslSocket *ss);
+SECStatus dtls13_MaskSequenceNumber(sslSocket *ss, ssl3CipherSpec *spec,
+ PRUint8 *hdr, PRUint8 *cipherText, PRUint32 cipherTextLen);
+PRBool dtls13_AeadLimitReached(ssl3CipherSpec *spec);
+
+CK_MECHANISM_TYPE tls13_SequenceNumberEncryptionMechanism(SSLCipherAlgorithm bulkAlgorithm);
+
+#endif
diff --git a/security/nss/lib/ssl/dtlscon.c b/security/nss/lib/ssl/dtlscon.c
new file mode 100644
index 0000000000..a4a7c998c4
--- /dev/null
+++ b/security/nss/lib/ssl/dtlscon.c
@@ -0,0 +1,1474 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * DTLS Protocol
+ */
+
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "dtls13con.h"
+
+#ifndef PR_ARRAY_SIZE
+#define PR_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
+#endif
+
+static SECStatus dtls_StartRetransmitTimer(sslSocket *ss);
+static void dtls_RetransmitTimerExpiredCb(sslSocket *ss);
+static SECStatus dtls_SendSavedWriteData(sslSocket *ss);
+static void dtls_FinishedTimerCb(sslSocket *ss);
+static void dtls_CancelAllTimers(sslSocket *ss);
+
+/* -28 adjusts for the IP/UDP header */
+static const PRUint16 COMMON_MTU_VALUES[] = {
+ 1500 - 28, /* Ethernet MTU */
+ 1280 - 28, /* IPv6 minimum MTU */
+ 576 - 28, /* Common assumption */
+ 256 - 28 /* We're in serious trouble now */
+};
+
+#define DTLS_COOKIE_BYTES 32
+/* Maximum DTLS expansion = header + IV + max CBC padding +
+ * maximum MAC. */
+#define DTLS_MAX_EXPANSION (DTLS_RECORD_HEADER_LENGTH + 16 + 16 + 32)
+
+/* List copied from ssl3con.c:cipherSuites */
+static const ssl3CipherSuite nonDTLSSuites[] = {
+ TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
+ TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+ TLS_DHE_DSS_WITH_RC4_128_SHA,
+ TLS_ECDH_RSA_WITH_RC4_128_SHA,
+ TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ TLS_RSA_WITH_RC4_128_MD5,
+ TLS_RSA_WITH_RC4_128_SHA,
+ 0 /* End of list marker */
+};
+
+/* Map back and forth between TLS and DTLS versions in wire format.
+ * Mapping table is:
+ *
+ * TLS DTLS
+ * 1.1 (0302) 1.0 (feff)
+ * 1.2 (0303) 1.2 (fefd)
+ * 1.3 (0304) 1.3 (0304)
+ */
+SSL3ProtocolVersion
+dtls_TLSVersionToDTLSVersion(SSL3ProtocolVersion tlsv)
+{
+ if (tlsv == SSL_LIBRARY_VERSION_TLS_1_1) {
+ return SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
+ }
+ if (tlsv == SSL_LIBRARY_VERSION_TLS_1_2) {
+ return SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
+ }
+ if (tlsv == SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SSL_LIBRARY_VERSION_DTLS_1_3_WIRE;
+ }
+
+ /* Anything else is an error, so return
+ * the invalid version 0xffff. */
+ return 0xffff;
+}
+
+/* Map known DTLS versions to known TLS versions.
+ * - Invalid versions (< 1.0) return a version of 0
+ * - Versions > known return a version one higher than we know of
+ * to accomodate a theoretically newer version */
+SSL3ProtocolVersion
+dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv)
+{
+ if (MSB(dtlsv) == 0xff) {
+ return 0;
+ }
+
+ if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_0_WIRE) {
+ return SSL_LIBRARY_VERSION_TLS_1_1;
+ }
+ /* Handle the skipped version of DTLS 1.1 by returning
+ * an error. */
+ if (dtlsv == ((~0x0101) & 0xffff)) {
+ return 0;
+ }
+ if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_2_WIRE) {
+ return SSL_LIBRARY_VERSION_TLS_1_2;
+ }
+ if (dtlsv == SSL_LIBRARY_VERSION_DTLS_1_3_WIRE) {
+ return SSL_LIBRARY_VERSION_TLS_1_3;
+ }
+
+ /* Return a fictional higher version than we know of */
+ return SSL_LIBRARY_VERSION_MAX_SUPPORTED + 1;
+}
+
+/* On this socket, Disable non-DTLS cipher suites in the argument's list */
+SECStatus
+ssl3_DisableNonDTLSSuites(sslSocket *ss)
+{
+ const ssl3CipherSuite *suite;
+
+ for (suite = nonDTLSSuites; *suite; ++suite) {
+ PORT_CheckSuccess(ssl3_CipherPrefSet(ss, *suite, PR_FALSE));
+ }
+ return SECSuccess;
+}
+
+/* Allocate a DTLSQueuedMessage.
+ *
+ * Called from dtls_QueueMessage()
+ */
+static DTLSQueuedMessage *
+dtls_AllocQueuedMessage(ssl3CipherSpec *cwSpec, SSLContentType ct,
+ const unsigned char *data, PRUint32 len)
+{
+ DTLSQueuedMessage *msg;
+
+ msg = PORT_ZNew(DTLSQueuedMessage);
+ if (!msg)
+ return NULL;
+
+ msg->data = PORT_Alloc(len);
+ if (!msg->data) {
+ PORT_Free(msg);
+ return NULL;
+ }
+ PORT_Memcpy(msg->data, data, len);
+
+ msg->len = len;
+ msg->cwSpec = cwSpec;
+ msg->type = ct;
+ /* Safe if we are < 1.3, since the refct is
+ * already very high. */
+ ssl_CipherSpecAddRef(cwSpec);
+
+ return msg;
+}
+
+/*
+ * Free a handshake message
+ *
+ * Called from dtls_FreeHandshakeMessages()
+ */
+void
+dtls_FreeHandshakeMessage(DTLSQueuedMessage *msg)
+{
+ if (!msg)
+ return;
+
+ /* Safe if we are < 1.3, since the refct is
+ * already very high. */
+ ssl_CipherSpecRelease(msg->cwSpec);
+ PORT_ZFree(msg->data, msg->len);
+ PORT_Free(msg);
+}
+
+/*
+ * Free a list of handshake messages
+ *
+ * Called from:
+ * dtls_HandleHandshake()
+ * ssl3_DestroySSL3Info()
+ */
+void
+dtls_FreeHandshakeMessages(PRCList *list)
+{
+ PRCList *cur_p;
+
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ cur_p = PR_LIST_TAIL(list);
+ PR_REMOVE_LINK(cur_p);
+ dtls_FreeHandshakeMessage((DTLSQueuedMessage *)cur_p);
+ }
+}
+
+/* Called by dtls_HandleHandshake() and dtls_MaybeRetransmitHandshake() if a
+ * handshake message retransmission is detected. */
+static SECStatus
+dtls_RetransmitDetected(sslSocket *ss)
+{
+ dtlsTimer *timer = ss->ssl3.hs.rtTimer;
+ SECStatus rv = SECSuccess;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (timer->cb == dtls_RetransmitTimerExpiredCb) {
+ /* Check to see if we retransmitted recently. If so,
+ * suppress the triggered retransmit. This avoids
+ * retransmit wars after packet loss.
+ * This is not in RFC 5346 but it should be.
+ */
+ if ((PR_IntervalNow() - timer->started) >
+ (timer->timeout / 4)) {
+ SSL_TRC(30,
+ ("%d: SSL3[%d]: Shortcutting retransmit timer",
+ SSL_GETPID(), ss->fd));
+
+ /* Cancel the timer and call the CB,
+ * which re-arms the timer */
+ dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
+ dtls_RetransmitTimerExpiredCb(ss);
+ } else {
+ SSL_TRC(30,
+ ("%d: SSL3[%d]: Ignoring retransmission: "
+ "last retransmission %dms ago, suppressed for %dms",
+ SSL_GETPID(), ss->fd,
+ PR_IntervalNow() - timer->started,
+ timer->timeout / 4));
+ }
+
+ } else if (timer->cb == dtls_FinishedTimerCb) {
+ SSL_TRC(30, ("%d: SSL3[%d]: Retransmit detected in holddown",
+ SSL_GETPID(), ss->fd));
+ /* Retransmit the messages and re-arm the timer
+ * Note that we are not backing off the timer here.
+ * The spec isn't clear and my reasoning is that this
+ * may be a re-ordered packet rather than slowness,
+ * so let's be aggressive. */
+ dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
+ rv = dtls_TransmitMessageFlight(ss);
+ if (rv == SECSuccess) {
+ rv = dtls_StartHolddownTimer(ss);
+ }
+
+ } else {
+ PORT_Assert(timer->cb == NULL);
+ /* ... and ignore it. */
+ }
+ return rv;
+}
+
+static SECStatus
+dtls_HandleHandshakeMessage(sslSocket *ss, PRUint8 *data, PRBool last)
+{
+ ss->ssl3.hs.recvdHighWater = -1;
+
+ return ssl3_HandleHandshakeMessage(ss, data, ss->ssl3.hs.msg_len,
+ last);
+}
+
+/* Called only from ssl3_HandleRecord, for each (deciphered) DTLS record.
+ * origBuf is the decrypted ssl record content and is expected to contain
+ * complete handshake records
+ * Caller must hold the handshake and RecvBuf locks.
+ *
+ * Note that this code uses msg_len for two purposes:
+ *
+ * (1) To pass the length to ssl3_HandleHandshakeMessage()
+ * (2) To carry the length of a message currently being reassembled
+ *
+ * However, unlike ssl3_HandleHandshake(), it is not used to carry
+ * the state of reassembly (i.e., whether one is in progress). That
+ * is carried in recvdHighWater and recvdFragments.
+ */
+#define OFFSET_BYTE(o) (o / 8)
+#define OFFSET_MASK(o) (1 << (o % 8))
+
+SECStatus
+dtls_HandleHandshake(sslSocket *ss, DTLSEpoch epoch, sslSequenceNumber seqNum,
+ sslBuffer *origBuf)
+{
+ sslBuffer buf = *origBuf;
+ SECStatus rv = SECSuccess;
+ PRBool discarded = PR_FALSE;
+
+ ss->ssl3.hs.endOfFlight = PR_FALSE;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ while (buf.len > 0) {
+ PRUint8 type;
+ PRUint32 message_length;
+ PRUint16 message_seq;
+ PRUint32 fragment_offset;
+ PRUint32 fragment_length;
+ PRUint32 offset;
+
+ if (buf.len < 12) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ /* Parse the header */
+ type = buf.buf[0];
+ message_length = (buf.buf[1] << 16) | (buf.buf[2] << 8) | buf.buf[3];
+ message_seq = (buf.buf[4] << 8) | buf.buf[5];
+ fragment_offset = (buf.buf[6] << 16) | (buf.buf[7] << 8) | buf.buf[8];
+ fragment_length = (buf.buf[9] << 16) | (buf.buf[10] << 8) | buf.buf[11];
+
+#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
+ if (message_length > MAX_HANDSHAKE_MSG_LEN) {
+ (void)ssl3_DecodeError(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ rv = SECFailure;
+ goto loser;
+ }
+#undef MAX_HANDSHAKE_MSG_LEN
+
+ buf.buf += 12;
+ buf.len -= 12;
+
+ /* This fragment must be complete */
+ if (buf.len < fragment_length) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ /* Sanity check the packet contents */
+ if ((fragment_length + fragment_offset) > message_length) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ /* If we're a server and we receive what appears to be a retried
+ * ClientHello, and we are expecting a ClientHello, move the receive
+ * sequence number forward. This allows for a retried ClientHello if we
+ * send a stateless HelloRetryRequest. */
+ if (message_seq > ss->ssl3.hs.recvMessageSeq &&
+ message_seq == 1 &&
+ fragment_offset == 0 &&
+ ss->ssl3.hs.ws == wait_client_hello &&
+ (SSLHandshakeType)type == ssl_hs_client_hello) {
+ SSL_TRC(5, ("%d: DTLS[%d]: Received apparent 2nd ClientHello",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.recvMessageSeq = 1;
+ ss->ssl3.hs.helloRetry = PR_TRUE;
+ }
+
+ /* There are three ways we could not be ready for this packet.
+ *
+ * 1. It's a partial next message.
+ * 2. It's a partial or complete message beyond the next
+ * 3. It's a message we've already seen
+ *
+ * If it's the complete next message we accept it right away.
+ * This is the common case for short messages
+ */
+ if ((message_seq == ss->ssl3.hs.recvMessageSeq) &&
+ (fragment_offset == 0) &&
+ (fragment_length == message_length)) {
+ /* Complete next message. Process immediately */
+ ss->ssl3.hs.msg_type = (SSLHandshakeType)type;
+ ss->ssl3.hs.msg_len = message_length;
+
+ rv = dtls_HandleHandshakeMessage(ss, buf.buf,
+ buf.len == fragment_length);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ if (message_seq < ss->ssl3.hs.recvMessageSeq) {
+ /* Case 3: we do an immediate retransmit if we're
+ * in a waiting state. */
+ rv = dtls_RetransmitDetected(ss);
+ goto loser;
+ } else if (message_seq > ss->ssl3.hs.recvMessageSeq) {
+ /* Case 2
+ *
+ * Ignore this message. This means we don't handle out of
+ * order complete messages that well, but we're still
+ * compliant and this probably does not happen often
+ *
+ * XXX OK for now. Maybe do something smarter at some point?
+ */
+ SSL_TRC(10, ("%d: SSL3[%d]: dtls_HandleHandshake, discarding handshake message",
+ SSL_GETPID(), ss->fd));
+ discarded = PR_TRUE;
+ } else {
+ PRInt32 end = fragment_offset + fragment_length;
+
+ /* Case 1
+ *
+ * Buffer the fragment for reassembly
+ */
+ /* Make room for the message */
+ if (ss->ssl3.hs.recvdHighWater == -1) {
+ PRUint32 map_length = OFFSET_BYTE(message_length) + 1;
+
+ rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, message_length);
+ if (rv != SECSuccess)
+ goto loser;
+ /* Make room for the fragment map */
+ rv = sslBuffer_Grow(&ss->ssl3.hs.recvdFragments,
+ map_length);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Reset the reassembly map */
+ ss->ssl3.hs.recvdHighWater = 0;
+ PORT_Memset(ss->ssl3.hs.recvdFragments.buf, 0,
+ ss->ssl3.hs.recvdFragments.space);
+ ss->ssl3.hs.msg_type = (SSLHandshakeType)type;
+ ss->ssl3.hs.msg_len = message_length;
+ }
+
+ /* If we have a message length mismatch, abandon the reassembly
+ * in progress and hope that the next retransmit will give us
+ * something sane
+ */
+ if (message_length != ss->ssl3.hs.msg_len) {
+ ss->ssl3.hs.recvdHighWater = -1;
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ /* Now copy this fragment into the buffer. */
+ if (end > ss->ssl3.hs.recvdHighWater) {
+ PORT_Memcpy(ss->ssl3.hs.msg_body.buf + fragment_offset,
+ buf.buf, fragment_length);
+ }
+
+ /* This logic is a bit tricky. We have two values for
+ * reassembly state:
+ *
+ * - recvdHighWater contains the highest contiguous number of
+ * bytes received
+ * - recvdFragments contains a bitmask of packets received
+ * above recvdHighWater
+ *
+ * This avoids having to fill in the bitmask in the common
+ * case of adjacent fragments received in sequence
+ */
+ if (fragment_offset <= (unsigned int)ss->ssl3.hs.recvdHighWater) {
+ /* Either this is the adjacent fragment or an overlapping
+ * fragment */
+ if (end > ss->ssl3.hs.recvdHighWater) {
+ ss->ssl3.hs.recvdHighWater = end;
+ }
+ } else {
+ for (offset = fragment_offset; offset < end; offset++) {
+ ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] |=
+ OFFSET_MASK(offset);
+ }
+ }
+
+ /* Now figure out the new high water mark if appropriate */
+ for (offset = ss->ssl3.hs.recvdHighWater;
+ offset < ss->ssl3.hs.msg_len; offset++) {
+ /* Note that this loop is not efficient, since it counts
+ * bit by bit. If we have a lot of out-of-order packets,
+ * we should optimize this */
+ if (ss->ssl3.hs.recvdFragments.buf[OFFSET_BYTE(offset)] &
+ OFFSET_MASK(offset)) {
+ ss->ssl3.hs.recvdHighWater++;
+ } else {
+ break;
+ }
+ }
+
+ /* If we have all the bytes, then we are good to go */
+ if (ss->ssl3.hs.recvdHighWater == ss->ssl3.hs.msg_len) {
+ rv = dtls_HandleHandshakeMessage(ss, ss->ssl3.hs.msg_body.buf,
+ buf.len == fragment_length);
+
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ }
+ }
+
+ buf.buf += fragment_length;
+ buf.len -= fragment_length;
+ }
+
+ // This should never happen, but belt and suspenders.
+ if (rv != SECSuccess) {
+ PORT_Assert(0);
+ goto loser;
+ }
+
+ /* If we processed all the fragments in this message, then mark it as remembered.
+ * TODO(ekr@rtfm.com): Store out of order messages for DTLS 1.3 so ACKs work
+ * better. Bug 1392620.*/
+ if (!discarded && tls13_MaybeTls13(ss)) {
+ rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsRcvdHandshake,
+ 0, 0, 0, epoch, seqNum);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = dtls13_SetupAcks(ss);
+
+loser:
+ origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
+ return rv;
+}
+
+/* Enqueue a message (either handshake or CCS)
+ *
+ * Called from:
+ * dtls_StageHandshakeMessage()
+ * ssl3_SendChangeCipherSpecs()
+ */
+SECStatus
+dtls_QueueMessage(sslSocket *ss, SSLContentType ct,
+ const PRUint8 *pIn, PRInt32 nIn)
+{
+ SECStatus rv = SECSuccess;
+ DTLSQueuedMessage *msg = NULL;
+ ssl3CipherSpec *spec;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ spec = ss->ssl3.cwSpec;
+ msg = dtls_AllocQueuedMessage(spec, ct, pIn, nIn);
+
+ if (!msg) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ rv = SECFailure;
+ } else {
+ PR_APPEND_LINK(&msg->link, &ss->ssl3.hs.lastMessageFlight);
+ }
+
+ return rv;
+}
+
+/* Add DTLS handshake message to the pending queue
+ * Empty the sendBuf buffer.
+ * Always set sendBuf.len to 0, even when returning SECFailure.
+ *
+ * Called from:
+ * ssl3_AppendHandshakeHeader()
+ * dtls_FlushHandshake()
+ */
+SECStatus
+dtls_StageHandshakeMessage(sslSocket *ss)
+{
+ SECStatus rv = SECSuccess;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ /* This function is sometimes called when no data is actually to
+ * be staged, so just return SECSuccess. */
+ if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
+ return rv;
+
+ rv = dtls_QueueMessage(ss, ssl_ct_handshake,
+ ss->sec.ci.sendBuf.buf, ss->sec.ci.sendBuf.len);
+
+ /* Whether we succeeded or failed, toss the old handshake data. */
+ ss->sec.ci.sendBuf.len = 0;
+ return rv;
+}
+
+/* Enqueue the handshake message in sendBuf (if any) and then
+ * transmit the resulting flight of handshake messages.
+ *
+ * Called from:
+ * ssl3_FlushHandshake()
+ */
+SECStatus
+dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
+{
+ SECStatus rv = SECSuccess;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ rv = dtls_StageHandshakeMessage(ss);
+ if (rv != SECSuccess)
+ return rv;
+
+ if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
+ rv = dtls_TransmitMessageFlight(ss);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ if (!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)) {
+ rv = dtls_StartRetransmitTimer(ss);
+ } else {
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+ }
+ }
+
+ return rv;
+}
+
+/* The callback for when the retransmit timer expires
+ *
+ * Called from:
+ * dtls_CheckTimer()
+ * dtls_HandleHandshake()
+ */
+static void
+dtls_RetransmitTimerExpiredCb(sslSocket *ss)
+{
+ SECStatus rv;
+ dtlsTimer *timer = ss->ssl3.hs.rtTimer;
+ ss->ssl3.hs.rtRetries++;
+
+ if (!(ss->ssl3.hs.rtRetries % 3)) {
+ /* If one of the messages was potentially greater than > MTU,
+ * then downgrade. Do this every time we have retransmitted a
+ * message twice, per RFC 6347 Sec. 4.1.1 */
+ dtls_SetMTU(ss, ss->ssl3.hs.maxMessageSent - 1);
+ }
+
+ rv = dtls_TransmitMessageFlight(ss);
+ if (rv == SECSuccess) {
+ /* Re-arm the timer */
+ timer->timeout *= 2;
+ if (timer->timeout > DTLS_RETRANSMIT_MAX_MS) {
+ timer->timeout = DTLS_RETRANSMIT_MAX_MS;
+ }
+
+ timer->started = PR_IntervalNow();
+ timer->cb = dtls_RetransmitTimerExpiredCb;
+
+ SSL_TRC(30,
+ ("%d: SSL3[%d]: Retransmit #%d, next in %d",
+ SSL_GETPID(), ss->fd,
+ ss->ssl3.hs.rtRetries, timer->timeout));
+ }
+ /* else: OK for now. In future maybe signal the stack that we couldn't
+ * transmit. For now, let the read handle any real network errors */
+}
+
+#define DTLS_HS_HDR_LEN 12
+#define DTLS_MIN_FRAGMENT (DTLS_HS_HDR_LEN + 1 + DTLS_MAX_EXPANSION)
+
+/* Encrypt and encode a handshake message fragment. Flush the data out to the
+ * network if there is insufficient space for any fragment. */
+static SECStatus
+dtls_SendFragment(sslSocket *ss, DTLSQueuedMessage *msg, PRUint8 *data,
+ unsigned int len)
+{
+ PRInt32 sent;
+ SECStatus rv;
+
+ PRINT_BUF(40, (ss, "dtls_SendFragment", data, len));
+ sent = ssl3_SendRecord(ss, msg->cwSpec, msg->type, data, len,
+ ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+ if (sent != len) {
+ if (sent != -1) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ }
+ return SECFailure;
+ }
+
+ /* If another fragment won't fit, flush. */
+ if (ss->ssl3.mtu < ss->pendingBuf.len + DTLS_MIN_FRAGMENT) {
+ SSL_TRC(20, ("%d: DTLS[%d]: dtls_SendFragment: flush",
+ SSL_GETPID(), ss->fd));
+ rv = dtls_SendSavedWriteData(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ return SECSuccess;
+}
+
+/* Fragment a handshake message into multiple records and send them. */
+static SECStatus
+dtls_FragmentHandshake(sslSocket *ss, DTLSQueuedMessage *msg)
+{
+ PRBool fragmentWritten = PR_FALSE;
+ PRUint16 msgSeq;
+ PRUint8 *fragment;
+ PRUint32 fragmentOffset = 0;
+ PRUint32 fragmentLen;
+ const PRUint8 *content = msg->data + DTLS_HS_HDR_LEN;
+ PRUint32 contentLen = msg->len - DTLS_HS_HDR_LEN;
+ SECStatus rv;
+
+ /* The headers consume 12 bytes so the smallest possible message (i.e., an
+ * empty one) is 12 bytes. */
+ PORT_Assert(msg->len >= DTLS_HS_HDR_LEN);
+
+ /* DTLS only supports fragmenting handshaking messages. */
+ PORT_Assert(msg->type == ssl_ct_handshake);
+
+ msgSeq = (msg->data[4] << 8) | msg->data[5];
+
+ /* do {} while() so that empty messages are sent at least once. */
+ do {
+ PRUint8 buf[DTLS_MAX_MTU]; /* >= than largest plausible MTU */
+ PRBool hasUnackedRange;
+ PRUint32 end;
+
+ hasUnackedRange = dtls_NextUnackedRange(ss, msgSeq,
+ fragmentOffset, contentLen,
+ &fragmentOffset, &end);
+ if (!hasUnackedRange) {
+ SSL_TRC(20, ("%d: SSL3[%d]: FragmentHandshake %d: all acknowledged",
+ SSL_GETPID(), ss->fd, msgSeq));
+ break;
+ }
+
+ SSL_TRC(20, ("%d: SSL3[%d]: FragmentHandshake %d: unacked=%u-%u",
+ SSL_GETPID(), ss->fd, msgSeq, fragmentOffset, end));
+
+ /* Cut down to the data we have available. */
+ PORT_Assert(fragmentOffset <= contentLen);
+ PORT_Assert(fragmentOffset <= end);
+ PORT_Assert(end <= contentLen);
+ fragmentLen = PR_MIN(end, contentLen) - fragmentOffset;
+
+ /* Limit further by the record size limit. Account for the header. */
+ fragmentLen = PR_MIN(fragmentLen,
+ msg->cwSpec->recordSizeLimit - DTLS_HS_HDR_LEN);
+
+ /* Reduce to the space remaining in the MTU. */
+ fragmentLen = PR_MIN(fragmentLen,
+ ss->ssl3.mtu - /* MTU estimate. */
+ ss->pendingBuf.len - /* Less any unsent records. */
+ DTLS_MAX_EXPANSION - /* Allow for expansion. */
+ DTLS_HS_HDR_LEN); /* And the handshake header. */
+ PORT_Assert(fragmentLen > 0 || fragmentOffset == 0);
+
+ /* Make totally sure that we will fit in the buffer. This should be
+ * impossible; DTLS_MAX_MTU should always be more than ss->ssl3.mtu. */
+ if (fragmentLen >= (DTLS_MAX_MTU - DTLS_HS_HDR_LEN)) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (fragmentLen == contentLen) {
+ fragment = msg->data;
+ } else {
+ sslBuffer tmp = SSL_BUFFER_FIXED(buf, sizeof(buf));
+
+ /* Construct an appropriate-sized fragment */
+ /* Type, length, sequence */
+ rv = sslBuffer_Append(&tmp, msg->data, 6);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* Offset. */
+ rv = sslBuffer_AppendNumber(&tmp, fragmentOffset, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* Length. */
+ rv = sslBuffer_AppendNumber(&tmp, fragmentLen, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* Data. */
+ rv = sslBuffer_Append(&tmp, content + fragmentOffset, fragmentLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ fragment = SSL_BUFFER_BASE(&tmp);
+ }
+
+ /* Record that we are sending first, because encrypting
+ * increments the sequence number. */
+ rv = dtls13_RememberFragment(ss, &ss->ssl3.hs.dtlsSentHandshake,
+ msgSeq, fragmentOffset, fragmentLen,
+ msg->cwSpec->epoch,
+ msg->cwSpec->nextSeqNum);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = dtls_SendFragment(ss, msg, fragment,
+ fragmentLen + DTLS_HS_HDR_LEN);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ fragmentWritten = PR_TRUE;
+ fragmentOffset += fragmentLen;
+ } while (fragmentOffset < contentLen);
+
+ if (!fragmentWritten) {
+ /* Nothing was written if we got here, so the whole message must have
+ * been acknowledged. Discard it. */
+ SSL_TRC(10, ("%d: SSL3[%d]: FragmentHandshake %d: removed",
+ SSL_GETPID(), ss->fd, msgSeq));
+ PR_REMOVE_LINK(&msg->link);
+ dtls_FreeHandshakeMessage(msg);
+ }
+
+ return SECSuccess;
+}
+
+/* Transmit a flight of handshake messages, stuffing them
+ * into as few records as seems reasonable.
+ *
+ * TODO: Space separate UDP packets out a little.
+ *
+ * Called from:
+ * dtls_FlushHandshake()
+ * dtls_RetransmitTimerExpiredCb()
+ */
+SECStatus
+dtls_TransmitMessageFlight(sslSocket *ss)
+{
+ SECStatus rv = SECSuccess;
+ PRCList *msg_p;
+
+ SSL_TRC(10, ("%d: SSL3[%d]: dtls_TransmitMessageFlight",
+ SSL_GETPID(), ss->fd));
+
+ ssl_GetXmitBufLock(ss);
+ ssl_GetSpecReadLock(ss);
+
+ /* DTLS does not buffer its handshake messages in ss->pendingBuf, but rather
+ * in the lastMessageFlight structure. This is just a sanity check that some
+ * programming error hasn't inadvertantly stuffed something in
+ * ss->pendingBuf. This function uses ss->pendingBuf temporarily and it
+ * needs to be empty to start.
+ */
+ PORT_Assert(!ss->pendingBuf.len);
+
+ for (msg_p = PR_LIST_HEAD(&ss->ssl3.hs.lastMessageFlight);
+ msg_p != &ss->ssl3.hs.lastMessageFlight;) {
+ DTLSQueuedMessage *msg = (DTLSQueuedMessage *)msg_p;
+
+ /* Move the pointer forward so that the functions below are free to
+ * remove messages from the list. */
+ msg_p = PR_NEXT_LINK(msg_p);
+
+ /* Note: This function fragments messages so that each record is close
+ * to full. This produces fewer records, but it means that messages can
+ * be quite fragmented. Adding an extra flush here would push new
+ * messages into new records and reduce fragmentation. */
+
+ if (msg->type == ssl_ct_handshake) {
+ rv = dtls_FragmentHandshake(ss, msg);
+ } else {
+ PORT_Assert(!tls13_MaybeTls13(ss));
+ rv = dtls_SendFragment(ss, msg, msg->data, msg->len);
+ }
+ if (rv != SECSuccess) {
+ break;
+ }
+ }
+
+ /* Finally, flush any data that wasn't flushed already. */
+ if (rv == SECSuccess) {
+ rv = dtls_SendSavedWriteData(ss);
+ }
+
+ /* Give up the locks */
+ ssl_ReleaseSpecReadLock(ss);
+ ssl_ReleaseXmitBufLock(ss);
+
+ return rv;
+}
+
+/* Flush the data in the pendingBuf and update the max message sent
+ * so we can adjust the MTU estimate if we need to.
+ * Wrapper for ssl_SendSavedWriteData.
+ *
+ * Called from dtls_TransmitMessageFlight()
+ */
+static SECStatus
+dtls_SendSavedWriteData(sslSocket *ss)
+{
+ PRInt32 sent;
+
+ sent = ssl_SendSavedWriteData(ss);
+ if (sent < 0)
+ return SECFailure;
+
+ /* We should always have complete writes b/c datagram sockets
+ * don't really block */
+ if (ss->pendingBuf.len > 0) {
+ ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
+ return SECFailure;
+ }
+
+ /* Update the largest message sent so we can adjust the MTU
+ * estimate if necessary */
+ if (sent > ss->ssl3.hs.maxMessageSent)
+ ss->ssl3.hs.maxMessageSent = sent;
+
+ return SECSuccess;
+}
+
+void
+dtls_InitTimers(sslSocket *ss)
+{
+ unsigned int i;
+ dtlsTimer **timers[PR_ARRAY_SIZE(ss->ssl3.hs.timers)] = {
+ &ss->ssl3.hs.rtTimer,
+ &ss->ssl3.hs.ackTimer,
+ &ss->ssl3.hs.hdTimer
+ };
+ static const char *timerLabels[] = {
+ "retransmit", "ack", "holddown"
+ };
+
+ PORT_Assert(PR_ARRAY_SIZE(timers) == PR_ARRAY_SIZE(timerLabels));
+ for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
+ *timers[i] = &ss->ssl3.hs.timers[i];
+ ss->ssl3.hs.timers[i].label = timerLabels[i];
+ }
+}
+
+SECStatus
+dtls_StartTimer(sslSocket *ss, dtlsTimer *timer, PRUint32 time, DTLSTimerCb cb)
+{
+ PORT_Assert(timer->cb == NULL);
+
+ SSL_TRC(10, ("%d: SSL3[%d]: %s dtls_StartTimer %s timeout=%d",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss), timer->label, time));
+
+ timer->started = PR_IntervalNow();
+ timer->timeout = time;
+ timer->cb = cb;
+ return SECSuccess;
+}
+
+SECStatus
+dtls_RestartTimer(sslSocket *ss, dtlsTimer *timer)
+{
+ timer->started = PR_IntervalNow();
+ return SECSuccess;
+}
+
+PRBool
+dtls_TimerActive(sslSocket *ss, dtlsTimer *timer)
+{
+ return timer->cb != NULL;
+}
+/* Start a timer for retransmission. */
+static SECStatus
+dtls_StartRetransmitTimer(sslSocket *ss)
+{
+ ss->ssl3.hs.rtRetries = 0;
+ return dtls_StartTimer(ss, ss->ssl3.hs.rtTimer,
+ DTLS_RETRANSMIT_INITIAL_MS,
+ dtls_RetransmitTimerExpiredCb);
+}
+
+/* Start a timer for holding an old cipher spec. */
+SECStatus
+dtls_StartHolddownTimer(sslSocket *ss)
+{
+ ss->ssl3.hs.rtRetries = 0;
+ return dtls_StartTimer(ss, ss->ssl3.hs.rtTimer,
+ DTLS_RETRANSMIT_FINISHED_MS,
+ dtls_FinishedTimerCb);
+}
+
+/* Cancel a pending timer
+ *
+ * Called from:
+ * dtls_HandleHandshake()
+ * dtls_CheckTimer()
+ */
+void
+dtls_CancelTimer(sslSocket *ss, dtlsTimer *timer)
+{
+ SSL_TRC(30, ("%d: SSL3[%d]: %s dtls_CancelTimer %s",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss),
+ timer->label));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+
+ timer->cb = NULL;
+}
+
+static void
+dtls_CancelAllTimers(sslSocket *ss)
+{
+ unsigned int i;
+
+ for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
+ dtls_CancelTimer(ss, &ss->ssl3.hs.timers[i]);
+ }
+}
+
+/* Check the pending timer and fire the callback if it expired
+ *
+ * Called from ssl3_GatherCompleteHandshake()
+ */
+void
+dtls_CheckTimer(sslSocket *ss)
+{
+ unsigned int i;
+ SSL_TRC(30, ("%d: SSL3[%d]: dtls_CheckTimer (%s)",
+ SSL_GETPID(), ss->fd, ss->sec.isServer ? "server" : "client"));
+
+ ssl_GetSSL3HandshakeLock(ss);
+
+ for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
+ dtlsTimer *timer = &ss->ssl3.hs.timers[i];
+ if (!timer->cb) {
+ continue;
+ }
+
+ if ((PR_IntervalNow() - timer->started) >=
+ PR_MillisecondsToInterval(timer->timeout)) {
+ /* Timer has expired */
+ DTLSTimerCb cb = timer->cb;
+
+ SSL_TRC(10, ("%d: SSL3[%d]: %s firing timer %s",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss),
+ timer->label));
+
+ /* Cancel the timer so that we can call the CB safely */
+ dtls_CancelTimer(ss, timer);
+
+ /* Now call the CB */
+ cb(ss);
+ }
+ }
+ ssl_ReleaseSSL3HandshakeLock(ss);
+}
+
+/* The callback to fire when the holddown timer for the Finished
+ * message expires and we can delete it
+ *
+ * Called from dtls_CheckTimer()
+ */
+static void
+dtls_FinishedTimerCb(sslSocket *ss)
+{
+ dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
+}
+
+/* Cancel the Finished hold-down timer and destroy the
+ * pending cipher spec. Note that this means that
+ * successive rehandshakes will fail if the Finished is
+ * lost.
+ *
+ * XXX OK for now. Figure out how to handle the combination
+ * of Finished lost and rehandshake
+ */
+void
+dtls_RehandshakeCleanup(sslSocket *ss)
+{
+ /* Skip this if we are handling a second ClientHello. */
+ if (ss->ssl3.hs.helloRetry) {
+ return;
+ }
+ PORT_Assert((ss->version < SSL_LIBRARY_VERSION_TLS_1_3));
+ dtls_CancelAllTimers(ss);
+ dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
+ ss->ssl3.hs.sendMessageSeq = 0;
+ ss->ssl3.hs.recvMessageSeq = 0;
+}
+
+/* Set the MTU to the next step less than or equal to the
+ * advertised value. Also used to downgrade the MTU by
+ * doing dtls_SetMTU(ss, biggest packet set).
+ *
+ * Passing 0 means set this to the largest MTU known
+ * (effectively resetting the PMTU backoff value).
+ *
+ * Called by:
+ * ssl3_InitState()
+ * dtls_RetransmitTimerExpiredCb()
+ */
+void
+dtls_SetMTU(sslSocket *ss, PRUint16 advertised)
+{
+ int i;
+
+ if (advertised == 0) {
+ ss->ssl3.mtu = COMMON_MTU_VALUES[0];
+ SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
+ return;
+ }
+
+ for (i = 0; i < PR_ARRAY_SIZE(COMMON_MTU_VALUES); i++) {
+ if (COMMON_MTU_VALUES[i] <= advertised) {
+ ss->ssl3.mtu = COMMON_MTU_VALUES[i];
+ SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
+ return;
+ }
+ }
+
+ /* Fallback */
+ ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES) - 1];
+ SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu));
+}
+
+/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a
+ * DTLS hello_verify_request
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+SECStatus
+dtls_HandleHelloVerifyRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ int errCode = SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST;
+ SECStatus rv;
+ SSL3ProtocolVersion temp;
+ SSL3AlertDescription desc = illegal_parameter;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle hello_verify_request handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->ssl3.hs.ws != wait_server_hello) {
+ errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST;
+ desc = unexpected_message;
+ goto alert_loser;
+ }
+
+ dtls_ReceivedFirstMessageInFlight(ss);
+
+ /* The version.
+ *
+ * RFC 4347 required that you verify that the server versions
+ * match (Section 4.2.1) in the HelloVerifyRequest and the
+ * ServerHello.
+ *
+ * RFC 6347 suggests (SHOULD) that servers always use 1.0 in
+ * HelloVerifyRequest and allows the versions not to match,
+ * especially when 1.2 is being negotiated.
+ *
+ * Therefore we do not do anything to enforce a match, just
+ * read and check that this value is sane.
+ */
+ rv = ssl_ClientReadVersion(ss, &b, &length, &temp);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+
+ /* Read the cookie.
+ * IMPORTANT: The value of ss->ssl3.hs.cookie is only valid while the
+ * HelloVerifyRequest message remains valid. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, &ss->ssl3.hs.cookie, 1, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+ if (ss->ssl3.hs.cookie.len > DTLS_COOKIE_BYTES) {
+ desc = decode_error;
+ goto alert_loser; /* malformed. */
+ }
+
+ ssl_GetXmitBufLock(ss); /*******************************/
+
+ /* Now re-send the client hello */
+ rv = ssl3_SendClientHello(ss, client_hello_retransmit);
+
+ ssl_ReleaseXmitBufLock(ss); /*******************************/
+
+ if (rv == SECSuccess)
+ return rv;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+
+loser:
+ ssl_MapLowLevelError(errCode);
+ return SECFailure;
+}
+
+/* Initialize the DTLS anti-replay window
+ *
+ * Called from:
+ * ssl3_SetupPendingCipherSpec()
+ * ssl3_InitCipherSpec()
+ */
+void
+dtls_InitRecvdRecords(DTLSRecvdRecords *records)
+{
+ PORT_Memset(records->data, 0, sizeof(records->data));
+ records->left = 0;
+ records->right = DTLS_RECVD_RECORDS_WINDOW - 1;
+}
+
+/*
+ * Has this DTLS record been received? Return values are:
+ * -1 -- out of range to the left
+ * 0 -- not received yet
+ * 1 -- replay
+ *
+ * Called from: ssl3_HandleRecord()
+ */
+int
+dtls_RecordGetRecvd(const DTLSRecvdRecords *records, sslSequenceNumber seq)
+{
+ PRUint64 offset;
+
+ /* Out of range to the left */
+ if (seq < records->left) {
+ return -1;
+ }
+
+ /* Out of range to the right; since we advance the window on
+ * receipt, that means that this packet has not been received
+ * yet */
+ if (seq > records->right)
+ return 0;
+
+ offset = seq % DTLS_RECVD_RECORDS_WINDOW;
+
+ return !!(records->data[offset / 8] & (1 << (offset % 8)));
+}
+
+/* Update the DTLS anti-replay window
+ *
+ * Called from ssl3_HandleRecord()
+ */
+void
+dtls_RecordSetRecvd(DTLSRecvdRecords *records, sslSequenceNumber seq)
+{
+ PRUint64 offset;
+
+ if (seq < records->left)
+ return;
+
+ if (seq > records->right) {
+ sslSequenceNumber new_left;
+ sslSequenceNumber new_right;
+ sslSequenceNumber right;
+
+ /* Slide to the right; this is the tricky part
+ *
+ * 1. new_top is set to have room for seq, on the
+ * next byte boundary by setting the right 8
+ * bits of seq
+ * 2. new_left is set to compensate.
+ * 3. Zero all bits between top and new_top. Since
+ * this is a ring, this zeroes everything as-yet
+ * unseen. Because we always operate on byte
+ * boundaries, we can zero one byte at a time
+ */
+ new_right = seq | 0x07;
+ new_left = (new_right - DTLS_RECVD_RECORDS_WINDOW) + 1;
+
+ if (new_right > records->right + DTLS_RECVD_RECORDS_WINDOW) {
+ PORT_Memset(records->data, 0, sizeof(records->data));
+ } else {
+ for (right = records->right + 8; right <= new_right; right += 8) {
+ offset = right % DTLS_RECVD_RECORDS_WINDOW;
+ records->data[offset / 8] = 0;
+ }
+ }
+
+ records->right = new_right;
+ records->left = new_left;
+ }
+
+ offset = seq % DTLS_RECVD_RECORDS_WINDOW;
+
+ records->data[offset / 8] |= (1 << (offset % 8));
+}
+
+SECStatus
+DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout)
+{
+ sslSocket *ss = NULL;
+ PRBool found = PR_FALSE;
+ PRIntervalTime now = PR_IntervalNow();
+ PRIntervalTime to;
+ unsigned int i;
+
+ *timeout = PR_INTERVAL_NO_TIMEOUT;
+
+ ss = ssl_FindSocket(socket);
+
+ if (!ss) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!IS_DTLS(ss)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ for (i = 0; i < PR_ARRAY_SIZE(ss->ssl3.hs.timers); ++i) {
+ PRIntervalTime elapsed;
+ PRIntervalTime desired;
+ dtlsTimer *timer = &ss->ssl3.hs.timers[i];
+
+ if (!timer->cb) {
+ continue;
+ }
+ found = PR_TRUE;
+
+ elapsed = now - timer->started;
+ desired = PR_MillisecondsToInterval(timer->timeout);
+ if (elapsed > desired) {
+ /* Timer expired */
+ *timeout = PR_INTERVAL_NO_WAIT;
+ return SECSuccess;
+ } else {
+ to = desired - elapsed;
+ }
+
+ if (*timeout > to) {
+ *timeout = to;
+ }
+ }
+
+ if (!found) {
+ PORT_SetError(SSL_ERROR_NO_TIMERS_FOUND);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+PRBool
+dtls_IsLongHeader(SSL3ProtocolVersion version, PRUint8 firstOctet)
+{
+#ifndef UNSAFE_FUZZER_MODE
+ return version < SSL_LIBRARY_VERSION_TLS_1_3 ||
+ firstOctet == ssl_ct_handshake ||
+ firstOctet == ssl_ct_ack ||
+ firstOctet == ssl_ct_alert;
+#else
+ return PR_TRUE;
+#endif
+}
+
+PRBool
+dtls_IsDtls13Ciphertext(SSL3ProtocolVersion version, PRUint8 firstOctet)
+{
+ // Allow no version in case we haven't negotiated one yet.
+ return (version == 0 || version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
+ (firstOctet & 0xe0) == 0x20;
+}
+
+DTLSEpoch
+dtls_ReadEpoch(const ssl3CipherSpec *crSpec, const PRUint8 *hdr)
+{
+ DTLSEpoch epoch;
+ DTLSEpoch maxEpoch;
+ DTLSEpoch partial;
+
+ if (dtls_IsLongHeader(crSpec->version, hdr[0])) {
+ return ((DTLSEpoch)hdr[3] << 8) | hdr[4];
+ }
+
+ /* A lot of how we recover the epoch here will depend on how we plan to
+ * manage KeyUpdate. In the case that we decide to install a new read spec
+ * as a KeyUpdate is handled, crSpec will always be the highest epoch we can
+ * possibly receive. That makes this easier to manage.
+ */
+ if (dtls_IsDtls13Ciphertext(crSpec->version, hdr[0])) {
+ /* TODO(ekr@rtfm.com: do something with the two-bit epoch. */
+ /* Use crSpec->epoch, or crSpec->epoch - 1 if the last bit differs. */
+ return crSpec->epoch - ((hdr[0] ^ crSpec->epoch) & 0x3);
+ }
+
+ /* dtls_GatherData should ensure that this works. */
+ PORT_Assert(hdr[0] == ssl_ct_application_data);
+
+ /* This uses the same method as is used to recover the sequence number in
+ * dtls_ReadSequenceNumber, except that the maximum value is set to the
+ * current epoch. */
+ partial = hdr[1] >> 6;
+ maxEpoch = PR_MAX(crSpec->epoch, 3);
+ epoch = (maxEpoch & 0xfffc) | partial;
+ if (partial > (maxEpoch & 0x03)) {
+ epoch -= 4;
+ }
+ return epoch;
+}
+
+static sslSequenceNumber
+dtls_ReadSequenceNumber(const ssl3CipherSpec *spec, const PRUint8 *hdr)
+{
+ sslSequenceNumber cap;
+ sslSequenceNumber partial;
+ sslSequenceNumber seqNum;
+ sslSequenceNumber mask;
+
+ if (dtls_IsLongHeader(spec->version, hdr[0])) {
+ static const unsigned int seqNumOffset = 5; /* type, version, epoch */
+ static const unsigned int seqNumLength = 6;
+ sslReader r = SSL_READER(hdr + seqNumOffset, seqNumLength);
+ (void)sslRead_ReadNumber(&r, seqNumLength, &seqNum);
+ return seqNum;
+ }
+
+ /* Only the least significant bits of the sequence number is available here.
+ * This recovers the value based on the next expected sequence number.
+ *
+ * This works by determining the maximum possible sequence number, which is
+ * half the range of possible values above the expected next value (the
+ * expected next value is in |spec->seqNum|). Then, the last part of the
+ * sequence number is replaced. If that causes the value to exceed the
+ * maximum, subtract an entire range.
+ */
+ if (hdr[0] & 0x08) {
+ cap = spec->nextSeqNum + (1ULL << 15);
+ partial = (((sslSequenceNumber)hdr[1]) << 8) |
+ (sslSequenceNumber)hdr[2];
+ mask = (1ULL << 16) - 1;
+ } else {
+ cap = spec->nextSeqNum + (1ULL << 7);
+ partial = (sslSequenceNumber)hdr[1];
+ mask = (1ULL << 8) - 1;
+ }
+ seqNum = (cap & ~mask) | partial;
+ /* The second check prevents the value from underflowing if we get a large
+ * gap at the start of a connection, where this subtraction would cause the
+ * sequence number to wrap to near UINT64_MAX. */
+ if ((partial > (cap & mask)) && (seqNum > mask)) {
+ seqNum -= mask + 1;
+ }
+ return seqNum;
+}
+
+/*
+ * DTLS relevance checks:
+ * Note that this code currently ignores all out-of-epoch packets,
+ * which means we lose some in the case of rehandshake +
+ * loss/reordering. Since DTLS is explicitly unreliable, this
+ * seems like a good tradeoff for implementation effort and is
+ * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1.
+ *
+ * If the packet is not relevant, this function returns PR_FALSE. If the packet
+ * is relevant, this function returns PR_TRUE and sets |*seqNumOut| to the
+ * packet sequence number (removing the epoch).
+ */
+PRBool
+dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *spec,
+ const SSL3Ciphertext *cText,
+ sslSequenceNumber *seqNumOut)
+{
+ sslSequenceNumber seqNum = dtls_ReadSequenceNumber(spec, cText->hdr);
+ if (dtls_RecordGetRecvd(&spec->recvdRecords, seqNum) != 0) {
+ SSL_TRC(10, ("%d: SSL3[%d]: dtls_IsRelevant, rejecting "
+ "potentially replayed packet",
+ SSL_GETPID(), ss->fd));
+ return PR_FALSE;
+ }
+
+ *seqNumOut = seqNum;
+ return PR_TRUE;
+}
+
+void
+dtls_ReceivedFirstMessageInFlight(sslSocket *ss)
+{
+ if (!IS_DTLS(ss))
+ return;
+
+ /* At this point we are advancing our state machine, so we can free our last
+ * flight of messages. */
+ if (ss->ssl3.hs.ws != idle_handshake ||
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ /* We need to keep our last flight around in DTLS 1.2 and below,
+ * so we can retransmit it in response to other people's
+ * retransmits. */
+ dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
+
+ /* Reset the timer to the initial value if the retry counter
+ * is 0, per RFC 6347, Sec. 4.2.4.1 */
+ dtls_CancelTimer(ss, ss->ssl3.hs.rtTimer);
+ if (ss->ssl3.hs.rtRetries == 0) {
+ ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
+ }
+ }
+
+ /* Empty the ACK queue (TLS 1.3 only). */
+ ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL);
+}
diff --git a/security/nss/lib/ssl/dtlscon.h b/security/nss/lib/ssl/dtlscon.h
new file mode 100644
index 0000000000..9d10aa248d
--- /dev/null
+++ b/security/nss/lib/ssl/dtlscon.h
@@ -0,0 +1,51 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __dtlscon_h_
+#define __dtlscon_h_
+
+extern void dtls_FreeHandshakeMessage(DTLSQueuedMessage *msg);
+extern void dtls_FreeHandshakeMessages(PRCList *lst);
+SECStatus dtls_TransmitMessageFlight(sslSocket *ss);
+void dtls_InitTimers(sslSocket *ss);
+SECStatus dtls_StartTimer(sslSocket *ss, dtlsTimer *timer,
+ PRUint32 time, DTLSTimerCb cb);
+SECStatus dtls_RestartTimer(sslSocket *ss, dtlsTimer *timer);
+PRBool dtls_TimerActive(sslSocket *ss, dtlsTimer *timer);
+extern SECStatus dtls_HandleHandshake(sslSocket *ss, DTLSEpoch epoch,
+ sslSequenceNumber seqNum,
+ sslBuffer *origBuf);
+extern SECStatus dtls_HandleHelloVerifyRequest(sslSocket *ss,
+ PRUint8 *b, PRUint32 length);
+extern SECStatus dtls_StageHandshakeMessage(sslSocket *ss);
+extern SECStatus dtls_QueueMessage(sslSocket *ss, SSLContentType type,
+ const PRUint8 *pIn, PRInt32 nIn);
+extern SECStatus dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
+SECStatus ssl3_DisableNonDTLSSuites(sslSocket *ss);
+extern SECStatus dtls_StartHolddownTimer(sslSocket *ss);
+extern void dtls_CheckTimer(sslSocket *ss);
+extern void dtls_CancelTimer(sslSocket *ss, dtlsTimer *timer);
+extern void dtls_SetMTU(sslSocket *ss, PRUint16 advertised);
+extern void dtls_InitRecvdRecords(DTLSRecvdRecords *records);
+extern int dtls_RecordGetRecvd(const DTLSRecvdRecords *records,
+ sslSequenceNumber seq);
+extern void dtls_RecordSetRecvd(DTLSRecvdRecords *records,
+ sslSequenceNumber seq);
+extern void dtls_RehandshakeCleanup(sslSocket *ss);
+extern SSL3ProtocolVersion
+dtls_TLSVersionToDTLSVersion(SSL3ProtocolVersion tlsv);
+extern SSL3ProtocolVersion
+dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv);
+DTLSEpoch dtls_ReadEpoch(const ssl3CipherSpec *crSpec, const PRUint8 *hdr);
+extern PRBool dtls_IsRelevant(sslSocket *ss, const ssl3CipherSpec *spec,
+ const SSL3Ciphertext *cText,
+ sslSequenceNumber *seqNum);
+void dtls_ReceivedFirstMessageInFlight(sslSocket *ss);
+PRBool dtls_IsLongHeader(SSL3ProtocolVersion version, PRUint8 firstOctet);
+PRBool dtls_IsDtls13Ciphertext(SSL3ProtocolVersion version, PRUint8 firstOctet);
+#endif
diff --git a/security/nss/lib/ssl/exports.gyp b/security/nss/lib/ssl/exports.gyp
new file mode 100644
index 0000000000..c3b34c6cc3
--- /dev/null
+++ b/security/nss/lib/ssl/exports.gyp
@@ -0,0 +1,30 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+{
+ 'includes': [
+ '../../coreconf/config.gypi'
+ ],
+ 'targets': [
+ {
+ 'target_name': 'lib_ssl_exports',
+ 'type': 'none',
+ 'copies': [
+ {
+ 'files': [
+ 'preenc.h',
+ 'ssl.h',
+ 'sslerr.h',
+ 'sslexp.h',
+ 'sslproto.h',
+ 'sslt.h'
+ ],
+ 'destination': '<(nss_public_dist_dir)/<(module)'
+ }
+ ]
+ }
+ ],
+ 'variables': {
+ 'module': 'nss'
+ }
+}
diff --git a/security/nss/lib/ssl/manifest.mn b/security/nss/lib/ssl/manifest.mn
new file mode 100644
index 0000000000..fedc42b4e5
--- /dev/null
+++ b/security/nss/lib/ssl/manifest.mn
@@ -0,0 +1,73 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+CORE_DEPTH = ../..
+
+# DEFINES = -DTRACE
+
+ifdef ZLIB_INCLUDE_DIR
+INCLUDES += -I$(ZLIB_INCLUDE_DIR)
+endif
+
+EXPORTS = \
+ ssl.h \
+ sslt.h \
+ sslerr.h \
+ sslexp.h \
+ sslproto.h \
+ preenc.h \
+ $(NULL)
+
+MODULE = nss
+
+CSRCS = \
+ authcert.c \
+ cmpcert.c \
+ dtls13con.c \
+ dtlscon.c \
+ prelib.c \
+ selfencrypt.c \
+ ssl3con.c \
+ ssl3ecc.c \
+ ssl3ext.c \
+ ssl3exthandle.c \
+ ssl3gthr.c \
+ sslauth.c \
+ sslbloom.c \
+ sslcert.c \
+ sslcon.c \
+ ssldef.c \
+ sslencode.c \
+ sslenum.c \
+ sslerr.c \
+ sslerrstrs.c \
+ sslgrp.c \
+ sslinfo.c \
+ sslinit.c \
+ sslmutex.c \
+ sslnonce.c \
+ sslprimitive.c \
+ sslreveal.c \
+ sslsecur.c \
+ sslsnce.c \
+ sslsock.c \
+ sslspec.c \
+ ssltrace.c \
+ sslver.c \
+ tls13con.c \
+ tls13ech.c \
+ tls13echv.c \
+ tls13exthandle.c \
+ tls13hashstate.c \
+ tls13hkdf.c \
+ tls13psk.c \
+ tls13replay.c \
+ tls13subcerts.c \
+ $(NULL)
+
+LIBRARY_NAME = ssl
+LIBRARY_VERSION = 3
+MAPFILE = $(OBJDIR)/$(LIBRARY_NAME).def
+
+# This part of the code, including all sub-dirs, can be optimized for size
+export ALLOW_OPT_CODE_SIZE = 1
diff --git a/security/nss/lib/ssl/notes.txt b/security/nss/lib/ssl/notes.txt
new file mode 100644
index 0000000000..7a8998a85c
--- /dev/null
+++ b/security/nss/lib/ssl/notes.txt
@@ -0,0 +1,104 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+SSL's Buffers: enumerated and explained.
+
+---------------------------------------------------------------------------
+incoming:
+
+gs = ss->gather
+hs = ss->ssl3->hs
+
+gs->inbuf incoming (encrypted) ssl records are placed here,
+ and then decrypted (or copied) to gs->buf.
+
+gs->buf ssl3_HandleHandshake puts decrypted ssl records here.
+
+hs.msg_body When an incoming handshake message spans more
+ than one ssl record, the first part(s) of it are accumulated
+ here until it all arrives.
+
+hs.msgState an alternative set of pointers/lengths for gs->buf.
+ Used only when a handleHandshake function returns SECWouldBlock.
+ ssl3_HandleHandshake remembers how far it previously got by
+ using these pointers instead of gs->buf when it is called
+ after a previous SECWouldBlock return.
+
+---------------------------------------------------------------------------
+outgoing:
+
+sec = ss->sec
+ci = ss->sec->ci /* connect info */
+
+ci->sendBuf Outgoing handshake messages are appended to this buffer.
+ This buffer will then be sent as a single SSL record.
+
+sec->writeBuf outgoing ssl records are constructed here and encrypted in
+ place before being written or copied to pendingBuf.
+
+ss->pendingBuf contains outgoing ciphertext that was saved after a write
+ attempt to the socket failed, e.g. EWouldBlock.
+ Generally empty with blocking sockets (should be no incomplete
+ writes).
+
+ss->saveBuf Used only by socks code. Intended to be used to buffer
+ outgoing data until a socks handshake completes. However,
+ this buffer is always empty. There is no code to put
+ anything into it.
+
+---------------------------------------------------------------------------
+
+SECWouldBlock means that the function cannot make progress because it is
+waiting for some event OTHER THAN socket I/O completion (e.g. waiting for
+user dialog to finish). It is not the same as EWOULDBLOCK.
+
+---------------------------------------------------------------------------
+
+Rank (order) of locks
+
+recvLock ->\ firstHandshake -> recvbuf -> ssl3Handshake -> xmitbuf -> "spec"
+sendLock ->/
+
+crypto and hash Data that must be protected while turning plaintext into
+ciphertext:
+
+SSl3: (in ssl3_SendPlainText)
+ ss->ssl3 (the pointer)
+ ss->ssl3->current_write* (the pointer and the data in the spec
+ and any data referenced by the spec.
+
+ ss->sec->isServer
+ ss->sec->writebuf* (ptr & content) locked by xmitBufLock
+ "buf" locked by xmitBufLock
+
+crypto and hash data that must be protected while turning ciphertext into
+plaintext:
+
+SSL3: (in ssl3_HandleRecord )
+ ssl3->current_read* (the pointer and all data refernced)
+ ss->sec->isServer
+
+
+Data that must be protected while being used by a "writer":
+
+ss->pendingBuf.*
+ss->saveBuf.* (which is dead)
+
+in ssl3_sendPlainText
+
+ss->ssl3->current_write-> (spec)
+ss->sec->writeBuf.*
+ss->sec->isServer
+
+in SendBlock
+
+ss->sec->writeBuf.*
+ss->pendingBuf
+
+--------------------------------------------------------------------------
+
+Data variables (not const) protected by the "sslGlobalDataLock".
+Note, this really should be a reader/writer lock.
+
+cipherSuites[] ssl3con.c
diff --git a/security/nss/lib/ssl/os2_err.c b/security/nss/lib/ssl/os2_err.c
new file mode 100644
index 0000000000..6e3d423f49
--- /dev/null
+++ b/security/nss/lib/ssl/os2_err.c
@@ -0,0 +1,330 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/*
+ * This file essentially replicates NSPR's source for the functions that
+ * map system-specific error codes to NSPR error codes. We would use
+ * NSPR's functions, instead of duplicating them, but they're private.
+ * As long as SSL's server session cache code must do platform native I/O
+ * to accomplish its job, and NSPR's error mapping functions remain private,
+ * this code will continue to need to be replicated.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "prerror.h"
+#include "prlog.h"
+#include <errno.h>
+
+/*
+ * Based on win32err.c
+ * OS2TODO Stub everything for now to build. HCT
+ */
+
+/* forward declaration. */
+void nss_MD_os2_map_default_error(PRInt32 err);
+
+void
+nss_MD_os2_map_opendir_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_closedir_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_readdir_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_delete_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+/* The error code for stat() is in errno. */
+void
+nss_MD_os2_map_stat_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_fstat_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_rename_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+/* The error code for access() is in errno. */
+void
+nss_MD_os2_map_access_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_mkdir_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_rmdir_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_read_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_transmitfile_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_write_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_lseek_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_fsync_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+/*
+ * For both CloseHandle() and closesocket().
+ */
+void
+nss_MD_os2_map_close_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_socket_error(PRInt32 err)
+{
+ // PR_ASSERT(err != WSANOTINITIALISED);
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_recv_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_recvfrom_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_send_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEMSGSIZE: prError = PR_INVALID_ARGUMENT_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_sendto_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEMSGSIZE: prError = PR_INVALID_ARGUMENT_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_accept_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break;
+ // case WSAEINVAL: prError = PR_INVALID_STATE_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_acceptex_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_connect_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEWOULDBLOCK: prError = PR_IN_PROGRESS_ERROR; break;
+ // case WSAEINVAL: prError = PR_ALREADY_INITIATED_ERROR; break;
+ // case WSAETIMEDOUT: prError = PR_IO_TIMEOUT_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_bind_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEINVAL: prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_listen_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEOPNOTSUPP: prError = PR_NOT_TCP_SOCKET_ERROR; break;
+ // case WSAEINVAL: prError = PR_INVALID_STATE_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_shutdown_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_getsockname_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAEINVAL: prError = PR_INVALID_STATE_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_getpeername_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_getsockopt_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_setsockopt_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_open_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_gethostname_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+/* Win32 select() only works on sockets. So in this
+** context, WSAENOTSOCK is equivalent to EBADF on Unix.
+*/
+void
+nss_MD_os2_map_select_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ // case WSAENOTSOCK: prError = PR_BAD_DESCRIPTOR_ERROR; break;
+ default:
+ nss_MD_os2_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_os2_map_lockf_error(PRInt32 err)
+{
+ nss_MD_os2_map_default_error(err);
+}
+
+void
+nss_MD_os2_map_default_error(PRInt32 err)
+{
+ PRErrorCode prError;
+
+ switch (err) {
+// case ENOENT: prError = PR_FILE_NOT_FOUND_ERROR; break;
+// case ERROR_ACCESS_DENIED: prError = PR_NO_ACCESS_RIGHTS_ERROR; break;
+// case ERROR_ALREADY_EXISTS: prError = PR_FILE_EXISTS_ERROR; break;
+// case ERROR_DISK_CORRUPT: prError = PR_IO_ERROR; break;
+// case ERROR_DISK_FULL: prError = PR_NO_DEVICE_SPACE_ERROR; break;
+// case ERROR_DISK_OPERATION_FAILED: prError = PR_IO_ERROR; break;
+// case ERROR_DRIVE_LOCKED: prError = PR_FILE_IS_LOCKED_ERROR; break;
+// case ERROR_FILENAME_EXCED_RANGE: prError = PR_NAME_TOO_LONG_ERROR; break;
+// case ERROR_FILE_CORRUPT: prError = PR_IO_ERROR; break;
+// case ERROR_FILE_EXISTS: prError = PR_FILE_EXISTS_ERROR; break;
+// case ERROR_FILE_INVALID: prError = PR_BAD_DESCRIPTOR_ERROR; break;
+#if ERROR_FILE_NOT_FOUND != ENOENT
+// case ERROR_FILE_NOT_FOUND: prError = PR_FILE_NOT_FOUND_ERROR; break;
+#endif
+ default:
+ prError = PR_UNKNOWN_ERROR;
+ break;
+ }
+ PR_SetError(prError, err);
+}
diff --git a/security/nss/lib/ssl/os2_err.h b/security/nss/lib/ssl/os2_err.h
new file mode 100644
index 0000000000..15e47411a1
--- /dev/null
+++ b/security/nss/lib/ssl/os2_err.h
@@ -0,0 +1,53 @@
+/*
+ * This file essentially replicates NSPR's source for the functions that
+ * map system-specific error codes to NSPR error codes. We would use
+ * NSPR's functions, instead of duplicating them, but they're private.
+ * As long as SSL's server session cache code must do platform native I/O
+ * to accomplish its job, and NSPR's error mapping functions remain private,
+ * This code will continue to need to be replicated.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* NSPR doesn't make these functions public, so we have to duplicate
+** them in NSS.
+*/
+
+//HCT Based on Win32err.h
+extern void nss_MD_os2_map_accept_error(PRInt32 err);
+extern void nss_MD_os2_map_acceptex_error(PRInt32 err);
+extern void nss_MD_os2_map_access_error(PRInt32 err);
+extern void nss_MD_os2_map_bind_error(PRInt32 err);
+extern void nss_MD_os2_map_close_error(PRInt32 err);
+extern void nss_MD_os2_map_closedir_error(PRInt32 err);
+extern void nss_MD_os2_map_connect_error(PRInt32 err);
+extern void nss_MD_os2_map_default_error(PRInt32 err);
+extern void nss_MD_os2_map_delete_error(PRInt32 err);
+extern void nss_MD_os2_map_fstat_error(PRInt32 err);
+extern void nss_MD_os2_map_fsync_error(PRInt32 err);
+extern void nss_MD_os2_map_gethostname_error(PRInt32 err);
+extern void nss_MD_os2_map_getpeername_error(PRInt32 err);
+extern void nss_MD_os2_map_getsockname_error(PRInt32 err);
+extern void nss_MD_os2_map_getsockopt_error(PRInt32 err);
+extern void nss_MD_os2_map_listen_error(PRInt32 err);
+extern void nss_MD_os2_map_lockf_error(PRInt32 err);
+extern void nss_MD_os2_map_lseek_error(PRInt32 err);
+extern void nss_MD_os2_map_mkdir_error(PRInt32 err);
+extern void nss_MD_os2_map_open_error(PRInt32 err);
+extern void nss_MD_os2_map_opendir_error(PRInt32 err);
+extern void nss_MD_os2_map_read_error(PRInt32 err);
+extern void nss_MD_os2_map_readdir_error(PRInt32 err);
+extern void nss_MD_os2_map_recv_error(PRInt32 err);
+extern void nss_MD_os2_map_recvfrom_error(PRInt32 err);
+extern void nss_MD_os2_map_rename_error(PRInt32 err);
+extern void nss_MD_os2_map_rmdir_error(PRInt32 err);
+extern void nss_MD_os2_map_select_error(PRInt32 err);
+extern void nss_MD_os2_map_send_error(PRInt32 err);
+extern void nss_MD_os2_map_sendto_error(PRInt32 err);
+extern void nss_MD_os2_map_setsockopt_error(PRInt32 err);
+extern void nss_MD_os2_map_shutdown_error(PRInt32 err);
+extern void nss_MD_os2_map_socket_error(PRInt32 err);
+extern void nss_MD_os2_map_stat_error(PRInt32 err);
+extern void nss_MD_os2_map_transmitfile_error(PRInt32 err);
+extern void nss_MD_os2_map_write_error(PRInt32 err);
diff --git a/security/nss/lib/ssl/preenc.h b/security/nss/lib/ssl/preenc.h
new file mode 100644
index 0000000000..bebff89e22
--- /dev/null
+++ b/security/nss/lib/ssl/preenc.h
@@ -0,0 +1,113 @@
+/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
+
+/*
+ * Fortezza support is removed.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Fortezza support is removed.
+ * This file remains so that old programs will continue to compile,
+ * But this functionality is no longer supported or implemented.
+ */
+
+#include "seccomon.h"
+#include "prio.h"
+
+typedef struct PEHeaderStr PEHeader;
+
+#define PE_MIME_TYPE "application/pre-encrypted"
+
+typedef struct PEFortezzaHeaderStr PEFortezzaHeader;
+typedef struct PEFortezzaGeneratedHeaderStr PEFortezzaGeneratedHeader;
+typedef struct PEFixedKeyHeaderStr PEFixedKeyHeader;
+typedef struct PERSAKeyHeaderStr PERSAKeyHeader;
+
+struct PEFortezzaHeaderStr {
+ unsigned char key[12];
+ unsigned char iv[24];
+ unsigned char hash[20];
+ unsigned char serial[8];
+};
+
+struct PEFortezzaGeneratedHeaderStr {
+ unsigned char key[12];
+ unsigned char iv[24];
+ unsigned char hash[20];
+ unsigned char Ra[128];
+ unsigned char Y[128];
+};
+
+struct PEFixedKeyHeaderStr {
+ unsigned char pkcs11Mech[4];
+ unsigned char labelLen[2];
+ unsigned char keyIDLen[2];
+ unsigned char ivLen[2];
+ unsigned char keyLen[2];
+ unsigned char data[1];
+};
+
+struct PERSAKeyHeaderStr {
+ unsigned char pkcs11Mech[4];
+ unsigned char issuerLen[2];
+ unsigned char serialLen[2];
+ unsigned char ivLen[2];
+ unsigned char keyLen[2];
+ unsigned char data[1];
+};
+
+#define PEFIXED_Label(header) (header->data)
+#define PEFIXED_KeyID(header) (&header->data[GetInt2(header->labelLen)])
+#define PEFIXED_IV(header) (&header->data[GetInt2(header->labelLen) + \
+ GetInt2(header->keyIDLen)])
+#define PEFIXED_Key(header) (&header->data[GetInt2(header->labelLen) + \
+ GetInt2(header->keyIDLen) + \
+ GetInt2(header->keyLen)])
+#define PERSA_Issuer(header) (header->data)
+#define PERSA_Serial(header) (&header->data[GetInt2(header->issuerLen)])
+#define PERSA_IV(header) (&header->data[GetInt2(header->issuerLen) + \
+ GetInt2(header->serialLen)])
+#define PERSA_Key(header) (&header->data[GetInt2(header->issuerLen) + \
+ GetInt2(header->serialLen) + \
+ GetInt2(header->keyLen)])
+struct PEHeaderStr {
+ unsigned char magic[2];
+ unsigned char len[2];
+ unsigned char type[2];
+ unsigned char version[2];
+ union {
+ PEFortezzaHeader fortezza;
+ PEFortezzaGeneratedHeader g_fortezza;
+ PEFixedKeyHeader fixed;
+ PERSAKeyHeader rsa;
+ } u;
+};
+
+#define PE_CRYPT_INTRO_LEN 8
+#define PE_INTRO_LEN 4
+#define PE_BASE_HEADER_LEN 8
+
+#define PRE_BLOCK_SIZE 8
+
+#define GetInt2(c) ((c[0] << 8) | c[1])
+#define GetInt4(c) (((unsigned long)c[0] << 24) | ((unsigned long)c[1] << 16) | \
+ ((unsigned long)c[2] << 8) | ((unsigned long)c[3]))
+#define PutInt2(c, i) ((c[1] = (i)&0xff), (c[0] = ((i) >> 8) & 0xff))
+#define PutInt4(c, i) ((c[0] = ((i) >> 24) & 0xff), (c[1] = ((i) >> 16) & 0xff), \
+ (c[2] = ((i) >> 8) & 0xff), (c[3] = (i)&0xff))
+
+#define PRE_MAGIC 0xc0de
+#define PRE_VERSION 0x1010
+#define PRE_FORTEZZA_FILE 0x00ff
+#define PRE_FORTEZZA_STREAM 0x00f5
+#define PRE_FORTEZZA_GEN_STREAM 0x00f6
+#define PRE_FIXED_FILE 0x000f
+#define PRE_RSA_FILE 0x001f
+#define PRE_FIXED_STREAM 0x0005
+
+PEHeader *SSL_PreencryptedStreamToFile(PRFileDesc *fd, PEHeader *,
+ int *headerSize);
+
+PEHeader *SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *,
+ int *headerSize);
diff --git a/security/nss/lib/ssl/prelib.c b/security/nss/lib/ssl/prelib.c
new file mode 100644
index 0000000000..4db9ffe699
--- /dev/null
+++ b/security/nss/lib/ssl/prelib.c
@@ -0,0 +1,34 @@
+/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
+
+/*
+ * Functions used by https servers to send (download) pre-encrypted files
+ * over SSL connections that use Fortezza ciphersuites.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "cert.h"
+#include "ssl.h"
+#include "keyhi.h"
+#include "secitem.h"
+#include "sslimpl.h"
+#include "pkcs11t.h"
+#include "preenc.h"
+#include "pk11func.h"
+
+PEHeader *
+SSL_PreencryptedStreamToFile(PRFileDesc *fd, PEHeader *inHeader,
+ int *headerSize)
+{
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return NULL;
+}
+
+PEHeader *
+SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *header,
+ int *headerSize)
+{
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return NULL;
+}
diff --git a/security/nss/lib/ssl/selfencrypt.c b/security/nss/lib/ssl/selfencrypt.c
new file mode 100644
index 0000000000..1c70f76353
--- /dev/null
+++ b/security/nss/lib/ssl/selfencrypt.c
@@ -0,0 +1,321 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "blapit.h"
+#include "pk11func.h"
+#include "ssl.h"
+#include "sslt.h"
+#include "sslimpl.h"
+#include "selfencrypt.h"
+
+static SECStatus
+ssl_MacBuffer(PK11SymKey *key, CK_MECHANISM_TYPE mech,
+ const unsigned char *in, unsigned int len,
+ unsigned char *mac, unsigned int *macLen, unsigned int maxMacLen)
+{
+ PK11Context *ctx;
+ SECItem macParam = { 0, NULL, 0 };
+ unsigned int computedLen;
+ SECStatus rv;
+
+ ctx = PK11_CreateContextBySymKey(mech, CKA_SIGN, key, &macParam);
+ if (!ctx) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = PK11_DigestBegin(ctx);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+
+ rv = PK11_DigestOp(ctx, in, len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+
+ rv = PK11_DigestFinal(ctx, mac, &computedLen, maxMacLen);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+
+ *macLen = maxMacLen;
+ PK11_DestroyContext(ctx, PR_TRUE);
+ return SECSuccess;
+
+loser:
+ PK11_DestroyContext(ctx, PR_TRUE);
+ return SECFailure;
+}
+
+#ifdef UNSAFE_FUZZER_MODE
+SECStatus
+ssl_SelfEncryptProtectInt(
+ PK11SymKey *encKey, PK11SymKey *macKey,
+ const unsigned char *keyName,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen)
+{
+ if (inLen > maxOutLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ PORT_Memcpy(out, in, inLen);
+ *outLen = inLen;
+
+ return 0;
+}
+
+SECStatus
+ssl_SelfEncryptUnprotectInt(
+ PK11SymKey *encKey, PK11SymKey *macKey, const unsigned char *keyName,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen)
+{
+ if (inLen > maxOutLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ PORT_Memcpy(out, in, inLen);
+ *outLen = inLen;
+
+ return 0;
+}
+
+#else
+/*
+ * Structure is.
+ *
+ * struct {
+ * opaque keyName[16];
+ * opaque iv[16];
+ * opaque ciphertext<16..2^16-1>;
+ * opaque mac[32];
+ * } SelfEncrypted;
+ *
+ * We are using AES-CBC + HMAC-SHA256 in Encrypt-then-MAC mode for
+ * two reasons:
+ *
+ * 1. It's what we already used for tickets.
+ * 2. We don't have to worry about nonce collisions as much
+ * (the chance is lower because we have a random 128-bit nonce
+ * and they are less serious than with AES-GCM).
+ */
+SECStatus
+ssl_SelfEncryptProtectInt(
+ PK11SymKey *encKey, PK11SymKey *macKey,
+ const unsigned char *keyName,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen)
+{
+ unsigned int len;
+ unsigned int lenOffset;
+ unsigned char iv[AES_BLOCK_SIZE];
+ SECItem ivItem = { siBuffer, iv, sizeof(iv) };
+ /* Write directly to out. */
+ sslBuffer buf = SSL_BUFFER_FIXED(out, maxOutLen);
+ SECStatus rv;
+
+ /* Generate a random IV */
+ rv = PK11_GenerateRandom(iv, sizeof(iv));
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Add header. */
+ rv = sslBuffer_Append(&buf, keyName, SELF_ENCRYPT_KEY_NAME_LEN);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Append(&buf, iv, sizeof(iv));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Leave space for the length of the ciphertext. */
+ rv = sslBuffer_Skip(&buf, 2, &lenOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Encode the ciphertext in place. */
+ rv = PK11_Encrypt(encKey, CKM_AES_CBC_PAD, &ivItem,
+ SSL_BUFFER_NEXT(&buf), &len,
+ SSL_BUFFER_SPACE(&buf), in, inLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Skip(&buf, len, NULL);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_InsertLength(&buf, lenOffset, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* MAC the entire output buffer into the output. */
+ PORT_Assert(buf.space - buf.len >= SHA256_LENGTH);
+ rv = ssl_MacBuffer(macKey, CKM_SHA256_HMAC,
+ SSL_BUFFER_BASE(&buf), /* input */
+ SSL_BUFFER_LEN(&buf),
+ SSL_BUFFER_NEXT(&buf), &len, /* output */
+ SHA256_LENGTH);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Skip(&buf, len, NULL);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *outLen = SSL_BUFFER_LEN(&buf);
+ return SECSuccess;
+}
+
+SECStatus
+ssl_SelfEncryptUnprotectInt(
+ PK11SymKey *encKey, PK11SymKey *macKey, const unsigned char *keyName,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen)
+{
+ sslReader reader = SSL_READER(in, inLen);
+
+ sslReadBuffer encodedKeyNameBuffer = { 0 };
+ SECStatus rv = sslRead_Read(&reader, SELF_ENCRYPT_KEY_NAME_LEN,
+ &encodedKeyNameBuffer);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ sslReadBuffer ivBuffer = { 0 };
+ rv = sslRead_Read(&reader, AES_BLOCK_SIZE, &ivBuffer);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ PRUint64 cipherTextLen = 0;
+ rv = sslRead_ReadNumber(&reader, 2, &cipherTextLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ sslReadBuffer cipherTextBuffer = { 0 };
+ rv = sslRead_Read(&reader, (unsigned int)cipherTextLen, &cipherTextBuffer);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ unsigned int bytesToMac = reader.offset;
+
+ sslReadBuffer encodedMacBuffer = { 0 };
+ rv = sslRead_Read(&reader, SHA256_LENGTH, &encodedMacBuffer);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Make sure we're at the end of the block. */
+ if (reader.offset != reader.buf.len) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+
+ /* Now that everything is decoded, we can make progress. */
+ /* 1. Check that we have the right key. */
+ if (PORT_Memcmp(keyName, encodedKeyNameBuffer.buf, SELF_ENCRYPT_KEY_NAME_LEN)) {
+ PORT_SetError(SEC_ERROR_NOT_A_RECIPIENT);
+ return SECFailure;
+ }
+
+ /* 2. Check the MAC */
+ unsigned char computedMac[SHA256_LENGTH];
+ unsigned int computedMacLen = 0;
+ rv = ssl_MacBuffer(macKey, CKM_SHA256_HMAC, in, bytesToMac,
+ computedMac, &computedMacLen, sizeof(computedMac));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PORT_Assert(computedMacLen == SHA256_LENGTH);
+ if (NSS_SecureMemcmp(computedMac, encodedMacBuffer.buf, computedMacLen) != 0) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+
+ /* 3. OK, it verifies, now decrypt. */
+ SECItem ivItem = { siBuffer, (unsigned char *)ivBuffer.buf, AES_BLOCK_SIZE };
+ rv = PK11_Decrypt(encKey, CKM_AES_CBC_PAD, &ivItem,
+ out, outLen, maxOutLen, cipherTextBuffer.buf, cipherTextLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+#endif
+
+/* Predict the size of the encrypted data, including padding */
+unsigned int
+ssl_SelfEncryptGetProtectedSize(unsigned int inLen)
+{
+ return SELF_ENCRYPT_KEY_NAME_LEN +
+ AES_BLOCK_SIZE +
+ 2 +
+ ((inLen / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE + /* Padded */
+ SHA256_LENGTH;
+}
+
+SECStatus
+ssl_SelfEncryptProtect(
+ sslSocket *ss, const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen)
+{
+ PRUint8 keyName[SELF_ENCRYPT_KEY_NAME_LEN];
+ PK11SymKey *encKey;
+ PK11SymKey *macKey;
+ SECStatus rv;
+
+ /* Get session ticket keys. */
+ rv = ssl_GetSelfEncryptKeys(ss, keyName, &encKey, &macKey);
+ if (rv != SECSuccess) {
+ SSL_DBG(("%d: SSL[%d]: Unable to get/generate self-encrypt keys.",
+ SSL_GETPID(), ss->fd));
+ return SECFailure;
+ }
+
+ return ssl_SelfEncryptProtectInt(encKey, macKey, keyName,
+ in, inLen, out, outLen, maxOutLen);
+}
+
+SECStatus
+ssl_SelfEncryptUnprotect(
+ sslSocket *ss, const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen)
+{
+ PRUint8 keyName[SELF_ENCRYPT_KEY_NAME_LEN];
+ PK11SymKey *encKey;
+ PK11SymKey *macKey;
+ SECStatus rv;
+
+ /* Get session ticket keys. */
+ rv = ssl_GetSelfEncryptKeys(ss, keyName, &encKey, &macKey);
+ if (rv != SECSuccess) {
+ SSL_DBG(("%d: SSL[%d]: Unable to get/generate self-encrypt keys.",
+ SSL_GETPID(), ss->fd));
+ return SECFailure;
+ }
+
+ return ssl_SelfEncryptUnprotectInt(encKey, macKey, keyName,
+ in, inLen, out, outLen, maxOutLen);
+}
diff --git a/security/nss/lib/ssl/selfencrypt.h b/security/nss/lib/ssl/selfencrypt.h
new file mode 100644
index 0000000000..5415ac09f3
--- /dev/null
+++ b/security/nss/lib/ssl/selfencrypt.h
@@ -0,0 +1,32 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __selfencrypt_h_
+#define __selfencrypt_h_
+
+#include "secmodt.h"
+
+unsigned int ssl_SelfEncryptGetProtectedSize(unsigned int inLen);
+SECStatus ssl_SelfEncryptProtect(
+ sslSocket *ss, const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen);
+SECStatus ssl_SelfEncryptUnprotect(
+ sslSocket *ss, const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen);
+
+/* Exported for use in unit tests.*/
+SECStatus ssl_SelfEncryptProtectInt(
+ PK11SymKey *encKey, PK11SymKey *macKey, const unsigned char *keyName,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen);
+SECStatus ssl_SelfEncryptUnprotectInt(
+ PK11SymKey *encKey, PK11SymKey *macKey, const unsigned char *keyName,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOutLen);
+
+#endif
diff --git a/security/nss/lib/ssl/ssl.def b/security/nss/lib/ssl/ssl.def
new file mode 100644
index 0000000000..75c37f2bed
--- /dev/null
+++ b/security/nss/lib/ssl/ssl.def
@@ -0,0 +1,255 @@
+;+#
+;+# This Source Code Form is subject to the terms of the Mozilla Public
+;+# License, v. 2.0. If a copy of the MPL was not distributed with this
+;+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+;+#
+;+# OK, this file is meant to support SUN, LINUX, AIX and WINDOWS
+;+# 1. For all unix platforms, the string ";-" means "remove this line"
+;+# 2. For all unix platforms, the string " DATA " will be removed from any
+;+# line on which it occurs.
+;+# 3. Lines containing ";+" will have ";+" removed on SUN and LINUX.
+;+# On AIX, lines containing ";+" will be removed.
+;+# 4. For all unix platforms, the string ";;" will thave the ";;" removed.
+;+# 5. For all unix platforms, after the above processing has taken place,
+;+# all characters after the first ";" on the line will be removed.
+;+# And for AIX, the first ";" will also be removed.
+;+# This file is passed directly to windows. Since ';' is a comment, all UNIX
+;+# directives are hidden behind ";", ";+", and ";-"
+;+
+;+NSS_3.2 { # NSS 3.2 release
+;+ global:
+LIBRARY ssl3 ;-
+EXPORTS ;-
+SSL_ImplementedCiphers DATA ;
+SSL_NumImplementedCiphers DATA ;
+NSS_CmpCertChainWCANames;
+NSS_FindCertKEAType;
+NSS_GetClientAuthData;
+NSS_SetDomesticPolicy;
+NSS_SetExportPolicy;
+NSS_SetFrancePolicy;
+SSL_AuthCertificate;
+SSL_AuthCertificateHook;
+SSL_BadCertHook;
+SSL_CertDBHandleSet;
+SSL_CipherPolicyGet;
+SSL_CipherPolicySet;
+SSL_CipherPrefGet;
+SSL_CipherPrefGetDefault;
+SSL_CipherPrefSet;
+SSL_CipherPrefSetDefault;
+SSL_ClearSessionCache;
+SSL_ConfigMPServerSIDCache;
+SSL_ConfigSecureServer;
+SSL_ConfigServerSessionIDCache;
+SSL_DataPending;
+SSL_ForceHandshake;
+SSL_GetClientAuthDataHook;
+SSL_GetSessionID;
+SSL_GetStatistics;
+SSL_HandshakeCallback;
+SSL_ImportFD;
+SSL_InheritMPServerSIDCache;
+SSL_InvalidateSession;
+SSL_OptionGet;
+SSL_OptionGetDefault;
+SSL_OptionSet;
+SSL_OptionSetDefault;
+SSL_PeerCertificate;
+SSL_PreencryptedFileToStream;
+SSL_PreencryptedStreamToFile;
+SSL_ReHandshake;
+SSL_ResetHandshake;
+SSL_RestartHandshakeAfterCertReq;
+SSL_RestartHandshakeAfterServerCert;
+SSL_RevealCert;
+SSL_RevealPinArg;
+SSL_RevealURL;
+SSL_SecurityStatus;
+SSL_SetPKCS11PinArg;
+SSL_SetSockPeerID;
+SSL_SetURL;
+;+ local:
+;+*;
+;+};
+;+NSS_3.2.1 { # NSS 3.2.1 release
+;+ global:
+NSSSSL_VersionCheck;
+;+ local:
+;+*;
+;+};
+;+NSS_3.4 { # NSS 3.4 release
+;+ global:
+SSL_GetChannelInfo;
+SSL_GetCipherSuiteInfo;
+SSL_GetMaxServerCacheLocks;
+SSL_LocalCertificate;
+SSL_SetMaxServerCacheLocks;
+;+ local:
+;+*;
+;+};
+;+NSS_3.7.4 { # NSS 3.7.4 release
+;+ global:
+SSL_ShutdownServerSessionIDCache;
+;+ local:
+;+*;
+;+};
+;+NSS_3.11.4 { # NSS 3.11.4 release
+;+ global:
+SSL_ForceHandshakeWithTimeout;
+SSL_ReHandshakeWithTimeout;
+;+ local:
+;+*;
+;+};
+;+NSS_3.11.8 { # NSS 3.11.8 release
+;+ global:
+SSL_CanBypass;
+;+ local:
+;+*;
+;+};
+;+NSS_3.12.6 { # NSS 3.12.6 release
+;+ global:
+SSL_ConfigServerSessionIDCacheWithOpt;
+SSL_GetImplementedCiphers;
+SSL_GetNegotiatedHostInfo;
+SSL_GetNumImplementedCiphers;
+SSL_HandshakeNegotiatedExtension;
+SSL_ReconfigFD;
+SSL_SetTrustAnchors;
+SSL_SNISocketConfigHook;
+;+ local:
+;+*;
+;+};
+;+NSS_3.12.10 { # NSS 3.12.10 release
+;+ global:
+SSL_ConfigSecureServerWithCertChain;
+;+ local:
+;+*;
+;+};
+;+NSS_3.13 { # NSS 3.13 release
+;+ global:
+NSSSSL_GetVersion;
+;+ local:
+;+ *;
+;+};
+;+NSS_3.13.2 { # NSS 3.13.2 release
+;+ global:
+SSL_SetNextProtoCallback;
+SSL_SetNextProtoNego;
+SSL_GetNextProto;
+SSL_AuthCertificateComplete;
+;+ local:
+;+ *;
+;+};
+;+NSS_3.14 { # NSS 3.14 release
+;+ global:
+DTLS_GetHandshakeTimeout;
+DTLS_ImportFD;
+SSL_ExportKeyingMaterial;
+SSL_VersionRangeGet;
+SSL_VersionRangeGetDefault;
+SSL_VersionRangeGetSupported;
+SSL_VersionRangeSet;
+SSL_VersionRangeSetDefault;
+SSL_GetSRTPCipher;
+SSL_SetSRTPCiphers;
+;+ local:
+;+*;
+;+};
+;+NSS_3.15 { # NSS 3.15 release
+;+ global:
+SSL_PeerStapledOCSPResponses;
+SSL_SetStapledOCSPResponses;
+;+ local:
+;+*;
+;+};
+;+NSS_3.15.4 { # NSS 3.15.4 release
+;+ global:
+SSL_PeerCertificateChain;
+SSL_RecommendedCanFalseStart;
+SSL_SetCanFalseStartCallback;
+;+ local:
+;+*;
+;+};
+;+NSS_3.20 { # NSS 3.20 release
+;+ global:
+SSL_DHEGroupPrefSet;
+SSL_EnableWeakDHEPrimeGroup;
+;+ local:
+;+*;
+;+};
+;+NSS_3.21 { # NSS 3.21 release
+;+ global:
+SSL_GetPreliminaryChannelInfo;
+SSL_SignaturePrefSet;
+SSL_SignaturePrefGet;
+SSL_SignatureMaxCount;
+;+ local:
+;+*;
+;+};
+;+NSS_3.22 { # NSS 3.22 release
+;+ global:
+SSL_PeerSignedCertTimestamps;
+SSL_SetSignedCertTimestamps;
+;+ local:
+;+*;
+;+};
+;+NSS_3.23 { # NSS 3.23 release
+;+ global:
+SSL_SetDowngradeCheckVersion;
+;+ local:
+;+*;
+;+};
+;+NSS_3.24 { # NSS 3.24 release
+;+ global:
+SSL_ConfigServerCert;
+;+ local:
+;+*;
+;+};
+;+NSS_3.27 { # NSS 3.27 release
+;+ global:
+SSL_NamedGroupConfig;
+;+ local:
+;+*;
+;+};
+;+NSS_3.28 { # NSS 3.28 release
+;+ global:
+SSL_ExportEarlyKeyingMaterial;
+SSL_SendAdditionalKeyShares;
+SSL_SignatureSchemePrefSet;
+SSL_SignatureSchemePrefGet;
+;+ local:
+;+*;
+;+};
+;+NSS_3.30 { # NSS 3.30 release
+;+ global:
+SSL_SetSessionTicketKeyPair;
+;+ local:
+;+*;
+;+};
+;+NSS_3.30.0.1 { # Additional symbols for NSS 3.30 release
+;+ global:
+SSL_AlertReceivedCallback;
+SSL_AlertSentCallback;
+;+ local:
+;+*;
+;+};
+;+NSS_3.33 { # NSS 3.33 release
+;+ global:
+SSL_GetExperimentalAPI;
+;+ local:
+;+*;
+;+};
+;+NSS_3.77 { # NSS 3.77 release
+;+ global:
+SSL_CertIsUsable;
+SSL_FilterClientCertListBySocket;
+;+ local:
+;+*;
+;+};
+;+NSS_3.80 { # NSS 3.80 release
+;+ global:
+SSL_ClientCertCallbackComplete;
+;+ local:
+;+*;
+;+};
diff --git a/security/nss/lib/ssl/ssl.gyp b/security/nss/lib/ssl/ssl.gyp
new file mode 100644
index 0000000000..2aa35cc963
--- /dev/null
+++ b/security/nss/lib/ssl/ssl.gyp
@@ -0,0 +1,102 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+{
+ 'includes': [
+ '../../coreconf/config.gypi'
+ ],
+ 'targets': [
+ {
+ 'target_name': 'ssl',
+ 'type': 'static_library',
+ 'sources': [
+ 'authcert.c',
+ 'cmpcert.c',
+ 'dtlscon.c',
+ 'dtls13con.c',
+ 'prelib.c',
+ 'selfencrypt.c',
+ 'ssl3con.c',
+ 'ssl3ecc.c',
+ 'ssl3ext.c',
+ 'ssl3exthandle.c',
+ 'ssl3gthr.c',
+ 'sslauth.c',
+ 'sslbloom.c',
+ 'sslcert.c',
+ 'sslcon.c',
+ 'ssldef.c',
+ 'sslencode.c',
+ 'sslenum.c',
+ 'sslerr.c',
+ 'sslerrstrs.c',
+ 'sslgrp.c',
+ 'sslinfo.c',
+ 'sslinit.c',
+ 'sslmutex.c',
+ 'sslnonce.c',
+ 'sslprimitive.c',
+ 'sslreveal.c',
+ 'sslsecur.c',
+ 'sslsnce.c',
+ 'sslsock.c',
+ 'sslspec.c',
+ 'ssltrace.c',
+ 'sslver.c',
+ 'tls13con.c',
+ 'tls13ech.c',
+ 'tls13echv.c',
+ 'tls13exthandle.c',
+ 'tls13hashstate.c',
+ 'tls13hkdf.c',
+ 'tls13psk.c',
+ 'tls13replay.c',
+ 'tls13subcerts.c',
+ ],
+ 'conditions': [
+ [ 'OS=="win"', {
+ 'sources': [
+ 'win32err.c',
+ ],
+ 'defines': [
+ 'IN_LIBSSL',
+ ],
+ }, {
+ # Not Windows.
+ 'sources': [
+ 'unix_err.c'
+ ],
+ }],
+ [ 'fuzz_tls==1', {
+ 'defines': [
+ 'UNSAFE_FUZZER_MODE',
+ ],
+ }],
+ [ 'enable_sslkeylogfile==1', {
+ 'defines': [
+ 'NSS_ALLOW_SSLKEYLOGFILE',
+ ],
+ }],
+ ],
+ 'dependencies': [
+ '<(DEPTH)/exports.gyp:nss_exports',
+ ],
+ },
+ {
+ 'target_name': 'ssl3',
+ 'type': 'shared_library',
+ 'dependencies': [
+ 'ssl',
+ '<(DEPTH)/lib/nss/nss.gyp:nss3',
+ '<(DEPTH)/lib/util/util.gyp:nssutil3',
+ '<(DEPTH)/lib/freebl/freebl.gyp:freebl',
+ ],
+ 'variables': {
+ 'mapfile': 'ssl.def'
+ }
+ }
+ ],
+ 'variables': {
+ 'module': 'nss'
+ }
+}
diff --git a/security/nss/lib/ssl/ssl.h b/security/nss/lib/ssl/ssl.h
new file mode 100644
index 0000000000..fc817a781e
--- /dev/null
+++ b/security/nss/lib/ssl/ssl.h
@@ -0,0 +1,1608 @@
+/*
+ * This file contains prototypes for the public SSL functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __ssl_h_
+#define __ssl_h_
+
+#include "prtypes.h"
+#include "prerror.h"
+#include "prio.h"
+#include "seccomon.h"
+#include "cert.h"
+#include "keythi.h"
+
+#include "sslt.h" /* public ssl data types */
+
+#if defined(_WIN32) && !defined(IN_LIBSSL) && !defined(NSS_USE_STATIC_LIBS)
+#define SSL_IMPORT extern __declspec(dllimport)
+#else
+#define SSL_IMPORT extern
+#endif
+
+SEC_BEGIN_PROTOS
+
+/* constant table enumerating all implemented cipher suites. */
+SSL_IMPORT const PRUint16 SSL_ImplementedCiphers[];
+
+/* the same as the above, but is a function */
+SSL_IMPORT const PRUint16 *SSL_GetImplementedCiphers(void);
+
+/* number of entries in the above table. */
+SSL_IMPORT const PRUint16 SSL_NumImplementedCiphers;
+
+/* the same as the above, but is a function */
+SSL_IMPORT PRUint16 SSL_GetNumImplementedCiphers(void);
+
+/* Macro to tell which ciphers in table are SSL2 vs SSL3/TLS. */
+#define SSL_IS_SSL2_CIPHER(which) (((which)&0xfff0) == 0xff00)
+
+/*
+** Imports fd into SSL, returning a new socket. Copies SSL configuration
+** from model.
+*/
+SSL_IMPORT PRFileDesc *SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd);
+
+/*
+** Imports fd into DTLS, returning a new socket. Copies DTLS configuration
+** from model.
+*/
+SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd);
+
+/*
+** Enable/disable an ssl mode
+**
+** SSL_SECURITY:
+** enable/disable use of SSL security protocol before connect
+**
+** SSL_SOCKS:
+** enable/disable use of socks before connect
+** (No longer supported).
+**
+** SSL_REQUEST_CERTIFICATE:
+** require a certificate during secure connect
+*/
+/* options */
+#define SSL_SECURITY 1 /* (on by default) */
+#define SSL_SOCKS 2 /* (off by default) */
+#define SSL_REQUEST_CERTIFICATE 3 /* (off by default) */
+#define SSL_HANDSHAKE_AS_CLIENT 5 /* force accept to hs as client */
+ /* (off by default) */
+#define SSL_HANDSHAKE_AS_SERVER 6 /* force connect to hs as server */
+ /* (off by default) */
+
+/* OBSOLETE: SSL v2 is obsolete and may be removed soon. */
+#define SSL_ENABLE_SSL2 7 /* enable ssl v2 (off by default) */
+
+/* OBSOLETE: See "SSL Version Range API" below for the replacement and a
+** description of the non-obvious semantics of using SSL_ENABLE_SSL3.
+*/
+#define SSL_ENABLE_SSL3 8 /* enable ssl v3 (on by default) */
+
+#define SSL_NO_CACHE 9 /* don't use the session cache */
+ /* (off by default) */
+#define SSL_REQUIRE_CERTIFICATE 10 /* (SSL_REQUIRE_FIRST_HANDSHAKE */
+ /* by default) */
+#define SSL_ENABLE_FDX 11 /* permit simultaneous read/write */
+ /* (off by default) */
+
+/* OBSOLETE: SSL v2 compatible hellos are not accepted by some TLS servers
+** and cannot negotiate extensions. SSL v2 is obsolete. This option may be
+** removed soon.
+*/
+#define SSL_V2_COMPATIBLE_HELLO 12 /* send v3 client hello in v2 fmt */
+ /* (off by default) */
+
+/* OBSOLETE: See "SSL Version Range API" below for the replacement and a
+** description of the non-obvious semantics of using SSL_ENABLE_TLS.
+*/
+#define SSL_ENABLE_TLS 13 /* enable TLS (on by default) */
+
+#define SSL_ROLLBACK_DETECTION 14 /* for compatibility, default: on */
+#define SSL_NO_STEP_DOWN 15 /* (unsupported, deprecated, off) */
+#define SSL_BYPASS_PKCS11 16 /* (unsupported, deprecated, off) */
+#define SSL_NO_LOCKS 17 /* Don't use locks for protection */
+#define SSL_ENABLE_SESSION_TICKETS 18 /* Enable TLS SessionTicket */
+ /* extension (off by default) */
+#define SSL_ENABLE_DEFLATE 19 /* (unsupported, deprecated, off) */
+#define SSL_ENABLE_RENEGOTIATION 20 /* Values below (default: never) */
+#define SSL_REQUIRE_SAFE_NEGOTIATION 21 /* Peer must send Signaling */
+ /* Cipher Suite Value (SCSV) or */
+ /* Renegotiation Info (RI) */
+ /* extension in ALL handshakes. */
+ /* default: off */
+#define SSL_ENABLE_FALSE_START 22 /* Enable SSL false start (off by */
+ /* default, applies only to */
+ /* clients). False start is a */
+/* mode where an SSL client will start sending application data before
+ * verifying the server's Finished message. This means that we could end up
+ * sending data to an imposter. However, the data will be encrypted and
+ * only the true server can derive the session key. Thus, so long as the
+ * cipher isn't broken this is safe. The advantage of false start is that
+ * it saves a round trip for client-speaks-first protocols when performing a
+ * full handshake.
+ *
+ * In addition to enabling this option, the application must register a
+ * callback using the SSL_SetCanFalseStartCallback function.
+ */
+
+/* For SSL 3.0 and TLS 1.0, by default we prevent chosen plaintext attacks
+ * on SSL CBC mode cipher suites (see RFC 4346 Section F.3) by splitting
+ * non-empty application_data records into two records; the first record has
+ * only the first byte of plaintext, and the second has the rest.
+ *
+ * This only prevents the attack in the sending direction; the connection may
+ * still be vulnerable to such attacks if the peer does not implement a similar
+ * countermeasure.
+ *
+ * This protection mechanism is on by default; the default can be overridden by
+ * setting NSS_SSL_CBC_RANDOM_IV=0 in the environment prior to execution,
+ * and/or by the application setting the option SSL_CBC_RANDOM_IV to PR_FALSE.
+ *
+ * The per-record IV in TLS 1.1 and later adds one block of overhead per
+ * record, whereas this hack will add at least two blocks of overhead per
+ * record, so TLS 1.1+ will always be more efficient.
+ *
+ * Other implementations (e.g. some versions of OpenSSL, in some
+ * configurations) prevent the same attack by prepending an empty
+ * application_data record to every application_data record they send; we do
+ * not do that because some implementations cannot handle empty
+ * application_data records. Also, we only split application_data records and
+ * not other types of records, because some implementations will not accept
+ * fragmented records of some other types (e.g. some versions of NSS do not
+ * accept fragmented alerts).
+ */
+#define SSL_CBC_RANDOM_IV 23
+#define SSL_ENABLE_OCSP_STAPLING 24 /* Request OCSP stapling (client) */
+
+/* SSL_ENABLE_NPN is defunct and defaults to false.
+ * Using this option will not have any effect but won't produce an error. */
+#define SSL_ENABLE_NPN 25
+
+/* SSL_ENABLE_ALPN controls whether the ALPN extension is enabled for the
+ * initial handshake when application layer protocol negotiation is used.
+ * SSL_SetNextProtoNego or SSL_SetNextProtoCallback can be used to control
+ * the application layer protocol negotiation;
+ * ALPN is not negotiated for renegotiation handshakes, even though the ALPN
+ * specification defines a way to use ALPN during renegotiations.
+ * SSL_ENABLE_ALPN is currently enabled by default, but this may change in
+ * future versions.
+ */
+#define SSL_ENABLE_ALPN 26
+
+/* SSL_REUSE_SERVER_ECDHE_KEY controls whether the ECDHE server key is
+ * reused for multiple handshakes or generated each time.
+ * SSL_REUSE_SERVER_ECDHE_KEY is currently disabled by default.
+ * This socket option is for ECDHE, only. It is unrelated to DHE.
+ */
+#define SSL_REUSE_SERVER_ECDHE_KEY 27
+
+#define SSL_ENABLE_FALLBACK_SCSV 28 /* Send fallback SCSV in \
+ * handshakes. */
+
+/* SSL_ENABLE_SERVER_DHE controls whether DHE is enabled for the server socket.
+ */
+#define SSL_ENABLE_SERVER_DHE 29
+
+/* Use draft-ietf-tls-session-hash. Controls whether we offer the
+ * extended_master_secret extension which, when accepted, hashes
+ * the handshake transcript into the master secret. This option is
+ * enabled by default.
+ */
+#define SSL_ENABLE_EXTENDED_MASTER_SECRET 30
+
+/* Request Signed Certificate Timestamps via TLS extension (client) */
+#define SSL_ENABLE_SIGNED_CERT_TIMESTAMPS 31
+
+/* Ordinarily, when negotiating a TLS_DHE_* cipher suite the server picks the
+ * group. draft-ietf-tls-negotiated-ff-dhe changes this to use supported_groups
+ * (formerly supported_curves) to signal which pre-defined groups are OK.
+ *
+ * This option causes an NSS client to use this extension and demand that those
+ * groups be used. A client will signal any enabled DHE groups in the
+ * supported_groups extension and reject groups that don't match what it has
+ * enabled. A server will only negotiate TLS_DHE_* cipher suites if the
+ * client includes the extension.
+ *
+ * See SSL_NamedGroupConfig() for how to control which groups are enabled.
+ *
+ * This option cannot be enabled if NSS is not compiled with ECC support.
+ */
+#define SSL_REQUIRE_DH_NAMED_GROUPS 32
+
+/* Allow 0-RTT data (for TLS 1.3).
+ *
+ * When this option is set, the server's session tickets will contain
+ * a flag indicating that it accepts 0-RTT. When resuming such a
+ * session, PR_Write() on the client will be allowed immediately after
+ * starting the handshake and PR_Read() on the server will be allowed
+ * on the server to read that data. Calls to
+ * SSL_GetPreliminaryChannelInfo() and SSL_GetNextProto()
+ * can be made used during this period to learn about the channel
+ * parameters.
+ *
+ * The transition between the 0-RTT and 1-RTT modes is marked by the
+ * handshake callback. However, it is possible to force the completion
+ * of the handshake (and cause the handshake callback to be called)
+ * prior to reading all 0-RTT data using SSL_ForceHandshake(). To
+ * ensure that all early data is read before the handshake callback, any
+ * time that SSL_ForceHandshake() returns a PR_WOULD_BLOCK_ERROR, use
+ * PR_Read() to read all available data. If PR_Read() is called
+ * multiple times, this will result in the handshake completing, but the
+ * handshake callback will occur after early data has all been read.
+ *
+ * WARNING: 0-RTT data has different anti-replay and PFS properties than
+ * the rest of the TLS data. See [draft-ietf-tls-tls13; Section 8]
+ * for more details.
+ *
+ * Note: when DTLS 1.3 is in use, any 0-RTT data received after EndOfEarlyData
+ * (e.g., because of reordering) is discarded.
+ */
+#define SSL_ENABLE_0RTT_DATA 33
+
+/* Sets a limit to the size of encrypted records (see
+ * draft-ietf-tls-record-limit). This is the value that is advertised to peers,
+ * not a limit on the size of records that will be created. Setting this value
+ * reduces the size of records that will be received (not sent).
+ *
+ * This limit applies to the plaintext, but the records that appear on the wire
+ * will be bigger. This doesn't include record headers, IVs, block cipher
+ * padding, and authentication tags or MACs.
+ *
+ * NSS always advertises the record size limit extension. If this option is not
+ * set, the extension will contain the maximum allowed size for the selected TLS
+ * version (currently this is 16384 or 2^14 for TLS 1.2 and lower and 16385 for
+ * TLS 1.3).
+ *
+ * By default, NSS creates records that are the maximum size possible, using all
+ * the data that was written by the application. Writes larger than the maximum
+ * are split into maximum sized records, and any remainder (unless
+ * SSL_CBC_RANDOM_IV is enabled and active). If a peer advertises a record size
+ * limit then that value is used instead.
+ */
+#define SSL_RECORD_SIZE_LIMIT 34
+
+/* Enables TLS 1.3 compatibility mode. In this mode, the client includes a fake
+ * session ID in the handshake and sends a ChangeCipherSpec. A server will
+ * always use the setting chosen by the client, so the value of this option has
+ * no effect for a server. This setting is ignored for DTLS. */
+#define SSL_ENABLE_TLS13_COMPAT_MODE 35
+
+/* Enables the sending of DTLS records using the short (two octet) record
+ * header. Only do this if there are 2^10 or fewer packets in flight at a time;
+ * using this with a larger number of packets in flight could mean that packets
+ * are dropped if there is reordering.
+ *
+ * This applies to TLS 1.3 only. This is not a parameter that is negotiated
+ * during the TLS handshake. Unlike other socket options, this option can be
+ * changed after a handshake is complete.
+ */
+#define SSL_ENABLE_DTLS_SHORT_HEADER 36
+
+/*
+ * Enables the processing of the downgrade sentinel that can be added to the
+ * ServerHello.random by a server that supports Section 4.1.3 of TLS 1.3
+ * [RFC8446]. This sentinel will always be generated by a server that
+ * negotiates a version lower than its maximum, this only controls whether a
+ * client will treat receipt of a value that indicates a downgrade as an error.
+ */
+#define SSL_ENABLE_HELLO_DOWNGRADE_CHECK 37
+
+/* Enables the SSLv2-compatible ClientHello for servers. NSS does not support
+ * SSLv2 and will never send an SSLv2-compatible ClientHello as a client. An
+ * NSS server with this option enabled will accept a ClientHello that is
+ * v2-compatible as defined in Appendix E.1 of RFC 6101.
+ *
+ * This is disabled by default and will be removed in a future version. */
+#define SSL_ENABLE_V2_COMPATIBLE_HELLO 38
+
+/* Enables the post-handshake authentication in TLS 1.3. If it is set
+ * to PR_TRUE, the client will send the "post_handshake_auth"
+ * extension to indicate that it will process CertificateRequest
+ * messages after handshake.
+ *
+ * This option applies only to clients. For a server, the
+ * SSL_SendCertificateRequest can be used to request post-handshake
+ * authentication.
+ */
+#define SSL_ENABLE_POST_HANDSHAKE_AUTH 39
+
+/* Enables the delegated credentials extension (draft-ietf-tls-subcerts). When
+ * enabled, a client that supports TLS 1.3 will indicate willingness to
+ * negotiate a delegated credential (DC). Note that client-delegated credentials
+ * are not currently supported.
+ *
+ * If support is indicated, the peer may use a DC to authenticate itself. The DC
+ * is sent as an extension to the peer's end-entity certificate; the end-entity
+ * certificate is used to verify the DC, which in turn is used to verify the
+ * handshake. DCs effectively extend the certificate chain by one, but only
+ * within the context of TLS. Once issued, DCs can't be revoked; in order to
+ * mitigate the damage in case the secret key is compromised, the DC is only
+ * valid for a short time (days, hours, or even minutes).
+ *
+ * This library implements draft-07 of the protocol spec.
+ */
+#define SSL_ENABLE_DELEGATED_CREDENTIALS 40
+
+/* Causes TLS (>=1.3) to suppress the EndOfEarlyData message in stream mode.
+ *
+ * This is not advisable in general, but the message only exists to delineate
+ * early data in a streamed connection. DTLS does not use this message as a
+ * result. The integration of TLS with QUIC, which uses a record/packet
+ * protection layer that is unreliable, also does not use this message.
+ *
+ * On the server, this requires that SSL_RecordLayerData be used.
+ * EndOfEarlyData is otherwise needed to drive key changes. Additionally,
+ * servers that use this API must check that handshake messages (Certificate,
+ * CertificateVerify, and Finished in particular) are only received in epoch 2
+ * (Handshake). SSL_RecordLayerData will accept these handshake messages if
+ * they are passed as epoch 1 (Early Data) in a single call.
+ *
+ * Using this option will cause connections to fail if early data is attempted
+ * and the peer expects this message.
+ */
+#define SSL_SUPPRESS_END_OF_EARLY_DATA 41
+
+/* Enables TLS GREASE (specified in RFC8701, following Chrome 55 implementation
+ * decisions).
+ *
+ * If enabled and the client's ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 or
+ * the server's ss->version >= SSL_LIBRARY_VERSION_TLS_1_3, this adds random
+ * GREASE values to:
+ * - ClientHello (Client):
+ * - A cipher_suite value to the cipher_suites field.
+ * - An empty and a 1B zeroed payload extension.
+ * - A named group value to the supported_groups extension and a
+ * KeyShareEntry value for the added named group.
+ * - A signature algorithm value to the signature_algorithms extension.
+ * - A version value to the supported_versions extension.
+ * - A PskKeyExchangeMode value to the psk_key_exchange_modes extension.
+ * - A alpn value to the application_layer_protocol_negotiation extension.
+ *
+ * - CertificateRequest (Server):
+ * - An empty extension.
+ * - A signature algorithm value to the signature_algorithms extension.
+ *
+ * - NewSessionTicket (Server):
+ * - An empty extension.
+ *
+ * GREASE values MUST nerver be negotiated but ignored.
+ */
+#define SSL_ENABLE_GREASE 42
+
+/* Enables TLS ClientHello Extension Permutation.
+ *
+ * On a TLS ClientHello all extensions but the Psk extension
+ * (which MUST be last) will be sent in randomly shuffeld order.
+ */
+#define SSL_ENABLE_CH_EXTENSION_PERMUTATION 43
+
+#ifdef SSL_DEPRECATED_FUNCTION
+/* Old deprecated function names */
+SSL_IMPORT SECStatus SSL_Enable(PRFileDesc *fd, int option, PRIntn on);
+SSL_IMPORT SECStatus SSL_EnableDefault(int option, PRIntn on);
+#endif
+
+/* Set (and get) options for sockets and defaults for newly created sockets.
+ *
+ * While the |val| parameter of these methods is PRIntn, options only support
+ * two values by default: PR_TRUE or PR_FALSE. The documentation of specific
+ * options will explain if other values are permitted.
+ */
+SSL_IMPORT SECStatus SSL_OptionSet(PRFileDesc *fd, PRInt32 option, PRIntn val);
+SSL_IMPORT SECStatus SSL_OptionGet(PRFileDesc *fd, PRInt32 option, PRIntn *val);
+SSL_IMPORT SECStatus SSL_OptionSetDefault(PRInt32 option, PRIntn val);
+SSL_IMPORT SECStatus SSL_OptionGetDefault(PRInt32 option, PRIntn *val);
+SSL_IMPORT SECStatus SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle);
+
+/* SSLNextProtoCallback is called during the handshake for the server, when an
+ * Application-Layer Protocol Negotiation (ALPN) extension has been received
+ * from the client. |protos| and |protosLen| define a buffer which contains the
+ * client's advertisement.
+ * |protoOut| is a buffer provided by the caller, of length 255 (the maximum
+ * allowed by the protocol). On successful return, the protocol to be announced
+ * to the server will be in |protoOut| and its length in |*protoOutLen|.
+ *
+ * The callback must return SECFailure or SECSuccess (not SECWouldBlock).
+ */
+typedef SECStatus(PR_CALLBACK *SSLNextProtoCallback)(
+ void *arg,
+ PRFileDesc *fd,
+ const unsigned char *protos,
+ unsigned int protosLen,
+ unsigned char *protoOut,
+ unsigned int *protoOutLen,
+ unsigned int protoMaxOut);
+
+/* SSL_SetNextProtoCallback sets a callback function to handle ALPN Negotiation.
+ * It causes a client to advertise ALPN. */
+SSL_IMPORT SECStatus SSL_SetNextProtoCallback(PRFileDesc *fd,
+ SSLNextProtoCallback callback,
+ void *arg);
+
+/* SSL_SetNextProtoNego can be used as an alternative to
+ * SSL_SetNextProtoCallback.
+ *
+ * Using this function allows client and server to transparently support ALPN.
+ * The same set of protocols will be advertised via ALPN and, if the server
+ * uses ALPN to select a protocol, SSL_GetNextProto will return
+ * SSL_NEXT_PROTO_SELECTED as the state.
+ *
+ * Because the predecessor to ALPN, NPN, used the first protocol as the fallback
+ * protocol, when sending an ALPN extension, the first protocol is moved to the
+ * end of the list. This indicates that the fallback protocol is the least
+ * preferred. The other protocols should be in preference order.
+ *
+ * The supported protocols are specified in |data| in wire-format (8-bit
+ * length-prefixed). For example: "\010http/1.1\006spdy/2".
+ *
+ * An empty value (i.e., where |length| is 0 and |data| is any value,
+ * including NULL) forcibly disables ALPN. In this mode, the server will
+ * reject any ClientHello that includes the ALPN extension.
+ *
+ * Calling this function overrides the callback previously set by
+ * SSL_SetNextProtoCallback. */
+SSL_IMPORT SECStatus SSL_SetNextProtoNego(PRFileDesc *fd,
+ const unsigned char *data,
+ unsigned int length);
+
+typedef enum SSLNextProtoState {
+ SSL_NEXT_PROTO_NO_SUPPORT = 0, /* No peer support */
+ SSL_NEXT_PROTO_NEGOTIATED = 1, /* Mutual agreement */
+ SSL_NEXT_PROTO_NO_OVERLAP = 2, /* No protocol overlap found */
+ SSL_NEXT_PROTO_SELECTED = 3, /* Server selected proto (ALPN) */
+ SSL_NEXT_PROTO_EARLY_VALUE = 4 /* We are in 0-RTT using this value. */
+} SSLNextProtoState;
+
+/* SSL_GetNextProto can be used in the HandshakeCallback or any time after
+ * a handshake to retrieve the result of the Next Protocol negotiation.
+ *
+ * The length of the negotiated protocol, if any, is written into *bufLen.
+ * If the negotiated protocol is longer than bufLenMax, then SECFailure is
+ * returned. Otherwise, the negotiated protocol, if any, is written into buf,
+ * and SECSuccess is returned. */
+SSL_IMPORT SECStatus SSL_GetNextProto(PRFileDesc *fd,
+ SSLNextProtoState *state,
+ unsigned char *buf,
+ unsigned int *bufLen,
+ unsigned int bufLenMax);
+
+/*
+** Control ciphers that SSL uses. If on is non-zero then the named cipher
+** is enabled, otherwise it is disabled.
+** The "cipher" values are defined in sslproto.h (the SSL_EN_* values).
+** EnableCipher records user preferences.
+** SetPolicy sets the policy according to the policy module.
+*/
+#ifdef SSL_DEPRECATED_FUNCTION
+/* Old deprecated function names */
+SSL_IMPORT SECStatus SSL_EnableCipher(long which, PRBool enabled);
+SSL_IMPORT SECStatus SSL_SetPolicy(long which, int policy);
+#endif
+
+/* New function names */
+SSL_IMPORT SECStatus SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 cipher, PRBool enabled);
+SSL_IMPORT SECStatus SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 cipher, PRBool *enabled);
+SSL_IMPORT SECStatus SSL_CipherPrefSetDefault(PRInt32 cipher, PRBool enabled);
+SSL_IMPORT SECStatus SSL_CipherPrefGetDefault(PRInt32 cipher, PRBool *enabled);
+SSL_IMPORT SECStatus SSL_CipherPolicySet(PRInt32 cipher, PRInt32 policy);
+SSL_IMPORT SECStatus SSL_CipherPolicyGet(PRInt32 cipher, PRInt32 *policy);
+
+/*
+** Control for TLS signature schemes for TLS 1.2 and 1.3.
+**
+** This governs what signature schemes (or algorithms) are sent by a client in
+** the signature_algorithms extension. A client will not accept a signature
+** from a server unless it uses an enabled algorithm.
+**
+** This also governs what the server sends in the supported_signature_algorithms
+** field of a CertificateRequest.
+**
+** This changes what the server uses to sign ServerKeyExchange and
+** CertificateVerify messages. An endpoint uses the first entry from this list
+** that is compatible with both its certificate and its peer's supported
+** values.
+**
+** This configuration affects TLS 1.2, but the combination of EC group and hash
+** algorithm is interpreted loosely to be compatible with other implementations.
+** For TLS 1.2, NSS will ignore the curve group when generating or verifying
+** ECDSA signatures. For example, a P-384 ECDSA certificate is used with
+** SHA-256 if ssl_sig_ecdsa_secp256r1_sha256 is enabled.
+**
+** Omitting SHA-256 schemes from this list might be foolish. Support is
+** mandatory in TLS 1.2 and 1.3 and there might be interoperability issues.
+*/
+SSL_IMPORT SECStatus SSL_SignatureSchemePrefSet(
+ PRFileDesc *fd, const SSLSignatureScheme *schemes, unsigned int count);
+
+/* Deprecated, use SSL_SignatureSchemePrefSet() instead. */
+SSL_IMPORT SECStatus SSL_SignaturePrefSet(
+ PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
+ unsigned int count);
+
+/*
+** Get the currently configured signature schemes.
+**
+** The schemes are written to |schemes| but not if there are more than
+** |maxCount| values configured. The number of schemes that are in use are
+** written to |count|. This fails if |maxCount| is insufficiently large.
+*/
+SSL_IMPORT SECStatus SSL_SignatureSchemePrefGet(
+ PRFileDesc *fd, SSLSignatureScheme *algorithms, unsigned int *count,
+ unsigned int maxCount);
+
+/* Deprecated, use SSL_SignatureSchemePrefGet() instead. */
+SSL_IMPORT SECStatus SSL_SignaturePrefGet(
+ PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms, unsigned int *count,
+ unsigned int maxCount);
+
+/*
+** Returns the maximum number of signature algorithms that are supported and
+** can be set or retrieved using SSL_SignatureSchemePrefSet or
+** SSL_SignatureSchemePrefGet.
+*/
+SSL_IMPORT unsigned int SSL_SignatureMaxCount(void);
+
+/*
+** Define custom priorities for EC and FF groups used in DH key exchange and EC
+** groups for ECDSA. This only changes the order of enabled lists (and thus
+** their priorities) and enables all groups in |groups| while disabling all other
+** groups.
+*/
+SSL_IMPORT SECStatus SSL_NamedGroupConfig(PRFileDesc *fd,
+ const SSLNamedGroup *groups,
+ unsigned int num_groups);
+
+/*
+** Configure the socket to configure additional key shares. Normally when a TLS
+** 1.3 ClientHello is sent, just one key share is included using the first
+** preference group (as set by SSL_NamedGroupConfig). If the server decides to
+** pick a different group for key exchange, it is forced to send a
+** HelloRetryRequest, which adds an entire round trip of latency.
+**
+** This function can be used to configure libssl to generate additional key
+** shares when sending a TLS 1.3 ClientHello. If |count| is set to a non-zero
+** value, then additional key shares are generated. Shares are added in the
+** preference order set in SSL_NamedGroupConfig. |count| can be set to any
+** value; NSS limits the number of shares to the number of supported groups.
+*/
+SSL_IMPORT SECStatus SSL_SendAdditionalKeyShares(PRFileDesc *fd,
+ unsigned int count);
+
+/* Deprecated: use SSL_NamedGroupConfig() instead.
+** SSL_DHEGroupPrefSet is used to configure the set of allowed/enabled DHE group
+** parameters that can be used by NSS for the given server socket.
+** The first item in the array is used as the default group, if no other
+** selection criteria can be used by NSS.
+** The set is provided as an array of identifiers as defined by SSLDHEGroupType.
+** If more than one group identifier is provided, NSS will select the one to use.
+** For example, a TLS extension sent by the client might indicate a preference.
+*/
+SSL_IMPORT SECStatus SSL_DHEGroupPrefSet(PRFileDesc *fd,
+ const SSLDHEGroupType *groups,
+ PRUint16 num_groups);
+
+/* Enable the use of a DHE group that's smaller than the library default,
+** for backwards compatibility reasons. The DH parameters will be created
+** at the time this function is called, which might take a very long time.
+** The function will block until generation is completed.
+** The intention is to enforce that fresh and safe parameters are generated
+** each time a process is started.
+** At the time this API was initially implemented, the API will enable the
+** use of 1024 bit DHE parameters. This value might get increased in future
+** versions of NSS.
+**
+** It is allowed to call this API will a NULL value for parameter fd,
+** which will prepare the global parameters that NSS will reuse for the remainder
+** of the process lifetime. This can be used early after startup of a process,
+** to avoid a delay when handling incoming client connections.
+** This preparation with a NULL for parameter fd will NOT enable the weak group
+** on sockets. The function needs to be called again for every socket that
+** should use the weak group.
+**
+** It is allowed to use this API in combination with the SSL_NamedGroupConfig API.
+** If both APIs have been called, the weakest group will be used, unless it is
+** certain that the client supports larger group parameters. The weak group will
+** be used as the default group for TLS <= 1.2, overriding the preference for
+** the first group potentially set with a call to SSL_NamedGroupConfig.
+*/
+SSL_IMPORT SECStatus SSL_EnableWeakDHEPrimeGroup(PRFileDesc *fd, PRBool enabled);
+
+/* SSL Version Range API
+**
+** This API should be used to control SSL 3.0 & TLS support instead of the
+** older SSL_Option* API; however, the SSL_Option* API MUST still be used to
+** control SSL 2.0 support. In this version of libssl, SSL 3.0 and TLS 1.0 are
+** enabled by default. Future versions of libssl may change which versions of
+** the protocol are enabled by default.
+**
+** The SSLProtocolVariant enum indicates whether the protocol is of type
+** stream or datagram. This must be provided to the functions that do not
+** take an fd. Functions which take an fd will get the variant from the fd,
+** which is typed.
+**
+** Using the new version range API in conjunction with the older
+** SSL_OptionSet-based API for controlling the enabled protocol versions may
+** cause unexpected results. Going forward, we guarantee only the following:
+**
+** SSL_OptionGet(SSL_ENABLE_TLS) will return PR_TRUE if *ANY* versions of TLS
+** are enabled.
+**
+** SSL_OptionSet(SSL_ENABLE_TLS, PR_FALSE) will disable *ALL* versions of TLS,
+** including TLS 1.0 and later.
+**
+** The above two properties provide compatibility for applications that use
+** SSL_OptionSet to implement the insecure fallback from TLS 1.x to SSL 3.0.
+**
+** SSL_OptionSet(SSL_ENABLE_TLS, PR_TRUE) will enable TLS 1.0, and may also
+** enable some later versions of TLS, if it is necessary to do so in order to
+** keep the set of enabled versions contiguous. For example, if TLS 1.2 is
+** enabled, then after SSL_OptionSet(SSL_ENABLE_TLS, PR_TRUE), TLS 1.0,
+** TLS 1.1, and TLS 1.2 will be enabled, and the call will have no effect on
+** whether SSL 3.0 is enabled. If no later versions of TLS are enabled at the
+** time SSL_OptionSet(SSL_ENABLE_TLS, PR_TRUE) is called, then no later
+** versions of TLS will be enabled by the call.
+**
+** SSL_OptionSet(SSL_ENABLE_SSL3, PR_FALSE) will disable SSL 3.0, and will not
+** change the set of TLS versions that are enabled.
+**
+** SSL_OptionSet(SSL_ENABLE_SSL3, PR_TRUE) will enable SSL 3.0, and may also
+** enable some versions of TLS if TLS 1.1 or later is enabled at the time of
+** the call, the same way SSL_OptionSet(SSL_ENABLE_TLS, PR_TRUE) works, in
+** order to keep the set of enabled versions contiguous.
+*/
+
+/* Returns, in |*vrange|, the range of SSL3/TLS versions supported for the
+** given protocol variant by the version of libssl linked-to at runtime.
+*/
+SSL_IMPORT SECStatus SSL_VersionRangeGetSupported(
+ SSLProtocolVariant protocolVariant, SSLVersionRange *vrange);
+
+/* Returns, in |*vrange|, the range of SSL3/TLS versions enabled by default
+** for the given protocol variant.
+*/
+SSL_IMPORT SECStatus SSL_VersionRangeGetDefault(
+ SSLProtocolVariant protocolVariant, SSLVersionRange *vrange);
+
+/* Sets the range of enabled-by-default SSL3/TLS versions for the given
+** protocol variant to |*vrange|.
+*/
+SSL_IMPORT SECStatus SSL_VersionRangeSetDefault(
+ SSLProtocolVariant protocolVariant, const SSLVersionRange *vrange);
+
+/* Returns, in |*vrange|, the range of enabled SSL3/TLS versions for |fd|. */
+SSL_IMPORT SECStatus SSL_VersionRangeGet(PRFileDesc *fd,
+ SSLVersionRange *vrange);
+
+/* Sets the range of enabled SSL3/TLS versions for |fd| to |*vrange|. */
+SSL_IMPORT SECStatus SSL_VersionRangeSet(PRFileDesc *fd,
+ const SSLVersionRange *vrange);
+
+/* Sets the version to check the server random against for the
+ * fallback check defined in [draft-ietf-tls-tls13-11 Section 6.3.1.1].
+ * This function is provided to allow for detection of forced downgrade
+ * attacks against client-side reconnect-and-fallback outside of TLS
+ * by setting |version| to be that of the original connection, rather
+ * than that of the new connection.
+ *
+ * The default, which can also be enabled by setting |version| to
+ * zero, is just to check against the max version in the
+ * version range (see SSL_VersionRangeSet). */
+SSL_IMPORT SECStatus SSL_SetDowngradeCheckVersion(PRFileDesc *fd,
+ PRUint16 version);
+
+/* Values for "policy" argument to SSL_CipherPolicySet */
+/* Values returned by SSL_CipherPolicyGet. */
+#define SSL_NOT_ALLOWED 0 /* or invalid or unimplemented */
+#define SSL_ALLOWED 1
+#define SSL_RESTRICTED 2 /* only with "Step-Up" certs. */
+
+/* Values for "on" with SSL_REQUIRE_CERTIFICATE. */
+#define SSL_REQUIRE_NEVER ((PRBool)0)
+#define SSL_REQUIRE_ALWAYS ((PRBool)1)
+#define SSL_REQUIRE_FIRST_HANDSHAKE ((PRBool)2)
+#define SSL_REQUIRE_NO_ERROR ((PRBool)3)
+
+/* Values for "on" with SSL_ENABLE_RENEGOTIATION */
+/* Never renegotiate at all. */
+#define SSL_RENEGOTIATE_NEVER ((PRBool)0)
+/* Renegotiate without restriction, whether or not the peer's client hello */
+/* bears the renegotiation info extension. Vulnerable, as in the past. */
+#define SSL_RENEGOTIATE_UNRESTRICTED ((PRBool)1)
+/* Only renegotiate if the peer's hello bears the TLS renegotiation_info */
+/* extension. This is safe renegotiation. */
+#define SSL_RENEGOTIATE_REQUIRES_XTN ((PRBool)2)
+/* Disallow unsafe renegotiation in server sockets only, but allow clients */
+/* to continue to renegotiate with vulnerable servers. */
+/* This value should only be used during the transition period when few */
+/* servers have been upgraded. */
+#define SSL_RENEGOTIATE_TRANSITIONAL ((PRBool)3)
+
+/*
+** Reset the handshake state for fd. This will make the complete SSL
+** handshake protocol execute from the ground up on the next i/o
+** operation.
+*/
+SSL_IMPORT SECStatus SSL_ResetHandshake(PRFileDesc *fd, PRBool asServer);
+
+/*
+** Force the handshake for fd to complete immediately. This blocks until
+** the complete SSL handshake protocol is finished.
+*/
+SSL_IMPORT SECStatus SSL_ForceHandshake(PRFileDesc *fd);
+
+/*
+** Same as above, but with an I/O timeout.
+ */
+SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd,
+ PRIntervalTime timeout);
+
+/*
+** Query security status of socket. *on is set to one if security is
+** enabled. *keySize will contain the stream key size used. *issuer will
+** contain the RFC1485 verison of the name of the issuer of the
+** certificate at the other end of the connection. For a client, this is
+** the issuer of the server's certificate; for a server, this is the
+** issuer of the client's certificate (if any). Subject is the subject of
+** the other end's certificate. The pointers can be zero if the desired
+** data is not needed. All strings returned by this function are owned
+** by the caller, and need to be freed with PORT_Free.
+*/
+SSL_IMPORT SECStatus SSL_SecurityStatus(PRFileDesc *fd, int *on, char **cipher,
+ int *keySize, int *secretKeySize,
+ char **issuer, char **subject);
+
+/* Values for "on" */
+#define SSL_SECURITY_STATUS_NOOPT -1
+#define SSL_SECURITY_STATUS_OFF 0
+#define SSL_SECURITY_STATUS_ON_HIGH 1
+#define SSL_SECURITY_STATUS_ON_LOW 2
+#define SSL_SECURITY_STATUS_FORTEZZA 3 /* NO LONGER SUPPORTED */
+
+/*
+** Return the certificate for our SSL peer. If the client calls this
+** it will always return the server's certificate. If the server calls
+** this, it may return NULL if client authentication is not enabled or
+** if the client had no certificate when asked.
+** "fd" the socket "file" descriptor
+*/
+SSL_IMPORT CERTCertificate *SSL_PeerCertificate(PRFileDesc *fd);
+
+/*
+** Return the certificates presented by the SSL peer. If the SSL peer
+** did not present certificates, return NULL with the
+** SSL_ERROR_NO_CERTIFICATE error. On failure, return NULL with an error
+** code other than SSL_ERROR_NO_CERTIFICATE.
+** "fd" the socket "file" descriptor
+*/
+SSL_IMPORT CERTCertList *SSL_PeerCertificateChain(PRFileDesc *fd);
+
+/* SSL_PeerStapledOCSPResponses returns the OCSP responses that were provided
+ * by the TLS server. The return value is a pointer to an internal SECItemArray
+ * that contains the returned OCSP responses; it is only valid until the
+ * callback function that calls SSL_PeerStapledOCSPResponses returns.
+ *
+ * If no OCSP responses were given by the server then the result will be empty.
+ * If there was an error, then the result will be NULL.
+ *
+ * You must set the SSL_ENABLE_OCSP_STAPLING option to enable OCSP stapling.
+ * to be provided by a server.
+ *
+ * libssl does not do any validation of the OCSP response itself; the
+ * authenticate certificate hook is responsible for doing so. The default
+ * authenticate certificate hook, SSL_AuthCertificate, does not implement
+ * any OCSP stapling funtionality, but this may change in future versions.
+ */
+SSL_IMPORT const SECItemArray *SSL_PeerStapledOCSPResponses(PRFileDesc *fd);
+
+/* SSL_PeerSignedCertTimestamps returns the signed_certificate_timestamp
+ * extension data provided by the TLS server. The return value is a pointer
+ * to an internal SECItem that contains the returned response (as a serialized
+ * SignedCertificateTimestampList, see RFC 6962). The returned pointer is only
+ * valid until the callback function that calls SSL_PeerSignedCertTimestamps
+ * (e.g. the authenticate certificate hook, or the handshake callback) returns.
+ *
+ * If no Signed Certificate Timestamps were given by the server then the result
+ * will be empty. If there was an error, then the result will be NULL.
+ *
+ * You must set the SSL_ENABLE_SIGNED_CERT_TIMESTAMPS option to indicate support
+ * for Signed Certificate Timestamps to a server.
+ *
+ * libssl does not do any parsing or validation of the response itself.
+ */
+SSL_IMPORT const SECItem *SSL_PeerSignedCertTimestamps(PRFileDesc *fd);
+
+/* SSL_SetStapledOCSPResponses stores an array of one or multiple OCSP responses
+ * in the fd's data, which may be sent as part of a server side cert_status
+ * handshake message. Parameter |responses| is for the server certificate of
+ * the key exchange type |kea|.
+ * The function will duplicate the responses array.
+ *
+ * Deprecated: see SSL_ConfigSecureServer for details.
+ */
+SSL_IMPORT SECStatus
+SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses,
+ SSLKEAType kea);
+
+/*
+ * SSL_SetSignedCertTimestamps stores serialized signed_certificate_timestamp
+ * extension data in the fd. The signed_certificate_timestamp data is sent
+ * during the handshake (if requested by the client). Parameter |scts|
+ * is for the server certificate of the key exchange type |kea|.
+ * The function will duplicate the provided data item. To clear previously
+ * set data for a given key exchange type |kea|, pass NULL to |scts|.
+ *
+ * Deprecated: see SSL_ConfigSecureServer for details.
+ */
+SSL_IMPORT SECStatus
+SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts,
+ SSLKEAType kea);
+
+/*
+** Authenticate certificate hook. Called when a certificate comes in
+** (because of SSL_REQUIRE_CERTIFICATE in SSL_Enable) to authenticate the
+** certificate.
+**
+** The authenticate certificate hook must return SECSuccess to indicate the
+** certificate is valid, SECFailure to indicate the certificate is invalid,
+** or SECWouldBlock if the application will authenticate the certificate
+** asynchronously. SECWouldBlock is only supported for non-blocking sockets.
+**
+** If the authenticate certificate hook returns SECFailure, then the bad cert
+** hook will be called. The bad cert handler is NEVER called if the
+** authenticate certificate hook returns SECWouldBlock. If the application
+** needs to handle and/or override a bad cert, it should do so before it
+** calls SSL_AuthCertificateComplete (modifying the error it passes to
+** SSL_AuthCertificateComplete as needed).
+**
+** See the documentation for SSL_AuthCertificateComplete for more information
+** about the asynchronous behavior that occurs when the authenticate
+** certificate hook returns SECWouldBlock.
+**
+** RFC 6066 says that clients should send the bad_certificate_status_response
+** alert when they encounter an error processing the stapled OCSP response.
+** libssl does not provide a way for the authenticate certificate hook to
+** indicate that an OCSP error (SEC_ERROR_OCSP_*) that it returns is an error
+** in the stapled OCSP response or an error in some other OCSP response.
+** Further, NSS does not provide a convenient way to control or determine
+** which OCSP response(s) were used to validate a certificate chain.
+** Consequently, the current version of libssl does not ever send the
+** bad_certificate_status_response alert. This may change in future releases.
+*/
+typedef SECStatus(PR_CALLBACK *SSLAuthCertificate)(void *arg, PRFileDesc *fd,
+ PRBool checkSig,
+ PRBool isServer);
+
+SSL_IMPORT SECStatus SSL_AuthCertificateHook(PRFileDesc *fd,
+ SSLAuthCertificate f,
+ void *arg);
+
+/* An implementation of the certificate authentication hook */
+SSL_IMPORT SECStatus SSL_AuthCertificate(void *arg, PRFileDesc *fd,
+ PRBool checkSig, PRBool isServer);
+
+/*
+ * Prototype for SSL callback to get client auth data from the application.
+ * arg - application passed argument
+ * caNames - pointer to distinguished names of CAs that the server likes
+ * pRetCert - pointer to pointer to cert, for return of cert
+ * pRetKey - pointer to key pointer, for return of key
+ * Return value can be one of {SECSuccess, SECFailure, SECWouldBlock}
+ *
+ * If SECSuccess, pRetCert and pRetKey should be set to the selected
+ * client cert and private key respectively. If SECFailure or SECWouldBlock
+ * they should not be changed.
+ *
+ * Ownership of pRetCert and pRetKey passes to NSS. The application must not
+ * mutate or free the structures after passing them to NSS.
+ *
+ * Returning SECWouldBlock will block the handshake until SSL_ClientCertCallbackComplete
+ * is called. Note that references to *caNames should not be kept after SSLGetClientAuthData
+ * returns. Instead, take a copy of the data.
+ *
+ * See also the comments for SSL_ClientCertCallbackComplete.
+ */
+typedef SECStatus(PR_CALLBACK *SSLGetClientAuthData)(void *arg,
+ PRFileDesc *fd,
+ CERTDistNames *caNames,
+ CERTCertificate **pRetCert, /*return */
+ SECKEYPrivateKey **pRetKey); /* return */
+
+/*
+ * Set the client side callback for SSL to retrieve user's private key
+ * and certificate.
+ * fd - the file descriptor for the connection in question
+ * f - the application's callback that delivers the key and cert
+ * a - application specific data
+ */
+SSL_IMPORT SECStatus SSL_GetClientAuthDataHook(PRFileDesc *fd,
+ SSLGetClientAuthData f, void *a);
+
+/*
+** SNI extension processing callback function.
+** It is called when SSL socket receives SNI extension in ClientHello message.
+** Upon this callback invocation, application is responsible to reconfigure the
+** socket with the data for a particular server name.
+** There are three potential outcomes of this function invocation:
+** * application does not recognize the name or the type and wants the
+** "unrecognized_name" alert be sent to the client. In this case the callback
+** function must return SSL_SNI_SEND_ALERT status.
+** * application does not recognize the name, but wants to continue with
+** the handshake using the current socket configuration. In this case,
+** no socket reconfiguration is needed and the function should return
+** SSL_SNI_CURRENT_CONFIG_IS_USED.
+** * application recognizes the name and reconfigures the socket with
+** appropriate certs, key, etc. There are many ways to reconfigure. NSS
+** provides SSL_ReconfigFD function that can be used to update the socket
+** data from model socket. To continue with the rest of the handshake, the
+** implementation function should return an index of a name it has chosen.
+** LibSSL will ignore any SNI extension received in a ClientHello message
+** if application does not register a SSLSNISocketConfig callback.
+** Each type field of SECItem indicates the name type.
+** NOTE: currently RFC3546 defines only one name type: sni_host_name.
+** Client is allowed to send only one name per known type. LibSSL will
+** send an "unrecognized_name" alert if SNI extension name list contains more
+** then one name of a type.
+*/
+typedef PRInt32(PR_CALLBACK *SSLSNISocketConfig)(PRFileDesc *fd,
+ const SECItem *srvNameArr,
+ PRUint32 srvNameArrSize,
+ void *arg);
+
+/*
+** SSLSNISocketConfig should return an index within 0 and srvNameArrSize-1
+** when it has reconfigured the socket fd to use certs and keys, etc
+** for a specific name. There are two other allowed return values. One
+** tells libSSL to use the default cert and key. The other tells libSSL
+** to send the "unrecognized_name" alert. These values are:
+**/
+#define SSL_SNI_CURRENT_CONFIG_IS_USED -1
+#define SSL_SNI_SEND_ALERT -2
+
+/*
+** Set application implemented SNISocketConfig callback.
+*/
+SSL_IMPORT SECStatus SSL_SNISocketConfigHook(PRFileDesc *fd,
+ SSLSNISocketConfig f,
+ void *arg);
+
+/*
+** Reconfigure fd SSL socket with model socket parameters. Sets
+** server certs and keys, list of trust anchor, socket options
+** and all SSL socket call backs and parameters.
+*/
+SSL_IMPORT PRFileDesc *SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd);
+
+/*
+ * Set the client side argument for SSL to retrieve PKCS #11 pin.
+ * fd - the file descriptor for the connection in question
+ * a - pkcs11 application specific data
+ */
+SSL_IMPORT SECStatus SSL_SetPKCS11PinArg(PRFileDesc *fd, void *a);
+
+/*
+** These are callbacks for dealing with SSL alerts.
+ */
+
+typedef PRUint8 SSLAlertLevel;
+typedef PRUint8 SSLAlertDescription;
+
+typedef struct {
+ SSLAlertLevel level;
+ SSLAlertDescription description;
+} SSLAlert;
+
+typedef void(PR_CALLBACK *SSLAlertCallback)(const PRFileDesc *fd, void *arg,
+ const SSLAlert *alert);
+
+SSL_IMPORT SECStatus SSL_AlertReceivedCallback(PRFileDesc *fd, SSLAlertCallback cb,
+ void *arg);
+SSL_IMPORT SECStatus SSL_AlertSentCallback(PRFileDesc *fd, SSLAlertCallback cb,
+ void *arg);
+/*
+** This is a callback for dealing with server certs that are not authenticated
+** by the client. The client app can decide that it actually likes the
+** cert by some external means and restart the connection.
+**
+** The bad cert hook must return SECSuccess to override the result of the
+** authenticate certificate hook, SECFailure if the certificate should still be
+** considered invalid, or SECWouldBlock if the application will authenticate
+** the certificate asynchronously. SECWouldBlock is only supported for
+** non-blocking sockets.
+**
+** See the documentation for SSL_AuthCertificateComplete for more information
+** about the asynchronous behavior that occurs when the bad cert hook returns
+** SECWouldBlock.
+*/
+typedef SECStatus(PR_CALLBACK *SSLBadCertHandler)(void *arg, PRFileDesc *fd);
+SSL_IMPORT SECStatus SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f,
+ void *arg);
+
+/*
+** Configure SSL socket for running a secure server. Needs the
+** certificate for the server and the servers private key. The arguments
+** are copied.
+**
+** This method should be used in preference to SSL_ConfigSecureServer,
+** SSL_ConfigSecureServerWithCertChain, SSL_SetStapledOCSPResponses, and
+** SSL_SetSignedCertTimestamps.
+**
+** The authentication method is determined from the certificate and private key
+** based on how libssl authenticates peers. Primarily, this uses the value of
+** the SSLAuthType enum and is derived from the type of public key in the
+** certificate. For example, different RSA certificates might be saved for
+** signing (ssl_auth_rsa_sign) and key encipherment
+** (ssl_auth_rsa_decrypt). Unique to RSA, the same certificate can be used for
+** both usages. Additional information about the authentication method is also
+** used: EC keys with different curves are separately stored.
+**
+** Only one certificate is stored for each authentication method.
+**
+** The optional |data| argument contains additional information about the
+** certificate:
+**
+** - |authType| (with a value other than ssl_auth_null) limits the
+** authentication method; this is primarily useful in limiting the use of an
+** RSA certificate to one particular key usage (either signing or key
+** encipherment) when its key usages indicate support for both.
+**
+** - |certChain| provides an explicit certificate chain, rather than relying on
+** NSS functions for finding a certificate chain.
+**
+** - |stapledOCSPResponses| provides a response for OCSP stapling.
+**
+** - |signedCertTimestamps| provides a value for the
+** signed_certificate_timestamp extension used in certificate transparency.
+**
+** The |data_len| argument provides the length of the data. This should be set
+** to |sizeof(data)|.
+**
+** This function allows an application to provide certificates with narrow key
+** usages attached to them. For instance, RSA keys can be provided that are
+** limited to signing or decryption only. Multiple EC certificates with keys on
+** different named curves can be provided.
+**
+** Unlike SSL_ConfigSecureServer(WithCertChain), this function does not accept
+** NULL for the |cert| and |key| arguments. It will replace certificates that
+** have the same type, but it cannot be used to remove certificates that have
+** already been configured.
+*/
+SSL_IMPORT SECStatus SSL_ConfigServerCert(
+ PRFileDesc *fd, CERTCertificate *cert, SECKEYPrivateKey *key,
+ const SSLExtraServerCertData *data, unsigned int data_len);
+
+/*
+** Deprecated variant of SSL_ConfigServerCert.
+**
+** This uses values from the SSLKEAType to identify the type of |key| that the
+** |cert| contains. This is incorrect, since key exchange and authentication
+** are separated in some cipher suites (in particular, ECDHE_RSA_* suites).
+**
+** Providing a |kea| parameter of ssl_kea_ecdh (or kt_ecdh) is interpreted as
+** providing both ECDH and ECDSA certificates.
+*/
+SSL_IMPORT SECStatus SSL_ConfigSecureServer(
+ PRFileDesc *fd, CERTCertificate *cert,
+ SECKEYPrivateKey *key, SSLKEAType kea);
+
+/*
+** Deprecated variant of SSL_ConfigSecureServerCert. The |data| argument to
+** SSL_ConfigSecureServerCert can be used to pass a certificate chain.
+*/
+SSL_IMPORT SECStatus
+SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert,
+ const CERTCertificateList *certChainOpt,
+ SECKEYPrivateKey *key, SSLKEAType kea);
+
+/*
+** SSL_SetSessionTicketKeyPair configures an asymmetric key pair for use in
+** wrapping session ticket keys, used by the server. This function currently
+** only accepts an RSA public/private key pair.
+**
+** Prior to the existence of this function, NSS used an RSA private key
+** associated with a configured certificate to perform session ticket
+** encryption. If this function isn't used, the keys provided with a configured
+** RSA certificate are used for wrapping session ticket keys.
+**
+** NOTE: This key is used for all self-encryption but is named for
+** session tickets for historical reasons.
+*/
+SSL_IMPORT SECStatus
+SSL_SetSessionTicketKeyPair(SECKEYPublicKey *pubKey, SECKEYPrivateKey *privKey);
+
+/*
+** Configure a secure server's session-id cache. Define the maximum number
+** of entries in the cache, the longevity of the entires, and the directory
+** where the cache files will be placed. These values can be zero, and
+** if so, the implementation will choose defaults.
+** This version of the function is for use in applications that have only one
+** process that uses the cache (even if that process has multiple threads).
+*/
+SSL_IMPORT SECStatus SSL_ConfigServerSessionIDCache(int maxCacheEntries,
+ PRUint32 timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory);
+
+/* Configure a secure server's session-id cache. Depends on value of
+ * enableMPCache, configures malti-proc or single proc cache. */
+SSL_IMPORT SECStatus SSL_ConfigServerSessionIDCacheWithOpt(
+ PRUint32 timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory,
+ int maxCacheEntries,
+ int maxCertCacheEntries,
+ int maxSrvNameCacheEntries,
+ PRBool enableMPCache);
+
+/*
+** Like SSL_ConfigServerSessionIDCache, with one important difference.
+** If the application will run multiple processes (as opposed to, or in
+** addition to multiple threads), then it must call this function, instead
+** of calling SSL_ConfigServerSessionIDCache().
+** This has nothing to do with the number of processORs, only processEs.
+** This function sets up a Server Session ID (SID) cache that is safe for
+** access by multiple processes on the same system.
+*/
+SSL_IMPORT SECStatus SSL_ConfigMPServerSIDCache(int maxCacheEntries,
+ PRUint32 timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory);
+
+/* Get and set the configured maximum number of mutexes used for the
+** server's store of SSL sessions. This value is used by the server
+** session ID cache initialization functions shown above. Note that on
+** some platforms, these mutexes are actually implemented with POSIX
+** semaphores, or with unnamed pipes. The default value varies by platform.
+** An attempt to set a too-low maximum will return an error and the
+** configured value will not be changed.
+*/
+SSL_IMPORT PRUint32 SSL_GetMaxServerCacheLocks(void);
+SSL_IMPORT SECStatus SSL_SetMaxServerCacheLocks(PRUint32 maxLocks);
+
+/* environment variable set by SSL_ConfigMPServerSIDCache, and queried by
+ * SSL_InheritMPServerSIDCache when envString is NULL.
+ */
+#define SSL_ENV_VAR_NAME "SSL_INHERITANCE"
+
+/* called in child to inherit SID Cache variables.
+ * If envString is NULL, this function will use the value of the environment
+ * variable "SSL_INHERITANCE", otherwise the string value passed in will be
+ * used.
+ */
+SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char *envString);
+
+/*
+** Set the callback that gets called when a TLS handshake is complete. The
+** handshake callback is called after verifying the peer's Finished message and
+** before processing incoming application data.
+**
+** For the initial handshake: If the handshake false started (see
+** SSL_ENABLE_FALSE_START), then application data may already have been sent
+** before the handshake callback is called. If we did not false start then the
+** callback will get called before any application data is sent.
+*/
+typedef void(PR_CALLBACK *SSLHandshakeCallback)(PRFileDesc *fd,
+ void *client_data);
+SSL_IMPORT SECStatus SSL_HandshakeCallback(PRFileDesc *fd,
+ SSLHandshakeCallback cb, void *client_data);
+
+/* Applications that wish to enable TLS false start must set this callback
+** function. NSS will invoke the functon to determine if a particular
+** connection should use false start or not. SECSuccess indicates that the
+** callback completed successfully, and if so *canFalseStart indicates if false
+** start can be used. If the callback does not return SECSuccess then the
+** handshake will be canceled. NSS's recommended criteria can be evaluated by
+** calling SSL_RecommendedCanFalseStart.
+**
+** If no false start callback is registered then false start will never be
+** done, even if the SSL_ENABLE_FALSE_START option is enabled.
+**/
+typedef SECStatus(PR_CALLBACK *SSLCanFalseStartCallback)(
+ PRFileDesc *fd, void *arg, PRBool *canFalseStart);
+
+SSL_IMPORT SECStatus SSL_SetCanFalseStartCallback(
+ PRFileDesc *fd, SSLCanFalseStartCallback callback, void *arg);
+
+/* This function sets *canFalseStart according to the recommended criteria for
+** false start. These criteria may change from release to release and may depend
+** on which handshake features have been negotiated and/or properties of the
+** certifciates/keys used on the connection.
+*/
+SSL_IMPORT SECStatus SSL_RecommendedCanFalseStart(PRFileDesc *fd,
+ PRBool *canFalseStart);
+
+/*
+** For the server, request a new handshake. For the client, begin a new
+** handshake. If flushCache is non-zero, the SSL3 cache entry will be
+** flushed first, ensuring that a full SSL handshake will be done.
+** If flushCache is zero, and an SSL connection is established, it will
+** do the much faster session restart handshake. This will change the
+** session keys without doing another private key operation.
+*/
+SSL_IMPORT SECStatus SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache);
+
+/*
+** Same as above, but with an I/O timeout.
+ */
+SSL_IMPORT SECStatus SSL_ReHandshakeWithTimeout(PRFileDesc *fd,
+ PRBool flushCache,
+ PRIntervalTime timeout);
+
+#ifdef SSL_DEPRECATED_FUNCTION
+/* deprecated!
+** For the server, request a new handshake. For the client, begin a new
+** handshake. Flushes SSL3 session cache entry first, ensuring that a
+** full handshake will be done.
+** This call is equivalent to SSL_ReHandshake(fd, PR_TRUE)
+*/
+SSL_IMPORT SECStatus SSL_RedoHandshake(PRFileDesc *fd);
+#endif
+
+/*
+ * Allow the application to pass a URL or hostname into the SSL library.
+ */
+SSL_IMPORT SECStatus SSL_SetURL(PRFileDesc *fd, const char *url);
+
+/*
+ * Allow an application to define a set of trust anchors for peer
+ * cert validation.
+ */
+SSL_IMPORT SECStatus SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *list);
+
+/*
+** Return the number of bytes that SSL has waiting in internal buffers.
+** Return 0 if security is not enabled.
+*/
+SSL_IMPORT int SSL_DataPending(PRFileDesc *fd);
+
+/*
+** Invalidate the SSL session associated with fd.
+*/
+SSL_IMPORT SECStatus SSL_InvalidateSession(PRFileDesc *fd);
+
+/*
+** Return a SECItem containing the SSL session ID associated with the fd.
+*/
+SSL_IMPORT SECItem *SSL_GetSessionID(PRFileDesc *fd);
+
+/*
+** Clear out the client's SSL session cache, not the server's session cache.
+*/
+SSL_IMPORT void SSL_ClearSessionCache(void);
+
+/*
+** Close the server's SSL session cache.
+*/
+SSL_IMPORT SECStatus SSL_ShutdownServerSessionIDCache(void);
+
+/*
+** Set peer information so we can correctly look up SSL session later.
+** You only have to do this if you're tunneling through a proxy.
+*/
+SSL_IMPORT SECStatus SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID);
+
+/*
+** Reveal the security information for the peer.
+*/
+SSL_IMPORT CERTCertificate *SSL_RevealCert(PRFileDesc *socket);
+SSL_IMPORT void *SSL_RevealPinArg(PRFileDesc *socket);
+SSL_IMPORT char *SSL_RevealURL(PRFileDesc *socket);
+
+/* This callback may be passed to the SSL library via a call to
+ * SSL_GetClientAuthDataHook() for each SSL client socket.
+ * It will be invoked when SSL needs to know what certificate and private key
+ * (if any) to use to respond to a request for client authentication.
+ * If arg is non-NULL, it is a pointer to a NULL-terminated string containing
+ * the nickname of the cert/key pair to use.
+ * If arg is NULL, this function will search the cert and key databases for
+ * a suitable match and send it if one is found.
+ */
+SSL_IMPORT SECStatus
+NSS_GetClientAuthData(void *arg,
+ PRFileDesc *socket,
+ struct CERTDistNamesStr *caNames,
+ struct CERTCertificateStr **pRetCert,
+ struct SECKEYPrivateKeyStr **pRetKey);
+
+/* This function can be called by the appliation's custom GetClientAuthHook
+ * to filter out any certs in the cert list that doesn't match the negotiated
+ * requirements of the current SSL connection.
+ */
+SSL_IMPORT SECStatus
+SSL_FilterClientCertListBySocket(PRFileDesc *socket, CERTCertList *certlist);
+
+/* This function can be called by the application's custom GetClientAuthHook
+ * to determine if a single certificate matches the negotiated requirements of
+ * the current SSL connection.
+ */
+SSL_IMPORT PRBool
+SSL_CertIsUsable(PRFileDesc *socket, CERTCertificate *cert);
+
+/*
+** Configure DTLS-SRTP (RFC 5764) cipher suite preferences.
+** Input is a list of ciphers in descending preference order and a length
+** of the list. As a side effect, this causes the use_srtp extension to be
+** negotiated.
+**
+** Invalid or unimplemented cipher suites in |ciphers| are ignored. If at
+** least one cipher suite in |ciphers| is implemented, returns SECSuccess.
+** Otherwise returns SECFailure.
+*/
+SSL_IMPORT SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd,
+ const PRUint16 *ciphers,
+ unsigned int numCiphers);
+
+/*
+** Get the selected DTLS-SRTP cipher suite (if any).
+** To be called after the handshake completes.
+** Returns SECFailure if not negotiated.
+*/
+SSL_IMPORT SECStatus SSL_GetSRTPCipher(PRFileDesc *fd,
+ PRUint16 *cipher);
+
+/*
+ * Look to see if any of the signers in the cert chain for "cert" are found
+ * in the list of caNames.
+ * Returns SECSuccess if so, SECFailure if not.
+ * Used by NSS_GetClientAuthData. May be used by other callback functions.
+ */
+SSL_IMPORT SECStatus NSS_CmpCertChainWCANames(CERTCertificate *cert,
+ CERTDistNames *caNames);
+
+/* Deprecated. This reports a misleading value for certificates that might
+ * be used for signing rather than key exchange.
+ * Returns key exchange type of the keys in an SSL server certificate.
+ */
+SSL_IMPORT SSLKEAType NSS_FindCertKEAType(CERTCertificate *cert);
+
+/* Set cipher policies to a predefined Domestic (U.S.A.) policy.
+ * This essentially allows all supported ciphers.
+ */
+SSL_IMPORT SECStatus NSS_SetDomesticPolicy(void);
+
+/* Set cipher policies to a predefined Policy that is exportable from the USA
+ * according to present U.S. policies as we understand them.
+ * It is the same as NSS_SetDomesticPolicy now.
+ */
+SSL_IMPORT SECStatus NSS_SetExportPolicy(void);
+
+/* Set cipher policies to a predefined Policy that is exportable from the USA
+ * according to present U.S. policies as we understand them, and that the
+ * nation of France will permit to be imported into their country.
+ * It is the same as NSS_SetDomesticPolicy now.
+ */
+SSL_IMPORT SECStatus NSS_SetFrancePolicy(void);
+
+SSL_IMPORT SSL3Statistics *SSL_GetStatistics(void);
+
+/* Report more information than SSL_SecurityStatus.
+ * Caller supplies the info struct. This function fills it in. Caller should
+ * pass sizeof(SSLChannelInfo) as the |len| argument.
+ *
+ * The information here will be zeroed prior to details being confirmed. The
+ * details are confirmed either when a Finished message is received, or - for a
+ * client - when the second flight of messages have been sent. This function
+ * therefore produces unreliable results prior to receiving the
+ * SSLHandshakeCallback or the SSLCanFalseStartCallback.
+ */
+SSL_IMPORT SECStatus SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info,
+ PRUintn len);
+/* Get preliminary information about a channel.
+ * Caller supplies the info struct. This function fills it in. Caller should
+ * pass sizeof(SSLPreliminaryChannelInfo) as the |len| argument.
+ *
+ * This function can be called prior to handshake details being confirmed (see
+ * SSL_GetChannelInfo above for what that means). Thus, information provided by
+ * this function is available to SSLAuthCertificate, SSLGetClientAuthData,
+ * SSLSNISocketConfig, and other callbacks that might be called during the
+ * processing of the first flight of client of server handshake messages.
+ * Values are marked as being unavailable when renegotiation is initiated.
+ */
+SSL_IMPORT SECStatus
+SSL_GetPreliminaryChannelInfo(PRFileDesc *fd,
+ SSLPreliminaryChannelInfo *info,
+ PRUintn len);
+/* Get information about cipher suite with id of |cipherSuite|.
+ * Caller supplies the info struct. This function fills it in. Caller should
+ * pass sizeof(SSLCipherSuiteInfo) as the |len| argument.
+ */
+SSL_IMPORT SECStatus SSL_GetCipherSuiteInfo(PRUint16 cipherSuite,
+ SSLCipherSuiteInfo *info, PRUintn len);
+
+/* Returnes negotiated through SNI host info. */
+SSL_IMPORT SECItem *SSL_GetNegotiatedHostInfo(PRFileDesc *fd);
+
+/* Export keying material according to RFC 5705.
+** fd must correspond to a TLS 1.0 or higher socket and out must
+** already be allocated. If hasContext is false, it uses the no-context
+** construction from the RFC and ignores the context and contextLen
+** arguments.
+*/
+SSL_IMPORT SECStatus SSL_ExportKeyingMaterial(PRFileDesc *fd,
+ const char *label,
+ unsigned int labelLen,
+ PRBool hasContext,
+ const unsigned char *context,
+ unsigned int contextLen,
+ unsigned char *out,
+ unsigned int outLen);
+
+/* Early exporters are used if 0-RTT is enabled. This is TLS 1.3 only. Note
+ * that in TLS 1.3, an empty context is equivalent to an absent context. */
+SSL_IMPORT SECStatus SSL_ExportEarlyKeyingMaterial(PRFileDesc *fd,
+ const char *label,
+ unsigned int labelLen,
+ const unsigned char *context,
+ unsigned int contextLen,
+ unsigned char *out,
+ unsigned int outLen);
+
+/*
+** Return a new reference to the certificate that was most recently sent
+** to the peer on this SSL/TLS connection, or NULL if none has been sent.
+*/
+SSL_IMPORT CERTCertificate *SSL_LocalCertificate(PRFileDesc *fd);
+
+#define SSL_CBP_SSL3 0x0001 /* (deprecated) */
+#define SSL_CBP_TLS1_0 0x0002 /* (deprecated) */
+
+/* DEPRECATED: The PKCS#11 bypass has been removed.
+** This function will now always return false. */
+SSL_IMPORT SECStatus SSL_CanBypass(CERTCertificate *cert,
+ SECKEYPrivateKey *privKey,
+ PRUint32 protocolmask,
+ PRUint16 *ciphers, int nciphers,
+ PRBool *pcanbypass, void *pwArg);
+
+/*
+** Did the handshake with the peer negotiate the given extension?
+** Output parameter valid only if function returns SECSuccess
+*/
+SSL_IMPORT SECStatus SSL_HandshakeNegotiatedExtension(PRFileDesc *socket,
+ SSLExtensionType extId,
+ PRBool *yes);
+
+/*
+** How long should we wait before retransmitting the next flight of
+** the DTLS handshake? Returns SECFailure if not DTLS or not in a
+** handshake.
+*/
+SSL_IMPORT SECStatus DTLS_GetHandshakeTimeout(PRFileDesc *socket,
+ PRIntervalTime *timeout);
+
+/*
+ * Return a boolean that indicates whether the underlying library
+ * will perform as the caller expects.
+ *
+ * The only argument is a string, which should be the version
+ * identifier of the NSS library. That string will be compared
+ * against a string that represents the actual build version of
+ * the SSL library.
+ */
+extern PRBool NSSSSL_VersionCheck(const char *importedVersion);
+
+/*
+ * Returns a const string of the SSL library version.
+ */
+extern const char *NSSSSL_GetVersion(void);
+
+/* Restart an SSL connection that was paused to do asynchronous certificate
+ * chain validation (when the auth certificate hook or bad cert handler
+ * returned SECWouldBlock).
+ *
+ * This function only works for non-blocking sockets; Do not use it for
+ * blocking sockets. Currently, this function works only for the client role of
+ * a connection; it does not work for the server role.
+ *
+ * The application must call SSL_AuthCertificateComplete with 0 as the value of
+ * the error parameter after it has successfully validated the peer's
+ * certificate, in order to continue the SSL handshake.
+ *
+ * The application may call SSL_AuthCertificateComplete with a non-zero value
+ * for error (e.g. SEC_ERROR_REVOKED_CERTIFICATE) when certificate validation
+ * fails, before it closes the connection. If the application does so, an
+ * alert corresponding to the error (e.g. certificate_revoked) will be sent to
+ * the peer. See the source code of the internal function
+ * ssl3_SendAlertForCertError for the current mapping of error to alert. This
+ * mapping may change in future versions of libssl.
+ *
+ * This function will not complete the entire handshake. The application must
+ * call SSL_ForceHandshake, PR_Recv, PR_Send, etc. after calling this function
+ * to force the handshake to complete.
+ *
+ * On the first handshake of a connection, libssl will wait for the peer's
+ * certificate to be authenticated before calling the handshake callback,
+ * sending a client certificate, sending any application data, or returning
+ * any application data to the application. On subsequent (renegotiation)
+ * handshakes, libssl will block the handshake unconditionally while the
+ * certificate is being validated.
+ *
+ * libssl may send and receive handshake messages while waiting for the
+ * application to call SSL_AuthCertificateComplete, and it may call other
+ * callbacks (e.g, the client auth data hook) before
+ * SSL_AuthCertificateComplete has been called.
+ *
+ * An application that uses this asynchronous mechanism will usually have lower
+ * handshake latency if it has to do public key operations on the certificate
+ * chain and/or CRL/OCSP/cert fetching during the authentication, especially if
+ * it does so in parallel on another thread. However, if the application can
+ * authenticate the peer's certificate quickly then it may be more efficient
+ * to use the synchronous mechanism (i.e. returning SECFailure/SECSuccess
+ * instead of SECWouldBlock from the authenticate certificate hook).
+ *
+ * Be careful about converting an application from synchronous cert validation
+ * to asynchronous certificate validation. A naive conversion is likely to
+ * result in deadlocks; e.g. the application will wait in PR_Poll for network
+ * I/O on the connection while all network I/O on the connection is blocked
+ * waiting for this function to be called.
+ *
+ * Returns SECFailure on failure, SECSuccess on success. Never returns
+ * SECWouldBlock. Note that SSL_AuthCertificateComplete will (usually) return
+ * SECSuccess; do not interpret the return value of SSL_AuthCertificateComplete
+ * as an indicator of whether it is OK to continue using the connection. For
+ * example, SSL_AuthCertificateComplete(fd, SEC_ERROR_REVOKED_CERTIFICATE) will
+ * return SECSuccess (normally), but that does not mean that the application
+ * should continue using the connection. If the application passes a non-zero
+ * value for second argument (error), or if SSL_AuthCertificateComplete returns
+ * anything other than SECSuccess, then the application should close the
+ * connection.
+ */
+SSL_IMPORT SECStatus SSL_AuthCertificateComplete(PRFileDesc *fd,
+ PRErrorCode error);
+
+/* Restart an SSL connection which was paused to do asynchronous client
+ * certificate selection (when the client certificate hook returned SECWouldBlock).
+ *
+ * This function only works for non-blocking sockets; Do not use it for
+ * blocking sockets. This function works only for the client role of
+ * a connection; it does not work for the server role.
+ *
+ * If a certificate has been sucessfully selected, the application must call
+ * SSL_ClientCertCallbackComplete with:
+ * - SECSuccess (0) as the value of outcome
+ * - a valid SECKEYPrivateKey located at *clientPrivateKey
+ * - a valid CERTCertificate located at *clientCertificate
+ * The ownership of these latter structures will pass to NSS and the application
+ * MUST not retain any references to them or invalidate them.
+ *
+ * If a certificate has not been selected, the application must call
+ * SSL_ClientCertCallbackComplete with:
+ * - SECFailure (-1) as the value of outcome
+ * - *clientPrivateKey set to NULL.
+ * - *clientCertificate set to NULL
+ *
+ * Once the application has returned SECWouldBlock to getClientAuthData
+ * the handshake will not proceed until this function is called. It is an
+ * error to call this function when the handshake is not waiting on client
+ * certificate selection, or to call this function more than once.
+
+ * This function will not complete the entire handshake. The application must
+ * call SSL_ForceHandshake, PR_Recv, PR_Send, etc. after calling this function
+ * to force the handshake to complete.
+ *
+ * Be careful about converting an application from synchronous cert selection
+ * to asynchronous certificate selection. A naive conversion is likely to
+ * result in deadlocks; e.g. the application will wait in PR_Poll for network
+ * I/O on the connection while all network I/O on the connection is blocked
+ * waiting for this function to be called.
+ *
+ * Note that SSL_ClientCertCallbackComplete will (usually) return
+ * SECSuccess; SECFailure indicates that the function was invoked incorrectly or
+ * an error whilst processing the handshake. The return code does not indicate
+ * whether or not the provided private key and certificate were sucessfully loaded
+ * or accepted by the server.
+ */
+SSL_IMPORT SECStatus SSL_ClientCertCallbackComplete(PRFileDesc *fd, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate);
+
+/*
+ * This is used to access experimental APIs. Don't call this directly. This is
+ * used to enable the experimental APIs that are defined in "sslexp.h".
+ */
+SSL_IMPORT void *SSL_GetExperimentalAPI(const char *name);
+
+SEC_END_PROTOS
+
+#endif /* __ssl_h_ */
diff --git a/security/nss/lib/ssl/ssl.rc b/security/nss/lib/ssl/ssl.rc
new file mode 100644
index 0000000000..809a07e5ff
--- /dev/null
+++ b/security/nss/lib/ssl/ssl.rc
@@ -0,0 +1,68 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include <winver.h>
+
+#define MY_LIBNAME "ssl"
+#define MY_FILEDESCRIPTION "NSS SSL Library"
+
+#define STRINGIZE(x) #x
+#define STRINGIZE2(x) STRINGIZE(x)
+#define NSS_VMAJOR_STR STRINGIZE2(NSS_VMAJOR)
+
+#ifdef _DEBUG
+#define MY_DEBUG_STR " (debug)"
+#define MY_FILEFLAGS_1 VS_FF_DEBUG
+#else
+#define MY_DEBUG_STR ""
+#define MY_FILEFLAGS_1 0x0L
+#endif
+#if NSS_BETA
+#define MY_FILEFLAGS_2 MY_FILEFLAGS_1|VS_FF_PRERELEASE
+#else
+#define MY_FILEFLAGS_2 MY_FILEFLAGS_1
+#endif
+
+#ifdef WINNT
+#define MY_FILEOS VOS_NT_WINDOWS32
+#else
+#define MY_FILEOS VOS__WINDOWS32
+#endif
+
+#define MY_INTERNAL_NAME MY_LIBNAME NSS_VMAJOR_STR
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version-information resource
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION NSS_VMAJOR,NSS_VMINOR,NSS_VPATCH,NSS_VBUILD
+ PRODUCTVERSION NSS_VMAJOR,NSS_VMINOR,NSS_VPATCH,NSS_VBUILD
+ FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
+ FILEFLAGS MY_FILEFLAGS_2
+ FILEOS MY_FILEOS
+ FILETYPE VFT_DLL
+ FILESUBTYPE 0x0L // not used
+
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904B0" // Lang=US English, CharSet=Unicode
+ BEGIN
+ VALUE "CompanyName", "Mozilla Foundation\0"
+ VALUE "FileDescription", MY_FILEDESCRIPTION MY_DEBUG_STR "\0"
+ VALUE "FileVersion", NSS_VERSION "\0"
+ VALUE "InternalName", MY_INTERNAL_NAME "\0"
+ VALUE "OriginalFilename", MY_INTERNAL_NAME ".dll\0"
+ VALUE "ProductName", "Network Security Services\0"
+ VALUE "ProductVersion", NSS_VERSION "\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x409, 1200
+ END
+END
diff --git a/security/nss/lib/ssl/ssl3con.c b/security/nss/lib/ssl/ssl3con.c
new file mode 100644
index 0000000000..84246954a5
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3con.c
@@ -0,0 +1,14318 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * SSL3 Protocol
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
+
+#include "cert.h"
+#include "ssl.h"
+#include "cryptohi.h" /* for DSAU_ stuff */
+#include "keyhi.h"
+#include "secder.h"
+#include "secitem.h"
+#include "sechash.h"
+
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "sslerr.h"
+#include "ssl3ext.h"
+#include "ssl3exthandle.h"
+#include "tls13ech.h"
+#include "tls13exthandle.h"
+#include "tls13psk.h"
+#include "tls13subcerts.h"
+#include "prtime.h"
+#include "prinrval.h"
+#include "prerror.h"
+#include "pratom.h"
+#include "prthread.h"
+#include "nss.h"
+#include "nssoptions.h"
+
+#include "pk11func.h"
+#include "secmod.h"
+#include "blapi.h"
+
+#include <stdio.h>
+
+static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
+ PK11SlotInfo *serverKeySlot);
+static SECStatus ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
+ PK11SymKey **msp);
+static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss,
+ PK11SymKey *masterSecret);
+static SECStatus ssl3_HandshakeFailure(sslSocket *ss);
+static SECStatus ssl3_SendCertificate(sslSocket *ss);
+static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
+static SECStatus ssl3_SendNextProto(sslSocket *ss);
+static SECStatus ssl3_SendFinished(sslSocket *ss, PRInt32 flags);
+static SECStatus ssl3_SendServerHelloDone(sslSocket *ss);
+static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss);
+static SECStatus ssl3_HandleClientHelloPart2(sslSocket *ss,
+ SECItem *suites,
+ sslSessionID *sid,
+ const PRUint8 *msg,
+ unsigned int len);
+static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss,
+ const SECItem *sidBytes,
+ int *retErrCode);
+static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss,
+ PRUint8 *b,
+ PRUint32 length);
+static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
+static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType);
+static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash);
+PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme);
+PRBool ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme);
+PRBool ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme);
+PRBool ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme);
+static SECStatus ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss,
+ const unsigned char *b,
+ unsigned int l);
+const PRUint32 kSSLSigSchemePolicy =
+ NSS_USE_ALG_IN_SSL_KX | NSS_USE_ALG_IN_ANY_SIGNATURE;
+
+const PRUint8 ssl_hello_retry_random[] = {
+ 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11,
+ 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91,
+ 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E,
+ 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C
+};
+PR_STATIC_ASSERT(PR_ARRAY_SIZE(ssl_hello_retry_random) == SSL3_RANDOM_LENGTH);
+
+/* This list of SSL3 cipher suites is sorted in descending order of
+ * precedence (desirability). It only includes cipher suites we implement.
+ * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
+ * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
+ *
+ * Important: See bug 946147 before enabling, reordering, or adding any cipher
+ * suites to this list.
+ */
+/* clang-format off */
+static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
+ /* cipher_suite policy enabled isPresent */
+ /* Special TLS 1.3 suites. */
+ { TLS_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
+ { TLS_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE },
+ { TLS_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE },
+
+ { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
+ * bug 946147.
+ */
+ { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+
+ { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,SSL_ALLOWED,PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+
+ { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+
+ /* RSA */
+ { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_AES_256_CBC_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_SEED_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_3DES_EDE_CBC_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_RC4_128_SHA, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+ { TLS_RSA_WITH_RC4_128_MD5, SSL_ALLOWED, PR_TRUE, PR_FALSE},
+
+ /* 56-bit DES "domestic" cipher suites */
+ { TLS_DHE_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_DHE_DSS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+
+ /* ciphersuites with no encryption */
+ { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_NULL_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_NULL_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+ { TLS_RSA_WITH_NULL_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE},
+};
+/* clang-format on */
+
+/* This is the default supported set of signature schemes. The order of the
+ * hashes here is all that is important, since that will (sometimes) determine
+ * which hash we use. The key pair (i.e., cert) is the primary thing that
+ * determines what we use and this doesn't affect how we select key pairs. The
+ * order of signature types is based on the same rules for ordering we use for
+ * cipher suites just for consistency.
+ */
+static const SSLSignatureScheme defaultSignatureSchemes[] = {
+ ssl_sig_ecdsa_secp256r1_sha256,
+ ssl_sig_ecdsa_secp384r1_sha384,
+ ssl_sig_ecdsa_secp521r1_sha512,
+ ssl_sig_ecdsa_sha1,
+ ssl_sig_rsa_pss_rsae_sha256,
+ ssl_sig_rsa_pss_rsae_sha384,
+ ssl_sig_rsa_pss_rsae_sha512,
+ ssl_sig_rsa_pkcs1_sha256,
+ ssl_sig_rsa_pkcs1_sha384,
+ ssl_sig_rsa_pkcs1_sha512,
+ ssl_sig_rsa_pkcs1_sha1,
+ ssl_sig_dsa_sha256,
+ ssl_sig_dsa_sha384,
+ ssl_sig_dsa_sha512,
+ ssl_sig_dsa_sha1
+};
+PR_STATIC_ASSERT(PR_ARRAY_SIZE(defaultSignatureSchemes) <=
+ MAX_SIGNATURE_SCHEMES);
+
+/* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
+ */
+#ifdef DEBUG
+void
+ssl3_CheckCipherSuiteOrderConsistency()
+{
+ unsigned int i;
+
+ PORT_Assert(SSL_NumImplementedCiphers == PR_ARRAY_SIZE(cipherSuites));
+
+ for (i = 0; i < PR_ARRAY_SIZE(cipherSuites); ++i) {
+ PORT_Assert(SSL_ImplementedCiphers[i] == cipherSuites[i].cipher_suite);
+ }
+}
+#endif
+
+static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = {
+ ct_RSA_sign,
+ ct_ECDSA_sign,
+ ct_DSS_sign,
+};
+
+static SSL3Statistics ssl3stats;
+
+static const ssl3KEADef kea_defs[] = {
+ /* indexed by SSL3KeyExchangeAlgorithm */
+ /* kea exchKeyType signKeyType authKeyType ephemeral oid */
+ { kea_null, ssl_kea_null, nullKey, ssl_auth_null, PR_FALSE, 0 },
+ { kea_rsa, ssl_kea_rsa, nullKey, ssl_auth_rsa_decrypt, PR_FALSE, SEC_OID_TLS_RSA },
+ { kea_dh_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_FALSE, SEC_OID_TLS_DH_DSS },
+ { kea_dh_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_FALSE, SEC_OID_TLS_DH_RSA },
+ { kea_dhe_dss, ssl_kea_dh, dsaKey, ssl_auth_dsa, PR_TRUE, SEC_OID_TLS_DHE_DSS },
+ { kea_dhe_rsa, ssl_kea_dh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_DHE_RSA },
+ { kea_dh_anon, ssl_kea_dh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_DH_ANON },
+ { kea_ecdh_ecdsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_ecdsa, PR_FALSE, SEC_OID_TLS_ECDH_ECDSA },
+ { kea_ecdhe_ecdsa, ssl_kea_ecdh, ecKey, ssl_auth_ecdsa, PR_TRUE, SEC_OID_TLS_ECDHE_ECDSA },
+ { kea_ecdh_rsa, ssl_kea_ecdh, nullKey, ssl_auth_ecdh_rsa, PR_FALSE, SEC_OID_TLS_ECDH_RSA },
+ { kea_ecdhe_rsa, ssl_kea_ecdh, rsaKey, ssl_auth_rsa_sign, PR_TRUE, SEC_OID_TLS_ECDHE_RSA },
+ { kea_ecdh_anon, ssl_kea_ecdh, nullKey, ssl_auth_null, PR_TRUE, SEC_OID_TLS_ECDH_ANON },
+ { kea_ecdhe_psk, ssl_kea_ecdh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_ECDHE_PSK },
+ { kea_dhe_psk, ssl_kea_dh_psk, nullKey, ssl_auth_psk, PR_TRUE, SEC_OID_TLS_DHE_PSK },
+ { kea_tls13_any, ssl_kea_tls13_any, nullKey, ssl_auth_tls13_any, PR_TRUE, SEC_OID_TLS13_KEA_ANY },
+};
+
+/* must use ssl_LookupCipherSuiteDef to access */
+static const ssl3CipherSuiteDef cipher_suite_defs[] = {
+ /* cipher_suite bulk_cipher_alg mac_alg key_exchange_alg prf_hash */
+ /* Note that the prf_hash_alg is the hash function used by the PRF, see sslimpl.h. */
+
+ { TLS_NULL_WITH_NULL_NULL, cipher_null, ssl_mac_null, kea_null, ssl_hash_none },
+ { TLS_RSA_WITH_NULL_MD5, cipher_null, ssl_mac_md5, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_NULL_SHA256, cipher_null, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
+ { TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, ssl_mac_md5, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
+ cipher_3des, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ cipher_3des, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
+
+ /* New TLS cipher suites */
+ { TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
+ { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
+ { TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_rsa, ssl_hash_sha256 },
+ { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_rsa, ssl_hash_sha256 },
+ { TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha384 },
+
+ { TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, ssl_mac_sha, kea_rsa, ssl_hash_none },
+
+ { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_camellia_128, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ cipher_camellia_128, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
+ { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, ssl_mac_sha, kea_rsa, ssl_hash_none },
+ { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_camellia_256, ssl_mac_sha, kea_dhe_dss, ssl_hash_none },
+ { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ cipher_camellia_256, ssl_mac_sha, kea_dhe_rsa, ssl_hash_none },
+
+ { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
+ { TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha256 },
+
+ { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
+ { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
+ { TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384 },
+ { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha384 },
+ { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384 },
+ { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, ssl_hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384 },
+ { TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha256 },
+ { TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
+ { TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, ssl_hmac_sha256, kea_dhe_dss, ssl_hash_sha256 },
+ { TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_dhe_dss, ssl_hash_sha384 },
+ { TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_rsa, ssl_hash_sha384 },
+
+ { TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_dhe_rsa, ssl_hash_sha256 },
+
+ { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_rsa, ssl_hash_sha256 },
+ { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256 },
+
+ { TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
+ { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
+ { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
+ { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
+ { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_ecdsa, ssl_hash_none },
+
+ { TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
+ { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
+ { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
+ { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
+ { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256 },
+ { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_ecdsa, ssl_hash_none },
+
+ { TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
+ { TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
+ { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
+ { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
+ { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdh_rsa, ssl_hash_none },
+
+ { TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
+ { TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
+ { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
+ { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
+ { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, ssl_hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256 },
+ { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, ssl_mac_sha, kea_ecdhe_rsa, ssl_hash_none },
+
+ { TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
+ { TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, ssl_mac_aead, kea_tls13_any, ssl_hash_sha256 },
+ { TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, ssl_mac_aead, kea_tls13_any, ssl_hash_sha384 },
+};
+
+static const CK_MECHANISM_TYPE auth_alg_defs[] = {
+ CKM_INVALID_MECHANISM, /* ssl_auth_null */
+ CKM_RSA_PKCS, /* ssl_auth_rsa_decrypt */
+ CKM_DSA, /* ? _SHA1 */ /* ssl_auth_dsa */
+ CKM_INVALID_MECHANISM, /* ssl_auth_kea (unused) */
+ CKM_ECDSA, /* ssl_auth_ecdsa */
+ CKM_ECDH1_DERIVE, /* ssl_auth_ecdh_rsa */
+ CKM_ECDH1_DERIVE, /* ssl_auth_ecdh_ecdsa */
+ CKM_RSA_PKCS, /* ssl_auth_rsa_sign */
+ CKM_RSA_PKCS_PSS, /* ssl_auth_rsa_pss */
+ CKM_NSS_HKDF_SHA256, /* ssl_auth_psk (just check for HKDF) */
+ CKM_INVALID_MECHANISM /* ssl_auth_tls13_any */
+};
+PR_STATIC_ASSERT(PR_ARRAY_SIZE(auth_alg_defs) == ssl_auth_size);
+
+static const CK_MECHANISM_TYPE kea_alg_defs[] = {
+ CKM_INVALID_MECHANISM, /* ssl_kea_null */
+ CKM_RSA_PKCS, /* ssl_kea_rsa */
+ CKM_DH_PKCS_DERIVE, /* ssl_kea_dh */
+ CKM_INVALID_MECHANISM, /* ssl_kea_fortezza (unused) */
+ CKM_ECDH1_DERIVE, /* ssl_kea_ecdh */
+ CKM_ECDH1_DERIVE, /* ssl_kea_ecdh_psk */
+ CKM_DH_PKCS_DERIVE, /* ssl_kea_dh_psk */
+ CKM_INVALID_MECHANISM, /* ssl_kea_tls13_any */
+};
+PR_STATIC_ASSERT(PR_ARRAY_SIZE(kea_alg_defs) == ssl_kea_size);
+
+typedef struct SSLCipher2MechStr {
+ SSLCipherAlgorithm calg;
+ CK_MECHANISM_TYPE cmech;
+} SSLCipher2Mech;
+
+/* indexed by type SSLCipherAlgorithm */
+static const SSLCipher2Mech alg2Mech[] = {
+ /* calg, cmech */
+ { ssl_calg_null, CKM_INVALID_MECHANISM },
+ { ssl_calg_rc4, CKM_RC4 },
+ { ssl_calg_rc2, CKM_RC2_CBC },
+ { ssl_calg_des, CKM_DES_CBC },
+ { ssl_calg_3des, CKM_DES3_CBC },
+ { ssl_calg_idea, CKM_IDEA_CBC },
+ { ssl_calg_fortezza, CKM_SKIPJACK_CBC64 },
+ { ssl_calg_aes, CKM_AES_CBC },
+ { ssl_calg_camellia, CKM_CAMELLIA_CBC },
+ { ssl_calg_seed, CKM_SEED_CBC },
+ { ssl_calg_aes_gcm, CKM_AES_GCM },
+ { ssl_calg_chacha20, CKM_CHACHA20_POLY1305 },
+};
+
+const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
+ 0x47, 0x52, 0x44, 0x01 };
+const PRUint8 tls1_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E,
+ 0x47, 0x52, 0x44, 0x00 };
+PR_STATIC_ASSERT(sizeof(tls12_downgrade_random) ==
+ sizeof(tls1_downgrade_random));
+
+/* The ECCWrappedKeyInfo structure defines how various pieces of
+ * information are laid out within wrappedSymmetricWrappingkey
+ * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
+ * a 512-byte buffer (see sslimpl.h), the variable length field
+ * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
+ *
+ * XXX For now, NSS only supports named elliptic curves of size 571 bits
+ * or smaller. The public value will fit within 145 bytes and EC params
+ * will fit within 12 bytes. We'll need to revisit this when NSS
+ * supports arbitrary curves.
+ */
+#define MAX_EC_WRAPPED_KEY_BUFLEN 504
+
+typedef struct ECCWrappedKeyInfoStr {
+ PRUint16 size; /* EC public key size in bits */
+ PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
+ PRUint16 pubValueLen; /* length (in bytes) of EC public value */
+ PRUint16 wrappedKeyLen; /* length (in bytes) of the wrapped key */
+ PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
+ /* EC public-key params, the EC public value and the wrapped key */
+} ECCWrappedKeyInfo;
+
+CK_MECHANISM_TYPE
+ssl3_Alg2Mech(SSLCipherAlgorithm calg)
+{
+ PORT_Assert(alg2Mech[calg].calg == calg);
+ return alg2Mech[calg].cmech;
+}
+
+#if defined(TRACE)
+
+static char *
+ssl3_DecodeHandshakeType(int msgType)
+{
+ char *rv;
+ static char line[40];
+
+ switch (msgType) {
+ case ssl_hs_hello_request:
+ rv = "hello_request (0)";
+ break;
+ case ssl_hs_client_hello:
+ rv = "client_hello (1)";
+ break;
+ case ssl_hs_server_hello:
+ rv = "server_hello (2)";
+ break;
+ case ssl_hs_hello_verify_request:
+ rv = "hello_verify_request (3)";
+ break;
+ case ssl_hs_new_session_ticket:
+ rv = "new_session_ticket (4)";
+ break;
+ case ssl_hs_end_of_early_data:
+ rv = "end_of_early_data (5)";
+ break;
+ case ssl_hs_hello_retry_request:
+ rv = "hello_retry_request (6)";
+ break;
+ case ssl_hs_encrypted_extensions:
+ rv = "encrypted_extensions (8)";
+ break;
+ case ssl_hs_certificate:
+ rv = "certificate (11)";
+ break;
+ case ssl_hs_server_key_exchange:
+ rv = "server_key_exchange (12)";
+ break;
+ case ssl_hs_certificate_request:
+ rv = "certificate_request (13)";
+ break;
+ case ssl_hs_server_hello_done:
+ rv = "server_hello_done (14)";
+ break;
+ case ssl_hs_certificate_verify:
+ rv = "certificate_verify (15)";
+ break;
+ case ssl_hs_client_key_exchange:
+ rv = "client_key_exchange (16)";
+ break;
+ case ssl_hs_finished:
+ rv = "finished (20)";
+ break;
+ case ssl_hs_certificate_status:
+ rv = "certificate_status (22)";
+ break;
+ case ssl_hs_key_update:
+ rv = "key_update (24)";
+ break;
+ default:
+ snprintf(line, sizeof(line), "*UNKNOWN* handshake type! (%d)", msgType);
+ rv = line;
+ }
+ return rv;
+}
+
+static char *
+ssl3_DecodeContentType(int msgType)
+{
+ char *rv;
+ static char line[40];
+
+ switch (msgType) {
+ case ssl_ct_change_cipher_spec:
+ rv = "change_cipher_spec (20)";
+ break;
+ case ssl_ct_alert:
+ rv = "alert (21)";
+ break;
+ case ssl_ct_handshake:
+ rv = "handshake (22)";
+ break;
+ case ssl_ct_application_data:
+ rv = "application_data (23)";
+ break;
+ case ssl_ct_ack:
+ rv = "ack (26)";
+ break;
+ default:
+ snprintf(line, sizeof(line), "*UNKNOWN* record type! (%d)", msgType);
+ rv = line;
+ }
+ return rv;
+}
+
+#endif
+
+SSL3Statistics *
+SSL_GetStatistics(void)
+{
+ return &ssl3stats;
+}
+
+typedef struct tooLongStr {
+#if defined(IS_LITTLE_ENDIAN)
+ PRInt32 low;
+ PRInt32 high;
+#else
+ PRInt32 high;
+ PRInt32 low;
+#endif
+} tooLong;
+
+void
+SSL_AtomicIncrementLong(long *x)
+{
+ if ((sizeof *x) == sizeof(PRInt32)) {
+ PR_ATOMIC_INCREMENT((PRInt32 *)x);
+ } else {
+ tooLong *tl = (tooLong *)x;
+ if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
+ PR_ATOMIC_INCREMENT(&tl->high);
+ }
+}
+
+PRBool
+ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
+ const SSLVersionRange *vrange)
+{
+ switch (cipherSuite) {
+ case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
+ case TLS_RSA_WITH_AES_256_CBC_SHA256:
+ case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
+ case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:
+ case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
+ case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:
+ case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
+ case TLS_RSA_WITH_AES_128_CBC_SHA256:
+ case TLS_RSA_WITH_AES_128_GCM_SHA256:
+ case TLS_RSA_WITH_AES_256_GCM_SHA384:
+ case TLS_DHE_DSS_WITH_AES_128_CBC_SHA256:
+ case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256:
+ case TLS_RSA_WITH_NULL_SHA256:
+ case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256:
+ case TLS_DHE_DSS_WITH_AES_256_GCM_SHA384:
+ case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
+ case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
+ case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
+ case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
+ case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
+ case TLS_DHE_RSA_WITH_AES_256_GCM_SHA384:
+ case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256:
+ case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
+ case TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256:
+ return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
+ vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
+
+ /* RFC 4492: ECC cipher suites need TLS extensions to negotiate curves and
+ * point formats.*/
+ case TLS_ECDH_ECDSA_WITH_NULL_SHA:
+ case TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
+ case TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA:
+ case TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA:
+ case TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA:
+ case TLS_ECDHE_ECDSA_WITH_NULL_SHA:
+ case TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
+ case TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA:
+ case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
+ case TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
+ case TLS_ECDH_RSA_WITH_NULL_SHA:
+ case TLS_ECDH_RSA_WITH_RC4_128_SHA:
+ case TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA:
+ case TLS_ECDH_RSA_WITH_AES_128_CBC_SHA:
+ case TLS_ECDH_RSA_WITH_AES_256_CBC_SHA:
+ case TLS_ECDHE_RSA_WITH_NULL_SHA:
+ case TLS_ECDHE_RSA_WITH_RC4_128_SHA:
+ case TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
+ case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
+ case TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
+ return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_0 &&
+ vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
+
+ case TLS_AES_128_GCM_SHA256:
+ case TLS_AES_256_GCM_SHA384:
+ case TLS_CHACHA20_POLY1305_SHA256:
+ return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3;
+
+ default:
+ return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3;
+ }
+}
+
+/* return pointer to ssl3CipherSuiteDef for suite, or NULL */
+/* XXX This does a linear search. A binary search would be better. */
+const ssl3CipherSuiteDef *
+ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
+{
+ int cipher_suite_def_len =
+ sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
+ int i;
+
+ for (i = 0; i < cipher_suite_def_len; i++) {
+ if (cipher_suite_defs[i].cipher_suite == suite)
+ return &cipher_suite_defs[i];
+ }
+ PORT_Assert(PR_FALSE); /* We should never get here. */
+ PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
+ return NULL;
+}
+
+/* Find the cipher configuration struct associate with suite */
+/* XXX This does a linear search. A binary search would be better. */
+static ssl3CipherSuiteCfg *
+ssl_LookupCipherSuiteCfgMutable(ssl3CipherSuite suite,
+ ssl3CipherSuiteCfg *suites)
+{
+ int i;
+
+ for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ if (suites[i].cipher_suite == suite)
+ return &suites[i];
+ }
+ /* return NULL and let the caller handle it. */
+ PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
+ return NULL;
+}
+
+const ssl3CipherSuiteCfg *
+ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, const ssl3CipherSuiteCfg *suites)
+{
+ return ssl_LookupCipherSuiteCfgMutable(suite,
+ CONST_CAST(ssl3CipherSuiteCfg, suites));
+}
+
+static PRBool
+ssl_NamedGroupTypeEnabled(const sslSocket *ss, SSLKEAType keaType)
+{
+ unsigned int i;
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ss->namedGroupPreferences[i] &&
+ ss->namedGroupPreferences[i]->keaType == keaType) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+static PRBool
+ssl_KEAEnabled(const sslSocket *ss, SSLKEAType keaType)
+{
+ switch (keaType) {
+ case ssl_kea_rsa:
+ return PR_TRUE;
+
+ case ssl_kea_dh:
+ case ssl_kea_dh_psk: {
+ if (ss->sec.isServer && !ss->opt.enableServerDhe) {
+ return PR_FALSE;
+ }
+
+ if (ss->sec.isServer) {
+ /* If the server requires named FFDHE groups, then the client
+ * must have included an FFDHE group. peerSupportsFfdheGroups
+ * is set to true in ssl_HandleSupportedGroupsXtn(). */
+ if (ss->opt.requireDHENamedGroups &&
+ !ss->xtnData.peerSupportsFfdheGroups) {
+ return PR_FALSE;
+ }
+
+ /* We can use the weak DH group if all of these are true:
+ * 1. We don't require named groups.
+ * 2. The peer doesn't support named groups.
+ * 3. This isn't TLS 1.3.
+ * 4. The weak group is enabled. */
+ if (!ss->opt.requireDHENamedGroups &&
+ !ss->xtnData.peerSupportsFfdheGroups &&
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ ss->ssl3.dheWeakGroupEnabled) {
+ return PR_TRUE;
+ }
+ } else {
+ if (ss->vrange.min < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ !ss->opt.requireDHENamedGroups) {
+ /* The client enables DHE cipher suites even if no DHE groups
+ * are enabled. Only if this isn't TLS 1.3 and named groups
+ * are not required. */
+ return PR_TRUE;
+ }
+ }
+ return ssl_NamedGroupTypeEnabled(ss, ssl_kea_dh);
+ }
+
+ case ssl_kea_ecdh:
+ case ssl_kea_ecdh_psk:
+ return ssl_NamedGroupTypeEnabled(ss, ssl_kea_ecdh);
+
+ case ssl_kea_tls13_any:
+ return PR_TRUE;
+
+ case ssl_kea_fortezza:
+ default:
+ PORT_Assert(0);
+ }
+ return PR_FALSE;
+}
+
+static PRBool
+ssl_HasCert(const sslSocket *ss, PRUint16 maxVersion, SSLAuthType authType)
+{
+ PRCList *cursor;
+ if (authType == ssl_auth_null || authType == ssl_auth_psk || authType == ssl_auth_tls13_any) {
+ return PR_TRUE;
+ }
+ for (cursor = PR_NEXT_LINK(&ss->serverCerts);
+ cursor != &ss->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *cert = (sslServerCert *)cursor;
+ if (!cert->serverKeyPair ||
+ !cert->serverKeyPair->privKey ||
+ !cert->serverCertChain ||
+ !SSL_CERT_IS(cert, authType)) {
+ continue;
+ }
+ /* When called from ssl3_config_match_init(), all the EC curves will be
+ * enabled, so this will essentially do nothing (unless we implement
+ * curve configuration). However, once we have seen the
+ * supported_groups extension and this is called from config_match(),
+ * this will filter out certificates with an unsupported curve.
+ *
+ * If we might negotiate TLS 1.3, skip this test as group configuration
+ * doesn't affect choices in TLS 1.3.
+ */
+ if (maxVersion < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ (authType == ssl_auth_ecdsa ||
+ authType == ssl_auth_ecdh_ecdsa ||
+ authType == ssl_auth_ecdh_rsa) &&
+ !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
+ continue;
+ }
+ return PR_TRUE;
+ }
+ if (authType == ssl_auth_rsa_sign) {
+ return ssl_HasCert(ss, maxVersion, ssl_auth_rsa_pss);
+ }
+ return PR_FALSE;
+}
+
+/* return true if the scheme is allowed by policy, This prevents
+ * failures later when our actual signatures are rejected by
+ * policy by either ssl code, or lower level NSS code */
+static PRBool
+ssl_SchemePolicyOK(SSLSignatureScheme scheme, PRUint32 require)
+{
+ /* Hash policy. */
+ PRUint32 policy;
+ SECOidTag hashOID = ssl3_HashTypeToOID(ssl_SignatureSchemeToHashType(scheme));
+ SECOidTag sigOID;
+
+ /* policy bits needed to enable a SignatureScheme */
+ SECStatus rv = NSS_GetAlgorithmPolicy(hashOID, &policy);
+ if (rv == SECSuccess &&
+ (policy & require) != require) {
+ return PR_FALSE;
+ }
+
+ /* ssl_SignatureSchemeToAuthType reports rsa for rsa_pss_rsae, but we
+ * actually implement pss signatures when we sign, so just use RSA_PSS
+ * for all RSA PSS Siganture schemes */
+ if (ssl_IsRsaPssSignatureScheme(scheme)) {
+ sigOID = SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
+ } else {
+ sigOID = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
+ }
+ /* Signature Policy. */
+ rv = NSS_GetAlgorithmPolicy(sigOID, &policy);
+ if (rv == SECSuccess &&
+ (policy & require) != require) {
+ return PR_FALSE;
+ }
+ return PR_TRUE;
+}
+
+/* Check that a signature scheme is accepted.
+ * Both by policy and by having a token that supports it. */
+static PRBool
+ssl_SignatureSchemeAccepted(PRUint16 minVersion,
+ SSLSignatureScheme scheme,
+ PRBool forCert)
+{
+ /* Disable RSA-PSS schemes if there are no tokens to verify them. */
+ if (ssl_IsRsaPssSignatureScheme(scheme)) {
+ if (!PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) {
+ return PR_FALSE;
+ }
+ } else if (!forCert && ssl_IsRsaPkcs1SignatureScheme(scheme)) {
+ /* Disable PKCS#1 signatures if we are limited to TLS 1.3.
+ * We still need to advertise PKCS#1 signatures in CH and CR
+ * for certificate signatures.
+ */
+ if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ return PR_FALSE;
+ }
+ } else if (ssl_IsDsaSignatureScheme(scheme)) {
+ /* DSA: not in TLS 1.3, and check policy. */
+ if (minVersion >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ return PR_FALSE;
+ }
+ }
+
+ return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
+}
+
+static SECStatus
+ssl_CheckSignatureSchemes(sslSocket *ss)
+{
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) {
+ return SECSuccess;
+ }
+
+ /* If this is a server using TLS 1.3, we just need to have one signature
+ * scheme for which we have a usable certificate.
+ *
+ * Note: Certificates for earlier TLS versions are checked along with the
+ * cipher suite in ssl3_config_match_init. */
+ if (ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ PRBool foundCert = PR_FALSE;
+ for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ SSLAuthType authType =
+ ssl_SignatureSchemeToAuthType(ss->ssl3.signatureSchemes[i]);
+ if (ssl_HasCert(ss, ss->vrange.max, authType)) {
+ foundCert = PR_TRUE;
+ break;
+ }
+ }
+ if (!foundCert) {
+ PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ }
+
+ /* Ensure that there is a signature scheme that can be accepted.*/
+ for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ if (ssl_SignatureSchemeAccepted(ss->vrange.min,
+ ss->ssl3.signatureSchemes[i],
+ PR_FALSE /* forCert */)) {
+ return SECSuccess;
+ }
+ }
+ PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+}
+
+/* For a server, check that a signature scheme that can be used with the
+ * provided authType is both enabled and usable. */
+static PRBool
+ssl_HasSignatureScheme(const sslSocket *ss, SSLAuthType authType)
+{
+ PORT_Assert(ss->sec.isServer);
+ PORT_Assert(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version);
+ PORT_Assert(authType != ssl_auth_null);
+ PORT_Assert(authType != ssl_auth_tls13_any);
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2 ||
+ authType == ssl_auth_rsa_decrypt ||
+ authType == ssl_auth_ecdh_rsa ||
+ authType == ssl_auth_ecdh_ecdsa) {
+ return PR_TRUE;
+ }
+ for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ SSLSignatureScheme scheme = ss->ssl3.signatureSchemes[i];
+ SSLAuthType schemeAuthType = ssl_SignatureSchemeToAuthType(scheme);
+ PRBool acceptable = authType == schemeAuthType ||
+ (schemeAuthType == ssl_auth_rsa_pss &&
+ authType == ssl_auth_rsa_sign);
+ if (acceptable && ssl_SignatureSchemeAccepted(ss->version, scheme, PR_FALSE /* forCert */)) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+/* Initialize the suite->isPresent value for config_match
+ * Returns count of enabled ciphers supported by extant tokens,
+ * regardless of policy or user preference.
+ * If this returns zero, the user cannot do SSL v3.
+ */
+unsigned int
+ssl3_config_match_init(sslSocket *ss)
+{
+ ssl3CipherSuiteCfg *suite;
+ const ssl3CipherSuiteDef *cipher_def;
+ SSLCipherAlgorithm cipher_alg;
+ CK_MECHANISM_TYPE cipher_mech;
+ SSLAuthType authType;
+ SSLKEAType keaType;
+ unsigned int i;
+ unsigned int numPresent = 0;
+ unsigned int numEnabled = 0;
+
+ PORT_Assert(ss);
+ if (!ss) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return 0;
+ }
+ if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
+ return 0;
+ }
+ if (ss->sec.isServer && ss->psk &&
+ PR_CLIST_IS_EMPTY(&ss->serverCerts) &&
+ (ss->opt.requestCertificate || ss->opt.requireCertificate)) {
+ /* PSK and certificate auth cannot be combined. */
+ PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
+ return 0;
+ }
+ if (ssl_CheckSignatureSchemes(ss) != SECSuccess) {
+ return 0; /* Code already set. */
+ }
+
+ ssl_FilterSupportedGroups(ss);
+ for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ suite = &ss->cipherSuites[i];
+ if (suite->enabled) {
+ ++numEnabled;
+ /* We need the cipher defs to see if we have a token that can handle
+ * this cipher. It isn't part of the static definition.
+ */
+ cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
+ if (!cipher_def) {
+ suite->isPresent = PR_FALSE;
+ continue;
+ }
+ cipher_alg = ssl_GetBulkCipherDef(cipher_def)->calg;
+ cipher_mech = ssl3_Alg2Mech(cipher_alg);
+
+ /* Mark the suites that are backed by real tokens, certs and keys */
+ suite->isPresent = PR_TRUE;
+
+ authType = kea_defs[cipher_def->key_exchange_alg].authKeyType;
+ if (authType != ssl_auth_null && authType != ssl_auth_tls13_any) {
+ if (ss->sec.isServer &&
+ !(ssl_HasCert(ss, ss->vrange.max, authType) &&
+ ssl_HasSignatureScheme(ss, authType))) {
+ suite->isPresent = PR_FALSE;
+ } else if (!PK11_TokenExists(auth_alg_defs[authType])) {
+ suite->isPresent = PR_FALSE;
+ }
+ }
+
+ keaType = kea_defs[cipher_def->key_exchange_alg].exchKeyType;
+ if (keaType != ssl_kea_null &&
+ keaType != ssl_kea_tls13_any &&
+ !PK11_TokenExists(kea_alg_defs[keaType])) {
+ suite->isPresent = PR_FALSE;
+ }
+
+ if (cipher_alg != ssl_calg_null &&
+ !PK11_TokenExists(cipher_mech)) {
+ suite->isPresent = PR_FALSE;
+ }
+
+ if (suite->isPresent) {
+ ++numPresent;
+ }
+ }
+ }
+ PORT_AssertArg(numPresent > 0 || numEnabled == 0);
+ if (numPresent == 0) {
+ PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
+ }
+ return numPresent;
+}
+
+/* Return PR_TRUE if suite is usable. This if the suite is permitted by policy,
+ * enabled, has a certificate (as needed), has a viable key agreement method, is
+ * usable with the negotiated TLS version, and is otherwise usable. */
+PRBool
+ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
+ const SSLVersionRange *vrange, const sslSocket *ss)
+{
+ const ssl3CipherSuiteDef *cipher_def;
+ const ssl3KEADef *kea_def;
+
+ if (!suite) {
+ PORT_Assert(suite);
+ return PR_FALSE;
+ }
+
+ PORT_Assert(policy != SSL_NOT_ALLOWED);
+ if (policy == SSL_NOT_ALLOWED)
+ return PR_FALSE;
+
+ if (!suite->enabled || !suite->isPresent)
+ return PR_FALSE;
+
+ if ((suite->policy == SSL_NOT_ALLOWED) ||
+ (suite->policy > policy))
+ return PR_FALSE;
+
+ PORT_Assert(ss != NULL);
+ cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
+ PORT_Assert(cipher_def != NULL);
+ kea_def = &kea_defs[cipher_def->key_exchange_alg];
+ PORT_Assert(kea_def != NULL);
+ if (!ssl_KEAEnabled(ss, kea_def->exchKeyType)) {
+ return PR_FALSE;
+ }
+
+ if (ss->sec.isServer && !ssl_HasCert(ss, vrange->max, kea_def->authKeyType)) {
+ return PR_FALSE;
+ }
+
+ /* If a PSK is selected, disable suites that use a different hash than
+ * the PSK. We advertise non-PSK-compatible suites in the CH, as we could
+ * fallback to certificate auth. The client handler will check hash
+ * compatibility before committing to use the PSK. */
+ if (ss->xtnData.selectedPsk) {
+ if (ss->xtnData.selectedPsk->hash != cipher_def->prf_hash) {
+ return PR_FALSE;
+ }
+ }
+
+ return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange);
+}
+
+/* For TLS 1.3, when resuming, check for a ciphersuite that is both compatible
+ * with the identified ciphersuite and enabled. */
+static PRBool
+tls13_ResumptionCompatible(sslSocket *ss, ssl3CipherSuite suite)
+{
+ SSLVersionRange vrange = { SSL_LIBRARY_VERSION_TLS_1_3,
+ SSL_LIBRARY_VERSION_TLS_1_3 };
+ SSLHashType hash = tls13_GetHashForCipherSuite(suite);
+ for (unsigned int i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
+ if (cipher_suite_defs[i].prf_hash == hash) {
+ const ssl3CipherSuiteCfg *suiteCfg =
+ ssl_LookupCipherSuiteCfg(cipher_suite_defs[i].cipher_suite,
+ ss->cipherSuites);
+ if (suite && ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
+ return PR_TRUE;
+ }
+ }
+ }
+ return PR_FALSE;
+}
+
+/*
+ * Null compression, mac and encryption functions
+ */
+SECStatus
+Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen, unsigned int maxOutputLen,
+ const unsigned char *input, unsigned int inputLen)
+{
+ if (inputLen > maxOutputLen) {
+ *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ return SECFailure;
+ }
+ *outputLen = inputLen;
+ if (inputLen > 0 && input != output) {
+ PORT_Memcpy(output, input, inputLen);
+ }
+ return SECSuccess;
+}
+
+/*
+ * SSL3 Utility functions
+ */
+
+static void
+ssl_SetSpecVersions(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ spec->version = ss->version;
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ tls13_SetSpecRecordVersion(ss, spec);
+ } else if (IS_DTLS(ss)) {
+ spec->recordVersion = dtls_TLSVersionToDTLSVersion(ss->version);
+ } else {
+ spec->recordVersion = ss->version;
+ }
+}
+
+/* allowLargerPeerVersion controls whether the function will select the
+ * highest enabled SSL version or fail when peerVersion is greater than the
+ * highest enabled version.
+ *
+ * If allowLargerPeerVersion is true, peerVersion is the peer's highest
+ * enabled version rather than the peer's selected version.
+ */
+SECStatus
+ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
+ PRBool allowLargerPeerVersion)
+{
+ SSL3ProtocolVersion negotiated;
+
+ /* Prevent negotiating to a lower version in response to a TLS 1.3 HRR. */
+ if (ss->ssl3.hs.helloRetry) {
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
+ return SECFailure;
+ }
+
+ if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
+ PORT_SetError(SSL_ERROR_SSL_DISABLED);
+ return SECFailure;
+ }
+
+ if (peerVersion < ss->vrange.min ||
+ (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
+ return SECFailure;
+ }
+
+ negotiated = PR_MIN(peerVersion, ss->vrange.max);
+ PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, negotiated));
+ if (ss->firstHsDone && ss->version != negotiated) {
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
+ return SECFailure;
+ }
+
+ ss->version = negotiated;
+ return SECSuccess;
+}
+
+/* Used by the client when the server produces a version number.
+ * This reads, validates, and normalizes the value. */
+SECStatus
+ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b, unsigned int *len,
+ SSL3ProtocolVersion *version)
+{
+ SSL3ProtocolVersion v;
+ PRUint32 temp;
+ SECStatus rv;
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, b, len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* alert has been sent */
+ }
+ v = (SSL3ProtocolVersion)temp;
+
+ if (IS_DTLS(ss)) {
+ v = dtls_DTLSVersionToTLSVersion(v);
+ /* Check for failure. */
+ if (!v || v > SSL_LIBRARY_VERSION_MAX_SUPPORTED) {
+ SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ return SECFailure;
+ }
+ }
+
+ /* You can't negotiate TLS 1.3 this way. */
+ if (v >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ return SECFailure;
+ }
+ *version = v;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_GetNewRandom(SSL3Random random)
+{
+ SECStatus rv;
+
+ rv = PK11_GenerateRandom(random, SSL3_RANDOM_LENGTH);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
+ }
+ return rv;
+}
+
+SECStatus
+ssl3_SignHashesWithPrivKey(SSL3Hashes *hash, SECKEYPrivateKey *key,
+ SSLSignatureScheme scheme, PRBool isTls, SECItem *buf)
+{
+ SECStatus rv = SECFailure;
+ PRBool doDerEncode = PR_FALSE;
+ PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(scheme);
+ SECItem hashItem;
+
+ buf->data = NULL;
+
+ switch (SECKEY_GetPrivateKeyType(key)) {
+ case rsaKey:
+ hashItem.data = hash->u.raw;
+ hashItem.len = hash->len;
+ break;
+ case dsaKey:
+ doDerEncode = isTls;
+ /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
+ * In that case, we use just the SHA1 part. */
+ if (hash->hashAlg == ssl_hash_none) {
+ hashItem.data = hash->u.s.sha;
+ hashItem.len = sizeof(hash->u.s.sha);
+ } else {
+ hashItem.data = hash->u.raw;
+ hashItem.len = hash->len;
+ }
+ break;
+ case ecKey:
+ doDerEncode = PR_TRUE;
+ /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
+ * In that case, we use just the SHA1 part. */
+ if (hash->hashAlg == ssl_hash_none) {
+ hashItem.data = hash->u.s.sha;
+ hashItem.len = sizeof(hash->u.s.sha);
+ } else {
+ hashItem.data = hash->u.raw;
+ hashItem.len = hash->len;
+ }
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ goto done;
+ }
+ PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
+
+ if (useRsaPss || hash->hashAlg == ssl_hash_none) {
+ CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
+ int signatureLen = PK11_SignatureLen(key);
+
+ SECItem *params = NULL;
+ CK_RSA_PKCS_PSS_PARAMS pssParams;
+ SECItem pssParamsItem = { siBuffer,
+ (unsigned char *)&pssParams,
+ sizeof(pssParams) };
+
+ if (signatureLen <= 0) {
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ goto done;
+ }
+
+ buf->len = (unsigned)signatureLen;
+ buf->data = (unsigned char *)PORT_Alloc(signatureLen);
+ if (!buf->data)
+ goto done; /* error code was set. */
+
+ if (useRsaPss) {
+ pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
+ pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
+ pssParams.sLen = hashItem.len;
+ params = &pssParamsItem;
+ mech = CKM_RSA_PKCS_PSS;
+ }
+
+ rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem);
+ } else {
+ SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg);
+ rv = SGN_Digest(key, hashOID, buf, &hashItem);
+ }
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
+ } else if (doDerEncode) {
+ SECItem derSig = { siBuffer, NULL, 0 };
+
+ /* This also works for an ECDSA signature */
+ rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
+ if (rv == SECSuccess) {
+ PORT_Free(buf->data); /* discard unencoded signature. */
+ *buf = derSig; /* give caller encoded signature. */
+ } else if (derSig.data) {
+ PORT_Free(derSig.data);
+ }
+ }
+
+ PRINT_BUF(60, (NULL, "signed hashes", (unsigned char *)buf->data, buf->len));
+done:
+ if (rv != SECSuccess && buf->data) {
+ PORT_Free(buf->data);
+ buf->data = NULL;
+ }
+ return rv;
+}
+
+/* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
+SECStatus
+ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key,
+ SECItem *buf)
+{
+ SECStatus rv = SECFailure;
+ PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
+ SSLSignatureScheme scheme = ss->ssl3.hs.signatureScheme;
+
+ rv = ssl3_SignHashesWithPrivKey(hash, key, scheme, isTLS, buf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->sec.isServer) {
+ ss->sec.signatureScheme = scheme;
+ ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
+ }
+
+ return SECSuccess;
+}
+
+/* Called from ssl3_VerifySignedHashes and tls13_HandleCertificateVerify. */
+SECStatus
+ssl_VerifySignedHashesWithPubKey(sslSocket *ss, SECKEYPublicKey *key,
+ SSLSignatureScheme scheme,
+ SSL3Hashes *hash, SECItem *buf)
+{
+ SECItem *signature = NULL;
+ SECStatus rv = SECFailure;
+ SECItem hashItem;
+ SECOidTag encAlg;
+ SECOidTag hashAlg;
+ void *pwArg = ss->pkcs11PinArg;
+ PRBool isRsaPssScheme = ssl_IsRsaPssSignatureScheme(scheme);
+
+ PRINT_BUF(60, (NULL, "check signed hashes", buf->data, buf->len));
+
+ hashAlg = ssl3_HashTypeToOID(hash->hashAlg);
+ switch (SECKEY_GetPublicKeyType(key)) {
+ case rsaKey:
+ encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
+ hashItem.data = hash->u.raw;
+ hashItem.len = hash->len;
+ if (scheme == ssl_sig_none) {
+ scheme = ssl_sig_rsa_pkcs1_sha1md5;
+ }
+ break;
+ case dsaKey:
+ encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
+ /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
+ * In that case, we use just the SHA1 part. */
+ if (hash->hashAlg == ssl_hash_none) {
+ hashItem.data = hash->u.s.sha;
+ hashItem.len = sizeof(hash->u.s.sha);
+ } else {
+ hashItem.data = hash->u.raw;
+ hashItem.len = hash->len;
+ }
+ /* Allow DER encoded DSA signatures in SSL 3.0 */
+ if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0 ||
+ buf->len != SECKEY_SignatureLen(key)) {
+ signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key));
+ if (!signature) {
+ PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
+ goto loser;
+ }
+ buf = signature;
+ }
+ if (scheme == ssl_sig_none) {
+ scheme = ssl_sig_dsa_sha1;
+ }
+ break;
+
+ case ecKey:
+ encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
+ /* ssl_hash_none is used to specify the MD5/SHA1 concatenated hash.
+ * In that case, we use just the SHA1 part.
+ * ECDSA signatures always encode the integers r and s using ASN.1
+ * (unlike DSA where ASN.1 encoding is used with TLS but not with
+ * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
+ */
+ if (hash->hashAlg == ssl_hash_none) {
+ hashAlg = SEC_OID_SHA1;
+ hashItem.data = hash->u.s.sha;
+ hashItem.len = sizeof(hash->u.s.sha);
+ } else {
+ hashItem.data = hash->u.raw;
+ hashItem.len = hash->len;
+ }
+ if (scheme == ssl_sig_none) {
+ scheme = ssl_sig_ecdsa_sha1;
+ }
+ break;
+
+ default:
+ PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
+ goto loser;
+ }
+
+ PRINT_BUF(60, (NULL, "hash(es) to be verified",
+ hashItem.data, hashItem.len));
+
+ if (isRsaPssScheme ||
+ hashAlg == SEC_OID_UNKNOWN ||
+ SECKEY_GetPublicKeyType(key) == dsaKey) {
+ /* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
+ * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
+ * above always removes the DER encoding of DSA signatures when
+ * present. Thus DSA signatures are always verified with PK11_Verify.
+ */
+ CK_MECHANISM_TYPE mech = PK11_MapSignKeyType(key->keyType);
+
+ SECItem *params = NULL;
+ CK_RSA_PKCS_PSS_PARAMS pssParams;
+ SECItem pssParamsItem = { siBuffer,
+ (unsigned char *)&pssParams,
+ sizeof(pssParams) };
+
+ if (isRsaPssScheme) {
+ pssParams.hashAlg = ssl3_GetHashMechanismByHashType(hash->hashAlg);
+ pssParams.mgf = ssl3_GetMgfMechanismByHashType(hash->hashAlg);
+ pssParams.sLen = hashItem.len;
+ params = &pssParamsItem;
+ mech = CKM_RSA_PKCS_PSS;
+ }
+
+ rv = PK11_VerifyWithMechanism(key, mech, params, buf, &hashItem, pwArg);
+ } else {
+ rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
+ pwArg);
+ }
+ if (signature) {
+ SECITEM_FreeItem(signature, PR_TRUE);
+ }
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
+ }
+ if (!ss->sec.isServer) {
+ ss->sec.signatureScheme = scheme;
+ ss->sec.authType = ssl_SignatureSchemeToAuthType(scheme);
+ }
+
+loser:
+#ifdef UNSAFE_FUZZER_MODE
+ rv = SECSuccess;
+ PORT_SetError(0);
+#endif
+ return rv;
+}
+
+/* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
+SECStatus
+ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash,
+ SECItem *buf)
+{
+ SECKEYPublicKey *pubKey =
+ SECKEY_ExtractPublicKey(&ss->sec.peerCert->subjectPublicKeyInfo);
+ if (pubKey == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
+ return SECFailure;
+ }
+ SECStatus rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, scheme,
+ hash, buf);
+ SECKEY_DestroyPublicKey(pubKey);
+ return rv;
+}
+
+/* Caller must set hiLevel error code. */
+/* Called from ssl3_ComputeDHKeyHash
+ * which are called from ssl3_HandleServerKeyExchange.
+ *
+ * hashAlg: ssl_hash_none indicates the pre-1.2, MD5/SHA1 combination hash.
+ */
+SECStatus
+ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
+ PRUint8 *hashBuf, unsigned int bufLen,
+ SSL3Hashes *hashes)
+{
+ SECStatus rv;
+ SECOidTag hashOID;
+ PRUint32 policy;
+
+ if (hashAlg == ssl_hash_none) {
+ if ((NSS_GetAlgorithmPolicy(SEC_OID_SHA1, &policy) == SECSuccess) &&
+ !(policy & NSS_USE_ALG_IN_SSL_KX)) {
+ ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
+ return SECFailure;
+ }
+ rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ return rv;
+ }
+ rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return rv;
+ }
+ hashes->len = MD5_LENGTH + SHA1_LENGTH;
+ } else {
+ hashOID = ssl3_HashTypeToOID(hashAlg);
+ if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) &&
+ !(policy & NSS_USE_ALG_IN_SSL_KX)) {
+ ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
+ return SECFailure;
+ }
+ hashes->len = HASH_ResultLenByOidTag(hashOID);
+ if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) {
+ ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
+ return SECFailure;
+ }
+ rv = PK11_HashBuf(hashOID, hashes->u.raw, hashBuf, bufLen);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return rv;
+ }
+ }
+ hashes->hashAlg = hashAlg;
+ return SECSuccess;
+}
+
+/* Caller must set hiLevel error code. */
+/* Called from ssl3_HandleServerKeyExchange. */
+static SECStatus
+ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes,
+ SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY)
+{
+ sslBuffer buf = SSL_BUFFER_EMPTY;
+ SECStatus rv;
+ unsigned int yLen;
+ unsigned int i;
+
+ PORT_Assert(dh_p.data);
+ PORT_Assert(dh_g.data);
+ PORT_Assert(dh_Ys.data);
+
+ rv = sslBuffer_Append(&buf, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_Append(&buf, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* p */
+ rv = sslBuffer_AppendVariable(&buf, dh_p.data, dh_p.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* g */
+ rv = sslBuffer_AppendVariable(&buf, dh_g.data, dh_g.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* y - complicated by padding */
+ yLen = padY ? dh_p.len : dh_Ys.len;
+ rv = sslBuffer_AppendNumber(&buf, yLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* If we're padding Y, dh_Ys can't be longer than dh_p. */
+ PORT_Assert(!padY || dh_p.len >= dh_Ys.len);
+ for (i = dh_Ys.len; i < yLen; ++i) {
+ rv = sslBuffer_AppendNumber(&buf, 0, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ rv = sslBuffer_Append(&buf, dh_Ys.data, dh_Ys.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl3_ComputeCommonKeyHash(hashAlg, SSL_BUFFER_BASE(&buf),
+ SSL_BUFFER_LEN(&buf), hashes);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ PRINT_BUF(95, (NULL, "DHkey hash: ", SSL_BUFFER_BASE(&buf),
+ SSL_BUFFER_LEN(&buf)));
+ if (hashAlg == ssl_hash_none) {
+ PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
+ hashes->u.s.md5, MD5_LENGTH));
+ PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
+ hashes->u.s.sha, SHA1_LENGTH));
+ } else {
+ PRINT_BUF(95, (NULL, "DHkey hash: result",
+ hashes->u.raw, hashes->len));
+ }
+
+ sslBuffer_Clear(&buf);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&buf);
+ return SECFailure;
+}
+
+static SECStatus
+ssl3_SetupPendingCipherSpec(sslSocket *ss, SSLSecretDirection direction,
+ const ssl3CipherSuiteDef *suiteDef,
+ ssl3CipherSpec **specp)
+{
+ ssl3CipherSpec *spec;
+ const ssl3CipherSpec *prev;
+
+ prev = (direction == ssl_secret_write) ? ss->ssl3.cwSpec : ss->ssl3.crSpec;
+ if (prev->epoch == PR_UINT16_MAX) {
+ PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
+ return SECFailure;
+ }
+
+ spec = ssl_CreateCipherSpec(ss, direction);
+ if (!spec) {
+ return SECFailure;
+ }
+
+ spec->cipherDef = ssl_GetBulkCipherDef(suiteDef);
+ spec->macDef = ssl_GetMacDef(ss, suiteDef);
+
+ spec->epoch = prev->epoch + 1;
+ spec->nextSeqNum = 0;
+ if (IS_DTLS(ss) && direction == ssl_secret_read) {
+ dtls_InitRecvdRecords(&spec->recvdRecords);
+ }
+ ssl_SetSpecVersions(ss, spec);
+
+ ssl_SaveCipherSpec(ss, spec);
+ *specp = spec;
+ return SECSuccess;
+}
+
+/* Fill in the pending cipher spec with info from the selected ciphersuite.
+** This is as much initialization as we can do without having key material.
+** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
+** Caller must hold the ssl3 handshake lock.
+** Acquires & releases SpecWriteLock.
+*/
+SECStatus
+ssl3_SetupBothPendingCipherSpecs(sslSocket *ss)
+{
+ ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
+ SSL3KeyExchangeAlgorithm kea;
+ const ssl3CipherSuiteDef *suiteDef;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ ssl_GetSpecWriteLock(ss); /*******************************/
+
+ /* This hack provides maximal interoperability with SSL 3 servers. */
+ if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
+ /* SSL records are not being MACed. */
+ ss->ssl3.cwSpec->version = ss->version;
+ }
+
+ SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
+ SSL_GETPID(), ss->fd, suite));
+
+ suiteDef = ssl_LookupCipherSuiteDef(suite);
+ if (suiteDef == NULL) {
+ goto loser;
+ }
+
+ if (IS_DTLS(ss)) {
+ /* Double-check that we did not pick an RC4 suite */
+ PORT_Assert(suiteDef->bulk_cipher_alg != cipher_rc4);
+ }
+
+ ss->ssl3.hs.suite_def = suiteDef;
+
+ kea = suiteDef->key_exchange_alg;
+ ss->ssl3.hs.kea_def = &kea_defs[kea];
+ PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
+
+ rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_read, suiteDef,
+ &ss->ssl3.prSpec);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = ssl3_SetupPendingCipherSpec(ss, ssl_secret_write, suiteDef,
+ &ss->ssl3.pwSpec);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
+ ss->ssl3.prSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
+ ss->opt.recordSizeLimit);
+ ss->ssl3.pwSpec->recordSizeLimit = PR_MIN(MAX_FRAGMENT_LENGTH,
+ ss->xtnData.recordSizeLimit);
+ }
+
+ ssl_ReleaseSpecWriteLock(ss); /*******************************/
+ return SECSuccess;
+
+loser:
+ ssl_ReleaseSpecWriteLock(ss);
+ return SECFailure;
+}
+
+/* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data which
+ * is included in the MAC or AEAD additional data) to |buf|. See
+ * https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the definition of the
+ * AEAD additional data.
+ *
+ * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
+ * pseudo-header definition to use should be decided based on the version of
+ * the protocol that was negotiated when the cipher spec became current, NOT
+ * based on the version value in the record itself, and the decision is passed
+ * to this function as the |includesVersion| argument. But, the |version|
+ * argument should be the record's version value.
+ */
+static SECStatus
+ssl3_BuildRecordPseudoHeader(DTLSEpoch epoch,
+ sslSequenceNumber seqNum,
+ SSLContentType ct,
+ PRBool includesVersion,
+ SSL3ProtocolVersion version,
+ PRBool isDTLS,
+ int length,
+ sslBuffer *buf)
+{
+ SECStatus rv;
+ if (isDTLS) {
+ rv = sslBuffer_AppendNumber(buf, epoch, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(buf, seqNum, 6);
+ } else {
+ rv = sslBuffer_AppendNumber(buf, seqNum, 8);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(buf, ct, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* SSL3 MAC doesn't include the record's version field. */
+ if (includesVersion) {
+ /* TLS MAC and AEAD additional data include version. */
+ rv = sslBuffer_AppendNumber(buf, version, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ rv = sslBuffer_AppendNumber(buf, length, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Initialize encryption and MAC contexts for pending spec.
+ * Master Secret already is derived.
+ * Caller holds Spec write lock.
+ */
+static SECStatus
+ssl3_InitPendingContexts(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ CK_MECHANISM_TYPE encMechanism;
+ CK_ATTRIBUTE_TYPE encMode;
+ SECItem macParam;
+ CK_ULONG macLength;
+ SECItem iv;
+ SSLCipherAlgorithm calg;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
+
+ calg = spec->cipherDef->calg;
+ PORT_Assert(alg2Mech[calg].calg == calg);
+
+ if (spec->cipherDef->type != type_aead) {
+ macLength = spec->macDef->mac_size;
+
+ /*
+ ** Now setup the MAC contexts,
+ ** crypto contexts are setup below.
+ */
+ macParam.data = (unsigned char *)&macLength;
+ macParam.len = sizeof(macLength);
+ macParam.type = siBuffer;
+
+ spec->keyMaterial.macContext = PK11_CreateContextBySymKey(
+ spec->macDef->mmech, CKA_SIGN, spec->keyMaterial.macKey, &macParam);
+ if (!spec->keyMaterial.macContext) {
+ ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ /*
+ ** Now setup the crypto contexts.
+ */
+ if (calg == ssl_calg_null) {
+ spec->cipher = Null_Cipher;
+ return SECSuccess;
+ }
+
+ encMechanism = ssl3_Alg2Mech(calg);
+ encMode = (spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT;
+ if (spec->cipherDef->type == type_aead) {
+ encMode |= CKA_NSS_MESSAGE;
+ iv.data = NULL;
+ iv.len = 0;
+ } else {
+ spec->cipher = (SSLCipher)PK11_CipherOp;
+ iv.data = spec->keyMaterial.iv;
+ iv.len = spec->cipherDef->iv_size;
+ }
+
+ /*
+ * build the context
+ */
+ spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
+ spec->keyMaterial.key,
+ &iv);
+ if (!spec->cipherContext) {
+ ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Complete the initialization of all keys, ciphers, MACs and their contexts
+ * for the pending Cipher Spec.
+ * Called from: ssl3_SendClientKeyExchange (for Full handshake)
+ * ssl3_HandleRSAClientKeyExchange (for Full handshake)
+ * ssl3_HandleServerHello (for session restart)
+ * ssl3_HandleClientHello (for session restart)
+ * Sets error code, but caller probably should override to disambiguate.
+ *
+ * If |secret| is a master secret from a previous connection is reused, |derive|
+ * is PR_FALSE. If the secret is a pre-master secret, then |derive| is PR_TRUE
+ * and the master secret is derived from |secret|.
+ */
+SECStatus
+ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret, PRBool derive)
+{
+ PK11SymKey *masterSecret;
+ ssl3CipherSpec *pwSpec;
+ ssl3CipherSpec *prSpec;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(secret);
+
+ ssl_GetSpecWriteLock(ss); /**************************************/
+
+ PORT_Assert(ss->ssl3.pwSpec);
+ PORT_Assert(ss->ssl3.cwSpec->epoch == ss->ssl3.crSpec->epoch);
+ prSpec = ss->ssl3.prSpec;
+ pwSpec = ss->ssl3.pwSpec;
+
+ if (ss->ssl3.cwSpec->epoch == PR_UINT16_MAX) {
+ /* The problem here is that we have rehandshaked too many
+ * times (you are not allowed to wrap the epoch). The
+ * spec says you should be discarding the connection
+ * and start over, so not much we can do here. */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+
+ if (derive) {
+ rv = ssl3_ComputeMasterSecret(ss, secret, &masterSecret);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ masterSecret = secret;
+ }
+
+ PORT_Assert(masterSecret);
+ rv = ssl3_DeriveConnectionKeys(ss, masterSecret);
+ if (rv != SECSuccess) {
+ if (derive) {
+ /* masterSecret was created here. */
+ PK11_FreeSymKey(masterSecret);
+ }
+ goto loser;
+ }
+
+ /* Both cipher specs maintain a reference to the master secret, since each
+ * is managed and freed independently. */
+ prSpec->masterSecret = masterSecret;
+ pwSpec->masterSecret = PK11_ReferenceSymKey(masterSecret);
+ rv = ssl3_InitPendingContexts(ss, ss->ssl3.prSpec);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl3_InitPendingContexts(ss, ss->ssl3.pwSpec);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ ssl_ReleaseSpecWriteLock(ss); /******************************/
+ return SECSuccess;
+
+loser:
+ ssl_ReleaseSpecWriteLock(ss); /******************************/
+ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+ return SECFailure;
+}
+
+/*
+ * 60 bytes is 3 times the maximum length MAC size that is supported.
+ */
+static const unsigned char mac_pad_1[60] = {
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+ 0x36, 0x36, 0x36, 0x36
+};
+static const unsigned char mac_pad_2[60] = {
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
+ 0x5c, 0x5c, 0x5c, 0x5c
+};
+
+/* Called from: ssl3_SendRecord()
+** Caller must already hold the SpecReadLock. (wish we could assert that!)
+*/
+static SECStatus
+ssl3_ComputeRecordMAC(
+ ssl3CipherSpec *spec,
+ const unsigned char *header,
+ unsigned int headerLen,
+ const PRUint8 *input,
+ int inputLen,
+ unsigned char *outbuf,
+ unsigned int *outLen)
+{
+ PK11Context *context;
+ int macSize = spec->macDef->mac_size;
+ SECStatus rv;
+
+ PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
+ PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLen));
+
+ if (spec->macDef->mac == ssl_mac_null) {
+ *outLen = 0;
+ return SECSuccess;
+ }
+
+ context = spec->keyMaterial.macContext;
+ rv = PK11_DigestBegin(context);
+ rv |= PK11_DigestOp(context, header, headerLen);
+ rv |= PK11_DigestOp(context, input, inputLen);
+ rv |= PK11_DigestFinal(context, outbuf, outLen, macSize);
+ PORT_Assert(rv != SECSuccess || *outLen == (unsigned)macSize);
+
+ PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLen));
+
+ if (rv != SECSuccess) {
+ rv = SECFailure;
+ ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
+ }
+ return rv;
+}
+
+/* Called from: ssl3_HandleRecord()
+ * Caller must already hold the SpecReadLock. (wish we could assert that!)
+ *
+ * On entry:
+ * originalLen >= inputLen >= MAC size
+*/
+static SECStatus
+ssl3_ComputeRecordMACConstantTime(
+ ssl3CipherSpec *spec,
+ const unsigned char *header,
+ unsigned int headerLen,
+ const PRUint8 *input,
+ int inputLen,
+ int originalLen,
+ unsigned char *outbuf,
+ unsigned int *outLen)
+{
+ CK_MECHANISM_TYPE macType;
+ CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
+ SECItem param, inputItem, outputItem;
+ int macSize = spec->macDef->mac_size;
+ SECStatus rv;
+
+ PORT_Assert(inputLen >= spec->macDef->mac_size);
+ PORT_Assert(originalLen >= inputLen);
+
+ if (spec->macDef->mac == ssl_mac_null) {
+ *outLen = 0;
+ return SECSuccess;
+ }
+
+ macType = CKM_NSS_HMAC_CONSTANT_TIME;
+ if (spec->version == SSL_LIBRARY_VERSION_3_0) {
+ macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
+ }
+
+ params.macAlg = spec->macDef->mmech;
+ params.ulBodyTotalLen = originalLen;
+ params.pHeader = (unsigned char *)header; /* const cast */
+ params.ulHeaderLen = headerLen;
+
+ param.data = (unsigned char *)&params;
+ param.len = sizeof(params);
+ param.type = 0;
+
+ inputItem.data = (unsigned char *)input;
+ inputItem.len = inputLen;
+ inputItem.type = 0;
+
+ outputItem.data = outbuf;
+ outputItem.len = *outLen;
+ outputItem.type = 0;
+
+ rv = PK11_SignWithSymKey(spec->keyMaterial.macKey, macType, &param,
+ &outputItem, &inputItem);
+ if (rv != SECSuccess) {
+ if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) {
+ /* ssl3_ComputeRecordMAC() expects the MAC to have been removed
+ * from the input length already. */
+ return ssl3_ComputeRecordMAC(spec, header, headerLen,
+ input, inputLen - macSize,
+ outbuf, outLen);
+ }
+
+ *outLen = 0;
+ rv = SECFailure;
+ ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
+ return rv;
+ }
+
+ PORT_Assert(outputItem.len == (unsigned)macSize);
+ *outLen = outputItem.len;
+
+ return rv;
+}
+
+static PRBool
+ssl3_ClientAuthTokenPresent(sslSessionID *sid)
+{
+ PK11SlotInfo *slot = NULL;
+ PRBool isPresent = PR_TRUE;
+
+ /* we only care if we are doing client auth */
+ if (!sid || !sid->u.ssl3.clAuthValid) {
+ return PR_TRUE;
+ }
+
+ /* get the slot */
+ slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
+ sid->u.ssl3.clAuthSlotID);
+ if (slot == NULL ||
+ !PK11_IsPresent(slot) ||
+ sid->u.ssl3.clAuthSeries != PK11_GetSlotSeries(slot) ||
+ sid->u.ssl3.clAuthSlotID != PK11_GetSlotID(slot) ||
+ sid->u.ssl3.clAuthModuleID != PK11_GetModuleID(slot) ||
+ (PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
+ isPresent = PR_FALSE;
+ }
+ if (slot) {
+ PK11_FreeSlot(slot);
+ }
+ return isPresent;
+}
+
+/* Caller must hold the spec read lock. */
+SECStatus
+ssl3_MACEncryptRecord(ssl3CipherSpec *cwSpec,
+ PRBool isServer,
+ PRBool isDTLS,
+ SSLContentType ct,
+ const PRUint8 *pIn,
+ PRUint32 contentLen,
+ sslBuffer *wrBuf)
+{
+ SECStatus rv;
+ PRUint32 macLen = 0;
+ PRUint32 fragLen;
+ PRUint32 p1Len, p2Len, oddLen = 0;
+ unsigned int ivLen = 0;
+ unsigned char pseudoHeaderBuf[13];
+ sslBuffer pseudoHeader = SSL_BUFFER(pseudoHeaderBuf);
+ unsigned int len;
+
+ if (cwSpec->cipherDef->type == type_block &&
+ cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
+ /* Prepend the per-record explicit IV using technique 2b from
+ * RFC 4346 section 6.2.3.2: The IV is a cryptographically
+ * strong random number XORed with the CBC residue from the previous
+ * record.
+ */
+ ivLen = cwSpec->cipherDef->iv_size;
+ if (ivLen > SSL_BUFFER_SPACE(wrBuf)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ rv = PK11_GenerateRandom(SSL_BUFFER_NEXT(wrBuf), ivLen);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
+ return rv;
+ }
+ rv = cwSpec->cipher(cwSpec->cipherContext,
+ SSL_BUFFER_NEXT(wrBuf), /* output */
+ &len, /* outlen */
+ ivLen, /* max outlen */
+ SSL_BUFFER_NEXT(wrBuf), /* input */
+ ivLen); /* input len */
+ if (rv != SECSuccess || len != ivLen) {
+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_Skip(wrBuf, len, NULL);
+ PORT_Assert(rv == SECSuccess); /* Can't fail. */
+ }
+
+ rv = ssl3_BuildRecordPseudoHeader(
+ cwSpec->epoch, cwSpec->nextSeqNum, ct,
+ cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->recordVersion,
+ isDTLS, contentLen, &pseudoHeader);
+ PORT_Assert(rv == SECSuccess);
+ if (cwSpec->cipherDef->type == type_aead) {
+ const unsigned int nonceLen = cwSpec->cipherDef->explicit_nonce_size;
+ const unsigned int tagLen = cwSpec->cipherDef->tag_size;
+ unsigned int ivOffset = 0;
+ CK_GENERATOR_FUNCTION gen;
+ /* ivOut includes the iv and the nonce and is the internal iv/nonce
+ * for the AEAD function. On Encrypt, this is an in/out parameter */
+ unsigned char ivOut[MAX_IV_LENGTH];
+ ivLen = cwSpec->cipherDef->iv_size;
+
+ PORT_Assert((ivLen + nonceLen) <= MAX_IV_LENGTH);
+ PORT_Assert((ivLen + nonceLen) >= sizeof(sslSequenceNumber));
+
+ if (nonceLen + contentLen + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (nonceLen == 0) {
+ ivOffset = ivLen - sizeof(sslSequenceNumber);
+ gen = CKG_GENERATE_COUNTER_XOR;
+ } else {
+ ivOffset = ivLen;
+ gen = CKG_GENERATE_COUNTER;
+ }
+ ivOffset = tls13_SetupAeadIv(isDTLS, ivOut, cwSpec->keyMaterial.iv,
+ ivOffset, ivLen, cwSpec->epoch);
+ rv = tls13_AEAD(cwSpec->cipherContext,
+ PR_FALSE,
+ gen, ivOffset * BPB, /* iv generator params */
+ ivOut, /* iv in */
+ ivOut, /* iv out */
+ ivLen + nonceLen, /* full iv length */
+ NULL, 0, /* nonce is generated*/
+ SSL_BUFFER_BASE(&pseudoHeader), /* aad */
+ SSL_BUFFER_LEN(&pseudoHeader), /* aadlen */
+ SSL_BUFFER_NEXT(wrBuf) + nonceLen, /* output */
+ &len, /* out len */
+ SSL_BUFFER_SPACE(wrBuf) - nonceLen, /* max out */
+ tagLen,
+ pIn, contentLen); /* input */
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+ return SECFailure;
+ }
+ len += nonceLen; /* include the nonce at the beginning */
+ /* copy out the generated iv if we are using explict nonces */
+ if (nonceLen) {
+ PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), ivOut + ivLen, nonceLen);
+ }
+
+ rv = sslBuffer_Skip(wrBuf, len, NULL);
+ PORT_Assert(rv == SECSuccess); /* Can't fail. */
+ } else {
+ int blockSize = cwSpec->cipherDef->block_size;
+
+ /*
+ * Add the MAC
+ */
+ rv = ssl3_ComputeRecordMAC(cwSpec, SSL_BUFFER_BASE(&pseudoHeader),
+ SSL_BUFFER_LEN(&pseudoHeader),
+ pIn, contentLen,
+ SSL_BUFFER_NEXT(wrBuf) + contentLen, &macLen);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
+ return SECFailure;
+ }
+ p1Len = contentLen;
+ p2Len = macLen;
+ fragLen = contentLen + macLen; /* needs to be encrypted */
+ PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
+
+ /*
+ * Pad the text (if we're doing a block cipher)
+ * then Encrypt it
+ */
+ if (cwSpec->cipherDef->type == type_block) {
+ unsigned char *pBuf;
+ int padding_length;
+ int i;
+
+ oddLen = contentLen % blockSize;
+ /* Assume blockSize is a power of two */
+ padding_length = blockSize - 1 - ((fragLen) & (blockSize - 1));
+ fragLen += padding_length + 1;
+ PORT_Assert((fragLen % blockSize) == 0);
+
+ /* Pad according to TLS rules (also acceptable to SSL3). */
+ pBuf = SSL_BUFFER_NEXT(wrBuf) + fragLen - 1;
+ for (i = padding_length + 1; i > 0; --i) {
+ *pBuf-- = padding_length;
+ }
+ /* now, if contentLen is not a multiple of block size, fix it */
+ p2Len = fragLen - p1Len;
+ }
+ if (p1Len < 256) {
+ oddLen = p1Len;
+ p1Len = 0;
+ } else {
+ p1Len -= oddLen;
+ }
+ if (oddLen) {
+ p2Len += oddLen;
+ PORT_Assert((blockSize < 2) ||
+ (p2Len % blockSize) == 0);
+ memmove(SSL_BUFFER_NEXT(wrBuf) + p1Len, pIn + p1Len, oddLen);
+ }
+ if (p1Len > 0) {
+ unsigned int cipherBytesPart1 = 0;
+ rv = cwSpec->cipher(cwSpec->cipherContext,
+ SSL_BUFFER_NEXT(wrBuf), /* output */
+ &cipherBytesPart1, /* actual outlen */
+ p1Len, /* max outlen */
+ pIn,
+ p1Len); /* input, and inputlen */
+ PORT_Assert(rv == SECSuccess && cipherBytesPart1 == p1Len);
+ if (rv != SECSuccess || cipherBytesPart1 != p1Len) {
+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+ return SECFailure;
+ }
+ rv = sslBuffer_Skip(wrBuf, p1Len, NULL);
+ PORT_Assert(rv == SECSuccess);
+ }
+ if (p2Len > 0) {
+ unsigned int cipherBytesPart2 = 0;
+ rv = cwSpec->cipher(cwSpec->cipherContext,
+ SSL_BUFFER_NEXT(wrBuf),
+ &cipherBytesPart2, /* output and actual outLen */
+ p2Len, /* max outlen */
+ SSL_BUFFER_NEXT(wrBuf),
+ p2Len); /* input and inputLen*/
+ PORT_Assert(rv == SECSuccess && cipherBytesPart2 == p2Len);
+ if (rv != SECSuccess || cipherBytesPart2 != p2Len) {
+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+ return SECFailure;
+ }
+ rv = sslBuffer_Skip(wrBuf, p2Len, NULL);
+ PORT_Assert(rv == SECSuccess);
+ }
+ }
+
+ return SECSuccess;
+}
+
+/* Note: though this can report failure, it shouldn't. */
+SECStatus
+ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
+ SSLContentType contentType, sslBuffer *wrBuf,
+ PRBool *needsLength)
+{
+ SECStatus rv;
+
+#ifndef UNSAFE_FUZZER_MODE
+ if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ cwSpec->epoch > TrafficKeyClearText) {
+ if (IS_DTLS(ss)) {
+ return dtls13_InsertCipherTextHeader(ss, cwSpec, wrBuf,
+ needsLength);
+ }
+ contentType = ssl_ct_application_data;
+ }
+#endif
+ rv = sslBuffer_AppendNumber(wrBuf, contentType, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(wrBuf, cwSpec->recordVersion, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (IS_DTLS(ss)) {
+ rv = sslBuffer_AppendNumber(wrBuf, cwSpec->epoch, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(wrBuf, cwSpec->nextSeqNum, 6);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ *needsLength = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, SSLContentType ct,
+ const PRUint8 *pIn, PRUint32 contentLen, sslBuffer *wrBuf)
+{
+ PRBool needsLength;
+ unsigned int lenOffset;
+ SECStatus rv;
+
+ PORT_Assert(cwSpec->direction == ssl_secret_write);
+ PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
+ PORT_Assert(cwSpec->cipherDef->max_records <= RECORD_SEQ_MAX);
+
+ if (cwSpec->nextSeqNum >= cwSpec->cipherDef->max_records) {
+ PORT_Assert(cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_3);
+ SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx",
+ SSL_GETPID(), cwSpec->nextSeqNum));
+ PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
+ return SECFailure;
+ }
+
+ rv = ssl_InsertRecordHeader(ss, cwSpec, ct, wrBuf, &needsLength);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (needsLength) {
+ rv = sslBuffer_Skip(wrBuf, 2, &lenOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+#ifdef UNSAFE_FUZZER_MODE
+ {
+ unsigned int len;
+ rv = Null_Cipher(NULL, SSL_BUFFER_NEXT(wrBuf), &len,
+ SSL_BUFFER_SPACE(wrBuf), pIn, contentLen);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error was set */
+ }
+ rv = sslBuffer_Skip(wrBuf, len, NULL);
+ PORT_Assert(rv == SECSuccess); /* Can't fail. */
+ }
+#else
+ if (cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ PRUint8 *cipherText = SSL_BUFFER_NEXT(wrBuf);
+ unsigned int bufLen = SSL_BUFFER_LEN(wrBuf);
+ rv = tls13_ProtectRecord(ss, cwSpec, ct, pIn, contentLen, wrBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (IS_DTLS(ss)) {
+ bufLen = SSL_BUFFER_LEN(wrBuf) - bufLen;
+ rv = dtls13_MaskSequenceNumber(ss, cwSpec,
+ SSL_BUFFER_BASE(wrBuf),
+ cipherText, bufLen);
+ }
+ } else {
+ rv = ssl3_MACEncryptRecord(cwSpec, ss->sec.isServer, IS_DTLS(ss), ct,
+ pIn, contentLen, wrBuf);
+ }
+#endif
+ if (rv != SECSuccess) {
+ return SECFailure; /* error was set */
+ }
+
+ if (needsLength) {
+ /* Insert the length. */
+ rv = sslBuffer_InsertLength(wrBuf, lenOffset, 2);
+ if (rv != SECSuccess) {
+ PORT_Assert(0); /* Can't fail. */
+ return SECFailure;
+ }
+ }
+
+ ++cwSpec->nextSeqNum;
+ return SECSuccess;
+}
+
+SECStatus
+ssl_ProtectNextRecord(sslSocket *ss, ssl3CipherSpec *spec, SSLContentType ct,
+ const PRUint8 *pIn, unsigned int nIn,
+ unsigned int *written)
+{
+ sslBuffer *wrBuf = &ss->sec.writeBuf;
+ unsigned int contentLen;
+ unsigned int spaceNeeded;
+ SECStatus rv;
+
+ contentLen = PR_MIN(nIn, spec->recordSizeLimit);
+ spaceNeeded = contentLen + SSL3_BUFFER_FUDGE;
+ if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
+ spec->cipherDef->type == type_block) {
+ spaceNeeded += spec->cipherDef->iv_size;
+ }
+ if (spaceNeeded > SSL_BUFFER_SPACE(wrBuf)) {
+ rv = sslBuffer_Grow(wrBuf, spaceNeeded);
+ if (rv != SECSuccess) {
+ SSL_DBG(("%d: SSL3[%d]: failed to expand write buffer to %d",
+ SSL_GETPID(), ss->fd, spaceNeeded));
+ return SECFailure;
+ }
+ }
+
+ rv = ssl_ProtectRecord(ss, spec, ct, pIn, contentLen, wrBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PRINT_BUF(50, (ss, "send (encrypted) record data:",
+ SSL_BUFFER_BASE(wrBuf), SSL_BUFFER_LEN(wrBuf)));
+ *written = contentLen;
+ return SECSuccess;
+}
+
+/* Process the plain text before sending it.
+ * Returns the number of bytes of plaintext that were successfully sent
+ * plus the number of bytes of plaintext that were copied into the
+ * output (write) buffer.
+ * Returns -1 on an error. PR_WOULD_BLOCK_ERROR is set if the error is blocking
+ * and not terminal.
+ *
+ * Notes on the use of the private ssl flags:
+ * (no private SSL flags)
+ * Attempt to make and send SSL records for all plaintext
+ * If non-blocking and a send gets WOULD_BLOCK,
+ * or if the pending (ciphertext) buffer is not empty,
+ * then buffer remaining bytes of ciphertext into pending buf,
+ * and continue to do that for all succssive records until all
+ * bytes are used.
+ * ssl_SEND_FLAG_FORCE_INTO_BUFFER
+ * As above, except this suppresses all write attempts, and forces
+ * all ciphertext into the pending ciphertext buffer.
+ * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
+ * Forces the use of the provided epoch
+ */
+PRInt32
+ssl3_SendRecord(sslSocket *ss,
+ ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */
+ SSLContentType ct,
+ const PRUint8 *pIn, /* input buffer */
+ PRInt32 nIn, /* bytes of input */
+ PRInt32 flags)
+{
+ sslBuffer *wrBuf = &ss->sec.writeBuf;
+ ssl3CipherSpec *spec;
+ SECStatus rv;
+ PRInt32 totalSent = 0;
+
+ SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
+ SSL_GETPID(), ss->fd, ssl3_DecodeContentType(ct),
+ nIn));
+ PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(SSL_BUFFER_LEN(wrBuf) == 0);
+
+ if (ss->ssl3.fatalAlertSent) {
+ SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent",
+ SSL_GETPID(), ss->fd));
+ if (ct != ssl_ct_alert) {
+ /* If we are sending an alert, then we already have an
+ * error, so don't overwrite. */
+ PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
+ }
+ return -1;
+ }
+
+ /* check for Token Presence */
+ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
+ PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
+ return -1;
+ }
+
+ if (ss->recordWriteCallback) {
+ PRUint16 epoch;
+ ssl_GetSpecReadLock(ss);
+ epoch = ss->ssl3.cwSpec->epoch;
+ ssl_ReleaseSpecReadLock(ss);
+ rv = ss->recordWriteCallback(ss->fd, epoch, ct, pIn, nIn,
+ ss->recordWriteCallbackArg);
+ if (rv != SECSuccess) {
+ return -1;
+ }
+ return nIn;
+ }
+
+ if (cwSpec) {
+ /* cwSpec can only be set for retransmissions of the DTLS handshake. */
+ PORT_Assert(IS_DTLS(ss) &&
+ (ct == ssl_ct_handshake ||
+ ct == ssl_ct_change_cipher_spec));
+ spec = cwSpec;
+ } else {
+ spec = ss->ssl3.cwSpec;
+ }
+
+ while (nIn > 0) {
+ unsigned int written = 0;
+ PRInt32 sent;
+
+ ssl_GetSpecReadLock(ss);
+ rv = ssl_ProtectNextRecord(ss, spec, ct, pIn, nIn, &written);
+ ssl_ReleaseSpecReadLock(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ PORT_Assert(written > 0);
+ /* DTLS should not fragment non-application data here. */
+ if (IS_DTLS(ss) && ct != ssl_ct_application_data) {
+ PORT_Assert(written == nIn);
+ }
+
+ pIn += written;
+ nIn -= written;
+ PORT_Assert(nIn >= 0);
+
+ /* If there's still some previously saved ciphertext,
+ * or the caller doesn't want us to send the data yet,
+ * then add all our new ciphertext to the amount previously saved.
+ */
+ if ((ss->pendingBuf.len > 0) ||
+ (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
+
+ rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf),
+ SSL_BUFFER_LEN(wrBuf));
+ if (rv != SECSuccess) {
+ /* presumably a memory error, SEC_ERROR_NO_MEMORY */
+ goto loser;
+ }
+
+ if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
+ ss->handshakeBegun = 1;
+ sent = ssl_SendSavedWriteData(ss);
+ if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
+ ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
+ goto loser;
+ }
+ if (ss->pendingBuf.len) {
+ flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
+ }
+ }
+ } else {
+ PORT_Assert(SSL_BUFFER_LEN(wrBuf) > 0);
+ ss->handshakeBegun = 1;
+ sent = ssl_DefSend(ss, SSL_BUFFER_BASE(wrBuf),
+ SSL_BUFFER_LEN(wrBuf),
+ flags & ~ssl_SEND_FLAG_MASK);
+ if (sent < 0) {
+ if (PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
+ ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
+ goto loser;
+ }
+ /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
+ sent = 0;
+ }
+ if (SSL_BUFFER_LEN(wrBuf) > (unsigned int)sent) {
+ if (IS_DTLS(ss)) {
+ /* DTLS just says no in this case. No buffering */
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ goto loser;
+ }
+ /* now take all the remaining unsent new ciphertext and
+ * append it to the buffer of previously unsent ciphertext.
+ */
+ rv = ssl_SaveWriteData(ss, SSL_BUFFER_BASE(wrBuf) + sent,
+ SSL_BUFFER_LEN(wrBuf) - sent);
+ if (rv != SECSuccess) {
+ /* presumably a memory error, SEC_ERROR_NO_MEMORY */
+ goto loser;
+ }
+ }
+ }
+ wrBuf->len = 0;
+ totalSent += written;
+ }
+ return totalSent;
+
+loser:
+ /* Don't leave bits of buffer lying around. */
+ wrBuf->len = 0;
+ return -1;
+}
+
+#define SSL3_PENDING_HIGH_WATER 1024
+
+/* Attempt to send the content of "in" in an SSL application_data record.
+ * Returns "len" or -1 on failure.
+ */
+int
+ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
+ PRInt32 len, PRInt32 flags)
+{
+ PRInt32 totalSent = 0;
+ PRInt32 discarded = 0;
+ PRBool splitNeeded = PR_FALSE;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ /* These flags for internal use only */
+ PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT));
+ if (len < 0 || !in) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return -1;
+ }
+
+ if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
+ !ssl_SocketIsBlocking(ss)) {
+ PORT_Assert(!ssl_SocketIsBlocking(ss));
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return -1;
+ }
+
+ if (ss->appDataBuffered && len) {
+ PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered));
+ if (in[0] != (unsigned char)(ss->appDataBuffered)) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return -1;
+ }
+ in++;
+ len--;
+ discarded = 1;
+ }
+
+ /* We will split the first byte of the record into its own record, as
+ * explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h.
+ */
+ if (len > 1 && ss->opt.cbcRandomIV &&
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
+ ss->ssl3.cwSpec->cipherDef->type == type_block /* CBC */) {
+ splitNeeded = PR_TRUE;
+ }
+
+ while (len > totalSent) {
+ PRInt32 sent, toSend;
+
+ if (totalSent > 0) {
+ /*
+ * The thread yield is intended to give the reader thread a
+ * chance to get some cycles while the writer thread is in
+ * the middle of a large application data write. (See
+ * Bugzilla bug 127740, comment #1.)
+ */
+ ssl_ReleaseXmitBufLock(ss);
+ PR_Sleep(PR_INTERVAL_NO_WAIT); /* PR_Yield(); */
+ ssl_GetXmitBufLock(ss);
+ }
+
+ if (splitNeeded) {
+ toSend = 1;
+ splitNeeded = PR_FALSE;
+ } else {
+ toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
+ }
+
+ /*
+ * Note that the 0 epoch is OK because flags will never require
+ * its use, as guaranteed by the PORT_Assert above.
+ */
+ sent = ssl3_SendRecord(ss, NULL, ssl_ct_application_data,
+ in + totalSent, toSend, flags);
+ if (sent < 0) {
+ if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
+ PORT_Assert(ss->lastWriteBlocked);
+ break;
+ }
+ return -1; /* error code set by ssl3_SendRecord */
+ }
+ totalSent += sent;
+ if (ss->pendingBuf.len) {
+ /* must be a non-blocking socket */
+ PORT_Assert(!ssl_SocketIsBlocking(ss));
+ PORT_Assert(ss->lastWriteBlocked);
+ break;
+ }
+ }
+ if (ss->pendingBuf.len) {
+ /* Must be non-blocking. */
+ PORT_Assert(!ssl_SocketIsBlocking(ss));
+ if (totalSent > 0) {
+ ss->appDataBuffered = 0x100 | in[totalSent - 1];
+ }
+
+ totalSent = totalSent + discarded - 1;
+ if (totalSent <= 0) {
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ totalSent = SECFailure;
+ }
+ return totalSent;
+ }
+ ss->appDataBuffered = 0;
+ return totalSent + discarded;
+}
+
+/* Attempt to send buffered handshake messages.
+ * Always set sendBuf.len to 0, even when returning SECFailure.
+ *
+ * Depending on whether we are doing DTLS or not, this either calls
+ *
+ * - ssl3_FlushHandshakeMessages if non-DTLS
+ * - dtls_FlushHandshakeMessages if DTLS
+ *
+ * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
+ * ssl3_AppendHandshake(), ssl3_SendClientHello(),
+ * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
+ * ssl3_SendFinished(),
+ */
+SECStatus
+ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
+{
+ if (IS_DTLS(ss)) {
+ return dtls_FlushHandshakeMessages(ss, flags);
+ }
+ return ssl3_FlushHandshakeMessages(ss, flags);
+}
+
+/* Attempt to send the content of sendBuf buffer in an SSL handshake record.
+ * Always set sendBuf.len to 0, even when returning SECFailure.
+ *
+ * Called from ssl3_FlushHandshake
+ */
+static SECStatus
+ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
+{
+ static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
+ PRInt32 count = -1;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
+ return SECSuccess;
+
+ /* only these flags are allowed */
+ PORT_Assert(!(flags & ~allowedFlags));
+ if ((flags & ~allowedFlags) != 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ count = ssl3_SendRecord(ss, NULL, ssl_ct_handshake,
+ ss->sec.ci.sendBuf.buf,
+ ss->sec.ci.sendBuf.len, flags);
+ if (count < 0) {
+ int err = PORT_GetError();
+ PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
+ if (err == PR_WOULD_BLOCK_ERROR) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ }
+ rv = SECFailure;
+ } else if ((unsigned int)count < ss->sec.ci.sendBuf.len) {
+ /* short write should never happen */
+ PORT_Assert((unsigned int)count >= ss->sec.ci.sendBuf.len);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ rv = SECFailure;
+ } else {
+ rv = SECSuccess;
+ }
+
+ /* Whether we succeeded or failed, toss the old handshake data. */
+ ss->sec.ci.sendBuf.len = 0;
+ return rv;
+}
+
+/*
+ * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
+ * the remote client sends a negative response to our certificate request.
+ * Returns SECFailure if the application has required client auth.
+ * SECSuccess otherwise.
+ */
+SECStatus
+ssl3_HandleNoCertificate(sslSocket *ss)
+{
+ ssl3_CleanupPeerCerts(ss);
+
+ /* If the server has required client-auth blindly but doesn't
+ * actually look at the certificate it won't know that no
+ * certificate was presented so we shutdown the socket to ensure
+ * an error. We only do this if we haven't already completed the
+ * first handshake because if we're redoing the handshake we
+ * know the server is paying attention to the certificate.
+ */
+ if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
+ (!ss->firstHsDone &&
+ (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
+ PRFileDesc *lower;
+
+ ssl_UncacheSessionID(ss);
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ SSL3_SendAlert(ss, alert_fatal, certificate_required);
+ } else {
+ SSL3_SendAlert(ss, alert_fatal, bad_certificate);
+ }
+
+ lower = ss->fd->lower;
+#ifdef _WIN32
+ lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
+#else
+ lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
+#endif
+ PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/************************************************************************
+ * Alerts
+ */
+
+/*
+** Acquires both handshake and XmitBuf locks.
+** Called from: ssl3_IllegalParameter <-
+** ssl3_HandshakeFailure <-
+** ssl3_HandleAlert <- ssl3_HandleRecord.
+** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
+** ssl3_ConsumeHandshakeVariable <-
+** ssl3_HandleHelloRequest <-
+** ssl3_HandleServerHello <-
+** ssl3_HandleServerKeyExchange <-
+** ssl3_HandleCertificateRequest <-
+** ssl3_HandleServerHelloDone <-
+** ssl3_HandleClientHello <-
+** ssl3_HandleV2ClientHello <-
+** ssl3_HandleCertificateVerify <-
+** ssl3_HandleClientKeyExchange <-
+** ssl3_HandleCertificate <-
+** ssl3_HandleFinished <-
+** ssl3_HandleHandshakeMessage <-
+** ssl3_HandlePostHelloHandshakeMessage <-
+** ssl3_HandleRecord <-
+**
+*/
+SECStatus
+SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
+{
+ PRUint8 bytes[2];
+ SECStatus rv;
+ PRBool needHsLock = !ssl_HaveSSL3HandshakeLock(ss);
+
+ /* Check that if I need the HS lock I also need the Xmit lock */
+ PORT_Assert(!needHsLock || !ssl_HaveXmitBufLock(ss));
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
+ SSL_GETPID(), ss->fd, level, desc));
+
+ bytes[0] = level;
+ bytes[1] = desc;
+
+ if (needHsLock) {
+ ssl_GetSSL3HandshakeLock(ss);
+ }
+ if (level == alert_fatal) {
+ if (ss->sec.ci.sid) {
+ ssl_UncacheSessionID(ss);
+ }
+ }
+
+ rv = tls13_SetAlertCipherSpec(ss);
+ if (rv != SECSuccess) {
+ if (needHsLock) {
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ }
+ return rv;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+ if (rv == SECSuccess) {
+ PRInt32 sent;
+ sent = ssl3_SendRecord(ss, NULL, ssl_ct_alert, bytes, 2,
+ (desc == no_certificate) ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
+ rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
+ }
+ if (level == alert_fatal) {
+ ss->ssl3.fatalAlertSent = PR_TRUE;
+ }
+ ssl_ReleaseXmitBufLock(ss);
+ if (needHsLock) {
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ }
+ if (rv == SECSuccess && ss->alertSentCallback) {
+ SSLAlert alert = { level, desc };
+ ss->alertSentCallback(ss->fd, ss->alertSentCallbackArg, &alert);
+ }
+ return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */
+}
+
+/*
+ * Send illegal_parameter alert. Set generic error number.
+ */
+static SECStatus
+ssl3_IllegalParameter(sslSocket *ss)
+{
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
+ : SSL_ERROR_BAD_SERVER);
+ return SECFailure;
+}
+
+/*
+ * Send handshake_Failure alert. Set generic error number.
+ */
+static SECStatus
+ssl3_HandshakeFailure(sslSocket *ss)
+{
+ (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
+ : SSL_ERROR_BAD_SERVER);
+ return SECFailure;
+}
+
+void
+ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode)
+{
+ SSL3AlertDescription desc = bad_certificate;
+ PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
+
+ switch (errCode) {
+ case SEC_ERROR_LIBRARY_FAILURE:
+ desc = unsupported_certificate;
+ break;
+ case SEC_ERROR_EXPIRED_CERTIFICATE:
+ desc = certificate_expired;
+ break;
+ case SEC_ERROR_REVOKED_CERTIFICATE:
+ desc = certificate_revoked;
+ break;
+ case SEC_ERROR_INADEQUATE_KEY_USAGE:
+ case SEC_ERROR_INADEQUATE_CERT_TYPE:
+ desc = certificate_unknown;
+ break;
+ case SEC_ERROR_UNTRUSTED_CERT:
+ desc = isTLS ? access_denied : certificate_unknown;
+ break;
+ case SEC_ERROR_UNKNOWN_ISSUER:
+ case SEC_ERROR_UNTRUSTED_ISSUER:
+ desc = isTLS ? unknown_ca : certificate_unknown;
+ break;
+ case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
+ desc = isTLS ? unknown_ca : certificate_expired;
+ break;
+
+ case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
+ case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
+ case SEC_ERROR_CA_CERT_INVALID:
+ case SEC_ERROR_BAD_SIGNATURE:
+ default:
+ desc = bad_certificate;
+ break;
+ }
+ SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
+ SSL_GETPID(), ss->fd, errCode));
+
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+}
+
+/*
+ * Send decode_error alert. Set generic error number.
+ */
+SECStatus
+ssl3_DecodeError(sslSocket *ss)
+{
+ (void)SSL3_SendAlert(ss, alert_fatal,
+ ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
+ : illegal_parameter);
+ PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
+ : SSL_ERROR_BAD_SERVER);
+ return SECFailure;
+}
+
+/* Called from ssl3_HandleRecord.
+** Caller must hold both RecvBuf and Handshake locks.
+*/
+static SECStatus
+ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
+{
+ SSL3AlertLevel level;
+ SSL3AlertDescription desc;
+ int error;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
+
+ if (buf->len != 2) {
+ (void)ssl3_DecodeError(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
+ return SECFailure;
+ }
+ level = (SSL3AlertLevel)buf->buf[0];
+ desc = (SSL3AlertDescription)buf->buf[1];
+ buf->len = 0;
+ SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
+ SSL_GETPID(), ss->fd, level, desc));
+
+ if (ss->alertReceivedCallback) {
+ SSLAlert alert = { level, desc };
+ ss->alertReceivedCallback(ss->fd, ss->alertReceivedCallbackArg, &alert);
+ }
+
+ switch (desc) {
+ case close_notify:
+ ss->recvdCloseNotify = 1;
+ error = SSL_ERROR_CLOSE_NOTIFY_ALERT;
+ break;
+ case unexpected_message:
+ error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
+ break;
+ case bad_record_mac:
+ error = SSL_ERROR_BAD_MAC_ALERT;
+ break;
+ case decryption_failed_RESERVED:
+ error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
+ break;
+ case record_overflow:
+ error = SSL_ERROR_RECORD_OVERFLOW_ALERT;
+ break;
+ case decompression_failure:
+ error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
+ break;
+ case handshake_failure:
+ error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
+ break;
+ case no_certificate:
+ error = SSL_ERROR_NO_CERTIFICATE;
+ break;
+ case certificate_required:
+ error = SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT;
+ break;
+ case bad_certificate:
+ error = SSL_ERROR_BAD_CERT_ALERT;
+ break;
+ case unsupported_certificate:
+ error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;
+ break;
+ case certificate_revoked:
+ error = SSL_ERROR_REVOKED_CERT_ALERT;
+ break;
+ case certificate_expired:
+ error = SSL_ERROR_EXPIRED_CERT_ALERT;
+ break;
+ case certificate_unknown:
+ error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
+ break;
+ case illegal_parameter:
+ error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;
+ break;
+ case inappropriate_fallback:
+ error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
+ break;
+
+ /* All alerts below are TLS only. */
+ case unknown_ca:
+ error = SSL_ERROR_UNKNOWN_CA_ALERT;
+ break;
+ case access_denied:
+ error = SSL_ERROR_ACCESS_DENIED_ALERT;
+ break;
+ case decode_error:
+ error = SSL_ERROR_DECODE_ERROR_ALERT;
+ break;
+ case decrypt_error:
+ error = SSL_ERROR_DECRYPT_ERROR_ALERT;
+ break;
+ case export_restriction:
+ error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
+ break;
+ case protocol_version:
+ error = SSL_ERROR_PROTOCOL_VERSION_ALERT;
+ break;
+ case insufficient_security:
+ error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
+ break;
+ case internal_error:
+ error = SSL_ERROR_INTERNAL_ERROR_ALERT;
+ break;
+ case user_canceled:
+ error = SSL_ERROR_USER_CANCELED_ALERT;
+ break;
+ case no_renegotiation:
+ error = SSL_ERROR_NO_RENEGOTIATION_ALERT;
+ break;
+
+ /* Alerts for TLS client hello extensions */
+ case missing_extension:
+ error = SSL_ERROR_MISSING_EXTENSION_ALERT;
+ break;
+ case unsupported_extension:
+ error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;
+ break;
+ case certificate_unobtainable:
+ error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT;
+ break;
+ case unrecognized_name:
+ error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
+ break;
+ case bad_certificate_status_response:
+ error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT;
+ break;
+ case bad_certificate_hash_value:
+ error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;
+ break;
+ case no_application_protocol:
+ error = SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL;
+ break;
+ case ech_required:
+ error = SSL_ERROR_ECH_REQUIRED_ALERT;
+ break;
+ default:
+ error = SSL_ERROR_RX_UNKNOWN_ALERT;
+ break;
+ }
+ if ((ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) &&
+ (ss->ssl3.hs.ws != wait_server_hello)) {
+ /* TLS 1.3 requires all but "end of data" alerts to be
+ * treated as fatal. */
+ switch (desc) {
+ case close_notify:
+ case user_canceled:
+ break;
+ default:
+ level = alert_fatal;
+ }
+ }
+ if (level == alert_fatal) {
+ ssl_UncacheSessionID(ss);
+ if ((ss->ssl3.hs.ws == wait_server_hello) &&
+ (desc == handshake_failure)) {
+ /* XXX This is a hack. We're assuming that any handshake failure
+ * XXX on the client hello is a failure to match ciphers.
+ */
+ error = SSL_ERROR_NO_CYPHER_OVERLAP;
+ }
+ PORT_SetError(error);
+ return SECFailure;
+ }
+ if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
+ /* I'm a server. I've requested a client cert. He hasn't got one. */
+ SECStatus rv;
+
+ PORT_Assert(ss->sec.isServer);
+ ss->ssl3.hs.ws = wait_client_key;
+ rv = ssl3_HandleNoCertificate(ss);
+ return rv;
+ }
+ return SECSuccess;
+}
+
+/*
+ * Change Cipher Specs
+ * Called from ssl3_HandleServerHelloDone,
+ * ssl3_HandleClientHello,
+ * and ssl3_HandleFinished
+ *
+ * Acquires and releases spec write lock, to protect switching the current
+ * and pending write spec pointers.
+ */
+
+SECStatus
+ssl3_SendChangeCipherSpecsInt(sslSocket *ss)
+{
+ PRUint8 change = change_cipher_spec_choice;
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
+ SSL_GETPID(), ss->fd));
+
+ rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code set by ssl3_FlushHandshake */
+ }
+
+ if (!IS_DTLS(ss)) {
+ PRInt32 sent;
+ sent = ssl3_SendRecord(ss, NULL, ssl_ct_change_cipher_spec,
+ &change, 1, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+ if (sent < 0) {
+ return SECFailure; /* error code set by ssl3_SendRecord */
+ }
+ } else {
+ rv = dtls_QueueMessage(ss, ssl_ct_change_cipher_spec, &change, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_SendChangeCipherSpecs(sslSocket *ss)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ rv = ssl3_SendChangeCipherSpecsInt(ss);
+ if (rv != SECSuccess) {
+ return rv; /* Error code set. */
+ }
+
+ /* swap the pending and current write specs. */
+ ssl_GetSpecWriteLock(ss); /**************************************/
+
+ ssl_CipherSpecRelease(ss->ssl3.cwSpec);
+ ss->ssl3.cwSpec = ss->ssl3.pwSpec;
+ ss->ssl3.pwSpec = NULL;
+
+ SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
+ SSL_GETPID(), ss->fd));
+
+ /* With DTLS, we need to set a holddown timer in case the final
+ * message got lost */
+ if (IS_DTLS(ss) && ss->ssl3.crSpec->epoch == ss->ssl3.cwSpec->epoch) {
+ rv = dtls_StartHolddownTimer(ss);
+ }
+ ssl_ReleaseSpecWriteLock(ss); /**************************************/
+
+ return rv;
+}
+
+/* Called from ssl3_HandleRecord.
+** Caller must hold both RecvBuf and Handshake locks.
+ *
+ * Acquires and releases spec write lock, to protect switching the current
+ * and pending write spec pointers.
+*/
+static SECStatus
+ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
+{
+ SSL3WaitState ws = ss->ssl3.hs.ws;
+ SSL3ChangeCipherSpecChoice change;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
+ SSL_GETPID(), ss->fd));
+
+ /* For DTLS: Ignore this if we aren't expecting it. Don't kill a connection
+ * as a result of receiving trash.
+ * For TLS: Maybe ignore, but only after checking format. */
+ if (ws != wait_change_cipher && IS_DTLS(ss)) {
+ /* Ignore this because it's out of order. */
+ SSL_TRC(3, ("%d: SSL3[%d]: discard out of order "
+ "DTLS change_cipher_spec",
+ SSL_GETPID(), ss->fd));
+ buf->len = 0;
+ return SECSuccess;
+ }
+
+ /* Handshake messages should not span ChangeCipherSpec. */
+ if (ss->ssl3.hs.header_bytes) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
+ return SECFailure;
+ }
+ if (buf->len != 1) {
+ (void)ssl3_DecodeError(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
+ return SECFailure;
+ }
+ change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
+ if (change != change_cipher_spec_choice) {
+ /* illegal_parameter is correct here for both SSL3 and TLS. */
+ (void)ssl3_IllegalParameter(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
+ return SECFailure;
+ }
+
+ buf->len = 0;
+ if (ws != wait_change_cipher) {
+ /* Ignore a CCS for TLS 1.3. This only happens if the server sends a
+ * HelloRetryRequest. In other cases, the CCS will fail decryption and
+ * will be discarded by ssl3_HandleRecord(). */
+ if (ws == wait_server_hello &&
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ ss->ssl3.hs.helloRetry) {
+ PORT_Assert(!ss->sec.isServer);
+ return SECSuccess;
+ }
+ /* Note: For a server, we can't test ss->ssl3.hs.helloRetry or
+ * ss->version because the server might be stateless (and so it won't
+ * have set either value yet). Set a flag so that at least we will
+ * guarantee that the server will treat any ClientHello properly. */
+ if (ws == wait_client_hello &&
+ ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ !ss->ssl3.hs.receivedCcs) {
+ PORT_Assert(ss->sec.isServer);
+ ss->ssl3.hs.receivedCcs = PR_TRUE;
+ return SECSuccess;
+ }
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
+ return SECFailure;
+ }
+
+ SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
+ SSL_GETPID(), ss->fd));
+ ssl_GetSpecWriteLock(ss); /*************************************/
+ PORT_Assert(ss->ssl3.prSpec);
+ ssl_CipherSpecRelease(ss->ssl3.crSpec);
+ ss->ssl3.crSpec = ss->ssl3.prSpec;
+ ss->ssl3.prSpec = NULL;
+ ssl_ReleaseSpecWriteLock(ss); /*************************************/
+
+ ss->ssl3.hs.ws = wait_finished;
+ return SECSuccess;
+}
+
+static CK_MECHANISM_TYPE
+ssl3_GetMgfMechanismByHashType(SSLHashType hash)
+{
+ switch (hash) {
+ case ssl_hash_sha256:
+ return CKG_MGF1_SHA256;
+ case ssl_hash_sha384:
+ return CKG_MGF1_SHA384;
+ case ssl_hash_sha512:
+ return CKG_MGF1_SHA512;
+ default:
+ PORT_Assert(0);
+ }
+ return CKG_MGF1_SHA256;
+}
+
+/* Function valid for >= TLS 1.2, only. */
+static CK_MECHANISM_TYPE
+ssl3_GetHashMechanismByHashType(SSLHashType hashType)
+{
+ switch (hashType) {
+ case ssl_hash_sha512:
+ return CKM_SHA512;
+ case ssl_hash_sha384:
+ return CKM_SHA384;
+ case ssl_hash_sha256:
+ case ssl_hash_none:
+ /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
+ return CKM_SHA256;
+ case ssl_hash_sha1:
+ return CKM_SHA_1;
+ default:
+ PORT_Assert(0);
+ }
+ return CKM_SHA256;
+}
+
+/* Function valid for >= TLS 1.2, only. */
+static CK_MECHANISM_TYPE
+ssl3_GetPrfHashMechanism(sslSocket *ss)
+{
+ return ssl3_GetHashMechanismByHashType(ss->ssl3.hs.suite_def->prf_hash);
+}
+
+static SSLHashType
+ssl3_GetSuitePrfHash(sslSocket *ss)
+{
+ /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */
+ if (ss->ssl3.hs.suite_def->prf_hash == ssl_hash_none) {
+ return ssl_hash_sha256;
+ }
+ return ss->ssl3.hs.suite_def->prf_hash;
+}
+
+/* This method completes the derivation of the MS from the PMS.
+**
+** 1. Derive the MS, if possible, else return an error.
+**
+** 2. Check the version if |pms_version| is non-zero and if wrong,
+** return an error.
+**
+** 3. If |msp| is nonzero, return MS in |*msp|.
+
+** Called from:
+** ssl3_ComputeMasterSecretInt
+** tls_ComputeExtendedMasterSecretInt
+*/
+static SECStatus
+ssl3_ComputeMasterSecretFinish(sslSocket *ss,
+ CK_MECHANISM_TYPE master_derive,
+ CK_MECHANISM_TYPE key_derive,
+ CK_VERSION *pms_version,
+ SECItem *params, CK_FLAGS keyFlags,
+ PK11SymKey *pms, PK11SymKey **msp)
+{
+ PK11SymKey *ms = NULL;
+
+ ms = PK11_DeriveWithFlags(pms, master_derive,
+ params, key_derive,
+ CKA_DERIVE, 0, keyFlags);
+ if (!ms) {
+ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+ return SECFailure;
+ }
+
+ if (pms_version && ss->opt.detectRollBack) {
+ SSL3ProtocolVersion client_version;
+ client_version = pms_version->major << 8 | pms_version->minor;
+
+ if (IS_DTLS(ss)) {
+ client_version = dtls_DTLSVersionToTLSVersion(client_version);
+ }
+
+ if (client_version != ss->clientHelloVersion) {
+ /* Destroy MS. Version roll-back detected. */
+ PK11_FreeSymKey(ms);
+ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ if (msp) {
+ *msp = ms;
+ } else {
+ PK11_FreeSymKey(ms);
+ }
+
+ return SECSuccess;
+}
+
+/* Compute the ordinary (pre draft-ietf-tls-session-hash) master
+ ** secret and return it in |*msp|.
+ **
+ ** Called from: ssl3_ComputeMasterSecret
+ */
+static SECStatus
+ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
+ PK11SymKey **msp)
+{
+ PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
+ PRBool isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+ /*
+ * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
+ * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
+ * data into a 48-byte value, and does not expect to return the version.
+ */
+ PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
+ (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh));
+ CK_MECHANISM_TYPE master_derive;
+ CK_MECHANISM_TYPE key_derive;
+ SECItem params;
+ CK_FLAGS keyFlags;
+ CK_VERSION pms_version;
+ CK_VERSION *pms_version_ptr = NULL;
+ /* master_params may be used as a CK_SSL3_MASTER_KEY_DERIVE_PARAMS */
+ CK_TLS12_MASTER_KEY_DERIVE_PARAMS master_params;
+ unsigned int master_params_len;
+
+ if (isTLS12) {
+ if (isDH)
+ master_derive = CKM_TLS12_MASTER_KEY_DERIVE_DH;
+ else
+ master_derive = CKM_TLS12_MASTER_KEY_DERIVE;
+ key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
+ keyFlags = CKF_SIGN | CKF_VERIFY;
+ } else if (isTLS) {
+ if (isDH)
+ master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
+ else
+ master_derive = CKM_TLS_MASTER_KEY_DERIVE;
+ key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
+ keyFlags = CKF_SIGN | CKF_VERIFY;
+ } else {
+ if (isDH)
+ master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
+ else
+ master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
+ key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
+ keyFlags = 0;
+ }
+
+ if (!isDH) {
+ pms_version_ptr = &pms_version;
+ }
+
+ master_params.pVersion = pms_version_ptr;
+ master_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
+ master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
+ master_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
+ master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
+ if (isTLS12) {
+ master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
+ master_params_len = sizeof(CK_TLS12_MASTER_KEY_DERIVE_PARAMS);
+ } else {
+ /* prfHashMechanism is not relevant with this PRF */
+ master_params_len = sizeof(CK_SSL3_MASTER_KEY_DERIVE_PARAMS);
+ }
+
+ params.data = (unsigned char *)&master_params;
+ params.len = master_params_len;
+
+ return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
+ pms_version_ptr, &params,
+ keyFlags, pms, msp);
+}
+
+/* Compute the draft-ietf-tls-session-hash master
+** secret and return it in |*msp|.
+**
+** Called from: ssl3_ComputeMasterSecret
+*/
+static SECStatus
+tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms,
+ PK11SymKey **msp)
+{
+ ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
+ CK_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_PARAMS extended_master_params;
+ SSL3Hashes hashes;
+ /*
+ * Determine whether to use the DH/ECDH or RSA derivation modes.
+ */
+ /*
+ * TODO(ekr@rtfm.com): Verify that the slot can handle this key expansion
+ * mode. Bug 1198298 */
+ PRBool isDH = (PRBool)((ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_dh) ||
+ (ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_ecdh));
+ CK_MECHANISM_TYPE master_derive;
+ CK_MECHANISM_TYPE key_derive;
+ SECItem params;
+ const CK_FLAGS keyFlags = CKF_SIGN | CKF_VERIFY;
+ CK_VERSION pms_version;
+ CK_VERSION *pms_version_ptr = NULL;
+ SECStatus rv;
+
+ rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0);
+ if (rv != SECSuccess) {
+ PORT_Assert(0); /* Should never fail */
+ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+ return SECFailure;
+ }
+
+ if (isDH) {
+ master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE_DH;
+ } else {
+ master_derive = CKM_NSS_TLS_EXTENDED_MASTER_KEY_DERIVE;
+ pms_version_ptr = &pms_version;
+ }
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ /* TLS 1.2+ */
+ extended_master_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
+ key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
+ } else {
+ /* TLS < 1.2 */
+ extended_master_params.prfHashMechanism = CKM_TLS_PRF;
+ key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
+ }
+
+ extended_master_params.pVersion = pms_version_ptr;
+ extended_master_params.pSessionHash = hashes.u.raw;
+ extended_master_params.ulSessionHashLen = hashes.len;
+
+ params.data = (unsigned char *)&extended_master_params;
+ params.len = sizeof extended_master_params;
+
+ return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive,
+ pms_version_ptr, &params,
+ keyFlags, pms, msp);
+}
+
+/* Wrapper method to compute the master secret and return it in |*msp|.
+**
+** Called from ssl3_ComputeMasterSecret
+*/
+static SECStatus
+ssl3_ComputeMasterSecret(sslSocket *ss, PK11SymKey *pms,
+ PK11SymKey **msp)
+{
+ PORT_Assert(pms != NULL);
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
+ return tls_ComputeExtendedMasterSecretInt(ss, pms, msp);
+ } else {
+ return ssl3_ComputeMasterSecretInt(ss, pms, msp);
+ }
+}
+
+/*
+ * Derive encryption and MAC Keys (and IVs) from master secret
+ * Sets a useful error code when returning SECFailure.
+ *
+ * Called only from ssl3_InitPendingCipherSpec(),
+ * which in turn is called from
+ * ssl3_SendRSAClientKeyExchange (for Full handshake)
+ * ssl3_SendDHClientKeyExchange (for Full handshake)
+ * ssl3_HandleClientKeyExchange (for Full handshake)
+ * ssl3_HandleServerHello (for session restart)
+ * ssl3_HandleClientHello (for session restart)
+ * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
+ * ssl3_InitPendingCipherSpec does that.
+ *
+ */
+static SECStatus
+ssl3_DeriveConnectionKeys(sslSocket *ss, PK11SymKey *masterSecret)
+{
+ ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
+ ssl3CipherSpec *prSpec = ss->ssl3.prSpec;
+ ssl3CipherSpec *clientSpec;
+ ssl3CipherSpec *serverSpec;
+ PRBool isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
+ PRBool isTLS12 =
+ (PRBool)(isTLS && ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+ const ssl3BulkCipherDef *cipher_def = pwSpec->cipherDef;
+ PK11SlotInfo *slot = NULL;
+ PK11SymKey *derivedKeyHandle = NULL;
+ void *pwArg = ss->pkcs11PinArg;
+ int keySize;
+ CK_TLS12_KEY_MAT_PARAMS key_material_params; /* may be used as a
+ * CK_SSL3_KEY_MAT_PARAMS */
+ unsigned int key_material_params_len;
+ CK_SSL3_KEY_MAT_OUT returnedKeys;
+ CK_MECHANISM_TYPE key_derive;
+ CK_MECHANISM_TYPE bulk_mechanism;
+ SSLCipherAlgorithm calg;
+ SECItem params;
+ PRBool skipKeysAndIVs = (PRBool)(cipher_def->calg == ssl_calg_null);
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
+ PORT_Assert(masterSecret);
+
+ /* These functions operate in terms of who is writing specs. */
+ if (ss->sec.isServer) {
+ clientSpec = prSpec;
+ serverSpec = pwSpec;
+ } else {
+ clientSpec = pwSpec;
+ serverSpec = prSpec;
+ }
+
+ /*
+ * generate the key material
+ */
+ if (cipher_def->type == type_block &&
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
+ /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
+ key_material_params.ulIVSizeInBits = 0;
+ PORT_Memset(clientSpec->keyMaterial.iv, 0, cipher_def->iv_size);
+ PORT_Memset(serverSpec->keyMaterial.iv, 0, cipher_def->iv_size);
+ }
+
+ key_material_params.bIsExport = PR_FALSE;
+ key_material_params.RandomInfo.pClientRandom = ss->ssl3.hs.client_random;
+ key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
+ key_material_params.RandomInfo.pServerRandom = ss->ssl3.hs.server_random;
+ key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
+ key_material_params.pReturnedKeyMaterial = &returnedKeys;
+
+ if (skipKeysAndIVs) {
+ keySize = 0;
+ returnedKeys.pIVClient = NULL;
+ returnedKeys.pIVServer = NULL;
+ key_material_params.ulKeySizeInBits = 0;
+ key_material_params.ulIVSizeInBits = 0;
+ } else {
+ keySize = cipher_def->key_size;
+ returnedKeys.pIVClient = clientSpec->keyMaterial.iv;
+ returnedKeys.pIVServer = serverSpec->keyMaterial.iv;
+ key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB;
+ key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB;
+ }
+ key_material_params.ulMacSizeInBits = pwSpec->macDef->mac_size * BPB;
+
+ calg = cipher_def->calg;
+ bulk_mechanism = ssl3_Alg2Mech(calg);
+
+ if (isTLS12) {
+ key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE;
+ key_material_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
+ key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS);
+ } else if (isTLS) {
+ key_derive = CKM_TLS_KEY_AND_MAC_DERIVE;
+ key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
+ } else {
+ key_derive = CKM_SSL3_KEY_AND_MAC_DERIVE;
+ key_material_params_len = sizeof(CK_SSL3_KEY_MAT_PARAMS);
+ }
+
+ params.data = (unsigned char *)&key_material_params;
+ params.len = key_material_params_len;
+
+ /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
+ * DERIVE by DEFAULT */
+ derivedKeyHandle = PK11_Derive(masterSecret, key_derive, &params,
+ bulk_mechanism, CKA_ENCRYPT, keySize);
+ if (!derivedKeyHandle) {
+ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+ return SECFailure;
+ }
+ /* we really should use the actual mac'ing mechanism here, but we
+ * don't because these types are used to map keytype anyway and both
+ * mac's map to the same keytype.
+ */
+ slot = PK11_GetSlotFromKey(derivedKeyHandle);
+
+ PK11_FreeSlot(slot); /* slot is held until the key is freed */
+ clientSpec->keyMaterial.macKey =
+ PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
+ CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret,
+ PR_TRUE, pwArg);
+ if (clientSpec->keyMaterial.macKey == NULL) {
+ goto loser; /* loser sets err */
+ }
+ serverSpec->keyMaterial.macKey =
+ PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
+ CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret,
+ PR_TRUE, pwArg);
+ if (serverSpec->keyMaterial.macKey == NULL) {
+ goto loser; /* loser sets err */
+ }
+ if (!skipKeysAndIVs) {
+ clientSpec->keyMaterial.key =
+ PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
+ bulk_mechanism, returnedKeys.hClientKey,
+ PR_TRUE, pwArg);
+ if (clientSpec->keyMaterial.key == NULL) {
+ goto loser; /* loser sets err */
+ }
+ serverSpec->keyMaterial.key =
+ PK11_SymKeyFromHandle(slot, derivedKeyHandle, PK11_OriginDerive,
+ bulk_mechanism, returnedKeys.hServerKey,
+ PR_TRUE, pwArg);
+ if (serverSpec->keyMaterial.key == NULL) {
+ goto loser; /* loser sets err */
+ }
+ }
+ PK11_FreeSymKey(derivedKeyHandle);
+ return SECSuccess;
+
+loser:
+ PK11_FreeSymKey(derivedKeyHandle);
+ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
+ return SECFailure;
+}
+
+void
+ssl3_CoalesceEchHandshakeHashes(sslSocket *ss)
+{
+ /* |sha| contains the CHOuter transcript, which is the singular
+ * transcript if not doing ECH. If the server responded with 1.2,
+ * contexts are not yet initialized. */
+ if (ss->ssl3.hs.echAccepted) {
+ if (ss->ssl3.hs.sha) {
+ PORT_Assert(ss->ssl3.hs.shaEchInner);
+ PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
+ ss->ssl3.hs.sha = ss->ssl3.hs.shaEchInner;
+ ss->ssl3.hs.shaEchInner = NULL;
+ }
+ } else {
+ if (ss->ssl3.hs.shaEchInner) {
+ PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
+ ss->ssl3.hs.shaEchInner = NULL;
+ }
+ }
+}
+
+/* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
+ * buffered messages in ss->ssl3.hs.messages. Called from
+ * ssl3_NegotiateCipherSuite(), tls13_HandleClientHelloPart2(),
+ * and ssl3_HandleServerHello. */
+SECStatus
+ssl3_InitHandshakeHashes(sslSocket *ss)
+{
+ SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
+ if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+ ss->ssl3.hs.hashType = handshake_hash_record;
+ } else {
+ PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
+ /*
+ * note: We should probably lookup an SSL3 slot for these
+ * handshake hashes in hopes that we wind up with the same slots
+ * that the master secret will wind up in ...
+ */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ /* determine the hash from the prf */
+ const SECOidData *hash_oid =
+ SECOID_FindOIDByMechanism(ssl3_GetPrfHashMechanism(ss));
+
+ /* Get the PKCS #11 mechanism for the Hash from the cipher suite (prf_hash)
+ * Convert that to the OidTag. We can then use that OidTag to create our
+ * PK11Context */
+ PORT_Assert(hash_oid != NULL);
+ if (hash_oid == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.sha = PK11_CreateDigestContext(hash_oid->offset);
+ if (ss->ssl3.hs.sha == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ ss->ssl3.hs.hashType = handshake_hash_single;
+ if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return SECFailure;
+ }
+
+ /* Transcript hash used on ECH client. */
+ if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx) {
+ ss->ssl3.hs.shaEchInner = PK11_CreateDigestContext(hash_oid->offset);
+ if (ss->ssl3.hs.shaEchInner == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ if (PK11_DigestBegin(ss->ssl3.hs.shaEchInner) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ }
+ } else {
+ /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
+ * created successfully. */
+ ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
+ if (ss->ssl3.hs.md5 == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
+ if (ss->ssl3.hs.sha == NULL) {
+ PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
+ ss->ssl3.hs.md5 = NULL;
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ ss->ssl3.hs.hashType = handshake_hash_combo;
+
+ if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ }
+ }
+
+ if (ss->ssl3.hs.hashType != handshake_hash_record &&
+ ss->ssl3.hs.messages.len > 0) {
+ /* When doing ECH, ssl3_UpdateHandshakeHashes will store outer messages
+ * into the both the outer and inner transcripts.
+ * ssl3_UpdateDefaultHandshakeHashes uses the default context which is
+ * the outer when doing client ECH. For ECH shared-mode or backend
+ * servers only the hs.messages buffer is used. */
+ if (ssl3_UpdateDefaultHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
+ ss->ssl3.hs.messages.len) != SECSuccess) {
+ return SECFailure;
+ }
+ /* When doing ECH, deriving the accept_confirmation value requires all
+ * messages up to and including the ServerHello
+ * (see draft-ietf-tls-esni-14, Section 7.2).
+ *
+ * Don't free the transcript buffer until confirmation calculation. */
+ if (!ss->ssl3.hs.echHpkeCtx && !ss->opt.enableTls13BackendEch) {
+ sslBuffer_Clear(&ss->ssl3.hs.messages);
+ }
+ }
+ if (ss->ssl3.hs.shaEchInner &&
+ ss->ssl3.hs.echInnerMessages.len > 0) {
+ if (PK11_DigestOp(ss->ssl3.hs.shaEchInner, ss->ssl3.hs.echInnerMessages.buf,
+ ss->ssl3.hs.echInnerMessages.len) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ if (!ss->ssl3.hs.echHpkeCtx) {
+ sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
+ }
+ }
+
+ return SECSuccess;
+}
+
+void
+ssl3_RestartHandshakeHashes(sslSocket *ss)
+{
+ SSL_TRC(30, ("%d: SSL3[%d]: reset handshake hashes",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.hashType = handshake_hash_unknown;
+ ss->ssl3.hs.messages.len = 0;
+ ss->ssl3.hs.echInnerMessages.len = 0;
+ if (ss->ssl3.hs.md5) {
+ PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
+ ss->ssl3.hs.md5 = NULL;
+ }
+ if (ss->ssl3.hs.sha) {
+ PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
+ ss->ssl3.hs.sha = NULL;
+ }
+ if (ss->ssl3.hs.shaEchInner) {
+ PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
+ ss->ssl3.hs.shaEchInner = NULL;
+ }
+ if (ss->ssl3.hs.shaPostHandshake) {
+ PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
+ ss->ssl3.hs.shaPostHandshake = NULL;
+ }
+}
+
+/* Add the provided bytes to the handshake hash context. When doing
+ * TLS 1.3 ECH, |target| may be provided to specify only the inner/outer
+ * transcript, else the input is added to both contexts. This happens
+ * only on the client. On the server, only the default context is used. */
+SECStatus
+ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
+ unsigned int l, sslBuffer *target)
+{
+
+ SECStatus rv = SECSuccess;
+ PRBool explicit = (target != NULL);
+ PRBool appendToEchInner = !ss->sec.isServer &&
+ ss->ssl3.hs.echHpkeCtx &&
+ !explicit;
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(target != &ss->ssl3.hs.echInnerMessages ||
+ !ss->sec.isServer);
+
+ if (target == NULL) {
+ /* Default context. */
+ target = &ss->ssl3.hs.messages;
+ }
+ /* With TLS 1.3, and versions TLS.1.1 and older, we keep the hash(es)
+ * always up to date. However, we must initially buffer the handshake
+ * messages, until we know what to do.
+ * If ss->ssl3.hs.hashType != handshake_hash_unknown,
+ * it means we know what to do. We calculate (hash our input),
+ * and we stop appending to the buffer.
+ *
+ * With TLS 1.2, we always append all handshake messages,
+ * and never update the hash, because the hash function we must use for
+ * certificate_verify might be different from the hash function we use
+ * when signing other handshake hashes. */
+ if (ss->ssl3.hs.hashType == handshake_hash_unknown ||
+ ss->ssl3.hs.hashType == handshake_hash_record) {
+ rv = sslBuffer_Append(target, b, l);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (appendToEchInner) {
+ return sslBuffer_Append(&ss->ssl3.hs.echInnerMessages, b, l);
+ }
+ return SECSuccess;
+ }
+
+ PRINT_BUF(90, (ss, "handshake hash input:", b, l));
+
+ if (ss->ssl3.hs.hashType == handshake_hash_single) {
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ if (target == &ss->ssl3.hs.messages) {
+ rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return rv;
+ }
+ }
+ if (ss->ssl3.hs.shaEchInner &&
+ (target == &ss->ssl3.hs.echInnerMessages || !explicit)) {
+ rv = PK11_DigestOp(ss->ssl3.hs.shaEchInner, b, l);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ return rv;
+ }
+ }
+ } else if (ss->ssl3.hs.hashType == handshake_hash_combo) {
+ rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ return rv;
+ }
+ rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return rv;
+ }
+ }
+ return rv;
+}
+
+static SECStatus
+ssl3_UpdateDefaultHandshakeHashes(sslSocket *ss, const unsigned char *b,
+ unsigned int l)
+{
+ return ssl3_UpdateHandshakeHashesInt(ss, b, l,
+ &ss->ssl3.hs.messages);
+}
+
+static SECStatus
+ssl3_UpdateInnerHandshakeHashes(sslSocket *ss, const unsigned char *b,
+ unsigned int l)
+{
+ return ssl3_UpdateHandshakeHashesInt(ss, b, l,
+ &ss->ssl3.hs.echInnerMessages);
+}
+
+/*
+ * Handshake messages
+ */
+/* Called from ssl3_InitHandshakeHashes()
+** ssl3_AppendHandshake()
+** ssl3_HandleV2ClientHello()
+** ssl3_HandleHandshakeMessage()
+** Caller must hold the ssl3Handshake lock.
+*/
+SECStatus
+ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
+{
+ return ssl3_UpdateHandshakeHashesInt(ss, b, l, NULL);
+}
+
+SECStatus
+ssl3_UpdatePostHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l)
+{
+ SECStatus rv = SECSuccess;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ PRINT_BUF(90, (ss, "post handshake hash input:", b, l));
+
+ PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ rv = PK11_DigestOp(ss->ssl3.hs.shaPostHandshake, b, l);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_DIGEST_FAILURE);
+ }
+ return rv;
+}
+
+SECStatus
+ssl3_AppendHandshakeHeader(sslSocket *ss, SSLHandshakeType t, PRUint32 length)
+{
+ SECStatus rv;
+
+ /* If we already have a message in place, we need to enqueue it.
+ * This empties the buffer. This is a convenient place to call
+ * dtls_StageHandshakeMessage to mark the message boundary.
+ */
+ if (IS_DTLS(ss)) {
+ rv = dtls_StageHandshakeMessage(ss);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+
+ SSL_TRC(30, ("%d: SSL3[%d]: append handshake header: type %s",
+ SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
+
+ rv = ssl3_AppendHandshakeNumber(ss, t, 1);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake, if applicable. */
+ }
+ rv = ssl3_AppendHandshakeNumber(ss, length, 3);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake, if applicable. */
+ }
+
+ if (IS_DTLS(ss)) {
+ /* Note that we make an unfragmented message here. We fragment in the
+ * transmission code, if necessary */
+ rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake, if applicable. */
+ }
+ ss->ssl3.hs.sendMessageSeq++;
+
+ /* 0 is the fragment offset, because it's not fragmented yet */
+ rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake, if applicable. */
+ }
+
+ /* Fragment length -- set to the packet length because not fragmented */
+ rv = ssl3_AppendHandshakeNumber(ss, length, 3);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake, if applicable. */
+ }
+ }
+
+ return rv; /* error code set by AppendHandshake, if applicable. */
+}
+
+/**************************************************************************
+ * Consume Handshake functions.
+ *
+ * All data used in these functions is protected by two locks,
+ * the RecvBufLock and the SSL3HandshakeLock
+ **************************************************************************/
+
+/* Read up the next "bytes" number of bytes from the (decrypted) input
+ * stream "b" (which is *length bytes long). Copy them into buffer "v".
+ * Reduces *length by bytes. Advances *b by bytes.
+ *
+ * If this function returns SECFailure, it has already sent an alert,
+ * and has set a generic error code. The caller should probably
+ * override the generic error code by setting another.
+ */
+SECStatus
+ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length)
+{
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if ((PRUint32)bytes > *length) {
+ return ssl3_DecodeError(ss);
+ }
+ PORT_Memcpy(v, *b, bytes);
+ PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
+ *b += bytes;
+ *length -= bytes;
+ return SECSuccess;
+}
+
+/* Read up the next "bytes" number of bytes from the (decrypted) input
+ * stream "b" (which is *length bytes long), and interpret them as an
+ * integer in network byte order. Sets *num to the received value.
+ * Reduces *length by bytes. Advances *b by bytes.
+ *
+ * On error, an alert has been sent, and a generic error code has been set.
+ */
+SECStatus
+ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num, PRUint32 bytes,
+ PRUint8 **b, PRUint32 *length)
+{
+ PRUint8 *buf = *b;
+ PRUint32 i;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ *num = 0;
+ if (bytes > sizeof(*num)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (bytes > *length) {
+ return ssl3_DecodeError(ss);
+ }
+ PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
+
+ for (i = 0; i < bytes; i++) {
+ *num = (*num << 8) + buf[i];
+ }
+ *b += bytes;
+ *length -= bytes;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num, PRUint32 bytes,
+ PRUint8 **b, PRUint32 *length)
+{
+ PRUint64 num64;
+ SECStatus rv;
+
+ PORT_Assert(bytes <= sizeof(*num));
+ if (bytes > sizeof(*num)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ rv = ssl3_ConsumeHandshakeNumber64(ss, &num64, bytes, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ *num = num64 & 0xffffffff;
+ return SECSuccess;
+}
+
+/* Read in two values from the incoming decrypted byte stream "b", which is
+ * *length bytes long. The first value is a number whose size is "bytes"
+ * bytes long. The second value is a byte-string whose size is the value
+ * of the first number received. The latter byte-string, and its length,
+ * is returned in the SECItem i.
+ *
+ * Returns SECFailure (-1) on failure.
+ * On error, an alert has been sent, and a generic error code has been set.
+ *
+ * RADICAL CHANGE for NSS 3.11. All callers of this function make copies
+ * of the data returned in the SECItem *i, so making a copy of it here
+ * is simply wasteful. So, This function now just sets SECItem *i to
+ * point to the values in the buffer **b.
+ */
+SECStatus
+ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRUint32 bytes,
+ PRUint8 **b, PRUint32 *length)
+{
+ PRUint32 count;
+ SECStatus rv;
+
+ PORT_Assert(bytes <= 3);
+ i->len = 0;
+ i->data = NULL;
+ i->type = siBuffer;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &count, bytes, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (count > 0) {
+ if (count > *length) {
+ return ssl3_DecodeError(ss);
+ }
+ i->data = *b;
+ i->len = count;
+ *b += count;
+ *length -= count;
+ }
+ return SECSuccess;
+}
+
+/* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
+ * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
+ *
+ * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
+SECOidTag
+ssl3_HashTypeToOID(SSLHashType hashType)
+{
+ switch (hashType) {
+ case ssl_hash_sha1:
+ return SEC_OID_SHA1;
+ case ssl_hash_sha256:
+ return SEC_OID_SHA256;
+ case ssl_hash_sha384:
+ return SEC_OID_SHA384;
+ case ssl_hash_sha512:
+ return SEC_OID_SHA512;
+ default:
+ break;
+ }
+ return SEC_OID_UNKNOWN;
+}
+
+SECOidTag
+ssl3_AuthTypeToOID(SSLAuthType authType)
+{
+ switch (authType) {
+ case ssl_auth_rsa_sign:
+ return SEC_OID_PKCS1_RSA_ENCRYPTION;
+ case ssl_auth_rsa_pss:
+ return SEC_OID_PKCS1_RSA_PSS_SIGNATURE;
+ case ssl_auth_ecdsa:
+ return SEC_OID_ANSIX962_EC_PUBLIC_KEY;
+ case ssl_auth_dsa:
+ return SEC_OID_ANSIX9_DSA_SIGNATURE;
+ default:
+ break;
+ }
+ /* shouldn't ever get there */
+ PORT_Assert(0);
+ return SEC_OID_UNKNOWN;
+}
+
+SSLHashType
+ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_rsa_pkcs1_sha1:
+ case ssl_sig_dsa_sha1:
+ case ssl_sig_ecdsa_sha1:
+ return ssl_hash_sha1;
+ case ssl_sig_rsa_pkcs1_sha256:
+ case ssl_sig_ecdsa_secp256r1_sha256:
+ case ssl_sig_rsa_pss_rsae_sha256:
+ case ssl_sig_rsa_pss_pss_sha256:
+ case ssl_sig_dsa_sha256:
+ return ssl_hash_sha256;
+ case ssl_sig_rsa_pkcs1_sha384:
+ case ssl_sig_ecdsa_secp384r1_sha384:
+ case ssl_sig_rsa_pss_rsae_sha384:
+ case ssl_sig_rsa_pss_pss_sha384:
+ case ssl_sig_dsa_sha384:
+ return ssl_hash_sha384;
+ case ssl_sig_rsa_pkcs1_sha512:
+ case ssl_sig_ecdsa_secp521r1_sha512:
+ case ssl_sig_rsa_pss_rsae_sha512:
+ case ssl_sig_rsa_pss_pss_sha512:
+ case ssl_sig_dsa_sha512:
+ return ssl_hash_sha512;
+ case ssl_sig_rsa_pkcs1_sha1md5:
+ return ssl_hash_none; /* Special for TLS 1.0/1.1. */
+ case ssl_sig_none:
+ case ssl_sig_ed25519:
+ case ssl_sig_ed448:
+ break;
+ }
+ PORT_Assert(0);
+ return ssl_hash_none;
+}
+
+static PRBool
+ssl_SignatureSchemeMatchesSpkiOid(SSLSignatureScheme scheme, SECOidTag spkiOid)
+{
+ SECOidTag authOid = ssl3_AuthTypeToOID(ssl_SignatureSchemeToAuthType(scheme));
+
+ if (spkiOid == authOid) {
+ return PR_TRUE;
+ }
+ if ((authOid == SEC_OID_PKCS1_RSA_ENCRYPTION) &&
+ (spkiOid == SEC_OID_X500_RSA_ENCRYPTION)) {
+ return PR_TRUE;
+ }
+ return PR_FALSE;
+}
+
+/* Validate that the signature scheme works for the given key type. */
+PRBool
+ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
+ PRBool isTls13)
+{
+ if (!ssl_IsSupportedSignatureScheme(scheme)) {
+ return PR_FALSE;
+ }
+ /* if we are purposefully passed SEC_OID_UNKNOWN, it means
+ * we not checking the scheme against a potential key, so skip
+ * the call */
+ if ((spkiOid != SEC_OID_UNKNOWN) &&
+ !ssl_SignatureSchemeMatchesSpkiOid(scheme, spkiOid)) {
+ return PR_FALSE;
+ }
+ if (isTls13) {
+ if (ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) {
+ return PR_FALSE;
+ }
+ if (ssl_IsRsaPkcs1SignatureScheme(scheme)) {
+ return PR_FALSE;
+ }
+ if (ssl_IsDsaSignatureScheme(scheme)) {
+ return PR_FALSE;
+ }
+ /* With TLS 1.3, EC keys should have been selected based on calling
+ * ssl_SignatureSchemeFromSpki(), reject them otherwise. */
+ return spkiOid != SEC_OID_ANSIX962_EC_PUBLIC_KEY;
+ }
+ return PR_TRUE;
+}
+
+static SECStatus
+ssl_SignatureSchemeFromPssSpki(const CERTSubjectPublicKeyInfo *spki,
+ SSLSignatureScheme *scheme)
+{
+ SECKEYRSAPSSParams pssParam = { 0 };
+ PORTCheapArenaPool arena;
+ SECStatus rv;
+
+ /* The key doesn't have parameters, boo. */
+ if (!spki->algorithm.parameters.len) {
+ *scheme = ssl_sig_none;
+ return SECSuccess;
+ }
+
+ PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
+ rv = SEC_QuickDERDecodeItem(&arena.arena, &pssParam,
+ SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate),
+ &spki->algorithm.parameters);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* Not having hashAlg means SHA-1 and we don't accept that. */
+ if (!pssParam.hashAlg) {
+ goto loser;
+ }
+ switch (SECOID_GetAlgorithmTag(pssParam.hashAlg)) {
+ case SEC_OID_SHA256:
+ *scheme = ssl_sig_rsa_pss_pss_sha256;
+ break;
+ case SEC_OID_SHA384:
+ *scheme = ssl_sig_rsa_pss_pss_sha384;
+ break;
+ case SEC_OID_SHA512:
+ *scheme = ssl_sig_rsa_pss_pss_sha512;
+ break;
+ default:
+ goto loser;
+ }
+
+ PORT_DestroyCheapArena(&arena);
+ return SECSuccess;
+
+loser:
+ PORT_DestroyCheapArena(&arena);
+ PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
+ return SECFailure;
+}
+
+static SECStatus
+ssl_SignatureSchemeFromEcSpki(const CERTSubjectPublicKeyInfo *spki,
+ SSLSignatureScheme *scheme)
+{
+ const sslNamedGroupDef *group;
+ SECKEYPublicKey *key;
+
+ key = SECKEY_ExtractPublicKey(spki);
+ if (!key) {
+ PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
+ return SECFailure;
+ }
+ group = ssl_ECPubKey2NamedGroup(key);
+ SECKEY_DestroyPublicKey(key);
+ if (!group) {
+ PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
+ return SECFailure;
+ }
+ switch (group->name) {
+ case ssl_grp_ec_secp256r1:
+ *scheme = ssl_sig_ecdsa_secp256r1_sha256;
+ return SECSuccess;
+ case ssl_grp_ec_secp384r1:
+ *scheme = ssl_sig_ecdsa_secp384r1_sha384;
+ return SECSuccess;
+ case ssl_grp_ec_secp521r1:
+ *scheme = ssl_sig_ecdsa_secp521r1_sha512;
+ return SECSuccess;
+ default:
+ break;
+ }
+ PORT_SetError(SSL_ERROR_BAD_CERTIFICATE);
+ return SECFailure;
+}
+
+/* Newer signature schemes are designed so that a single SPKI can be used with
+ * that scheme. This determines that scheme from the SPKI. If the SPKI doesn't
+ * have a single scheme, |*scheme| is set to ssl_sig_none. */
+SECStatus
+ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
+ PRBool isTls13, SSLSignatureScheme *scheme)
+{
+ SECOidTag spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
+
+ if (spkiOid == SEC_OID_PKCS1_RSA_PSS_SIGNATURE) {
+ return ssl_SignatureSchemeFromPssSpki(spki, scheme);
+ }
+
+ /* Only do this lookup for TLS 1.3, where the scheme can be determined from
+ * the SPKI alone because the ECDSA key size determines the hash. Earlier
+ * TLS versions allow the same EC key to be used with different hashes. */
+ if (isTls13 && spkiOid == SEC_OID_ANSIX962_EC_PUBLIC_KEY) {
+ return ssl_SignatureSchemeFromEcSpki(spki, scheme);
+ }
+
+ *scheme = ssl_sig_none;
+ return SECSuccess;
+}
+
+/* Check that a signature scheme is enabled by configuration. */
+PRBool
+ssl_SignatureSchemeEnabled(const sslSocket *ss, SSLSignatureScheme scheme)
+{
+ unsigned int i;
+ for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ if (scheme == ss->ssl3.signatureSchemes[i]) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+static PRBool
+ssl_SignatureKeyMatchesSpkiOid(const ssl3KEADef *keaDef, SECOidTag spkiOid)
+{
+ switch (spkiOid) {
+ case SEC_OID_X500_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
+ return keaDef->signKeyType == rsaKey;
+ case SEC_OID_ANSIX9_DSA_SIGNATURE:
+ return keaDef->signKeyType == dsaKey;
+ case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
+ return keaDef->signKeyType == ecKey;
+ default:
+ break;
+ }
+ return PR_FALSE;
+}
+
+/* ssl3_CheckSignatureSchemeConsistency checks that the signature algorithm
+ * identifier in |scheme| is consistent with the public key in |spki|. It also
+ * checks the hash algorithm against the configured signature algorithms. If
+ * all the tests pass, SECSuccess is returned. Otherwise, PORT_SetError is
+ * called and SECFailure is returned. */
+SECStatus
+ssl_CheckSignatureSchemeConsistency(sslSocket *ss, SSLSignatureScheme scheme,
+ CERTSubjectPublicKeyInfo *spki)
+{
+ SSLSignatureScheme spkiScheme;
+ PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3;
+ SECOidTag spkiOid;
+ SECStatus rv;
+
+ rv = ssl_SignatureSchemeFromSpki(spki, isTLS13, &spkiScheme);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (spkiScheme != ssl_sig_none) {
+ /* The SPKI in the certificate can only be used for a single scheme. */
+ if (spkiScheme != scheme ||
+ !ssl_SignatureSchemeEnabled(ss, scheme)) {
+ PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ return SECSuccess;
+ }
+
+ spkiOid = SECOID_GetAlgorithmTag(&spki->algorithm);
+
+ /* If we're a client, check that the signature algorithm matches the signing
+ * key type of the cipher suite. */
+ if (!isTLS13 && !ss->sec.isServer) {
+ if (!ssl_SignatureKeyMatchesSpkiOid(ss->ssl3.hs.kea_def, spkiOid)) {
+ PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ }
+
+ /* Verify that the signature scheme matches the signing key. */
+ if ((spkiOid == SEC_OID_UNKNOWN) ||
+ !ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13)) {
+ PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+
+ if (!ssl_SignatureSchemeEnabled(ss, scheme)) {
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+PRBool
+ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_rsa_pkcs1_sha1:
+ case ssl_sig_rsa_pkcs1_sha256:
+ case ssl_sig_rsa_pkcs1_sha384:
+ case ssl_sig_rsa_pkcs1_sha512:
+ case ssl_sig_rsa_pss_rsae_sha256:
+ case ssl_sig_rsa_pss_rsae_sha384:
+ case ssl_sig_rsa_pss_rsae_sha512:
+ case ssl_sig_rsa_pss_pss_sha256:
+ case ssl_sig_rsa_pss_pss_sha384:
+ case ssl_sig_rsa_pss_pss_sha512:
+ case ssl_sig_ecdsa_secp256r1_sha256:
+ case ssl_sig_ecdsa_secp384r1_sha384:
+ case ssl_sig_ecdsa_secp521r1_sha512:
+ case ssl_sig_dsa_sha1:
+ case ssl_sig_dsa_sha256:
+ case ssl_sig_dsa_sha384:
+ case ssl_sig_dsa_sha512:
+ case ssl_sig_ecdsa_sha1:
+ return ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy);
+ break;
+
+ case ssl_sig_rsa_pkcs1_sha1md5:
+ case ssl_sig_none:
+ case ssl_sig_ed25519:
+ case ssl_sig_ed448:
+ return PR_FALSE;
+ }
+ return PR_FALSE;
+}
+
+PRBool
+ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_rsa_pss_rsae_sha256:
+ case ssl_sig_rsa_pss_rsae_sha384:
+ case ssl_sig_rsa_pss_rsae_sha512:
+ case ssl_sig_rsa_pss_pss_sha256:
+ case ssl_sig_rsa_pss_pss_sha384:
+ case ssl_sig_rsa_pss_pss_sha512:
+ return PR_TRUE;
+
+ default:
+ return PR_FALSE;
+ }
+ return PR_FALSE;
+}
+
+PRBool
+ssl_IsRsaeSignatureScheme(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_rsa_pss_rsae_sha256:
+ case ssl_sig_rsa_pss_rsae_sha384:
+ case ssl_sig_rsa_pss_rsae_sha512:
+ return PR_TRUE;
+
+ default:
+ return PR_FALSE;
+ }
+ return PR_FALSE;
+}
+
+PRBool
+ssl_IsRsaPkcs1SignatureScheme(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_rsa_pkcs1_sha256:
+ case ssl_sig_rsa_pkcs1_sha384:
+ case ssl_sig_rsa_pkcs1_sha512:
+ case ssl_sig_rsa_pkcs1_sha1:
+ return PR_TRUE;
+
+ default:
+ return PR_FALSE;
+ }
+ return PR_FALSE;
+}
+
+PRBool
+ssl_IsDsaSignatureScheme(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_dsa_sha256:
+ case ssl_sig_dsa_sha384:
+ case ssl_sig_dsa_sha512:
+ case ssl_sig_dsa_sha1:
+ return PR_TRUE;
+
+ default:
+ return PR_FALSE;
+ }
+ return PR_FALSE;
+}
+
+SSLAuthType
+ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme)
+{
+ switch (scheme) {
+ case ssl_sig_rsa_pkcs1_sha1:
+ case ssl_sig_rsa_pkcs1_sha1md5:
+ case ssl_sig_rsa_pkcs1_sha256:
+ case ssl_sig_rsa_pkcs1_sha384:
+ case ssl_sig_rsa_pkcs1_sha512:
+ /* We report based on the key type for PSS signatures. */
+ case ssl_sig_rsa_pss_rsae_sha256:
+ case ssl_sig_rsa_pss_rsae_sha384:
+ case ssl_sig_rsa_pss_rsae_sha512:
+ return ssl_auth_rsa_sign;
+ case ssl_sig_rsa_pss_pss_sha256:
+ case ssl_sig_rsa_pss_pss_sha384:
+ case ssl_sig_rsa_pss_pss_sha512:
+ return ssl_auth_rsa_pss;
+ case ssl_sig_ecdsa_secp256r1_sha256:
+ case ssl_sig_ecdsa_secp384r1_sha384:
+ case ssl_sig_ecdsa_secp521r1_sha512:
+ case ssl_sig_ecdsa_sha1:
+ return ssl_auth_ecdsa;
+ case ssl_sig_dsa_sha1:
+ case ssl_sig_dsa_sha256:
+ case ssl_sig_dsa_sha384:
+ case ssl_sig_dsa_sha512:
+ return ssl_auth_dsa;
+
+ default:
+ PORT_Assert(0);
+ }
+ return ssl_auth_null;
+}
+
+/* ssl_ConsumeSignatureScheme reads a SSLSignatureScheme (formerly
+ * SignatureAndHashAlgorithm) structure from |b| and puts the resulting value
+ * into |out|. |b| and |length| are updated accordingly.
+ *
+ * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
+SECStatus
+ssl_ConsumeSignatureScheme(sslSocket *ss, PRUint8 **b,
+ PRUint32 *length, SSLSignatureScheme *out)
+{
+ PRUint32 tmp;
+ SECStatus rv;
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Alert sent, Error code set already. */
+ }
+ if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) {
+ SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ *out = (SSLSignatureScheme)tmp;
+ return SECSuccess;
+}
+
+/**************************************************************************
+ * end of Consume Handshake functions.
+ **************************************************************************/
+
+static SECStatus
+ssl3_ComputeHandshakeHash(unsigned char *buf, unsigned int len,
+ SSLHashType hashAlg, SSL3Hashes *hashes)
+{
+ SECStatus rv = SECFailure;
+ PK11Context *hashContext = PK11_CreateDigestContext(
+ ssl3_HashTypeToOID(hashAlg));
+
+ if (!hashContext) {
+ return rv;
+ }
+ rv = PK11_DigestBegin(hashContext);
+ if (rv == SECSuccess) {
+ rv = PK11_DigestOp(hashContext, buf, len);
+ }
+ if (rv == SECSuccess) {
+ rv = PK11_DigestFinal(hashContext, hashes->u.raw, &hashes->len,
+ sizeof(hashes->u.raw));
+ }
+ if (rv == SECSuccess) {
+ hashes->hashAlg = hashAlg;
+ }
+ PK11_DestroyContext(hashContext, PR_TRUE);
+ return rv;
+}
+
+/* Extract the hashes of handshake messages to this point.
+ * Called from ssl3_SendCertificateVerify
+ * ssl3_SendFinished
+ * ssl3_HandleHandshakeMessage
+ *
+ * Caller must hold the SSL3HandshakeLock.
+ * Caller must hold a read or write lock on the Spec R/W lock.
+ * (There is presently no way to assert on a Read lock.)
+ */
+SECStatus
+ssl3_ComputeHandshakeHashes(sslSocket *ss,
+ ssl3CipherSpec *spec, /* uses ->master_secret */
+ SSL3Hashes *hashes, /* output goes here. */
+ PRUint32 sender)
+{
+ SECStatus rv = SECSuccess;
+ PRBool isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
+ unsigned int outLength;
+ PRUint8 md5_inner[MAX_MAC_LENGTH];
+ PRUint8 sha_inner[MAX_MAC_LENGTH];
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ hashes->hashAlg = ssl_hash_none;
+
+ if (ss->ssl3.hs.hashType == handshake_hash_single) {
+ PK11Context *h;
+ unsigned int stateLen;
+ unsigned char stackBuf[1024];
+ unsigned char *stateBuf = NULL;
+
+ h = ss->ssl3.hs.sha;
+ stateBuf = PK11_SaveContextAlloc(h, stackBuf,
+ sizeof(stackBuf), &stateLen);
+ if (stateBuf == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto tls12_loser;
+ }
+ rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
+ sizeof(hashes->u.raw));
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto tls12_loser;
+ }
+
+ hashes->hashAlg = ssl3_GetSuitePrfHash(ss);
+
+ tls12_loser:
+ if (stateBuf) {
+ if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ rv = SECFailure;
+ }
+ if (stateBuf != stackBuf) {
+ PORT_ZFree(stateBuf, stateLen);
+ }
+ }
+ } else if (ss->ssl3.hs.hashType == handshake_hash_record) {
+ rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
+ ss->ssl3.hs.messages.len,
+ ssl3_GetSuitePrfHash(ss),
+ hashes);
+ } else {
+ PK11Context *md5;
+ PK11Context *sha = NULL;
+ unsigned char *md5StateBuf = NULL;
+ unsigned char *shaStateBuf = NULL;
+ unsigned int md5StateLen, shaStateLen;
+ unsigned char md5StackBuf[256];
+ unsigned char shaStackBuf[512];
+ const int md5Pad = ssl_GetMacDefByAlg(ssl_mac_md5)->pad_size;
+ const int shaPad = ssl_GetMacDefByAlg(ssl_mac_sha)->pad_size;
+
+ md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
+ sizeof md5StackBuf, &md5StateLen);
+ if (md5StateBuf == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto loser;
+ }
+ md5 = ss->ssl3.hs.md5;
+
+ shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
+ sizeof shaStackBuf, &shaStateLen);
+ if (shaStateBuf == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto loser;
+ }
+ sha = ss->ssl3.hs.sha;
+
+ if (!isTLS) {
+ /* compute hashes for SSL3. */
+ unsigned char s[4];
+
+ if (!spec->masterSecret) {
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ s[0] = (unsigned char)(sender >> 24);
+ s[1] = (unsigned char)(sender >> 16);
+ s[2] = (unsigned char)(sender >> 8);
+ s[3] = (unsigned char)sender;
+
+ if (sender != 0) {
+ rv |= PK11_DigestOp(md5, s, 4);
+ PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
+ }
+
+ PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, md5Pad));
+
+ rv |= PK11_DigestKey(md5, spec->masterSecret);
+ rv |= PK11_DigestOp(md5, mac_pad_1, md5Pad);
+ rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
+ PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
+
+ if (sender != 0) {
+ rv |= PK11_DigestOp(sha, s, 4);
+ PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
+ }
+
+ PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, shaPad));
+
+ rv |= PK11_DigestKey(sha, spec->masterSecret);
+ rv |= PK11_DigestOp(sha, mac_pad_1, shaPad);
+ rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
+ PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
+
+ PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, md5Pad));
+ PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
+
+ rv |= PK11_DigestBegin(md5);
+ rv |= PK11_DigestKey(md5, spec->masterSecret);
+ rv |= PK11_DigestOp(md5, mac_pad_2, md5Pad);
+ rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
+ }
+ rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
+ PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
+
+ if (!isTLS) {
+ PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, shaPad));
+ PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
+
+ rv |= PK11_DigestBegin(sha);
+ rv |= PK11_DigestKey(sha, spec->masterSecret);
+ rv |= PK11_DigestOp(sha, mac_pad_2, shaPad);
+ rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
+ }
+ rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
+ PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ rv = SECFailure;
+ goto loser;
+ }
+
+ PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
+
+ hashes->len = MD5_LENGTH + SHA1_LENGTH;
+
+ loser:
+ if (md5StateBuf) {
+ if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen) !=
+ SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
+ rv = SECFailure;
+ }
+ if (md5StateBuf != md5StackBuf) {
+ PORT_ZFree(md5StateBuf, md5StateLen);
+ }
+ }
+ if (shaStateBuf) {
+ if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen) !=
+ SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ rv = SECFailure;
+ }
+ if (shaStateBuf != shaStackBuf) {
+ PORT_ZFree(shaStateBuf, shaStateLen);
+ }
+ }
+ }
+ return rv;
+}
+
+/**************************************************************************
+ * end of Handshake Hash functions.
+ * Begin Send and Handle functions for handshakes.
+ **************************************************************************/
+
+#ifdef TRACE
+#define CHTYPE(t) \
+ case client_hello_##t: \
+ return #t;
+
+static const char *
+ssl_ClientHelloTypeName(sslClientHelloType type)
+{
+ switch (type) {
+ CHTYPE(initial);
+ CHTYPE(retry);
+ CHTYPE(retransmit); /* DTLS only */
+ CHTYPE(renegotiation); /* TLS <= 1.2 only */
+ }
+ PORT_Assert(0);
+ return NULL;
+}
+#undef CHTYPE
+#endif
+
+PR_STATIC_ASSERT(SSL3_SESSIONID_BYTES == SSL3_RANDOM_LENGTH);
+static void
+ssl_MakeFakeSid(sslSocket *ss, PRUint8 *buf)
+{
+ PRUint8 x = 0x5a;
+ int i;
+ for (i = 0; i < SSL3_SESSIONID_BYTES; ++i) {
+ x += ss->ssl3.hs.client_random[i];
+ buf[i] = x;
+ }
+}
+
+/* Set the version fields of the cipher spec for a ClientHello. */
+static void
+ssl_SetClientHelloSpecVersion(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ ssl_GetSpecWriteLock(ss);
+ PORT_Assert(spec->cipherDef->cipher == cipher_null);
+ /* This is - a best guess - but it doesn't matter here. */
+ spec->version = ss->vrange.max;
+ if (IS_DTLS(ss)) {
+ spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
+ } else {
+ /* For new connections, cap the record layer version number of TLS
+ * ClientHello to { 3, 1 } (TLS 1.0). Some TLS 1.0 servers (which seem
+ * to use F5 BIG-IP) ignore ClientHello.client_version and use the
+ * record layer version number (TLSPlaintext.version) instead when
+ * negotiating protocol versions. In addition, if the record layer
+ * version number of ClientHello is { 3, 2 } (TLS 1.1) or higher, these
+ * servers reset the TCP connections. Lastly, some F5 BIG-IP servers
+ * hang if a record containing a ClientHello has a version greater than
+ * { 3, 1 } and a length greater than 255. Set this flag to work around
+ * such servers.
+ *
+ * The final version is set when a version is negotiated.
+ */
+ spec->recordVersion = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0,
+ ss->vrange.max);
+ }
+ ssl_ReleaseSpecWriteLock(ss);
+}
+
+SECStatus
+ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions)
+{
+ SECStatus rv;
+ unsigned int msgLen = preamble->len;
+ msgLen += extensions->len ? (2 + extensions->len) : 0;
+ unsigned int headerLen = IS_DTLS(ss) ? 12 : 4;
+
+ /* Record the message length. */
+ rv = sslBuffer_InsertNumber(preamble, 1, msgLen - headerLen, 3);
+ if (rv != SECSuccess) {
+ return SECFailure; /* code set */
+ }
+ if (IS_DTLS(ss)) {
+ /* Record the (unfragmented) fragment length. */
+ unsigned int offset = 1 /* ch */ + 3 /* len */ +
+ 2 /* seq */ + 3 /* fragment offset */;
+ rv = sslBuffer_InsertNumber(preamble, offset, msgLen - headerLen, 3);
+ if (rv != SECSuccess) {
+ return SECFailure; /* code set */
+ }
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_AppendCipherSuites(sslSocket *ss, PRBool fallbackSCSV, sslBuffer *buf)
+{
+ SECStatus rv;
+ unsigned int offset;
+ unsigned int i;
+ unsigned int saveLen;
+
+ rv = sslBuffer_Skip(buf, 2, &offset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->ssl3.hs.sendingSCSV) {
+ /* Add the actual SCSV */
+ rv = sslBuffer_AppendNumber(buf, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
+ sizeof(ssl3CipherSuite));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ if (fallbackSCSV) {
+ rv = sslBuffer_AppendNumber(buf, TLS_FALLBACK_SCSV,
+ sizeof(ssl3CipherSuite));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ saveLen = SSL_BUFFER_LEN(buf);
+ /* CipherSuites are appended to Hello message here */
+ for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
+ if (ssl3_config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) {
+ rv = sslBuffer_AppendNumber(buf, suite->cipher_suite,
+ sizeof(ssl3CipherSuite));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ }
+
+ /* GREASE CipherSuites:
+ * A client MAY select one or more GREASE cipher suite values and advertise
+ * them in the "cipher_suites" field [RFC8701, Section 3.1]. */
+ if (ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_cipher],
+ sizeof(ssl3CipherSuite));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange) ||
+ (SSL_BUFFER_LEN(buf) - saveLen) == 0) {
+ PORT_SetError(SSL_ERROR_SSL_DISABLED);
+ return SECFailure;
+ }
+
+ return sslBuffer_InsertLength(buf, offset, 2);
+}
+
+SECStatus
+ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
+ PRBool realSid, PRUint16 version, PRBool isEchInner,
+ const sslBuffer *extensions, sslBuffer *preamble)
+{
+ SECStatus rv;
+ sslBuffer constructed = SSL_BUFFER_EMPTY;
+ const PRUint8 *client_random = isEchInner ? ss->ssl3.hs.client_inner_random : ss->ssl3.hs.client_random;
+ PORT_Assert(sid);
+ PRBool fallbackSCSV = ss->opt.enableFallbackSCSV && !isEchInner &&
+ (!realSid || version < sid->version);
+
+ rv = sslBuffer_AppendNumber(&constructed, ssl_hs_client_hello, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_Skip(&constructed, 3, NULL);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (IS_DTLS(ss)) {
+ /* Note that we make an unfragmented message here. We fragment in the
+ * transmission code, if necessary */
+ rv = sslBuffer_AppendNumber(&constructed, ss->ssl3.hs.sendMessageSeq, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ ss->ssl3.hs.sendMessageSeq++;
+
+ /* 0 is the fragment offset, because it's not fragmented yet */
+ rv = sslBuffer_AppendNumber(&constructed, 0, 3);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Fragment length -- set to the packet length because not fragmented */
+ rv = sslBuffer_Skip(&constructed, 3, NULL);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ if (ss->firstHsDone) {
+ /* The client hello version must stay unchanged to work around
+ * the Windows SChannel bug described in ssl3_SendClientHello. */
+ PORT_Assert(version == ss->clientHelloVersion);
+ }
+
+ ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2);
+ if (IS_DTLS(ss)) {
+ PRUint16 dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
+ rv = sslBuffer_AppendNumber(&constructed, dtlsVersion, 2);
+ } else {
+ rv = sslBuffer_AppendNumber(&constructed, ss->clientHelloVersion, 2);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_Append(&constructed, client_random, SSL3_RANDOM_LENGTH);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3 && !isEchInner) {
+ rv = sslBuffer_AppendVariable(&constructed, sid->u.ssl3.sessionID,
+ sid->u.ssl3.sessionIDLength, 1);
+ } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
+ /* We're faking session resumption, so rather than create new
+ * randomness, just mix up the client random a little. */
+ PRUint8 buf[SSL3_SESSIONID_BYTES];
+ ssl_MakeFakeSid(ss, buf);
+ rv = sslBuffer_AppendVariable(&constructed, buf, SSL3_SESSIONID_BYTES, 1);
+ } else {
+ rv = sslBuffer_AppendNumber(&constructed, 0, 1);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (IS_DTLS(ss)) {
+ /* This cookieLen applies to the cookie that appears in the DTLS
+ * ClientHello, which isn't used in DTLS 1.3. */
+ rv = sslBuffer_AppendVariable(&constructed, ss->ssl3.hs.cookie.data,
+ ss->ssl3.hs.helloRetry ? 0 : ss->ssl3.hs.cookie.len,
+ 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ rv = ssl3_AppendCipherSuites(ss, fallbackSCSV, &constructed);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Compression methods: count is always 1, null compression. */
+ rv = sslBuffer_AppendNumber(&constructed, 1, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(&constructed, ssl_compression_null, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl3_InsertChHeaderSize(ss, &constructed, extensions);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ *preamble = constructed;
+ return SECSuccess;
+loser:
+ sslBuffer_Clear(&constructed);
+ return SECFailure;
+}
+
+/* Called from ssl3_HandleHelloRequest(),
+ * ssl3_RedoHandshake()
+ * ssl_BeginClientHandshake (when resuming ssl3 session)
+ * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
+ *
+ * The |type| argument indicates what is going on here:
+ * - client_hello_initial is set for the very first ClientHello
+ * - client_hello_retry indicates that this is a second attempt after receiving
+ * a HelloRetryRequest (in TLS 1.3)
+ * - client_hello_retransmit is used in DTLS when resending
+ * - client_hello_renegotiation is used to renegotiate (in TLS <1.3)
+ */
+SECStatus
+ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type)
+{
+ sslSessionID *sid;
+ SECStatus rv;
+ PRBool isTLS = PR_FALSE;
+ PRBool requestingResume = PR_FALSE;
+ PRBool unlockNeeded = PR_FALSE;
+ sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
+ PRUint16 version = ss->vrange.max;
+ PRInt32 flags;
+ sslBuffer chBuf = SSL_BUFFER_EMPTY;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(),
+ ss->fd, ssl_ClientHelloTypeName(type)));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ /* shouldn't get here if SSL3 is disabled, but ... */
+ if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
+ PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
+ PORT_SetError(SSL_ERROR_SSL_DISABLED);
+ return SECFailure;
+ }
+
+ /* If we are responding to a HelloRetryRequest, don't reinitialize. We need
+ * to maintain the handshake hashes. */
+ if (!ss->ssl3.hs.helloRetry) {
+ ssl3_RestartHandshakeHashes(ss);
+ }
+ PORT_Assert(!ss->ssl3.hs.helloRetry || type == client_hello_retry);
+
+ if (type == client_hello_initial) {
+ ssl_SetClientHelloSpecVersion(ss, ss->ssl3.cwSpec);
+ }
+ /* These must be reset every handshake. */
+ ssl3_ResetExtensionData(&ss->xtnData, ss);
+ ss->ssl3.hs.sendingSCSV = PR_FALSE;
+ ss->ssl3.hs.preliminaryInfo = 0;
+ PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit);
+ SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
+ ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
+
+ /* How many suites does our PKCS11 support (regardless of policy)? */
+ if (ssl3_config_match_init(ss) == 0) {
+ return SECFailure; /* ssl3_config_match_init has set error code. */
+ }
+
+ /*
+ * During a renegotiation, ss->clientHelloVersion will be used again to
+ * work around a Windows SChannel bug. Ensure that it is still enabled.
+ */
+ if (ss->firstHsDone) {
+ PORT_Assert(type != client_hello_initial);
+ if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
+ PORT_SetError(SSL_ERROR_SSL_DISABLED);
+ return SECFailure;
+ }
+
+ if (ss->clientHelloVersion < ss->vrange.min ||
+ ss->clientHelloVersion > ss->vrange.max) {
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+ }
+ }
+
+ /* Check if we have a ss->sec.ci.sid.
+ * Check that it's not expired.
+ * If we have an sid and it comes from an external cache, we use it. */
+ if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
+ PORT_Assert(!ss->sec.isServer);
+ sid = ssl_ReferenceSID(ss->sec.ci.sid);
+ SSL_TRC(3, ("%d: SSL3[%d]: using external resumption token in ClientHello",
+ SSL_GETPID(), ss->fd));
+ } else if (ss->sec.ci.sid && ss->statelessResume && type == client_hello_retry) {
+ /* If we are sending a second ClientHello, reuse the same SID
+ * as the original one. */
+ sid = ssl_ReferenceSID(ss->sec.ci.sid);
+ } else if (!ss->opt.noCache) {
+ /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
+ * handles expired entries and other details.
+ * XXX If we've been called from ssl_BeginClientHandshake, then
+ * this lookup is duplicative and wasteful.
+ */
+ sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
+ ss->sec.ci.port, ss->peerID, ss->url);
+ } else {
+ sid = NULL;
+ }
+
+ /* We can't resume based on a different token. If the sid exists,
+ * make sure the token that holds the master secret still exists ...
+ * If we previously did client-auth, make sure that the token that holds
+ * the private key still exists, is logged in, hasn't been removed, etc.
+ */
+ if (sid) {
+ PRBool sidOK = PR_TRUE;
+
+ if (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ if (!tls13_ResumptionCompatible(ss, sid->u.ssl3.cipherSuite)) {
+ sidOK = PR_FALSE;
+ }
+ } else {
+ /* Check that the cipher suite we need is enabled. */
+ const ssl3CipherSuiteCfg *suite =
+ ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite,
+ ss->cipherSuites);
+ SSLVersionRange vrange = { sid->version, sid->version };
+ if (!suite || !ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
+ sidOK = PR_FALSE;
+ }
+
+ /* Check that no (valid) ECHConfigs are setup in combination with a
+ * (resumable) TLS < 1.3 session id. */
+ if (!PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
+ /* If there are ECH configs, the client must not resume but
+ * offer ECH. */
+ sidOK = PR_FALSE;
+ }
+ }
+
+ /* Check that we can recover the master secret. */
+ if (sidOK) {
+ PK11SlotInfo *slot = NULL;
+ if (sid->u.ssl3.masterValid) {
+ slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
+ sid->u.ssl3.masterSlotID);
+ }
+ if (slot == NULL) {
+ sidOK = PR_FALSE;
+ } else {
+ PK11SymKey *wrapKey = NULL;
+ if (!PK11_IsPresent(slot) ||
+ ((wrapKey = PK11_GetWrapKey(slot,
+ sid->u.ssl3.masterWrapIndex,
+ sid->u.ssl3.masterWrapMech,
+ sid->u.ssl3.masterWrapSeries,
+ ss->pkcs11PinArg)) == NULL)) {
+ sidOK = PR_FALSE;
+ }
+ if (wrapKey)
+ PK11_FreeSymKey(wrapKey);
+ PK11_FreeSlot(slot);
+ slot = NULL;
+ }
+ }
+ /* If we previously did client-auth, make sure that the token that
+ ** holds the private key still exists, is logged in, hasn't been
+ ** removed, etc.
+ */
+ if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
+ sidOK = PR_FALSE;
+ }
+
+ if (sidOK) {
+ /* Set version based on the sid. */
+ if (ss->firstHsDone) {
+ /*
+ * Windows SChannel compares the client_version inside the RSA
+ * EncryptedPreMasterSecret of a renegotiation with the
+ * client_version of the initial ClientHello rather than the
+ * ClientHello in the renegotiation. To work around this bug, we
+ * continue to use the client_version used in the initial
+ * ClientHello when renegotiating.
+ *
+ * The client_version of the initial ClientHello is still
+ * available in ss->clientHelloVersion. Ensure that
+ * sid->version is bounded within
+ * [ss->vrange.min, ss->clientHelloVersion], otherwise we
+ * can't use sid.
+ */
+ if (sid->version >= ss->vrange.min &&
+ sid->version <= ss->clientHelloVersion) {
+ version = ss->clientHelloVersion;
+ } else {
+ sidOK = PR_FALSE;
+ }
+ } else {
+ /*
+ * Check sid->version is OK first.
+ * Previously, we would cap the version based on sid->version,
+ * but that prevents negotiation of a higher version if the
+ * previous session was reduced (e.g., with version fallback)
+ */
+ if (sid->version < ss->vrange.min ||
+ sid->version > ss->vrange.max) {
+ sidOK = PR_FALSE;
+ }
+ }
+ }
+
+ if (!sidOK) {
+ SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok);
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ sid = NULL;
+ }
+ }
+
+ if (sid) {
+ requestingResume = PR_TRUE;
+ SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_hits);
+
+ PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
+ sid->u.ssl3.sessionIDLength));
+
+ ss->ssl3.policy = sid->u.ssl3.policy;
+ } else {
+ SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_misses);
+
+ /*
+ * Windows SChannel compares the client_version inside the RSA
+ * EncryptedPreMasterSecret of a renegotiation with the
+ * client_version of the initial ClientHello rather than the
+ * ClientHello in the renegotiation. To work around this bug, we
+ * continue to use the client_version used in the initial
+ * ClientHello when renegotiating.
+ */
+ if (ss->firstHsDone) {
+ version = ss->clientHelloVersion;
+ }
+
+ sid = ssl3_NewSessionID(ss, PR_FALSE);
+ if (!sid) {
+ return SECFailure; /* memory error is set */
+ }
+ /* ss->version isn't set yet, but the sid needs a sane value. */
+ sid->version = version;
+ }
+
+ isTLS = (version > SSL_LIBRARY_VERSION_3_0);
+ ssl_GetSpecWriteLock(ss);
+ if (ss->ssl3.cwSpec->macDef->mac == ssl_mac_null) {
+ /* SSL records are not being MACed. */
+ ss->ssl3.cwSpec->version = version;
+ }
+ ssl_ReleaseSpecWriteLock(ss);
+
+ ssl_FreeSID(ss->sec.ci.sid); /* release the old sid */
+ ss->sec.ci.sid = sid;
+
+ /* HACK for SCSV in SSL 3.0. On initial handshake, prepend SCSV,
+ * only if TLS is disabled.
+ */
+ if (!ss->firstHsDone && !isTLS) {
+ /* Must set this before calling Hello Extension Senders,
+ * to suppress sending of empty RI extension.
+ */
+ ss->ssl3.hs.sendingSCSV = PR_TRUE;
+ }
+
+ /* When we attempt session resumption (only), we must lock the sid to
+ * prevent races with other resumption connections that receive a
+ * NewSessionTicket that will cause the ticket in the sid to be replaced.
+ * Once we've copied the session ticket into our ClientHello message, it
+ * is OK for the ticket to change, so we just need to make sure we hold
+ * the lock across the calls to ssl_ConstructExtensions.
+ */
+ if (sid->u.ssl3.lock) {
+ unlockNeeded = PR_TRUE;
+ PR_RWLock_Rlock(sid->u.ssl3.lock);
+ }
+
+ /* Generate a new random if this is the first attempt or renegotiation. */
+ if (type == client_hello_initial ||
+ type == client_hello_renegotiation) {
+ rv = ssl3_GetNewRandom(ss->ssl3.hs.client_random);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by GetNewRandom. */
+ }
+ }
+
+ if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = tls13_SetupClientHello(ss, type);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ /* Setup TLS ClientHello Extension Permutation? */
+ if (type == client_hello_initial &&
+ ss->vrange.max > SSL_LIBRARY_VERSION_3_0 &&
+ ss->opt.enableChXtnPermutation) {
+ rv = tls_ClientHelloExtensionPermutationSetup(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
+ rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_client_hello);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ if (IS_DTLS(ss)) {
+ ssl3_DisableNonDTLSSuites(ss);
+ }
+
+ rv = ssl3_CreateClientHelloPreamble(ss, sid, requestingResume, version,
+ PR_FALSE, &extensionBuf, &chBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_CreateClientHelloPreamble. */
+ }
+
+ if (!ss->ssl3.hs.echHpkeCtx) {
+ if (extensionBuf.len) {
+ rv = tls13_MaybeGreaseEch(ss, &chBuf, &extensionBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by tls13_MaybeGreaseEch. */
+ }
+ rv = ssl_InsertPaddingExtension(ss, chBuf.len, &extensionBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl_InsertPaddingExtension. */
+ }
+
+ rv = ssl3_InsertChHeaderSize(ss, &chBuf, &extensionBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_InsertChHeaderSize. */
+ }
+
+ /* If we are sending a PSK binder, replace the dummy value. */
+ if (ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
+ rv = tls13_WriteExtensionsWithBinder(ss, &extensionBuf, &chBuf);
+ } else {
+ rv = sslBuffer_AppendNumber(&chBuf, extensionBuf.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendBuffer(&chBuf, &extensionBuf);
+ }
+ if (rv != SECSuccess) {
+ goto loser; /* err set by sslBuffer_Append*. */
+ }
+ }
+
+ /* If we already have a message in place, we need to enqueue it.
+ * This empties the buffer. This is a convenient place to call
+ * dtls_StageHandshakeMessage to mark the message boundary. */
+ if (IS_DTLS(ss)) {
+ rv = dtls_StageHandshakeMessage(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ rv = ssl3_AppendHandshake(ss, chBuf.buf, chBuf.len);
+ } else {
+ rv = tls13_ConstructClientHelloWithEch(ss, sid, !requestingResume, &chBuf, &extensionBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+ rv = ssl3_UpdateDefaultHandshakeHashes(ss, chBuf.buf, chBuf.len);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+
+ if (IS_DTLS(ss)) {
+ rv = dtls_StageHandshakeMessage(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ /* By default, all messagess are added to both the inner and
+ * outer transcripts. For CH (or CH2 if HRR), that's problematic. */
+ rv = ssl3_AppendHandshakeSuppressHash(ss, chBuf.buf, chBuf.len);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (unlockNeeded) {
+ /* Note: goto loser can't be used past this point. */
+ PR_RWLock_Unlock(sid->u.ssl3.lock);
+ }
+
+ if (ss->xtnData.sentSessionTicketInClientHello) {
+ SSL_AtomicIncrementLong(&ssl3stats.sch_sid_stateless_resumes);
+ }
+
+ if (ss->ssl3.hs.sendingSCSV) {
+ /* Since we sent the SCSV, pretend we sent empty RI extension. */
+ TLSExtensionData *xtnData = &ss->xtnData;
+ xtnData->advertised[xtnData->numAdvertised++] =
+ ssl_renegotiation_info_xtn;
+ }
+
+ flags = 0;
+ rv = ssl3_FlushHandshake(ss, flags);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by ssl3_FlushHandshake */
+ }
+
+ if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = tls13_MaybeDo0RTTHandshake(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code set already. */
+ }
+ }
+
+ ss->ssl3.hs.ws = wait_server_hello;
+ sslBuffer_Clear(&chBuf);
+ sslBuffer_Clear(&extensionBuf);
+ return SECSuccess;
+
+loser:
+ if (unlockNeeded) {
+ PR_RWLock_Unlock(sid->u.ssl3.lock);
+ }
+ sslBuffer_Clear(&chBuf);
+ sslBuffer_Clear(&extensionBuf);
+ return SECFailure;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
+ * complete ssl3 Hello Request.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleHelloRequest(sslSocket *ss)
+{
+ sslSessionID *sid = ss->sec.ci.sid;
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (ss->ssl3.hs.ws == wait_server_hello)
+ return SECSuccess;
+ if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
+ return SECFailure;
+ }
+ if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
+ (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation);
+ PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
+ return SECFailure;
+ }
+
+ if (sid) {
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ ss->sec.ci.sid = NULL;
+ }
+
+ if (IS_DTLS(ss)) {
+ dtls_RehandshakeCleanup(ss);
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
+ ssl_ReleaseXmitBufLock(ss);
+
+ return rv;
+}
+
+static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
+ CKM_DES3_ECB,
+ CKM_CAST5_ECB,
+ CKM_DES_ECB,
+ CKM_KEY_WRAP_LYNKS,
+ CKM_IDEA_ECB,
+ CKM_CAST3_ECB,
+ CKM_CAST_ECB,
+ CKM_RC5_ECB,
+ CKM_RC2_ECB,
+ CKM_CDMF_ECB,
+ CKM_SKIPJACK_WRAP,
+ CKM_SKIPJACK_CBC64,
+ CKM_AES_ECB,
+ CKM_CAMELLIA_ECB,
+ CKM_SEED_ECB
+};
+
+static SECStatus
+ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech, unsigned int *wrapMechIndex)
+{
+ unsigned int i;
+ for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
+ if (wrapMechanismList[i] == mech) {
+ *wrapMechIndex = i;
+ return SECSuccess;
+ }
+ }
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+}
+
+/* Each process sharing the server session ID cache has its own array of SymKey
+ * pointers for the symmetric wrapping keys that are used to wrap the master
+ * secrets. There is one key for each authentication type. These Symkeys
+ * correspond to the wrapped SymKeys kept in the server session cache.
+ */
+const SSLAuthType ssl_wrap_key_auth_type[SSL_NUM_WRAP_KEYS] = {
+ ssl_auth_rsa_decrypt,
+ ssl_auth_rsa_sign,
+ ssl_auth_rsa_pss,
+ ssl_auth_ecdsa,
+ ssl_auth_ecdh_rsa,
+ ssl_auth_ecdh_ecdsa
+};
+
+static SECStatus
+ssl_FindIndexByWrapKey(const sslServerCert *serverCert, unsigned int *wrapKeyIndex)
+{
+ unsigned int i;
+ for (i = 0; i < SSL_NUM_WRAP_KEYS; ++i) {
+ if (SSL_CERT_IS(serverCert, ssl_wrap_key_auth_type[i])) {
+ *wrapKeyIndex = i;
+ return SECSuccess;
+ }
+ }
+ /* Can't assert here because we still get people using DSA certificates. */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+}
+
+static PK11SymKey *
+ssl_UnwrapSymWrappingKey(
+ SSLWrappedSymWrappingKey *pWswk,
+ SECKEYPrivateKey *svrPrivKey,
+ unsigned int wrapKeyIndex,
+ CK_MECHANISM_TYPE masterWrapMech,
+ void *pwArg)
+{
+ PK11SymKey *unwrappedWrappingKey = NULL;
+ SECItem wrappedKey;
+ PK11SymKey *Ks;
+ SECKEYPublicKey pubWrapKey;
+ ECCWrappedKeyInfo *ecWrapped;
+
+ /* found the wrapping key on disk. */
+ PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
+ PORT_Assert(pWswk->wrapKeyIndex == wrapKeyIndex);
+ if (pWswk->symWrapMechanism != masterWrapMech ||
+ pWswk->wrapKeyIndex != wrapKeyIndex) {
+ goto loser;
+ }
+ wrappedKey.type = siBuffer;
+ wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
+ wrappedKey.len = pWswk->wrappedSymKeyLen;
+ PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
+
+ switch (ssl_wrap_key_auth_type[wrapKeyIndex]) {
+
+ case ssl_auth_rsa_decrypt:
+ case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
+ unwrappedWrappingKey =
+ PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
+ masterWrapMech, CKA_UNWRAP, 0);
+ break;
+
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ /*
+ * For ssl_auth_ecd*, we first create an EC public key based on
+ * data stored with the wrappedSymmetricWrappingkey. Next,
+ * we do an ECDH computation involving this public key and
+ * the SSL server's (long-term) EC private key. The resulting
+ * shared secret is treated the same way as Fortezza's Ks, i.e.,
+ * it is used to recover the symmetric wrapping key.
+ *
+ * The data in wrappedSymmetricWrappingkey is laid out as defined
+ * in the ECCWrappedKeyInfo structure.
+ */
+ ecWrapped = (ECCWrappedKeyInfo *)pWswk->wrappedSymmetricWrappingkey;
+
+ PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
+ ecWrapped->wrappedKeyLen <=
+ MAX_EC_WRAPPED_KEY_BUFLEN);
+
+ if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
+ ecWrapped->wrappedKeyLen >
+ MAX_EC_WRAPPED_KEY_BUFLEN) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+
+ pubWrapKey.keyType = ecKey;
+ pubWrapKey.u.ec.size = ecWrapped->size;
+ pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
+ pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
+ pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
+ pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
+ ecWrapped->encodedParamLen;
+
+ wrappedKey.len = ecWrapped->wrappedKeyLen;
+ wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
+ ecWrapped->pubValueLen;
+
+ /* Derive Ks using ECDH */
+ Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
+ NULL, CKM_ECDH1_DERIVE, masterWrapMech,
+ CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
+ if (Ks == NULL) {
+ goto loser;
+ }
+
+ /* Use Ks to unwrap the wrapping key */
+ unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
+ &wrappedKey, masterWrapMech,
+ CKA_UNWRAP, 0);
+ PK11_FreeSymKey(Ks);
+
+ break;
+
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+loser:
+ return unwrappedWrappingKey;
+}
+
+typedef struct {
+ PK11SymKey *symWrapKey[SSL_NUM_WRAP_KEYS];
+} ssl3SymWrapKey;
+
+static PZLock *symWrapKeysLock = NULL;
+static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS];
+
+SECStatus
+ssl_FreeSymWrapKeysLock(void)
+{
+ if (symWrapKeysLock) {
+ PZ_DestroyLock(symWrapKeysLock);
+ symWrapKeysLock = NULL;
+ return SECSuccess;
+ }
+ PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+ return SECFailure;
+}
+
+SECStatus
+SSL3_ShutdownServerCache(void)
+{
+ int i, j;
+
+ if (!symWrapKeysLock)
+ return SECSuccess; /* lock was never initialized */
+ PZ_Lock(symWrapKeysLock);
+ /* get rid of all symWrapKeys */
+ for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
+ for (j = 0; j < SSL_NUM_WRAP_KEYS; ++j) {
+ PK11SymKey **pSymWrapKey;
+ pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
+ if (*pSymWrapKey) {
+ PK11_FreeSymKey(*pSymWrapKey);
+ *pSymWrapKey = NULL;
+ }
+ }
+ }
+
+ PZ_Unlock(symWrapKeysLock);
+ ssl_FreeSessionCacheLocks();
+ return SECSuccess;
+}
+
+SECStatus
+ssl_InitSymWrapKeysLock(void)
+{
+ symWrapKeysLock = PZ_NewLock(nssILockOther);
+ return symWrapKeysLock ? SECSuccess : SECFailure;
+}
+
+/* Try to get wrapping key for mechanism from in-memory array.
+ * If that fails, look for one on disk.
+ * If that fails, generate a new one, put the new one on disk,
+ * Put the new key in the in-memory array.
+ *
+ * Note that this function performs some fairly inadvisable functions with
+ * certificate private keys. ECDSA keys are used with ECDH; similarly, RSA
+ * signing keys are used to encrypt. Bug 1248320.
+ */
+PK11SymKey *
+ssl3_GetWrappingKey(sslSocket *ss,
+ PK11SlotInfo *masterSecretSlot,
+ CK_MECHANISM_TYPE masterWrapMech,
+ void *pwArg)
+{
+ SSLAuthType authType;
+ SECKEYPrivateKey *svrPrivKey;
+ SECKEYPublicKey *svrPubKey = NULL;
+ PK11SymKey *unwrappedWrappingKey = NULL;
+ PK11SymKey **pSymWrapKey;
+ CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM;
+ int length;
+ unsigned int wrapMechIndex;
+ unsigned int wrapKeyIndex;
+ SECStatus rv;
+ SECItem wrappedKey;
+ SSLWrappedSymWrappingKey wswk;
+ PK11SymKey *Ks = NULL;
+ SECKEYPublicKey *pubWrapKey = NULL;
+ SECKEYPrivateKey *privWrapKey = NULL;
+ ECCWrappedKeyInfo *ecWrapped;
+ const sslServerCert *serverCert = ss->sec.serverCert;
+
+ PORT_Assert(serverCert);
+ PORT_Assert(serverCert->serverKeyPair);
+ PORT_Assert(serverCert->serverKeyPair->privKey);
+ PORT_Assert(serverCert->serverKeyPair->pubKey);
+ if (!serverCert || !serverCert->serverKeyPair ||
+ !serverCert->serverKeyPair->privKey ||
+ !serverCert->serverKeyPair->pubKey) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return NULL; /* hmm */
+ }
+
+ rv = ssl_FindIndexByWrapKey(serverCert, &wrapKeyIndex);
+ if (rv != SECSuccess)
+ return NULL; /* unusable wrapping key. */
+
+ rv = ssl_FindIndexByWrapMechanism(masterWrapMech, &wrapMechIndex);
+ if (rv != SECSuccess)
+ return NULL; /* invalid masterWrapMech. */
+
+ authType = ssl_wrap_key_auth_type[wrapKeyIndex];
+ svrPrivKey = serverCert->serverKeyPair->privKey;
+ pSymWrapKey = &symWrapKeys[wrapMechIndex].symWrapKey[wrapKeyIndex];
+
+ ssl_InitSessionCacheLocks(PR_TRUE);
+
+ PZ_Lock(symWrapKeysLock);
+
+ unwrappedWrappingKey = *pSymWrapKey;
+ if (unwrappedWrappingKey != NULL) {
+ if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
+ unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
+ goto done;
+ }
+ /* slot series has changed, so this key is no good any more. */
+ PK11_FreeSymKey(unwrappedWrappingKey);
+ *pSymWrapKey = unwrappedWrappingKey = NULL;
+ }
+
+ /* Try to get wrapped SymWrapping key out of the (disk) cache. */
+ /* Following call fills in wswk on success. */
+ rv = ssl_GetWrappingKey(wrapMechIndex, wrapKeyIndex, &wswk);
+ if (rv == SECSuccess) {
+ /* found the wrapped sym wrapping key on disk. */
+ unwrappedWrappingKey =
+ ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
+ masterWrapMech, pwArg);
+ if (unwrappedWrappingKey) {
+ goto install;
+ }
+ }
+
+ if (!masterSecretSlot) /* caller doesn't want to create a new one. */
+ goto loser;
+
+ length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
+ /* Zero length means fixed key length algorithm, or error.
+ * It's ambiguous.
+ */
+ unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
+ length, pwArg);
+ if (!unwrappedWrappingKey) {
+ goto loser;
+ }
+
+ /* Prepare the buffer to receive the wrappedWrappingKey,
+ * the symmetric wrapping key wrapped using the server's pub key.
+ */
+ PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */
+
+ svrPubKey = serverCert->serverKeyPair->pubKey;
+ wrappedKey.type = siBuffer;
+ wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
+ wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
+
+ PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
+ if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
+ goto loser;
+
+ /* wrap symmetric wrapping key in server's public key. */
+ switch (authType) {
+ case ssl_auth_rsa_decrypt:
+ case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */
+ case ssl_auth_rsa_pss:
+ asymWrapMechanism = CKM_RSA_PKCS;
+ rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
+ unwrappedWrappingKey, &wrappedKey);
+ break;
+
+ case ssl_auth_ecdsa:
+ case ssl_auth_ecdh_rsa:
+ case ssl_auth_ecdh_ecdsa:
+ /*
+ * We generate an ephemeral EC key pair. Perform an ECDH
+ * computation involving this ephemeral EC public key and
+ * the SSL server's (long-term) EC private key. The resulting
+ * shared secret is treated in the same way as Fortezza's Ks,
+ * i.e., it is used to wrap the wrapping key. To facilitate
+ * unwrapping in ssl_UnwrapWrappingKey, we also store all
+ * relevant info about the ephemeral EC public key in
+ * wswk.wrappedSymmetricWrappingkey and lay it out as
+ * described in the ECCWrappedKeyInfo structure.
+ */
+ PORT_Assert(SECKEY_GetPublicKeyType(svrPubKey) == ecKey);
+ if (SECKEY_GetPublicKeyType(svrPubKey) != ecKey) {
+ /* something is wrong in sslsecur.c if this isn't an ecKey */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ rv = SECFailure;
+ goto ec_cleanup;
+ }
+
+ privWrapKey = SECKEY_CreateECPrivateKey(
+ &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
+ if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
+ rv = SECFailure;
+ goto ec_cleanup;
+ }
+
+ /* Set the key size in bits */
+ if (pubWrapKey->u.ec.size == 0) {
+ pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
+ }
+
+ PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
+ pubWrapKey->u.ec.publicValue.len <
+ MAX_EC_WRAPPED_KEY_BUFLEN);
+ if (pubWrapKey->u.ec.DEREncodedParams.len +
+ pubWrapKey->u.ec.publicValue.len >=
+ MAX_EC_WRAPPED_KEY_BUFLEN) {
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ rv = SECFailure;
+ goto ec_cleanup;
+ }
+
+ /* Derive Ks using ECDH */
+ Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
+ NULL, CKM_ECDH1_DERIVE, masterWrapMech,
+ CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
+ if (Ks == NULL) {
+ rv = SECFailure;
+ goto ec_cleanup;
+ }
+
+ ecWrapped = (ECCWrappedKeyInfo *)(wswk.wrappedSymmetricWrappingkey);
+ ecWrapped->size = pubWrapKey->u.ec.size;
+ ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
+ PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
+ pubWrapKey->u.ec.DEREncodedParams.len);
+
+ ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
+ PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
+ pubWrapKey->u.ec.publicValue.data,
+ pubWrapKey->u.ec.publicValue.len);
+
+ wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
+ (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
+ wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
+ ecWrapped->pubValueLen;
+
+ /* wrap symmetricWrapping key with the local Ks */
+ rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
+ unwrappedWrappingKey, &wrappedKey);
+
+ if (rv != SECSuccess) {
+ goto ec_cleanup;
+ }
+
+ /* Write down the length of wrapped key in the buffer
+ * wswk.wrappedSymmetricWrappingkey at the appropriate offset
+ */
+ ecWrapped->wrappedKeyLen = wrappedKey.len;
+
+ ec_cleanup:
+ if (privWrapKey)
+ SECKEY_DestroyPrivateKey(privWrapKey);
+ if (pubWrapKey)
+ SECKEY_DestroyPublicKey(pubWrapKey);
+ if (Ks)
+ PK11_FreeSymKey(Ks);
+ asymWrapMechanism = masterWrapMech;
+ break;
+
+ default:
+ rv = SECFailure;
+ break;
+ }
+
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
+
+ wswk.symWrapMechanism = masterWrapMech;
+ wswk.asymWrapMechanism = asymWrapMechanism;
+ wswk.wrapMechIndex = wrapMechIndex;
+ wswk.wrapKeyIndex = wrapKeyIndex;
+ wswk.wrappedSymKeyLen = wrappedKey.len;
+
+ /* put it on disk. */
+ /* If the wrapping key for this KEA type has already been set,
+ * then abandon the value we just computed and
+ * use the one we got from the disk.
+ */
+ rv = ssl_SetWrappingKey(&wswk);
+ if (rv == SECSuccess) {
+ /* somebody beat us to it. The original contents of our wswk
+ * has been replaced with the content on disk. Now, discard
+ * the key we just created and unwrap this new one.
+ */
+ PK11_FreeSymKey(unwrappedWrappingKey);
+
+ unwrappedWrappingKey =
+ ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, wrapKeyIndex,
+ masterWrapMech, pwArg);
+ }
+
+install:
+ if (unwrappedWrappingKey) {
+ *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
+ }
+
+loser:
+done:
+ PZ_Unlock(symWrapKeysLock);
+ return unwrappedWrappingKey;
+}
+
+#ifdef NSS_ALLOW_SSLKEYLOGFILE
+/* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
+ * bytes to |out|. */
+static void
+hexEncode(char *out, const unsigned char *in, unsigned int length)
+{
+ static const char hextable[] = "0123456789abcdef";
+ unsigned int i;
+
+ for (i = 0; i < length; i++) {
+ *(out++) = hextable[in[i] >> 4];
+ *(out++) = hextable[in[i] & 15];
+ }
+}
+#endif
+
+/* Called from ssl3_SendClientKeyExchange(). */
+static SECStatus
+ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
+{
+ PK11SymKey *pms = NULL;
+ SECStatus rv = SECFailure;
+ SECItem enc_pms = { siBuffer, NULL, 0 };
+ PRBool isTLS;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ /* Generate the pre-master secret ... */
+ ssl_GetSpecWriteLock(ss);
+ isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
+
+ pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
+ ssl_ReleaseSpecWriteLock(ss);
+ if (pms == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ /* Get the wrapped (encrypted) pre-master secret, enc_pms */
+ unsigned int svrPubKeyBits = SECKEY_PublicKeyStrengthInBits(svrPubKey);
+ enc_pms.len = (svrPubKeyBits + 7) / 8;
+ /* Check that the RSA key isn't larger than 8k bit. */
+ if (svrPubKeyBits > SSL_MAX_RSA_KEY_BITS) {
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+ enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len);
+ if (enc_pms.data == NULL) {
+ goto loser; /* err set by PORT_Alloc */
+ }
+
+ /* Wrap pre-master secret in server's public key. */
+ rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+#ifdef TRACE
+ if (ssl_trace >= 100) {
+ SECStatus extractRV = PK11_ExtractKeyValue(pms);
+ if (extractRV == SECSuccess) {
+ SECItem *keyData = PK11_GetKeyData(pms);
+ if (keyData && keyData->data && keyData->len) {
+ ssl_PrintBuf(ss, "Pre-Master Secret",
+ keyData->data, keyData->len);
+ }
+ }
+ }
+#endif
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
+ isTLS ? enc_pms.len + 2
+ : enc_pms.len);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_AppendHandshake* */
+ }
+ if (isTLS) {
+ rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
+ } else {
+ rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
+ }
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_AppendHandshake* */
+ }
+
+ rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+ PK11_FreeSymKey(pms);
+ pms = NULL;
+
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ rv = SECSuccess;
+
+loser:
+ if (enc_pms.data != NULL) {
+ PORT_Free(enc_pms.data);
+ }
+ if (pms != NULL) {
+ PK11_FreeSymKey(pms);
+ }
+ return rv;
+}
+
+/* DH shares need to be padded to the size of their prime. Some implementations
+ * require this. TLS 1.3 also requires this. */
+SECStatus
+ssl_AppendPaddedDHKeyShare(sslBuffer *buf, const SECKEYPublicKey *pubKey,
+ PRBool appendLength)
+{
+ SECStatus rv;
+ unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len;
+
+ if (appendLength) {
+ rv = sslBuffer_AppendNumber(buf, pubKey->u.dh.prime.len, 2);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+ while (pad) {
+ rv = sslBuffer_AppendNumber(buf, 0, 1);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ --pad;
+ }
+ rv = sslBuffer_Append(buf, pubKey->u.dh.publicValue.data,
+ pubKey->u.dh.publicValue.len);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ return SECSuccess;
+}
+
+/* Called from ssl3_SendClientKeyExchange(). */
+static SECStatus
+ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
+{
+ PK11SymKey *pms = NULL;
+ SECStatus rv;
+ PRBool isTLS;
+ CK_MECHANISM_TYPE target;
+
+ const ssl3DHParams *params;
+ ssl3DHParams customParams;
+ const sslNamedGroupDef *groupDef;
+ static const sslNamedGroupDef customGroupDef = {
+ ssl_grp_ffdhe_custom, 0, ssl_kea_dh, SEC_OID_TLS_DHE_CUSTOM, PR_FALSE
+ };
+ sslEphemeralKeyPair *keyPair = NULL;
+ SECKEYPublicKey *pubKey;
+ PRUint8 dhData[SSL_MAX_DH_KEY_BITS / 8 + 2];
+ sslBuffer dhBuf = SSL_BUFFER(dhData);
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
+
+ /* Copy DH parameters from server key */
+
+ if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) {
+ PORT_SetError(SEC_ERROR_BAD_KEY);
+ return SECFailure;
+ }
+
+ /* Work out the parameters. */
+ rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime,
+ &svrPubKey->u.dh.base,
+ &groupDef, &params);
+ if (rv != SECSuccess) {
+ /* If we require named groups, we will have already validated the group
+ * in ssl_HandleDHServerKeyExchange() */
+ PORT_Assert(!ss->opt.requireDHENamedGroups &&
+ !ss->xtnData.peerSupportsFfdheGroups);
+
+ customParams.name = ssl_grp_ffdhe_custom;
+ customParams.prime.data = svrPubKey->u.dh.prime.data;
+ customParams.prime.len = svrPubKey->u.dh.prime.len;
+ customParams.base.data = svrPubKey->u.dh.base.data;
+ customParams.base.len = svrPubKey->u.dh.base.len;
+ params = &customParams;
+ groupDef = &customGroupDef;
+ }
+ ss->sec.keaGroup = groupDef;
+
+ rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
+ goto loser;
+ }
+ pubKey = keyPair->keys->pubKey;
+ PRINT_BUF(50, (ss, "DH public value:",
+ pubKey->u.dh.publicValue.data,
+ pubKey->u.dh.publicValue.len));
+
+ if (isTLS)
+ target = CKM_TLS_MASTER_KEY_DERIVE_DH;
+ else
+ target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
+
+ /* Determine the PMS */
+ pms = PK11_PubDerive(keyPair->keys->privKey, svrPubKey,
+ PR_FALSE, NULL, NULL, CKM_DH_PKCS_DERIVE,
+ target, CKA_DERIVE, 0, NULL);
+
+ if (pms == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ /* Note: send the DH share padded to avoid triggering bugs. */
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
+ params->prime.len + 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_AppendHandshake* */
+ }
+ rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl_AppendPaddedDHKeyShare */
+ }
+ rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_AppendBufferToHandshake */
+ }
+
+ rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ sslBuffer_Clear(&dhBuf);
+ PK11_FreeSymKey(pms);
+ ssl_FreeEphemeralKeyPair(keyPair);
+ return SECSuccess;
+
+loser:
+ if (pms)
+ PK11_FreeSymKey(pms);
+ if (keyPair)
+ ssl_FreeEphemeralKeyPair(keyPair);
+ sslBuffer_Clear(&dhBuf);
+ return SECFailure;
+}
+
+/* Called from ssl3_HandleServerHelloDone(). */
+static SECStatus
+ssl3_SendClientKeyExchange(sslSocket *ss)
+{
+ SECKEYPublicKey *serverKey = NULL;
+ SECStatus rv = SECFailure;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->sec.peerKey == NULL) {
+ serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
+ if (serverKey == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
+ return SECFailure;
+ }
+ } else {
+ serverKey = ss->sec.peerKey;
+ ss->sec.peerKey = NULL; /* we're done with it now */
+ }
+
+ ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
+ ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
+
+ switch (ss->ssl3.hs.kea_def->exchKeyType) {
+ case ssl_kea_rsa:
+ rv = ssl3_SendRSAClientKeyExchange(ss, serverKey);
+ break;
+
+ case ssl_kea_dh:
+ rv = ssl3_SendDHClientKeyExchange(ss, serverKey);
+ break;
+
+ case ssl_kea_ecdh:
+ rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
+ break;
+
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ break;
+ }
+
+ SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
+ SSL_GETPID(), ss->fd));
+
+ SECKEY_DestroyPublicKey(serverKey);
+ return rv; /* err code already set. */
+}
+
+/* Used by ssl_PickSignatureScheme(). */
+PRBool
+ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
+ const SSLSignatureScheme *peerSchemes,
+ unsigned int peerSchemeCount,
+ PRBool requireSha1,
+ PRBool slotDoesPss)
+{
+ SSLHashType hashType;
+ unsigned int i;
+
+ /* Skip RSA-PSS schemes when the certificate's private key slot does
+ * not support this signature mechanism. */
+ if (ssl_IsRsaPssSignatureScheme(scheme) && !slotDoesPss) {
+ return PR_FALSE;
+ }
+
+ hashType = ssl_SignatureSchemeToHashType(scheme);
+ if (requireSha1 && (hashType != ssl_hash_sha1)) {
+ return PR_FALSE;
+ }
+
+ if (!ssl_SchemePolicyOK(scheme, kSSLSigSchemePolicy)) {
+ return PR_FALSE;
+ }
+
+ for (i = 0; i < peerSchemeCount; i++) {
+ if (peerSchemes[i] == scheme) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+SECStatus
+ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey, CERTCertificate *cert,
+ void *pwarg, PRBool *supportsRsaPss)
+{
+ PK11SlotInfo *slot = NULL;
+ if (privKey) {
+ slot = PK11_GetSlotFromPrivateKey(privKey);
+ } else {
+ CK_OBJECT_HANDLE certID = PK11_FindObjectForCert(cert, pwarg, &slot);
+ if (certID == CK_INVALID_HANDLE) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ }
+ if (!slot) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ *supportsRsaPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]);
+ PK11_FreeSlot(slot);
+ return SECSuccess;
+}
+
+SECStatus
+ssl_PickSignatureScheme(sslSocket *ss,
+ CERTCertificate *cert,
+ SECKEYPublicKey *pubKey,
+ SECKEYPrivateKey *privKey,
+ const SSLSignatureScheme *peerSchemes,
+ unsigned int peerSchemeCount,
+ PRBool requireSha1,
+ SSLSignatureScheme *schemePtr)
+{
+ unsigned int i;
+ PRBool doesRsaPss;
+ PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
+ SECStatus rv;
+ SSLSignatureScheme scheme;
+ SECOidTag spkiOid;
+
+ /* We can't require SHA-1 in TLS 1.3. */
+ PORT_Assert(!(requireSha1 && isTLS13));
+ if (!pubKey || !cert) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ rv = ssl_PrivateKeySupportsRsaPss(privKey, cert, ss->pkcs11PinArg,
+ &doesRsaPss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* If the certificate SPKI indicates a single scheme, don't search. */
+ rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
+ isTLS13, &scheme);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (scheme != ssl_sig_none) {
+ if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
+ !ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
+ requireSha1, doesRsaPss)) {
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ *schemePtr = scheme;
+ return SECSuccess;
+ }
+
+ spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
+ if (spkiOid == SEC_OID_UNKNOWN) {
+ return SECFailure;
+ }
+
+ /* Now we have to search based on the key type. Go through our preferred
+ * schemes in order and find the first that can be used. */
+ for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ scheme = ss->ssl3.signatureSchemes[i];
+
+ if (ssl_SignatureSchemeValid(scheme, spkiOid, isTLS13) &&
+ ssl_CanUseSignatureScheme(scheme, peerSchemes, peerSchemeCount,
+ requireSha1, doesRsaPss)) {
+ *schemePtr = scheme;
+ return SECSuccess;
+ }
+ }
+
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+}
+
+static SECStatus
+ssl_PickFallbackSignatureScheme(sslSocket *ss, SECKEYPublicKey *pubKey)
+{
+ PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
+
+ switch (SECKEY_GetPublicKeyType(pubKey)) {
+ case rsaKey:
+ if (isTLS12) {
+ ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1;
+ } else {
+ ss->ssl3.hs.signatureScheme = ssl_sig_rsa_pkcs1_sha1md5;
+ }
+ break;
+ case ecKey:
+ ss->ssl3.hs.signatureScheme = ssl_sig_ecdsa_sha1;
+ break;
+ case dsaKey:
+ ss->ssl3.hs.signatureScheme = ssl_sig_dsa_sha1;
+ break;
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/* ssl3_PickServerSignatureScheme selects a signature scheme for signing the
+ * handshake. Most of this is determined by the key pair we are using.
+ * Prior to TLS 1.2, the MD5/SHA1 combination is always used. With TLS 1.2, a
+ * client may advertise its support for signature and hash combinations. */
+static SECStatus
+ssl3_PickServerSignatureScheme(sslSocket *ss)
+{
+ const sslServerCert *cert = ss->sec.serverCert;
+ PRBool isTLS12 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_2;
+
+ if (!isTLS12 || !ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
+ /* If the client didn't provide any signature_algorithms extension then
+ * we can assume that they support SHA-1: RFC5246, Section 7.4.1.4.1. */
+ return ssl_PickFallbackSignatureScheme(ss, cert->serverKeyPair->pubKey);
+ }
+
+ /* Sets error code, if needed. */
+ return ssl_PickSignatureScheme(ss, cert->serverCert,
+ cert->serverKeyPair->pubKey,
+ cert->serverKeyPair->privKey,
+ ss->xtnData.sigSchemes,
+ ss->xtnData.numSigSchemes,
+ PR_FALSE /* requireSha1 */,
+ &ss->ssl3.hs.signatureScheme);
+}
+
+SECStatus
+ssl_PickClientSignatureScheme(sslSocket *ss, CERTCertificate *clientCertificate,
+ SECKEYPrivateKey *privKey,
+ const SSLSignatureScheme *schemes,
+ unsigned int numSchemes,
+ SSLSignatureScheme *schemePtr)
+{
+ SECStatus rv;
+ PRBool isTLS13 = (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
+ SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(clientCertificate);
+
+ PORT_Assert(pubKey);
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ /* We should have already checked that a signature scheme was
+ * listed in the request. */
+ PORT_Assert(schemes && numSchemes > 0);
+ }
+
+ if (!isTLS13 &&
+ (SECKEY_GetPublicKeyType(pubKey) == rsaKey ||
+ SECKEY_GetPublicKeyType(pubKey) == dsaKey) &&
+ SECKEY_PublicKeyStrengthInBits(pubKey) <= 1024) {
+ /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
+ * it may be unable to sign SHA-256 hashes. This is the case for older
+ * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
+ * older, DSA key size is at most 1024 bits and the hash function must
+ * be SHA-1.
+ */
+ rv = ssl_PickSignatureScheme(ss, clientCertificate,
+ pubKey, privKey, schemes, numSchemes,
+ PR_TRUE /* requireSha1 */, schemePtr);
+ if (rv == SECSuccess) {
+ SECKEY_DestroyPublicKey(pubKey);
+ return SECSuccess;
+ }
+ /* If this fails, that's because the peer doesn't advertise SHA-1,
+ * so fall back to the full negotiation. */
+ }
+ rv = ssl_PickSignatureScheme(ss, clientCertificate,
+ pubKey, privKey, schemes, numSchemes,
+ PR_FALSE /* requireSha1 */, schemePtr);
+ SECKEY_DestroyPublicKey(pubKey);
+ return rv;
+}
+
+/* Called from ssl3_HandleServerHelloDone(). */
+static SECStatus
+ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
+{
+ SECStatus rv = SECFailure;
+ PRBool isTLS12;
+ SECItem buf = { siBuffer, NULL, 0 };
+ SSL3Hashes hashes;
+ unsigned int len;
+ SSLHashType hashAlg;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
+ SSL_GETPID(), ss->fd));
+
+ ssl_GetSpecReadLock(ss);
+
+ if (ss->ssl3.hs.hashType == handshake_hash_record) {
+ hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
+ } else {
+ /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+ hashAlg = ssl_hash_none;
+ }
+ if (ss->ssl3.hs.hashType == handshake_hash_record &&
+ hashAlg != ssl3_GetSuitePrfHash(ss)) {
+ rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
+ ss->ssl3.hs.messages.len,
+ hashAlg, &hashes);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ }
+ } else {
+ rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
+ }
+ ssl_ReleaseSpecReadLock(ss);
+ if (rv != SECSuccess) {
+ goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */
+ }
+
+ isTLS12 = (PRBool)(ss->version == SSL_LIBRARY_VERSION_TLS_1_2);
+ PORT_Assert(ss->version <= SSL_LIBRARY_VERSION_TLS_1_2);
+
+ rv = ssl3_SignHashes(ss, &hashes, privKey, &buf);
+ if (rv == SECSuccess && !ss->sec.isServer) {
+ /* Remember the info about the slot that did the signing.
+ ** Later, when doing an SSL restart handshake, verify this.
+ ** These calls are mere accessors, and can't fail.
+ */
+ PK11SlotInfo *slot;
+ sslSessionID *sid = ss->sec.ci.sid;
+
+ slot = PK11_GetSlotFromPrivateKey(privKey);
+ sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
+ sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
+ sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
+ sid->u.ssl3.clAuthValid = PR_TRUE;
+ PK11_FreeSlot(slot);
+ }
+ if (rv != SECSuccess) {
+ goto done; /* err code was set by ssl3_SignHashes */
+ }
+
+ len = buf.len + 2 + (isTLS12 ? 2 : 0);
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
+ if (rv != SECSuccess) {
+ goto done; /* error code set by AppendHandshake */
+ }
+ if (isTLS12) {
+ rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
+ if (rv != SECSuccess) {
+ goto done; /* err set by AppendHandshake. */
+ }
+ }
+ rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
+ if (rv != SECSuccess) {
+ goto done; /* error code set by AppendHandshake */
+ }
+
+done:
+ if (buf.data)
+ PORT_Free(buf.data);
+ return rv;
+}
+
+/* Once a cipher suite has been selected, make sure that the necessary secondary
+ * information is properly set. */
+SECStatus
+ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes)
+{
+ ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
+ if (!ss->ssl3.hs.suite_def) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.kea_def = &kea_defs[ss->ssl3.hs.suite_def->key_exchange_alg];
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite;
+
+ if (!initHashes) {
+ return SECSuccess;
+ }
+ /* Now we have a cipher suite, initialize the handshake hashes. */
+ return ssl3_InitHandshakeHashes(ss);
+}
+
+SECStatus
+ssl_ClientSetCipherSuite(sslSocket *ss, SSL3ProtocolVersion version,
+ ssl3CipherSuite suite, PRBool initHashes)
+{
+ unsigned int i;
+ if (ssl3_config_match_init(ss) == 0) {
+ PORT_Assert(PR_FALSE);
+ return SECFailure;
+ }
+ for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
+ if (suite == suiteCfg->cipher_suite) {
+ SSLVersionRange vrange = { version, version };
+ if (!ssl3_config_match(suiteCfg, ss->ssl3.policy, &vrange, ss)) {
+ /* config_match already checks whether the cipher suite is
+ * acceptable for the version, but the check is repeated here
+ * in order to give a more precise error code. */
+ if (!ssl3_CipherSuiteAllowedForVersionRange(suite, &vrange)) {
+ PORT_SetError(SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION);
+ } else {
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ }
+ return SECFailure;
+ }
+ break;
+ }
+ }
+ if (i >= ssl_V3_SUITES_IMPLEMENTED) {
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+ }
+
+ /* Don't let the server change its mind. */
+ if (ss->ssl3.hs.helloRetry && suite != ss->ssl3.hs.cipher_suite) {
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)suite;
+ return ssl3_SetupCipherSuite(ss, initHashes);
+}
+
+/* Check that session ID we received from the server, if any, matches our
+ * expectations, depending on whether we're in compat mode and whether we
+ * negotiated TLS 1.3+ or TLS 1.2-.
+ */
+static PRBool
+ssl_CheckServerSessionIdCorrectness(sslSocket *ss, SECItem *sidBytes)
+{
+ sslSessionID *sid = ss->sec.ci.sid;
+ PRBool sidMatch = PR_FALSE;
+ PRBool sentFakeSid = PR_FALSE;
+ PRBool sentRealSid = sid && sid->version < SSL_LIBRARY_VERSION_TLS_1_3;
+
+ /* If attempting to resume a TLS 1.2 connection, the session ID won't be a
+ * fake. Check for the real value. */
+ if (sentRealSid) {
+ sidMatch = (sidBytes->len == sid->u.ssl3.sessionIDLength) &&
+ (!sidBytes->len || PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len) == 0);
+ } else {
+ /* Otherwise, the session ID was a fake if TLS 1.3 compat mode is
+ * enabled. If so, check for the fake value. */
+ sentFakeSid = ss->opt.enableTls13CompatMode && !IS_DTLS(ss);
+ if (sentFakeSid && sidBytes->len == SSL3_SESSIONID_BYTES) {
+ PRUint8 buf[SSL3_SESSIONID_BYTES];
+ ssl_MakeFakeSid(ss, buf);
+ sidMatch = PORT_Memcmp(buf, sidBytes->data, sidBytes->len) == 0;
+ }
+ }
+
+ /* TLS 1.2: Session ID shouldn't match if we sent a fake. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ if (sentFakeSid) {
+ return !sidMatch;
+ }
+ return PR_TRUE;
+ }
+
+ /* TLS 1.3: We sent a session ID. The server's should match. */
+ if (!IS_DTLS(ss) && (sentRealSid || sentFakeSid)) {
+ return sidMatch;
+ }
+
+ /* TLS 1.3 (no SID)/DTLS 1.3: The server shouldn't send a session ID. */
+ return sidBytes->len == 0;
+}
+
+static SECStatus
+ssl_CheckServerRandom(sslSocket *ss)
+{
+ /* Check the ServerHello.random per [RFC 8446 Section 4.1.3].
+ *
+ * TLS 1.3 clients receiving a ServerHello indicating TLS 1.2 or below
+ * MUST check that the last 8 bytes are not equal to either of these
+ * values. TLS 1.2 clients SHOULD also check that the last 8 bytes are
+ * not equal to the second value if the ServerHello indicates TLS 1.1 or
+ * below. If a match is found, the client MUST abort the handshake with
+ * an "illegal_parameter" alert.
+ */
+ SSL3ProtocolVersion checkVersion =
+ ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion
+ : ss->vrange.max;
+
+ if (checkVersion >= SSL_LIBRARY_VERSION_TLS_1_2 &&
+ checkVersion > ss->version) {
+ /* Both sections use the same sentinel region. */
+ PRUint8 *downgrade_sentinel =
+ ss->ssl3.hs.server_random +
+ SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
+
+ if (!PORT_Memcmp(downgrade_sentinel,
+ tls12_downgrade_random,
+ sizeof(tls12_downgrade_random)) ||
+ !PORT_Memcmp(downgrade_sentinel,
+ tls1_downgrade_random,
+ sizeof(tls1_downgrade_random))) {
+ return SECFailure;
+ }
+ }
+
+ return SECSuccess;
+}
+
+/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
+ * ssl3 ServerHello message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleServerHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ PRUint32 cipher;
+ int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ PRUint32 compression;
+ SECStatus rv;
+ SECItem sidBytes = { siBuffer, NULL, 0 };
+ PRBool isHelloRetry;
+ SSL3AlertDescription desc = illegal_parameter;
+ const PRUint8 *savedMsg = b;
+ const PRUint32 savedLength = length;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->ssl3.hs.ws != wait_server_hello) {
+ errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
+ desc = unexpected_message;
+ goto alert_loser;
+ }
+
+ /* clean up anything left from previous handshake. */
+ if (ss->ssl3.clientCertChain != NULL) {
+ CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
+ ss->ssl3.clientCertChain = NULL;
+ }
+ if (ss->ssl3.clientCertificate != NULL) {
+ CERT_DestroyCertificate(ss->ssl3.clientCertificate);
+ ss->ssl3.clientCertificate = NULL;
+ }
+ if (ss->ssl3.clientPrivateKey != NULL) {
+ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
+ ss->ssl3.clientPrivateKey = NULL;
+ }
+ // TODO(djackson) - Bob removed this. Why?
+ if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
+ PR_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
+ ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
+ ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
+ }
+
+ /* Note that if the server selects TLS 1.3, this will set the version to TLS
+ * 1.2. We will amend that once all other fields have been read. */
+ rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+
+ rv = ssl3_ConsumeHandshake(
+ ss, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+ isHelloRetry = !PORT_Memcmp(ss->ssl3.hs.server_random,
+ ssl_hello_retry_random, SSL3_RANDOM_LENGTH);
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+ if (sidBytes.len > SSL3_SESSIONID_BYTES) {
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_0)
+ desc = decode_error;
+ goto alert_loser; /* malformed. */
+ }
+
+ /* Read the cipher suite. */
+ rv = ssl3_ConsumeHandshakeNumber(ss, &cipher, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+
+ /* Compression method. */
+ rv = ssl3_ConsumeHandshakeNumber(ss, &compression, 1, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert has been sent */
+ }
+ if (compression != ssl_compression_null) {
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ goto alert_loser;
+ }
+
+ /* Parse extensions. */
+ if (length != 0) {
+ PRUint32 extensionLength;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert already sent */
+ }
+ if (extensionLength != length) {
+ desc = decode_error;
+ goto alert_loser;
+ }
+ rv = ssl3_ParseExtensions(ss, &b, &length);
+ if (rv != SECSuccess) {
+ goto alert_loser; /* malformed */
+ }
+ }
+
+ /* Read supported_versions if present. */
+ rv = tls13_ClientReadSupportedVersion(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange));
+ /* Check that the version is within the configured range. */
+ if (ss->vrange.min > ss->version || ss->vrange.max < ss->version) {
+ desc = (ss->version > SSL_LIBRARY_VERSION_3_0)
+ ? protocol_version
+ : handshake_failure;
+ errCode = SSL_ERROR_UNSUPPORTED_VERSION;
+ goto alert_loser;
+ }
+
+ if (isHelloRetry && ss->ssl3.hs.helloRetry) {
+ SSL_TRC(3, ("%d: SSL3[%d]: received a second hello_retry_request",
+ SSL_GETPID(), ss->fd));
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST;
+ goto alert_loser;
+ }
+
+ /* There are three situations in which the server must pick
+ * TLS 1.3.
+ *
+ * 1. We received HRR
+ * 2. We sent early app data
+ * 3. ECH was accepted (checked in MaybeHandleEchSignal)
+ *
+ * If we offered ECH and the server negotiated a lower version,
+ * authenticate to the public name for secure disablement.
+ *
+ */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ if (isHelloRetry || ss->ssl3.hs.helloRetry) {
+ /* SSL3_SendAlert() will uncache the SID. */
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ goto alert_loser;
+ }
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+ /* SSL3_SendAlert() will uncache the SID. */
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA;
+ goto alert_loser;
+ }
+ }
+
+ /* Check that the server negotiated the same version as it did
+ * in the first handshake. This isn't really the best place for
+ * us to be getting this version number, but it's what we have.
+ * (1294697). */
+ if (ss->firstHsDone && (ss->version != ss->ssl3.crSpec->version)) {
+ desc = protocol_version;
+ errCode = SSL_ERROR_UNSUPPORTED_VERSION;
+ goto alert_loser;
+ }
+
+ if (ss->opt.enableHelloDowngradeCheck
+#ifdef DTLS_1_3_DRAFT_VERSION
+ /* Disable this check while we are on draft DTLS 1.3 versions. */
+ && !IS_DTLS(ss)
+#endif
+ ) {
+ rv = ssl_CheckServerRandom(ss);
+ if (rv != SECSuccess) {
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ goto alert_loser;
+ }
+ }
+
+ /* Finally, now all the version-related checks have passed. */
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
+ /* Update the write cipher spec to match the version. But not after
+ * HelloRetryRequest, because cwSpec might be a 0-RTT cipher spec,
+ * in which case this is a no-op. */
+ if (!ss->firstHsDone && !isHelloRetry) {
+ ssl_GetSpecWriteLock(ss);
+ ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
+ ssl_ReleaseSpecWriteLock(ss);
+ }
+
+ /* Check that the session ID is as expected. */
+ if (!ssl_CheckServerSessionIdCorrectness(ss, &sidBytes)) {
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ goto alert_loser;
+ }
+
+ /* Only initialize hashes if this isn't a Hello Retry. */
+ rv = ssl_ClientSetCipherSuite(ss, ss->version, cipher,
+ !isHelloRetry);
+ if (rv != SECSuccess) {
+ desc = illegal_parameter;
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+
+ dtls_ReceivedFirstMessageInFlight(ss);
+
+ if (isHelloRetry) {
+ rv = tls13_HandleHelloRetryRequest(ss, savedMsg, savedLength);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ return SECSuccess;
+ }
+
+ rv = ssl3_HandleParsedExtensions(ss, ssl_hs_server_hello);
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
+ savedMsg, savedLength);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = tls13_HandleServerHelloPart2(ss, savedMsg, savedLength);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+ } else {
+ rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode);
+ if (rv != SECSuccess)
+ goto loser;
+ }
+
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+
+loser:
+ /* Clean up the temporary pointer to the handshake buffer. */
+ ss->xtnData.signedCertTimestamps.len = 0;
+ ssl_MapLowLevelError(errCode);
+ return SECFailure;
+}
+
+static SECStatus
+ssl3_UnwrapMasterSecretClient(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
+{
+ PK11SlotInfo *slot;
+ PK11SymKey *wrapKey;
+ CK_FLAGS keyFlags = 0;
+ SECItem wrappedMS = {
+ siBuffer,
+ sid->u.ssl3.keys.wrapped_master_secret,
+ sid->u.ssl3.keys.wrapped_master_secret_len
+ };
+
+ /* unwrap master secret */
+ slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
+ sid->u.ssl3.masterSlotID);
+ if (slot == NULL) {
+ return SECFailure;
+ }
+ if (!PK11_IsPresent(slot)) {
+ PK11_FreeSlot(slot);
+ return SECFailure;
+ }
+ wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
+ sid->u.ssl3.masterWrapMech,
+ sid->u.ssl3.masterWrapSeries,
+ ss->pkcs11PinArg);
+ PK11_FreeSlot(slot);
+ if (wrapKey == NULL) {
+ return SECFailure;
+ }
+
+ if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
+ keyFlags = CKF_SIGN | CKF_VERIFY;
+ }
+
+ *ms = PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
+ NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
+ CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH, keyFlags);
+ PK11_FreeSymKey(wrapKey);
+ if (!*ms) {
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_HandleServerHelloPart2(sslSocket *ss, const SECItem *sidBytes,
+ int *retErrCode)
+{
+ SSL3AlertDescription desc = handshake_failure;
+ int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ SECStatus rv;
+ PRBool sid_match;
+ sslSessionID *sid = ss->sec.ci.sid;
+
+ if ((ss->opt.requireSafeNegotiation ||
+ (ss->firstHsDone && (ss->peerRequestedProtection ||
+ ss->opt.enableRenegotiation ==
+ SSL_RENEGOTIATE_REQUIRES_XTN))) &&
+ !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
+ desc = handshake_failure;
+ errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
+ : SSL_ERROR_UNSAFE_NEGOTIATION;
+ goto alert_loser;
+ }
+
+ /* Any errors after this point are not "malformed" errors. */
+ desc = handshake_failure;
+
+ /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
+ * key exchange algorithm. */
+ rv = ssl3_SetupBothPendingCipherSpecs(ss);
+ if (rv != SECSuccess) {
+ goto alert_loser; /* error code is set. */
+ }
+
+ /* We may or may not have sent a session id, we may get one back or
+ * not and if so it may match the one we sent.
+ * Attempt to restore the master secret to see if this is so...
+ * Don't consider failure to find a matching SID an error.
+ */
+ sid_match = (PRBool)(sidBytes->len > 0 &&
+ sidBytes->len ==
+ sid->u.ssl3.sessionIDLength &&
+ !PORT_Memcmp(sid->u.ssl3.sessionID,
+ sidBytes->data, sidBytes->len));
+
+ if (sid_match) {
+ if (sid->version != ss->version ||
+ sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
+ errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
+ goto alert_loser;
+ }
+ do {
+ PK11SymKey *masterSecret;
+
+ /* [draft-ietf-tls-session-hash-06; Section 5.3]
+ *
+ * o If the original session did not use the "extended_master_secret"
+ * extension but the new ServerHello contains the extension, the
+ * client MUST abort the handshake.
+ */
+ if (!sid->u.ssl3.keys.extendedMasterSecretUsed &&
+ ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
+ errCode = SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET;
+ goto alert_loser;
+ }
+
+ /*
+ * o If the original session used an extended master secret but the new
+ * ServerHello does not contain the "extended_master_secret"
+ * extension, the client SHOULD abort the handshake.
+ *
+ * TODO(ekr@rtfm.com): Add option to refuse to resume when EMS is not
+ * used at all (bug 1176526).
+ */
+ if (sid->u.ssl3.keys.extendedMasterSecretUsed &&
+ !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
+ errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
+ goto alert_loser;
+ }
+
+ ss->sec.authType = sid->authType;
+ ss->sec.authKeyBits = sid->authKeyBits;
+ ss->sec.keaType = sid->keaType;
+ ss->sec.keaKeyBits = sid->keaKeyBits;
+ ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
+ ss->sec.signatureScheme = sid->sigScheme;
+
+ rv = ssl3_UnwrapMasterSecretClient(ss, sid, &masterSecret);
+ if (rv != SECSuccess) {
+ break; /* not considered an error */
+ }
+
+ /* Got a Match */
+ SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_hits);
+
+ /* If we sent a session ticket, then this is a stateless resume. */
+ if (ss->xtnData.sentSessionTicketInClientHello)
+ SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_stateless_resumes);
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
+ ss->ssl3.hs.ws = wait_new_session_ticket;
+ else
+ ss->ssl3.hs.ws = wait_change_cipher;
+
+ ss->ssl3.hs.isResuming = PR_TRUE;
+
+ /* copy the peer cert from the SID */
+ if (sid->peerCert != NULL) {
+ ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
+ }
+
+ /* We are re-using the old MS, so no need to derive again. */
+ rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
+ if (rv != SECSuccess) {
+ goto alert_loser; /* err code was set */
+ }
+ return SECSuccess;
+ } while (0);
+ }
+
+ if (sid_match)
+ SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok);
+ else
+ SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses);
+
+ /* We tried to resume a 1.3 session but the server negotiated 1.2. */
+ if (ss->statelessResume) {
+ PORT_Assert(sid->version == SSL_LIBRARY_VERSION_TLS_1_3);
+ PORT_Assert(ss->ssl3.hs.currentSecret);
+
+ /* Reset resumption state, only used by 1.3 code. */
+ ss->statelessResume = PR_FALSE;
+
+ /* Clear TLS 1.3 early data traffic key. */
+ PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
+ ss->ssl3.hs.currentSecret = NULL;
+ }
+
+ /* throw the old one away */
+ sid->u.ssl3.keys.resumable = PR_FALSE;
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+
+ /* get a new sid */
+ ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
+ if (sid == NULL) {
+ goto alert_loser; /* memory error is set. */
+ }
+
+ sid->version = ss->version;
+ sid->u.ssl3.sessionIDLength = sidBytes->len;
+ if (sidBytes->len > 0) {
+ PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes->data, sidBytes->len);
+ }
+
+ sid->u.ssl3.keys.extendedMasterSecretUsed =
+ ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
+
+ /* Copy Signed Certificate Timestamps, if any. */
+ if (ss->xtnData.signedCertTimestamps.len) {
+ rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
+ &ss->xtnData.signedCertTimestamps);
+ ss->xtnData.signedCertTimestamps.len = 0;
+ if (rv != SECSuccess)
+ goto loser;
+ }
+
+ ss->ssl3.hs.isResuming = PR_FALSE;
+ if (ss->ssl3.hs.kea_def->authKeyType != ssl_auth_null) {
+ /* All current cipher suites other than those with ssl_auth_null (i.e.,
+ * (EC)DH_anon_* suites) require a certificate, so use that signal. */
+ ss->ssl3.hs.ws = wait_server_cert;
+ } else {
+ /* All the remaining cipher suites must be (EC)DH_anon_* and so
+ * must be ephemeral. Note, if we ever add PSK this might
+ * change. */
+ PORT_Assert(ss->ssl3.hs.kea_def->ephemeral);
+ ss->ssl3.hs.ws = wait_server_key;
+ }
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+
+loser:
+ *retErrCode = errCode;
+ return SECFailure;
+}
+
+static SECStatus
+ssl_HandleDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
+ SSL3AlertDescription desc = illegal_parameter;
+ SSLHashType hashAlg;
+ PRBool isTLS = ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0;
+ SSLSignatureScheme sigScheme;
+
+ SECItem dh_p = { siBuffer, NULL, 0 };
+ SECItem dh_g = { siBuffer, NULL, 0 };
+ SECItem dh_Ys = { siBuffer, NULL, 0 };
+ unsigned dh_p_bits;
+ unsigned dh_g_bits;
+ PRInt32 minDH = 0;
+ PRInt32 optval;
+
+ SSL3Hashes hashes;
+ SECItem signature = { siBuffer, NULL, 0 };
+ PLArenaPool *arena = NULL;
+ SECKEYPublicKey *peerKey = NULL;
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+ rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
+ if ((rv == SECSuccess) && (optval & NSS_KEY_SIZE_POLICY_SSL_FLAG)) {
+ (void)NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
+ }
+
+ if (minDH <= 0) {
+ minDH = SSL_DH_MIN_P_BITS;
+ }
+ dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p);
+ if (dh_p_bits < (unsigned)minDH) {
+ errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
+ goto alert_loser;
+ }
+ if (dh_p_bits > SSL_MAX_DH_KEY_BITS) {
+ errCode = SSL_ERROR_DH_KEY_TOO_LONG;
+ goto alert_loser;
+ }
+ rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+ /* Abort if dh_g is 0, 1, or obviously too big. */
+ dh_g_bits = SECKEY_BigIntegerBitLength(&dh_g);
+ if (dh_g_bits > dh_p_bits || dh_g_bits <= 1) {
+ goto alert_loser;
+ }
+ if (ss->opt.requireDHENamedGroups) {
+ /* If we're doing named groups, make sure it's good. */
+ rv = ssl_ValidateDHENamedGroup(ss, &dh_p, &dh_g, NULL, NULL);
+ if (rv != SECSuccess) {
+ errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
+ goto alert_loser;
+ }
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+ if (!ssl_IsValidDHEShare(&dh_p, &dh_Ys)) {
+ errCode = SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE;
+ goto alert_loser;
+ }
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+ if (rv != SECSuccess) {
+ goto loser; /* alert already sent */
+ }
+ rv = ssl_CheckSignatureSchemeConsistency(
+ ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
+ } else {
+ /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+ hashAlg = ssl_hash_none;
+ sigScheme = ssl_sig_none;
+ }
+ rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+ if (length != 0) {
+ if (isTLS) {
+ desc = decode_error;
+ }
+ goto alert_loser; /* malformed. */
+ }
+
+ PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
+ PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
+ PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
+
+ /* failures after this point are not malformed handshakes. */
+ /* TLS: send decrypt_error if signature failed. */
+ desc = isTLS ? decrypt_error : handshake_failure;
+
+ /*
+ * Check to make sure the hash is signed by right guy.
+ */
+ rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
+ dh_p, dh_g, dh_Ys, PR_FALSE /* padY */);
+ if (rv != SECSuccess) {
+ errCode =
+ ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ goto alert_loser;
+ }
+ rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
+ if (rv != SECSuccess) {
+ errCode =
+ ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ goto alert_loser;
+ }
+
+ /*
+ * we really need to build a new key here because we can no longer
+ * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
+ * pkcs11 slots and ID's.
+ */
+ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (arena == NULL) {
+ errCode = SEC_ERROR_NO_MEMORY;
+ goto loser;
+ }
+
+ peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
+ if (peerKey == NULL) {
+ errCode = SEC_ERROR_NO_MEMORY;
+ goto loser;
+ }
+
+ peerKey->arena = arena;
+ peerKey->keyType = dhKey;
+ peerKey->pkcs11Slot = NULL;
+ peerKey->pkcs11ID = CK_INVALID_HANDLE;
+
+ if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime, &dh_p) ||
+ SECITEM_CopyItem(arena, &peerKey->u.dh.base, &dh_g) ||
+ SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue, &dh_Ys)) {
+ errCode = SEC_ERROR_NO_MEMORY;
+ goto loser;
+ }
+ ss->sec.peerKey = peerKey;
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+loser:
+ if (arena) {
+ PORT_FreeArena(arena, PR_FALSE);
+ }
+ PORT_SetError(ssl_MapLowLevelError(errCode));
+ return SECFailure;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a
+ * complete ssl3 ServerKeyExchange message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->ssl3.hs.ws != wait_server_key) {
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
+ return SECFailure;
+ }
+
+ switch (ss->ssl3.hs.kea_def->exchKeyType) {
+ case ssl_kea_dh:
+ rv = ssl_HandleDHServerKeyExchange(ss, b, length);
+ break;
+
+ case ssl_kea_ecdh:
+ rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
+ break;
+
+ default:
+ SSL3_SendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
+ rv = SECFailure;
+ break;
+ }
+
+ if (rv == SECSuccess) {
+ ss->ssl3.hs.ws = wait_cert_request;
+ }
+ /* All Handle*ServerKeyExchange functions set the error code. */
+ return rv;
+}
+
+typedef struct dnameNode {
+ struct dnameNode *next;
+ SECItem name;
+} dnameNode;
+
+/*
+ * Parse the ca_list structure in a CertificateRequest.
+ *
+ * Called from:
+ * ssl3_HandleCertificateRequest
+ * tls13_HandleCertificateRequest
+ */
+SECStatus
+ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b, PRUint32 *length,
+ CERTDistNames *ca_list)
+{
+ PRUint32 remaining;
+ int nnames = 0;
+ dnameNode *node;
+ SECStatus rv;
+ int i;
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 2, b, length);
+ if (rv != SECSuccess)
+ return SECFailure; /* malformed, alert has been sent */
+
+ if (remaining > *length)
+ goto alert_loser;
+
+ ca_list->head = node = PORT_ArenaZNew(ca_list->arena, dnameNode);
+ if (node == NULL)
+ goto no_mem;
+
+ while (remaining > 0) {
+ PRUint32 len;
+
+ if (remaining < 2)
+ goto alert_loser; /* malformed */
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &len, 2, b, length);
+ if (rv != SECSuccess)
+ return SECFailure; /* malformed, alert has been sent */
+ if (len == 0 || remaining < len + 2)
+ goto alert_loser; /* malformed */
+
+ remaining -= 2;
+ if (SECITEM_MakeItem(ca_list->arena, &node->name, *b, len) != SECSuccess) {
+ goto no_mem;
+ }
+ node->name.len = len;
+ *b += len;
+ *length -= len;
+ remaining -= len;
+ nnames++;
+ if (remaining <= 0)
+ break; /* success */
+
+ node->next = PORT_ArenaZNew(ca_list->arena, dnameNode);
+ node = node->next;
+ if (node == NULL)
+ goto no_mem;
+ }
+
+ ca_list->nnames = nnames;
+ ca_list->names = PORT_ArenaNewArray(ca_list->arena, SECItem, nnames);
+ if (nnames > 0 && ca_list->names == NULL)
+ goto no_mem;
+
+ for (i = 0, node = (dnameNode *)ca_list->head;
+ i < nnames;
+ i++, node = node->next) {
+ ca_list->names[i] = node->name;
+ }
+
+ return SECSuccess;
+
+no_mem:
+ return SECFailure;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal,
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_0 ? illegal_parameter
+ : decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
+ return SECFailure;
+}
+
+SECStatus
+ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
+ SSLSignatureScheme **schemesOut,
+ unsigned int *numSchemesOut,
+ unsigned char **b, unsigned int *len)
+{
+ SECStatus rv;
+ SECItem buf;
+ SSLSignatureScheme *schemes = NULL;
+ unsigned int numSupported = 0;
+ unsigned int numRemaining = 0;
+ unsigned int max;
+
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* An odd-length value is invalid. */
+ if ((buf.len & 1) != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ return SECFailure;
+ }
+
+ /* Let the caller decide whether to alert here. */
+ if (buf.len == 0) {
+ goto done;
+ }
+
+ /* Limit the number of schemes we read. */
+ numRemaining = buf.len / 2;
+ max = PR_MIN(numRemaining, MAX_SIGNATURE_SCHEMES);
+
+ if (arena) {
+ schemes = PORT_ArenaZNewArray(arena, SSLSignatureScheme, max);
+ } else {
+ schemes = PORT_ZNewArray(SSLSignatureScheme, max);
+ }
+ if (!schemes) {
+ ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
+ return SECFailure;
+ }
+
+ for (; numRemaining && numSupported < MAX_SIGNATURE_SCHEMES; --numRemaining) {
+ PRUint32 tmp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &buf.data, &buf.len);
+ if (rv != SECSuccess) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ if (ssl_SignatureSchemeValid((SSLSignatureScheme)tmp, SEC_OID_UNKNOWN,
+ (PRBool)ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
+ ;
+ schemes[numSupported++] = (SSLSignatureScheme)tmp;
+ }
+ }
+
+ if (!numSupported) {
+ if (!arena) {
+ PORT_Free(schemes);
+ }
+ schemes = NULL;
+ }
+
+done:
+ *schemesOut = schemes;
+ *numSchemesOut = numSupported;
+ return SECSuccess;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 Certificate Request message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ PLArenaPool *arena = NULL;
+ PRBool isTLS = PR_FALSE;
+ PRBool isTLS12 = PR_FALSE;
+ int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
+ SECStatus rv;
+ SSL3AlertDescription desc = illegal_parameter;
+ SECItem cert_types = { siBuffer, NULL, 0 };
+ SSLSignatureScheme *signatureSchemes = NULL;
+ unsigned int signatureSchemeCount = 0;
+ CERTDistNames ca_list;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->ssl3.hs.ws != wait_cert_request) {
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
+ goto alert_loser;
+ }
+
+ PORT_Assert(ss->ssl3.clientCertChain == NULL);
+ PORT_Assert(ss->ssl3.clientCertificate == NULL);
+ PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
+
+ isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
+ isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+ rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
+ if (rv != SECSuccess)
+ goto loser; /* malformed, alert has been sent */
+
+ arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (arena == NULL)
+ goto no_mem;
+
+ if (isTLS12) {
+ rv = ssl_ParseSignatureSchemes(ss, arena,
+ &signatureSchemes,
+ &signatureSchemeCount,
+ &b, &length);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
+ goto loser; /* malformed, alert has been sent */
+ }
+ if (signatureSchemeCount == 0) {
+ errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+ }
+
+ rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, &ca_list);
+ if (rv != SECSuccess)
+ goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */
+
+ if (length != 0)
+ goto alert_loser; /* malformed */
+
+ ss->ssl3.hs.ws = wait_hello_done;
+
+ rv = ssl3_BeginHandleCertificateRequest(ss, signatureSchemes,
+ signatureSchemeCount, &ca_list);
+ if (rv != SECSuccess) {
+ PORT_Assert(0);
+ errCode = SEC_ERROR_LIBRARY_FAILURE;
+ desc = internal_error;
+ goto alert_loser;
+ }
+ goto done;
+
+no_mem:
+ rv = SECFailure;
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ goto done;
+
+alert_loser:
+ if (isTLS && desc == illegal_parameter)
+ desc = decode_error;
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+loser:
+ PORT_SetError(errCode);
+ rv = SECFailure;
+done:
+ if (arena != NULL)
+ PORT_FreeArena(arena, PR_FALSE);
+ return rv;
+}
+
+static void
+ssl3_ClientAuthCallbackOutcome(sslSocket *ss, SECStatus outcome)
+{
+ SECStatus rv;
+ switch (outcome) {
+ case SECSuccess:
+ /* check what the callback function returned */
+ if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
+ /* we are missing either the key or cert */
+ goto send_no_certificate;
+ }
+ /* Setting ssl3.clientCertChain non-NULL will cause
+ * ssl3_HandleServerHelloDone to call SendCertificate.
+ */
+ ss->ssl3.clientCertChain = CERT_CertChainFromCert(
+ ss->ssl3.clientCertificate,
+ certUsageSSLClient, PR_FALSE);
+ if (ss->ssl3.clientCertChain == NULL) {
+ goto send_no_certificate;
+ }
+ if (ss->ssl3.hs.hashType == handshake_hash_record ||
+ ss->ssl3.hs.hashType == handshake_hash_single) {
+ rv = ssl_PickClientSignatureScheme(ss,
+ ss->ssl3.clientCertificate,
+ ss->ssl3.clientPrivateKey,
+ ss->ssl3.hs.clientAuthSignatureSchemes,
+ ss->ssl3.hs.clientAuthSignatureSchemesLen,
+ &ss->ssl3.hs.signatureScheme);
+ if (rv != SECSuccess) {
+ /* This should only happen if our schemes changed or
+ * if an RSA-PSS cert was selected, but the token
+ * does not support PSS schemes.
+ */
+ goto send_no_certificate;
+ }
+ }
+ break;
+
+ case SECFailure:
+ default:
+ send_no_certificate:
+ CERT_DestroyCertificate(ss->ssl3.clientCertificate);
+ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
+ ss->ssl3.clientCertificate = NULL;
+ ss->ssl3.clientPrivateKey = NULL;
+ if (ss->ssl3.clientCertChain) {
+ CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
+ ss->ssl3.clientCertChain = NULL;
+ }
+
+ if (ss->version > SSL_LIBRARY_VERSION_3_0) {
+ ss->ssl3.sendEmptyCert = PR_TRUE;
+ } else {
+ (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
+ }
+ break;
+ }
+
+ /* Release the cached parameters */
+ PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
+ ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
+ ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
+}
+
+SECStatus
+ssl3_BeginHandleCertificateRequest(sslSocket *ss,
+ const SSLSignatureScheme *signatureSchemes,
+ unsigned int signatureSchemeCount,
+ CERTDistNames *ca_list)
+{
+ SECStatus rv;
+
+ PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
+
+ /* Should not send a client cert when (non-GREASE) ECH is rejected. */
+ if (ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
+ PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
+ rv = SECFailure;
+ } else if (ss->getClientAuthData != NULL) {
+ PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
+ ssl_preinfo_all);
+ PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
+ PORT_Assert(ss->ssl3.clientCertificate == NULL);
+ PORT_Assert(ss->ssl3.clientCertChain == NULL);
+
+ /* Previously cached parameters should be empty */
+ PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
+ PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
+ /*
+ * Peer signatures are only available while in the context of
+ * of a getClientAuthData callback. It is required for proper
+ * functioning of SSL_CertIsUsable and SSL_FilterClientCertListBySocket
+ * Calling these functions outside the context of a getClientAuthData
+ * callback will result in no filtering.*/
+
+ ss->ssl3.hs.clientAuthSignatureSchemes = PORT_ZNewArray(SSLSignatureScheme, signatureSchemeCount);
+ PORT_Memcpy(ss->ssl3.hs.clientAuthSignatureSchemes, signatureSchemes, signatureSchemeCount * sizeof(SSLSignatureScheme));
+ ss->ssl3.hs.clientAuthSignatureSchemesLen = signatureSchemeCount;
+
+ rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
+ ss->fd, ca_list,
+ &ss->ssl3.clientCertificate,
+ &ss->ssl3.clientPrivateKey);
+ } else {
+ rv = SECFailure; /* force it to send a no_certificate alert */
+ }
+
+ if (rv == SECWouldBlock) {
+ /* getClientAuthData needs more time (e.g. for user interaction) */
+
+ /* The out parameters should not have changed. */
+ PORT_Assert(ss->ssl3.clientCertificate == NULL);
+ PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
+
+ /* Mark the handshake as blocked */
+ ss->ssl3.hs.clientCertificatePending = PR_TRUE;
+
+ rv = SECSuccess;
+ } else {
+ /* getClientAuthData returned SECSuccess or SECFailure immediately, handle accordingly */
+ ssl3_ClientAuthCallbackOutcome(ss, rv);
+ rv = SECSuccess;
+ }
+ return rv;
+}
+
+/* Invoked by the application when client certificate selection is complete */
+SECStatus
+ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate)
+{
+ PORT_Assert(ss->ssl3.hs.clientCertificatePending);
+ ss->ssl3.hs.clientCertificatePending = PR_FALSE;
+
+ ss->ssl3.clientCertificate = clientCertificate;
+ ss->ssl3.clientPrivateKey = clientPrivateKey;
+
+ ssl3_ClientAuthCallbackOutcome(ss, outcome);
+
+ /* Continue the handshake */
+ PORT_Assert(ss->ssl3.hs.restartTarget);
+ if (!ss->ssl3.hs.restartTarget) {
+ FATAL_ERROR(ss, PR_INVALID_STATE_ERROR, internal_error);
+ return SECFailure;
+ }
+ sslRestartTarget target = ss->ssl3.hs.restartTarget;
+ ss->ssl3.hs.restartTarget = NULL;
+ return target(ss);
+}
+
+static SECStatus
+ssl3_CheckFalseStart(sslSocket *ss)
+{
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(!ss->ssl3.hs.authCertificatePending);
+ PORT_Assert(!ss->ssl3.hs.canFalseStart);
+
+ if (!ss->canFalseStartCallback) {
+ SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
+ SSL_GETPID(), ss->fd));
+ } else {
+ SECStatus rv;
+
+ rv = ssl_CheckServerRandom(ss);
+ if (rv != SECSuccess) {
+ SSL_TRC(3, ("%d: SSL[%d]: no false start due to possible downgrade",
+ SSL_GETPID(), ss->fd));
+ goto no_false_start;
+ }
+
+ /* An attacker can control the selected ciphersuite so we only wish to
+ * do False Start in the case that the selected ciphersuite is
+ * sufficiently strong that the attack can gain no advantage.
+ * Therefore we always require an 80-bit cipher. */
+ ssl_GetSpecReadLock(ss);
+ PRBool weakCipher = ss->ssl3.cwSpec->cipherDef->secret_key_size < 10;
+ ssl_ReleaseSpecReadLock(ss);
+ if (weakCipher) {
+ SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
+ SSL_GETPID(), ss->fd));
+ goto no_false_start;
+ }
+
+ if (ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
+ SSL_TRC(3, ("%d: SSL[%d]: no false start due to lower version after ECH",
+ SSL_GETPID(), ss->fd));
+ goto no_false_start;
+ }
+
+ PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
+ ssl_preinfo_all);
+ rv = (ss->canFalseStartCallback)(ss->fd,
+ ss->canFalseStartCallbackData,
+ &ss->ssl3.hs.canFalseStart);
+ if (rv == SECSuccess) {
+ SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
+ SSL_GETPID(), ss->fd,
+ ss->ssl3.hs.canFalseStart ? "TRUE"
+ : "FALSE"));
+ } else {
+ SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
+ SSL_GETPID(), ss->fd,
+ PR_ErrorToName(PR_GetError())));
+ }
+ return rv;
+ }
+
+no_false_start:
+ ss->ssl3.hs.canFalseStart = PR_FALSE;
+ return SECSuccess;
+}
+
+PRBool
+ssl3_WaitingForServerSecondRound(sslSocket *ss)
+{
+ PRBool result;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ switch (ss->ssl3.hs.ws) {
+ case wait_new_session_ticket:
+ case wait_change_cipher:
+ case wait_finished:
+ result = PR_TRUE;
+ break;
+ default:
+ result = PR_FALSE;
+ break;
+ }
+
+ return result;
+}
+
+static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 Server Hello Done message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleServerHelloDone(sslSocket *ss)
+{
+ SECStatus rv;
+ SSL3WaitState ws = ss->ssl3.hs.ws;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ /* Skipping CertificateRequest is always permitted. */
+ if (ws != wait_hello_done &&
+ ws != wait_cert_request) {
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
+ return SECFailure;
+ }
+
+ rv = ssl3_SendClientSecondRound(ss);
+
+ return rv;
+}
+
+/* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
+ *
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_SendClientSecondRound(sslSocket *ss)
+{
+ SECStatus rv;
+ PRBool sendClientCert;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ sendClientCert = !ss->ssl3.sendEmptyCert &&
+ ss->ssl3.clientCertChain != NULL &&
+ ss->ssl3.clientPrivateKey != NULL;
+
+ /* We must wait for the server's certificate to be authenticated before
+ * sending the client certificate in order to disclosing the client
+ * certificate to an attacker that does not have a valid cert for the
+ * domain we are connecting to.
+ *
+ * During the initial handshake on a connection, we never send/receive
+ * application data until we have authenticated the server's certificate;
+ * i.e. we have fully authenticated the handshake before using the cipher
+ * specs agreed upon for that handshake. During a renegotiation, we may
+ * continue sending and receiving application data during the handshake
+ * interleaved with the handshake records. If we were to send the client's
+ * second round for a renegotiation before the server's certificate was
+ * authenticated, then the application data sent/received after this point
+ * would be using cipher spec that hadn't been authenticated. By waiting
+ * until the server's certificate has been authenticated during
+ * renegotiations, we ensure that renegotiations have the same property
+ * as initial handshakes; i.e. we have fully authenticated the handshake
+ * before using the cipher specs agreed upon for that handshake for
+ * application data.
+ */
+ if (ss->ssl3.hs.restartTarget) {
+ PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ /* Check whether waiting for client certificate selection OR
+ waiting on server certificate verification AND
+ going to send client cert */
+ if ((ss->ssl3.hs.clientCertificatePending) ||
+ (ss->ssl3.hs.authCertificatePending && (sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone))) {
+ SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
+ " certificate authentication is still pending.",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+
+ ssl_GetXmitBufLock(ss); /*******************************/
+
+ if (ss->ssl3.sendEmptyCert) {
+ ss->ssl3.sendEmptyCert = PR_FALSE;
+ rv = ssl3_SendEmptyCertificate(ss);
+ /* Don't send verify */
+ if (rv != SECSuccess) {
+ goto loser; /* error code is set. */
+ }
+ } else if (sendClientCert) {
+ rv = ssl3_SendCertificate(ss);
+ if (rv != SECSuccess) {
+ goto loser; /* error code is set. */
+ }
+ }
+
+ rv = ssl3_SendClientKeyExchange(ss);
+ if (rv != SECSuccess) {
+ goto loser; /* err is set. */
+ }
+
+ if (sendClientCert) {
+ rv = ssl3_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
+ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
+ ss->ssl3.clientPrivateKey = NULL;
+ if (rv != SECSuccess) {
+ goto loser; /* err is set. */
+ }
+ }
+
+ rv = ssl3_SendChangeCipherSpecs(ss);
+ if (rv != SECSuccess) {
+ goto loser; /* err code was set. */
+ }
+
+ /* This must be done after we've set ss->ssl3.cwSpec in
+ * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
+ * from cwSpec. This must be done before we call ssl3_CheckFalseStart
+ * because the false start callback (if any) may need the information from
+ * the functions that depend on this being set.
+ */
+ ss->enoughFirstHsDone = PR_TRUE;
+
+ if (!ss->firstHsDone) {
+ if (ss->opt.enableFalseStart) {
+ if (!ss->ssl3.hs.authCertificatePending) {
+ /* When we fix bug 589047, we will need to know whether we are
+ * false starting before we try to flush the client second
+ * round to the network. With that in mind, we purposefully
+ * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
+ * which includes a call to ssl3_FlushHandshake, so that
+ * no application develops a reliance on such flushing being
+ * done before its false start callback is called.
+ */
+ ssl_ReleaseXmitBufLock(ss);
+ rv = ssl3_CheckFalseStart(ss);
+ ssl_GetXmitBufLock(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ /* The certificate authentication and the server's Finished
+ * message are racing each other. If the certificate
+ * authentication wins, then we will try to false start in
+ * ssl3_AuthCertificateComplete.
+ */
+ SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
+ " certificate authentication is still pending.",
+ SSL_GETPID(), ss->fd));
+ }
+ }
+ }
+
+ rv = ssl3_SendFinished(ss, 0);
+ if (rv != SECSuccess) {
+ goto loser; /* err code was set. */
+ }
+
+ ssl_ReleaseXmitBufLock(ss); /*******************************/
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
+ ss->ssl3.hs.ws = wait_new_session_ticket;
+ else
+ ss->ssl3.hs.ws = wait_change_cipher;
+
+ PORT_Assert(ssl3_WaitingForServerSecondRound(ss));
+
+ return SECSuccess;
+
+loser:
+ ssl_ReleaseXmitBufLock(ss);
+ return rv;
+}
+
+/*
+ * Routines used by servers
+ */
+static SECStatus
+ssl3_SendHelloRequest(sslSocket *ss)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
+ ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_hello_request, 0);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake */
+ }
+ rv = ssl3_FlushHandshake(ss, 0);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by ssl3_FlushHandshake */
+ }
+ ss->ssl3.hs.ws = wait_client_hello;
+ return SECSuccess;
+}
+
+/*
+ * Called from:
+ * ssl3_HandleClientHello()
+ */
+static SECComparison
+ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
+{
+ if (!name1 != !name2) {
+ return SECLessThan;
+ }
+ if (!name1) {
+ return SECEqual;
+ }
+ if (name1->type != name2->type) {
+ return SECLessThan;
+ }
+ return SECITEM_CompareItem(name1, name2);
+}
+
+/* Sets memory error when returning NULL.
+ * Called from:
+ * ssl3_SendClientHello()
+ * ssl3_HandleServerHello()
+ * ssl3_HandleClientHello()
+ * ssl3_HandleV2ClientHello()
+ */
+sslSessionID *
+ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
+{
+ sslSessionID *sid;
+
+ sid = PORT_ZNew(sslSessionID);
+ if (sid == NULL)
+ return sid;
+
+ if (is_server) {
+ const SECItem *srvName;
+ SECStatus rv = SECSuccess;
+
+ ssl_GetSpecReadLock(ss); /********************************/
+ srvName = &ss->ssl3.hs.srvVirtName;
+ if (srvName->len && srvName->data) {
+ rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
+ }
+ ssl_ReleaseSpecReadLock(ss); /************************************/
+ if (rv != SECSuccess) {
+ PORT_Free(sid);
+ return NULL;
+ }
+ }
+ sid->peerID = (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
+ sid->urlSvrName = (ss->url == NULL) ? NULL : PORT_Strdup(ss->url);
+ sid->addr = ss->sec.ci.peer;
+ sid->port = ss->sec.ci.port;
+ sid->references = 1;
+ sid->cached = never_cached;
+ sid->version = ss->version;
+ sid->sigScheme = ssl_sig_none;
+
+ sid->u.ssl3.keys.resumable = PR_TRUE;
+ sid->u.ssl3.policy = SSL_ALLOWED;
+ sid->u.ssl3.keys.extendedMasterSecretUsed = PR_FALSE;
+
+ if (is_server) {
+ SECStatus rv;
+ int pid = SSL_GETPID();
+
+ sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
+ sid->u.ssl3.sessionID[0] = (pid >> 8) & 0xff;
+ sid->u.ssl3.sessionID[1] = pid & 0xff;
+ rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
+ SSL3_SESSIONID_BYTES - 2);
+ if (rv != SECSuccess) {
+ ssl_FreeSID(sid);
+ ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
+ return NULL;
+ }
+ }
+ return sid;
+}
+
+/* Called from: ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
+static SECStatus
+ssl3_SendServerHelloSequence(sslSocket *ss)
+{
+ const ssl3KEADef *kea_def;
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ rv = ssl3_SendServerHello(ss);
+ if (rv != SECSuccess) {
+ return rv; /* err code is set. */
+ }
+ rv = ssl3_SendCertificate(ss);
+ if (rv != SECSuccess) {
+ return rv; /* error code is set. */
+ }
+ rv = ssl3_SendCertificateStatus(ss);
+ if (rv != SECSuccess) {
+ return rv; /* error code is set. */
+ }
+ /* We have to do this after the call to ssl3_SendServerHello,
+ * because kea_def is set up by ssl3_SendServerHello().
+ */
+ kea_def = ss->ssl3.hs.kea_def;
+
+ if (kea_def->ephemeral) {
+ rv = ssl3_SendServerKeyExchange(ss);
+ if (rv != SECSuccess) {
+ return rv; /* err code was set. */
+ }
+ }
+
+ if (ss->opt.requestCertificate) {
+ rv = ssl3_SendCertificateRequest(ss);
+ if (rv != SECSuccess) {
+ return rv; /* err code is set. */
+ }
+ }
+ rv = ssl3_SendServerHelloDone(ss);
+ if (rv != SECSuccess) {
+ return rv; /* err code is set. */
+ }
+
+ ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
+ : wait_client_key;
+ return SECSuccess;
+}
+
+/* An empty TLS Renegotiation Info (RI) extension */
+static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 };
+
+static PRBool
+ssl3_KEASupportsTickets(const ssl3KEADef *kea_def)
+{
+ if (kea_def->signKeyType == dsaKey) {
+ /* TODO: Fix session tickets for DSS. The server code rejects the
+ * session ticket received from the client. Bug 1174677 */
+ return PR_FALSE;
+ }
+ return PR_TRUE;
+}
+
+static PRBool
+ssl3_PeerSupportsCipherSuite(const SECItem *peerSuites, uint16_t suite)
+{
+ for (unsigned int i = 0; i + 1 < peerSuites->len; i += 2) {
+ PRUint16 suite_i = (peerSuites->data[i] << 8) | peerSuites->data[i + 1];
+ if (suite_i == suite) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+SECStatus
+ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
+ PRUint16 version, PRUint16 *suitep)
+{
+ unsigned int i;
+ SSLVersionRange vrange = { version, version };
+
+ /* If we negotiated an External PSK and that PSK has a ciphersuite
+ * configured, we need to constrain our choice. If the client does
+ * not support it, negotiate a certificate auth suite and fall back.
+ */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ ss->xtnData.selectedPsk &&
+ ss->xtnData.selectedPsk->type == ssl_psk_external &&
+ ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
+ PRUint16 pskSuite = ss->xtnData.selectedPsk->zeroRttSuite;
+ ssl3CipherSuiteCfg *pskSuiteCfg = ssl_LookupCipherSuiteCfgMutable(pskSuite,
+ ss->cipherSuites);
+ if (ssl3_config_match(pskSuiteCfg, ss->ssl3.policy, &vrange, ss) &&
+ ssl3_PeerSupportsCipherSuite(suites, pskSuite)) {
+ *suitep = pskSuite;
+ return SECSuccess;
+ }
+ }
+
+ for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
+ if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
+ continue;
+ }
+ if (!ssl3_PeerSupportsCipherSuite(suites, suite->cipher_suite)) {
+ continue;
+ }
+ *suitep = suite->cipher_suite;
+ return SECSuccess;
+ }
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+}
+
+/* Select a cipher suite.
+**
+** NOTE: This suite selection algorithm should be the same as the one in
+** ssl3_HandleV2ClientHello().
+**
+** If TLS 1.0 is enabled, we could handle the case where the client
+** offered TLS 1.1 but offered only export cipher suites by choosing TLS
+** 1.0 and selecting one of those export cipher suites. However, a secure
+** TLS 1.1 client should not have export cipher suites enabled at all,
+** and a TLS 1.1 client should definitely not be offering *only* export
+** cipher suites. Therefore, we refuse to negotiate export cipher suites
+** with any client that indicates support for TLS 1.1 or higher when we
+** (the server) have TLS 1.1 support enabled.
+*/
+SECStatus
+ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
+ PRBool initHashes)
+{
+ PRUint16 selected;
+ SECStatus rv;
+
+ /* Ensure that only valid cipher suites are enabled. */
+ if (ssl3_config_match_init(ss) == 0) {
+ /* No configured cipher is both supported by PK11 and allowed.
+ * This is a configuration error, so report handshake failure.*/
+ FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
+ return SECFailure;
+ }
+
+ rv = ssl3_NegotiateCipherSuiteInner(ss, suites, ss->version, &selected);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.cipher_suite = selected;
+ return ssl3_SetupCipherSuite(ss, initHashes);
+}
+
+/*
+ * Call the SNI config hook.
+ *
+ * Called from:
+ * ssl3_HandleClientHello
+ * tls13_HandleClientHelloPart2
+ */
+SECStatus
+ssl3_ServerCallSNICallback(sslSocket *ss)
+{
+ int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ SSL3AlertDescription desc = illegal_parameter;
+ int ret = 0;
+
+#ifdef SSL_SNI_ALLOW_NAME_CHANGE_2HS
+#error("No longer allowed to set SSL_SNI_ALLOW_NAME_CHANGE_2HS")
+#endif
+ if (!ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
+ if (ss->firstHsDone) {
+ /* Check that we don't have the name is current spec
+ * if this extension was not negotiated on the 2d hs. */
+ PRBool passed = PR_TRUE;
+ ssl_GetSpecReadLock(ss); /*******************************/
+ if (ss->ssl3.hs.srvVirtName.data) {
+ passed = PR_FALSE;
+ }
+ ssl_ReleaseSpecReadLock(ss); /***************************/
+ if (!passed) {
+ errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+ }
+ return SECSuccess;
+ }
+
+ if (ss->sniSocketConfig)
+ do { /* not a loop */
+ PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
+ ssl_preinfo_all);
+
+ ret = SSL_SNI_SEND_ALERT;
+ /* If extension is negotiated, the len of names should > 0. */
+ if (ss->xtnData.sniNameArrSize) {
+ /* Calling client callback to reconfigure the socket. */
+ ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
+ ss->xtnData.sniNameArr,
+ ss->xtnData.sniNameArrSize,
+ ss->sniSocketConfigArg);
+ }
+ if (ret <= SSL_SNI_SEND_ALERT) {
+ /* Application does not know the name or was not able to
+ * properly reconfigure the socket. */
+ errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
+ desc = unrecognized_name;
+ break;
+ } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
+ SECStatus rv = SECSuccess;
+ SECItem pwsNameBuf = { 0, NULL, 0 };
+ SECItem *pwsName = &pwsNameBuf;
+ SECItem *cwsName;
+
+ ssl_GetSpecWriteLock(ss); /*******************************/
+ cwsName = &ss->ssl3.hs.srvVirtName;
+ /* not allow name change on the 2d HS */
+ if (ss->firstHsDone) {
+ if (ssl3_ServerNameCompare(pwsName, cwsName)) {
+ ssl_ReleaseSpecWriteLock(ss); /******************/
+ errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
+ desc = handshake_failure;
+ ret = SSL_SNI_SEND_ALERT;
+ break;
+ }
+ }
+ if (pwsName->data) {
+ SECITEM_FreeItem(pwsName, PR_FALSE);
+ }
+ if (cwsName->data) {
+ rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
+ }
+ ssl_ReleaseSpecWriteLock(ss); /**************************/
+ if (rv != SECSuccess) {
+ errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
+ desc = internal_error;
+ ret = SSL_SNI_SEND_ALERT;
+ break;
+ }
+ } else if ((unsigned int)ret < ss->xtnData.sniNameArrSize) {
+ /* Application has configured new socket info. Lets check it
+ * and save the name. */
+ SECStatus rv;
+ SECItem *name = &ss->xtnData.sniNameArr[ret];
+ SECItem *pwsName;
+
+ /* get rid of the old name and save the newly picked. */
+ /* This code is protected by ssl3HandshakeLock. */
+ ssl_GetSpecWriteLock(ss); /*******************************/
+ /* not allow name change on the 2d HS */
+ if (ss->firstHsDone) {
+ SECItem *cwsName = &ss->ssl3.hs.srvVirtName;
+ if (ssl3_ServerNameCompare(name, cwsName)) {
+ ssl_ReleaseSpecWriteLock(ss); /******************/
+ errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
+ desc = handshake_failure;
+ ret = SSL_SNI_SEND_ALERT;
+ break;
+ }
+ }
+ pwsName = &ss->ssl3.hs.srvVirtName;
+ if (pwsName->data) {
+ SECITEM_FreeItem(pwsName, PR_FALSE);
+ }
+ rv = SECITEM_CopyItem(NULL, pwsName, name);
+ ssl_ReleaseSpecWriteLock(ss); /***************************/
+ if (rv != SECSuccess) {
+ errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
+ desc = internal_error;
+ ret = SSL_SNI_SEND_ALERT;
+ break;
+ }
+ /* Need to tell the client that application has picked
+ * the name from the offered list and reconfigured the socket.
+ */
+ ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_server_name_xtn,
+ ssl_SendEmptyExtension);
+ } else {
+ /* Callback returned index outside of the boundary. */
+ PORT_Assert((unsigned int)ret < ss->xtnData.sniNameArrSize);
+ errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
+ desc = internal_error;
+ ret = SSL_SNI_SEND_ALERT;
+ break;
+ }
+ } while (0);
+ ssl3_FreeSniNameArray(&ss->xtnData);
+ if (ret <= SSL_SNI_SEND_ALERT) {
+ /* desc and errCode should be set. */
+ goto alert_loser;
+ }
+
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+ PORT_SetError(errCode);
+ return SECFailure;
+}
+
+SECStatus
+ssl3_SelectServerCert(sslSocket *ss)
+{
+ const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
+ PRCList *cursor;
+ SECStatus rv;
+
+ /* If the client didn't include the supported groups extension, assume just
+ * P-256 support and disable all the other ECDHE groups. This also affects
+ * ECDHE group selection, but this function is called first. */
+ if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
+ unsigned int i;
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ss->namedGroupPreferences[i] &&
+ ss->namedGroupPreferences[i]->keaType == ssl_kea_ecdh &&
+ ss->namedGroupPreferences[i]->name != ssl_grp_ec_secp256r1) {
+ ss->namedGroupPreferences[i] = NULL;
+ }
+ }
+ }
+
+ /* This picks the first certificate that has:
+ * a) the right authentication method, and
+ * b) the right named curve (EC only)
+ *
+ * We might want to do some sort of ranking here later. For now, it's all
+ * based on what order they are configured in. */
+ for (cursor = PR_NEXT_LINK(&ss->serverCerts);
+ cursor != &ss->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *cert = (sslServerCert *)cursor;
+ if (kea_def->authKeyType == ssl_auth_rsa_sign) {
+ /* We consider PSS certificates here as well for TLS 1.2. */
+ if (!SSL_CERT_IS(cert, ssl_auth_rsa_sign) &&
+ (!SSL_CERT_IS(cert, ssl_auth_rsa_pss) ||
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_2)) {
+ continue;
+ }
+ } else {
+ if (!SSL_CERT_IS(cert, kea_def->authKeyType)) {
+ continue;
+ }
+ if (SSL_CERT_IS_EC(cert) &&
+ !ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
+ continue;
+ }
+ }
+
+ /* Found one. */
+ ss->sec.serverCert = cert;
+ ss->sec.authKeyBits = cert->serverKeyBits;
+
+ /* Don't pick a signature scheme if we aren't going to use it. */
+ if (kea_def->signKeyType == nullKey) {
+ ss->sec.authType = kea_def->authKeyType;
+ return SECSuccess;
+ }
+
+ rv = ssl3_PickServerSignatureScheme(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ ss->sec.authType =
+ ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
+ return SECSuccess;
+ }
+
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+}
+
+static SECStatus
+ssl_GenerateServerRandom(sslSocket *ss)
+{
+ SECStatus rv;
+ PRUint8 *downgradeSentinel;
+
+ rv = ssl3_GetNewRandom(ss->ssl3.hs.server_random);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->version == ss->vrange.max) {
+ return SECSuccess;
+ }
+#ifdef DTLS_1_3_DRAFT_VERSION
+ if (IS_DTLS(ss)) {
+ return SECSuccess;
+ }
+#endif
+
+ /*
+ * [RFC 8446 Section 4.1.3].
+ *
+ * TLS 1.3 servers which negotiate TLS 1.2 or below in response to a
+ * ClientHello MUST set the last 8 bytes of their Random value specially in
+ * their ServerHello.
+ *
+ * If negotiating TLS 1.2, TLS 1.3 servers MUST set the last 8 bytes of
+ * their Random value to the bytes:
+ *
+ * 44 4F 57 4E 47 52 44 01
+ *
+ * If negotiating TLS 1.1 or below, TLS 1.3 servers MUST, and TLS 1.2
+ * servers SHOULD, set the last 8 bytes of their ServerHello.Random value to
+ * the bytes:
+ *
+ * 44 4F 57 4E 47 52 44 00
+ */
+ downgradeSentinel =
+ ss->ssl3.hs.server_random +
+ SSL3_RANDOM_LENGTH - sizeof(tls12_downgrade_random);
+ if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ switch (ss->version) {
+ case SSL_LIBRARY_VERSION_TLS_1_2:
+ /* vrange.max > 1.2, since we didn't early exit above. */
+ PORT_Memcpy(downgradeSentinel,
+ tls12_downgrade_random, sizeof(tls12_downgrade_random));
+ break;
+ case SSL_LIBRARY_VERSION_TLS_1_1:
+ case SSL_LIBRARY_VERSION_TLS_1_0:
+ PORT_Memcpy(downgradeSentinel,
+ tls1_downgrade_random, sizeof(tls1_downgrade_random));
+ break;
+ default:
+ /* Do not change random. */
+ break;
+ }
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
+ SECItem *cookieBytes, SECItem *suites, SECItem *comps)
+{
+ SECStatus rv;
+ PRUint32 tmp;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &tmp, 2, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* malformed, alert already sent */
+ }
+
+ /* Translate the version. */
+ if (IS_DTLS(ss)) {
+ ss->clientHelloVersion = dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
+ } else {
+ ss->clientHelloVersion = (SSL3ProtocolVersion)tmp;
+ }
+
+ /* Grab the client random data. */
+ rv = ssl3_ConsumeHandshake(
+ ss, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* malformed */
+ }
+
+ /* Grab the client's SID, if present. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, sidBytes, 1, b, length);
+ /* Check that the SID has the format: opaque legacy_session_id<0..32>, as
+ * specified in RFC8446, Section 4.1.2. */
+ if (rv != SECSuccess || sidBytes->len > SSL3_SESSIONID_BYTES) {
+ return SECFailure; /* malformed */
+ }
+
+ /* Grab the client's cookie, if present. It is checked after version negotiation. */
+ if (IS_DTLS(ss)) {
+ rv = ssl3_ConsumeHandshakeVariable(ss, cookieBytes, 1, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* malformed */
+ }
+ }
+
+ /* Grab the list of cipher suites. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, suites, 2, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* malformed */
+ }
+
+ /* Grab the list of compression methods. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, comps, 1, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* malformed */
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_ValidatePreambleWithVersion(sslSocket *ss, const SECItem *sidBytes, const SECItem *comps,
+ const SECItem *cookieBytes)
+{
+ SECStatus rv;
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ if (sidBytes->len > 0 && !IS_DTLS(ss)) {
+ SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
+ rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.fakeSid, sidBytes);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+ }
+
+ /* TLS 1.3 requires that compression include only null. */
+ if (comps->len != 1 || comps->data[0] != ssl_compression_null) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* receivedCcs is only valid if we sent an HRR. */
+ if (ss->ssl3.hs.receivedCcs && !ss->ssl3.hs.helloRetry) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
+ return SECFailure;
+ }
+
+ /* A DTLS 1.3-only client MUST set the legacy_cookie field to zero length.
+ * If a DTLS 1.3 ClientHello is received with any other value in this field,
+ * the server MUST abort the handshake with an "illegal_parameter" alert. */
+ if (IS_DTLS(ss) && cookieBytes->len != 0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ } else {
+ /* ECH not possible here. */
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
+
+ /* HRR and ECH are TLS1.3-only. We ignore the Cookie extension here. */
+ if (ss->ssl3.hs.helloRetry) {
+ FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
+ return SECFailure;
+ }
+
+ /* receivedCcs is only valid if we sent an HRR. */
+ if (ss->ssl3.hs.receivedCcs) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER, unexpected_message);
+ return SECFailure;
+ }
+
+ /* TLS versions prior to 1.3 must include null somewhere. */
+ if (comps->len < 1 ||
+ !memchr(comps->data, ssl_compression_null, comps->len)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* We never send cookies in DTLS 1.2. */
+ if (IS_DTLS(ss) && cookieBytes->len != 0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ }
+
+ return SECSuccess;
+}
+
+/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
+ * ssl3 Client Hello message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleClientHello(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ sslSessionID *sid = NULL;
+ unsigned int i;
+ SECStatus rv;
+ PRUint32 extensionLength;
+ int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ SSL3AlertDescription desc = illegal_parameter;
+ SSL3AlertLevel level = alert_fatal;
+ TLSExtension *versionExtension;
+ SECItem sidBytes = { siBuffer, NULL, 0 };
+ SECItem cookieBytes = { siBuffer, NULL, 0 };
+ SECItem suites = { siBuffer, NULL, 0 };
+ SECItem comps = { siBuffer, NULL, 0 };
+ SECItem *echInner = NULL;
+ PRBool isTLS13;
+ const PRUint8 *savedMsg = b;
+ const PRUint32 savedLen = length;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ ss->ssl3.hs.preliminaryInfo = 0;
+
+ if (!ss->sec.isServer ||
+ (ss->ssl3.hs.ws != wait_client_hello &&
+ ss->ssl3.hs.ws != idle_handshake)) {
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
+ goto alert_loser;
+ }
+ if (ss->ssl3.hs.ws == idle_handshake) {
+ /* Refuse re-handshake when we have already negotiated TLS 1.3. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
+ goto alert_loser;
+ }
+ if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
+ desc = no_renegotiation;
+ level = alert_warning;
+ errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
+ goto alert_loser;
+ }
+ }
+
+ /* We should always be in a fresh state. */
+ SSL_ASSERT_HASHES_EMPTY(ss);
+
+ /* Get peer name of client */
+ rv = ssl_GetPeerInfo(ss);
+ if (rv != SECSuccess) {
+ return rv; /* error code is set. */
+ }
+
+ /* We might be starting session renegotiation in which case we should
+ * clear previous state.
+ */
+ ssl3_ResetExtensionData(&ss->xtnData, ss);
+ ss->statelessResume = PR_FALSE;
+
+ if (IS_DTLS(ss)) {
+ dtls_RehandshakeCleanup(ss);
+ }
+
+ rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &sidBytes,
+ &cookieBytes, &suites, &comps);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed */
+ }
+
+ /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
+ * we are restarting a previous session until extensions have been
+ * parsed, since we might have received a SessionTicket extension.
+ * Note: we allow extensions even when negotiating SSL3 for the sake
+ * of interoperability (and backwards compatibility).
+ */
+ if (length) {
+ /* Get length of hello extensions */
+ rv = ssl3_ConsumeHandshakeNumber(ss, &extensionLength, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* alert already sent */
+ }
+ if (extensionLength != length) {
+ errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ desc = decode_error;
+ goto alert_loser;
+ }
+
+ rv = ssl3_ParseExtensions(ss, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed */
+ }
+ }
+
+ versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
+ if (versionExtension) {
+ rv = tls13_NegotiateVersion(ss, versionExtension);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = (errCode == SSL_ERROR_UNSUPPORTED_VERSION) ? protocol_version : illegal_parameter;
+ goto alert_loser;
+ }
+ } else {
+ /* The PR_MIN here ensures that we never negotiate 1.3 if the
+ * peer didn't offer "supported_versions". */
+ rv = ssl3_NegotiateVersion(ss,
+ PR_MIN(ss->clientHelloVersion,
+ SSL_LIBRARY_VERSION_TLS_1_2),
+ PR_TRUE);
+ /* Send protocol version alert if the ClientHello.legacy_version is not
+ * supported by the server.
+ *
+ * If the "supported_versions" extension is absent and the server only
+ * supports versions greater than ClientHello.legacy_version, the
+ * server MUST abort the handshake with a "protocol_version" alert
+ * [RFC8446, Appendix D.2]. */
+ if (rv != SECSuccess) {
+ desc = protocol_version;
+ errCode = SSL_ERROR_UNSUPPORTED_VERSION;
+ goto alert_loser;
+ }
+ }
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
+
+ /* Update the write spec to match the selected version. */
+ if (!ss->firstHsDone) {
+ ssl_GetSpecWriteLock(ss);
+ ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
+ ssl_ReleaseSpecWriteLock(ss);
+ }
+
+ isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
+ if (isTLS13) {
+ if (ss->firstHsDone) {
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
+ goto alert_loser;
+ }
+
+ /* If there is a cookie, then this is a second ClientHello (TLS 1.3). */
+ if (ssl3_FindExtension(ss, ssl_tls13_cookie_xtn)) {
+ ss->ssl3.hs.helloRetry = PR_TRUE;
+ }
+
+ rv = tls13_MaybeHandleEch(ss, savedMsg, savedLen, &sidBytes,
+ &comps, &cookieBytes, &suites, &echInner);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser; /* code set, alert sent. */
+ }
+ }
+
+ rv = ssl3_ValidatePreambleWithVersion(ss, &sidBytes, &comps, &cookieBytes);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser; /* code set, alert sent. */
+ }
+
+ /* Now parse the rest of the extensions. */
+ rv = ssl3_HandleParsedExtensions(ss, ssl_hs_client_hello);
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+ if (rv != SECSuccess) {
+ if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
+ errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
+ }
+ goto loser; /* malformed */
+ }
+
+ /* If the ClientHello version is less than our maximum version, check for a
+ * TLS_FALLBACK_SCSV and reject the connection if found. */
+ if (ss->vrange.max > ss->version) {
+ for (i = 0; i + 1 < suites.len; i += 2) {
+ PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
+ if (suite_i != TLS_FALLBACK_SCSV)
+ continue;
+ desc = inappropriate_fallback;
+ errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
+ goto alert_loser;
+ }
+ }
+
+ if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
+ /* If we didn't receive an RI extension, look for the SCSV,
+ * and if found, treat it just like an empty RI extension
+ * by processing a local copy of an empty RI extension.
+ */
+ for (i = 0; i + 1 < suites.len; i += 2) {
+ PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
+ if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
+ PRUint8 *b2 = (PRUint8 *)emptyRIext;
+ PRUint32 L2 = sizeof emptyRIext;
+ (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
+ break;
+ }
+ }
+ }
+
+ /* The check for renegotiation in TLS 1.3 is earlier. */
+ if (!isTLS13) {
+ if (ss->firstHsDone &&
+ (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
+ ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
+ !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
+ desc = no_renegotiation;
+ level = alert_warning;
+ errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
+ goto alert_loser;
+ }
+ if ((ss->opt.requireSafeNegotiation ||
+ (ss->firstHsDone && ss->peerRequestedProtection)) &&
+ !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
+ desc = handshake_failure;
+ errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
+ goto alert_loser;
+ }
+ }
+
+ /* We do stateful resumes only if we are in TLS < 1.3 and
+ * either of the following conditions are satisfied:
+ * (1) the client does not support the session ticket extension, or
+ * (2) the client support the session ticket extension, but sent an
+ * empty ticket.
+ */
+ if (!isTLS13 &&
+ (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
+ ss->xtnData.emptySessionTicket)) {
+ if (sidBytes.len > 0 && !ss->opt.noCache) {
+ SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
+ SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
+ ss->sec.ci.peer.pr_s6_addr32[1],
+ ss->sec.ci.peer.pr_s6_addr32[2],
+ ss->sec.ci.peer.pr_s6_addr32[3]));
+ if (ssl_sid_lookup) {
+ sid = (*ssl_sid_lookup)(ssl_Time(ss), &ss->sec.ci.peer,
+ sidBytes.data, sidBytes.len, ss->dbHandle);
+ } else {
+ errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
+ goto loser;
+ }
+ }
+ } else if (ss->statelessResume) {
+ /* Fill in the client's session ID if doing a stateless resume.
+ * (When doing stateless resumes, server echos client's SessionID.)
+ * This branch also handles TLS 1.3 resumption-PSK.
+ */
+ sid = ss->sec.ci.sid;
+ PORT_Assert(sid != NULL); /* Should have already been filled in.*/
+
+ if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
+ sid->u.ssl3.sessionIDLength = sidBytes.len;
+ PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
+ sidBytes.len);
+ sid->u.ssl3.sessionIDLength = sidBytes.len;
+ } else {
+ sid->u.ssl3.sessionIDLength = 0;
+ }
+ ss->sec.ci.sid = NULL;
+ }
+
+ /* Free a potentially leftover session ID from a previous handshake. */
+ if (ss->sec.ci.sid) {
+ ssl_FreeSID(ss->sec.ci.sid);
+ ss->sec.ci.sid = NULL;
+ }
+
+ if (sid != NULL) {
+ /* We've found a session cache entry for this client.
+ * Now, if we're going to require a client-auth cert,
+ * and we don't already have this client's cert in the session cache,
+ * and this is the first handshake on this connection (not a redo),
+ * then drop this old cache entry and start a new session.
+ */
+ if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
+ ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
+ (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
+ ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE) &&
+ !ss->firstHsDone))) {
+
+ SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
+ ssl_FreeSID(sid);
+ sid = NULL;
+ ss->statelessResume = PR_FALSE;
+ }
+ }
+
+ if (IS_DTLS(ss)) {
+ ssl3_DisableNonDTLSSuites(ss);
+ dtls_ReceivedFirstMessageInFlight(ss);
+ }
+
+ if (isTLS13) {
+ rv = tls13_HandleClientHelloPart2(ss, &suites, sid,
+ ss->ssl3.hs.echAccepted ? echInner->data : savedMsg,
+ ss->ssl3.hs.echAccepted ? echInner->len : savedLen);
+ SECITEM_FreeItem(echInner, PR_TRUE);
+ echInner = NULL;
+ } else {
+ rv = ssl3_HandleClientHelloPart2(ss, &suites, sid,
+ savedMsg, savedLen);
+ }
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, level, desc);
+/* FALLTHRU */
+loser:
+ SECITEM_FreeItem(echInner, PR_TRUE);
+ PORT_SetError(errCode);
+ return SECFailure;
+}
+
+/* unwrap helper function to handle the case where the wrapKey doesn't wind
+ * up in the correct token for the master secret */
+PK11SymKey *
+ssl_unwrapSymKey(PK11SymKey *wrapKey,
+ CK_MECHANISM_TYPE wrapType, SECItem *param,
+ SECItem *wrappedKey,
+ CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
+ int keySize, CK_FLAGS keyFlags, void *pinArg)
+{
+ PK11SymKey *unwrappedKey;
+
+ /* unwrap the master secret. */
+ unwrappedKey = PK11_UnwrapSymKeyWithFlags(wrapKey, wrapType, param,
+ wrappedKey, target, operation, keySize,
+ keyFlags);
+ if (!unwrappedKey) {
+ PK11SlotInfo *targetSlot = PK11_GetBestSlot(target, pinArg);
+ PK11SymKey *newWrapKey;
+
+ /* it's possible that we failed to unwrap because the wrapKey is in
+ * a slot that can't handle target. Move the wrapKey to a slot that
+ * can handle this mechanism and retry the operation */
+ if (targetSlot == NULL) {
+ return NULL;
+ }
+ newWrapKey = PK11_MoveSymKey(targetSlot, CKA_UNWRAP, 0,
+ PR_FALSE, wrapKey);
+ PK11_FreeSlot(targetSlot);
+ if (newWrapKey == NULL) {
+ return NULL;
+ }
+ unwrappedKey = PK11_UnwrapSymKeyWithFlags(newWrapKey, wrapType, param,
+ wrappedKey, target, operation, keySize,
+ keyFlags);
+ PK11_FreeSymKey(newWrapKey);
+ }
+ return unwrappedKey;
+}
+
+static SECStatus
+ssl3_UnwrapMasterSecretServer(sslSocket *ss, sslSessionID *sid, PK11SymKey **ms)
+{
+ PK11SymKey *wrapKey;
+ CK_FLAGS keyFlags = 0;
+ SECItem wrappedMS = {
+ siBuffer,
+ sid->u.ssl3.keys.wrapped_master_secret,
+ sid->u.ssl3.keys.wrapped_master_secret_len
+ };
+
+ wrapKey = ssl3_GetWrappingKey(ss, NULL, sid->u.ssl3.masterWrapMech,
+ ss->pkcs11PinArg);
+ if (!wrapKey) {
+ return SECFailure;
+ }
+
+ if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
+ keyFlags = CKF_SIGN | CKF_VERIFY;
+ }
+
+ *ms = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech, NULL,
+ &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
+ CKA_DERIVE, SSL3_MASTER_SECRET_LENGTH,
+ keyFlags, ss->pkcs11PinArg);
+ PK11_FreeSymKey(wrapKey);
+ if (!*ms) {
+ SSL_TRC(10, ("%d: SSL3[%d]: server wrapping key found, but couldn't unwrap MasterSecret. wrapMech=0x%0lx",
+ SSL_GETPID(), ss->fd, sid->u.ssl3.masterWrapMech));
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_HandleClientHelloPart2(sslSocket *ss,
+ SECItem *suites,
+ sslSessionID *sid,
+ const PRUint8 *msg,
+ unsigned int len)
+{
+ PRBool haveXmitBufLock = PR_FALSE;
+ int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ SSL3AlertDescription desc = illegal_parameter;
+ SECStatus rv;
+ unsigned int i;
+ unsigned int j;
+
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
+ if (rv != SECSuccess) {
+ errCode = SEC_ERROR_LIBRARY_FAILURE;
+ desc = internal_error;
+ goto alert_loser;
+ }
+
+ /* If we already have a session for this client, be sure to pick the same
+ ** cipher suite we picked before. This is not a loop, despite appearances.
+ */
+ if (sid)
+ do {
+ ssl3CipherSuiteCfg *suite;
+ SSLVersionRange vrange = { ss->version, ss->version };
+
+ suite = ss->cipherSuites;
+ /* Find the entry for the cipher suite used in the cached session. */
+ for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
+ if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
+ break;
+ }
+ PORT_Assert(j > 0);
+ if (j == 0)
+ break;
+
+ /* Double check that the cached cipher suite is still enabled,
+ * implemented, and allowed by policy. Might have been disabled.
+ */
+ if (ssl3_config_match_init(ss) == 0) {
+ desc = handshake_failure;
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+ if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss))
+ break;
+
+ /* Double check that the cached cipher suite is in the client's
+ * list. If it isn't, fall through and start a new session. */
+ for (i = 0; i + 1 < suites->len; i += 2) {
+ PRUint16 suite_i = (suites->data[i] << 8) | suites->data[i + 1];
+ if (suite_i == suite->cipher_suite) {
+ ss->ssl3.hs.cipher_suite = suite_i;
+ rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
+ if (rv != SECSuccess) {
+ desc = internal_error;
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+
+ goto cipher_found;
+ }
+ }
+ } while (0);
+ /* START A NEW SESSION */
+
+ rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE);
+ if (rv != SECSuccess) {
+ desc = handshake_failure;
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+
+cipher_found:
+ suites->data = NULL;
+
+ /* If there are any failures while processing the old sid,
+ * we don't consider them to be errors. Instead, We just behave
+ * as if the client had sent us no sid to begin with, and make a new one.
+ * The exception here is attempts to resume extended_master_secret
+ * sessions without the extension, which causes an alert.
+ */
+ if (sid != NULL)
+ do {
+ PK11SymKey *masterSecret;
+
+ if (sid->version != ss->version ||
+ sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
+ break; /* not an error */
+ }
+
+ /* server sids don't remember the server cert we previously sent,
+ ** but they do remember the slot we originally used, so we
+ ** can locate it again, provided that the current ssl socket
+ ** has had its server certs configured the same as the previous one.
+ */
+ ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
+ if (!ss->sec.serverCert || !ss->sec.serverCert->serverCert) {
+ /* A compatible certificate must not have been configured. It
+ * might not be the same certificate, but we only find that out
+ * when the ticket fails to decrypt. */
+ break;
+ }
+
+ /* [draft-ietf-tls-session-hash-06; Section 5.3]
+ * o If the original session did not use the "extended_master_secret"
+ * extension but the new ClientHello contains the extension, then the
+ * server MUST NOT perform the abbreviated handshake. Instead, it
+ * SHOULD continue with a full handshake (as described in
+ * Section 5.2) to negotiate a new session.
+ *
+ * o If the original session used the "extended_master_secret"
+ * extension but the new ClientHello does not contain the extension,
+ * the server MUST abort the abbreviated handshake.
+ */
+ if (ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)) {
+ if (!sid->u.ssl3.keys.extendedMasterSecretUsed) {
+ break; /* not an error */
+ }
+ } else {
+ if (sid->u.ssl3.keys.extendedMasterSecretUsed) {
+ /* Note: we do not destroy the session */
+ desc = handshake_failure;
+ errCode = SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET;
+ goto alert_loser;
+ }
+ }
+
+ if (ss->sec.ci.sid) {
+ ssl_UncacheSessionID(ss);
+ PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */
+ if (ss->sec.ci.sid != sid) {
+ ssl_FreeSID(ss->sec.ci.sid);
+ }
+ ss->sec.ci.sid = NULL;
+ }
+
+ /* we need to resurrect the master secret.... */
+ rv = ssl3_UnwrapMasterSecretServer(ss, sid, &masterSecret);
+ if (rv != SECSuccess) {
+ break; /* not an error */
+ }
+
+ ss->sec.ci.sid = sid;
+ if (sid->peerCert != NULL) {
+ ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
+ }
+
+ /*
+ * Old SID passed all tests, so resume this old session.
+ */
+ SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_hits);
+ if (ss->statelessResume)
+ SSL_AtomicIncrementLong(&ssl3stats.hch_sid_stateless_resumes);
+ ss->ssl3.hs.isResuming = PR_TRUE;
+
+ ss->sec.authType = sid->authType;
+ ss->sec.authKeyBits = sid->authKeyBits;
+ ss->sec.keaType = sid->keaType;
+ ss->sec.keaKeyBits = sid->keaKeyBits;
+ ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
+ ss->sec.signatureScheme = sid->sigScheme;
+
+ ss->sec.localCert =
+ CERT_DupCertificate(ss->sec.serverCert->serverCert);
+
+ /* Copy cached name in to pending spec */
+ if (sid != NULL &&
+ sid->version > SSL_LIBRARY_VERSION_3_0 &&
+ sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
+ /* Set server name from sid */
+ SECItem *sidName = &sid->u.ssl3.srvName;
+ SECItem *pwsName = &ss->ssl3.hs.srvVirtName;
+ if (pwsName->data) {
+ SECITEM_FreeItem(pwsName, PR_FALSE);
+ }
+ rv = SECITEM_CopyItem(NULL, pwsName, sidName);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = internal_error;
+ goto alert_loser;
+ }
+ }
+
+ /* Clean up sni name array */
+ ssl3_FreeSniNameArray(&ss->xtnData);
+
+ ssl_GetXmitBufLock(ss);
+ haveXmitBufLock = PR_TRUE;
+
+ rv = ssl3_SendServerHello(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ /* We are re-using the old MS, so no need to derive again. */
+ rv = ssl3_InitPendingCipherSpecs(ss, masterSecret, PR_FALSE);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ rv = ssl3_SendChangeCipherSpecs(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+ rv = ssl3_SendFinished(ss, 0);
+ ss->ssl3.hs.ws = wait_change_cipher;
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ if (haveXmitBufLock) {
+ ssl_ReleaseXmitBufLock(ss);
+ }
+
+ return SECSuccess;
+ } while (0);
+
+ if (sid) { /* we had a sid, but it's no longer valid, free it */
+ ss->statelessResume = PR_FALSE;
+ SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok);
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ sid = NULL;
+ }
+ SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
+
+ /* We only send a session ticket extension if the client supports
+ * the extension and we are unable to resume.
+ *
+ * TODO: send a session ticket if performing a stateful
+ * resumption. (As per RFC4507, a server may issue a session
+ * ticket while doing a (stateless or stateful) session resume,
+ * but OpenSSL-0.9.8g does not accept session tickets while
+ * resuming.)
+ */
+ if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
+ ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
+ ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_session_ticket_xtn,
+ ssl_SendEmptyExtension);
+ }
+
+ rv = ssl3_ServerCallSNICallback(ss);
+ if (rv != SECSuccess) {
+ /* The alert has already been sent. */
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ rv = ssl3_SelectServerCert(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+
+ sid = ssl3_NewSessionID(ss, PR_TRUE);
+ if (sid == NULL) {
+ errCode = PORT_GetError();
+ goto loser; /* memory error is set. */
+ }
+ ss->sec.ci.sid = sid;
+
+ sid->u.ssl3.keys.extendedMasterSecretUsed =
+ ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn);
+ ss->ssl3.hs.isResuming = PR_FALSE;
+
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_SendServerHelloSequence(ss);
+ ssl_ReleaseXmitBufLock(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+
+ if (haveXmitBufLock) {
+ ssl_ReleaseXmitBufLock(ss);
+ }
+
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+/* FALLTHRU */
+loser:
+ if (sid && sid != ss->sec.ci.sid) {
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ }
+
+ if (haveXmitBufLock) {
+ ssl_ReleaseXmitBufLock(ss);
+ }
+
+ PORT_SetError(errCode);
+ return SECFailure;
+}
+
+/*
+ * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
+ * in asking to use the V3 handshake.
+ */
+SECStatus
+ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, unsigned int length,
+ PRUint8 padding)
+{
+ sslSessionID *sid = NULL;
+ unsigned char *suites;
+ unsigned char *random;
+ SSL3ProtocolVersion version;
+ SECStatus rv;
+ unsigned int i;
+ unsigned int j;
+ unsigned int sid_length;
+ unsigned int suite_length;
+ unsigned int rand_length;
+ int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ SSL3AlertDescription desc = handshake_failure;
+ unsigned int total = SSL_HL_CLIENT_HELLO_HBYTES;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+
+ ssl_GetSSL3HandshakeLock(ss);
+
+ version = (buffer[1] << 8) | buffer[2];
+ if (version < SSL_LIBRARY_VERSION_3_0) {
+ goto loser;
+ }
+
+ ssl3_RestartHandshakeHashes(ss);
+
+ if (ss->ssl3.hs.ws != wait_client_hello) {
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
+ goto alert_loser;
+ }
+
+ total += suite_length = (buffer[3] << 8) | buffer[4];
+ total += sid_length = (buffer[5] << 8) | buffer[6];
+ total += rand_length = (buffer[7] << 8) | buffer[8];
+ total += padding;
+ ss->clientHelloVersion = version;
+
+ if (version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ /* [draft-ietf-tls-tls-11; C.3] forbids sending a TLS 1.3
+ * ClientHello using the backwards-compatible format. */
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ goto alert_loser;
+ }
+
+ rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
+ if (rv != SECSuccess) {
+ /* send back which ever alert client will understand. */
+ desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
+ : handshake_failure;
+ errCode = SSL_ERROR_UNSUPPORTED_VERSION;
+ goto alert_loser;
+ }
+ /* ECH not possible here. */
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version;
+ if (!ss->firstHsDone) {
+ ssl_GetSpecWriteLock(ss);
+ ssl_SetSpecVersions(ss, ss->ssl3.cwSpec);
+ ssl_ReleaseSpecWriteLock(ss);
+ }
+
+ /* if we get a non-zero SID, just ignore it. */
+ if (length != total) {
+ SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
+ SSL_GETPID(), ss->fd, length, total));
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ goto alert_loser;
+ }
+
+ suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
+ random = suites + suite_length + sid_length;
+
+ if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
+ rand_length > SSL_MAX_CHALLENGE_BYTES) {
+ desc = illegal_parameter;
+ errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ goto alert_loser;
+ }
+
+ PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
+
+ PORT_Memset(ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
+ PORT_Memcpy(&ss->ssl3.hs.client_random[SSL3_RANDOM_LENGTH - rand_length],
+ random, rand_length);
+
+ PRINT_BUF(60, (ss, "client random:", ss->ssl3.hs.client_random,
+ SSL3_RANDOM_LENGTH));
+
+ if (ssl3_config_match_init(ss) == 0) {
+ errCode = PORT_GetError(); /* error code is already set. */
+ goto alert_loser;
+ }
+
+ /* Select a cipher suite.
+ **
+ ** NOTE: This suite selection algorithm should be the same as the one in
+ ** ssl3_HandleClientHello().
+ */
+ for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
+ ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
+ SSLVersionRange vrange = { ss->version, ss->version };
+ if (!ssl3_config_match(suite, ss->ssl3.policy, &vrange, ss)) {
+ continue;
+ }
+ for (i = 0; i + 2 < suite_length; i += 3) {
+ PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
+ if (suite_i == suite->cipher_suite) {
+ ss->ssl3.hs.cipher_suite = suite_i;
+ rv = ssl3_SetupCipherSuite(ss, PR_TRUE);
+ if (rv != SECSuccess) {
+ desc = internal_error;
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+ goto suite_found;
+ }
+ }
+ }
+ errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
+ goto alert_loser;
+
+suite_found:
+
+ /* If the ClientHello version is less than our maximum version, check for a
+ * TLS_FALLBACK_SCSV and reject the connection if found. */
+ if (ss->vrange.max > ss->clientHelloVersion) {
+ for (i = 0; i + 2 < suite_length; i += 3) {
+ PRUint16 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
+ if (suite_i == TLS_FALLBACK_SCSV) {
+ desc = inappropriate_fallback;
+ errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
+ goto alert_loser;
+ }
+ }
+ }
+
+ /* Look for the SCSV, and if found, treat it just like an empty RI
+ * extension by processing a local copy of an empty RI extension.
+ */
+ for (i = 0; i + 2 < suite_length; i += 3) {
+ PRUint32 suite_i = (suites[i] << 16) | (suites[i + 1] << 8) | suites[i + 2];
+ if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
+ PRUint8 *b2 = (PRUint8 *)emptyRIext;
+ PRUint32 L2 = sizeof emptyRIext;
+ (void)ssl3_HandleExtensions(ss, &b2, &L2, ssl_hs_client_hello);
+ break;
+ }
+ }
+
+ if (ss->opt.requireSafeNegotiation &&
+ !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
+ desc = handshake_failure;
+ errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
+ goto alert_loser;
+ }
+
+ rv = ssl3_SelectServerCert(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+
+ /* we don't even search for a cache hit here. It's just a miss. */
+ SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_misses);
+ sid = ssl3_NewSessionID(ss, PR_TRUE);
+ if (sid == NULL) {
+ errCode = PORT_GetError();
+ goto loser; /* memory error is set. */
+ }
+ ss->sec.ci.sid = sid;
+ /* do not worry about memory leak of sid since it now belongs to ci */
+
+ /* We have to update the handshake hashes before we can send stuff */
+ rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_SendServerHelloSequence(ss);
+ ssl_ReleaseXmitBufLock(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ return SECSuccess;
+
+alert_loser:
+ SSL3_SendAlert(ss, alert_fatal, desc);
+loser:
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ PORT_SetError(errCode);
+ return SECFailure;
+}
+
+SECStatus
+ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
+ const sslBuffer *extensionBuf, sslBuffer *messageBuf)
+{
+ SECStatus rv;
+ SSL3ProtocolVersion version;
+ sslSessionID *sid = ss->sec.ci.sid;
+ const PRUint8 *random;
+
+ version = PR_MIN(ss->version, SSL_LIBRARY_VERSION_TLS_1_2);
+ if (IS_DTLS(ss)) {
+ version = dtls_TLSVersionToDTLSVersion(version);
+ }
+ rv = sslBuffer_AppendNumber(messageBuf, version, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (helloRetry) {
+ random = ssl_hello_retry_random;
+ } else {
+ rv = ssl_GenerateServerRandom(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ random = ss->ssl3.hs.server_random;
+ }
+ rv = sslBuffer_Append(messageBuf, random, SSL3_RANDOM_LENGTH);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ if (sid) {
+ rv = sslBuffer_AppendVariable(messageBuf, sid->u.ssl3.sessionID,
+ sid->u.ssl3.sessionIDLength, 1);
+ } else {
+ rv = sslBuffer_AppendNumber(messageBuf, 0, 1);
+ }
+ } else {
+ rv = sslBuffer_AppendVariable(messageBuf, ss->ssl3.hs.fakeSid.data,
+ ss->ssl3.hs.fakeSid.len, 1);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(messageBuf, ss->ssl3.hs.cipher_suite, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(messageBuf, ssl_compression_null, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (SSL_BUFFER_LEN(extensionBuf)) {
+ /* Directly copy the extensions */
+ rv = sslBuffer_AppendBufferVariable(messageBuf, extensionBuf, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ if (ss->xtnData.ech && ss->xtnData.ech->receivedInnerXtn) {
+ /* Signal ECH acceptance if we handled handled both CHOuter/CHInner (i.e.
+ * in shared mode), or if we received a CHInner in split/backend mode. */
+ if (ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch) {
+ if (helloRetry) {
+ return tls13_WriteServerEchHrrSignal(ss, SSL_BUFFER_BASE(messageBuf),
+ SSL_BUFFER_LEN(messageBuf));
+ } else {
+ return tls13_WriteServerEchSignal(ss, SSL_BUFFER_BASE(messageBuf),
+ SSL_BUFFER_LEN(messageBuf));
+ }
+ }
+ }
+ return SECSuccess;
+}
+
+/* The negotiated version number has been already placed in ss->version.
+**
+** Called from: ssl3_HandleClientHello (resuming session),
+** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session),
+** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
+*/
+SECStatus
+ssl3_SendServerHello(sslSocket *ss)
+{
+ SECStatus rv;
+ sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
+ sslBuffer messageBuf = SSL_BUFFER_EMPTY;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
+ ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
+ if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+ }
+
+ rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_server_hello);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl_ConstructServerHello(ss, PR_FALSE, &extensionBuf, &messageBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
+ SSL_BUFFER_LEN(&messageBuf));
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&messageBuf),
+ SSL_BUFFER_LEN(&messageBuf));
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = ssl3_SetupBothPendingCipherSpecs(ss);
+ if (rv != SECSuccess) {
+ goto loser; /* err set */
+ }
+ }
+
+ sslBuffer_Clear(&extensionBuf);
+ sslBuffer_Clear(&messageBuf);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&extensionBuf);
+ sslBuffer_Clear(&messageBuf);
+ return SECFailure;
+}
+
+SECStatus
+ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
+ const ssl3DHParams *params,
+ sslEphemeralKeyPair **keyPair)
+{
+ SECKEYDHParams dhParam;
+ SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */
+ SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */
+ sslEphemeralKeyPair *pair;
+
+ dhParam.prime.data = params->prime.data;
+ dhParam.prime.len = params->prime.len;
+ dhParam.base.data = params->base.data;
+ dhParam.base.len = params->base.len;
+
+ PRINT_BUF(60, (NULL, "Server DH p", dhParam.prime.data,
+ dhParam.prime.len));
+ PRINT_BUF(60, (NULL, "Server DH g", dhParam.base.data,
+ dhParam.base.len));
+
+ /* Generate ephemeral DH keypair */
+ privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
+ if (!privKey || !pubKey) {
+ ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
+ return SECFailure;
+ }
+
+ pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey);
+ if (!pair) {
+ SECKEY_DestroyPrivateKey(privKey);
+ SECKEY_DestroyPublicKey(pubKey);
+
+ return SECFailure;
+ }
+
+ *keyPair = pair;
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_SendDHServerKeyExchange(sslSocket *ss)
+{
+ const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
+ SECStatus rv = SECFailure;
+ int length;
+ SECItem signed_hash = { siBuffer, NULL, 0 };
+ SSL3Hashes hashes;
+ SSLHashType hashAlg;
+
+ const ssl3DHParams *params;
+ sslEphemeralKeyPair *keyPair;
+ SECKEYPublicKey *pubKey;
+ SECKEYPrivateKey *certPrivateKey;
+ const sslNamedGroupDef *groupDef;
+ /* Do this on the heap, this could be over 2k long. */
+ sslBuffer dhBuf = SSL_BUFFER_EMPTY;
+
+ if (kea_def->kea != kea_dhe_dss && kea_def->kea != kea_dhe_rsa) {
+ /* TODO: Support DH_anon. It might be sufficient to drop the signature.
+ See bug 1170510. */
+ PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl_SelectDHEGroup(ss, &groupDef);
+ if (rv == SECFailure) {
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+ }
+ ss->sec.keaGroup = groupDef;
+
+ params = ssl_GetDHEParams(groupDef);
+ rv = ssl_CreateDHEKeyPair(groupDef, params, &keyPair);
+ if (rv == SECFailure) {
+ ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
+ return SECFailure;
+ }
+ PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
+
+ if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+ hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
+ } else {
+ /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+ hashAlg = ssl_hash_none;
+ }
+
+ pubKey = keyPair->keys->pubKey;
+ PRINT_BUF(50, (ss, "DH public value:",
+ pubKey->u.dh.publicValue.data,
+ pubKey->u.dh.publicValue.len));
+ rv = ssl3_ComputeDHKeyHash(ss, hashAlg, &hashes,
+ pubKey->u.dh.prime,
+ pubKey->u.dh.base,
+ pubKey->u.dh.publicValue,
+ PR_TRUE /* padY */);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey;
+ rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash);
+ if (rv != SECSuccess) {
+ goto loser; /* ssl3_SignHashes has set err. */
+ }
+
+ length = 2 + pubKey->u.dh.prime.len +
+ 2 + pubKey->u.dh.base.len +
+ 2 + pubKey->u.dh.prime.len +
+ 2 + signed_hash.len;
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ length += 2;
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.prime.data,
+ pubKey->u.dh.prime.len, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.base.data,
+ pubKey->u.dh.base.len, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl_AppendPaddedDHKeyShare(&dhBuf, pubKey, PR_TRUE);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendPaddedDHKeyShare. */
+ }
+ rv = ssl3_AppendBufferToHandshake(ss, &dhBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
+ signed_hash.len, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ sslBuffer_Clear(&dhBuf);
+ PORT_Free(signed_hash.data);
+ return SECSuccess;
+
+loser:
+ if (signed_hash.data)
+ PORT_Free(signed_hash.data);
+ sslBuffer_Clear(&dhBuf);
+ return SECFailure;
+}
+
+static SECStatus
+ssl3_SendServerKeyExchange(sslSocket *ss)
+{
+ const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ switch (kea_def->exchKeyType) {
+ case ssl_kea_dh: {
+ return ssl3_SendDHServerKeyExchange(ss);
+ }
+
+ case ssl_kea_ecdh: {
+ return ssl3_SendECDHServerKeyExchange(ss);
+ }
+
+ case ssl_kea_rsa:
+ case ssl_kea_null:
+ default:
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ break;
+ }
+
+ return SECFailure;
+}
+
+SECStatus
+ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
+ PRBool grease, sslBuffer *buf)
+{
+ SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
+ unsigned int filteredCount = 0;
+
+ SECStatus rv = ssl3_FilterSigAlgs(ss, minVersion, PR_FALSE, forCert,
+ PR_ARRAY_SIZE(filtered),
+ filtered, &filteredCount);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount, grease, buf);
+}
+
+SECStatus
+ssl3_EncodeFilteredSigAlgs(const sslSocket *ss, const SSLSignatureScheme *schemes,
+ PRUint32 numSchemes, PRBool grease, sslBuffer *buf)
+{
+ if (!numSchemes) {
+ PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+
+ unsigned int lengthOffset;
+ SECStatus rv;
+
+ rv = sslBuffer_Skip(buf, 2, &lengthOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ for (unsigned int i = 0; i < numSchemes; ++i) {
+ rv = sslBuffer_AppendNumber(buf, schemes[i], 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ /* GREASE SignatureAlgorithms:
+ * A client MAY select one or more GREASE signature algorithm values and
+ * advertise them in the "signature_algorithms" or
+ * "signature_algorithms_cert" extensions, if sent [RFC8701, Section 3.1].
+ *
+ * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
+ * follows: [...] A server MAY select one or more GREASE signature
+ * algorithm values and advertise them in the "signature_algorithms" or
+ * "signature_algorithms_cert" extensions, if present
+ * [RFC8701, Section 4.1]. */
+ if (grease &&
+ ((!ss->sec.isServer && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) ||
+ (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3))) {
+ PRUint16 value;
+ if (ss->sec.isServer) {
+ rv = tls13_RandomGreaseValue(&value);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ } else {
+ value = ss->ssl3.hs.grease->idx[grease_sigalg];
+ }
+ rv = sslBuffer_AppendNumber(buf, value, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ return sslBuffer_InsertLength(buf, lengthOffset, 2);
+}
+
+/*
+ * In TLS 1.3 we are permitted to advertise support for PKCS#1
+ * schemes. This doesn't affect the signatures in TLS itself, just
+ * those on certificates. Not advertising PKCS#1 signatures creates a
+ * serious compatibility risk as it excludes many certificate chains
+ * that include PKCS#1. Hence, forCert is used to enable advertising
+ * PKCS#1 support. Note that we include these in signature_algorithms
+ * because we don't yet support signature_algorithms_cert. TLS 1.3
+ * requires that PKCS#1 schemes are placed last in the list if they
+ * are present. This sorting can be removed once we support
+ * signature_algorithms_cert.
+ */
+SECStatus
+ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae,
+ PRBool forCert,
+ unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
+ unsigned int *numFilteredSchemes)
+{
+ PORT_Assert(filteredSchemes);
+ PORT_Assert(numFilteredSchemes);
+ PORT_Assert(maxSchemes >= ss->ssl3.signatureSchemeCount);
+ if (maxSchemes < ss->ssl3.signatureSchemeCount) {
+ return SECFailure;
+ }
+
+ *numFilteredSchemes = 0;
+ PRBool allowUnsortedPkcs1 = forCert && minVersion < SSL_LIBRARY_VERSION_TLS_1_3;
+ for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
+ continue;
+ }
+ if (ssl_SignatureSchemeAccepted(minVersion,
+ ss->ssl3.signatureSchemes[i],
+ allowUnsortedPkcs1)) {
+ filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
+ }
+ }
+ if (forCert && !allowUnsortedPkcs1) {
+ for (unsigned int i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ if (disableRsae && ssl_IsRsaeSignatureScheme(ss->ssl3.signatureSchemes[i])) {
+ continue;
+ }
+ if (!ssl_SignatureSchemeAccepted(minVersion,
+ ss->ssl3.signatureSchemes[i],
+ PR_FALSE) &&
+ ssl_SignatureSchemeAccepted(minVersion,
+ ss->ssl3.signatureSchemes[i],
+ PR_TRUE)) {
+ filteredSchemes[(*numFilteredSchemes)++] = ss->ssl3.signatureSchemes[i];
+ }
+ }
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_SendCertificateRequest(sslSocket *ss)
+{
+ PRBool isTLS12;
+ const PRUint8 *certTypes;
+ SECStatus rv;
+ PRUint32 length;
+ const SECItem *names;
+ unsigned int calen;
+ unsigned int nnames;
+ const SECItem *name;
+ unsigned int i;
+ int certTypesLength;
+ PRUint8 sigAlgs[2 + MAX_SIGNATURE_SCHEMES * 2];
+ sslBuffer sigAlgsBuf = SSL_BUFFER(sigAlgs);
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+
+ rv = ssl_GetCertificateRequestCAs(ss, &calen, &names, &nnames);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ certTypes = certificate_types;
+ certTypesLength = sizeof certificate_types;
+
+ length = 1 + certTypesLength + 2 + calen;
+ if (isTLS12) {
+ rv = ssl3_EncodeSigAlgs(ss, ss->version, PR_TRUE /* forCert */,
+ PR_FALSE /* GREASE */, &sigAlgsBuf);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ length += SSL_BUFFER_LEN(&sigAlgsBuf);
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request, length);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ if (isTLS12) {
+ rv = ssl3_AppendHandshake(ss, SSL_BUFFER_BASE(&sigAlgsBuf),
+ SSL_BUFFER_LEN(&sigAlgsBuf));
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ }
+ rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ for (i = 0, name = names; i < nnames; i++, name++) {
+ rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_SendServerHelloDone(sslSocket *ss)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello_done, 0);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ rv = ssl3_FlushHandshake(ss, 0);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by ssl3_FlushHandshake */
+ }
+ return SECSuccess;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 Certificate Verify message
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECItem signed_hash = { siBuffer, NULL, 0 };
+ SECStatus rv;
+ int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
+ SSL3AlertDescription desc = handshake_failure;
+ PRBool isTLS;
+ SSLSignatureScheme sigScheme;
+ SSL3Hashes hashes;
+ const PRUint8 *savedMsg = b;
+ const PRUint32 savedLen = length;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->ssl3.hs.ws != wait_cert_verify) {
+ desc = unexpected_message;
+ errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
+ goto alert_loser;
+ }
+
+ /* TLS 1.3 is handled by tls13_HandleCertificateVerify */
+ PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
+
+ if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+ PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_record);
+ rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+ if (rv != SECSuccess) {
+ if (PORT_GetError() == SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM) {
+ errCode = SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM;
+ }
+ goto loser; /* alert already sent */
+ }
+ rv = ssl_CheckSignatureSchemeConsistency(
+ ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = illegal_parameter;
+ goto alert_loser;
+ }
+
+ rv = ssl3_ComputeHandshakeHash(ss->ssl3.hs.messages.buf,
+ ss->ssl3.hs.messages.len,
+ ssl_SignatureSchemeToHashType(sigScheme),
+ &hashes);
+ } else {
+ PORT_Assert(ss->ssl3.hs.hashType != handshake_hash_record);
+ sigScheme = ssl_sig_none;
+ rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.prSpec, &hashes, 0);
+ }
+
+ if (rv != SECSuccess) {
+ errCode = SSL_ERROR_DIGEST_FAILURE;
+ desc = decrypt_error;
+ goto alert_loser;
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+
+ isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
+
+ /* XXX verify that the key & kea match */
+ rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signed_hash);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ desc = isTLS ? decrypt_error : handshake_failure;
+ goto alert_loser;
+ }
+
+ signed_hash.data = NULL;
+
+ if (length != 0) {
+ desc = isTLS ? decode_error : illegal_parameter;
+ goto alert_loser; /* malformed */
+ }
+
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify,
+ savedMsg, savedLen);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+
+ ss->ssl3.hs.ws = wait_change_cipher;
+ return SECSuccess;
+
+alert_loser:
+ SSL3_SendAlert(ss, alert_fatal, desc);
+loser:
+ PORT_SetError(errCode);
+ return SECFailure;
+}
+
+/* find a slot that is able to generate a PMS and wrap it with RSA.
+ * Then generate and return the PMS.
+ * If the serverKeySlot parameter is non-null, this function will use
+ * that slot to do the job, otherwise it will find a slot.
+ *
+ * Called from ssl3_DeriveConnectionKeys() (above)
+ * ssl3_SendRSAClientKeyExchange() (above)
+ * ssl3_HandleRSAClientKeyExchange() (below)
+ * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
+ */
+static PK11SymKey *
+ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
+ PK11SlotInfo *serverKeySlot)
+{
+ PK11SymKey *pms = NULL;
+ PK11SlotInfo *slot = serverKeySlot;
+ void *pwArg = ss->pkcs11PinArg;
+ SECItem param;
+ CK_VERSION version;
+ CK_MECHANISM_TYPE mechanism_array[3];
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (slot == NULL) {
+ SSLCipherAlgorithm calg;
+ /* The specReadLock would suffice here, but we cannot assert on
+ ** read locks. Also, all the callers who call with a non-null
+ ** slot already hold the SpecWriteLock.
+ */
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
+ PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
+
+ calg = spec->cipherDef->calg;
+
+ /* First get an appropriate slot. */
+ mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
+ mechanism_array[1] = CKM_RSA_PKCS;
+ mechanism_array[2] = ssl3_Alg2Mech(calg);
+
+ slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
+ if (slot == NULL) {
+ /* can't find a slot with all three, find a slot with the minimum */
+ slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
+ if (slot == NULL) {
+ PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
+ return pms; /* which is NULL */
+ }
+ }
+ }
+
+ /* Generate the pre-master secret ... */
+ if (IS_DTLS(ss)) {
+ SSL3ProtocolVersion temp;
+
+ temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
+ version.major = MSB(temp);
+ version.minor = LSB(temp);
+ } else {
+ version.major = MSB(ss->clientHelloVersion);
+ version.minor = LSB(ss->clientHelloVersion);
+ }
+
+ param.data = (unsigned char *)&version;
+ param.len = sizeof version;
+
+ pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
+ if (!serverKeySlot)
+ PK11_FreeSlot(slot);
+ if (pms == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ }
+ return pms;
+}
+
+static void
+ssl3_CSwapPK11SymKey(PK11SymKey **x, PK11SymKey **y, PRBool c)
+{
+ uintptr_t mask = (uintptr_t)c;
+ unsigned int i;
+ for (i = 1; i < sizeof(uintptr_t) * 8; i <<= 1) {
+ mask |= mask << i;
+ }
+ uintptr_t x_ptr = (uintptr_t)*x;
+ uintptr_t y_ptr = (uintptr_t)*y;
+ uintptr_t tmp = (x_ptr ^ y_ptr) & mask;
+ x_ptr = x_ptr ^ tmp;
+ y_ptr = y_ptr ^ tmp;
+ *x = (PK11SymKey *)x_ptr;
+ *y = (PK11SymKey *)y_ptr;
+}
+
+/* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
+ * return any indication of failure of the Client Key Exchange message,
+ * where that failure is caused by the content of the client's message.
+ * This function must not return SECFailure for any reason that is directly
+ * or indirectly caused by the content of the client's encrypted PMS.
+ * We must not send an alert and also not drop the connection.
+ * Instead, we generate a random PMS. This will cause a failure
+ * in the processing the finished message, which is exactly where
+ * the failure must occur.
+ *
+ * Called from ssl3_HandleClientKeyExchange
+ */
+static SECStatus
+ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
+ PRUint8 *b,
+ PRUint32 length,
+ sslKeyPair *serverKeyPair)
+{
+ SECStatus rv;
+ SECItem enc_pms;
+ PK11SymKey *pms = NULL;
+ PK11SymKey *fauxPms = NULL;
+ PK11SlotInfo *slot = NULL;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->ssl3.prSpec->epoch == ss->ssl3.pwSpec->epoch);
+
+ enc_pms.data = b;
+ enc_pms.len = length;
+
+ if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
+ PRUint32 kLen;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &kLen, 2, &enc_pms.data, &enc_pms.len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ return SECFailure;
+ }
+ if ((unsigned)kLen < enc_pms.len) {
+ enc_pms.len = kLen;
+ }
+ }
+
+ /*
+ * Get as close to algorithm 2 from RFC 5246; Section 7.4.7.1
+ * as we can within the constraints of the PKCS#11 interface.
+ *
+ * 1. Unconditionally generate a bogus PMS (what RFC 5246
+ * calls R).
+ * 2. Attempt the RSA decryption to recover the PMS (what
+ * RFC 5246 calls M).
+ * 3. Set PMS = (M == NULL) ? R : M
+ * 4. Use ssl3_ComputeMasterSecret(PMS) to attempt to derive
+ * the MS from PMS. This includes performing the version
+ * check and length check.
+ * 5. If either the initial RSA decryption failed or
+ * ssl3_ComputeMasterSecret(PMS) failed, then discard
+ * M and set PMS = R. Else, discard R and set PMS = M.
+ *
+ * We do two derivations here because we can't rely on having
+ * a function that only performs the PMS version and length
+ * check. The only redundant cost is that this runs the PRF,
+ * which isn't necessary here.
+ */
+
+ /* Generate the bogus PMS (R) */
+ slot = PK11_GetSlotFromPrivateKey(serverKeyPair->privKey);
+ if (!slot) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (!PK11_DoesMechanism(slot, CKM_SSL3_MASTER_KEY_DERIVE)) {
+ PK11_FreeSlot(slot);
+ slot = PK11_GetBestSlot(CKM_SSL3_MASTER_KEY_DERIVE, NULL);
+ if (!slot) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ ssl_GetSpecWriteLock(ss);
+ fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
+ ssl_ReleaseSpecWriteLock(ss);
+ PK11_FreeSlot(slot);
+
+ if (fauxPms == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ return SECFailure;
+ }
+
+ /*
+ * unwrap pms out of the incoming buffer
+ * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
+ * the unwrap. Rather, it is the mechanism with which the
+ * unwrapped pms will be used.
+ */
+ pms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms,
+ CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
+ /* Temporarily use the PMS if unwrapping the real PMS fails. */
+ ssl3_CSwapPK11SymKey(&pms, &fauxPms, pms == NULL);
+
+ /* Attempt to derive the MS from the PMS. This is the only way to
+ * check the version field in the RSA PMS. If this fails, we
+ * then use the faux PMS in place of the PMS. Note that this
+ * operation should never fail if we are using the faux PMS
+ * since it is correctly formatted. */
+ rv = ssl3_ComputeMasterSecret(ss, pms, NULL);
+
+ /* If we succeeded, then select the true PMS, else select the FPMS. */
+ ssl3_CSwapPK11SymKey(&pms, &fauxPms, (rv != SECSuccess) & (fauxPms != NULL));
+
+ /* This step will derive the MS from the PMS, among other things. */
+ rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+
+ /* Clear both PMS. */
+ PK11_FreeSymKey(pms);
+ PK11_FreeSymKey(fauxPms);
+
+ if (rv != SECSuccess) {
+ (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
+ return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+ssl3_HandleDHClientKeyExchange(sslSocket *ss,
+ PRUint8 *b,
+ PRUint32 length,
+ sslKeyPair *serverKeyPair)
+{
+ PK11SymKey *pms;
+ SECStatus rv;
+ SECKEYPublicKey clntPubKey;
+ CK_MECHANISM_TYPE target;
+ PRBool isTLS;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ clntPubKey.keyType = dhKey;
+ clntPubKey.u.dh.prime.len = serverKeyPair->pubKey->u.dh.prime.len;
+ clntPubKey.u.dh.prime.data = serverKeyPair->pubKey->u.dh.prime.data;
+ clntPubKey.u.dh.base.len = serverKeyPair->pubKey->u.dh.base.len;
+ clntPubKey.u.dh.base.data = serverKeyPair->pubKey->u.dh.base.data;
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.dh.publicValue,
+ 2, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (!ssl_IsValidDHEShare(&serverKeyPair->pubKey->u.dh.prime,
+ &clntPubKey.u.dh.publicValue)) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
+ return SECFailure;
+ }
+
+ isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
+
+ if (isTLS)
+ target = CKM_TLS_MASTER_KEY_DERIVE_DH;
+ else
+ target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
+
+ /* Determine the PMS */
+ pms = PK11_PubDerive(serverKeyPair->privKey, &clntPubKey, PR_FALSE, NULL, NULL,
+ CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
+ if (pms == NULL) {
+ ssl_FreeEphemeralKeyPairs(ss);
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+ PK11_FreeSymKey(pms);
+ ssl_FreeEphemeralKeyPairs(ss);
+ return rv;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 ClientKeyExchange message from the remote client
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleClientKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ sslKeyPair *serverKeyPair = NULL;
+ SECStatus rv;
+ const ssl3KEADef *kea_def;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->ssl3.hs.ws != wait_client_key) {
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
+ return SECFailure;
+ }
+
+ kea_def = ss->ssl3.hs.kea_def;
+
+ if (kea_def->ephemeral) {
+ sslEphemeralKeyPair *keyPair;
+ /* There should be exactly one pair. */
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
+ PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
+ PR_NEXT_LINK(&ss->ephemeralKeyPairs));
+ keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
+ serverKeyPair = keyPair->keys;
+ ss->sec.keaKeyBits =
+ SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
+ } else {
+ serverKeyPair = ss->sec.serverCert->serverKeyPair;
+ ss->sec.keaKeyBits = ss->sec.serverCert->serverKeyBits;
+ }
+
+ if (!serverKeyPair) {
+ SSL3_SendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
+ return SECFailure;
+ }
+ PORT_Assert(serverKeyPair->pubKey);
+ PORT_Assert(serverKeyPair->privKey);
+
+ ss->sec.keaType = kea_def->exchKeyType;
+
+ switch (kea_def->exchKeyType) {
+ case ssl_kea_rsa:
+ rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKeyPair);
+ break;
+
+ case ssl_kea_dh:
+ rv = ssl3_HandleDHClientKeyExchange(ss, b, length, serverKeyPair);
+ break;
+
+ case ssl_kea_ecdh:
+ rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, serverKeyPair);
+ break;
+
+ default:
+ (void)ssl3_HandshakeFailure(ss);
+ PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
+ return SECFailure;
+ }
+ ssl_FreeEphemeralKeyPairs(ss);
+ if (rv == SECSuccess) {
+ ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
+ } else {
+ /* PORT_SetError has been called by all the Handle*ClientKeyExchange
+ * functions above. However, not all error paths result in an alert, so
+ * this ensures that the server knows about the error. Note that if an
+ * alert was already sent, SSL3_SendAlert() is a noop. */
+ PRErrorCode errCode = PORT_GetError();
+ (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(errCode);
+ }
+ return rv;
+}
+
+/* This is TLS's equivalent of sending a no_certificate alert. */
+SECStatus
+ssl3_SendEmptyCertificate(sslSocket *ss)
+{
+ SECStatus rv;
+ unsigned int len = 0;
+ PRBool isTLS13 = PR_FALSE;
+ const SECItem *context;
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_Assert(ss->ssl3.hs.clientCertRequested);
+ context = &ss->xtnData.certReqContext;
+ len = context->len + 1;
+ isTLS13 = PR_TRUE;
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate, len + 3);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ if (isTLS13) {
+ rv = ssl3_AppendHandshakeVariable(ss, context->data, context->len, 1);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+
+ return ssl3_AppendHandshakeNumber(ss, 0, 3);
+}
+
+/*
+ * NewSessionTicket
+ * Called from ssl3_HandleFinished
+ */
+static SECStatus
+ssl3_SendNewSessionTicket(sslSocket *ss)
+{
+ SECItem ticket = { 0, NULL, 0 };
+ SECStatus rv;
+ NewSessionTicket nticket = { 0 };
+
+ rv = ssl3_EncodeSessionTicket(ss, &nticket, NULL, 0,
+ ss->ssl3.pwSpec->masterSecret, &ticket);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Serialize the handshake message. Length =
+ * lifetime (4) + ticket length (2) + ticket. */
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
+ 4 + 2 + ticket.len);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* This is a fixed value. */
+ rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Encode the ticket. */
+ rv = ssl3_AppendHandshakeVariable(ss, ticket.data, ticket.len, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ rv = SECSuccess;
+
+loser:
+ if (ticket.data) {
+ SECITEM_FreeItem(&ticket, PR_FALSE);
+ }
+ return rv;
+}
+
+static SECStatus
+ssl3_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ SECItem ticketData;
+ PRUint32 temp;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
+ PORT_Assert(!ss->ssl3.hs.receivedNewSessionTicket);
+
+ if (ss->ssl3.hs.ws != wait_new_session_ticket) {
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+
+ /* RFC5077 Section 3.3: "The client MUST NOT treat the ticket as valid
+ * until it has verified the server's Finished message." See the comment in
+ * ssl3_FinishHandshake for more details.
+ */
+ ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(ss);
+ if (length < 4) {
+ (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 4, &b, &length);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+ ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = temp;
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &ticketData, 2, &b, &length);
+ if (rv != SECSuccess || length != 0) {
+ (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
+ return SECFailure; /* malformed */
+ }
+ /* If the server sent a zero-length ticket, ignore it and keep the
+ * existing ticket. */
+ if (ticketData.len != 0) {
+ rv = SECITEM_CopyItem(NULL, &ss->ssl3.hs.newSessionTicket.ticket,
+ &ticketData);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ ss->ssl3.hs.receivedNewSessionTicket = PR_TRUE;
+ }
+
+ ss->ssl3.hs.ws = wait_change_cipher;
+ return SECSuccess;
+}
+
+#ifdef NISCC_TEST
+static PRInt32 connNum = 0;
+
+static SECStatus
+get_fake_cert(SECItem *pCertItem, int *pIndex)
+{
+ PRFileDesc *cf;
+ char *testdir;
+ char *startat;
+ char *stopat;
+ const char *extension;
+ int fileNum;
+ PRInt32 numBytes = 0;
+ PRStatus prStatus;
+ PRFileInfo info;
+ char cfn[100];
+
+ pCertItem->data = 0;
+ if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) {
+ return SECSuccess;
+ }
+ *pIndex = (NULL != strstr(testdir, "root"));
+ extension = (strstr(testdir, "simple") ? "" : ".der");
+ fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1;
+ if ((startat = PR_GetEnvSecure("START_AT")) != NULL) {
+ fileNum += atoi(startat);
+ }
+ if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL &&
+ fileNum >= atoi(stopat)) {
+ *pIndex = -1;
+ return SECSuccess;
+ }
+ snprintf(cfn, sizeof(cfn), "%s/%08d%s", testdir, fileNum, extension);
+ cf = PR_Open(cfn, PR_RDONLY, 0);
+ if (!cf) {
+ goto loser;
+ }
+ prStatus = PR_GetOpenFileInfo(cf, &info);
+ if (prStatus != PR_SUCCESS) {
+ PR_Close(cf);
+ goto loser;
+ }
+ pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
+ if (pCertItem) {
+ numBytes = PR_Read(cf, pCertItem->data, info.size);
+ }
+ PR_Close(cf);
+ if (numBytes != info.size) {
+ SECITEM_FreeItem(pCertItem, PR_FALSE);
+ PORT_SetError(SEC_ERROR_IO);
+ goto loser;
+ }
+ fprintf(stderr, "using %s\n", cfn);
+ return SECSuccess;
+
+loser:
+ fprintf(stderr, "failed to use %s\n", cfn);
+ *pIndex = -1;
+ return SECFailure;
+}
+#endif
+
+/*
+ * Used by both client and server.
+ * Called from HandleServerHelloDone and from SendServerHelloSequence.
+ */
+static SECStatus
+ssl3_SendCertificate(sslSocket *ss)
+{
+ SECStatus rv;
+ CERTCertificateList *certChain;
+ int certChainLen = 0;
+ int i;
+#ifdef NISCC_TEST
+ SECItem fakeCert;
+ int ndex = -1;
+#endif
+ PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3;
+ SECItem context = { siBuffer, NULL, 0 };
+ unsigned int contextLen = 0;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
+
+ if (ss->sec.localCert)
+ CERT_DestroyCertificate(ss->sec.localCert);
+ if (ss->sec.isServer) {
+ /* A server certificate is selected in ssl3_HandleClientHello. */
+ PORT_Assert(ss->sec.serverCert);
+
+ certChain = ss->sec.serverCert->serverCertChain;
+ ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
+ } else {
+ certChain = ss->ssl3.clientCertChain;
+ ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
+ }
+
+#ifdef NISCC_TEST
+ rv = get_fake_cert(&fakeCert, &ndex);
+#endif
+
+ if (isTLS13) {
+ contextLen = 1; /* Size of the context length */
+ if (!ss->sec.isServer) {
+ PORT_Assert(ss->ssl3.hs.clientCertRequested);
+ context = ss->xtnData.certReqContext;
+ contextLen += context.len;
+ }
+ }
+ if (certChain) {
+ for (i = 0; i < certChain->len; i++) {
+#ifdef NISCC_TEST
+ if (fakeCert.len > 0 && i == ndex) {
+ certChainLen += fakeCert.len + 3;
+ } else {
+ certChainLen += certChain->certs[i].len + 3;
+ }
+#else
+ certChainLen += certChain->certs[i].len + 3;
+#endif
+ }
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
+ contextLen + certChainLen + 3);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+
+ if (isTLS13) {
+ rv = ssl3_AppendHandshakeVariable(ss, context.data,
+ context.len, 1);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ }
+
+ rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ if (certChain) {
+ for (i = 0; i < certChain->len; i++) {
+#ifdef NISCC_TEST
+ if (fakeCert.len > 0 && i == ndex) {
+ rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
+ fakeCert.len, 3);
+ SECITEM_FreeItem(&fakeCert, PR_FALSE);
+ } else {
+ rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
+ certChain->certs[i].len, 3);
+ }
+#else
+ rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
+ certChain->certs[i].len, 3);
+#endif
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ }
+ }
+
+ return SECSuccess;
+}
+
+/*
+ * Used by server only.
+ * single-stapling, send only a single cert status
+ */
+SECStatus
+ssl3_SendCertificateStatus(sslSocket *ss)
+{
+ SECStatus rv;
+ int len = 0;
+ SECItemArray *statusToSend = NULL;
+ const sslServerCert *serverCert;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->sec.isServer);
+
+ if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
+ return SECSuccess;
+
+ /* Use certStatus based on the cert being used. */
+ serverCert = ss->sec.serverCert;
+ if (serverCert->certStatusArray && serverCert->certStatusArray->len) {
+ statusToSend = serverCert->certStatusArray;
+ }
+ if (!statusToSend)
+ return SECSuccess;
+
+ /* Use the array's first item only (single stapling) */
+ len = 1 + statusToSend->items[0].len + 3;
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_status, len);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
+ if (rv != SECSuccess)
+ return rv; /* err set by AppendHandshake. */
+
+ rv = ssl3_AppendHandshakeVariable(ss,
+ statusToSend->items[0].data,
+ statusToSend->items[0].len,
+ 3);
+ if (rv != SECSuccess)
+ return rv; /* err set by AppendHandshake. */
+
+ return SECSuccess;
+}
+
+/* This is used to delete the CA certificates in the peer certificate chain
+ * from the cert database after they've been validated.
+ */
+void
+ssl3_CleanupPeerCerts(sslSocket *ss)
+{
+ PLArenaPool *arena = ss->ssl3.peerCertArena;
+ ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
+
+ for (; certs; certs = certs->next) {
+ CERT_DestroyCertificate(certs->cert);
+ }
+ if (arena)
+ PORT_FreeArena(arena, PR_FALSE);
+ ss->ssl3.peerCertArena = NULL;
+ ss->ssl3.peerCertChain = NULL;
+
+ if (ss->sec.peerCert != NULL) {
+ if (ss->sec.peerKey) {
+ SECKEY_DestroyPublicKey(ss->sec.peerKey);
+ ss->sec.peerKey = NULL;
+ }
+ CERT_DestroyCertificate(ss->sec.peerCert);
+ ss->sec.peerCert = NULL;
+ }
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 CertificateStatus message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+
+ if (ss->ssl3.hs.ws != wait_certificate_status) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
+ return SECFailure;
+ }
+
+ rv = ssl_ReadCertificateStatus(ss, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* code already set */
+ }
+
+ return ssl3_AuthCertificate(ss);
+}
+
+SECStatus
+ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ PRUint32 status, len;
+ SECStatus rv;
+
+ PORT_Assert(!ss->sec.isServer);
+
+ /* Consume the CertificateStatusType enum */
+ rv = ssl3_ConsumeHandshakeNumber(ss, &status, 1, &b, &length);
+ if (rv != SECSuccess || status != 1 /* ocsp */) {
+ return ssl3_DecodeError(ss);
+ }
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &len, 3, &b, &length);
+ if (rv != SECSuccess || len != length) {
+ return ssl3_DecodeError(ss);
+ }
+
+#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */
+ if (length > MAX_CERTSTATUS_LEN) {
+ ssl3_DecodeError(ss); /* sets error code */
+ return SECFailure;
+ }
+#undef MAX_CERTSTATUS_LEN
+
+ /* Array size 1, because we currently implement single-stapling only */
+ SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
+ if (!ss->sec.ci.sid->peerCertStatus.items)
+ return SECFailure; /* code already set */
+
+ ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
+
+ if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
+ SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
+ return SECFailure; /* code already set */
+ }
+
+ PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
+ ss->sec.ci.sid->peerCertStatus.items[0].len = length;
+ ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
+ return SECSuccess;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 Certificate message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if ((ss->sec.isServer && ss->ssl3.hs.ws != wait_client_cert) ||
+ (!ss->sec.isServer && ss->ssl3.hs.ws != wait_server_cert)) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERTIFICATE);
+ return SECFailure;
+ }
+
+ if (ss->sec.isServer) {
+ dtls_ReceivedFirstMessageInFlight(ss);
+ }
+
+ return ssl3_CompleteHandleCertificate(ss, b, length);
+}
+
+/* Called from ssl3_HandleCertificate
+ */
+SECStatus
+ssl3_CompleteHandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ ssl3CertNode *c;
+ ssl3CertNode *lastCert = NULL;
+ PRUint32 remaining = 0;
+ PRUint32 size;
+ SECStatus rv;
+ PRBool isServer = ss->sec.isServer;
+ PRBool isTLS;
+ SSL3AlertDescription desc;
+ int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
+ SECItem certItem;
+
+ ssl3_CleanupPeerCerts(ss);
+ isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
+
+ /* It is reported that some TLS client sends a Certificate message
+ ** with a zero-length message body. We'll treat that case like a
+ ** normal no_certificates message to maximize interoperability.
+ */
+ if (length) {
+ rv = ssl3_ConsumeHandshakeNumber(ss, &remaining, 3, &b, &length);
+ if (rv != SECSuccess)
+ goto loser; /* fatal alert already sent by ConsumeHandshake. */
+ if (remaining > length)
+ goto decode_loser;
+ }
+
+ if (!remaining) {
+ if (!(isTLS && isServer)) {
+ desc = bad_certificate;
+ goto alert_loser;
+ }
+ /* This is TLS's version of a no_certificate alert. */
+ /* I'm a server. I've requested a client cert. He hasn't got one. */
+ rv = ssl3_HandleNoCertificate(ss);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ ss->ssl3.hs.ws = wait_client_key;
+ } else {
+ TLS13_SET_HS_STATE(ss, wait_finished);
+ }
+ return SECSuccess;
+ }
+
+ ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (ss->ssl3.peerCertArena == NULL) {
+ goto loser; /* don't send alerts on memory errors */
+ }
+
+ /* First get the peer cert. */
+ if (remaining < 3)
+ goto decode_loser;
+
+ remaining -= 3;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
+ if (rv != SECSuccess)
+ goto loser; /* fatal alert already sent by ConsumeHandshake. */
+ if (size == 0 || remaining < size)
+ goto decode_loser;
+
+ certItem.data = b;
+ certItem.len = size;
+ b += size;
+ length -= size;
+ remaining -= size;
+
+ ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
+ PR_FALSE, PR_TRUE);
+ if (ss->sec.peerCert == NULL) {
+ /* We should report an alert if the cert was bad, but not if the
+ * problem was just some local problem, like memory error.
+ */
+ goto ambiguous_err;
+ }
+
+ /* Now get all of the CA certs. */
+ while (remaining > 0) {
+ if (remaining < 3)
+ goto decode_loser;
+
+ remaining -= 3;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &size, 3, &b, &length);
+ if (rv != SECSuccess)
+ goto loser; /* fatal alert already sent by ConsumeHandshake. */
+ if (size == 0 || remaining < size)
+ goto decode_loser;
+
+ certItem.data = b;
+ certItem.len = size;
+ b += size;
+ length -= size;
+ remaining -= size;
+
+ c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
+ if (c == NULL) {
+ goto loser; /* don't send alerts on memory errors */
+ }
+
+ c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
+ PR_FALSE, PR_TRUE);
+ if (c->cert == NULL) {
+ goto ambiguous_err;
+ }
+
+ c->next = NULL;
+ if (lastCert) {
+ lastCert->next = c;
+ } else {
+ ss->ssl3.peerCertChain = c;
+ }
+ lastCert = c;
+ }
+
+ SECKEY_UpdateCertPQG(ss->sec.peerCert);
+
+ if (!isServer &&
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
+ ss->ssl3.hs.ws = wait_certificate_status;
+ rv = SECSuccess;
+ } else {
+ rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
+ }
+
+ return rv;
+
+ambiguous_err:
+ errCode = PORT_GetError();
+ switch (errCode) {
+ case PR_OUT_OF_MEMORY_ERROR:
+ case SEC_ERROR_BAD_DATABASE:
+ case SEC_ERROR_NO_MEMORY:
+ if (isTLS) {
+ desc = internal_error;
+ goto alert_loser;
+ }
+ goto loser;
+ }
+ ssl3_SendAlertForCertError(ss, errCode);
+ goto loser;
+
+decode_loser:
+ desc = isTLS ? decode_error : bad_certificate;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+
+loser:
+ (void)ssl_MapLowLevelError(errCode);
+ return SECFailure;
+}
+
+SECStatus
+ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey)
+{
+ SECStatus rv;
+ PRUint32 minKey = 0;
+ PRInt32 optval;
+ PRBool usePolicyLength = PR_TRUE;
+
+ rv = NSS_OptionGet(NSS_KEY_SIZE_POLICY_FLAGS, &optval);
+ if (rv == SECSuccess) {
+ usePolicyLength = (PRBool)((optval & NSS_KEY_SIZE_POLICY_SSL_FLAG) == NSS_KEY_SIZE_POLICY_SSL_FLAG);
+ }
+
+ ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey);
+ switch (SECKEY_GetPublicKeyType(pubKey)) {
+ case rsaKey:
+ case rsaPssKey:
+ case rsaOaepKey:
+ rv = usePolicyLength ? NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &optval)
+ : SECFailure;
+ if (rv == SECSuccess && optval > 0) {
+ minKey = (PRUint32)optval;
+ } else {
+ minKey = SSL_RSA_MIN_MODULUS_BITS;
+ }
+ break;
+
+ case dsaKey:
+ rv = usePolicyLength ? NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &optval)
+ : SECFailure;
+ if (rv == SECSuccess && optval > 0) {
+ minKey = (PRUint32)optval;
+ } else {
+ minKey = SSL_DSA_MIN_P_BITS;
+ }
+ break;
+
+ case dhKey:
+ rv = usePolicyLength ? NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &optval)
+ : SECFailure;
+ if (rv == SECSuccess && optval > 0) {
+ minKey = (PRUint32)optval;
+ } else {
+ minKey = SSL_DH_MIN_P_BITS;
+ }
+ break;
+
+ case ecKey:
+ rv = usePolicyLength ? NSS_OptionGet(NSS_ECC_MIN_KEY_SIZE, &optval)
+ : SECFailure;
+ if (rv == SECSuccess && optval > 0) {
+ minKey = (PRUint32)optval;
+ } else {
+ /* Don't check EC strength here on the understanding that we
+ * only support curves we like. */
+ minKey = ss->sec.authKeyBits;
+ }
+ break;
+
+ default:
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ /* Too small: not good enough. Send a fatal alert. */
+ if (ss->sec.authKeyBits < minKey) {
+ FATAL_ERROR(ss, SSL_ERROR_WEAK_SERVER_CERT_KEY,
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_0
+ ? insufficient_security
+ : illegal_parameter);
+ return SECFailure;
+ }
+
+ /* PreliminaryChannelInfo.authKeyBits, scheme, and peerDelegCred are now valid. */
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_peer_auth;
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_HandleServerSpki(sslSocket *ss)
+{
+ PORT_Assert(!ss->sec.isServer);
+ SECKEYPublicKey *pubKey;
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ tls13_IsVerifyingWithDelegatedCredential(ss)) {
+ sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
+ pubKey = SECKEY_ExtractPublicKey(dc->spki);
+ if (!pubKey) {
+ PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Because we have only a single authType (ssl_auth_tls13_any)
+ * for TLS 1.3 at this point, set the scheme so that the
+ * callback can interpret |authKeyBits| correctly.
+ */
+ ss->sec.signatureScheme = dc->expectedCertVerifyAlg;
+ } else {
+ pubKey = CERT_ExtractPublicKey(ss->sec.peerCert);
+ if (!pubKey) {
+ PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ SECStatus rv = ssl_SetAuthKeyBits(ss, pubKey);
+ SECKEY_DestroyPublicKey(pubKey);
+ if (rv != SECSuccess) {
+ return rv; /* Alert sent and code set. */
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_AuthCertificate(sslSocket *ss)
+{
+ SECStatus rv;
+ PRBool isServer = ss->sec.isServer;
+ int errCode;
+
+ ss->ssl3.hs.authCertificatePending = PR_FALSE;
+
+ PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
+ ssl_preinfo_all);
+
+ if (!ss->sec.isServer) {
+ /* Set the |spki| used to verify the handshake. When verifying with a
+ * delegated credential (DC), this corresponds to the DC public key;
+ * otherwise it correspond to the public key of the peer's end-entity
+ * certificate. */
+ rv = ssl3_HandleServerSpki(ss);
+ if (rv != SECSuccess) {
+ /* Alert sent and code set (if not SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE).
+ * In either case, we're done here. */
+ errCode = PORT_GetError();
+ goto loser;
+ }
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType;
+ ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType;
+ }
+ }
+
+ /*
+ * Ask caller-supplied callback function to validate cert chain.
+ */
+ rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
+ PR_TRUE, isServer);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ if (errCode == 0) {
+ errCode = SSL_ERROR_BAD_CERTIFICATE;
+ }
+ if (rv != SECWouldBlock) {
+ if (ss->handleBadCert) {
+ rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
+ }
+ }
+
+ if (rv == SECWouldBlock) {
+ if (ss->sec.isServer) {
+ errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
+ goto loser;
+ }
+
+ ss->ssl3.hs.authCertificatePending = PR_TRUE;
+ rv = SECSuccess;
+ }
+
+ if (rv != SECSuccess) {
+ ssl3_SendAlertForCertError(ss, errCode);
+ goto loser;
+ }
+ }
+
+ if (ss->sec.ci.sid->peerCert) {
+ CERT_DestroyCertificate(ss->sec.ci.sid->peerCert);
+ }
+ ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
+
+ if (!ss->sec.isServer) {
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ TLS13_SET_HS_STATE(ss, wait_cert_verify);
+ } else {
+ /* Ephemeral suites require ServerKeyExchange. */
+ if (ss->ssl3.hs.kea_def->ephemeral) {
+ /* require server_key_exchange */
+ ss->ssl3.hs.ws = wait_server_key;
+ } else {
+ /* disallow server_key_exchange */
+ ss->ssl3.hs.ws = wait_cert_request;
+ /* This is static RSA key exchange so set the key exchange
+ * details to compensate for that. */
+ ss->sec.keaKeyBits = ss->sec.authKeyBits;
+ ss->sec.signatureScheme = ssl_sig_none;
+ ss->sec.keaGroup = NULL;
+ }
+ }
+ } else {
+ /* Server */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ ss->ssl3.hs.ws = wait_client_key;
+ } else {
+ TLS13_SET_HS_STATE(ss, wait_cert_verify);
+ }
+ }
+
+ PORT_Assert(rv == SECSuccess);
+ if (rv != SECSuccess) {
+ errCode = SEC_ERROR_LIBRARY_FAILURE;
+ goto loser;
+ }
+
+ return SECSuccess;
+
+loser:
+ (void)ssl_MapLowLevelError(errCode);
+ return SECFailure;
+}
+
+static SECStatus ssl3_FinishHandshake(sslSocket *ss);
+
+static SECStatus
+ssl3_AlwaysFail(sslSocket *ss)
+{
+ /* The caller should have cleared the callback. */
+ ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
+ PORT_SetError(PR_INVALID_STATE_ERROR);
+ return SECFailure;
+}
+
+/* Caller must hold 1stHandshakeLock.
+*/
+SECStatus
+ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+
+ if (ss->sec.isServer) {
+ PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
+ return SECFailure;
+ }
+
+ ssl_GetRecvBufLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (!ss->ssl3.hs.authCertificatePending) {
+ PORT_SetError(PR_INVALID_STATE_ERROR);
+ rv = SECFailure;
+ goto done;
+ }
+
+ ss->ssl3.hs.authCertificatePending = PR_FALSE;
+
+ if (error != 0) {
+ ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
+ ssl3_SendAlertForCertError(ss, error);
+ rv = SECSuccess;
+ } else if (ss->ssl3.hs.restartTarget != NULL) {
+ sslRestartTarget target = ss->ssl3.hs.restartTarget;
+ ss->ssl3.hs.restartTarget = NULL;
+
+ if (target == ssl3_FinishHandshake) {
+ SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication lost the race"
+ " with peer's finished message",
+ SSL_GETPID(), ss->fd));
+ }
+
+ rv = target(ss);
+ } else {
+ SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
+ " peer's finished message",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(!ss->ssl3.hs.isResuming);
+ PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
+
+ if (ss->opt.enableFalseStart &&
+ !ss->firstHsDone &&
+ !ss->ssl3.hs.isResuming &&
+ ssl3_WaitingForServerSecondRound(ss)) {
+ /* ssl3_SendClientSecondRound deferred the false start check because
+ * certificate authentication was pending, so we do it now if we still
+ * haven't received all of the server's second round yet.
+ */
+ rv = ssl3_CheckFalseStart(ss);
+ } else {
+ rv = SECSuccess;
+ }
+ }
+
+done:
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_ReleaseRecvBufLock(ss);
+
+ return rv;
+}
+
+static SECStatus
+ssl3_ComputeTLSFinished(sslSocket *ss, ssl3CipherSpec *spec,
+ PRBool isServer,
+ const SSL3Hashes *hashes,
+ TLSFinished *tlsFinished)
+{
+ SECStatus rv;
+ CK_TLS_MAC_PARAMS tls_mac_params;
+ SECItem param = { siBuffer, NULL, 0 };
+ PK11Context *prf_context;
+ unsigned int retLen;
+
+ PORT_Assert(spec->masterSecret);
+ if (!spec->masterSecret) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) {
+ tls_mac_params.prfHashMechanism = CKM_TLS_PRF;
+ } else {
+ tls_mac_params.prfHashMechanism = ssl3_GetPrfHashMechanism(ss);
+ }
+ tls_mac_params.ulMacLength = 12;
+ tls_mac_params.ulServerOrClient = isServer ? 1 : 2;
+ param.data = (unsigned char *)&tls_mac_params;
+ param.len = sizeof(tls_mac_params);
+ prf_context = PK11_CreateContextBySymKey(CKM_TLS_MAC, CKA_SIGN,
+ spec->masterSecret, &param);
+ if (!prf_context)
+ return SECFailure;
+
+ rv = PK11_DigestBegin(prf_context);
+ rv |= PK11_DigestOp(prf_context, hashes->u.raw, hashes->len);
+ rv |= PK11_DigestFinal(prf_context, tlsFinished->verify_data, &retLen,
+ sizeof tlsFinished->verify_data);
+ PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data);
+
+ PK11_DestroyContext(prf_context, PR_TRUE);
+
+ return rv;
+}
+
+/* The calling function must acquire and release the appropriate
+ * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
+ * ss->ssl3.crSpec).
+ */
+SECStatus
+ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
+ const char *label, unsigned int labelLen,
+ const unsigned char *val, unsigned int valLen,
+ unsigned char *out, unsigned int outLen)
+{
+ SECItem param = { siBuffer, NULL, 0 };
+ CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
+ PK11Context *prf_context;
+ unsigned int retLen;
+ SECStatus rv;
+
+ if (!spec->masterSecret) {
+ PORT_Assert(spec->masterSecret);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
+ /* Bug 1312976 non-SHA256 exporters are broken. */
+ if (ssl3_GetPrfHashMechanism(ss) != CKM_SHA256) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
+ }
+ prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
+ spec->masterSecret, &param);
+ if (!prf_context)
+ return SECFailure;
+
+ rv = PK11_DigestBegin(prf_context);
+ rv |= PK11_DigestOp(prf_context, (unsigned char *)label, labelLen);
+ rv |= PK11_DigestOp(prf_context, val, valLen);
+ rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
+ PORT_Assert(rv != SECSuccess || retLen == outLen);
+
+ PK11_DestroyContext(prf_context, PR_TRUE);
+ return rv;
+}
+
+/* called from ssl3_SendClientSecondRound
+ * ssl3_HandleFinished
+ */
+static SECStatus
+ssl3_SendNextProto(sslSocket *ss)
+{
+ SECStatus rv;
+ int padding_len;
+ static const unsigned char padding[32] = { 0 };
+
+ if (ss->xtnData.nextProto.len == 0 ||
+ ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
+ return SECSuccess;
+ }
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32);
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_next_proto, ss->xtnData.nextProto.len + 2 + padding_len);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshakeHeader */
+ }
+ rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data,
+ ss->xtnData.nextProto.len, 1);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake */
+ }
+ rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
+ if (rv != SECSuccess) {
+ return rv; /* error code set by AppendHandshake */
+ }
+ return rv;
+}
+
+/* called from ssl3_SendFinished and tls13_DeriveSecret.
+ *
+ * This function is simply a debugging aid and therefore does not return a
+ * SECStatus. */
+void
+ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret)
+{
+#ifdef NSS_ALLOW_SSLKEYLOGFILE
+ SECStatus rv;
+ SECItem *keyData;
+ /* Longest label is "CLIENT_HANDSHAKE_TRAFFIC_SECRET", master secret is 48
+ * bytes which happens to be the largest in TLS 1.3 as well (SHA384).
+ * Maximum line length: "CLIENT_HANDSHAKE_TRAFFIC_SECRET" (31) + " " (1) +
+ * client_random (32*2) + " " (1) +
+ * traffic_secret (48*2) + "\n" (1) = 194. */
+ char buf[200];
+ unsigned int offset, len;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (!ssl_keylog_iob)
+ return;
+
+ rv = PK11_ExtractKeyValue(secret);
+ if (rv != SECSuccess)
+ return;
+
+ /* keyData does not need to be freed. */
+ keyData = PK11_GetKeyData(secret);
+ if (!keyData || !keyData->data)
+ return;
+
+ len = strlen(label) + 1 + /* label + space */
+ SSL3_RANDOM_LENGTH * 2 + 1 + /* client random (hex) + space */
+ keyData->len * 2 + 1; /* secret (hex) + newline */
+ PORT_Assert(len <= sizeof(buf));
+ if (len > sizeof(buf))
+ return;
+
+ /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
+
+ /* There could be multiple, concurrent writers to the
+ * keylog, so we have to do everything in a single call to
+ * fwrite. */
+
+ strcpy(buf, label);
+ offset = strlen(label);
+ buf[offset++] += ' ';
+ hexEncode(buf + offset, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
+ offset += SSL3_RANDOM_LENGTH * 2;
+ buf[offset++] = ' ';
+ hexEncode(buf + offset, keyData->data, keyData->len);
+ offset += keyData->len * 2;
+ buf[offset++] = '\n';
+
+ PORT_Assert(offset == len);
+
+ PZ_Lock(ssl_keylog_lock);
+ if (fwrite(buf, len, 1, ssl_keylog_iob) == 1)
+ fflush(ssl_keylog_iob);
+ PZ_Unlock(ssl_keylog_lock);
+#endif
+}
+
+/* called from ssl3_SendClientSecondRound
+ * ssl3_HandleClientHello
+ * ssl3_HandleFinished
+ */
+static SECStatus
+ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
+{
+ ssl3CipherSpec *cwSpec;
+ PRBool isTLS;
+ PRBool isServer = ss->sec.isServer;
+ SECStatus rv;
+ SSL3Sender sender = isServer ? sender_server : sender_client;
+ SSL3Hashes hashes;
+ TLSFinished tlsFinished;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PR_ASSERT(!ss->ssl3.hs.clientCertificatePending);
+
+ ssl_GetSpecReadLock(ss);
+ cwSpec = ss->ssl3.cwSpec;
+ isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
+ rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
+ if (isTLS && rv == SECSuccess) {
+ rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished);
+ }
+ ssl_ReleaseSpecReadLock(ss);
+ if (rv != SECSuccess) {
+ goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */
+ }
+
+ if (isTLS) {
+ if (isServer)
+ ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
+ else
+ ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
+ ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof tlsFinished);
+ if (rv != SECSuccess)
+ goto fail; /* err set by AppendHandshake. */
+ rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
+ if (rv != SECSuccess)
+ goto fail; /* err set by AppendHandshake. */
+ } else {
+ if (isServer)
+ ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
+ else
+ ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
+ PORT_Assert(hashes.len == sizeof hashes.u.s);
+ ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, sizeof hashes.u.s);
+ if (rv != SECSuccess)
+ goto fail; /* err set by AppendHandshake. */
+ rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
+ if (rv != SECSuccess)
+ goto fail; /* err set by AppendHandshake. */
+ }
+ rv = ssl3_FlushHandshake(ss, flags);
+ if (rv != SECSuccess) {
+ goto fail; /* error code set by ssl3_FlushHandshake */
+ }
+
+ ssl3_RecordKeyLog(ss, "CLIENT_RANDOM", ss->ssl3.cwSpec->masterSecret);
+
+ return SECSuccess;
+
+fail:
+ return rv;
+}
+
+/* wrap the master secret, and put it into the SID.
+ * Caller holds the Spec read lock.
+ */
+SECStatus
+ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
+ PK11SymKey *secret)
+{
+ PK11SymKey *wrappingKey = NULL;
+ PK11SlotInfo *symKeySlot;
+ void *pwArg = ss->pkcs11PinArg;
+ SECStatus rv = SECFailure;
+ PRBool isServer = ss->sec.isServer;
+ CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
+
+ symKeySlot = PK11_GetSlotFromKey(secret);
+ if (!isServer) {
+ int wrapKeyIndex;
+ int incarnation;
+
+ /* these next few functions are mere accessors and don't fail. */
+ sid->u.ssl3.masterWrapIndex = wrapKeyIndex =
+ PK11_GetCurrentWrapIndex(symKeySlot);
+ PORT_Assert(wrapKeyIndex == 0); /* array has only one entry! */
+
+ sid->u.ssl3.masterWrapSeries = incarnation =
+ PK11_GetSlotSeries(symKeySlot);
+ sid->u.ssl3.masterSlotID = PK11_GetSlotID(symKeySlot);
+ sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
+ sid->u.ssl3.masterValid = PR_TRUE;
+ /* Get the default wrapping key, for wrapping the master secret before
+ * placing it in the SID cache entry. */
+ wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
+ CKM_INVALID_MECHANISM, incarnation,
+ pwArg);
+ if (wrappingKey) {
+ mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
+ } else {
+ int keyLength;
+ /* if the wrappingKey doesn't exist, attempt to create it.
+ * Note: we intentionally ignore errors here. If we cannot
+ * generate a wrapping key, it is not fatal to this SSL connection,
+ * but we will not be able to restart this session.
+ */
+ mechanism = PK11_GetBestWrapMechanism(symKeySlot);
+ keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
+ /* Zero length means fixed key length algorithm, or error.
+ * It's ambiguous.
+ */
+ wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
+ keyLength, pwArg);
+ if (wrappingKey) {
+ /* The thread safety characteristics of PK11_[SG]etWrapKey is
+ * abominable. This protects against races in calling
+ * PK11_SetWrapKey by dropping and re-acquiring the canonical
+ * value once it is set. The mutex in PK11_[SG]etWrapKey will
+ * ensure that races produce the same value in the end. */
+ PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
+ PK11_FreeSymKey(wrappingKey);
+ wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
+ CKM_INVALID_MECHANISM, incarnation, pwArg);
+ if (!wrappingKey) {
+ PK11_FreeSlot(symKeySlot);
+ return SECFailure;
+ }
+ }
+ }
+ } else {
+ /* server socket using session cache. */
+ mechanism = PK11_GetBestWrapMechanism(symKeySlot);
+ if (mechanism != CKM_INVALID_MECHANISM) {
+ wrappingKey =
+ ssl3_GetWrappingKey(ss, symKeySlot, mechanism, pwArg);
+ if (wrappingKey) {
+ mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
+ }
+ }
+ }
+
+ sid->u.ssl3.masterWrapMech = mechanism;
+ PK11_FreeSlot(symKeySlot);
+
+ if (wrappingKey) {
+ SECItem wmsItem;
+
+ wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
+ wmsItem.len = sizeof sid->u.ssl3.keys.wrapped_master_secret;
+ rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
+ secret, &wmsItem);
+ /* rv is examined below. */
+ sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
+ PK11_FreeSymKey(wrappingKey);
+ }
+ return rv;
+}
+
+/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered
+ * a complete ssl3 Finished message from the peer.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv = SECSuccess;
+ PRBool isServer = ss->sec.isServer;
+ PRBool isTLS;
+ SSL3Hashes hashes;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
+ SSL_GETPID(), ss->fd));
+
+ if (ss->ssl3.hs.ws != wait_finished) {
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
+ return SECFailure;
+ }
+
+ if (!ss->sec.isServer || !ss->opt.requestCertificate) {
+ dtls_ReceivedFirstMessageInFlight(ss);
+ }
+
+ rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.crSpec, &hashes,
+ isServer ? sender_client : sender_server);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+
+ isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
+ if (isTLS) {
+ TLSFinished tlsFinished;
+
+ if (length != sizeof(tlsFinished)) {
+#ifndef UNSAFE_FUZZER_MODE
+ (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
+ return SECFailure;
+#endif
+ }
+ rv = ssl3_ComputeTLSFinished(ss, ss->ssl3.crSpec, !isServer,
+ &hashes, &tlsFinished);
+ if (!isServer)
+ ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
+ else
+ ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
+ ss->ssl3.hs.finishedBytes = sizeof(tlsFinished);
+ if (rv != SECSuccess ||
+ 0 != NSS_SecureMemcmp(&tlsFinished, b,
+ PR_MIN(length, ss->ssl3.hs.finishedBytes))) {
+#ifndef UNSAFE_FUZZER_MODE
+ (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
+ PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
+ return SECFailure;
+#endif
+ }
+ } else {
+ if (length != sizeof(SSL3Finished)) {
+ (void)ssl3_IllegalParameter(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
+ return SECFailure;
+ }
+
+ if (!isServer)
+ ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
+ else
+ ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
+ PORT_Assert(hashes.len == sizeof hashes.u.s);
+ ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
+ if (0 != NSS_SecureMemcmp(&hashes.u.s, b, length)) {
+ (void)ssl3_HandshakeFailure(ss);
+ PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
+ return SECFailure;
+ }
+ }
+
+ ssl_GetXmitBufLock(ss); /*************************************/
+
+ if ((isServer && !ss->ssl3.hs.isResuming) ||
+ (!isServer && ss->ssl3.hs.isResuming)) {
+ PRInt32 flags = 0;
+
+ /* Send a NewSessionTicket message if the client sent us
+ * either an empty session ticket, or one that did not verify.
+ * (Note that if either of these conditions was met, then the
+ * server has sent a SessionTicket extension in the
+ * ServerHello message.)
+ */
+ if (isServer && !ss->ssl3.hs.isResuming &&
+ ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) &&
+ ssl3_KEASupportsTickets(ss->ssl3.hs.kea_def)) {
+ /* RFC 5077 Section 3.3: "In the case of a full handshake, the
+ * server MUST verify the client's Finished message before sending
+ * the ticket." Presumably, this also means that the client's
+ * certificate, if any, must be verified beforehand too.
+ */
+ rv = ssl3_SendNewSessionTicket(ss);
+ if (rv != SECSuccess) {
+ goto xmit_loser;
+ }
+ }
+
+ rv = ssl3_SendChangeCipherSpecs(ss);
+ if (rv != SECSuccess) {
+ goto xmit_loser; /* err is set. */
+ }
+ /* If this thread is in SSL_SecureSend (trying to write some data)
+ ** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
+ ** last two handshake messages (change cipher spec and finished)
+ ** will be sent in the same send/write call as the application data.
+ */
+ if (ss->writerThread == PR_GetCurrentThread()) {
+ flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
+ }
+
+ if (!isServer && !ss->firstHsDone) {
+ rv = ssl3_SendNextProto(ss);
+ if (rv != SECSuccess) {
+ goto xmit_loser; /* err code was set. */
+ }
+ }
+
+ if (IS_DTLS(ss)) {
+ flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
+ }
+
+ rv = ssl3_SendFinished(ss, flags);
+ if (rv != SECSuccess) {
+ goto xmit_loser; /* err is set. */
+ }
+ }
+
+xmit_loser:
+ ssl_ReleaseXmitBufLock(ss); /*************************************/
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ if (ss->ssl3.hs.authCertificatePending) {
+ if (ss->ssl3.hs.restartTarget) {
+ PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+
+ rv = ssl3_FinishHandshake(ss);
+ return rv;
+}
+
+SECStatus
+ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid, PK11SymKey *secret)
+{
+ PORT_Assert(secret);
+
+ /* fill in the sid */
+ sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
+ sid->u.ssl3.policy = ss->ssl3.policy;
+ sid->version = ss->version;
+ sid->authType = ss->sec.authType;
+ sid->authKeyBits = ss->sec.authKeyBits;
+ sid->keaType = ss->sec.keaType;
+ sid->keaKeyBits = ss->sec.keaKeyBits;
+ if (ss->sec.keaGroup) {
+ sid->keaGroup = ss->sec.keaGroup->name;
+ } else {
+ sid->keaGroup = ssl_grp_none;
+ }
+ sid->sigScheme = ss->sec.signatureScheme;
+ sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
+ sid->expirationTime = sid->creationTime + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
+ sid->localCert = CERT_DupCertificate(ss->sec.localCert);
+ if (ss->sec.isServer) {
+ sid->namedCurve = ss->sec.serverCert->namedCurve;
+ }
+
+ if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
+ ss->xtnData.nextProto.data) {
+ SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
+ if (SECITEM_CopyItem(
+ NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) {
+ return SECFailure; /* error already set. */
+ }
+ }
+
+ /* Copy the master secret (wrapped or unwrapped) into the sid */
+ return ssl3_CacheWrappedSecret(ss, ss->sec.ci.sid, secret);
+}
+
+/* The return type is SECStatus instead of void because this function needs
+ * to have type sslRestartTarget.
+ */
+SECStatus
+ssl3_FinishHandshake(sslSocket *ss)
+{
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
+ sslSessionID *sid = ss->sec.ci.sid;
+ SECStatus sidRv = SECFailure;
+
+ /* The first handshake is now completed. */
+ ss->handshake = NULL;
+
+ if (sid->cached == never_cached && !ss->opt.noCache) {
+ /* If the wrap fails, don't cache the sid. The connection proceeds
+ * normally, so the rv is only used to determine whether we cache. */
+ sidRv = ssl3_FillInCachedSID(ss, sid, ss->ssl3.crSpec->masterSecret);
+ }
+
+ /* RFC 5077 Section 3.3: "The client MUST NOT treat the ticket as valid
+ * until it has verified the server's Finished message." When the server
+ * sends a NewSessionTicket in a resumption handshake, we must wait until
+ * the handshake is finished (we have verified the server's Finished
+ * AND the server's certificate) before we update the ticket in the sid.
+ *
+ * This must be done before we call ssl_CacheSessionID(ss)
+ * because CacheSID requires the session ticket to already be set, and also
+ * because of the lazy lock creation scheme used by CacheSID and
+ * ssl3_SetSIDSessionTicket. */
+ if (ss->ssl3.hs.receivedNewSessionTicket) {
+ PORT_Assert(!ss->sec.isServer);
+ if (sidRv == SECSuccess) {
+ /* The sid takes over the ticket data */
+ ssl3_SetSIDSessionTicket(ss->sec.ci.sid,
+ &ss->ssl3.hs.newSessionTicket);
+ } else {
+ PORT_Assert(ss->ssl3.hs.newSessionTicket.ticket.data);
+ SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket,
+ PR_FALSE);
+ }
+ PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data);
+ ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
+ }
+ if (sidRv == SECSuccess) {
+ PORT_Assert(ss->sec.ci.sid->cached == never_cached);
+ ssl_CacheSessionID(ss);
+ }
+
+ ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
+ ss->ssl3.hs.ws = idle_handshake;
+
+ return ssl_FinishHandshake(ss);
+}
+
+SECStatus
+ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType ct,
+ PRUint32 dtlsSeq,
+ const PRUint8 *b, PRUint32 length,
+ sslUpdateHandshakeHashes updateHashes)
+{
+ PRUint8 hdr[4];
+ PRUint8 dtlsData[8];
+ SECStatus rv;
+
+ PRINT_BUF(50, (ss, "Hash handshake message:", b, length));
+
+ hdr[0] = (PRUint8)ct;
+ hdr[1] = (PRUint8)(length >> 16);
+ hdr[2] = (PRUint8)(length >> 8);
+ hdr[3] = (PRUint8)(length);
+
+ rv = updateHashes(ss, (unsigned char *)hdr, 4);
+ if (rv != SECSuccess)
+ return rv; /* err code already set. */
+
+ /* Extra data to simulate a complete DTLS handshake fragment */
+ if (IS_DTLS(ss)) {
+ /* Sequence number */
+ dtlsData[0] = MSB(dtlsSeq);
+ dtlsData[1] = LSB(dtlsSeq);
+
+ /* Fragment offset */
+ dtlsData[2] = 0;
+ dtlsData[3] = 0;
+ dtlsData[4] = 0;
+
+ /* Fragment length */
+ dtlsData[5] = (PRUint8)(length >> 16);
+ dtlsData[6] = (PRUint8)(length >> 8);
+ dtlsData[7] = (PRUint8)(length);
+
+ rv = updateHashes(ss, (unsigned char *)dtlsData, sizeof(dtlsData));
+ if (rv != SECSuccess)
+ return rv; /* err code already set. */
+ }
+
+ /* The message body */
+ rv = updateHashes(ss, b, length);
+ if (rv != SECSuccess)
+ return rv; /* err code already set. */
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
+ const PRUint8 *b, PRUint32 length)
+{
+ return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
+ b, length, ssl3_UpdateHandshakeHashes);
+}
+
+SECStatus
+ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType ct,
+ const PRUint8 *b, PRUint32 length)
+{
+ return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
+ b, length, ssl3_UpdateDefaultHandshakeHashes);
+}
+SECStatus
+ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType ct,
+ const PRUint8 *b, PRUint32 length)
+{
+ return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
+ b, length, ssl3_UpdateInnerHandshakeHashes);
+}
+
+SECStatus
+ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType ct,
+ const PRUint8 *b, PRUint32 length)
+{
+ return ssl_HashHandshakeMessageInt(ss, ct, ss->ssl3.hs.recvMessageSeq,
+ b, length, ssl3_UpdatePostHandshakeHashes);
+}
+
+/* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
+ * handshake message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+SECStatus
+ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length,
+ PRBool endOfRecord)
+{
+ SECStatus rv = SECSuccess;
+ PRUint16 epoch;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
+ ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
+
+ /* Start new handshake hashes when we start a new handshake. */
+ if (ss->ssl3.hs.msg_type == ssl_hs_client_hello) {
+ ssl3_RestartHandshakeHashes(ss);
+ }
+ switch (ss->ssl3.hs.msg_type) {
+ case ssl_hs_hello_request:
+ case ssl_hs_hello_verify_request:
+ /* We don't include hello_request and hello_verify_request messages
+ * in the handshake hashes */
+ break;
+
+ /* Defer hashing of these messages until the message handlers. */
+ case ssl_hs_client_hello:
+ case ssl_hs_server_hello:
+ case ssl_hs_certificate_verify:
+ case ssl_hs_finished:
+ break;
+
+ default:
+ if (!tls13_IsPostHandshake(ss)) {
+ rv = ssl_HashHandshakeMessage(ss, ss->ssl3.hs.msg_type, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ }
+
+ PORT_SetError(0); /* each message starts with no error. */
+
+ if (ss->ssl3.hs.ws == wait_certificate_status &&
+ ss->ssl3.hs.msg_type != ssl_hs_certificate_status) {
+ /* If we negotiated the certificate_status extension then we deferred
+ * certificate validation until we get the CertificateStatus messsage.
+ * But the CertificateStatus message is optional. If the server did
+ * not send it then we need to validate the certificate now. If the
+ * server does send the CertificateStatus message then we will
+ * authenticate the certificate in ssl3_HandleCertificateStatus.
+ */
+ rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
+ if (rv != SECSuccess) {
+ /* This can't block. */
+ PORT_Assert(PORT_GetError() != PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+ }
+
+ epoch = ss->ssl3.crSpec->epoch;
+ switch (ss->ssl3.hs.msg_type) {
+ case ssl_hs_client_hello:
+ if (!ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
+ return SECFailure;
+ }
+ rv = ssl3_HandleClientHello(ss, b, length);
+ break;
+ case ssl_hs_server_hello:
+ if (ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
+ return SECFailure;
+ }
+ rv = ssl3_HandleServerHello(ss, b, length);
+ break;
+ default:
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = ssl3_HandlePostHelloHandshakeMessage(ss, b, length);
+ } else {
+ rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length);
+ }
+ break;
+ }
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ (epoch != ss->ssl3.crSpec->epoch) && !endOfRecord) {
+ /* If we changed read cipher states, there must not be any
+ * data in the input queue. */
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
+ return SECFailure;
+ }
+ /* We consider the record to have been handled if SECSuccess or else WOULD_BLOCK is set
+ * Whoever set WOULD_BLOCK must handle any remaining actions required to finsih processing the record.
+ * e.g. by setting restartTarget.
+ */
+ if (IS_DTLS(ss) && (rv == SECSuccess || (rv == SECFailure && PR_GetError() == PR_WOULD_BLOCK_ERROR))) {
+ /* Increment the expected sequence number */
+ ss->ssl3.hs.recvMessageSeq++;
+ }
+
+ /* Taint the message so that it's easier to detect UAFs. */
+ PORT_Memset(b, 'N', length);
+
+ return rv;
+}
+
+static SECStatus
+ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
+ PRUint32 length)
+{
+ SECStatus rv;
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ switch (ss->ssl3.hs.msg_type) {
+ case ssl_hs_hello_request:
+ if (length != 0) {
+ (void)ssl3_DecodeError(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
+ return SECFailure;
+ }
+ if (ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
+ return SECFailure;
+ }
+ rv = ssl3_HandleHelloRequest(ss);
+ break;
+
+ case ssl_hs_hello_verify_request:
+ if (!IS_DTLS(ss) || ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
+ return SECFailure;
+ }
+ rv = dtls_HandleHelloVerifyRequest(ss, b, length);
+ break;
+ case ssl_hs_certificate:
+ rv = ssl3_HandleCertificate(ss, b, length);
+ break;
+ case ssl_hs_certificate_status:
+ rv = ssl3_HandleCertificateStatus(ss, b, length);
+ break;
+ case ssl_hs_server_key_exchange:
+ if (ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
+ return SECFailure;
+ }
+ rv = ssl3_HandleServerKeyExchange(ss, b, length);
+ break;
+ case ssl_hs_certificate_request:
+ if (ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
+ return SECFailure;
+ }
+ rv = ssl3_HandleCertificateRequest(ss, b, length);
+ break;
+ case ssl_hs_server_hello_done:
+ if (length != 0) {
+ (void)ssl3_DecodeError(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
+ return SECFailure;
+ }
+ if (ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
+ return SECFailure;
+ }
+ rv = ssl3_HandleServerHelloDone(ss);
+ break;
+ case ssl_hs_certificate_verify:
+ if (!ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
+ return SECFailure;
+ }
+ rv = ssl3_HandleCertificateVerify(ss, b, length);
+ break;
+ case ssl_hs_client_key_exchange:
+ if (!ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
+ return SECFailure;
+ }
+ rv = ssl3_HandleClientKeyExchange(ss, b, length);
+ break;
+ case ssl_hs_new_session_ticket:
+ if (ss->sec.isServer) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+ rv = ssl3_HandleNewSessionTicket(ss, b, length);
+ break;
+ case ssl_hs_finished:
+ rv = ssl3_HandleFinished(ss, b, length);
+ break;
+ default:
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
+ rv = SECFailure;
+ }
+
+ return rv;
+}
+
+/* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
+ * origBuf is the decrypted ssl record content.
+ * Caller must hold the handshake and RecvBuf locks.
+ */
+static SECStatus
+ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
+{
+ sslBuffer buf = *origBuf; /* Work from a copy. */
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ while (buf.len > 0) {
+ if (ss->ssl3.hs.header_bytes < 4) {
+ PRUint8 t;
+ t = *(buf.buf++);
+ buf.len--;
+ if (ss->ssl3.hs.header_bytes++ == 0)
+ ss->ssl3.hs.msg_type = (SSLHandshakeType)t;
+ else
+ ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
+ if (ss->ssl3.hs.header_bytes < 4)
+ continue;
+
+#define MAX_HANDSHAKE_MSG_LEN 0x1ffff /* 128k - 1 */
+ if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
+ (void)ssl3_DecodeError(ss);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ goto loser;
+ }
+#undef MAX_HANDSHAKE_MSG_LEN
+
+ /* If msg_len is zero, be sure we fall through,
+ ** even if buf.len is zero.
+ */
+ if (ss->ssl3.hs.msg_len > 0)
+ continue;
+ }
+
+ /*
+ * Header has been gathered and there is at least one byte of new
+ * data available for this message. If it can be done right out
+ * of the original buffer, then use it from there.
+ */
+ if (ss->ssl3.hs.msg_body.len == 0 && buf.len >= ss->ssl3.hs.msg_len) {
+ /* handle it from input buffer */
+ rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len,
+ buf.len == ss->ssl3.hs.msg_len);
+ buf.buf += ss->ssl3.hs.msg_len;
+ buf.len -= ss->ssl3.hs.msg_len;
+ ss->ssl3.hs.msg_len = 0;
+ ss->ssl3.hs.header_bytes = 0;
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ /* must be copied to msg_body and dealt with from there */
+ unsigned int bytes;
+
+ PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
+ bytes = PR_MIN(buf.len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
+
+ /* Grow the buffer if needed */
+ rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
+ if (rv != SECSuccess) {
+ /* sslBuffer_Grow has set a memory error code. */
+ goto loser;
+ }
+
+ PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
+ buf.buf, bytes);
+ ss->ssl3.hs.msg_body.len += bytes;
+ buf.buf += bytes;
+ buf.len -= bytes;
+
+ PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
+
+ /* if we have a whole message, do it */
+ if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
+ rv = ssl3_HandleHandshakeMessage(
+ ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len,
+ buf.len == 0);
+ ss->ssl3.hs.msg_body.len = 0;
+ ss->ssl3.hs.msg_len = 0;
+ ss->ssl3.hs.header_bytes = 0;
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ PORT_Assert(buf.len == 0);
+ break;
+ }
+ }
+ } /* end loop */
+
+ origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
+ return SECSuccess;
+
+loser : {
+ /* Make sure to remove any data that was consumed. */
+ unsigned int consumed = origBuf->len - buf.len;
+ PORT_Assert(consumed == buf.buf - origBuf->buf);
+ if (consumed > 0) {
+ memmove(origBuf->buf, origBuf->buf + consumed, buf.len);
+ origBuf->len = buf.len;
+ }
+}
+ return SECFailure;
+}
+
+/* SECStatusToMask returns, in constant time, a mask value of all ones if
+ * rv == SECSuccess. Otherwise it returns zero. */
+static unsigned int
+SECStatusToMask(SECStatus rv)
+{
+ return PORT_CT_EQ(rv, SECSuccess);
+}
+
+/* ssl_ConstantTimeGE returns 0xffffffff if a>=b and 0x00 otherwise. */
+static unsigned char
+ssl_ConstantTimeGE(unsigned int a, unsigned int b)
+{
+ return PORT_CT_GE(a, b);
+}
+
+/* ssl_ConstantTimeEQ returns 0xffffffff if a==b and 0x00 otherwise. */
+static unsigned char
+ssl_ConstantTimeEQ(unsigned char a, unsigned char b)
+{
+ return PORT_CT_EQ(a, b);
+}
+
+/* ssl_constantTimeSelect return a if mask is 0xFF and b if mask is 0x00 */
+static unsigned char
+ssl_constantTimeSelect(unsigned char mask, unsigned char a, unsigned char b)
+{
+ return (mask & a) | (~mask & b);
+}
+
+static SECStatus
+ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
+ unsigned int blockSize,
+ unsigned int macSize)
+{
+ unsigned int paddingLength, good;
+ const unsigned int overhead = 1 /* padding length byte */ + macSize;
+
+ /* These lengths are all public so we can test them in non-constant
+ * time. */
+ if (overhead > plaintext->len) {
+ return SECFailure;
+ }
+
+ paddingLength = plaintext->buf[plaintext->len - 1];
+ /* SSLv3 padding bytes are random and cannot be checked. */
+ good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
+ /* SSLv3 requires that the padding is minimal. */
+ good &= PORT_CT_GE(blockSize, paddingLength + 1);
+ plaintext->len -= good & (paddingLength + 1);
+ return (good & SECSuccess) | (~good & SECFailure);
+}
+
+SECStatus
+ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
+{
+ unsigned int paddingLength, good, toCheck, i;
+ const unsigned int overhead = 1 /* padding length byte */ + macSize;
+
+ /* These lengths are all public so we can test them in non-constant
+ * time. */
+ if (overhead > plaintext->len) {
+ return SECFailure;
+ }
+
+ paddingLength = plaintext->buf[plaintext->len - 1];
+ good = PORT_CT_GE(plaintext->len, paddingLength + overhead);
+
+ /* The padding consists of a length byte at the end of the record and then
+ * that many bytes of padding, all with the same value as the length byte.
+ * Thus, with the length byte included, there are paddingLength+1 bytes of
+ * padding.
+ *
+ * We can't check just |paddingLength+1| bytes because that leaks
+ * decrypted information. Therefore we always have to check the maximum
+ * amount of padding possible. (Again, the length of the record is
+ * public information so we can use it.) */
+ toCheck = 256; /* maximum amount of padding + 1. */
+ if (toCheck > plaintext->len) {
+ toCheck = plaintext->len;
+ }
+
+ for (i = 0; i < toCheck; i++) {
+ /* If i <= paddingLength then the MSB of t is zero and mask is
+ * 0xff. Otherwise, mask is 0. */
+ unsigned char mask = PORT_CT_LE(i, paddingLength);
+ unsigned char b = plaintext->buf[plaintext->len - 1 - i];
+ /* The final |paddingLength+1| bytes should all have the value
+ * |paddingLength|. Therefore the XOR should be zero. */
+ good &= ~(mask & (paddingLength ^ b));
+ }
+
+ /* If any of the final |paddingLength+1| bytes had the wrong value,
+ * one or more of the lower eight bits of |good| will be cleared. We
+ * AND the bottom 8 bits together and duplicate the result to all the
+ * bits. */
+ good &= good >> 4;
+ good &= good >> 2;
+ good &= good >> 1;
+ good <<= sizeof(good) * 8 - 1;
+ good = PORT_CT_DUPLICATE_MSB_TO_ALL(good);
+
+ plaintext->len -= good & (paddingLength + 1);
+ return (good & SECSuccess) | (~good & SECFailure);
+}
+
+/* On entry:
+ * originalLength >= macSize
+ * macSize <= MAX_MAC_LENGTH
+ * plaintext->len >= macSize
+ */
+static void
+ssl_CBCExtractMAC(sslBuffer *plaintext,
+ unsigned int originalLength,
+ PRUint8 *out,
+ unsigned int macSize)
+{
+ unsigned char rotatedMac[MAX_MAC_LENGTH];
+ /* macEnd is the index of |plaintext->buf| just after the end of the
+ * MAC. */
+ unsigned macEnd = plaintext->len;
+ unsigned macStart = macEnd - macSize;
+ /* scanStart contains the number of bytes that we can ignore because
+ * the MAC's position can only vary by 255 bytes. */
+ unsigned scanStart = 0;
+ unsigned i, j;
+ unsigned char rotateOffset;
+
+ if (originalLength > macSize + 255 + 1) {
+ scanStart = originalLength - (macSize + 255 + 1);
+ }
+
+ /* We want to compute
+ * rotateOffset = (macStart - scanStart) % macSize
+ * But the time to compute this varies based on the amount of padding. Thus
+ * we explicitely handle all mac sizes with (hopefully) constant time modulo
+ * using Barrett reduction:
+ * q := (rotateOffset * m) >> k
+ * rotateOffset -= q * n
+ * if (n <= rotateOffset) rotateOffset -= n
+ */
+ rotateOffset = macStart - scanStart;
+ /* rotateOffset < 255 + 1 + 48 = 304 */
+ if (macSize == 16) {
+ rotateOffset &= 15;
+ } else if (macSize == 20) {
+ /*
+ * Correctness: rotateOffset * ( 1/20 - 25/2^9 ) < 1
+ * with rotateOffset <= 853
+ */
+ unsigned q = (rotateOffset * 25) >> 9;
+ rotateOffset -= q * 20;
+ rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 20),
+ 20, 0);
+ } else if (macSize == 32) {
+ rotateOffset &= 31;
+ } else if (macSize == 48) {
+ /*
+ * Correctness: rotateOffset * ( 1/48 - 10/2^9 ) < 1
+ * with rotateOffset < 768
+ */
+ unsigned q = (rotateOffset * 10) >> 9;
+ rotateOffset -= q * 48;
+ rotateOffset -= ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, 48),
+ 48, 0);
+ } else {
+ /*
+ * SHA384 (macSize == 48) is the largest we support. We should never
+ * get here.
+ */
+ PORT_Assert(0);
+ rotateOffset = rotateOffset % macSize;
+ }
+
+ memset(rotatedMac, 0, macSize);
+ for (i = scanStart; i < originalLength;) {
+ for (j = 0; j < macSize && i < originalLength; i++, j++) {
+ unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
+ unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
+ unsigned char b = 0;
+ b = plaintext->buf[i];
+ rotatedMac[j] |= b & macStarted & ~macEnded;
+ }
+ }
+
+ /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
+ * we could line-align |rotatedMac| and rotate in place. */
+ memset(out, 0, macSize);
+ rotateOffset = macSize - rotateOffset;
+ rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
+ 0, rotateOffset);
+ for (i = 0; i < macSize; i++) {
+ for (j = 0; j < macSize; j++) {
+ out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ(j, rotateOffset);
+ }
+ rotateOffset++;
+ rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize),
+ 0, rotateOffset);
+ }
+}
+
+/* MAX_EXPANSION is the amount by which a record might plausibly be expanded
+ * when protected. It's the worst case estimate, so the sum of block cipher
+ * padding (up to 256 octets), HMAC (48 octets for SHA-384), and IV (16
+ * octets for AES). */
+#define MAX_EXPANSION (256 + 48 + 16)
+
+/* Unprotect an SSL3 record and leave the result in plaintext.
+ *
+ * If SECFailure is returned, we:
+ * 1. Set |*alert| to the alert to be sent.
+ * 2. Call PORT_SetError() with an appropriate code.
+ *
+ * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
+ * Therefore, we MUST not call SSL3_SendAlert().
+ *
+ */
+static SECStatus
+ssl3_UnprotectRecord(sslSocket *ss,
+ ssl3CipherSpec *spec,
+ SSL3Ciphertext *cText, sslBuffer *plaintext,
+ SSL3AlertDescription *alert)
+{
+ const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
+ PRBool isTLS;
+ unsigned int good;
+ unsigned int ivLen = 0;
+ SSLContentType rType;
+ SSL3ProtocolVersion rVersion;
+ unsigned int minLength;
+ unsigned int originalLen = 0;
+ PRUint8 headerBuf[13];
+ sslBuffer header = SSL_BUFFER(headerBuf);
+ PRUint8 hash[MAX_MAC_LENGTH];
+ PRUint8 givenHashBuf[MAX_MAC_LENGTH];
+ PRUint8 *givenHash;
+ unsigned int hashBytes = MAX_MAC_LENGTH + 1;
+ SECStatus rv;
+
+ PORT_Assert(spec->direction == ssl_secret_read);
+
+ good = ~0U;
+ minLength = spec->macDef->mac_size;
+ if (cipher_def->type == type_block) {
+ /* CBC records have a padding length byte at the end. */
+ minLength++;
+ if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
+ /* With >= TLS 1.1, CBC records have an explicit IV. */
+ minLength += cipher_def->iv_size;
+ }
+ } else if (cipher_def->type == type_aead) {
+ minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
+ }
+
+ /* We can perform this test in variable time because the record's total
+ * length and the ciphersuite are both public knowledge. */
+ if (cText->buf->len < minLength) {
+ goto decrypt_loser;
+ }
+
+ if (cipher_def->type == type_block &&
+ spec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
+ /* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
+ * "The receiver decrypts the entire GenericBlockCipher structure and
+ * then discards the first cipher block corresponding to the IV
+ * component." Instead, we decrypt the first cipher block and then
+ * discard it before decrypting the rest.
+ */
+ PRUint8 iv[MAX_IV_LENGTH];
+ unsigned int decoded;
+
+ ivLen = cipher_def->iv_size;
+ if (ivLen < 8 || ivLen > sizeof(iv)) {
+ *alert = internal_error;
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
+
+ /* The decryption result is garbage, but since we just throw away
+ * the block it doesn't matter. The decryption of the next block
+ * depends only on the ciphertext of the IV block.
+ */
+ rv = spec->cipher(spec->cipherContext, iv, &decoded,
+ sizeof(iv), cText->buf->buf, ivLen);
+
+ good &= SECStatusToMask(rv);
+ }
+
+ PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
+ cText->buf->len - ivLen));
+
+ /* Check if the ciphertext can be valid if we assume maximum plaintext and
+ * add the maximum possible ciphersuite expansion.
+ * This way we detect overlong plaintexts/padding before decryption.
+ * This check enforces size limitations more strict than the RFC.
+ * [RFC5246, Section 6.2.3] */
+ if (cText->buf->len > (spec->recordSizeLimit + MAX_EXPANSION)) {
+ *alert = record_overflow;
+ PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+ return SECFailure;
+ }
+
+ isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
+ rType = (SSLContentType)cText->hdr[0];
+ rVersion = ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
+ (SSL3ProtocolVersion)cText->hdr[2];
+ if (cipher_def->type == type_aead) {
+ /* XXX For many AEAD ciphers, the plaintext is shorter than the
+ * ciphertext by a fixed byte count, but it is not true in general.
+ * Each AEAD cipher should provide a function that returns the
+ * plaintext length for a given ciphertext. */
+ const unsigned int explicitNonceLen = cipher_def->explicit_nonce_size;
+ const unsigned int tagLen = cipher_def->tag_size;
+ unsigned int nonceLen = explicitNonceLen;
+ unsigned int decryptedLen = cText->buf->len - nonceLen - tagLen;
+ /* even though read doesn't return and IV, we still need a space to put
+ * the combined iv/nonce n the gcm 1.2 case*/
+ unsigned char ivOut[MAX_IV_LENGTH];
+ unsigned char *iv = NULL;
+ unsigned char *nonce = NULL;
+
+ ivLen = cipher_def->iv_size;
+
+ rv = ssl3_BuildRecordPseudoHeader(
+ spec->epoch, cText->seqNum,
+ rType, isTLS, rVersion, IS_DTLS(ss), decryptedLen, &header);
+ PORT_Assert(rv == SECSuccess);
+
+ /* build the iv */
+ if (explicitNonceLen == 0) {
+ nonceLen = sizeof(cText->seqNum);
+ iv = spec->keyMaterial.iv;
+ nonce = SSL_BUFFER_BASE(&header);
+ } else {
+ PORT_Memcpy(ivOut, spec->keyMaterial.iv, ivLen);
+ PORT_Memset(ivOut + ivLen, 0, explicitNonceLen);
+ iv = ivOut;
+ nonce = cText->buf->buf;
+ nonceLen = explicitNonceLen;
+ }
+ rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
+ CKG_NO_GENERATE, 0, /* iv generator params
+ * (not used in decrypt)*/
+ iv, /* iv in */
+ NULL, /* iv out */
+ ivLen + explicitNonceLen, /* full iv length */
+ nonce, nonceLen, /* nonce in */
+ SSL_BUFFER_BASE(&header), /* aad */
+ SSL_BUFFER_LEN(&header), /* aadlen */
+ plaintext->buf, /* output */
+ &plaintext->len, /* out len */
+ plaintext->space, /* max out */
+ tagLen,
+ cText->buf->buf + explicitNonceLen, /* input */
+ cText->buf->len - explicitNonceLen); /* input len */
+ if (rv != SECSuccess) {
+ good = 0;
+ }
+ } else {
+ if (cipher_def->type == type_block &&
+ ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
+ goto decrypt_loser;
+ }
+
+ /* decrypt from cText buf to plaintext. */
+ rv = spec->cipher(
+ spec->cipherContext, plaintext->buf, &plaintext->len,
+ plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
+ if (rv != SECSuccess) {
+ goto decrypt_loser;
+ }
+
+ PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
+
+ originalLen = plaintext->len;
+
+ /* If it's a block cipher, check and strip the padding. */
+ if (cipher_def->type == type_block) {
+ const unsigned int blockSize = cipher_def->block_size;
+ const unsigned int macSize = spec->macDef->mac_size;
+
+ if (!isTLS) {
+ good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
+ plaintext, blockSize, macSize));
+ } else {
+ good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
+ plaintext, macSize));
+ }
+ }
+
+ /* compute the MAC */
+ rv = ssl3_BuildRecordPseudoHeader(
+ spec->epoch, cText->seqNum,
+ rType, isTLS, rVersion, IS_DTLS(ss),
+ plaintext->len - spec->macDef->mac_size, &header);
+ PORT_Assert(rv == SECSuccess);
+ if (cipher_def->type == type_block) {
+ rv = ssl3_ComputeRecordMACConstantTime(
+ spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
+ plaintext->buf, plaintext->len, originalLen,
+ hash, &hashBytes);
+
+ ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
+ spec->macDef->mac_size);
+ givenHash = givenHashBuf;
+
+ /* plaintext->len will always have enough space to remove the MAC
+ * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
+ * plaintext->len if the result has enough space for the MAC and we
+ * tested the unadjusted size against minLength, above. */
+ plaintext->len -= spec->macDef->mac_size;
+ } else {
+ /* This is safe because we checked the minLength above. */
+ plaintext->len -= spec->macDef->mac_size;
+
+ rv = ssl3_ComputeRecordMAC(
+ spec, SSL_BUFFER_BASE(&header), SSL_BUFFER_LEN(&header),
+ plaintext->buf, plaintext->len, hash, &hashBytes);
+
+ /* We can read the MAC directly from the record because its location
+ * is public when a stream cipher is used. */
+ givenHash = plaintext->buf + plaintext->len;
+ }
+
+ good &= SECStatusToMask(rv);
+
+ if (hashBytes != (unsigned)spec->macDef->mac_size ||
+ NSS_SecureMemcmp(givenHash, hash, spec->macDef->mac_size) != 0) {
+ /* We're allowed to leak whether or not the MAC check was correct */
+ good = 0;
+ }
+ }
+
+ if (good == 0) {
+ decrypt_loser:
+ /* always log mac error, in case attacker can read server logs. */
+ PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+ *alert = bad_record_mac;
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
+ DTLSEpoch epoch, sslSequenceNumber seqNum,
+ sslBuffer *databuf)
+{
+ SECStatus rv;
+
+ /* check for Token Presence */
+ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
+ PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
+ return SECFailure;
+ }
+
+ ssl_GetSSL3HandshakeLock(ss);
+
+ /* All the functions called in this switch MUST set error code if
+ ** they return SECFailure.
+ */
+ switch (rType) {
+ case ssl_ct_change_cipher_spec:
+ rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
+ break;
+ case ssl_ct_alert:
+ rv = ssl3_HandleAlert(ss, databuf);
+ break;
+ case ssl_ct_handshake:
+ if (!IS_DTLS(ss)) {
+ rv = ssl3_HandleHandshake(ss, databuf);
+ } else {
+ rv = dtls_HandleHandshake(ss, epoch, seqNum, databuf);
+ }
+ break;
+ case ssl_ct_ack:
+ if (IS_DTLS(ss) && tls13_MaybeTls13(ss)) {
+ rv = dtls13_HandleAck(ss, databuf);
+ break;
+ }
+ /* Fall through. */
+ default:
+ /* If a TLS implementation receives an unexpected record type,
+ * it MUST terminate the connection with an "unexpected_message"
+ * alert [RFC8446, Section 5].
+ *
+ * For TLS 1.3 the outer content type is checked before in
+ * tls13con.c/tls13_UnprotectRecord(),
+ * For DTLS 1.3 the outer content type is checked before in
+ * ssl3gthr.c/dtls_GatherData.
+ * The inner content types will be checked here.
+ *
+ * In DTLS generally invalid records SHOULD be silently discarded,
+ * no alert is sent [RFC6347, Section 4.1.2.7].
+ */
+ if (!IS_DTLS(ss)) {
+ SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ }
+ PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
+ SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
+ SSL_GETPID(), ss->fd, rType));
+ rv = SECFailure;
+ break;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ return rv;
+}
+
+/* Find the cipher spec to use for a given record. For TLS, this
+ * is the current cipherspec. For DTLS, we look up by epoch.
+ * In DTLS < 1.3 this just means the current epoch or nothing,
+ * but in DTLS >= 1.3, we keep multiple reading cipherspecs.
+ * Returns NULL if no appropriate cipher spec is found.
+ */
+static ssl3CipherSpec *
+ssl3_GetCipherSpec(sslSocket *ss, SSL3Ciphertext *cText)
+{
+ ssl3CipherSpec *crSpec = ss->ssl3.crSpec;
+ ssl3CipherSpec *newSpec = NULL;
+ DTLSEpoch epoch;
+
+ if (!IS_DTLS(ss)) {
+ return crSpec;
+ }
+ epoch = dtls_ReadEpoch(crSpec, cText->hdr);
+ if (crSpec->epoch == epoch) {
+ return crSpec;
+ }
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ /* Try to find the cipher spec. */
+ newSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_read,
+ epoch);
+ if (newSpec != NULL) {
+ return newSpec;
+ }
+ }
+ SSL_TRC(10, ("%d: DTLS[%d]: Couldn't find cipherspec from epoch %d",
+ SSL_GETPID(), ss->fd, epoch));
+ return NULL;
+}
+
+/* if cText is non-null, then decipher and check the MAC of the
+ * SSL record from cText->buf (typically gs->inbuf)
+ * into databuf (typically gs->buf), and any previous contents of databuf
+ * is lost. Then handle databuf according to its SSL record type,
+ * unless it's an application record.
+ *
+ * If cText is NULL, then the ciphertext has previously been deciphered and
+ * checked, and is already sitting in databuf. It is processed as an SSL
+ * Handshake message.
+ *
+ * DOES NOT process the decrypted application data.
+ * On return, databuf contains the decrypted record.
+ *
+ * Called from ssl3_GatherCompleteHandshake
+ * ssl3_RestartHandshakeAfterCertReq
+ *
+ * Caller must hold the RecvBufLock.
+ *
+ * This function aquires and releases the SSL3Handshake Lock, holding the
+ * lock around any calls to functions that handle records other than
+ * Application Data records.
+ */
+SECStatus
+ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText)
+{
+ SECStatus rv = SECFailure;
+ PRBool isTLS, isTLS13;
+ DTLSEpoch epoch;
+ ssl3CipherSpec *spec = NULL;
+ PRUint16 recordSizeLimit, cTextSizeLimit;
+ PRBool outOfOrderSpec = PR_FALSE;
+ SSLContentType rType;
+ sslBuffer *plaintext = &ss->gs.buf;
+ SSL3AlertDescription alert = internal_error;
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+
+ /* check for Token Presence */
+ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
+ PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
+ return SECFailure;
+ }
+
+ /* Clear out the buffer in case this exits early. Any data then won't be
+ * processed twice. */
+ plaintext->len = 0;
+
+ /* We're waiting for another ClientHello, which will appear unencrypted.
+ * Use the content type to tell whether this should be discarded. */
+ if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr &&
+ cText->hdr[0] == ssl_ct_application_data) {
+ PORT_Assert(ss->ssl3.hs.ws == wait_client_hello);
+ return SECSuccess;
+ }
+
+ ssl_GetSpecReadLock(ss); /******************************************/
+ spec = ssl3_GetCipherSpec(ss, cText);
+ if (!spec) {
+ PORT_Assert(IS_DTLS(ss));
+ ssl_ReleaseSpecReadLock(ss); /*****************************/
+ return SECSuccess;
+ }
+ if (spec != ss->ssl3.crSpec) {
+ PORT_Assert(IS_DTLS(ss));
+ SSL_TRC(3, ("%d: DTLS[%d]: Handling out-of-epoch record from epoch=%d",
+ SSL_GETPID(), ss->fd, spec->epoch));
+ outOfOrderSpec = PR_TRUE;
+ }
+ isTLS = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
+ if (IS_DTLS(ss)) {
+ if (dtls13_MaskSequenceNumber(ss, spec, cText->hdr,
+ SSL_BUFFER_BASE(cText->buf), SSL_BUFFER_LEN(cText->buf)) != SECSuccess) {
+ ssl_ReleaseSpecReadLock(ss); /*****************************/
+ /* code already set. */
+ return SECFailure;
+ }
+ if (!dtls_IsRelevant(ss, spec, cText, &cText->seqNum)) {
+ ssl_ReleaseSpecReadLock(ss); /*****************************/
+ return SECSuccess;
+ }
+ } else {
+ cText->seqNum = spec->nextSeqNum;
+ }
+ if (cText->seqNum >= spec->cipherDef->max_records) {
+ ssl_ReleaseSpecReadLock(ss); /*****************************/
+ SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx",
+ SSL_GETPID(), ss->fd, cText->seqNum));
+ PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS);
+ return SECFailure;
+ }
+
+ isTLS13 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ recordSizeLimit = spec->recordSizeLimit;
+ cTextSizeLimit = recordSizeLimit;
+ cTextSizeLimit += (isTLS13) ? TLS_1_3_MAX_EXPANSION : TLS_1_2_MAX_EXPANSION;
+
+ /* Check if the specified recordSizeLimit and the RFC8446 specified max
+ * expansion are respected. recordSizeLimit is probably at the default for
+ * the first (hello) handshake message and then set to a smaller size by
+ * the Record Size Limit Extension.
+ * Stricter expansion size checks dependent on implemented cipher suites
+ * are performed in ssl3con.c/ssl3_UnprotectRecord() OR
+ * tls13con.c/tls13_UnprotextRecord().
+ * After Decryption the plaintext size is checked (l. 13424). This also
+ * applies to unencrypted records. */
+ if (cText->buf->len > cTextSizeLimit) {
+ ssl_ReleaseSpecReadLock(ss); /*****************************/
+ /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
+ if (IS_DTLS(ss)) {
+ return SECSuccess;
+ }
+ SSL3_SendAlert(ss, alert_fatal, record_overflow);
+ PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+ return SECFailure;
+ }
+
+#ifdef DEBUG
+ /* In debug builds the gather buffers are freed after the handling of each
+ * record for advanced ASAN coverage. Allocate the buffer again to the
+ * maximum possibly needed size as on gather initialization in
+ * ssl3gthr.c/ssl3_InitGather(). */
+ PR_ASSERT(sslBuffer_Grow(plaintext, TLS_1_2_MAX_CTEXT_LENGTH) == SECSuccess);
+#endif
+ /* This replaces a dynamic plaintext buffer size check, since the buffer is
+ * allocated to the maximum size in ssl3gthr.c/ssl3_InitGather(). The buffer
+ * was always grown to the maximum size at first record gathering before. */
+ PR_ASSERT(plaintext->space >= cTextSizeLimit);
+
+ /* Most record types aside from protected TLS 1.3 records carry the content
+ * type in the first octet. TLS 1.3 will override this value later. */
+ rType = cText->hdr[0];
+ /* Encrypted application data records could arrive before the handshake
+ * completes in DTLS 1.3. These can look like valid TLS 1.2 application_data
+ * records in epoch 0, which is never valid. Pretend they didn't decrypt. */
+ if (spec->epoch == 0 && ((IS_DTLS(ss) &&
+ dtls_IsDtls13Ciphertext(0, rType)) ||
+ rType == ssl_ct_application_data)) {
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
+ alert = unexpected_message;
+ rv = SECFailure;
+ } else {
+#ifdef UNSAFE_FUZZER_MODE
+ rv = Null_Cipher(NULL, plaintext->buf, &plaintext->len,
+ plaintext->space, cText->buf->buf, cText->buf->len);
+#else
+ /* IMPORTANT:
+ * Unprotect functions MUST NOT send alerts
+ * because we still hold the spec read lock. Instead, if they
+ * return SECFailure, they set *alert to the alert to be sent.
+ * Additionaly, this is used to silently drop DTLS encryption/record
+ * errors/alerts using the error handling below as suggested in the
+ * DTLS specification [RFC6347, Section 4.1.2.7]. */
+ if (spec->cipherDef->cipher == cipher_null && cText->buf->len == 0) {
+ /* Handle a zero-length unprotected record
+ * In this case, we treat it as a no-op and let later functions decide
+ * whether to ignore or alert accordingly. */
+ PR_ASSERT(plaintext->len == 0);
+ rv = SECSuccess;
+ } else if (spec->version < SSL_LIBRARY_VERSION_TLS_1_3 || spec->epoch == 0) {
+ rv = ssl3_UnprotectRecord(ss, spec, cText, plaintext, &alert);
+ } else {
+ rv = tls13_UnprotectRecord(ss, spec, cText, plaintext, &rType,
+ &alert);
+ }
+#endif
+ }
+
+ /* Error/Alert handling for ssl3/tls13_UnprotectRecord */
+ if (rv != SECSuccess) {
+ ssl_ReleaseSpecReadLock(ss); /***************************/
+
+ SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
+
+ /* Ensure that we don't process this data again. */
+ plaintext->len = 0;
+
+ /* Ignore a CCS if compatibility mode is negotiated. Note that this
+ * will fail if the server fails to negotiate compatibility mode in a
+ * 0-RTT session that is resumed from a session that did negotiate it.
+ * We don't care about that corner case right now. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ cText->hdr[0] == ssl_ct_change_cipher_spec &&
+ ss->ssl3.hs.ws != idle_handshake &&
+ cText->buf->len == 1 &&
+ cText->buf->buf[0] == change_cipher_spec_choice) {
+ if (!ss->ssl3.hs.rejectCcs) {
+ /* Allow only the first CCS. */
+ ss->ssl3.hs.rejectCcs = PR_TRUE;
+ return SECSuccess;
+ } else {
+ alert = unexpected_message;
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
+ }
+ }
+
+ /* All errors/alerts that might occur during unprotection are related
+ * to invalid records (e.g. invalid formatting, length, MAC, ...).
+ * Following the DTLS specification such errors/alerts SHOULD be
+ * dropped silently [RFC6347, Section 4.1.2.7].
+ * This is done below. */
+ if ((IS_DTLS(ss) && !dtls13_AeadLimitReached(spec)) ||
+ (!IS_DTLS(ss) && ss->sec.isServer &&
+ ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) {
+ /* Silently drop the packet unless we set ss->ssl3.fatalAlertSent.
+ * (Manually or by using functions like
+ * SSL3_SendAlert(.., alert_fatal,..))
+ * This is not currently used in the unprotection functions since
+ * all TLS and DTLS errors are propagated to this handler. */
+ if (ss->ssl3.fatalAlertSent) {
+ return SECFailure;
+ }
+ return SECSuccess;
+ }
+
+ int errCode = PORT_GetError();
+ SSL3_SendAlert(ss, alert_fatal, alert);
+ /* Reset the error code in case SSL3_SendAlert called
+ * PORT_SetError(). */
+ PORT_SetError(errCode);
+ return SECFailure;
+ }
+
+ /* SECSuccess */
+ if (IS_DTLS(ss)) {
+ dtls_RecordSetRecvd(&spec->recvdRecords, cText->seqNum);
+ spec->nextSeqNum = PR_MAX(spec->nextSeqNum, cText->seqNum + 1);
+ } else {
+ ++spec->nextSeqNum;
+ }
+ epoch = spec->epoch;
+
+ ssl_ReleaseSpecReadLock(ss); /*****************************************/
+
+ /*
+ * The decrypted data is now in plaintext.
+ */
+
+ /* IMPORTANT: We are in DTLS 1.3 mode and we have processed something
+ * from the wrong epoch. Divert to a divert processing function to make
+ * sure we don't accidentally use the data unsafely. */
+ if (outOfOrderSpec) {
+ PORT_Assert(IS_DTLS(ss) && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ return dtls13_HandleOutOfEpochRecord(ss, spec, rType, plaintext);
+ }
+
+ /* Check the length of the plaintext. */
+ if (isTLS && plaintext->len > recordSizeLimit) {
+ plaintext->len = 0;
+ /* Drop DTLS Record Errors silently [RFC6347, Section 4.1.2.7] */
+ if (IS_DTLS(ss)) {
+ return SECSuccess;
+ }
+ SSL3_SendAlert(ss, alert_fatal, record_overflow);
+ PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+ return SECFailure;
+ }
+
+ /* Application data records are processed by the caller of this
+ ** function, not by this function.
+ */
+ if (rType == ssl_ct_application_data) {
+ if (ss->firstHsDone)
+ return SECSuccess;
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ ss->sec.isServer &&
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ return tls13_HandleEarlyApplicationData(ss, plaintext);
+ }
+ plaintext->len = 0;
+ (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
+ return SECFailure;
+ }
+
+ rv = ssl3_HandleNonApplicationData(ss, rType, epoch, cText->seqNum,
+ plaintext);
+
+#ifdef DEBUG
+ /* In Debug builds free and zero gather plaintext buffer after its content
+ * has been used/copied for advanced ASAN coverage/utilization.
+ * This frees buffer for non application data records, for application data
+ * records it is freed in sslsecur.c/DoRecv(). */
+ sslBuffer_Clear(&ss->gs.buf);
+#endif
+
+ return rv;
+}
+
+/*
+ * Initialization functions
+ */
+
+void
+ssl_InitSecState(sslSecurityInfo *sec)
+{
+ sec->authType = ssl_auth_null;
+ sec->authKeyBits = 0;
+ sec->signatureScheme = ssl_sig_none;
+ sec->keaType = ssl_kea_null;
+ sec->keaKeyBits = 0;
+ sec->keaGroup = NULL;
+}
+
+SECStatus
+ssl3_InitState(sslSocket *ss)
+{
+ SECStatus rv;
+
+ ss->ssl3.policy = SSL_ALLOWED;
+
+ ssl_InitSecState(&ss->sec);
+
+ ssl_GetSpecWriteLock(ss);
+ PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
+ rv = ssl_SetupNullCipherSpec(ss, ssl_secret_read);
+ rv |= ssl_SetupNullCipherSpec(ss, ssl_secret_write);
+ ss->ssl3.pwSpec = ss->ssl3.prSpec = NULL;
+ ssl_ReleaseSpecWriteLock(ss);
+ if (rv != SECSuccess) {
+ /* Rely on ssl_CreateNullCipherSpec() to set error code. */
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.sendingSCSV = PR_FALSE;
+ ss->ssl3.hs.preliminaryInfo = 0;
+ ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : idle_handshake;
+
+ ssl3_ResetExtensionData(&ss->xtnData, ss);
+ PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
+ PR_INIT_CLIST(&ss->ssl3.hs.echOuterExtensions);
+ if (IS_DTLS(ss)) {
+ ss->ssl3.hs.sendMessageSeq = 0;
+ ss->ssl3.hs.recvMessageSeq = 0;
+ ss->ssl3.hs.rtTimer->timeout = DTLS_RETRANSMIT_INITIAL_MS;
+ ss->ssl3.hs.rtRetries = 0;
+ ss->ssl3.hs.recvdHighWater = -1;
+ PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
+ dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
+ }
+
+ ss->ssl3.hs.currentSecret = NULL;
+ ss->ssl3.hs.resumptionMasterSecret = NULL;
+ ss->ssl3.hs.dheSecret = NULL;
+ ss->ssl3.hs.clientEarlyTrafficSecret = NULL;
+ ss->ssl3.hs.clientHsTrafficSecret = NULL;
+ ss->ssl3.hs.serverHsTrafficSecret = NULL;
+ ss->ssl3.hs.clientTrafficSecret = NULL;
+ ss->ssl3.hs.serverTrafficSecret = NULL;
+ ss->ssl3.hs.echHpkeCtx = NULL;
+ ss->ssl3.hs.greaseEchSize = 100;
+ ss->ssl3.hs.echAccepted = PR_FALSE;
+ ss->ssl3.hs.echDecided = PR_FALSE;
+
+ ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
+ ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
+
+ PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
+ ss->ssl3.hs.messages.buf = NULL;
+ ss->ssl3.hs.messages.space = 0;
+
+ ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE;
+ PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0,
+ sizeof(ss->ssl3.hs.newSessionTicket));
+
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
+
+ return SECSuccess;
+}
+
+/* record the export policy for this cipher suite */
+SECStatus
+ssl3_SetPolicy(ssl3CipherSuite which, int policy)
+{
+ ssl3CipherSuiteCfg *suite;
+
+ suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
+ if (suite == NULL) {
+ return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
+ }
+ suite->policy = policy;
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
+{
+ const ssl3CipherSuiteCfg *suite;
+ PRInt32 policy;
+ SECStatus rv;
+
+ suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
+ if (suite) {
+ policy = suite->policy;
+ rv = SECSuccess;
+ } else {
+ policy = SSL_NOT_ALLOWED;
+ rv = SECFailure; /* err code was set by Lookup. */
+ }
+ *oPolicy = policy;
+ return rv;
+}
+
+/* record the user preference for this suite */
+SECStatus
+ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
+{
+ ssl3CipherSuiteCfg *suite;
+
+ suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites);
+ if (suite == NULL) {
+ return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
+ }
+ suite->enabled = enabled;
+ return SECSuccess;
+}
+
+/* return the user preference for this suite */
+SECStatus
+ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
+{
+ const ssl3CipherSuiteCfg *suite;
+ PRBool pref;
+ SECStatus rv;
+
+ suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
+ if (suite) {
+ pref = suite->enabled;
+ rv = SECSuccess;
+ } else {
+ pref = SSL_NOT_ALLOWED;
+ rv = SECFailure; /* err code was set by Lookup. */
+ }
+ *enabled = pref;
+ return rv;
+}
+
+SECStatus
+ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
+{
+ ssl3CipherSuiteCfg *suite;
+
+ suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites);
+ if (suite == NULL) {
+ return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
+ }
+ suite->enabled = enabled;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
+{
+ const ssl3CipherSuiteCfg *suite;
+ PRBool pref;
+ SECStatus rv;
+
+ suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
+ if (suite) {
+ pref = suite->enabled;
+ rv = SECSuccess;
+ } else {
+ pref = SSL_NOT_ALLOWED;
+ rv = SECFailure; /* err code was set by Lookup. */
+ }
+ *enabled = pref;
+ return rv;
+}
+
+SECStatus
+SSL_SignatureSchemePrefSet(PRFileDesc *fd, const SSLSignatureScheme *schemes,
+ unsigned int count)
+{
+ sslSocket *ss;
+ unsigned int i;
+ unsigned int supported = 0;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!count) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ for (i = 0; i < count; ++i) {
+ if (ssl_IsSupportedSignatureScheme(schemes[i])) {
+ ++supported;
+ }
+ }
+ /* We don't check for duplicates, so it's possible to get too many. */
+ if (supported > MAX_SIGNATURE_SCHEMES) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss->ssl3.signatureSchemeCount = 0;
+ for (i = 0; i < count; ++i) {
+ if (!ssl_IsSupportedSignatureScheme(schemes[i])) {
+ SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored",
+ SSL_GETPID(), fd, schemes[i]));
+ continue;
+ }
+
+ ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i];
+ }
+
+ if (ss->ssl3.signatureSchemeCount == 0) {
+ PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms,
+ unsigned int count)
+{
+ SSLSignatureScheme schemes[MAX_SIGNATURE_SCHEMES];
+ unsigned int i;
+
+ count = PR_MIN(PR_ARRAY_SIZE(schemes), count);
+ for (i = 0; i < count; ++i) {
+ schemes[i] = (algorithms[i].hashAlg << 8) | algorithms[i].sigAlg;
+ }
+ return SSL_SignatureSchemePrefSet(fd, schemes, count);
+}
+
+SECStatus
+SSL_SignatureSchemePrefGet(PRFileDesc *fd, SSLSignatureScheme *schemes,
+ unsigned int *count, unsigned int maxCount)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefGet",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!schemes || !count ||
+ maxCount < ss->ssl3.signatureSchemeCount) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ PORT_Memcpy(schemes, ss->ssl3.signatureSchemes,
+ ss->ssl3.signatureSchemeCount * sizeof(SSLSignatureScheme));
+ *count = ss->ssl3.signatureSchemeCount;
+ return SECSuccess;
+}
+
+SECStatus
+SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms,
+ unsigned int *count, unsigned int maxCount)
+{
+ sslSocket *ss;
+ unsigned int i;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignaturePrefGet",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!algorithms || !count ||
+ maxCount < ss->ssl3.signatureSchemeCount) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) {
+ algorithms[i].hashAlg = (ss->ssl3.signatureSchemes[i] >> 8) & 0xff;
+ algorithms[i].sigAlg = ss->ssl3.signatureSchemes[i] & 0xff;
+ }
+ *count = ss->ssl3.signatureSchemeCount;
+ return SECSuccess;
+}
+
+unsigned int
+SSL_SignatureMaxCount(void)
+{
+ return MAX_SIGNATURE_SCHEMES;
+}
+
+/* copy global default policy into socket. */
+void
+ssl3_InitSocketPolicy(sslSocket *ss)
+{
+ PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof(cipherSuites));
+ PORT_Memcpy(ss->ssl3.signatureSchemes, defaultSignatureSchemes,
+ sizeof(defaultSignatureSchemes));
+ ss->ssl3.signatureSchemeCount = PR_ARRAY_SIZE(defaultSignatureSchemes);
+}
+
+/*
+** If ssl3 socket has completed the first handshake, and is in idle state,
+** then start a new handshake.
+** If flushCache is true, the SID cache will be flushed first, forcing a
+** "Full" handshake (not a session restart handshake), to be done.
+**
+** called from SSL_RedoHandshake(), which already holds the handshake locks.
+*/
+SECStatus
+ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
+{
+ sslSessionID *sid = ss->sec.ci.sid;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (!ss->firstHsDone || (ss->ssl3.hs.ws != idle_handshake)) {
+ PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
+ return SECFailure;
+ }
+
+ if (IS_DTLS(ss)) {
+ dtls_RehandshakeCleanup(ss);
+ }
+
+ if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER ||
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
+ return SECFailure;
+ }
+ if (ss->version > ss->vrange.max || ss->version < ss->vrange.min) {
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
+ return SECFailure;
+ }
+
+ if (sid && flushCache) {
+ ssl_UncacheSessionID(ss); /* remove it from whichever cache it's in. */
+ ssl_FreeSID(sid); /* dec ref count and free if zero. */
+ ss->sec.ci.sid = NULL;
+ }
+
+ ssl_GetXmitBufLock(ss); /**************************************/
+
+ /* start off a new handshake. */
+ if (ss->sec.isServer) {
+ rv = ssl3_SendHelloRequest(ss);
+ } else {
+ rv = ssl3_SendClientHello(ss, client_hello_renegotiation);
+ }
+
+ ssl_ReleaseXmitBufLock(ss); /**************************************/
+ return rv;
+}
+
+/* Called from ssl_DestroySocketContents() in sslsock.c */
+void
+ssl3_DestroySSL3Info(sslSocket *ss)
+{
+
+ if (ss->ssl3.clientCertificate != NULL)
+ CERT_DestroyCertificate(ss->ssl3.clientCertificate);
+
+ if (ss->ssl3.clientPrivateKey != NULL)
+ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
+
+ if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
+ PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
+ ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
+ ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
+ }
+
+ if (ss->ssl3.peerCertArena != NULL)
+ ssl3_CleanupPeerCerts(ss);
+
+ if (ss->ssl3.clientCertChain != NULL) {
+ CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
+ ss->ssl3.clientCertChain = NULL;
+ }
+ if (ss->ssl3.ca_list) {
+ CERT_FreeDistNames(ss->ssl3.ca_list);
+ }
+
+ /* clean up handshake */
+ if (ss->ssl3.hs.md5) {
+ PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
+ }
+ if (ss->ssl3.hs.sha) {
+ PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE);
+ }
+ if (ss->ssl3.hs.shaEchInner) {
+ PK11_DestroyContext(ss->ssl3.hs.shaEchInner, PR_TRUE);
+ }
+ if (ss->ssl3.hs.shaPostHandshake) {
+ PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
+ }
+ if (ss->ssl3.hs.messages.buf) {
+ sslBuffer_Clear(&ss->ssl3.hs.messages);
+ }
+ if (ss->ssl3.hs.echInnerMessages.buf) {
+ sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
+ }
+
+ /* free the SSL3Buffer (msg_body) */
+ PORT_Free(ss->ssl3.hs.msg_body.buf);
+
+ SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE);
+ SECITEM_FreeItem(&ss->ssl3.hs.srvVirtName, PR_FALSE);
+ SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
+
+ /* Destroy the DTLS data */
+ if (IS_DTLS(ss)) {
+ dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
+ if (ss->ssl3.hs.recvdFragments.buf) {
+ PORT_Free(ss->ssl3.hs.recvdFragments.buf);
+ }
+ }
+
+ /* Destroy remote extensions */
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
+ ssl3_DestroyExtensionData(&ss->xtnData);
+
+ /* Destroy cipher specs */
+ ssl_DestroyCipherSpecs(&ss->ssl3.hs.cipherSpecs);
+
+ /* Destroy TLS 1.3 keys */
+ if (ss->ssl3.hs.currentSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
+ if (ss->ssl3.hs.resumptionMasterSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret);
+ if (ss->ssl3.hs.dheSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
+ if (ss->ssl3.hs.clientEarlyTrafficSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.clientEarlyTrafficSecret);
+ if (ss->ssl3.hs.clientHsTrafficSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
+ if (ss->ssl3.hs.serverHsTrafficSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
+ if (ss->ssl3.hs.clientTrafficSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.clientTrafficSecret);
+ if (ss->ssl3.hs.serverTrafficSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.serverTrafficSecret);
+ if (ss->ssl3.hs.earlyExporterSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.earlyExporterSecret);
+ if (ss->ssl3.hs.exporterSecret)
+ PK11_FreeSymKey(ss->ssl3.hs.exporterSecret);
+
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
+ /* Destroy TLS 1.3 buffered early data. */
+ tls13_DestroyEarlyData(&ss->ssl3.hs.bufferedEarlyData);
+
+ /* Destroy TLS 1.3 PSKs. */
+ tls13_DestroyPskList(&ss->ssl3.hs.psks);
+
+ /* TLS 1.3 ECH state. */
+ PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
+ PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
+ sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
+
+ /* TLS 1.3 GREASE (client) state. */
+ tls13_ClientGreaseDestroy(ss);
+
+ /* TLS ClientHello Extension Permutation state. */
+ tls_ClientHelloExtensionPermutationDestroy(ss);
+}
+
+/* check if the current cipher spec is FIPS. We only need to
+ * check the contexts here, if the kea, prf or keys were not FIPS,
+ * that status would have been rolled up in the create context
+ * call */
+static PRBool
+ssl_cipherSpecIsFips(ssl3CipherSpec *spec)
+{
+ if (!spec || !spec->cipherDef) {
+ return PR_FALSE;
+ }
+
+ if (spec->cipherDef->type != type_aead) {
+ if (spec->keyMaterial.macContext == NULL) {
+ return PR_FALSE;
+ }
+ if (!PK11_ContextGetFIPSStatus(spec->keyMaterial.macContext)) {
+ return PR_FALSE;
+ }
+ }
+ if (!spec->cipherContext) {
+ return PR_FALSE;
+ }
+ return PK11_ContextGetFIPSStatus(spec->cipherContext);
+}
+
+/* return true if the current operation is running in FIPS mode */
+PRBool
+ssl_isFIPS(sslSocket *ss)
+{
+ if (!ssl_cipherSpecIsFips(ss->ssl3.crSpec)) {
+ return PR_FALSE;
+ }
+ return ssl_cipherSpecIsFips(ss->ssl3.cwSpec);
+}
+
+/*
+ * parse the policy value for a single algorithm in a cipher_suite,
+ * return TRUE if we disallow by the cipher suite by policy
+ * (we don't have to parse any more algorithm policies on this cipher suite),
+ * otherwise return FALSE.
+ * 1. If we don't have the required policy, disable by default, disallow by
+ * policy and return TRUE (no more processing needed).
+ * 2. If we have the required policy, and we are disabled, return FALSE,
+ * (if we are disabled, we only need to parse policy, not default).
+ * 3. If we have the required policy, and we aren't adjusting the defaults
+ * return FALSE. (only parsing the policy, not default).
+ * 4. We have the required policy and we are adjusting the defaults.
+ * If we are setting default = FALSE, set isDisabled to true so that
+ * we don't try to re-enable the cipher suite based on a different
+ * algorithm.
+ */
+PRBool
+ssl_HandlePolicy(int cipher_suite, SECOidTag policyOid,
+ PRUint32 requiredPolicy, PRBool *isDisabled)
+{
+ PRUint32 policy;
+ SECStatus rv;
+
+ /* first fetch the policy for this algorithm */
+ rv = NSS_GetAlgorithmPolicy(policyOid, &policy);
+ if (rv != SECSuccess) {
+ return PR_FALSE; /* no policy value, continue to the next algorithm */
+ }
+ /* first, are we allowed by policy, if not turn off allow and disable */
+ if (!(policy & requiredPolicy)) {
+ ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
+ ssl_CipherPolicySet(cipher_suite, SSL_NOT_ALLOWED);
+ return PR_TRUE;
+ }
+ /* If we are already disabled, or the policy isn't setting a default
+ * we are done processing this algorithm */
+ if (*isDisabled || (policy & NSS_USE_DEFAULT_NOT_VALID)) {
+ return PR_FALSE;
+ }
+ /* set the default value for the cipher suite. If we disable the cipher
+ * suite, remember that so we don't process the next default. This has
+ * the effect of disabling the whole cipher suite if any of the
+ * algorithms it uses are disabled by default. We still have to
+ * process the upper level because the cipher suite is still allowed
+ * by policy, and we may still have to disallow it based on other
+ * algorithms in the cipher suite. */
+ if (policy & NSS_USE_DEFAULT_SSL_ENABLE) {
+ ssl_CipherPrefSetDefault(cipher_suite, PR_TRUE);
+ } else {
+ *isDisabled = PR_TRUE;
+ ssl_CipherPrefSetDefault(cipher_suite, PR_FALSE);
+ }
+ return PR_FALSE;
+}
+
+#define MAP_NULL(x) (((x) != 0) ? (x) : SEC_OID_NULL_CIPHER)
+
+SECStatus
+ssl3_ApplyNSSPolicy(void)
+{
+ unsigned i;
+ SECStatus rv;
+ PRUint32 policy = 0;
+
+ rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
+ if (rv != SECSuccess || !(policy & NSS_USE_POLICY_IN_SSL)) {
+ return SECSuccess; /* do nothing */
+ }
+
+ /* disable every ciphersuite */
+ for (i = 1; i < PR_ARRAY_SIZE(cipher_suite_defs); ++i) {
+ const ssl3CipherSuiteDef *suite = &cipher_suite_defs[i];
+ SECOidTag policyOid;
+ PRBool isDisabled = PR_FALSE;
+
+ /* if we haven't explicitly disabled it below enable by policy */
+ ssl_CipherPolicySet(suite->cipher_suite, SSL_ALLOWED);
+
+ /* now check the various key exchange, ciphers and macs and
+ * if we ever disallow by policy, we are done, go to the next cipher
+ */
+ policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid);
+ if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
+ NSS_USE_ALG_IN_SSL_KX, &isDisabled)) {
+ continue;
+ }
+
+ policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid);
+ if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
+ NSS_USE_ALG_IN_SSL, &isDisabled)) {
+ continue;
+ }
+
+ if (ssl_GetBulkCipherDef(suite)->type != type_aead) {
+ policyOid = MAP_NULL(ssl_GetMacDefByAlg(suite->mac_alg)->oid);
+ if (ssl_HandlePolicy(suite->cipher_suite, policyOid,
+ NSS_USE_ALG_IN_SSL, &isDisabled)) {
+ continue;
+ }
+ }
+ }
+
+ rv = ssl3_ConstrainRangeByPolicy();
+
+ return rv;
+}
+
+/* End of ssl3con.c */
diff --git a/security/nss/lib/ssl/ssl3ecc.c b/security/nss/lib/ssl/ssl3ecc.c
new file mode 100644
index 0000000000..168ec59bf0
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3ecc.c
@@ -0,0 +1,965 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * SSL3 Protocol
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* ECC code moved here from ssl3con.c */
+
+#include "cert.h"
+#include "ssl.h"
+#include "cryptohi.h" /* for DSAU_ stuff */
+#include "keyhi.h"
+#include "secder.h"
+#include "secitem.h"
+
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "sslerr.h"
+#include "ssl3ext.h"
+#include "prtime.h"
+#include "prinrval.h"
+#include "prerror.h"
+#include "pratom.h"
+#include "prthread.h"
+#include "prinit.h"
+
+#include "pk11func.h"
+#include "secmod.h"
+
+#include <stdio.h>
+
+SECStatus
+ssl_NamedGroup2ECParams(PLArenaPool *arena, const sslNamedGroupDef *ecGroup,
+ SECKEYECParams *params)
+{
+ SECOidData *oidData = NULL;
+
+ if (!params) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!ecGroup || ecGroup->keaType != ssl_kea_ecdh ||
+ (oidData = SECOID_FindOIDByTag(ecGroup->oidTag)) == NULL) {
+ PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE);
+ return SECFailure;
+ }
+
+ if (SECITEM_AllocItem(arena, params, (2 + oidData->oid.len)) == NULL) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
+ }
+
+ /*
+ * params->data needs to contain the ASN encoding of an object ID (OID)
+ * representing the named curve. The actual OID is in
+ * oidData->oid.data so we simply prepend 0x06 and OID length
+ */
+ params->data[0] = SEC_ASN1_OBJECT_ID;
+ params->data[1] = oidData->oid.len;
+ memcpy(params->data + 2, oidData->oid.data, oidData->oid.len);
+
+ return SECSuccess;
+}
+
+const sslNamedGroupDef *
+ssl_ECPubKey2NamedGroup(const SECKEYPublicKey *pubKey)
+{
+ SECItem oid = { siBuffer, NULL, 0 };
+ SECOidData *oidData = NULL;
+ PRUint32 policyFlags = 0;
+ unsigned int i;
+ const SECKEYECParams *params;
+
+ if (pubKey->keyType != ecKey) {
+ PORT_Assert(0);
+ return NULL;
+ }
+
+ params = &pubKey->u.ec.DEREncodedParams;
+
+ /*
+ * params->data needs to contain the ASN encoding of an object ID (OID)
+ * representing a named curve. Here, we strip away everything
+ * before the actual OID and use the OID to look up a named curve.
+ */
+ if (params->data[0] != SEC_ASN1_OBJECT_ID)
+ return NULL;
+ oid.len = params->len - 2;
+ oid.data = params->data + 2;
+ if ((oidData = SECOID_FindOID(&oid)) == NULL)
+ return NULL;
+ if ((NSS_GetAlgorithmPolicy(oidData->offset, &policyFlags) ==
+ SECSuccess) &&
+ !(policyFlags & NSS_USE_ALG_IN_SSL_KX)) {
+ return NULL;
+ }
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ssl_named_groups[i].oidTag == oidData->offset) {
+ return &ssl_named_groups[i];
+ }
+ }
+
+ return NULL;
+}
+
+/* Caller must set hiLevel error code. */
+static SECStatus
+ssl3_ComputeECDHKeyHash(SSLHashType hashAlg,
+ SECItem ec_params, SECItem server_ecpoint,
+ PRUint8 *client_rand, PRUint8 *server_rand,
+ SSL3Hashes *hashes)
+{
+ PRUint8 *hashBuf;
+ PRUint8 *pBuf;
+ SECStatus rv = SECSuccess;
+ unsigned int bufLen;
+ /*
+ * We only support named curves (the appropriate checks are made before this
+ * method is called) so ec_params takes up only two bytes. ECPoint needs to
+ * fit in 256 bytes because the spec says the length must fit in one byte.
+ */
+ PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 1 + 256];
+
+ bufLen = 2 * SSL3_RANDOM_LENGTH + ec_params.len + 1 + server_ecpoint.len;
+ if (bufLen <= sizeof buf) {
+ hashBuf = buf;
+ } else {
+ hashBuf = PORT_Alloc(bufLen);
+ if (!hashBuf) {
+ return SECFailure;
+ }
+ }
+
+ memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
+ pBuf = hashBuf + SSL3_RANDOM_LENGTH;
+ memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
+ pBuf += SSL3_RANDOM_LENGTH;
+ memcpy(pBuf, ec_params.data, ec_params.len);
+ pBuf += ec_params.len;
+ pBuf[0] = (PRUint8)(server_ecpoint.len);
+ pBuf += 1;
+ memcpy(pBuf, server_ecpoint.data, server_ecpoint.len);
+ pBuf += server_ecpoint.len;
+ PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
+
+ rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes);
+
+ PRINT_BUF(95, (NULL, "ECDHkey hash: ", hashBuf, bufLen));
+ PRINT_BUF(95, (NULL, "ECDHkey hash: MD5 result",
+ hashes->u.s.md5, MD5_LENGTH));
+ PRINT_BUF(95, (NULL, "ECDHkey hash: SHA1 result",
+ hashes->u.s.sha, SHA1_LENGTH));
+
+ if (hashBuf != buf)
+ PORT_Free(hashBuf);
+ return rv;
+}
+
+/* Called from ssl3_SendClientKeyExchange(). */
+SECStatus
+ssl3_SendECDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey)
+{
+ PK11SymKey *pms = NULL;
+ SECStatus rv = SECFailure;
+ PRBool isTLS, isTLS12;
+ CK_MECHANISM_TYPE target;
+ const sslNamedGroupDef *groupDef;
+ sslEphemeralKeyPair *keyPair = NULL;
+ SECKEYPublicKey *pubKey;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ isTLS = (PRBool)(ss->version > SSL_LIBRARY_VERSION_3_0);
+ isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+
+ /* Generate ephemeral EC keypair */
+ if (svrPubKey->keyType != ecKey) {
+ PORT_SetError(SEC_ERROR_BAD_KEY);
+ goto loser;
+ }
+ groupDef = ssl_ECPubKey2NamedGroup(svrPubKey);
+ if (!groupDef) {
+ PORT_SetError(SEC_ERROR_BAD_KEY);
+ goto loser;
+ }
+ ss->sec.keaGroup = groupDef;
+ rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, &keyPair);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
+ goto loser;
+ }
+
+ pubKey = keyPair->keys->pubKey;
+ PRINT_BUF(50, (ss, "ECDH public value:",
+ pubKey->u.ec.publicValue.data,
+ pubKey->u.ec.publicValue.len));
+
+ if (isTLS12) {
+ target = CKM_TLS12_MASTER_KEY_DERIVE_DH;
+ } else if (isTLS) {
+ target = CKM_TLS_MASTER_KEY_DERIVE_DH;
+ } else {
+ target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
+ }
+
+ /* Determine the PMS */
+ pms = PK11_PubDeriveWithKDF(keyPair->keys->privKey, svrPubKey,
+ PR_FALSE, NULL, NULL, CKM_ECDH1_DERIVE, target,
+ CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
+
+ if (pms == NULL) {
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_client_key_exchange,
+ pubKey->u.ec.publicValue.len + 1);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_AppendHandshake* */
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.ec.publicValue.data,
+ pubKey->u.ec.publicValue.len, 1);
+
+ if (rv != SECSuccess) {
+ goto loser; /* err set by ssl3_AppendHandshake* */
+ }
+
+ rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ PK11_FreeSymKey(pms);
+ ssl_FreeEphemeralKeyPair(keyPair);
+ return SECSuccess;
+
+loser:
+ if (pms)
+ PK11_FreeSymKey(pms);
+ if (keyPair)
+ ssl_FreeEphemeralKeyPair(keyPair);
+ return SECFailure;
+}
+
+/*
+** Called from ssl3_HandleClientKeyExchange()
+*/
+SECStatus
+ssl3_HandleECDHClientKeyExchange(sslSocket *ss, PRUint8 *b,
+ PRUint32 length,
+ sslKeyPair *serverKeyPair)
+{
+ PK11SymKey *pms;
+ SECStatus rv;
+ SECKEYPublicKey clntPubKey;
+ CK_MECHANISM_TYPE target;
+ PRBool isTLS, isTLS12;
+ int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ clntPubKey.keyType = ecKey;
+ clntPubKey.u.ec.DEREncodedParams.len =
+ serverKeyPair->pubKey->u.ec.DEREncodedParams.len;
+ clntPubKey.u.ec.DEREncodedParams.data =
+ serverKeyPair->pubKey->u.ec.DEREncodedParams.data;
+ clntPubKey.u.ec.encoding = ECPoint_Undefined;
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.ec.publicValue,
+ 1, &b, &length);
+ if (rv != SECSuccess) {
+ PORT_SetError(errCode);
+ return SECFailure;
+ }
+
+ /* we have to catch the case when the client's public key has length 0. */
+ if (!clntPubKey.u.ec.publicValue.len) {
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(errCode);
+ return SECFailure;
+ }
+
+ isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
+ isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+
+ if (isTLS12) {
+ target = CKM_TLS12_MASTER_KEY_DERIVE_DH;
+ } else if (isTLS) {
+ target = CKM_TLS_MASTER_KEY_DERIVE_DH;
+ } else {
+ target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
+ }
+
+ /* Determine the PMS */
+ pms = PK11_PubDeriveWithKDF(serverKeyPair->privKey, &clntPubKey,
+ PR_FALSE, NULL, NULL,
+ CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0,
+ CKD_NULL, NULL, NULL);
+
+ if (pms == NULL) {
+ /* last gasp. */
+ errCode = ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
+ PORT_SetError(errCode);
+ return SECFailure;
+ }
+
+ rv = ssl3_InitPendingCipherSpecs(ss, pms, PR_TRUE);
+ PK11_FreeSymKey(pms);
+ if (rv != SECSuccess) {
+ /* error code set by ssl3_InitPendingCipherSpec */
+ return SECFailure;
+ }
+ ss->sec.keaGroup = ssl_ECPubKey2NamedGroup(&clntPubKey);
+ return SECSuccess;
+}
+
+/*
+** Take an encoded key share and make a public key out of it.
+*/
+SECStatus
+ssl_ImportECDHKeyShare(SECKEYPublicKey *peerKey,
+ PRUint8 *b, PRUint32 length,
+ const sslNamedGroupDef *ecGroup)
+{
+ SECStatus rv;
+ SECItem ecPoint = { siBuffer, NULL, 0 };
+
+ if (!length) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE);
+ return SECFailure;
+ }
+
+ /* Fail if the ec point uses compressed representation */
+ if (b[0] != EC_POINT_FORM_UNCOMPRESSED &&
+ ecGroup->name != ssl_grp_ec_curve25519) {
+ PORT_SetError(SEC_ERROR_UNSUPPORTED_EC_POINT_FORM);
+ return SECFailure;
+ }
+
+ peerKey->keyType = ecKey;
+ /* Set up the encoded params */
+ rv = ssl_NamedGroup2ECParams(peerKey->arena, ecGroup,
+ &peerKey->u.ec.DEREncodedParams);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE);
+ return SECFailure;
+ }
+ peerKey->u.ec.encoding = ECPoint_Undefined;
+
+ /* copy publicValue in peerKey */
+ ecPoint.data = b;
+ ecPoint.len = length;
+
+ rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.ec.publicValue, &ecPoint);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+const sslNamedGroupDef *
+ssl_GetECGroupWithStrength(sslSocket *ss, unsigned int requiredECCbits)
+{
+ int i;
+
+ PORT_Assert(ss);
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ const sslNamedGroupDef *group = ss->namedGroupPreferences[i];
+ if (group && group->keaType == ssl_kea_ecdh &&
+ group->bits >= requiredECCbits) {
+ return group;
+ }
+ }
+
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return NULL;
+}
+
+/* Find the "weakest link". Get the strength of the signature and symmetric
+ * keys and choose a curve based on the weakest of those two. */
+const sslNamedGroupDef *
+ssl_GetECGroupForServerSocket(sslSocket *ss)
+{
+ const sslServerCert *cert = ss->sec.serverCert;
+ unsigned int certKeySize;
+ const ssl3BulkCipherDef *bulkCipher;
+ unsigned int requiredECCbits;
+
+ PORT_Assert(cert);
+ if (!cert || !cert->serverKeyPair || !cert->serverKeyPair->pubKey) {
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return NULL;
+ }
+
+ if (SSL_CERT_IS(cert, ssl_auth_rsa_sign) ||
+ SSL_CERT_IS(cert, ssl_auth_rsa_pss)) {
+ certKeySize = SECKEY_PublicKeyStrengthInBits(cert->serverKeyPair->pubKey);
+ certKeySize = SSL_RSASTRENGTH_TO_ECSTRENGTH(certKeySize);
+ } else if (SSL_CERT_IS_EC(cert)) {
+ /* We won't select a certificate unless the named curve has been
+ * negotiated (or supported_curves was absent), double check that. */
+ PORT_Assert(cert->namedCurve->keaType == ssl_kea_ecdh);
+ PORT_Assert(ssl_NamedGroupEnabled(ss, cert->namedCurve));
+ if (!ssl_NamedGroupEnabled(ss, cert->namedCurve)) {
+ return NULL;
+ }
+ certKeySize = cert->namedCurve->bits;
+ } else {
+ PORT_Assert(0);
+ return NULL;
+ }
+ bulkCipher = ssl_GetBulkCipherDef(ss->ssl3.hs.suite_def);
+ requiredECCbits = bulkCipher->key_size * BPB * 2;
+ PORT_Assert(requiredECCbits ||
+ ss->ssl3.hs.suite_def->bulk_cipher_alg == cipher_null);
+ if (requiredECCbits > certKeySize) {
+ requiredECCbits = certKeySize;
+ }
+
+ return ssl_GetECGroupWithStrength(ss, requiredECCbits);
+}
+
+/* Create an ECDHE key pair for a given curve */
+SECStatus
+ssl_CreateECDHEphemeralKeyPair(const sslSocket *ss,
+ const sslNamedGroupDef *ecGroup,
+ sslEphemeralKeyPair **keyPair)
+{
+ SECKEYPrivateKey *privKey = NULL;
+ SECKEYPublicKey *pubKey = NULL;
+ SECKEYECParams ecParams = { siBuffer, NULL, 0 };
+ sslEphemeralKeyPair *pair;
+
+ if (ssl_NamedGroup2ECParams(NULL, ecGroup, &ecParams) != SECSuccess) {
+ return SECFailure;
+ }
+ privKey = SECKEY_CreateECPrivateKey(&ecParams, &pubKey, ss->pkcs11PinArg);
+ SECITEM_FreeItem(&ecParams, PR_FALSE);
+
+ if (!privKey || !pubKey ||
+ !(pair = ssl_NewEphemeralKeyPair(ecGroup, privKey, pubKey))) {
+ if (privKey) {
+ SECKEY_DestroyPrivateKey(privKey);
+ }
+ if (pubKey) {
+ SECKEY_DestroyPublicKey(pubKey);
+ }
+ ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
+ return SECFailure;
+ }
+
+ *keyPair = pair;
+ SSL_TRC(50, ("%d: SSL[%d]: Create ECDH ephemeral key %d",
+ SSL_GETPID(), ss ? ss->fd : NULL, ecGroup->name));
+ PRINT_BUF(50, (ss, "Public Key", pubKey->u.ec.publicValue.data,
+ pubKey->u.ec.publicValue.len));
+#ifdef TRACE
+ if (ssl_trace >= 50) {
+ SECItem d = { siBuffer, NULL, 0 };
+ SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, privKey,
+ CKA_VALUE, &d);
+ if (rv == SECSuccess) {
+ PRINT_BUF(50, (ss, "Private Key", d.data, d.len));
+ SECITEM_FreeItem(&d, PR_FALSE);
+ } else {
+ SSL_TRC(50, ("Error extracting private key"));
+ }
+ }
+#endif
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_HandleECDHServerKeyExchange(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ PLArenaPool *arena = NULL;
+ SECKEYPublicKey *peerKey = NULL;
+ PRBool isTLS;
+ SECStatus rv;
+ int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
+ SSL3AlertDescription desc = illegal_parameter;
+ SSL3Hashes hashes;
+ SECItem signature = { siBuffer, NULL, 0 };
+ SSLHashType hashAlg;
+ SSLSignatureScheme sigScheme;
+
+ SECItem ec_params = { siBuffer, NULL, 0 };
+ SECItem ec_point = { siBuffer, NULL, 0 };
+ unsigned char paramBuf[3];
+ const sslNamedGroupDef *ecGroup;
+
+ isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
+
+ ec_params.len = sizeof paramBuf;
+ ec_params.data = paramBuf;
+ rv = ssl3_ConsumeHandshake(ss, ec_params.data, ec_params.len, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+
+ /* Fail if the curve is not a named curve */
+ if (ec_params.data[0] != ec_type_named) {
+ errCode = SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE;
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+ ecGroup = ssl_LookupNamedGroup(ec_params.data[1] << 8 | ec_params.data[2]);
+ if (!ecGroup || ecGroup->keaType != ssl_kea_ecdh) {
+ errCode = SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE;
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &ec_point, 1, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+
+ /* Fail if the provided point has length 0. */
+ if (!ec_point.len) {
+ /* desc and errCode are initialized already */
+ goto alert_loser;
+ }
+
+ /* Fail if the ec point is not uncompressed for any curve that's not 25519. */
+ if (ecGroup->name != ssl_grp_ec_curve25519 &&
+ ec_point.data[0] != EC_POINT_FORM_UNCOMPRESSED) {
+ errCode = SEC_ERROR_UNSUPPORTED_EC_POINT_FORM;
+ desc = handshake_failure;
+ goto alert_loser;
+ }
+
+ PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2);
+ if (ss->ssl3.prSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+ rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto alert_loser; /* malformed or unsupported. */
+ }
+ rv = ssl_CheckSignatureSchemeConsistency(
+ ss, sigScheme, &ss->sec.peerCert->subjectPublicKeyInfo);
+ if (rv != SECSuccess) {
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+ hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
+ } else {
+ /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+ hashAlg = ssl_hash_none;
+ sigScheme = ssl_sig_none;
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed. */
+ }
+
+ if (length != 0) {
+ if (isTLS)
+ desc = decode_error;
+ goto alert_loser; /* malformed. */
+ }
+
+ PRINT_BUF(60, (NULL, "Server EC params", ec_params.data, ec_params.len));
+ PRINT_BUF(60, (NULL, "Server EC point", ec_point.data, ec_point.len));
+
+ /* failures after this point are not malformed handshakes. */
+ /* TLS: send decrypt_error if signature failed. */
+ desc = isTLS ? decrypt_error : handshake_failure;
+
+ /*
+ * check to make sure the hash is signed by right guy
+ */
+ rv = ssl3_ComputeECDHKeyHash(hashAlg, ec_params, ec_point,
+ ss->ssl3.hs.client_random,
+ ss->ssl3.hs.server_random,
+ &hashes);
+
+ if (rv != SECSuccess) {
+ errCode =
+ ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ goto alert_loser;
+ }
+ rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature);
+ if (rv != SECSuccess) {
+ errCode =
+ ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ goto alert_loser;
+ }
+
+ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (arena == NULL) {
+ errCode = SEC_ERROR_NO_MEMORY;
+ goto loser;
+ }
+
+ peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
+ if (peerKey == NULL) {
+ errCode = SEC_ERROR_NO_MEMORY;
+ goto loser;
+ }
+ peerKey->arena = arena;
+
+ /* create public key from point data */
+ rv = ssl_ImportECDHKeyShare(peerKey, ec_point.data, ec_point.len,
+ ecGroup);
+ if (rv != SECSuccess) {
+ /* error code is set */
+ desc = handshake_failure;
+ errCode = PORT_GetError();
+ goto alert_loser;
+ }
+ peerKey->pkcs11Slot = NULL;
+ peerKey->pkcs11ID = CK_INVALID_HANDLE;
+
+ ss->sec.peerKey = peerKey;
+ return SECSuccess;
+
+alert_loser:
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+loser:
+ if (arena) {
+ PORT_FreeArena(arena, PR_FALSE);
+ }
+ PORT_SetError(errCode);
+ return SECFailure;
+}
+
+SECStatus
+ssl3_SendECDHServerKeyExchange(sslSocket *ss)
+{
+ SECStatus rv = SECFailure;
+ int length;
+ PRBool isTLS12;
+ SECItem signed_hash = { siBuffer, NULL, 0 };
+ SSLHashType hashAlg;
+ SSL3Hashes hashes;
+
+ SECItem ec_params = { siBuffer, NULL, 0 };
+ unsigned char paramBuf[3];
+ const sslNamedGroupDef *ecGroup;
+ sslEphemeralKeyPair *keyPair;
+ SECKEYPublicKey *pubKey;
+
+ /* Generate ephemeral ECDH key pair and send the public key */
+ ecGroup = ssl_GetECGroupForServerSocket(ss);
+ if (!ecGroup) {
+ goto loser;
+ }
+
+ PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
+ if (ss->opt.reuseServerECDHEKey) {
+ rv = ssl_CreateStaticECDHEKey(ss, ecGroup);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
+ } else {
+ rv = ssl_CreateECDHEphemeralKeyPair(ss, ecGroup, &keyPair);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
+ }
+
+ PORT_Assert(keyPair);
+ if (!keyPair) {
+ PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ return SECFailure;
+ }
+
+ ec_params.len = sizeof(paramBuf);
+ ec_params.data = paramBuf;
+ PORT_Assert(keyPair->group);
+ PORT_Assert(keyPair->group->keaType == ssl_kea_ecdh);
+ ec_params.data[0] = ec_type_named;
+ ec_params.data[1] = keyPair->group->name >> 8;
+ ec_params.data[2] = keyPair->group->name & 0xff;
+
+ pubKey = keyPair->keys->pubKey;
+ if (ss->version == SSL_LIBRARY_VERSION_TLS_1_2) {
+ hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
+ } else {
+ /* Use ssl_hash_none to represent the MD5+SHA1 combo. */
+ hashAlg = ssl_hash_none;
+ }
+ rv = ssl3_ComputeECDHKeyHash(hashAlg, ec_params,
+ pubKey->u.ec.publicValue,
+ ss->ssl3.hs.client_random,
+ ss->ssl3.hs.server_random,
+ &hashes);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+
+ isTLS12 = (PRBool)(ss->version >= SSL_LIBRARY_VERSION_TLS_1_2);
+
+ rv = ssl3_SignHashes(ss, &hashes,
+ ss->sec.serverCert->serverKeyPair->privKey, &signed_hash);
+ if (rv != SECSuccess) {
+ goto loser; /* ssl3_SignHashes has set err. */
+ }
+
+ length = ec_params.len +
+ 1 + pubKey->u.ec.publicValue.len +
+ (isTLS12 ? 2 : 0) + 2 + signed_hash.len;
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_key_exchange, length);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshake(ss, ec_params.data, ec_params.len);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.ec.publicValue.data,
+ pubKey->u.ec.publicValue.len, 1);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ if (isTLS12) {
+ rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
+ signed_hash.len, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ PORT_Free(signed_hash.data);
+ return SECSuccess;
+
+loser:
+ if (signed_hash.data != NULL)
+ PORT_Free(signed_hash.data);
+ return SECFailure;
+}
+
+/* List of all ECC cipher suites */
+static const ssl3CipherSuite ssl_all_ec_suites[] = {
+ TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
+ TLS_ECDHE_ECDSA_WITH_NULL_SHA,
+ TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
+ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
+ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
+ TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
+ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
+ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
+ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
+ TLS_ECDHE_RSA_WITH_NULL_SHA,
+ TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+ TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDH_ECDSA_WITH_NULL_SHA,
+ TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDH_RSA_WITH_NULL_SHA,
+ TLS_ECDH_RSA_WITH_RC4_128_SHA,
+ 0 /* end of list marker */
+};
+
+static const ssl3CipherSuite ssl_dhe_suites[] = {
+ TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
+ TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
+ TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
+ TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,
+ TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
+ TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
+ TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
+ TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
+ TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
+ TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
+ TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
+ TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
+ TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
+ TLS_DHE_DSS_WITH_RC4_128_SHA,
+ TLS_DHE_RSA_WITH_DES_CBC_SHA,
+ TLS_DHE_DSS_WITH_DES_CBC_SHA,
+ 0
+};
+
+/* Order(N^2). Yuk. */
+static PRBool
+ssl_IsSuiteEnabled(const sslSocket *ss, const ssl3CipherSuite *list)
+{
+ const ssl3CipherSuite *suite;
+
+ for (suite = list; *suite; ++suite) {
+ PRBool enabled = PR_FALSE;
+ SECStatus rv = ssl3_CipherPrefGet(ss, *suite, &enabled);
+
+ PORT_Assert(rv == SECSuccess); /* else is coding error */
+ if (rv == SECSuccess && enabled)
+ return PR_TRUE;
+ }
+ return PR_FALSE;
+}
+
+/* Ask: is ANY ECC cipher suite enabled on this socket? */
+PRBool
+ssl_IsECCEnabled(const sslSocket *ss)
+{
+ PK11SlotInfo *slot;
+
+ /* make sure we can do ECC */
+ slot = PK11_GetBestSlot(CKM_ECDH1_DERIVE, ss->pkcs11PinArg);
+ if (!slot) {
+ return PR_FALSE;
+ }
+ PK11_FreeSlot(slot);
+
+ /* make sure an ECC cipher is enabled */
+ return ssl_IsSuiteEnabled(ss, ssl_all_ec_suites);
+}
+
+PRBool
+ssl_IsDHEEnabled(const sslSocket *ss)
+{
+ return ssl_IsSuiteEnabled(ss, ssl_dhe_suites);
+}
+
+/* Send our Supported Groups extension. */
+SECStatus
+ssl_SendSupportedGroupsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ unsigned int i;
+ PRBool ec;
+ PRBool ff = PR_FALSE;
+ PRBool found = PR_FALSE;
+ SECStatus rv;
+ unsigned int lengthOffset;
+
+ /* We only send FF supported groups if we require DH named groups
+ * or if TLS 1.3 is a possibility. */
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
+ ec = ssl_IsECCEnabled(ss);
+ if (ss->opt.requireDHENamedGroups) {
+ ff = ssl_IsDHEEnabled(ss);
+ }
+ if (!ec && !ff) {
+ return SECSuccess;
+ }
+ } else {
+ ec = ff = PR_TRUE;
+ }
+
+ /* Mark the location of the length. */
+ rv = sslBuffer_Skip(buf, 2, &lengthOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ const sslNamedGroupDef *group = ss->namedGroupPreferences[i];
+ if (!group) {
+ continue;
+ }
+ if (group->keaType == ssl_kea_ecdh && !ec) {
+ continue;
+ }
+ if (group->keaType == ssl_kea_dh && !ff) {
+ continue;
+ }
+
+ found = PR_TRUE;
+ rv = sslBuffer_AppendNumber(buf, group->name, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ /* GREASE SupportedGroups:
+ * A client MAY select one or more GREASE named group values and advertise
+ * them in the "supported_groups" extension, if sent [RFC8701, Section 3.1].
+ */
+ if (!ss->sec.isServer &&
+ ss->opt.enableGrease &&
+ ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_group], 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ found = PR_TRUE;
+ }
+
+ if (!found) {
+ /* We added nothing, don't send the extension. */
+ return SECSuccess;
+ }
+
+ rv = sslBuffer_InsertLength(buf, lengthOffset, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* Send our "canned" (precompiled) Supported Point Formats extension,
+ * which says that we only support uncompressed points.
+ */
+SECStatus
+ssl3_SendSupportedPointFormatsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ /* No point in doing this unless we have a socket that supports ECC.
+ * Similarly, no point if we are going to do TLS 1.3 only or we have already
+ * picked TLS 1.3 (server) given that it doesn't use point formats. */
+ if (!ss || !ssl_IsECCEnabled(ss) ||
+ ss->vrange.min >= SSL_LIBRARY_VERSION_TLS_1_3 ||
+ (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
+ return SECSuccess;
+ }
+ rv = sslBuffer_AppendNumber(buf, 1, 1); /* length */
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(buf, 0, 1); /* uncompressed type only */
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/ssl3ext.c b/security/nss/lib/ssl/ssl3ext.c
new file mode 100644
index 0000000000..194e6d0c8c
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3ext.c
@@ -0,0 +1,1181 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * SSL3 Protocol
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* TLS extension code moved here from ssl3ecc.c */
+
+#include "nssrenam.h"
+#include "nss.h"
+#include "pk11pub.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "ssl3exthandle.h"
+#include "tls13ech.h"
+#include "tls13err.h"
+#include "tls13exthandle.h"
+#include "tls13subcerts.h"
+
+/* Callback function that handles a received extension. */
+typedef SECStatus (*ssl3ExtensionHandlerFunc)(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+
+/* Row in a table of hello extension handlers. */
+typedef struct {
+ SSLExtensionType ex_type;
+ ssl3ExtensionHandlerFunc ex_handler;
+} ssl3ExtensionHandler;
+
+/* Table of handlers for received TLS hello extensions, one per extension.
+ * In the second generation, this table will be dynamic, and functions
+ * will be registered here.
+ */
+/* This table is used by the server, to handle client hello extensions. */
+static const ssl3ExtensionHandler clientHelloHandlers[] = {
+ { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
+ { ssl_supported_groups_xtn, &ssl_HandleSupportedGroupsXtn },
+ { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn },
+ { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn },
+ { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
+ { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn },
+ { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn },
+ { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn },
+ { ssl_tls13_certificate_authorities_xtn, &tls13_ServerHandleCertAuthoritiesXtn },
+ { ssl_signature_algorithms_xtn, &ssl3_HandleSigAlgsXtn },
+ { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
+ { ssl_signed_cert_timestamp_xtn, &ssl3_ServerHandleSignedCertTimestampXtn },
+ { ssl_delegated_credentials_xtn, &tls13_ServerHandleDelegatedCredentialsXtn },
+ { ssl_tls13_key_share_xtn, &tls13_ServerHandleKeyShareXtn },
+ { ssl_tls13_pre_shared_key_xtn, &tls13_ServerHandlePreSharedKeyXtn },
+ { ssl_tls13_early_data_xtn, &tls13_ServerHandleEarlyDataXtn },
+ { ssl_tls13_psk_key_exchange_modes_xtn, &tls13_ServerHandlePskModesXtn },
+ { ssl_tls13_cookie_xtn, &tls13_ServerHandleCookieXtn },
+ { ssl_tls13_post_handshake_auth_xtn, &tls13_ServerHandlePostHandshakeAuthXtn },
+ { ssl_record_size_limit_xtn, &ssl_HandleRecordSizeLimitXtn },
+ { 0, NULL }
+};
+
+/* These two tables are used by the client, to handle server hello
+ * extensions. */
+static const ssl3ExtensionHandler serverHelloHandlersTLS[] = {
+ { ssl_server_name_xtn, &ssl3_HandleServerNameXtn },
+ /* TODO: add a handler for ssl_ec_point_formats_xtn */
+ { ssl_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn },
+ { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
+ { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn },
+ { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn },
+ { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
+ { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn },
+ { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn },
+ { ssl_tls13_key_share_xtn, &tls13_ClientHandleKeyShareXtn },
+ { ssl_tls13_pre_shared_key_xtn, &tls13_ClientHandlePreSharedKeyXtn },
+ { ssl_tls13_early_data_xtn, &tls13_ClientHandleEarlyDataXtn },
+ { ssl_tls13_encrypted_client_hello_xtn, &tls13_ClientHandleEchXtn },
+ { ssl_record_size_limit_xtn, &ssl_HandleRecordSizeLimitXtn },
+ { 0, NULL }
+};
+
+static const ssl3ExtensionHandler helloRetryRequestHandlers[] = {
+ { ssl_tls13_key_share_xtn, tls13_ClientHandleKeyShareXtnHrr },
+ { ssl_tls13_cookie_xtn, tls13_ClientHandleHrrCookie },
+ { ssl_tls13_encrypted_client_hello_xtn, tls13_ClientHandleHrrEchXtn },
+ { 0, NULL }
+};
+
+static const ssl3ExtensionHandler serverHelloHandlersSSL3[] = {
+ { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
+ { 0, NULL }
+};
+
+static const ssl3ExtensionHandler newSessionTicketHandlers[] = {
+ { ssl_tls13_early_data_xtn,
+ &tls13_ClientHandleTicketEarlyDataXtn },
+ { 0, NULL }
+};
+
+/* This table is used by the client to handle server certificates in TLS 1.3 */
+static const ssl3ExtensionHandler serverCertificateHandlers[] = {
+ { ssl_signed_cert_timestamp_xtn, &ssl3_ClientHandleSignedCertTimestampXtn },
+ { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn },
+ { ssl_delegated_credentials_xtn, &tls13_ClientHandleDelegatedCredentialsXtn },
+ { 0, NULL }
+};
+
+static const ssl3ExtensionHandler certificateRequestHandlers[] = {
+ { ssl_signature_algorithms_xtn, &ssl3_HandleSigAlgsXtn },
+ { ssl_tls13_certificate_authorities_xtn,
+ &tls13_ClientHandleCertAuthoritiesXtn },
+ { 0, NULL }
+};
+
+/* Tables of functions to format TLS hello extensions, one function per
+ * extension.
+ * These static tables are for the formatting of client hello extensions.
+ * The server's table of hello senders is dynamic, in the socket struct,
+ * and sender functions are registered there.
+ * NB: the order of these extensions can have an impact on compatibility. Some
+ * servers (e.g. Tomcat) will terminate the connection if the last extension in
+ * the client hello is empty (for example, the extended master secret
+ * extension, if it were listed last). See bug 1243641.
+ */
+static const sslExtensionBuilder clientHelloSendersTLS[] = {
+ /* TLS 1.3 GREASE extensions - empty. */
+ { ssl_tls13_grease_xtn, &tls13_SendEmptyGreaseXtn },
+ { ssl_server_name_xtn, &ssl3_ClientSendServerNameXtn },
+ { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn },
+ { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
+ { ssl_supported_groups_xtn, &ssl_SendSupportedGroupsXtn },
+ { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn },
+ { ssl_session_ticket_xtn, &ssl3_ClientSendSessionTicketXtn },
+ { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
+ { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn },
+ { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn },
+ { ssl_delegated_credentials_xtn, &tls13_ClientSendDelegatedCredentialsXtn },
+ { ssl_signed_cert_timestamp_xtn, &ssl3_ClientSendSignedCertTimestampXtn },
+ { ssl_tls13_key_share_xtn, &tls13_ClientSendKeyShareXtn },
+ { ssl_tls13_early_data_xtn, &tls13_ClientSendEarlyDataXtn },
+ /* Some servers (e.g. WebSphere Application Server 7.0 and Tomcat) will
+ * time out or terminate the connection if the last extension in the
+ * client hello is empty. They are not intolerant of TLS 1.2, so list
+ * signature_algorithms at the end. See bug 1243641. */
+ { ssl_tls13_supported_versions_xtn, &tls13_ClientSendSupportedVersionsXtn },
+ { ssl_signature_algorithms_xtn, &ssl3_SendSigAlgsXtn },
+ { ssl_tls13_cookie_xtn, &tls13_ClientSendHrrCookieXtn },
+ { ssl_tls13_psk_key_exchange_modes_xtn, &tls13_ClientSendPskModesXtn },
+ { ssl_tls13_post_handshake_auth_xtn, &tls13_ClientSendPostHandshakeAuthXtn },
+ { ssl_record_size_limit_xtn, &ssl_SendRecordSizeLimitXtn },
+ /* TLS 1.3 GREASE extensions - 1 zero byte. */
+ { ssl_tls13_grease_xtn, &tls13_SendGreaseXtn },
+ /* The pre_shared_key extension MUST be last. */
+ { ssl_tls13_pre_shared_key_xtn, &tls13_ClientSendPreSharedKeyXtn },
+ { 0, NULL }
+};
+
+static const sslExtensionBuilder clientHelloSendersSSL3[] = {
+ { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
+ { 0, NULL }
+};
+
+static const sslExtensionBuilder tls13_cert_req_senders[] = {
+ { ssl_signature_algorithms_xtn, &ssl3_SendSigAlgsXtn },
+ { ssl_tls13_certificate_authorities_xtn, &tls13_SendCertAuthoritiesXtn },
+ /* TLS 1.3 GREASE extension. */
+ { ssl_tls13_grease_xtn, &tls13_SendEmptyGreaseXtn },
+ { 0, NULL }
+};
+
+static const sslExtensionBuilder tls13_hrr_senders[] = {
+ { ssl_tls13_key_share_xtn, &tls13_ServerSendHrrKeyShareXtn },
+ { ssl_tls13_cookie_xtn, &tls13_ServerSendHrrCookieXtn },
+ { ssl_tls13_supported_versions_xtn, &tls13_ServerSendSupportedVersionsXtn },
+ { ssl_tls13_encrypted_client_hello_xtn, &tls13_ServerSendHrrEchXtn },
+ { 0, NULL }
+};
+
+static const struct {
+ SSLExtensionType type;
+ SSLExtensionSupport support;
+} ssl_supported_extensions[] = {
+ { ssl_server_name_xtn, ssl_ext_native_only },
+ { ssl_cert_status_xtn, ssl_ext_native },
+ { ssl_delegated_credentials_xtn, ssl_ext_native },
+ { ssl_supported_groups_xtn, ssl_ext_native_only },
+ { ssl_ec_point_formats_xtn, ssl_ext_native },
+ { ssl_signature_algorithms_xtn, ssl_ext_native_only },
+ { ssl_use_srtp_xtn, ssl_ext_native },
+ { ssl_app_layer_protocol_xtn, ssl_ext_native_only },
+ { ssl_signed_cert_timestamp_xtn, ssl_ext_native },
+ { ssl_padding_xtn, ssl_ext_native },
+ { ssl_extended_master_secret_xtn, ssl_ext_native_only },
+ { ssl_session_ticket_xtn, ssl_ext_native_only },
+ { ssl_tls13_key_share_xtn, ssl_ext_native_only },
+ { ssl_tls13_pre_shared_key_xtn, ssl_ext_native_only },
+ { ssl_tls13_early_data_xtn, ssl_ext_native_only },
+ { ssl_tls13_supported_versions_xtn, ssl_ext_native_only },
+ { ssl_tls13_cookie_xtn, ssl_ext_native_only },
+ { ssl_tls13_psk_key_exchange_modes_xtn, ssl_ext_native_only },
+ { ssl_tls13_ticket_early_data_info_xtn, ssl_ext_native_only },
+ { ssl_tls13_certificate_authorities_xtn, ssl_ext_native },
+ { ssl_renegotiation_info_xtn, ssl_ext_native },
+ { ssl_tls13_encrypted_client_hello_xtn, ssl_ext_native_only },
+};
+
+static SSLExtensionSupport
+ssl_GetExtensionSupport(PRUint16 type)
+{
+ unsigned int i;
+ for (i = 0; i < PR_ARRAY_SIZE(ssl_supported_extensions); ++i) {
+ if (type == ssl_supported_extensions[i].type) {
+ return ssl_supported_extensions[i].support;
+ }
+ }
+ return ssl_ext_none;
+}
+
+SECStatus
+SSLExp_GetExtensionSupport(PRUint16 type, SSLExtensionSupport *support)
+{
+ *support = ssl_GetExtensionSupport(type);
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_InstallExtensionHooks(PRFileDesc *fd, PRUint16 extension,
+ SSLExtensionWriter writer, void *writerArg,
+ SSLExtensionHandler handler, void *handlerArg)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ PRCList *cursor;
+ sslCustomExtensionHooks *hook;
+
+ if (!ss) {
+ return SECFailure; /* Code already set. */
+ }
+
+ /* Need to specify both or neither, but not just one. */
+ if ((writer && !handler) || (!writer && handler)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ssl_GetExtensionSupport(extension) == ssl_ext_native_only) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ss->firstHsDone || ((ss->ssl3.hs.ws != idle_handshake) &&
+ (ss->ssl3.hs.ws != wait_client_hello))) {
+ PORT_SetError(PR_INVALID_STATE_ERROR);
+ return SECFailure;
+ }
+
+ /* Remove any old handler. */
+ for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
+ cursor != &ss->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ hook = (sslCustomExtensionHooks *)cursor;
+ if (hook->type == extension) {
+ PR_REMOVE_LINK(&hook->link);
+ PORT_Free(hook);
+ break;
+ }
+ }
+
+ if (!writer && !handler) {
+ return SECSuccess;
+ }
+
+ hook = PORT_ZNew(sslCustomExtensionHooks);
+ if (!hook) {
+ return SECFailure; /* This removed the old one, oh well. */
+ }
+
+ hook->type = extension;
+ hook->writer = writer;
+ hook->writerArg = writerArg;
+ hook->handler = handler;
+ hook->handlerArg = handlerArg;
+ PR_APPEND_LINK(&hook->link, &ss->extensionHooks);
+ return SECSuccess;
+}
+
+sslCustomExtensionHooks *
+ssl_FindCustomExtensionHooks(sslSocket *ss, PRUint16 extension)
+{
+ PRCList *cursor;
+
+ for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
+ cursor != &ss->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslCustomExtensionHooks *hook = (sslCustomExtensionHooks *)cursor;
+ if (hook->type == extension) {
+ return hook;
+ }
+ }
+
+ return NULL;
+}
+
+static PRBool
+arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type)
+{
+ unsigned int i;
+ for (i = 0; i < len; i++) {
+ if (ex_type == array[i])
+ return PR_TRUE;
+ }
+ return PR_FALSE;
+}
+
+PRBool
+ssl3_ExtensionNegotiated(const sslSocket *ss, PRUint16 ex_type)
+{
+ const TLSExtensionData *xtnData = &ss->xtnData;
+ return arrayContainsExtension(xtnData->negotiated,
+ xtnData->numNegotiated, ex_type);
+}
+
+/* This checks for whether an extension was advertised. On the client, this
+ * covers extensions that are sent in ClientHello; on the server, extensions
+ * sent in CertificateRequest (TLS 1.3 only). */
+PRBool
+ssl3_ExtensionAdvertised(const sslSocket *ss, PRUint16 ex_type)
+{
+ const TLSExtensionData *xtnData = &ss->xtnData;
+ return arrayContainsExtension(xtnData->advertised,
+ xtnData->numAdvertised, ex_type);
+}
+
+PRBool
+ssl3_ExtensionAdvertisedClientHelloInner(const sslSocket *ss, PRUint16 ex_type)
+{
+ const TLSExtensionData *xtnData = &ss->xtnData;
+ return arrayContainsExtension(xtnData->echAdvertised,
+ xtnData->echNumAdvertised, ex_type);
+}
+
+/* Go through hello extensions in |b| and deserialize
+ * them into the list in |ss->ssl3.hs.remoteExtensions|.
+ * The only checking we do in this point is for duplicates.
+ *
+ * IMPORTANT: This list just contains pointers to the incoming
+ * buffer so they can only be used during ClientHello processing.
+ */
+SECStatus
+ssl3_ParseExtensions(sslSocket *ss, PRUint8 **b, PRUint32 *length)
+{
+ /* Clean out the extensions list. */
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+
+ while (*length) {
+ SECStatus rv;
+ PRUint32 extension_type;
+ SECItem extension_data = { siBuffer, NULL, 0 };
+ TLSExtension *extension;
+ PRCList *cursor;
+
+ /* Get the extension's type field */
+ rv = ssl3_ConsumeHandshakeNumber(ss, &extension_type, 2, b, length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* alert already sent */
+ }
+
+ /* Check whether an extension has been sent multiple times. */
+ for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
+ cursor != &ss->ssl3.hs.remoteExtensions;
+ cursor = PR_NEXT_LINK(cursor)) {
+ if (((TLSExtension *)cursor)->type == extension_type) {
+ (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+ }
+
+ /* Get the data for this extension, so we can pass it or skip it. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, &extension_data, 2, b, length);
+ if (rv != SECSuccess) {
+ return rv; /* alert already sent */
+ }
+
+ SSL_TRC(10, ("%d: SSL3[%d]: parsed extension %d len=%u",
+ SSL_GETPID(), ss->fd, extension_type, extension_data.len));
+
+ extension = PORT_ZNew(TLSExtension);
+ if (!extension) {
+ return SECFailure;
+ }
+
+ extension->type = (PRUint16)extension_type;
+ extension->data = extension_data;
+ PR_APPEND_LINK(&extension->link, &ss->ssl3.hs.remoteExtensions);
+ }
+
+ return SECSuccess;
+}
+
+TLSExtension *
+ssl3_FindExtension(sslSocket *ss, SSLExtensionType extension_type)
+{
+ PRCList *cursor;
+
+ for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
+ cursor != &ss->ssl3.hs.remoteExtensions;
+ cursor = PR_NEXT_LINK(cursor)) {
+ TLSExtension *extension = (TLSExtension *)cursor;
+
+ if (extension->type == extension_type) {
+ return extension;
+ }
+ }
+
+ return NULL;
+}
+
+static SECStatus
+ssl_CallExtensionHandler(sslSocket *ss, SSLHandshakeType handshakeMessage,
+ TLSExtension *extension,
+ const ssl3ExtensionHandler *handler)
+{
+ SECStatus rv = SECSuccess;
+ SSLAlertDescription alert = handshake_failure;
+ sslCustomExtensionHooks *customHooks;
+
+ customHooks = ssl_FindCustomExtensionHooks(ss, extension->type);
+ if (customHooks) {
+ if (customHooks->handler) {
+ rv = customHooks->handler(ss->fd, handshakeMessage,
+ extension->data.data,
+ extension->data.len,
+ &alert, customHooks->handlerArg);
+ }
+ } else {
+ /* Find extension_type in table of Hello Extension Handlers. */
+ for (; handler->ex_handler != NULL; ++handler) {
+ if (handler->ex_type == extension->type) {
+ SECItem tmp = extension->data;
+
+ rv = (*handler->ex_handler)(ss, &ss->xtnData, &tmp);
+ break;
+ }
+ }
+ }
+
+ if (rv != SECSuccess) {
+ if (!ss->ssl3.fatalAlertSent) {
+ /* Send an alert if the handler didn't already. */
+ (void)SSL3_SendAlert(ss, alert_fatal, alert);
+ }
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Go through the hello extensions in |ss->ssl3.hs.remoteExtensions|.
+ * For each one, find the extension handler in the table, and
+ * if present, invoke that handler.
+ * Servers ignore any extensions with unknown extension types.
+ * Clients reject any extensions with unadvertised extension types
+ *
+ * In TLS >= 1.3, the client checks that extensions appear in the
+ * right phase.
+ */
+SECStatus
+ssl3_HandleParsedExtensions(sslSocket *ss, SSLHandshakeType message)
+{
+ const ssl3ExtensionHandler *handlers;
+ /* HelloRetryRequest doesn't set ss->version. It might be safe to
+ * do so, but we weren't entirely sure. TODO(ekr@rtfm.com). */
+ PRBool isTLS13 = (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) ||
+ (message == ssl_hs_hello_retry_request);
+ /* The following messages can include extensions that were not included in
+ * the original ClientHello. */
+ PRBool allowNotOffered = (message == ssl_hs_client_hello) ||
+ (message == ssl_hs_certificate_request) ||
+ (message == ssl_hs_new_session_ticket);
+ PRCList *cursor;
+
+ switch (message) {
+ case ssl_hs_client_hello:
+ handlers = clientHelloHandlers;
+ break;
+ case ssl_hs_new_session_ticket:
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ handlers = newSessionTicketHandlers;
+ break;
+ case ssl_hs_hello_retry_request:
+ handlers = helloRetryRequestHandlers;
+ break;
+ case ssl_hs_encrypted_extensions:
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ /* fall through */
+ case ssl_hs_server_hello:
+ if (ss->version > SSL_LIBRARY_VERSION_3_0) {
+ handlers = serverHelloHandlersTLS;
+ } else {
+ handlers = serverHelloHandlersSSL3;
+ }
+ break;
+ case ssl_hs_certificate:
+ PORT_Assert(!ss->sec.isServer);
+ handlers = serverCertificateHandlers;
+ break;
+ case ssl_hs_certificate_request:
+ PORT_Assert(!ss->sec.isServer);
+ handlers = certificateRequestHandlers;
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ PORT_Assert(0);
+ return SECFailure;
+ }
+
+ for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
+ cursor != &ss->ssl3.hs.remoteExtensions;
+ cursor = PR_NEXT_LINK(cursor)) {
+ TLSExtension *extension = (TLSExtension *)cursor;
+ SECStatus rv;
+
+ /* Check whether the server sent an extension which was not advertised
+ * in the ClientHello.
+ *
+ * Note that a TLS 1.3 server should check if CertificateRequest
+ * extensions were sent. But the extensions used for CertificateRequest
+ * do not have any response, so we rely on
+ * ssl3_ExtensionAdvertised to return false on the server. That
+ * results in the server only rejecting any extension. */
+ if (!allowNotOffered && (extension->type != ssl_tls13_cookie_xtn)) {
+ if (!ssl3_ExtensionAdvertised(ss, extension->type)) {
+ SSL_TRC(10, ("Server sent xtn type=%d which is invalid for the CHO", extension->type));
+ (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+ /* If we offered ECH, we also check whether the extension is compatible with
+ * the Client Hello Inner. We don't yet know whether the server accepted ECH,
+ * so we only store this for now. If we later accept, we check this boolean
+ * and reject with an unsupported_extension alert if it is set. */
+ if (ss->ssl3.hs.echHpkeCtx && !ssl3_ExtensionAdvertisedClientHelloInner(ss, extension->type)) {
+ SSL_TRC(10, ("Server sent xtn type=%d which is invalid for the CHI", extension->type));
+ ss->ssl3.hs.echInvalidExtension = PR_TRUE;
+ }
+ }
+
+ /* Check that this is a legal extension in TLS 1.3 */
+ if (isTLS13 &&
+ !ssl_FindCustomExtensionHooks(ss, extension->type)) {
+ switch (tls13_ExtensionStatus(extension->type, message)) {
+ case tls13_extension_allowed:
+ break;
+ case tls13_extension_unknown:
+ if (allowNotOffered) {
+ continue; /* Skip over unknown extensions. */
+ }
+ /* RFC8446 Section 4.2 - Implementations MUST NOT send extension responses if
+ * the remote endpoint did not send the corresponding extension request ...
+ * Upon receiving such an extension, an endpoint MUST abort the handshake with
+ * an "unsupported_extension" alert. */
+ SSL_TRC(3, ("%d: TLS13: unknown extension %d in message %d",
+ SSL_GETPID(), extension, message));
+ tls13_FatalError(ss, SSL_ERROR_RX_UNEXPECTED_EXTENSION,
+ unsupported_extension);
+ return SECFailure;
+ case tls13_extension_disallowed:
+ /* RFC8446 Section 4.2 - If an implementation receives an extension which it
+ * recognizes and which is not specified for the message in which it appears,
+ * it MUST abort the handshake with an "illegal_parameter" alert. */
+ SSL_TRC(3, ("%d: TLS13: disallowed extension %d in message %d",
+ SSL_GETPID(), extension, message));
+ tls13_FatalError(ss, SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION,
+ illegal_parameter);
+ return SECFailure;
+ }
+ }
+
+ /* Special check for this being the last extension if it's
+ * PreSharedKey */
+ if (ss->sec.isServer && isTLS13 &&
+ (extension->type == ssl_tls13_pre_shared_key_xtn) &&
+ (PR_NEXT_LINK(cursor) != &ss->ssl3.hs.remoteExtensions)) {
+ tls13_FatalError(ss,
+ SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,
+ illegal_parameter);
+ return SECFailure;
+ }
+
+ rv = ssl_CallExtensionHandler(ss, message, extension, handlers);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ return SECSuccess;
+}
+
+/* Syntactic sugar around ssl3_ParseExtensions and
+ * ssl3_HandleParsedExtensions. */
+SECStatus
+ssl3_HandleExtensions(sslSocket *ss,
+ PRUint8 **b, PRUint32 *length,
+ SSLHandshakeType handshakeMessage)
+{
+ SECStatus rv;
+
+ rv = ssl3_ParseExtensions(ss, b, length);
+ if (rv != SECSuccess)
+ return rv;
+
+ rv = ssl3_HandleParsedExtensions(ss, handshakeMessage);
+ if (rv != SECSuccess)
+ return rv;
+
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+ return SECSuccess;
+}
+
+/* Add a callback function to the table of senders of server hello extensions.
+ */
+SECStatus
+ssl3_RegisterExtensionSender(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ PRUint16 ex_type,
+ sslExtensionBuilderFunc cb)
+{
+ int i;
+ sslExtensionBuilder *sender;
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ sender = &xtnData->serverHelloSenders[0];
+ } else {
+ if (tls13_ExtensionStatus(ex_type, ssl_hs_server_hello) ==
+ tls13_extension_allowed) {
+ PORT_Assert(tls13_ExtensionStatus(ex_type,
+ ssl_hs_encrypted_extensions) ==
+ tls13_extension_disallowed);
+ sender = &xtnData->serverHelloSenders[0];
+ } else if (tls13_ExtensionStatus(ex_type,
+ ssl_hs_encrypted_extensions) ==
+ tls13_extension_allowed) {
+ sender = &xtnData->encryptedExtensionsSenders[0];
+ } else if (tls13_ExtensionStatus(ex_type, ssl_hs_certificate) ==
+ tls13_extension_allowed) {
+ sender = &xtnData->certificateSenders[0];
+ } else {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ }
+ for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) {
+ if (!sender->ex_sender) {
+ sender->ex_type = ex_type;
+ sender->ex_sender = cb;
+ return SECSuccess;
+ }
+ /* detect duplicate senders */
+ PORT_Assert(sender->ex_type != ex_type);
+ if (sender->ex_type == ex_type) {
+ /* duplicate */
+ break;
+ }
+ }
+ PORT_Assert(i < SSL_MAX_EXTENSIONS); /* table needs to grow */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+}
+
+SECStatus
+ssl_CallCustomExtensionSenders(sslSocket *ss, sslBuffer *buf,
+ SSLHandshakeType message)
+{
+ sslBuffer tail = SSL_BUFFER_EMPTY;
+ SECStatus rv;
+ PRCList *cursor;
+
+ /* Save any extensions that want to be last. */
+ if (ss->xtnData.lastXtnOffset) {
+ rv = sslBuffer_Append(&tail, buf->buf + ss->xtnData.lastXtnOffset,
+ buf->len - ss->xtnData.lastXtnOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ buf->len = ss->xtnData.lastXtnOffset;
+ }
+
+ /* Reserve the maximum amount of space possible. */
+ rv = sslBuffer_Grow(buf, 65535);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
+ cursor != &ss->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslCustomExtensionHooks *hook =
+ (sslCustomExtensionHooks *)cursor;
+ PRBool append = PR_FALSE;
+ unsigned int len = 0;
+
+ if (hook->writer) {
+ /* The writer writes directly into |buf|. Provide space that allows
+ * for the existing extensions, any tail, plus type and length. */
+ unsigned int space = buf->space - (buf->len + tail.len + 4);
+ append = (*hook->writer)(ss->fd, message,
+ buf->buf + buf->len + 4, &len, space,
+ hook->writerArg);
+ if (len > space) {
+ PORT_SetError(SEC_ERROR_APPLICATION_CALLBACK_ERROR);
+ goto loser;
+ }
+ }
+ if (!append) {
+ continue;
+ }
+
+ rv = sslBuffer_AppendNumber(buf, hook->type, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ rv = sslBuffer_AppendNumber(buf, len, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ buf->len += len;
+
+ if (message == ssl_hs_client_hello ||
+ message == ssl_hs_ech_outer_client_hello ||
+ message == ssl_hs_certificate_request) {
+ ss->xtnData.advertised[ss->xtnData.numAdvertised++] = hook->type;
+ }
+ }
+
+ rv = sslBuffer_Append(buf, tail.buf, tail.len);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ sslBuffer_Clear(&tail);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&tail);
+ return SECFailure;
+}
+
+/* Call extension handlers for the given message. */
+SECStatus
+ssl_ConstructExtensions(sslSocket *ss, sslBuffer *buf, SSLHandshakeType message)
+{
+ const sslExtensionBuilder *sender;
+ SECStatus rv;
+
+ PORT_Assert(buf->len == 0);
+
+ /* Clear out any extensions previously advertised */
+ ss->xtnData.numAdvertised = 0;
+ ss->xtnData.echNumAdvertised = 0;
+
+ switch (message) {
+ case ssl_hs_client_hello:
+ if (ss->vrange.max > SSL_LIBRARY_VERSION_3_0) {
+ /* Use TLS ClientHello Extension Permutation? */
+ if (ss->opt.enableChXtnPermutation) {
+ sender = ss->ssl3.hs.chExtensionPermutation;
+ } else {
+ sender = clientHelloSendersTLS;
+ }
+ } else {
+ sender = clientHelloSendersSSL3;
+ }
+ break;
+
+ case ssl_hs_server_hello:
+ sender = ss->xtnData.serverHelloSenders;
+ break;
+
+ case ssl_hs_certificate_request:
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ sender = tls13_cert_req_senders;
+ break;
+
+ case ssl_hs_certificate:
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ sender = ss->xtnData.certificateSenders;
+ break;
+
+ case ssl_hs_encrypted_extensions:
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ sender = ss->xtnData.encryptedExtensionsSenders;
+ break;
+
+ case ssl_hs_hello_retry_request:
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ sender = tls13_hrr_senders;
+ break;
+
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ for (; sender->ex_sender != NULL; ++sender) {
+ PRUint16 ex_type = sender->ex_type;
+ PRBool append = PR_FALSE;
+ unsigned int start = buf->len;
+ unsigned int length;
+
+ if (ssl_FindCustomExtensionHooks(ss, sender->ex_type)) {
+ continue;
+ }
+
+ /* Save space for the extension type and length. Note that we don't grow
+ * the buffer now; rely on sslBuffer_Append* to do that. */
+ buf->len += 4;
+ rv = (*sender->ex_sender)(ss, &ss->xtnData, buf, &append);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Save the length and go back to the start. */
+ length = buf->len - start - 4;
+ buf->len = start;
+ if (!append) {
+ continue;
+ }
+
+ /* If TLS 1.3 GREASE is enabled, replace ssl_tls13_grease_xtn dummy
+ * GREASE extension types with randomly generated GREASE value. */
+ rv = tls13_MaybeGreaseExtensionType(ss, message, &ex_type);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ rv = sslBuffer_AppendNumber(buf, ex_type, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ rv = sslBuffer_AppendNumber(buf, length, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ /* Skip over the extension body. */
+ buf->len += length;
+
+ if (message == ssl_hs_client_hello ||
+ message == ssl_hs_certificate_request) {
+ ss->xtnData.advertised[ss->xtnData.numAdvertised++] =
+ ex_type;
+ }
+ }
+
+ if (!PR_CLIST_IS_EMPTY(&ss->extensionHooks)) {
+ if (message == ssl_hs_client_hello && ss->opt.callExtensionWriterOnEchInner) {
+ message = ssl_hs_ech_outer_client_hello;
+ }
+ rv = ssl_CallCustomExtensionSenders(ss, buf, message);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ if (buf->len > 0xffff) {
+ PORT_SetError(SSL_ERROR_TX_RECORD_TOO_LONG);
+ goto loser;
+ }
+
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(buf);
+ return SECFailure;
+}
+
+/* This extension sender can be used anywhere that an always empty extension is
+ * needed. Mostly that is for ServerHello where sender registration is dynamic;
+ * ClientHello senders are usually conditional in some way. */
+SECStatus
+ssl_SendEmptyExtension(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append)
+{
+ *append = PR_TRUE;
+ return SECSuccess;
+}
+
+/* Takes the size of the ClientHello, less the record header, and determines how
+ * much padding is required. */
+static unsigned int
+ssl_CalculatePaddingExtLen(const sslSocket *ss, unsigned int clientHelloLength)
+{
+ unsigned int extensionLen;
+
+ /* Don't pad for DTLS, for SSLv3, or for renegotiation. */
+ if (IS_DTLS(ss) ||
+ ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_0 ||
+ ss->firstHsDone) {
+ return 0;
+ }
+
+ /* A padding extension may be included to ensure that the record containing
+ * the ClientHello doesn't have a length between 256 and 511 bytes
+ * (inclusive). Initial ClientHello records with such lengths trigger bugs
+ * in F5 devices. */
+ if (clientHelloLength < 256 || clientHelloLength >= 512) {
+ return 0;
+ }
+
+ extensionLen = 512 - clientHelloLength;
+ /* Extensions take at least four bytes to encode. Always include at least
+ * one byte of data if we are padding. Some servers will time out or
+ * terminate the connection if the last ClientHello extension is empty. */
+ if (extensionLen < 5) {
+ extensionLen = 5;
+ }
+
+ return extensionLen - 4;
+}
+
+/* Manually insert an extension, retaining the position of the PSK
+ * extension, if present. */
+SECStatus
+ssl3_EmplaceExtension(sslSocket *ss, sslBuffer *buf, PRUint16 exType,
+ const PRUint8 *data, unsigned int len, PRBool advertise)
+{
+ SECStatus rv;
+ unsigned int tailLen;
+
+ /* Move the tail if there is one. This only happens if we are sending the
+ * TLS 1.3 PSK extension, which needs to be at the end. */
+ if (ss->xtnData.lastXtnOffset) {
+ PORT_Assert(buf->len > ss->xtnData.lastXtnOffset);
+ tailLen = buf->len - ss->xtnData.lastXtnOffset;
+ rv = sslBuffer_Grow(buf, buf->len + 4 + len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PORT_Memmove(buf->buf + ss->xtnData.lastXtnOffset + 4 + len,
+ buf->buf + ss->xtnData.lastXtnOffset,
+ tailLen);
+ buf->len = ss->xtnData.lastXtnOffset;
+ } else {
+ tailLen = 0;
+ }
+ if (exType == ssl_tls13_encrypted_client_hello_xtn) {
+ ss->xtnData.echXtnOffset = buf->len;
+ }
+ rv = sslBuffer_AppendNumber(buf, exType, 2);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+ rv = sslBuffer_AppendVariable(buf, data, len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+
+ if (ss->xtnData.lastXtnOffset) {
+ ss->xtnData.lastXtnOffset += 4 + len;
+ }
+
+ buf->len += tailLen;
+
+ /* False only to retain behavior with padding_xtn. Maybe
+ * we can just mark that advertised as well? TODO */
+ if (advertise) {
+ ss->xtnData.advertised[ss->xtnData.numAdvertised++] = exType;
+ }
+
+ return SECSuccess;
+}
+
+/* ssl3_SendPaddingExtension possibly adds an extension which ensures that a
+ * ClientHello record is either < 256 bytes or is >= 512 bytes. This ensures
+ * that we don't trigger bugs in F5 products.
+ *
+ * This takes an existing extension buffer, |buf|, and the length of the
+ * remainder of the ClientHello, |prefixLen|. It modifies the extension buffer
+ * to insert padding at the right place.
+ */
+SECStatus
+ssl_InsertPaddingExtension(sslSocket *ss, unsigned int prefixLen,
+ sslBuffer *buf)
+{
+ static unsigned char padding[252] = { 0 };
+ unsigned int paddingLen;
+ /* Exit early if an application-provided extension hook
+ * already added padding. */
+ if (ssl3_ExtensionAdvertised(ss, ssl_padding_xtn)) {
+ return SECSuccess;
+ }
+
+ /* Account for the size of the header, the length field of the extensions
+ * block and the size of the existing extensions. */
+ paddingLen = ssl_CalculatePaddingExtLen(ss, prefixLen + 2 + buf->len);
+ if (!paddingLen) {
+ return SECSuccess;
+ }
+
+ return ssl3_EmplaceExtension(ss, buf, ssl_padding_xtn, padding, paddingLen, PR_FALSE);
+}
+
+void
+ssl3_MoveRemoteExtensions(PRCList *dst, PRCList *src)
+{
+ PRCList *cur_p;
+ while (!PR_CLIST_IS_EMPTY(src)) {
+ cur_p = PR_LIST_TAIL(src);
+ PR_REMOVE_LINK(cur_p);
+ PR_INSERT_LINK(cur_p, dst);
+ }
+}
+
+void
+ssl3_DestroyRemoteExtensions(PRCList *list)
+{
+ PRCList *cur_p;
+
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ cur_p = PR_LIST_TAIL(list);
+ PR_REMOVE_LINK(cur_p);
+ PORT_Free(cur_p);
+ }
+}
+
+/* Initialize the extension data block. */
+void
+ssl3_InitExtensionData(TLSExtensionData *xtnData, const sslSocket *ss)
+{
+ unsigned int advertisedMax;
+ PRCList *cursor;
+
+ /* Set things up to the right starting state. */
+ PORT_Memset(xtnData, 0, sizeof(*xtnData));
+ xtnData->peerSupportsFfdheGroups = PR_FALSE;
+ PR_INIT_CLIST(&xtnData->remoteKeyShares);
+
+ /* Allocate enough to allow for native extensions, plus any custom ones. */
+ if (ss->sec.isServer) {
+ advertisedMax = PR_MAX(PR_ARRAY_SIZE(certificateRequestHandlers),
+ PR_ARRAY_SIZE(tls13_cert_req_senders));
+ } else {
+ advertisedMax = PR_MAX(PR_ARRAY_SIZE(clientHelloHandlers),
+ PR_ARRAY_SIZE(clientHelloSendersTLS));
+ ++advertisedMax; /* For the RI SCSV, which we also track. */
+ }
+ for (cursor = PR_NEXT_LINK(&ss->extensionHooks);
+ cursor != &ss->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ ++advertisedMax;
+ }
+ xtnData->advertised = PORT_ZNewArray(PRUint16, advertisedMax);
+ xtnData->echAdvertised = PORT_ZNewArray(PRUint16, advertisedMax);
+
+ xtnData->peerDelegCred = NULL;
+ xtnData->peerRequestedDelegCred = PR_FALSE;
+ xtnData->sendingDelegCredToPeer = PR_FALSE;
+ xtnData->selectedPsk = NULL;
+}
+
+void
+ssl3_DestroyExtensionData(TLSExtensionData *xtnData)
+{
+ ssl3_FreeSniNameArray(xtnData);
+ PORT_Free(xtnData->sigSchemes);
+ PORT_Free(xtnData->delegCredSigSchemes);
+ PORT_Free(xtnData->delegCredSigSchemesAdvertised);
+ SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
+ tls13_DestroyKeyShares(&xtnData->remoteKeyShares);
+ SECITEM_FreeItem(&xtnData->certReqContext, PR_FALSE);
+ SECITEM_FreeItem(&xtnData->applicationToken, PR_FALSE);
+ if (xtnData->certReqAuthorities.arena) {
+ PORT_FreeArena(xtnData->certReqAuthorities.arena, PR_FALSE);
+ xtnData->certReqAuthorities.arena = NULL;
+ }
+ PORT_Free(xtnData->advertised);
+ PORT_Free(xtnData->echAdvertised);
+ tls13_DestroyDelegatedCredential(xtnData->peerDelegCred);
+
+ tls13_DestroyEchXtnState(xtnData->ech);
+ xtnData->ech = NULL;
+}
+
+/* Free everything that has been allocated and then reset back to
+ * the starting state. */
+void
+ssl3_ResetExtensionData(TLSExtensionData *xtnData, const sslSocket *ss)
+{
+ ssl3_DestroyExtensionData(xtnData);
+ ssl3_InitExtensionData(xtnData, ss);
+}
+
+/* Thunks to let extension handlers operate on const sslSocket* objects. */
+void
+ssl3_ExtSendAlert(const sslSocket *ss, SSL3AlertLevel level,
+ SSL3AlertDescription desc)
+{
+ (void)SSL3_SendAlert((sslSocket *)ss, level, desc);
+}
+
+void
+ssl3_ExtDecodeError(const sslSocket *ss)
+{
+ (void)ssl3_DecodeError((sslSocket *)ss);
+}
+
+SECStatus
+ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRUint32 bytes,
+ PRUint8 **b, PRUint32 *length)
+{
+ return ssl3_ConsumeHandshake((sslSocket *)ss, v, bytes, b, length);
+}
+
+SECStatus
+ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRUint32 *num,
+ PRUint32 bytes, PRUint8 **b, PRUint32 *length)
+{
+ return ssl3_ConsumeHandshakeNumber((sslSocket *)ss, num, bytes, b, length);
+}
+
+SECStatus
+ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i,
+ PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length)
+{
+ return ssl3_ConsumeHandshakeVariable((sslSocket *)ss, i, bytes, b, length);
+}
+
+SECStatus
+tls_ClientHelloExtensionPermutationSetup(sslSocket *ss)
+{
+ size_t buildersLen = PR_ARRAY_SIZE(clientHelloSendersTLS);
+ const size_t buildersSize = (sizeof(sslExtensionBuilder) * buildersLen);
+ /* Psk Extension and then NULL entry MUST be last. */
+ const size_t permutationLen = buildersLen - 2;
+
+ /* There shouldn't already be a stored permutation. */
+ PR_ASSERT(!ss->ssl3.hs.chExtensionPermutation);
+
+ /* This shuffle handles up to 256 extensions. */
+ PR_ASSERT(buildersLen < 256);
+ uint8_t permutation[256] = { 0 };
+
+ sslExtensionBuilder *builders = PORT_ZAlloc(buildersSize);
+ if (!builders) {
+ return SECFailure;
+ }
+
+ /* Get a working copy of default builders. */
+ PORT_Memcpy(builders, clientHelloSendersTLS, buildersSize);
+
+ /* Get permutation randoms. */
+ if (PK11_GenerateRandom(permutation, permutationLen) != SECSuccess) {
+ PORT_Free(builders);
+ return SECFailure;
+ }
+
+ /* Fisher-Yates Shuffle */
+ for (size_t i = permutationLen - 1; i > 0; i--) {
+ size_t idx = permutation[i - 1] % (i + 1);
+ sslExtensionBuilder tmp = builders[i];
+ builders[i] = builders[idx];
+ builders[idx] = tmp;
+ }
+
+ /* Make sure that Psk extension is penultimate (before NULL entry). */
+ PR_ASSERT(builders[buildersLen - 2].ex_type == ssl_tls13_pre_shared_key_xtn);
+ PR_ASSERT(builders[buildersLen - 2].ex_sender == clientHelloSendersTLS[buildersLen - 2].ex_sender);
+
+ ss->ssl3.hs.chExtensionPermutation = builders;
+ return SECSuccess;
+}
+
+void
+tls_ClientHelloExtensionPermutationDestroy(sslSocket *ss)
+{
+ if (ss->ssl3.hs.chExtensionPermutation) {
+ PORT_Free(ss->ssl3.hs.chExtensionPermutation);
+ ss->ssl3.hs.chExtensionPermutation = NULL;
+ }
+}
diff --git a/security/nss/lib/ssl/ssl3ext.h b/security/nss/lib/ssl/ssl3ext.h
new file mode 100644
index 0000000000..d582e2b2c3
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3ext.h
@@ -0,0 +1,212 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __ssl3ext_h_
+#define __ssl3ext_h_
+
+#include "pk11hpke.h"
+#include "sslencode.h"
+
+typedef enum {
+ sni_nametype_hostname
+} SNINameType;
+typedef struct TLSExtensionDataStr TLSExtensionData;
+
+/* Registerable callback function that either appends extension to buffer
+ * or returns length of data that it would have appended.
+ */
+typedef SECStatus (*sslExtensionBuilderFunc)(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+
+/* row in a table of hello extension senders */
+typedef struct {
+ PRInt32 ex_type;
+ sslExtensionBuilderFunc ex_sender;
+} sslExtensionBuilder;
+
+struct TLSExtensionDataStr {
+ /* registered callbacks that send server hello extensions */
+ sslExtensionBuilder serverHelloSenders[SSL_MAX_EXTENSIONS];
+ sslExtensionBuilder encryptedExtensionsSenders[SSL_MAX_EXTENSIONS];
+ sslExtensionBuilder certificateSenders[SSL_MAX_EXTENSIONS];
+
+ /* Keep track of the extensions that are advertised or negotiated. */
+ PRUint16 numAdvertised;
+ PRUint16 *advertised; /* Allocated dynamically. */
+ PRUint16 echNumAdvertised; /* Tracks Xtns offered in ClientHelloInner. */
+ PRUint16 *echAdvertised;
+ PRUint16 numNegotiated;
+ PRUint16 negotiated[SSL_MAX_EXTENSIONS];
+
+ /* SessionTicket Extension related data. */
+ PRBool ticketTimestampVerified;
+ PRBool emptySessionTicket;
+ PRBool sentSessionTicketInClientHello;
+ SECItem psk_ke_modes;
+ PRUint32 max_early_data_size;
+
+ /* SNI Extension related data
+ * Names data is not coppied from the input buffer. It can not be
+ * used outside the scope where input buffer is defined and that
+ * is beyond ssl3_HandleClientHello function. */
+ SECItem *sniNameArr;
+ PRUint32 sniNameArrSize;
+
+ /* Signed Certificate Timestamps extracted from the TLS extension.
+ * (client only).
+ * This container holds a temporary pointer to the extension data,
+ * until a session structure (the sec.ci.sid of an sslSocket) is setup
+ * that can hold a permanent copy of the data
+ * (in sec.ci.sid.u.ssl3.signedCertTimestamps).
+ * The data pointed to by this structure is neither explicitly allocated
+ * nor copied: the pointer points to the handshake message buffer and is
+ * only valid in the scope of ssl3_HandleServerHello.
+ */
+ SECItem signedCertTimestamps;
+
+ PRBool peerSupportsFfdheGroups; /* if the peer supports named ffdhe groups */
+
+ /* clientSigAndHash contains the contents of the signature_algorithms
+ * extension (if any) the other side supports. This is only valid for TLS
+ * 1.2 or later. In TLS 1.3, it is also used for CertificateRequest. */
+ SSLSignatureScheme *sigSchemes;
+ unsigned int numSigSchemes;
+
+ /* Keep track of signature schemes that the remote peer supports for
+ * Delegated Credentials signatures, as well was those we have
+ * advertised (for purposes of validating any received DC).
+ * This list may not be the same as those supported for certificates.
+ * Only valid for TLS 1.3. */
+ SSLSignatureScheme *delegCredSigSchemes;
+ unsigned int numDelegCredSigSchemes;
+ SSLSignatureScheme *delegCredSigSchemesAdvertised;
+ unsigned int numDelegCredSigSchemesAdvertised;
+
+ SECItem certReqContext;
+ CERTDistNames certReqAuthorities;
+
+ /* In a client: if the server supports Next Protocol Negotiation, then
+ * this is the protocol that was negotiated.
+ */
+ SECItem nextProto;
+ SSLNextProtoState nextProtoState;
+
+ PRUint16 dtlsSRTPCipherSuite; /* 0 if not selected */
+
+ unsigned int echXtnOffset; /* The start of the ECH Xtn (if any) */
+ unsigned int lastXtnOffset; /* Where to insert any other extensions.
+ * 0 = end, otherwise base of PSK xtn. */
+ PRCList remoteKeyShares; /* The other side's public keys (TLS 1.3) */
+
+ /* The following are used by a TLS 1.3 server. */
+ SECItem pskBinder; /* The binder for the first PSK. */
+ unsigned int pskBindersLen; /* The length of the binders. */
+ PRUint32 ticketAge; /* Used to accept early data. */
+ SECItem cookie; /* HRR Cookie. */
+ const sslNamedGroupDef *selectedGroup; /* For HRR. */
+ /* The application token contains a value that was passed to the client via
+ * a session ticket, or the cookie in a HelloRetryRequest. */
+ SECItem applicationToken;
+
+ /* The record size limit set by the peer. Our value is kept in ss->opt. */
+ PRUint16 recordSizeLimit;
+
+ /* Delegated credentials.
+ *
+ * The delegated credential sent by the peer. Set by
+ * |tls13_ReadDelegatedCredential|.
+ */
+ sslDelegatedCredential *peerDelegCred;
+ /* Whether the peer requested a delegated credential. */
+ PRBool peerRequestedDelegCred;
+ /* Whether the host is committed to using a delegated credential. Set by
+ * |tls13_MaybeSetDelegatedCredential|.
+ */
+ PRBool sendingDelegCredToPeer;
+
+ /* A non-owning reference to the selected PSKs. MUST NOT be freed directly,
+ * rather through tls13_DestoryPskList(). */
+ sslPsk *selectedPsk;
+
+ /* ECH working state. Non-null when a valid Encrypted Client Hello extension
+ * was received. */
+ sslEchXtnState *ech;
+};
+
+typedef struct TLSExtensionStr {
+ PRCList link; /* The linked list link */
+ PRUint16 type; /* Extension type */
+ SECItem data; /* Pointers into the handshake data. */
+} TLSExtension;
+
+typedef struct sslCustomExtensionHooks {
+ PRCList link;
+ PRUint16 type;
+ SSLExtensionWriter writer;
+ void *writerArg;
+ SSLExtensionHandler handler;
+ void *handlerArg;
+} sslCustomExtensionHooks;
+
+SECStatus ssl3_HandleExtensions(sslSocket *ss,
+ PRUint8 **b, PRUint32 *length,
+ SSLHandshakeType handshakeMessage);
+SECStatus ssl3_ParseExtensions(sslSocket *ss,
+ PRUint8 **b, PRUint32 *length);
+SECStatus ssl3_HandleParsedExtensions(sslSocket *ss,
+ SSLHandshakeType handshakeMessage);
+TLSExtension *ssl3_FindExtension(sslSocket *ss,
+ SSLExtensionType extension_type);
+void ssl3_DestroyRemoteExtensions(PRCList *list);
+void ssl3_MoveRemoteExtensions(PRCList *dst, PRCList *src);
+void ssl3_InitExtensionData(TLSExtensionData *xtnData, const sslSocket *ss);
+void ssl3_DestroyExtensionData(TLSExtensionData *xtnData);
+void ssl3_ResetExtensionData(TLSExtensionData *xtnData, const sslSocket *ss);
+
+PRBool ssl3_ExtensionNegotiated(const sslSocket *ss, PRUint16 ex_type);
+PRBool ssl3_ExtensionAdvertised(const sslSocket *ss, PRUint16 ex_type);
+
+SECStatus ssl3_RegisterExtensionSender(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ PRUint16 ex_type,
+ sslExtensionBuilderFunc cb);
+SECStatus ssl_ConstructExtensions(sslSocket *ss, sslBuffer *buf,
+ SSLHandshakeType message);
+SECStatus ssl_SendEmptyExtension(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus ssl3_EmplaceExtension(sslSocket *ss, sslBuffer *buf, PRUint16 exType,
+ const PRUint8 *data, unsigned int len, PRBool advertise);
+SECStatus ssl_InsertPaddingExtension(sslSocket *ss, unsigned int prefixLen,
+ sslBuffer *buf);
+
+/* Thunks to let us operate on const sslSocket* objects. */
+void ssl3_ExtSendAlert(const sslSocket *ss, SSL3AlertLevel level,
+ SSL3AlertDescription desc);
+void ssl3_ExtDecodeError(const sslSocket *ss);
+SECStatus ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRUint32 bytes,
+ PRUint8 **b, PRUint32 *length);
+SECStatus ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRUint32 *num,
+ PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length);
+SECStatus ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i,
+ PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length);
+
+SECStatus SSLExp_GetExtensionSupport(PRUint16 type,
+ SSLExtensionSupport *support);
+SECStatus SSLExp_InstallExtensionHooks(
+ PRFileDesc *fd, PRUint16 extension, SSLExtensionWriter writer,
+ void *writerArg, SSLExtensionHandler handler, void *handlerArg);
+sslCustomExtensionHooks *ssl_FindCustomExtensionHooks(sslSocket *ss, PRUint16 extension);
+SECStatus ssl_CallCustomExtensionSenders(sslSocket *ss, sslBuffer *buf,
+ SSLHandshakeType message);
+SECStatus tls_ClientHelloExtensionPermutationSetup(sslSocket *ss);
+void tls_ClientHelloExtensionPermutationDestroy(sslSocket *ss);
+
+#endif
diff --git a/security/nss/lib/ssl/ssl3exthandle.c b/security/nss/lib/ssl/ssl3exthandle.c
new file mode 100644
index 0000000000..cafddd81fd
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3exthandle.c
@@ -0,0 +1,2004 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nssrenam.h"
+#include "nss.h"
+#include "ssl.h"
+#include "sslproto.h"
+#include "sslimpl.h"
+#include "pk11pub.h"
+#include "blapit.h"
+#include "prinit.h"
+#include "selfencrypt.h"
+#include "ssl3ext.h"
+#include "ssl3exthandle.h"
+#include "tls13ech.h"
+#include "tls13exthandle.h" /* For tls13_ServerSendStatusRequestXtn. */
+
+PRBool
+ssl_ShouldSendSNIExtension(const sslSocket *ss, const char *url)
+{
+ PRNetAddr netAddr;
+
+ /* must have a hostname */
+ if (!url || !url[0]) {
+ return PR_FALSE;
+ }
+ /* must not be an IPv4 or IPv6 address */
+ if (PR_SUCCESS == PR_StringToNetAddr(url, &netAddr)) {
+ /* is an IP address (v4 or v6) */
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+/* Format an SNI extension, using the name from the socket's URL,
+ * unless that name is a dotted decimal string.
+ * Used by client and server.
+ */
+SECStatus
+ssl3_ClientFormatServerNameXtn(const sslSocket *ss, const char *url,
+ unsigned int len, TLSExtensionData *xtnData,
+ sslBuffer *buf)
+{
+ SECStatus rv;
+
+ /* length of server_name_list */
+ rv = sslBuffer_AppendNumber(buf, len + 3, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* Name Type (sni_host_name) */
+ rv = sslBuffer_AppendNumber(buf, 0, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* HostName (length and value) */
+ rv = sslBuffer_AppendVariable(buf, (const PRUint8 *)url, len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ClientSendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ const char *url = ss->url;
+
+ if (!ssl_ShouldSendSNIExtension(ss, url)) {
+ return SECSuccess;
+ }
+
+ /* If ECH, write the public name. The real server name
+ * is emplaced while constructing CHInner extensions. */
+ sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
+ const char *sniContents = PR_CLIST_IS_EMPTY(&ss->echConfigs) ? url : cfg->contents.publicName;
+ rv = ssl3_ClientFormatServerNameXtn(ss, sniContents, strlen(sniContents), xtnData, buf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECItem *names = NULL;
+ PRUint32 listLenBytes = 0;
+ SECStatus rv;
+
+ if (!ss->sec.isServer) {
+ return SECSuccess; /* ignore extension */
+ }
+
+ /* Server side - consume client data and register server sender. */
+ /* do not parse the data if don't have user extension handling function. */
+ if (!ss->sniSocketConfig) {
+ return SECSuccess;
+ }
+
+ /* length of server_name_list */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &listLenBytes, 2, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto loser; /* alert already sent */
+ }
+ if (listLenBytes == 0 || listLenBytes != data->len) {
+ goto alert_loser;
+ }
+
+ /* Read ServerNameList. */
+ while (data->len > 0) {
+ SECItem tmp;
+ PRUint32 type;
+
+ /* Read Name Type. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &type, 1, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ /* alert sent in ConsumeHandshakeNumber */
+ goto loser;
+ }
+
+ /* Read ServerName (length and value). */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &tmp, 2, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Record the value for host_name(0). */
+ if (type == sni_nametype_hostname) {
+ /* Fail if we encounter a second host_name entry. */
+ if (names) {
+ goto alert_loser;
+ }
+
+ /* Create an array for the only supported NameType. */
+ names = PORT_ZNewArray(SECItem, 1);
+ if (!names) {
+ goto loser;
+ }
+
+ /* Copy ServerName into the array. */
+ if (SECITEM_CopyItem(NULL, &names[0], &tmp) != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ /* Even if we don't support NameTypes other than host_name at the
+ * moment, we continue parsing the whole list to check its validity.
+ * We do not check for duplicate entries with NameType != host_name(0).
+ */
+ }
+ if (names) {
+ /* Free old and set the new data. */
+ ssl3_FreeSniNameArray(xtnData);
+ xtnData->sniNameArr = names;
+ xtnData->sniNameArrSize = 1;
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn;
+ }
+ return SECSuccess;
+
+alert_loser:
+ ssl3_ExtDecodeError(ss);
+loser:
+ if (names) {
+ PORT_Free(names);
+ }
+ return SECFailure;
+}
+
+/* Frees a given xtnData->sniNameArr and its elements. */
+void
+ssl3_FreeSniNameArray(TLSExtensionData *xtnData)
+{
+ PRUint32 i;
+
+ if (!xtnData->sniNameArr) {
+ return;
+ }
+
+ for (i = 0; i < xtnData->sniNameArrSize; i++) {
+ SECITEM_FreeItem(&xtnData->sniNameArr[i], PR_FALSE);
+ }
+
+ PORT_Free(xtnData->sniNameArr);
+ xtnData->sniNameArr = NULL;
+ xtnData->sniNameArrSize = 0;
+}
+
+/* Called by both clients and servers.
+ * Clients sends a filled in session ticket if one is available, and otherwise
+ * sends an empty ticket. Servers always send empty tickets.
+ */
+SECStatus
+ssl3_ClientSendSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ NewSessionTicket *session_ticket = NULL;
+ sslSessionID *sid = ss->sec.ci.sid;
+ SECStatus rv;
+
+ PORT_Assert(!ss->sec.isServer);
+
+ /* Never send an extension with a ticket for TLS 1.3, but
+ * OK to send the empty one in case the server does 1.2. */
+ if ((sid->cached == in_client_cache || sid->cached == in_external_cache) &&
+ sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ /* Ignore the SessionTicket extension if processing is disabled. */
+ if (!ss->opt.enableSessionTickets) {
+ return SECSuccess;
+ }
+
+ /* Send a session ticket if one is available.
+ *
+ * The caller must be holding sid->u.ssl3.lock for reading. We cannot
+ * just acquire and release the lock within this function because the
+ * caller will call this function twice, and we need the inputs to be
+ * consistent between the two calls. Note that currently the caller
+ * will only be holding the lock when we are the client and when we're
+ * attempting to resume an existing session.
+ */
+ session_ticket = &sid->u.ssl3.locked.sessionTicket;
+ if (session_ticket->ticket.data &&
+ (xtnData->ticketTimestampVerified ||
+ ssl_TicketTimeValid(ss, session_ticket))) {
+
+ xtnData->ticketTimestampVerified = PR_FALSE;
+
+ rv = sslBuffer_Append(buf, session_ticket->ticket.data,
+ session_ticket->ticket.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ xtnData->sentSessionTicketInClientHello = PR_TRUE;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+PRBool
+ssl_AlpnTagAllowed(const sslSocket *ss, const SECItem *tag)
+{
+ const unsigned char *data = ss->opt.nextProtoNego.data;
+ unsigned int length = ss->opt.nextProtoNego.len;
+ unsigned int offset = 0;
+
+ if (!tag->len)
+ return PR_TRUE;
+
+ while (offset < length) {
+ unsigned int taglen = (unsigned int)data[offset];
+ if ((taglen == tag->len) &&
+ !PORT_Memcmp(data + offset + 1, tag->data, tag->len))
+ return PR_TRUE;
+ offset += 1 + taglen;
+ }
+
+ return PR_FALSE;
+}
+
+/* ssl3_ValidateAppProtocol checks that the given block of data is valid: none
+ * of the lengths may be 0 and the sum of the lengths must equal the length of
+ * the block. */
+SECStatus
+ssl3_ValidateAppProtocol(const unsigned char *data, unsigned int length)
+{
+ unsigned int offset = 0;
+
+ while (offset < length) {
+ unsigned int newOffset = offset + 1 + (unsigned int)data[offset];
+ /* Reject embedded nulls to protect against buggy applications that
+ * store protocol identifiers in null-terminated strings.
+ */
+ if (newOffset > length || data[offset] == 0) {
+ return SECFailure;
+ }
+ offset = newOffset;
+ }
+
+ return SECSuccess;
+}
+
+/* Protocol selection handler for ALPN. */
+static SECStatus
+ssl3_SelectAppProtocol(const sslSocket *ss, TLSExtensionData *xtnData,
+ PRUint16 extension, SECItem *data)
+{
+ SECStatus rv;
+ unsigned char resultBuffer[255];
+ SECItem result = { siBuffer, resultBuffer, 0 };
+
+ rv = ssl3_ValidateAppProtocol(data->data, data->len);
+ if (rv != SECSuccess) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ return SECFailure;
+ }
+
+ PORT_Assert(ss->nextProtoCallback);
+ /* Neither the cipher suite nor ECH are selected yet Note that extensions
+ * sometimes affect what cipher suite is selected, e.g., for ECC. */
+ PORT_Assert((ss->ssl3.hs.preliminaryInfo &
+ ssl_preinfo_all & ~ssl_preinfo_cipher_suite & ~ssl_preinfo_ech) ==
+ (ssl_preinfo_all & ~ssl_preinfo_cipher_suite & ~ssl_preinfo_ech));
+ /* The callback has to make sure that either rv != SECSuccess or that result
+ * is not set if there is no common protocol. */
+ rv = ss->nextProtoCallback(ss->nextProtoArg, ss->fd, data->data, data->len,
+ result.data, &result.len, sizeof(resultBuffer));
+ if (rv != SECSuccess) {
+ /* Expect callback to call PORT_SetError() */
+ ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
+ return SECFailure;
+ }
+
+ /* If the callback wrote more than allowed to |result| it has corrupted our
+ * stack. */
+ if (result.len > sizeof(resultBuffer)) {
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ PORT_Assert(PR_FALSE);
+ return SECFailure;
+ }
+
+ SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
+
+ if (result.len < 1 || !result.data) {
+ /* Check that we actually got a result. */
+ ssl3_ExtSendAlert(ss, alert_fatal, no_application_protocol);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL);
+ return SECFailure;
+ }
+
+ xtnData->nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
+ xtnData->negotiated[xtnData->numNegotiated++] = extension;
+ return SECITEM_CopyItem(NULL, &xtnData->nextProto, &result);
+}
+
+/* handle an incoming ALPN extension at the server */
+SECStatus
+ssl3_ServerHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PRUint32 count;
+ SECStatus rv;
+
+ /* We expressly don't want to allow ALPN on renegotiation,
+ * despite it being permitted by the spec. */
+ if (ss->firstHsDone || data->len == 0) {
+ /* Clients MUST send a non-empty ALPN extension. */
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ return SECFailure;
+ }
+
+ /* ALPN has extra redundant length information so that
+ * the extension is the same in both ClientHello and ServerHello. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &count, 2, &data->data, &data->len);
+ if (rv != SECSuccess || count != data->len) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+
+ if (!ss->nextProtoCallback) {
+ /* we're not configured for it */
+ return SECSuccess;
+ }
+
+ rv = ssl3_SelectAppProtocol(ss, xtnData, ssl_app_layer_protocol_xtn, data);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ /* prepare to send back a response, if we negotiated */
+ if (xtnData->nextProtoState == SSL_NEXT_PROTO_NEGOTIATED) {
+ rv = ssl3_RegisterExtensionSender(ss, xtnData,
+ ssl_app_layer_protocol_xtn,
+ ssl3_ServerSendAppProtoXtn);
+ if (rv != SECSuccess) {
+ ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+ }
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ClientHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PRUint32 list_len;
+ SECItem protocol_name;
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_next_proto_nego_xtn)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* The extension data from the server has the following format:
+ * uint16 name_list_len;
+ * uint8 len; // where len >= 1
+ * uint8 protocol_name[len]; */
+ if (data->len < 4 || data->len > 2 + 1 + 255) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ return SECFailure;
+ }
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &list_len, 2, &data->data,
+ &data->len);
+ /* The list has to be the entire extension. */
+ if (rv != SECSuccess || list_len != data->len) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ return SECFailure;
+ }
+
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &protocol_name, 1,
+ &data->data, &data->len);
+ /* The list must have exactly one value. */
+ if (rv != SECSuccess || data->len != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ return SECFailure;
+ }
+
+ if (!ssl_AlpnTagAllowed(ss, &protocol_name)) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID);
+ return SECFailure;
+ }
+
+ SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE);
+ xtnData->nextProtoState = SSL_NEXT_PROTO_SELECTED;
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_app_layer_protocol_xtn;
+ return SECITEM_CopyItem(NULL, &xtnData->nextProto, &protocol_name);
+}
+
+SECStatus
+ssl3_ClientSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ /* Renegotiations do not send this extension. */
+ if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.len || ss->firstHsDone) {
+ PR_ASSERT(!ss->opt.nextProtoNego.data);
+ return SECSuccess;
+ }
+ PRBool addGrease = ss->opt.enableGrease && ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3;
+
+ /* The list of protocol strings is prefixed with a 2-byte length */
+ rv = sslBuffer_AppendNumber(buf, ss->opt.nextProtoNego.len + (addGrease ? 3 : 0), 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* The list of protocol strings */
+ rv = sslBuffer_Append(buf, ss->opt.nextProtoNego.data, ss->opt.nextProtoNego.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* A client MAY select one or more GREASE ALPN identifiers and advertise
+ * them in the "application_layer_protocol_negotiation" extension, if sent
+ * [RFC8701, Section 3.1]. */
+ if (addGrease) {
+ rv = sslBuffer_AppendNumber(buf, 2, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_alpn], 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ServerSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ /* We're in over our heads if any of these fail */
+ PORT_Assert(ss->opt.enableALPN);
+ PORT_Assert(xtnData->nextProto.data);
+ PORT_Assert(xtnData->nextProto.len > 0);
+ PORT_Assert(xtnData->nextProtoState == SSL_NEXT_PROTO_NEGOTIATED);
+ PORT_Assert(!ss->firstHsDone);
+
+ rv = sslBuffer_AppendNumber(buf, xtnData->nextProto.len + 1, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(buf, xtnData->nextProto.data,
+ xtnData->nextProto.len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ServerHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ sslExtensionBuilderFunc sender;
+
+ PORT_Assert(ss->sec.isServer);
+
+ /* remember that we got this extension. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_cert_status_xtn;
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ sender = tls13_ServerSendStatusRequestXtn;
+ } else {
+ sender = ssl3_ServerSendStatusRequestXtn;
+ }
+ return ssl3_RegisterExtensionSender(ss, xtnData, ssl_cert_status_xtn, sender);
+}
+
+SECStatus
+ssl3_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ const sslServerCert *serverCert = ss->sec.serverCert;
+
+ if (!serverCert->certStatusArray ||
+ !serverCert->certStatusArray->len) {
+ return SECSuccess;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the
+ * client side. See RFC 6066 section 8. */
+SECStatus
+ssl3_ClientSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ if (!ss->opt.enableOCSPStapling) {
+ return SECSuccess;
+ }
+
+ rv = sslBuffer_AppendNumber(buf, 1 /* status_type ocsp */, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* A zero length responder_id_list means that the responders are
+ * implicitly known to the server. */
+ rv = sslBuffer_AppendNumber(buf, 0, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* A zero length request_extensions means that there are no extensions.
+ * Specifically, we don't set the id-pkix-ocsp-nonce extension. This
+ * means that the server can replay a cached OCSP response to us. */
+ rv = sslBuffer_AppendNumber(buf, 0, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ClientHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ /* In TLS 1.3, the extension carries the OCSP response. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ SECStatus rv;
+ rv = ssl_ReadCertificateStatus(CONST_CAST(sslSocket, ss),
+ data->data, data->len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* code already set */
+ }
+ } else if (data->len != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_cert_status_xtn;
+ return SECSuccess;
+}
+
+#define TLS_EX_SESS_TICKET_VERSION (0x010a)
+
+/*
+ * Called from ssl3_SendNewSessionTicket, tls13_SendNewSessionTicket
+ */
+SECStatus
+ssl3_EncodeSessionTicket(sslSocket *ss, const NewSessionTicket *ticket,
+ const PRUint8 *appToken, unsigned int appTokenLen,
+ PK11SymKey *secret, SECItem *ticket_data)
+{
+ SECStatus rv;
+ sslBuffer plaintext = SSL_BUFFER_EMPTY;
+ SECItem ticket_buf = { 0, NULL, 0 };
+ sslSessionID sid;
+ unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH];
+ SECItem ms_item = { 0, NULL, 0 };
+ PRTime now;
+ SECItem *srvName = NULL;
+ CK_MECHANISM_TYPE msWrapMech;
+ SECItem *alpnSelection = NULL;
+ PRUint32 ticketAgeBaseline;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: send session_ticket handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ /* Extract the master secret wrapped. */
+
+ PORT_Memset(&sid, 0, sizeof(sslSessionID));
+
+ PORT_Assert(secret);
+ rv = ssl3_CacheWrappedSecret(ss, &sid, secret);
+ if (rv == SECSuccess) {
+ if (sid.u.ssl3.keys.wrapped_master_secret_len > sizeof(wrapped_ms))
+ goto loser;
+ memcpy(wrapped_ms, sid.u.ssl3.keys.wrapped_master_secret,
+ sid.u.ssl3.keys.wrapped_master_secret_len);
+ ms_item.data = wrapped_ms;
+ ms_item.len = sid.u.ssl3.keys.wrapped_master_secret_len;
+ msWrapMech = sid.u.ssl3.masterWrapMech;
+ } else {
+ /* TODO: else send an empty ticket. */
+ goto loser;
+ }
+ /* Prep to send negotiated name */
+ srvName = &ss->sec.ci.sid->u.ssl3.srvName;
+
+ /* ticket version */
+ rv = sslBuffer_AppendNumber(&plaintext, TLS_EX_SESS_TICKET_VERSION,
+ sizeof(PRUint16));
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* ssl_version */
+ rv = sslBuffer_AppendNumber(&plaintext, ss->version,
+ sizeof(SSL3ProtocolVersion));
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* ciphersuite */
+ rv = sslBuffer_AppendNumber(&plaintext, ss->ssl3.hs.cipher_suite,
+ sizeof(ssl3CipherSuite));
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* cipher spec parameters */
+ rv = sslBuffer_AppendNumber(&plaintext, ss->sec.authType, 1);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = sslBuffer_AppendNumber(&plaintext, ss->sec.authKeyBits, 4);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = sslBuffer_AppendNumber(&plaintext, ss->sec.keaType, 1);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = sslBuffer_AppendNumber(&plaintext, ss->sec.keaKeyBits, 4);
+ if (rv != SECSuccess)
+ goto loser;
+ if (ss->sec.keaGroup) {
+ rv = sslBuffer_AppendNumber(&plaintext, ss->sec.keaGroup->name, 4);
+ if (rv != SECSuccess)
+ goto loser;
+ } else {
+ /* No kea group. Write 0 as invalid value. */
+ rv = sslBuffer_AppendNumber(&plaintext, 0, 4);
+ if (rv != SECSuccess)
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(&plaintext, ss->sec.signatureScheme, 4);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* certificate type */
+ PORT_Assert(SSL_CERT_IS(ss->sec.serverCert, ss->sec.authType));
+ if (SSL_CERT_IS_EC(ss->sec.serverCert)) {
+ const sslServerCert *cert = ss->sec.serverCert;
+ PORT_Assert(cert->namedCurve);
+ /* EC curves only use the second of the two bytes. */
+ PORT_Assert(cert->namedCurve->name < 256);
+ rv = sslBuffer_AppendNumber(&plaintext, cert->namedCurve->name, 1);
+ } else {
+ rv = sslBuffer_AppendNumber(&plaintext, 0, 1);
+ }
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* master_secret */
+ rv = sslBuffer_AppendNumber(&plaintext, msWrapMech, 4);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = sslBuffer_AppendVariable(&plaintext, ms_item.data, ms_item.len, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* client identity */
+ if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) {
+ rv = sslBuffer_AppendNumber(&plaintext, CLIENT_AUTH_CERTIFICATE, 1);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = sslBuffer_AppendVariable(&plaintext,
+ ss->sec.ci.sid->peerCert->derCert.data,
+ ss->sec.ci.sid->peerCert->derCert.len, 2);
+ if (rv != SECSuccess)
+ goto loser;
+ } else {
+ rv = sslBuffer_AppendNumber(&plaintext, 0, 1);
+ if (rv != SECSuccess)
+ goto loser;
+ }
+
+ /* timestamp */
+ now = ssl_Time(ss);
+ PORT_Assert(sizeof(now) == 8);
+ rv = sslBuffer_AppendNumber(&plaintext, now, 8);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* HostName (length and value) */
+ rv = sslBuffer_AppendVariable(&plaintext, srvName->data, srvName->len, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* extendedMasterSecretUsed */
+ rv = sslBuffer_AppendNumber(
+ &plaintext, ss->sec.ci.sid->u.ssl3.keys.extendedMasterSecretUsed, 1);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Flags */
+ rv = sslBuffer_AppendNumber(&plaintext, ticket->flags,
+ sizeof(ticket->flags));
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* ALPN value. */
+ PORT_Assert(ss->xtnData.nextProtoState == SSL_NEXT_PROTO_SELECTED ||
+ ss->xtnData.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED ||
+ ss->xtnData.nextProto.len == 0);
+ alpnSelection = &ss->xtnData.nextProto;
+ PORT_Assert(alpnSelection->len < 256);
+ rv = sslBuffer_AppendVariable(&plaintext, alpnSelection->data,
+ alpnSelection->len, 1);
+ if (rv != SECSuccess)
+ goto loser;
+
+ rv = sslBuffer_AppendNumber(&plaintext, ss->opt.maxEarlyDataSize, 4);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /*
+ * We store this in the ticket:
+ * ticket_age_baseline = 1rtt - ticket_age_add
+ *
+ * When the client resumes, it will provide:
+ * obfuscated_age = ticket_age_client + ticket_age_add
+ *
+ * We expect to receive the ticket at:
+ * ticket_create + 1rtt + ticket_age_server
+ *
+ * We calculate the client's estimate of this as:
+ * ticket_create + ticket_age_baseline + obfuscated_age
+ * = ticket_create + 1rtt + ticket_age_client
+ *
+ * This is compared to the expected time, which should differ only as a
+ * result of clock errors or errors in the RTT estimate.
+ */
+ ticketAgeBaseline = ss->ssl3.hs.rttEstimate / PR_USEC_PER_MSEC;
+ ticketAgeBaseline -= ticket->ticket_age_add;
+ rv = sslBuffer_AppendNumber(&plaintext, ticketAgeBaseline, 4);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Application token */
+ rv = sslBuffer_AppendVariable(&plaintext, appToken, appTokenLen, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* This really only happens if appTokenLen is too much, and that always
+ * comes from the using application. */
+ if (SSL_BUFFER_LEN(&plaintext) > 0xffff) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ ticket_buf.len = ssl_SelfEncryptGetProtectedSize(SSL_BUFFER_LEN(&plaintext));
+ PORT_Assert(ticket_buf.len > 0);
+ if (SECITEM_AllocItem(NULL, &ticket_buf, ticket_buf.len) == NULL) {
+ goto loser;
+ }
+
+ /* Finally, encrypt the ticket. */
+ rv = ssl_SelfEncryptProtect(ss, SSL_BUFFER_BASE(&plaintext),
+ SSL_BUFFER_LEN(&plaintext),
+ ticket_buf.data, &ticket_buf.len, ticket_buf.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Give ownership of memory to caller. */
+ *ticket_data = ticket_buf;
+
+ sslBuffer_Clear(&plaintext);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&plaintext);
+ if (ticket_buf.data) {
+ SECITEM_FreeItem(&ticket_buf, PR_FALSE);
+ }
+
+ return SECFailure;
+}
+
+/* When a client receives a SessionTicket extension a NewSessionTicket
+ * message is expected during the handshake.
+ */
+SECStatus
+ssl3_ClientHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (data->len != 0) {
+ return SECSuccess; /* Ignore the extension. */
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_session_ticket_xtn;
+ return SECSuccess;
+}
+
+PR_STATIC_ASSERT((TLS_EX_SESS_TICKET_VERSION >> 8) == 1);
+
+static SECStatus
+ssl_ParseSessionTicket(sslSocket *ss, const SECItem *decryptedTicket,
+ SessionTicket *parsedTicket)
+{
+ PRUint32 temp;
+ SECStatus rv;
+
+ PRUint8 *buffer = decryptedTicket->data;
+ unsigned int len = decryptedTicket->len;
+
+ PORT_Memset(parsedTicket, 0, sizeof(*parsedTicket));
+ parsedTicket->valid = PR_FALSE;
+
+ /* If the decrypted ticket is empty, then report success, but leave the
+ * ticket marked as invalid. */
+ if (decryptedTicket->len == 0) {
+ return SECSuccess;
+ }
+
+ /* Read ticket version. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* All ticket versions start with 0x01, so check to see if this
+ * is a ticket or some other self-encrypted thing. */
+ if ((temp >> 8) != 1) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+ /* Skip the ticket if the version is wrong. This won't result in a
+ * handshake failure, just a failure to resume. */
+ if (temp != TLS_EX_SESS_TICKET_VERSION) {
+ return SECSuccess;
+ }
+
+ /* Read SSLVersion. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->ssl_version = (SSL3ProtocolVersion)temp;
+ if (!ssl3_VersionIsSupported(ss->protocolVariant,
+ parsedTicket->ssl_version)) {
+ /* This socket doesn't support the version from the ticket. */
+ return SECSuccess;
+ }
+
+ /* Read cipher_suite. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->cipher_suite = (ssl3CipherSuite)temp;
+
+ /* Read cipher spec parameters. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+#ifndef UNSAFE_FUZZER_MODE
+ PORT_Assert(temp < ssl_auth_size);
+#else
+ temp %= (8 * sizeof(SSLAuthType)) - 1;
+#endif
+
+ parsedTicket->authType = (SSLAuthType)temp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->authKeyBits = temp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->keaType = (SSLKEAType)temp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->keaKeyBits = temp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->originalKeaGroup = temp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->signatureScheme = (SSLSignatureScheme)temp;
+
+ /* Read the optional named curve. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ if (parsedTicket->authType == ssl_auth_ecdsa ||
+ parsedTicket->authType == ssl_auth_ecdh_rsa ||
+ parsedTicket->authType == ssl_auth_ecdh_ecdsa) {
+ const sslNamedGroupDef *group =
+ ssl_LookupNamedGroup((SSLNamedGroup)temp);
+ if (!group || group->keaType != ssl_kea_ecdh) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->namedCurve = group;
+ }
+
+ /* Read the master secret (and how it is wrapped). */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->msWrapMech = (CK_MECHANISM_TYPE)temp;
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 2, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ if (temp == 0 || temp > sizeof(parsedTicket->master_secret)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->ms_length = (PRUint16)temp;
+
+ /* Read the master secret. */
+ rv = ssl3_ExtConsumeHandshake(ss, parsedTicket->master_secret,
+ parsedTicket->ms_length, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ /* Read client identity */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->client_auth_type = (ClientAuthenticationType)temp;
+ switch (parsedTicket->client_auth_type) {
+ case CLIENT_AUTH_ANONYMOUS:
+ break;
+ case CLIENT_AUTH_CERTIFICATE:
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->peer_cert, 2,
+ &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Read timestamp. This is a 64-bit value and
+ * ssl3_ExtConsumeHandshakeNumber only reads 32-bits at a time. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Cast to avoid undefined behavior if the top bit is set. */
+ parsedTicket->timestamp = (PRTime)((PRUint64)temp << 32);
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->timestamp |= (PRTime)temp;
+
+ /* Read server name */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->srvName, 2,
+ &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Read extendedMasterSecretUsed */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 1, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+#ifndef UNSAFE_FUZZER_MODE
+ /* A well-behaving server should only write 0 or 1. */
+ PORT_Assert(temp == PR_TRUE || temp == PR_FALSE);
+#endif
+ parsedTicket->extendedMasterSecretUsed = temp ? PR_TRUE : PR_FALSE;
+
+ rv = ssl3_ExtConsumeHandshake(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->flags = PR_ntohl(temp);
+
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->alpnSelection, 1,
+ &buffer, &len);
+ PORT_Assert(parsedTicket->alpnSelection.len < 256);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->maxEarlyData = temp;
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &temp, 4, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ parsedTicket->ticketAgeBaseline = temp;
+
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &parsedTicket->applicationToken,
+ 2, &buffer, &len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+#ifndef UNSAFE_FUZZER_MODE
+ /* Done parsing. Check that all bytes have been consumed. */
+ if (len != 0) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+#endif
+
+ parsedTicket->valid = PR_TRUE;
+ return SECSuccess;
+}
+
+static SECStatus
+ssl_CreateSIDFromTicket(sslSocket *ss, const SECItem *rawTicket,
+ SessionTicket *parsedTicket, sslSessionID **out)
+{
+ sslSessionID *sid;
+ SECStatus rv;
+
+ sid = ssl3_NewSessionID(ss, PR_TRUE);
+ if (sid == NULL) {
+ return SECFailure;
+ }
+
+ /* Copy over parameters. */
+ sid->version = parsedTicket->ssl_version;
+ sid->creationTime = parsedTicket->timestamp;
+ sid->u.ssl3.cipherSuite = parsedTicket->cipher_suite;
+ sid->authType = parsedTicket->authType;
+ sid->authKeyBits = parsedTicket->authKeyBits;
+ sid->keaType = parsedTicket->keaType;
+ sid->keaKeyBits = parsedTicket->keaKeyBits;
+ sid->keaGroup = parsedTicket->originalKeaGroup;
+ sid->namedCurve = parsedTicket->namedCurve;
+ sid->sigScheme = parsedTicket->signatureScheme;
+
+ rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.locked.sessionTicket.ticket,
+ rawTicket);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ sid->u.ssl3.locked.sessionTicket.flags = parsedTicket->flags;
+ sid->u.ssl3.locked.sessionTicket.max_early_data_size =
+ parsedTicket->maxEarlyData;
+
+ if (parsedTicket->ms_length >
+ sizeof(sid->u.ssl3.keys.wrapped_master_secret)) {
+ goto loser;
+ }
+ PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret,
+ parsedTicket->master_secret, parsedTicket->ms_length);
+ sid->u.ssl3.keys.wrapped_master_secret_len = parsedTicket->ms_length;
+ sid->u.ssl3.masterWrapMech = parsedTicket->msWrapMech;
+ sid->u.ssl3.masterValid = PR_TRUE;
+ sid->u.ssl3.keys.resumable = PR_TRUE;
+ sid->u.ssl3.keys.extendedMasterSecretUsed = parsedTicket->extendedMasterSecretUsed;
+
+ /* Copy over client cert from session ticket if there is one. */
+ if (parsedTicket->peer_cert.data != NULL) {
+ PORT_Assert(!sid->peerCert);
+ sid->peerCert = CERT_NewTempCertificate(ss->dbHandle,
+ &parsedTicket->peer_cert,
+ NULL, PR_FALSE, PR_TRUE);
+ if (!sid->peerCert) {
+ goto loser;
+ }
+ }
+
+ /* Transfer ownership of the remaining items. */
+ if (parsedTicket->srvName.data != NULL) {
+ SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE);
+ rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName,
+ &parsedTicket->srvName);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ if (parsedTicket->alpnSelection.data != NULL) {
+ SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
+ rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.alpnSelection,
+ &parsedTicket->alpnSelection);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ *out = sid;
+ return SECSuccess;
+
+loser:
+ ssl_FreeSID(sid);
+ return SECFailure;
+}
+
+/* Generic ticket processing code, common to all TLS versions. */
+SECStatus
+ssl3_ProcessSessionTicketCommon(sslSocket *ss, const SECItem *ticket,
+ SECItem *appToken)
+{
+ SECItem decryptedTicket = { siBuffer, NULL, 0 };
+ SessionTicket parsedTicket;
+ sslSessionID *sid = NULL;
+ SECStatus rv;
+
+ if (ss->sec.ci.sid != NULL) {
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(ss->sec.ci.sid);
+ ss->sec.ci.sid = NULL;
+ }
+
+ if (!SECITEM_AllocItem(NULL, &decryptedTicket, ticket->len)) {
+ return SECFailure;
+ }
+
+ /* Decrypt the ticket. */
+ rv = ssl_SelfEncryptUnprotect(ss, ticket->data, ticket->len,
+ decryptedTicket.data,
+ &decryptedTicket.len,
+ decryptedTicket.len);
+ if (rv != SECSuccess) {
+ /* Ignore decryption failure if we are doing TLS 1.3; that
+ * means the server rejects the client's resumption
+ * attempt. In TLS 1.2, however, it's a hard failure, unless
+ * it's just because we're not the recipient of the ticket. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ||
+ PORT_GetError() == SEC_ERROR_NOT_A_RECIPIENT) {
+ SECITEM_ZfreeItem(&decryptedTicket, PR_FALSE);
+ return SECSuccess;
+ }
+
+ SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ goto loser;
+ }
+
+ rv = ssl_ParseSessionTicket(ss, &decryptedTicket, &parsedTicket);
+ if (rv != SECSuccess) {
+ SSL3Statistics *ssl3stats;
+
+ SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.",
+ SSL_GETPID(), ss->fd));
+ ssl3stats = SSL_GetStatistics();
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_ticket_parse_failures);
+ goto loser; /* code already set */
+ }
+
+ /* Use the ticket if it is valid and unexpired. */
+ PRTime end = parsedTicket.timestamp + (ssl_ticket_lifetime * PR_USEC_PER_SEC);
+ if (end > ssl_Time(ss)) {
+
+ rv = ssl_CreateSIDFromTicket(ss, ticket, &parsedTicket, &sid);
+ if (rv != SECSuccess) {
+ goto loser; /* code already set */
+ }
+ if (appToken && parsedTicket.applicationToken.len) {
+ rv = SECITEM_CopyItem(NULL, appToken,
+ &parsedTicket.applicationToken);
+ if (rv != SECSuccess) {
+ goto loser; /* code already set */
+ }
+ }
+
+ ss->statelessResume = PR_TRUE;
+ ss->sec.ci.sid = sid;
+
+ /* We have the baseline value for the obfuscated ticket age here. Save
+ * that in xtnData temporarily. This value is updated in
+ * tls13_ServerHandlePreSharedKeyXtn with the final estimate. */
+ ss->xtnData.ticketAge = parsedTicket.ticketAgeBaseline;
+ }
+
+ SECITEM_ZfreeItem(&decryptedTicket, PR_FALSE);
+ PORT_Memset(&parsedTicket, 0, sizeof(parsedTicket));
+ return SECSuccess;
+
+loser:
+ if (sid) {
+ ssl_FreeSID(sid);
+ }
+ SECITEM_ZfreeItem(&decryptedTicket, PR_FALSE);
+ PORT_Memset(&parsedTicket, 0, sizeof(parsedTicket));
+ return SECFailure;
+}
+
+SECStatus
+ssl3_ServerHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ /* Ignore the SessionTicket extension if processing is disabled. */
+ if (!ss->opt.enableSessionTickets) {
+ return SECSuccess;
+ }
+
+ /* If we are doing TLS 1.3, then ignore this. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_session_ticket_xtn;
+
+ /* Parse the received ticket sent in by the client. We are
+ * lenient about some parse errors, falling back to a fullshake
+ * instead of terminating the current connection.
+ */
+ if (data->len == 0) {
+ xtnData->emptySessionTicket = PR_TRUE;
+ return SECSuccess;
+ }
+
+ return ssl3_ProcessSessionTicketCommon(CONST_CAST(sslSocket, ss), data,
+ NULL);
+}
+
+/* Extension format:
+ * Extension number: 2 bytes
+ * Extension length: 2 bytes
+ * Verify Data Length: 1 byte
+ * Verify Data (TLS): 12 bytes (client) or 24 bytes (server)
+ * Verify Data (SSL): 36 bytes (client) or 72 bytes (server)
+ */
+SECStatus
+ssl3_SendRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ PRInt32 len = 0;
+ SECStatus rv;
+
+ /* In RFC 5746, it is NOT RECOMMENDED to send both the SCSV and the empty
+ * RI, so when we send SCSV in the initial handshake, we don't also send RI.
+ */
+ if (ss->ssl3.hs.sendingSCSV) {
+ return 0;
+ }
+ if (ss->firstHsDone) {
+ len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2
+ : ss->ssl3.hs.finishedBytes;
+ }
+
+ /* verify_Data from previous Finished message(s) */
+ rv = sslBuffer_AppendVariable(buf,
+ ss->ssl3.hs.finishedMsgs.data, len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* This function runs in both the client and server. */
+SECStatus
+ssl3_HandleRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv = SECSuccess;
+ PRUint32 len = 0;
+
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (ss->firstHsDone) {
+ len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes
+ : ss->ssl3.hs.finishedBytes * 2;
+ }
+ if (data->len != 1 + len || data->data[0] != len) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+ if (len && NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data,
+ data->data + 1, len)) {
+ ssl3_ExtSendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
+ return SECFailure;
+ }
+ /* remember that we got this extension and it was correct. */
+ CONST_CAST(sslSocket, ss)
+ ->peerRequestedProtection = 1;
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_renegotiation_info_xtn;
+ if (ss->sec.isServer) {
+ /* prepare to send back the appropriate response */
+ rv = ssl3_RegisterExtensionSender(ss, xtnData,
+ ssl_renegotiation_info_xtn,
+ ssl3_SendRenegotiationInfoXtn);
+ }
+ return rv;
+}
+
+SECStatus
+ssl3_ClientSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ unsigned int i;
+ SECStatus rv;
+
+ if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
+ return SECSuccess; /* Not relevant */
+ }
+
+ /* Length of the SRTP cipher list */
+ rv = sslBuffer_AppendNumber(buf, 2 * ss->ssl3.dtlsSRTPCipherCount, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* The SRTP ciphers */
+ for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
+ rv = sslBuffer_AppendNumber(buf, ss->ssl3.dtlsSRTPCiphers[i], 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ /* Empty MKI value */
+ rv = sslBuffer_AppendNumber(buf, 0, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ServerSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ /* Length of the SRTP cipher list */
+ rv = sslBuffer_AppendNumber(buf, 2, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* The selected cipher */
+ rv = sslBuffer_AppendNumber(buf, xtnData->dtlsSRTPCipherSuite, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* Empty MKI value */
+ rv = sslBuffer_AppendNumber(buf, 0, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ClientHandleUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ SECItem ciphers = { siBuffer, NULL, 0 };
+ PRUint16 i;
+ PRUint16 cipher = 0;
+ PRBool found = PR_FALSE;
+ SECItem litem;
+
+ if (!data->data || !data->len) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+
+ /* Get the cipher list */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &ciphers, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* fatal alert already sent */
+ }
+ /* Now check that the server has picked just 1 (i.e., len = 2) */
+ if (ciphers.len != 2) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+
+ /* Get the selected cipher */
+ cipher = (ciphers.data[0] << 8) | ciphers.data[1];
+
+ /* Now check that this is one of the ciphers we offered */
+ for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) {
+ if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
+ found = PR_TRUE;
+ break;
+ }
+ }
+
+ if (!found) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
+ return SECFailure;
+ }
+
+ /* Get the srtp_mki value */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &litem, 1,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* alert already sent */
+ }
+
+ /* We didn't offer an MKI, so this must be 0 length */
+ if (litem.len != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO);
+ return SECFailure;
+ }
+
+ /* extra trailing bytes */
+ if (data->len != 0) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+
+ /* OK, this looks fine. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_use_srtp_xtn;
+ xtnData->dtlsSRTPCipherSuite = cipher;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ServerHandleUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ SECItem ciphers = { siBuffer, NULL, 0 };
+ PRUint16 i;
+ unsigned int j;
+ PRUint16 cipher = 0;
+ PRBool found = PR_FALSE;
+ SECItem litem;
+
+ if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) {
+ /* Ignore the extension if we aren't doing DTLS or no DTLS-SRTP
+ * preferences have been set. */
+ return SECSuccess;
+ }
+
+ if (!data->data || data->len < 5) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+
+ /* Get the cipher list */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &ciphers, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* alert already sent */
+ }
+ /* Check that the list is even length */
+ if (ciphers.len % 2) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+
+ /* Walk through the offered list and pick the most preferred of our
+ * ciphers, if any */
+ for (i = 0; !found && i < ss->ssl3.dtlsSRTPCipherCount; i++) {
+ for (j = 0; j + 1 < ciphers.len; j += 2) {
+ cipher = (ciphers.data[j] << 8) | ciphers.data[j + 1];
+ if (cipher == ss->ssl3.dtlsSRTPCiphers[i]) {
+ found = PR_TRUE;
+ break;
+ }
+ }
+ }
+
+ /* Get the srtp_mki value */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (data->len != 0) {
+ ssl3_ExtDecodeError(ss); /* trailing bytes */
+ return SECFailure;
+ }
+
+ /* Now figure out what to do */
+ if (!found) {
+ /* No matching ciphers, pretend we don't support use_srtp */
+ return SECSuccess;
+ }
+
+ /* OK, we have a valid cipher and we've selected it */
+ xtnData->dtlsSRTPCipherSuite = cipher;
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_use_srtp_xtn;
+
+ return ssl3_RegisterExtensionSender(ss, xtnData,
+ ssl_use_srtp_xtn,
+ ssl3_ServerSendUseSRTPXtn);
+}
+
+/* ssl3_HandleSigAlgsXtn handles the signature_algorithms extension from a
+ * client. In TLS 1.3, the client uses this to parse CertificateRequest
+ * extensions. See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
+SECStatus
+ssl3_HandleSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+
+ /* Ignore this extension if we aren't doing TLS 1.2 or greater. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) {
+ return SECSuccess;
+ }
+
+ if (xtnData->sigSchemes) {
+ PORT_Free(xtnData->sigSchemes);
+ xtnData->sigSchemes = NULL;
+ }
+ rv = ssl_ParseSignatureSchemes(ss, NULL,
+ &xtnData->sigSchemes,
+ &xtnData->numSigSchemes,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+ if (xtnData->numSigSchemes == 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ /* Check for trailing data. */
+ if (data->len != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_signature_algorithms_xtn;
+ return SECSuccess;
+}
+
+/* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS
+ * 1.2 ClientHellos. */
+SECStatus
+ssl3_SendSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) {
+ return SECSuccess;
+ }
+
+ PRUint16 minVersion;
+ if (ss->sec.isServer) {
+ minVersion = ss->version; /* CertificateRequest */
+ } else {
+ minVersion = ss->vrange.min; /* ClientHello */
+ }
+
+ SECStatus rv = ssl3_EncodeSigAlgs(ss, minVersion, PR_TRUE /* forCert */,
+ ss->opt.enableGrease, buf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_SendExtendedMasterSecretXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ if (!ss->opt.enableExtendedMS) {
+ return SECSuccess;
+ }
+
+ /* Always send the extension in this function, since the
+ * client always sends it and this function is only called on
+ * the server if we negotiated the extension. */
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_HandleExtendedMasterSecretXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_0) {
+ return SECSuccess;
+ }
+
+ if (!ss->opt.enableExtendedMS) {
+ return SECSuccess;
+ }
+
+ if (data->len != 0) {
+ SSL_TRC(30, ("%d: SSL3[%d]: Bogus extended master secret extension",
+ SSL_GETPID(), ss->fd));
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ return SECFailure;
+ }
+
+ SSL_DBG(("%d: SSL[%d]: Negotiated extended master secret extension.",
+ SSL_GETPID(), ss->fd));
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_extended_master_secret_xtn;
+
+ if (ss->sec.isServer) {
+ return ssl3_RegisterExtensionSender(ss, xtnData,
+ ssl_extended_master_secret_xtn,
+ ssl_SendEmptyExtension);
+ }
+ return SECSuccess;
+}
+
+/* ssl3_ClientSendSignedCertTimestampXtn sends the signed_certificate_timestamp
+ * extension for TLS ClientHellos. */
+SECStatus
+ssl3_ClientSendSignedCertTimestampXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ /* Only send the extension if processing is enabled. */
+ if (!ss->opt.enableSignedCertTimestamps) {
+ return SECSuccess;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ClientHandleSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ /* We do not yet know whether we'll be resuming a session or creating
+ * a new one, so we keep a pointer to the data in the TLSExtensionData
+ * structure. This pointer is only valid in the scope of
+ * ssl3_HandleServerHello, and, if not resuming a session, the data is
+ * copied once a new session structure has been set up.
+ * All parsing is currently left to the application and we accept
+ * everything, including empty data.
+ */
+ SECItem *scts = &xtnData->signedCertTimestamps;
+ PORT_Assert(!scts->data && !scts->len);
+
+ if (!data->len) {
+ /* Empty extension data: RFC 6962 mandates non-empty contents. */
+ return SECFailure;
+ }
+ *scts = *data;
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_signed_cert_timestamp_xtn;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ServerSendSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ const SECItem *scts = &ss->sec.serverCert->signedCertTimestamps;
+ SECStatus rv;
+
+ if (!scts->len) {
+ /* No timestamps to send */
+ return SECSuccess;
+ }
+
+ rv = sslBuffer_Append(buf, scts->data, scts->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_ServerHandleSignedCertTimestampXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ if (data->len != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_signed_cert_timestamp_xtn;
+ PORT_Assert(ss->sec.isServer);
+ return ssl3_RegisterExtensionSender(ss, xtnData,
+ ssl_signed_cert_timestamp_xtn,
+ ssl3_ServerSendSignedCertTimestampXtn);
+}
+
+/* Just make sure that the remote client supports uncompressed points,
+ * Since that is all we support. Disable ECC cipher suites if it doesn't.
+ */
+SECStatus
+ssl3_HandleSupportedPointFormatsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ int i;
+
+ PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (data->len < 2 || data->len > 255 || !data->data ||
+ data->len != (unsigned int)data->data[0] + 1) {
+ ssl3_ExtDecodeError(ss);
+ return SECFailure;
+ }
+ for (i = data->len; --i > 0;) {
+ if (data->data[i] == 0) {
+ /* indicate that we should send a reply */
+ return ssl3_RegisterExtensionSender(
+ ss, xtnData, ssl_ec_point_formats_xtn,
+ &ssl3_SendSupportedPointFormatsXtn);
+ }
+ }
+
+ /* Poor client doesn't support uncompressed points.
+ *
+ * If the client sends the extension and the extension does not contain the
+ * uncompressed point format, and the client has used the Supported Groups
+ * extension to indicate support for any of the curves defined in this
+ * specification, then the server MUST abort the handshake and return an
+ * illegal_parameter alert. [RFC8422, Section 5.1.2] */
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+
+ return SECFailure;
+}
+
+static SECStatus
+ssl_UpdateSupportedGroups(sslSocket *ss, SECItem *data)
+{
+ SECStatus rv;
+ PRUint32 list_len;
+ unsigned int i;
+ const sslNamedGroupDef *enabled[SSL_NAMED_GROUP_COUNT] = { 0 };
+ PORT_Assert(SSL_NAMED_GROUP_COUNT == PR_ARRAY_SIZE(enabled));
+
+ if (!data->data || data->len < 4) {
+ (void)ssl3_DecodeError(ss);
+ return SECFailure;
+ }
+
+ /* get the length of elliptic_curve_list */
+ rv = ssl3_ConsumeHandshakeNumber(ss, &list_len, 2, &data->data, &data->len);
+ if (rv != SECSuccess || data->len != list_len || (data->len % 2) != 0) {
+ (void)ssl3_DecodeError(ss);
+ return SECFailure;
+ }
+
+ /* disable all groups and remember the enabled groups */
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ enabled[i] = ss->namedGroupPreferences[i];
+ ss->namedGroupPreferences[i] = NULL;
+ }
+
+ /* Read groups from data and enable if in |enabled| */
+ while (data->len) {
+ const sslNamedGroupDef *group;
+ PRUint32 curve_name;
+ rv = ssl3_ConsumeHandshakeNumber(ss, &curve_name, 2, &data->data,
+ &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* fatal alert already sent */
+ }
+ group = ssl_LookupNamedGroup(curve_name);
+ if (group) {
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (enabled[i] && group == enabled[i]) {
+ ss->namedGroupPreferences[i] = enabled[i];
+ break;
+ }
+ }
+ }
+
+ /* "Codepoints in the NamedCurve registry with a high byte of 0x01 (that
+ * is, between 256 and 511 inclusive) are set aside for FFDHE groups,"
+ * -- https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe-10
+ */
+ if ((curve_name & 0xff00) == 0x0100) {
+ ss->xtnData.peerSupportsFfdheGroups = PR_TRUE;
+ }
+ }
+
+ /* Note: if ss->opt.requireDHENamedGroups is set, we disable DHE cipher
+ * suites, but we do that in ssl3_config_match(). */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ !ss->opt.requireDHENamedGroups && !ss->xtnData.peerSupportsFfdheGroups) {
+ /* If we don't require that DHE use named groups, and no FFDHE was
+ * included, we pretend that they support all the FFDHE groups we do. */
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (enabled[i] && enabled[i]->keaType == ssl_kea_dh) {
+ ss->namedGroupPreferences[i] = enabled[i];
+ }
+ }
+ }
+
+ return SECSuccess;
+}
+
+/* Ensure that the curve in our server cert is one of the ones supported
+ * by the remote client, and disable all ECC cipher suites if not.
+ */
+SECStatus
+ssl_HandleSupportedGroupsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+
+ rv = ssl_UpdateSupportedGroups(CONST_CAST(sslSocket, ss), data);
+ if (rv != SECSuccess)
+ return SECFailure;
+
+ /* TLS 1.3 permits the server to send this extension so make it so. */
+ if (ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ rv = ssl3_RegisterExtensionSender(ss, xtnData, ssl_supported_groups_xtn,
+ &ssl_SendSupportedGroupsXtn);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error already set. */
+ }
+ }
+
+ /* Remember that we negotiated this extension. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_supported_groups_xtn;
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl_HandleRecordSizeLimitXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PRUint32 limit;
+ PRUint32 maxLimit = (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)
+ ? (MAX_FRAGMENT_LENGTH + 1)
+ : MAX_FRAGMENT_LENGTH;
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &limit, 2, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (data->len != 0 || limit < 64) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ return SECFailure;
+ }
+
+ if (ss->sec.isServer) {
+ rv = ssl3_RegisterExtensionSender(ss, xtnData, ssl_record_size_limit_xtn,
+ &ssl_SendRecordSizeLimitXtn);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error already set. */
+ }
+ } else if (limit > maxLimit) {
+ /* The client can sensibly check the maximum. */
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ return SECFailure;
+ }
+
+ /* We can't enforce the maximum on a server. But we do need to ensure
+ * that we don't apply a limit that is too large. */
+ xtnData->recordSizeLimit = PR_MIN(maxLimit, limit);
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_record_size_limit_xtn;
+ return SECSuccess;
+}
+
+SECStatus
+ssl_SendRecordSizeLimitXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ PRUint32 maxLimit;
+ if (ss->sec.isServer) {
+ maxLimit = (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)
+ ? (MAX_FRAGMENT_LENGTH + 1)
+ : MAX_FRAGMENT_LENGTH;
+ } else {
+ maxLimit = (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3)
+ ? (MAX_FRAGMENT_LENGTH + 1)
+ : MAX_FRAGMENT_LENGTH;
+ }
+ PRUint32 limit = PR_MIN(ss->opt.recordSizeLimit, maxLimit);
+ SECStatus rv = sslBuffer_AppendNumber(buf, limit, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/ssl3exthandle.h b/security/nss/lib/ssl/ssl3exthandle.h
new file mode 100644
index 0000000000..654b90de8c
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3exthandle.h
@@ -0,0 +1,133 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __ssl3exthandle_h_
+#define __ssl3exthandle_h_
+
+#include "sslencode.h"
+
+SECStatus ssl3_SendRenegotiationInfoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_HandleRenegotiationInfoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientHandleNextProtoNegoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientHandleAppProtoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ServerHandleNextProtoNegoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ServerHandleAppProtoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientSendNextProtoNegoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ClientSendAppProtoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ServerSendAppProtoXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ClientSendUseSRTPXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ServerSendUseSRTPXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ClientHandleUseSRTPXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ServerHandleUseSRTPXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ServerSendStatusRequestXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ServerHandleStatusRequestXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientHandleStatusRequestXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientSendStatusRequestXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_SendSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_HandleSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data);
+
+SECStatus ssl3_ClientSendPaddingExtension(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+
+SECStatus ssl3_ClientSendSignedCertTimestampXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ClientHandleSignedCertTimestampXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ServerSendSignedCertTimestampXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_ServerHandleSignedCertTimestampXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_SendExtendedMasterSecretXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_HandleExtendedMasterSecretXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ProcessSessionTicketCommon(sslSocket *ss, const SECItem *ticket,
+ /* out */ SECItem *appToken);
+PRBool ssl_ShouldSendSNIExtension(const sslSocket *ss, const char *url);
+SECStatus ssl3_ClientFormatServerNameXtn(const sslSocket *ss, const char *url,
+ unsigned int len, TLSExtensionData *xtnData,
+ sslBuffer *buf);
+SECStatus ssl3_ClientSendServerNameXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_HandleServerNameXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl_HandleSupportedGroupsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_HandleSupportedPointFormatsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientHandleSessionTicketXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ServerHandleSessionTicketXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl3_ClientSendSessionTicketXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+
+SECStatus ssl_SendSupportedGroupsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl3_SendSupportedPointFormatsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus ssl_HandleRecordSizeLimitXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus ssl_SendRecordSizeLimitXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+
+#endif
diff --git a/security/nss/lib/ssl/ssl3gthr.c b/security/nss/lib/ssl/ssl3gthr.c
new file mode 100644
index 0000000000..674ea89da9
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3gthr.c
@@ -0,0 +1,823 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * Gather (Read) entire SSL3 records from socket into buffer.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "cert.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "ssl3prot.h"
+
+struct ssl2GatherStr {
+ /* true when ssl3_GatherData encounters an SSLv2 handshake */
+ PRBool isV2;
+
+ /* number of bytes of padding appended to the message content */
+ PRUint8 padding;
+};
+
+typedef struct ssl2GatherStr ssl2Gather;
+
+/* Caller should hold RecvBufLock. */
+SECStatus
+ssl3_InitGather(sslGather *gs)
+{
+ gs->state = GS_INIT;
+ gs->writeOffset = 0;
+ gs->readOffset = 0;
+ gs->dtlsPacketOffset = 0;
+ gs->dtlsPacket.len = 0;
+ gs->rejectV2Records = PR_FALSE;
+ /* Allocate plaintext buffer to maximum possibly needed size. It needs to
+ * be larger than recordSizeLimit for TLS 1.0 and 1.1 compatability.
+ * The TLS 1.2 ciphertext is larger than the TLS 1.3 ciphertext. */
+ return sslBuffer_Grow(&gs->buf, TLS_1_2_MAX_CTEXT_LENGTH);
+}
+
+/* Caller must hold RecvBufLock. */
+void
+ssl3_DestroyGather(sslGather *gs)
+{
+ if (gs) { /* the PORT_*Free functions check for NULL pointers. */
+ PORT_ZFree(gs->buf.buf, gs->buf.space);
+ PORT_Free(gs->inbuf.buf);
+ PORT_Free(gs->dtlsPacket.buf);
+ }
+}
+
+/* Checks whether a given buffer is likely an SSLv3 record header. */
+PRBool
+ssl3_isLikelyV3Hello(const unsigned char *buf)
+{
+ /* Even if this was a V2 record header we couldn't possibly parse it
+ * correctly as the second bit denotes a vaguely-defined security escape. */
+ if (buf[0] & 0x40) {
+ return PR_TRUE;
+ }
+
+ /* Check for a typical V3 record header. */
+ return (PRBool)(buf[0] >= ssl_ct_change_cipher_spec &&
+ buf[0] <= ssl_ct_application_data &&
+ buf[1] == MSB(SSL_LIBRARY_VERSION_3_0));
+}
+
+/*
+ * Attempt to read in an entire SSL3 record.
+ * Blocks here for blocking sockets, otherwise returns -1 with
+ * PR_WOULD_BLOCK_ERROR when socket would block.
+ *
+ * returns 1 if received a complete SSL3 record.
+ * returns 0 if recv returns EOF
+ * returns -1 if recv returns < 0
+ * (The error value may have already been set to PR_WOULD_BLOCK_ERROR)
+ *
+ * Caller must hold the recv buf lock.
+ *
+ * The Gather state machine has 3 states: GS_INIT, GS_HEADER, GS_DATA.
+ * GS_HEADER: waiting for the 5-byte SSL3 record header to come in.
+ * GS_DATA: waiting for the body of the SSL3 record to come in.
+ *
+ * This loop returns when either
+ * (a) an error or EOF occurs,
+ * (b) PR_WOULD_BLOCK_ERROR,
+ * (c) data (entire SSL3 record) has been received.
+ */
+static int
+ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags, ssl2Gather *ssl2gs)
+{
+ unsigned char *bp;
+ unsigned char *lbp;
+ int nb;
+ int err;
+ int rv = 1;
+ PRUint8 v2HdrLength = 0;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ if (gs->state == GS_INIT) {
+ gs->state = GS_HEADER;
+ gs->remainder = 5;
+ gs->offset = 0;
+ gs->writeOffset = 0;
+ gs->readOffset = 0;
+ gs->inbuf.len = 0;
+ }
+
+ lbp = gs->inbuf.buf;
+ for (;;) {
+ SSL_TRC(30, ("%d: SSL3[%d]: gather state %d (need %d more)",
+ SSL_GETPID(), ss->fd, gs->state, gs->remainder));
+ bp = ((gs->state != GS_HEADER) ? lbp : gs->hdr) + gs->offset;
+ nb = ssl_DefRecv(ss, bp, gs->remainder, flags);
+
+ if (nb > 0) {
+ PRINT_BUF(60, (ss, "raw gather data:", bp, nb));
+ } else if (nb == 0) {
+ /* EOF */
+ SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd));
+ rv = 0;
+ break;
+ } else /* if (nb < 0) */ {
+ SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd,
+ PR_GetError()));
+ rv = SECFailure;
+ break;
+ }
+
+ PORT_Assert((unsigned int)nb <= gs->remainder);
+ if ((unsigned int)nb > gs->remainder) {
+ /* ssl_DefRecv is misbehaving! this error is fatal to SSL. */
+ gs->state = GS_INIT; /* so we don't crash next time */
+ rv = SECFailure;
+ break;
+ }
+
+ gs->offset += nb;
+ gs->remainder -= nb;
+ if (gs->state == GS_DATA)
+ gs->inbuf.len += nb;
+
+ /* if there's more to go, read some more. */
+ if (gs->remainder > 0) {
+ continue;
+ }
+
+ /* have received entire record header, or entire record. */
+ switch (gs->state) {
+ case GS_HEADER:
+ /* Check for SSLv2 handshakes. Always assume SSLv3 on clients,
+ * support SSLv2 handshakes only when ssl2gs != NULL.
+ * Always assume v3 after we received the first record. */
+ if (!ssl2gs ||
+ ss->gs.rejectV2Records ||
+ ssl3_isLikelyV3Hello(gs->hdr)) {
+ /* Should have a non-SSLv2 record header in gs->hdr. Extract
+ * the length of the following encrypted data, and then
+ * read in the rest of the record into gs->inbuf. */
+ gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4];
+ gs->hdrLen = SSL3_RECORD_HEADER_LENGTH;
+ } else {
+ /* Probably an SSLv2 record header. No need to handle any
+ * security escapes (gs->hdr[0] & 0x40) as we wouldn't get
+ * here if one was set. See ssl3_isLikelyV3Hello(). */
+ gs->remainder = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1];
+ ssl2gs->isV2 = PR_TRUE;
+ v2HdrLength = 2;
+
+ /* Is it a 3-byte header with padding? */
+ if (!(gs->hdr[0] & 0x80)) {
+ ssl2gs->padding = gs->hdr[2];
+ v2HdrLength++;
+ }
+ }
+
+ /* If it is NOT an SSLv2 header */
+ if (!v2HdrLength) {
+ /* Check if default RFC specified max ciphertext/record
+ * limits are respected. Checks for used record size limit
+ * extension boundaries are done in
+ * ssl3con.c/ssl3_HandleRecord() for tls and dtls records.
+ *
+ * -> For TLS 1.2 records MUST NOT be longer than
+ * 2^14 + 2048 bytes.
+ * -> For TLS 1.3 records MUST NOT exceed 2^14 + 256 bytes.
+ * -> For older versions this MAY be enforced, we do it.
+ * [RFC8446 Section 5.2, RFC5246 Section 6.2.3]. */
+ if (gs->remainder > TLS_1_2_MAX_CTEXT_LENGTH ||
+ (gs->remainder > TLS_1_3_MAX_CTEXT_LENGTH &&
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_3)) {
+ SSL3_SendAlert(ss, alert_fatal, record_overflow);
+ gs->state = GS_INIT;
+ PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+ return SECFailure;
+ }
+ }
+
+ gs->state = GS_DATA;
+ gs->offset = 0;
+ gs->inbuf.len = 0;
+
+ if (gs->remainder > gs->inbuf.space) {
+ err = sslBuffer_Grow(&gs->inbuf, gs->remainder);
+ if (err) { /* realloc has set error code to no mem. */
+ return err;
+ }
+ lbp = gs->inbuf.buf;
+ }
+
+ /* When we encounter an SSLv2 hello we've read 2 or 3 bytes too
+ * many into the gs->hdr[] buffer. Copy them over into inbuf so
+ * that we can properly process the hello record later. */
+ if (v2HdrLength) {
+ /* Reject v2 records that don't even carry enough data to
+ * resemble a valid ClientHello header. */
+ if (gs->remainder < SSL_HL_CLIENT_HELLO_HBYTES) {
+ SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ PORT_Assert(lbp);
+ gs->inbuf.len = 5 - v2HdrLength;
+ PORT_Memcpy(lbp, gs->hdr + v2HdrLength, gs->inbuf.len);
+ gs->remainder -= gs->inbuf.len;
+ lbp += gs->inbuf.len;
+ }
+
+ if (gs->remainder > 0) {
+ break; /* End this case. Continue around the loop. */
+ }
+
+ /* FALL THROUGH if (gs->remainder == 0) as we just received
+ * an empty record and there's really no point in calling
+ * ssl_DefRecv() with buf=NULL and len=0. */
+
+ case GS_DATA:
+ /*
+ ** SSL3 record has been completely received.
+ */
+ SSL_TRC(10, ("%d: SSL[%d]: got record of %d bytes",
+ SSL_GETPID(), ss->fd, gs->inbuf.len));
+
+ /* reject any v2 records from now on */
+ ss->gs.rejectV2Records = PR_TRUE;
+
+ gs->state = GS_INIT;
+ return 1;
+ }
+ }
+
+ return rv;
+}
+
+/*
+ * Read in an entire DTLS record.
+ *
+ * Blocks here for blocking sockets, otherwise returns -1 with
+ * PR_WOULD_BLOCK_ERROR when socket would block.
+ *
+ * This is simpler than SSL because we are reading on a datagram socket
+ * and datagrams must contain >=1 complete records.
+ *
+ * returns 1 if received a complete DTLS record.
+ * returns 0 if recv returns EOF
+ * returns -1 if recv returns < 0
+ * (The error value may have already been set to PR_WOULD_BLOCK_ERROR)
+ *
+ * Caller must hold the recv buf lock.
+ *
+ * This loop returns when either
+ * (a) an error or EOF occurs,
+ * (b) PR_WOULD_BLOCK_ERROR,
+ * (c) data (entire DTLS record) has been received.
+ */
+static int
+dtls_GatherData(sslSocket *ss, sslGather *gs, int flags)
+{
+ int nb;
+ PRUint8 contentType;
+ unsigned int headerLen;
+ SECStatus rv = SECSuccess;
+ PRBool dtlsLengthPresent = PR_TRUE;
+
+ SSL_TRC(30, ("dtls_GatherData"));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+
+ gs->state = GS_HEADER;
+ gs->offset = 0;
+
+ if (gs->dtlsPacketOffset == gs->dtlsPacket.len) { /* No data left */
+ gs->dtlsPacketOffset = 0;
+ gs->dtlsPacket.len = 0;
+
+ /* Resize to the maximum possible size so we can fit a full datagram.
+ * This leads to record_overflow errors if records/ciphertexts greater
+ * than the buffer (= maximum record) size are to be received.
+ * DTLS Record errors are dropped silently. [RFC6347, Section 4.1.2.7].
+ * Checks for record size limit extension boundaries are performed in
+ * ssl3con.c/ssl3_HandleRecord() for tls and dtls records.
+ *
+ * -> For TLS 1.2 records MUST NOT be longer than 2^14 + 2048 bytes.
+ * -> For TLS 1.3 records MUST NOT exceed 2^14 + 256 bytes.
+ * -> For older versions this MAY be enforced, we do it.
+ * [RFC8446 Section 5.2, RFC5246 Section 6.2.3]. */
+ if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_2) {
+ if (gs->dtlsPacket.space < DTLS_1_2_MAX_PACKET_LENGTH) {
+ rv = sslBuffer_Grow(&gs->dtlsPacket, DTLS_1_2_MAX_PACKET_LENGTH);
+ }
+ } else { /* version >= TLS 1.3 */
+ if (gs->dtlsPacket.space != DTLS_1_3_MAX_PACKET_LENGTH) {
+ /* During Hello and version negotiation older DTLS versions with
+ * greater possible packets are used. The buffer must therefore
+ * be "truncated" by clearing and reallocating it */
+ sslBuffer_Clear(&gs->dtlsPacket);
+ rv = sslBuffer_Grow(&gs->dtlsPacket, DTLS_1_3_MAX_PACKET_LENGTH);
+ }
+ }
+
+ if (rv != SECSuccess) {
+ return -1; /* Code already set. */
+ }
+
+ /* recv() needs to read a full datagram at a time */
+ nb = ssl_DefRecv(ss, gs->dtlsPacket.buf, gs->dtlsPacket.space, flags);
+ if (nb > 0) {
+ PRINT_BUF(60, (ss, "raw gather data:", gs->dtlsPacket.buf, nb));
+ } else if (nb == 0) {
+ /* EOF */
+ SSL_TRC(30, ("%d: SSL3[%d]: EOF", SSL_GETPID(), ss->fd));
+ return 0;
+ } else /* if (nb < 0) */ {
+ SSL_DBG(("%d: SSL3[%d]: recv error %d", SSL_GETPID(), ss->fd,
+ PR_GetError()));
+ /* DTLS Record Errors, including overlong records, are silently
+ * dropped [RFC6347, Section 4.1.2.7]. */
+ return -1;
+ }
+
+ gs->dtlsPacket.len = nb;
+ }
+
+ contentType = gs->dtlsPacket.buf[gs->dtlsPacketOffset];
+ if (dtls_IsLongHeader(ss->version, contentType)) {
+ headerLen = 13;
+ } else if (contentType == ssl_ct_application_data) {
+ headerLen = 7;
+ } else if (dtls_IsDtls13Ciphertext(ss->version, contentType)) {
+ /* We don't support CIDs.
+ *
+ * This condition is met on all invalid outer content types.
+ * For lower DTLS versions as well as the inner content types,
+ * this is checked in ssl3con.c/ssl3_HandleNonApplicationData().
+ *
+ * In DTLS generally invalid records SHOULD be silently discarded,
+ * no alert is sent [RFC6347, Section 4.1.2.7].
+ */
+ if (contentType & 0x10) {
+ PORT_Assert(PR_FALSE);
+ PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
+ gs->dtlsPacketOffset = 0;
+ gs->dtlsPacket.len = 0;
+ return -1;
+ }
+
+ dtlsLengthPresent = (contentType & 0x04) == 0x04;
+ PRUint8 dtlsSeqNoSize = (contentType & 0x08) ? 2 : 1;
+ PRUint8 dtlsLengthBytes = dtlsLengthPresent ? 2 : 0;
+ headerLen = 1 + dtlsSeqNoSize + dtlsLengthBytes;
+ } else {
+ SSL_DBG(("%d: SSL3[%d]: invalid first octet (%d) for DTLS",
+ SSL_GETPID(), ss->fd, contentType));
+ PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
+ gs->dtlsPacketOffset = 0;
+ gs->dtlsPacket.len = 0;
+ return -1;
+ }
+
+ /* At this point we should have >=1 complete records lined up in
+ * dtlsPacket. Read off the header.
+ */
+ if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < headerLen) {
+ SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet "
+ "too short to contain header",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ gs->dtlsPacketOffset = 0;
+ gs->dtlsPacket.len = 0;
+ return -1;
+ }
+ memcpy(gs->hdr, SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset,
+ headerLen);
+ gs->hdrLen = headerLen;
+ gs->dtlsPacketOffset += headerLen;
+
+ /* Have received SSL3 record header in gs->hdr. */
+ if (dtlsLengthPresent) {
+ gs->remainder = (gs->hdr[headerLen - 2] << 8) |
+ gs->hdr[headerLen - 1];
+ } else {
+ gs->remainder = gs->dtlsPacket.len - gs->dtlsPacketOffset;
+ }
+
+ if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < gs->remainder) {
+ SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet too short "
+ "to contain rest of body",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ gs->dtlsPacketOffset = 0;
+ gs->dtlsPacket.len = 0;
+ return -1;
+ }
+
+ /* OK, we have at least one complete packet, copy into inbuf */
+ gs->inbuf.len = 0;
+ rv = sslBuffer_Append(&gs->inbuf,
+ SSL_BUFFER_BASE(&gs->dtlsPacket) + gs->dtlsPacketOffset,
+ gs->remainder);
+ if (rv != SECSuccess) {
+ return -1; /* code already set. */
+ }
+ gs->offset = gs->remainder;
+ gs->dtlsPacketOffset += gs->remainder;
+ gs->state = GS_INIT;
+
+ SSL_TRC(20, ("%d: SSL3[%d]: dtls gathered record type=%d len=%d",
+ SSL_GETPID(), ss->fd, contentType, gs->inbuf.len));
+ return 1;
+}
+
+/* Gather in a record and when complete, Handle that record.
+ * Repeat this until the handshake is complete,
+ * or until application data is available.
+ *
+ * Returns 1 when the handshake is completed without error, or
+ * application data is available.
+ * Returns 0 if ssl3_GatherData hits EOF.
+ * Returns -1 on read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error.
+ *
+ * Called from ssl_GatherRecord1stHandshake in sslcon.c,
+ * and from SSL_ForceHandshake in sslsecur.c
+ * and from ssl3_GatherAppDataRecord below (<- DoRecv in sslsecur.c).
+ *
+ * Caller must hold the recv buf lock.
+ */
+int
+ssl3_GatherCompleteHandshake(sslSocket *ss, int flags)
+{
+ int rv;
+ SSL3Ciphertext cText;
+ PRBool keepGoing = PR_TRUE;
+
+ if (ss->ssl3.fatalAlertSent) {
+ SSL_TRC(3, ("%d: SSL3[%d] Cannot gather data; fatal alert already sent",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(SSL_ERROR_HANDSHAKE_FAILED);
+ return -1;
+ }
+
+ SSL_TRC(30, ("%d: SSL3[%d]: ssl3_GatherCompleteHandshake",
+ SSL_GETPID(), ss->fd));
+
+ /* ssl3_HandleRecord may end up eventually calling ssl_FinishHandshake,
+ * which requires the 1stHandshakeLock, which must be acquired before the
+ * RecvBufLock.
+ */
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+
+ do {
+ PRBool processingEarlyData;
+
+ ssl_GetSSL3HandshakeLock(ss);
+
+ processingEarlyData = ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted;
+
+ /* Without this, we may end up wrongly reporting
+ * SSL_ERROR_RX_UNEXPECTED_* errors if we receive any records from the
+ * peer while we are waiting to be restarted.
+ */
+ if (ss->ssl3.hs.restartTarget) {
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return -1;
+ }
+
+ /* If we have a detached record layer, don't ever gather. */
+ if (ss->recordWriteCallback) {
+ PRBool done = ss->firstHsDone;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ if (done) {
+ return 1;
+ }
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return -1;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+
+ /* State for SSLv2 client hello support. */
+ ssl2Gather ssl2gs = { PR_FALSE, 0 };
+ ssl2Gather *ssl2gs_ptr = NULL;
+
+ /* If we're a server and waiting for a client hello, accept v2. */
+ if (ss->sec.isServer && ss->opt.enableV2CompatibleHello &&
+ ss->ssl3.hs.ws == wait_client_hello) {
+ ssl2gs_ptr = &ssl2gs;
+ }
+
+ /* bring in the next sslv3 record. */
+ if (ss->recvdCloseNotify) {
+ /* RFC 5246 Section 7.2.1:
+ * Any data received after a closure alert is ignored.
+ */
+ return 0;
+ }
+
+ if (!IS_DTLS(ss)) {
+ /* If we're a server waiting for a ClientHello then pass
+ * ssl2gs to support SSLv2 ClientHello messages. */
+ rv = ssl3_GatherData(ss, &ss->gs, flags, ssl2gs_ptr);
+ } else {
+ rv = dtls_GatherData(ss, &ss->gs, flags);
+
+ /* If we got a would block error, that means that no data was
+ * available, so we check the timer to see if it's time to
+ * retransmit */
+ if (rv == SECFailure &&
+ (PORT_GetError() == PR_WOULD_BLOCK_ERROR)) {
+ dtls_CheckTimer(ss);
+ /* Restore the error in case something succeeded */
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ }
+ }
+
+ if (rv <= 0) {
+ return rv;
+ }
+
+ if (ssl2gs.isV2) {
+ rv = ssl3_HandleV2ClientHello(ss, ss->gs.inbuf.buf,
+ ss->gs.inbuf.len,
+ ssl2gs.padding);
+ if (rv < 0) {
+ return rv;
+ }
+ } else {
+ /* decipher it, and handle it if it's a handshake.
+ * If it's application data, ss->gs.buf will not be empty upon return.
+ * If it's a change cipher spec, alert, or handshake message,
+ * ss->gs.buf.len will be 0 when ssl3_HandleRecord returns SECSuccess.
+ *
+ * cText only needs to be valid for this next function call, so
+ * it can borrow gs.hdr.
+ */
+ cText.hdr = ss->gs.hdr;
+ cText.hdrLen = ss->gs.hdrLen;
+ cText.buf = &ss->gs.inbuf;
+ rv = ssl3_HandleRecord(ss, &cText);
+ }
+
+#ifdef DEBUG
+ /* In Debug builds free gather ciphertext buffer after each decryption
+ * for advanced ASAN coverage/utilization. The buffer content has been
+ * used at this point, ssl3_HandleRecord() and thereby the decryption
+ * functions are only called from this point of the implementation. */
+ sslBuffer_Clear(&ss->gs.inbuf);
+#endif
+
+ if (rv < 0) {
+ return ss->recvdCloseNotify ? 0 : rv;
+ }
+ if (ss->gs.buf.len > 0) {
+ /* We have application data to return to the application. This
+ * prioritizes returning application data to the application over
+ * completing any renegotiation handshake we may be doing.
+ */
+ PORT_Assert(ss->firstHsDone);
+ break;
+ }
+
+ PORT_Assert(keepGoing);
+ ssl_GetSSL3HandshakeLock(ss);
+ if (ss->ssl3.hs.ws == idle_handshake) {
+ /* We are done with the current handshake so stop trying to
+ * handshake. Note that it would be safe to test ss->firstHsDone
+ * instead of ss->ssl3.hs.ws. By testing ss->ssl3.hs.ws instead,
+ * we prioritize completing a renegotiation handshake over sending
+ * application data.
+ */
+ PORT_Assert(ss->firstHsDone);
+ PORT_Assert(!ss->ssl3.hs.canFalseStart);
+ keepGoing = PR_FALSE;
+ } else if (ss->ssl3.hs.canFalseStart) {
+ /* Prioritize sending application data over trying to complete
+ * the handshake if we're false starting.
+ *
+ * If we were to do this check at the beginning of the loop instead
+ * of here, then this function would become be a no-op after
+ * receiving the ServerHelloDone in the false start case, and we
+ * would never complete the handshake.
+ */
+ PORT_Assert(!ss->firstHsDone);
+
+ if (ssl3_WaitingForServerSecondRound(ss)) {
+ keepGoing = PR_FALSE;
+ } else {
+ ss->ssl3.hs.canFalseStart = PR_FALSE;
+ }
+ } else if (processingEarlyData &&
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_done &&
+ !PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
+ /* If we were processing early data and we are no longer, then force
+ * the handshake to block. This ensures that early data is
+ * delivered to the application before the handshake completes. */
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return -1;
+ }
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ } while (keepGoing);
+
+ /* Service the DTLS timer so that the post-handshake timers
+ * fire. */
+ if (IS_DTLS(ss) && (ss->ssl3.hs.ws == idle_handshake)) {
+ dtls_CheckTimer(ss);
+ }
+ ss->gs.readOffset = 0;
+ ss->gs.writeOffset = ss->gs.buf.len;
+ return 1;
+}
+
+/* Repeatedly gather in a record and when complete, Handle that record.
+ * Repeat this until some application data is received.
+ *
+ * Returns 1 when application data is available.
+ * Returns 0 if ssl3_GatherData hits EOF.
+ * Returns -1 on read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error.
+ *
+ * Called from DoRecv in sslsecur.c
+ * Caller must hold the recv buf lock.
+ */
+int
+ssl3_GatherAppDataRecord(sslSocket *ss, int flags)
+{
+ int rv;
+
+ /* ssl3_GatherCompleteHandshake requires both of these locks. */
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+
+ do {
+ rv = ssl3_GatherCompleteHandshake(ss, flags);
+ } while (rv > 0 && ss->gs.buf.len == 0);
+
+ return rv;
+}
+
+static SECStatus
+ssl_HandleZeroRttRecordData(sslSocket *ss, const PRUint8 *data, unsigned int len)
+{
+ PORT_Assert(ss->sec.isServer);
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ sslBuffer buf = { CONST_CAST(PRUint8, data), len, len, PR_TRUE };
+ return tls13_HandleEarlyApplicationData(ss, &buf);
+ }
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored &&
+ ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) {
+ /* We're ignoring 0-RTT so drop this record quietly. */
+ return SECSuccess;
+ }
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
+ return SECFailure;
+}
+
+/* Ensure that application data in the wrong epoch is blocked. */
+static PRBool
+ssl_IsApplicationDataPermitted(sslSocket *ss, PRUint16 epoch)
+{
+ /* Epoch 0 is never OK. */
+ if (epoch == 0) {
+ return PR_FALSE;
+ }
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return ss->firstHsDone;
+ }
+ /* TLS 1.3 application data. */
+ if (epoch >= TrafficKeyApplicationData) {
+ return ss->firstHsDone;
+ }
+ /* TLS 1.3 early data is server only. Further checks aren't needed
+ * as those are handled in ssl_HandleZeroRttRecordData. */
+ if (epoch == TrafficKeyEarlyApplicationData) {
+ return ss->sec.isServer;
+ }
+ return PR_FALSE;
+}
+
+SECStatus
+SSLExp_RecordLayerData(PRFileDesc *fd, PRUint16 epoch,
+ SSLContentType contentType,
+ const PRUint8 *data, unsigned int len)
+{
+ SECStatus rv;
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+ if (IS_DTLS(ss) || data == NULL || len == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* Run any handshake function. If SSL_RecordLayerData is the only way that
+ * the handshake is driven, then this is necessary to ensure that
+ * ssl_BeginClientHandshake or ssl_BeginServerHandshake is called. Note that
+ * the other function that might be set to ss->handshake,
+ * ssl3_GatherCompleteHandshake, does nothing when this function is used. */
+ ssl_Get1stHandshakeLock(ss);
+ rv = ssl_Do1stHandshake(ss);
+ if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
+ goto early_loser; /* Rely on the existing code. */
+ }
+
+ if (contentType == ssl_ct_application_data &&
+ !ssl_IsApplicationDataPermitted(ss, epoch)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto early_loser;
+ }
+
+ /* Then we can validate the epoch. */
+ PRErrorCode epochError;
+ ssl_GetSpecReadLock(ss);
+ if (epoch < ss->ssl3.crSpec->epoch) {
+ epochError = SEC_ERROR_INVALID_ARGS; /* Too c/old. */
+ } else if (epoch > ss->ssl3.crSpec->epoch) {
+ /* If a TLS 1.3 server is not expecting EndOfEarlyData,
+ * moving from 1 to 2 is a signal to execute the code
+ * as though that message had been received. Let that pass. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ ss->opt.suppressEndOfEarlyData &&
+ ss->sec.isServer &&
+ ss->ssl3.crSpec->epoch == TrafficKeyEarlyApplicationData &&
+ epoch == TrafficKeyHandshake) {
+ epochError = 0;
+ } else {
+ epochError = PR_WOULD_BLOCK_ERROR; /* Too warm/new. */
+ }
+ } else {
+ epochError = 0; /* Just right. */
+ }
+ ssl_ReleaseSpecReadLock(ss);
+ if (epochError) {
+ PORT_SetError(epochError);
+ goto early_loser;
+ }
+
+ /* If the handshake is still running, we need to run that. */
+ rv = ssl_Do1stHandshake(ss);
+ if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
+ goto early_loser;
+ }
+
+ /* 0-RTT needs its own special handling here. */
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ epoch == TrafficKeyEarlyApplicationData &&
+ contentType == ssl_ct_application_data) {
+ rv = ssl_HandleZeroRttRecordData(ss, data, len);
+ ssl_Release1stHandshakeLock(ss);
+ return rv;
+ }
+
+ /* Finally, save the data... */
+ ssl_GetRecvBufLock(ss);
+ rv = sslBuffer_Append(&ss->gs.buf, data, len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* ...and process it. Just saving application data is enough for it to be
+ * available to PR_Read(). */
+ if (contentType != ssl_ct_application_data) {
+ rv = ssl3_HandleNonApplicationData(ss, contentType, 0, 0, &ss->gs.buf);
+ /* This occasionally blocks, but that's OK here. */
+ if (rv != SECSuccess && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
+ goto loser;
+ }
+ }
+
+ ssl_ReleaseRecvBufLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECSuccess;
+
+loser:
+ /* Make sure that any data is not used again. */
+ ss->gs.buf.len = 0;
+ ssl_ReleaseRecvBufLock(ss);
+early_loser:
+ ssl_Release1stHandshakeLock(ss);
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_GetCurrentEpoch(PRFileDesc *fd, PRUint16 *readEpoch,
+ PRUint16 *writeEpoch)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ ssl_GetSpecReadLock(ss);
+ if (readEpoch) {
+ *readEpoch = ss->ssl3.crSpec->epoch;
+ }
+ if (writeEpoch) {
+ *writeEpoch = ss->ssl3.cwSpec->epoch;
+ }
+ ssl_ReleaseSpecReadLock(ss);
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/ssl3prot.h b/security/nss/lib/ssl/ssl3prot.h
new file mode 100644
index 0000000000..9eeb5a3028
--- /dev/null
+++ b/security/nss/lib/ssl/ssl3prot.h
@@ -0,0 +1,199 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* Private header file of libSSL.
+ * Various and sundry protocol constants. DON'T CHANGE THESE. These
+ * values are defined by the SSL 3.0 protocol specification.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __ssl3proto_h_
+#define __ssl3proto_h_
+
+typedef PRUint16 SSL3ProtocolVersion;
+/* version numbers are defined in sslproto.h */
+
+/* DTLS 1.3 is still a draft. */
+#define DTLS_1_3_DRAFT_VERSION 43
+
+typedef PRUint16 ssl3CipherSuite;
+/* The cipher suites are defined in sslproto.h */
+
+#define MAX_CERT_TYPES 10
+#define MAX_MAC_LENGTH 64
+#define MAX_PADDING_LENGTH 64
+#define MAX_KEY_LENGTH 64
+#define EXPORT_KEY_LENGTH 5
+#define SSL3_RANDOM_LENGTH 32
+
+#define SSL3_RECORD_HEADER_LENGTH 5
+
+/* SSL3_RECORD_HEADER_LENGTH + epoch/sequence_number */
+#define DTLS_RECORD_HEADER_LENGTH 13
+
+/* Max values for TLS records/ciphertexts
+ * For TLS 1.2 records MUST NOT be longer than 2^14 + 2048
+ * For TLS 1.3 records MUST NOT exceed 2^14 + 256 bytes.
+ * [RFC8446 Section 5.2, RFC5246 Section 6.2.3]. */
+#define MAX_FRAGMENT_LENGTH 16384
+#define TLS_1_2_MAX_EXPANSION 2048
+#define TLS_1_3_MAX_EXPANSION (255 + 1)
+#define TLS_1_3_MAX_CTEXT_LENGTH ((MAX_FRAGMENT_LENGTH) + (TLS_1_3_MAX_EXPANSION))
+#define TLS_1_2_MAX_CTEXT_LENGTH ((MAX_FRAGMENT_LENGTH) + (TLS_1_2_MAX_EXPANSION))
+
+/* DTLS_X_X_MAX_PACKET_LENGTH = TLS_X_X_MAX_RECORD_LENGTH + HEADER_LENGTH,
+ * used for DTLS datagram buffer size setting. We do not support DTLS CID! */
+#define DTLS_1_3_MAX_PACKET_LENGTH ((TLS_1_3_MAX_CTEXT_LENGTH) + (SSL3_RECORD_HEADER_LENGTH))
+#define DTLS_1_2_MAX_PACKET_LENGTH ((TLS_1_2_MAX_CTEXT_LENGTH) + (DTLS_RECORD_HEADER_LENGTH))
+
+typedef enum { change_cipher_spec_choice = 1 } SSL3ChangeCipherSpecChoice;
+
+typedef enum { alert_warning = 1,
+ alert_fatal = 2 } SSL3AlertLevel;
+
+typedef enum {
+ close_notify = 0,
+ unexpected_message = 10,
+ bad_record_mac = 20,
+ decryption_failed_RESERVED = 21, /* do not send; see RFC 5246 */
+ record_overflow = 22, /* TLS only */
+ decompression_failure = 30,
+ handshake_failure = 40,
+ no_certificate = 41, /* SSL3 only, NOT TLS */
+ bad_certificate = 42,
+ unsupported_certificate = 43,
+ certificate_revoked = 44,
+ certificate_expired = 45,
+ certificate_unknown = 46,
+ illegal_parameter = 47,
+
+ /* All alerts below are TLS only. */
+ unknown_ca = 48,
+ access_denied = 49,
+ decode_error = 50,
+ decrypt_error = 51,
+ export_restriction = 60,
+ protocol_version = 70,
+ insufficient_security = 71,
+ internal_error = 80,
+ inappropriate_fallback = 86, /* could also be sent for SSLv3 */
+ user_canceled = 90,
+ no_renegotiation = 100,
+
+ /* Alerts for client hello extensions */
+ missing_extension = 109,
+ unsupported_extension = 110,
+ certificate_unobtainable = 111,
+ unrecognized_name = 112,
+ bad_certificate_status_response = 113,
+ bad_certificate_hash_value = 114,
+ certificate_required = 116,
+ no_application_protocol = 120,
+ ech_required = 121,
+
+ /* invalid alert */
+ no_alert = 256
+} SSL3AlertDescription;
+
+typedef PRUint8 SSL3Random[SSL3_RANDOM_LENGTH];
+
+typedef struct {
+ PRUint8 id[32];
+ PRUint8 length;
+} SSL3SessionID;
+
+/* SSL3SignType moved to ssl.h */
+
+/* The SSL key exchange method used */
+typedef enum {
+ kea_null,
+ kea_rsa,
+ kea_dh_dss,
+ kea_dh_rsa,
+ kea_dhe_dss,
+ kea_dhe_rsa,
+ kea_dh_anon,
+ kea_ecdh_ecdsa,
+ kea_ecdhe_ecdsa,
+ kea_ecdh_rsa,
+ kea_ecdhe_rsa,
+ kea_ecdh_anon,
+ kea_ecdhe_psk,
+ kea_dhe_psk,
+ kea_tls13_any,
+} SSL3KeyExchangeAlgorithm;
+
+/* SSL3HashesIndividually contains a combination MD5/SHA1 hash, as used in TLS
+ * prior to 1.2. */
+typedef struct {
+ PRUint8 md5[16];
+ PRUint8 sha[20];
+} SSL3HashesIndividually;
+
+/* SSL3Hashes contains an SSL hash value. The digest is contained in |u.raw|
+ * which, if |hashAlg==ssl_hash_none| is also a SSL3HashesIndividually
+ * struct. */
+typedef struct {
+ unsigned int len;
+ SSLHashType hashAlg;
+ union {
+ PRUint8 raw[64];
+ SSL3HashesIndividually s;
+ } u;
+} SSL3Hashes;
+
+typedef enum {
+ ct_RSA_sign = 1,
+ ct_DSS_sign = 2,
+ ct_RSA_fixed_DH = 3,
+ ct_DSS_fixed_DH = 4,
+ ct_RSA_ephemeral_DH = 5,
+ ct_DSS_ephemeral_DH = 6,
+ ct_ECDSA_sign = 64,
+ ct_RSA_fixed_ECDH = 65,
+ ct_ECDSA_fixed_ECDH = 66
+} SSL3ClientCertificateType;
+
+typedef enum {
+ sender_client = 0x434c4e54,
+ sender_server = 0x53525652
+} SSL3Sender;
+
+typedef SSL3HashesIndividually SSL3Finished;
+
+typedef struct {
+ PRUint8 verify_data[12];
+} TLSFinished;
+
+/*
+ * TLS extension related data structures and constants.
+ */
+
+/* SessionTicket extension related data structures. */
+
+/* NewSessionTicket handshake message. */
+typedef struct {
+ PRTime received_timestamp;
+ PRUint32 ticket_lifetime_hint;
+ PRUint32 flags;
+ PRUint32 ticket_age_add;
+ PRUint32 max_early_data_size;
+ SECItem ticket;
+} NewSessionTicket;
+
+typedef enum {
+ tls13_psk_ke = 0,
+ tls13_psk_dh_ke = 1
+} TLS13PskKEModes;
+
+typedef enum {
+ CLIENT_AUTH_ANONYMOUS = 0,
+ CLIENT_AUTH_CERTIFICATE = 1
+} ClientAuthenticationType;
+
+#define SELF_ENCRYPT_KEY_NAME_LEN 16
+#define SELF_ENCRYPT_KEY_NAME_PREFIX "NSS!"
+#define SELF_ENCRYPT_KEY_NAME_PREFIX_LEN 4
+#define SELF_ENCRYPT_KEY_VAR_NAME_LEN 12
+
+#endif /* __ssl3proto_h_ */
diff --git a/security/nss/lib/ssl/sslauth.c b/security/nss/lib/ssl/sslauth.c
new file mode 100644
index 0000000000..f4c3642513
--- /dev/null
+++ b/security/nss/lib/ssl/sslauth.c
@@ -0,0 +1,292 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "cert.h"
+#include "secitem.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "pk11func.h"
+#include "ocsp.h"
+
+/* NEED LOCKS IN HERE. */
+CERTCertificate *
+SSL_PeerCertificate(PRFileDesc *fd)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate",
+ SSL_GETPID(), fd));
+ return 0;
+ }
+ if (ss->opt.useSecurity && ss->sec.peerCert) {
+ return CERT_DupCertificate(ss->sec.peerCert);
+ }
+ return 0;
+}
+
+/* NEED LOCKS IN HERE. */
+CERTCertList *
+SSL_PeerCertificateChain(PRFileDesc *fd)
+{
+ sslSocket *ss;
+ CERTCertList *chain = NULL;
+ CERTCertificate *cert;
+ ssl3CertNode *cur;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificateChain",
+ SSL_GETPID(), fd));
+ return NULL;
+ }
+ if (!ss->opt.useSecurity || !ss->sec.peerCert) {
+ PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
+ return NULL;
+ }
+ chain = CERT_NewCertList();
+ if (!chain) {
+ return NULL;
+ }
+ cert = CERT_DupCertificate(ss->sec.peerCert);
+ if (CERT_AddCertToListTail(chain, cert) != SECSuccess) {
+ goto loser;
+ }
+ for (cur = ss->ssl3.peerCertChain; cur; cur = cur->next) {
+ cert = CERT_DupCertificate(cur->cert);
+ if (CERT_AddCertToListTail(chain, cert) != SECSuccess) {
+ goto loser;
+ }
+ }
+ return chain;
+
+loser:
+ CERT_DestroyCertList(chain);
+ return NULL;
+}
+
+/* NEED LOCKS IN HERE. */
+CERTCertificate *
+SSL_LocalCertificate(PRFileDesc *fd)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate",
+ SSL_GETPID(), fd));
+ return NULL;
+ }
+ if (ss->opt.useSecurity) {
+ if (ss->sec.localCert) {
+ return CERT_DupCertificate(ss->sec.localCert);
+ }
+ if (ss->sec.ci.sid && ss->sec.ci.sid->localCert) {
+ return CERT_DupCertificate(ss->sec.ci.sid->localCert);
+ }
+ }
+ return NULL;
+}
+
+/* NEED LOCKS IN HERE. */
+SECStatus
+SSL_SecurityStatus(PRFileDesc *fd, int *op, char **cp, int *kp0, int *kp1,
+ char **ip, char **sp)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SecurityStatus",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (cp)
+ *cp = 0;
+ if (kp0)
+ *kp0 = 0;
+ if (kp1)
+ *kp1 = 0;
+ if (ip)
+ *ip = 0;
+ if (sp)
+ *sp = 0;
+ if (op) {
+ *op = SSL_SECURITY_STATUS_OFF;
+ }
+
+ if (ss->opt.useSecurity && ss->enoughFirstHsDone) {
+ const ssl3BulkCipherDef *bulkCipherDef;
+ PRBool isDes = PR_FALSE;
+
+ bulkCipherDef = ssl_GetBulkCipherDef(ss->ssl3.hs.suite_def);
+ if (cp) {
+ *cp = PORT_Strdup(bulkCipherDef->short_name);
+ }
+ if (PORT_Strstr(bulkCipherDef->short_name, "DES")) {
+ isDes = PR_TRUE;
+ }
+
+ if (kp0) {
+ *kp0 = bulkCipherDef->key_size * 8;
+ if (isDes)
+ *kp0 = (*kp0 * 7) / 8;
+ }
+ if (kp1) {
+ *kp1 = bulkCipherDef->secret_key_size * 8;
+ if (isDes)
+ *kp1 = (*kp1 * 7) / 8;
+ }
+ if (op) {
+ if (bulkCipherDef->key_size == 0) {
+ *op = SSL_SECURITY_STATUS_OFF;
+ } else if (bulkCipherDef->secret_key_size * 8 < 90) {
+ *op = SSL_SECURITY_STATUS_ON_LOW;
+ } else {
+ *op = SSL_SECURITY_STATUS_ON_HIGH;
+ }
+ }
+
+ if (ip || sp) {
+ CERTCertificate *cert;
+
+ cert = ss->sec.peerCert;
+ if (cert) {
+ if (ip) {
+ *ip = CERT_NameToAscii(&cert->issuer);
+ }
+ if (sp) {
+ *sp = CERT_NameToAscii(&cert->subject);
+ }
+ } else {
+ if (ip) {
+ *ip = PORT_Strdup("no certificate");
+ }
+ if (sp) {
+ *sp = PORT_Strdup("no certificate");
+ }
+ }
+ }
+ }
+
+ return SECSuccess;
+}
+
+/************************************************************************/
+
+/* NEED LOCKS IN HERE. */
+SECStatus
+SSL_AuthCertificateHook(PRFileDesc *s, SSLAuthCertificate func, void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(s);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in AuthCertificateHook",
+ SSL_GETPID(), s));
+ return SECFailure;
+ }
+
+ ss->authCertificate = func;
+ ss->authCertificateArg = arg;
+
+ return SECSuccess;
+}
+
+/* NEED LOCKS IN HERE. */
+SECStatus
+SSL_GetClientAuthDataHook(PRFileDesc *s, SSLGetClientAuthData func,
+ void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(s);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook",
+ SSL_GETPID(), s));
+ return SECFailure;
+ }
+
+ ss->getClientAuthData = func;
+ ss->getClientAuthDataArg = arg;
+ return SECSuccess;
+}
+
+/* NEED LOCKS IN HERE. */
+SECStatus
+SSL_SetPKCS11PinArg(PRFileDesc *s, void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(s);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook",
+ SSL_GETPID(), s));
+ return SECFailure;
+ }
+
+ ss->pkcs11PinArg = arg;
+ return SECSuccess;
+}
+
+/* This is the "default" authCert callback function. It is called when a
+ * certificate message is received from the peer and the local application
+ * has not registered an authCert callback function.
+ */
+SECStatus
+SSL_AuthCertificate(void *arg, PRFileDesc *fd, PRBool checkSig, PRBool isServer)
+{
+ SECStatus rv;
+ CERTCertDBHandle *handle;
+ sslSocket *ss;
+ SECCertUsage certUsage;
+ const char *hostname = NULL;
+ SECItemArray *certStatusArray;
+
+ ss = ssl_FindSocket(fd);
+ PORT_Assert(ss != NULL);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ handle = (CERTCertDBHandle *)arg;
+ certStatusArray = &ss->sec.ci.sid->peerCertStatus;
+
+ PRTime now = ssl_Time(ss);
+ if (certStatusArray->len) {
+ PORT_SetError(0);
+ if (CERT_CacheOCSPResponseFromSideChannel(handle, ss->sec.peerCert, now,
+ &certStatusArray->items[0],
+ ss->pkcs11PinArg) !=
+ SECSuccess) {
+ PORT_Assert(PR_GetError() != 0);
+ }
+ }
+
+ /* this may seem backwards, but isn't. */
+ certUsage = isServer ? certUsageSSLClient : certUsageSSLServer;
+
+ rv = CERT_VerifyCert(handle, ss->sec.peerCert, checkSig, certUsage,
+ now, ss->pkcs11PinArg, NULL);
+
+ if (rv != SECSuccess || isServer)
+ return rv;
+
+ /* cert is OK. This is the client side of an SSL connection.
+ * Now check the name field in the cert against the desired hostname.
+ * NB: This is our only defense against Man-In-The-Middle (MITM) attacks!
+ */
+ hostname = ss->url;
+ if (hostname && hostname[0])
+ rv = CERT_VerifyCertName(ss->sec.peerCert, hostname);
+ else
+ rv = SECFailure;
+ if (rv != SECSuccess)
+ PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN);
+
+ return rv;
+}
diff --git a/security/nss/lib/ssl/sslbloom.c b/security/nss/lib/ssl/sslbloom.c
new file mode 100644
index 0000000000..3d5f9d1f17
--- /dev/null
+++ b/security/nss/lib/ssl/sslbloom.c
@@ -0,0 +1,94 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * A bloom filter.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "sslbloom.h"
+#include "prnetdb.h"
+#include "secport.h"
+
+static inline unsigned int
+sslBloom_Size(unsigned int bits)
+{
+ return (bits >= 3) ? (1 << (bits - 3)) : 1;
+}
+
+SECStatus
+sslBloom_Init(sslBloomFilter *filter, unsigned int k, unsigned int bits)
+{
+ PORT_Assert(filter);
+ PORT_Assert(bits > 0);
+ PORT_Assert(bits <= sizeof(PRUint32) * 8);
+ PORT_Assert(k > 0);
+
+ filter->filter = PORT_ZNewArray(PRUint8, sslBloom_Size(bits));
+ if (!filter->filter) {
+ return SECFailure; /* Error code already set. */
+ }
+
+ filter->k = k;
+ filter->bits = bits;
+ return SECSuccess;
+}
+
+void
+sslBloom_Zero(sslBloomFilter *filter)
+{
+ PORT_Memset(filter->filter, 0, sslBloom_Size(filter->bits));
+}
+
+void
+sslBloom_Fill(sslBloomFilter *filter)
+{
+ PORT_Memset(filter->filter, 0xff, sslBloom_Size(filter->bits));
+}
+
+static PRBool
+sslBloom_AddOrCheck(sslBloomFilter *filter, const PRUint8 *hashes, PRBool add)
+{
+ unsigned int iteration;
+ unsigned int bitIndex;
+ PRUint32 tmp = 0;
+ PRUint8 mask;
+ unsigned int bytes = (filter->bits + 7) / 8;
+ unsigned int shift = (bytes * 8) - filter->bits;
+ PRBool found = PR_TRUE;
+
+ PORT_Assert(bytes <= sizeof(unsigned int));
+
+ for (iteration = 0; iteration < filter->k; ++iteration) {
+ PORT_Memcpy(((PRUint8 *)&tmp) + (sizeof(tmp) - bytes),
+ hashes, bytes);
+ hashes += bytes;
+ bitIndex = PR_ntohl(tmp) >> shift;
+
+ mask = 1 << (bitIndex % 8);
+ found = found && filter->filter[bitIndex / 8] & mask;
+ if (add) {
+ filter->filter[bitIndex / 8] |= mask;
+ }
+ }
+ return found;
+}
+
+PRBool
+sslBloom_Add(sslBloomFilter *filter, const PRUint8 *hashes)
+{
+ return sslBloom_AddOrCheck(filter, hashes, PR_TRUE);
+}
+
+PRBool
+sslBloom_Check(sslBloomFilter *filter, const PRUint8 *hashes)
+{
+ return sslBloom_AddOrCheck(filter, hashes, PR_FALSE);
+}
+
+void
+sslBloom_Destroy(sslBloomFilter *filter)
+{
+ PORT_Free(filter->filter);
+ PORT_Memset(filter, 0, sizeof(*filter));
+}
diff --git a/security/nss/lib/ssl/sslbloom.h b/security/nss/lib/ssl/sslbloom.h
new file mode 100644
index 0000000000..032c94b0f0
--- /dev/null
+++ b/security/nss/lib/ssl/sslbloom.h
@@ -0,0 +1,32 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * A bloom filter.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslbloom_h_
+#define __sslbloom_h_
+
+#include "prtypes.h"
+#include "seccomon.h"
+
+typedef struct sslBloomFilterStr {
+ unsigned int k; /* The number of hashes. */
+ unsigned int bits; /* The number of bits in each hash: bits = log2(m) */
+ PRUint8 *filter; /* The filter itself. */
+} sslBloomFilter;
+
+SECStatus sslBloom_Init(sslBloomFilter *filter, unsigned int k, unsigned int bits);
+void sslBloom_Zero(sslBloomFilter *filter);
+void sslBloom_Fill(sslBloomFilter *filter);
+/* Add the given hashes to the filter. It's the caller's responsibility to
+ * ensure that there is at least |ceil(k*bits/8)| bytes of data available in
+ * |hashes|. Returns PR_TRUE if the entry was already present or it was likely
+ * to be present. */
+PRBool sslBloom_Add(sslBloomFilter *filter, const PRUint8 *hashes);
+PRBool sslBloom_Check(sslBloomFilter *filter, const PRUint8 *hashes);
+void sslBloom_Destroy(sslBloomFilter *filter);
+
+#endif /* __sslbloom_h_ */
diff --git a/security/nss/lib/ssl/sslcert.c b/security/nss/lib/ssl/sslcert.c
new file mode 100644
index 0000000000..0fa6ca3538
--- /dev/null
+++ b/security/nss/lib/ssl/sslcert.c
@@ -0,0 +1,1016 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * SSL server certificate configuration functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ssl.h"
+#include "sslimpl.h"
+#include "secoid.h" /* for SECOID_GetAlgorithmTag */
+#include "pk11func.h" /* for PK11_ReferenceSlot */
+#include "nss.h" /* for NSS_RegisterShutdown */
+#include "prinit.h" /* for PR_CallOnceWithArg */
+#include "tls13subcerts.h" /* for tls13_ReadDelegatedCredential */
+
+/* This global item is used only in servers. It is is initialized by
+ * SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
+ */
+static struct {
+ PRCallOnceType setup;
+ CERTDistNames *names;
+} ssl_server_ca_list;
+
+static SECStatus
+ssl_ServerCAListShutdown(void *appData, void *nssData)
+{
+ PORT_Assert(ssl_server_ca_list.names);
+ if (ssl_server_ca_list.names) {
+ CERT_FreeDistNames(ssl_server_ca_list.names);
+ }
+ PORT_Memset(&ssl_server_ca_list, 0, sizeof(ssl_server_ca_list));
+ return SECSuccess;
+}
+
+static PRStatus
+ssl_SetupCAListOnce(void *arg)
+{
+ CERTCertDBHandle *dbHandle = (CERTCertDBHandle *)arg;
+ SECStatus rv = NSS_RegisterShutdown(ssl_ServerCAListShutdown, NULL);
+ PORT_Assert(SECSuccess == rv);
+ if (SECSuccess == rv) {
+ ssl_server_ca_list.names = CERT_GetSSLCACerts(dbHandle);
+ return PR_SUCCESS;
+ }
+ return PR_FAILURE;
+}
+
+SECStatus
+ssl_SetupCAList(const sslSocket *ss)
+{
+ if (PR_SUCCESS != PR_CallOnceWithArg(&ssl_server_ca_list.setup,
+ &ssl_SetupCAListOnce,
+ (void *)(ss->dbHandle))) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+ssl_GetCertificateRequestCAs(const sslSocket *ss, unsigned int *calen,
+ const SECItem **names, unsigned int *nnames)
+{
+ const SECItem *name;
+ const CERTDistNames *ca_list;
+ unsigned int i;
+
+ *calen = 0;
+ *names = NULL;
+ *nnames = 0;
+
+ /* ssl3.ca_list is initialized to NULL, and never changed. */
+ ca_list = ss->ssl3.ca_list;
+ if (!ca_list) {
+ if (ssl_SetupCAList(ss) != SECSuccess) {
+ return SECFailure;
+ }
+ ca_list = ssl_server_ca_list.names;
+ }
+
+ if (ca_list != NULL) {
+ *names = ca_list->names;
+ *nnames = ca_list->nnames;
+ }
+
+ for (i = 0, name = *names; i < *nnames; i++, name++) {
+ *calen += 2 + name->len;
+ }
+ return SECSuccess;
+}
+
+sslServerCert *
+ssl_NewServerCert()
+{
+ sslServerCert *sc = PORT_ZNew(sslServerCert);
+ if (!sc) {
+ return NULL;
+ }
+ sc->authTypes = 0;
+ sc->namedCurve = NULL;
+ sc->serverCert = NULL;
+ sc->serverCertChain = NULL;
+ sc->certStatusArray = NULL;
+ sc->signedCertTimestamps.len = 0;
+ sc->delegCred.len = 0;
+ sc->delegCredKeyPair = NULL;
+ return sc;
+}
+
+sslServerCert *
+ssl_CopyServerCert(const sslServerCert *oc)
+{
+ sslServerCert *sc;
+
+ sc = ssl_NewServerCert();
+ if (!sc) {
+ return NULL;
+ }
+
+ sc->authTypes = oc->authTypes;
+ sc->namedCurve = oc->namedCurve;
+
+ if (oc->serverCert && oc->serverCertChain) {
+ sc->serverCert = CERT_DupCertificate(oc->serverCert);
+ if (!sc->serverCert)
+ goto loser;
+ sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
+ if (!sc->serverCertChain)
+ goto loser;
+ } else {
+ sc->serverCert = NULL;
+ sc->serverCertChain = NULL;
+ }
+
+ if (oc->serverKeyPair) {
+ sc->serverKeyPair = ssl_GetKeyPairRef(oc->serverKeyPair);
+ if (!sc->serverKeyPair)
+ goto loser;
+ } else {
+ sc->serverKeyPair = NULL;
+ }
+ sc->serverKeyBits = oc->serverKeyBits;
+
+ if (oc->certStatusArray) {
+ sc->certStatusArray = SECITEM_DupArray(NULL, oc->certStatusArray);
+ if (!sc->certStatusArray)
+ goto loser;
+ } else {
+ sc->certStatusArray = NULL;
+ }
+
+ if (SECITEM_CopyItem(NULL, &sc->signedCertTimestamps,
+ &oc->signedCertTimestamps) != SECSuccess) {
+ goto loser;
+ }
+
+ if (SECITEM_CopyItem(NULL, &sc->delegCred, &oc->delegCred) != SECSuccess) {
+ goto loser;
+ }
+ if (oc->delegCredKeyPair) {
+ sc->delegCredKeyPair = ssl_GetKeyPairRef(oc->delegCredKeyPair);
+ }
+
+ return sc;
+loser:
+ ssl_FreeServerCert(sc);
+ return NULL;
+}
+
+void
+ssl_FreeServerCert(sslServerCert *sc)
+{
+ if (!sc) {
+ return;
+ }
+
+ if (sc->serverCert) {
+ CERT_DestroyCertificate(sc->serverCert);
+ }
+ if (sc->serverCertChain) {
+ CERT_DestroyCertificateList(sc->serverCertChain);
+ }
+ if (sc->serverKeyPair) {
+ ssl_FreeKeyPair(sc->serverKeyPair);
+ }
+ if (sc->certStatusArray) {
+ SECITEM_FreeArray(sc->certStatusArray, PR_TRUE);
+ }
+ if (sc->signedCertTimestamps.len) {
+ SECITEM_FreeItem(&sc->signedCertTimestamps, PR_FALSE);
+ }
+ if (sc->delegCred.len) {
+ SECITEM_FreeItem(&sc->delegCred, PR_FALSE);
+ }
+ if (sc->delegCredKeyPair) {
+ ssl_FreeKeyPair(sc->delegCredKeyPair);
+ }
+ PORT_ZFree(sc, sizeof(*sc));
+}
+
+const sslServerCert *
+ssl_FindServerCert(const sslSocket *ss, SSLAuthType authType,
+ const sslNamedGroupDef *namedCurve)
+{
+ PRCList *cursor;
+
+ /* Bug 1749475: avoid UB while fuzzing session tickets */
+ if ((unsigned)authType >= ssl_auth_size) {
+ return NULL;
+ }
+
+ for (cursor = PR_NEXT_LINK(&ss->serverCerts);
+ cursor != &ss->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *cert = (sslServerCert *)cursor;
+ if (!SSL_CERT_IS(cert, authType)) {
+ continue;
+ }
+ if (SSL_CERT_IS_EC(cert)) {
+ /* Note: For deprecated APIs, we need to be able to find and
+ match a slot with any named curve. */
+ if (namedCurve && cert->namedCurve != namedCurve) {
+ continue;
+ }
+ }
+ return cert;
+ }
+ return NULL;
+}
+
+static SECStatus
+ssl_PopulateServerCert(sslServerCert *sc, CERTCertificate *cert,
+ const CERTCertificateList *certChain)
+{
+ if (sc->serverCert) {
+ CERT_DestroyCertificate(sc->serverCert);
+ }
+ if (sc->serverCertChain) {
+ CERT_DestroyCertificateList(sc->serverCertChain);
+ }
+
+ if (!cert) {
+ sc->serverCert = NULL;
+ sc->serverCertChain = NULL;
+ return SECSuccess;
+ }
+
+ sc->serverCert = CERT_DupCertificate(cert);
+ if (certChain) {
+ sc->serverCertChain = CERT_DupCertList(certChain);
+ } else {
+ sc->serverCertChain =
+ CERT_CertChainFromCert(sc->serverCert, certUsageSSLServer,
+ PR_TRUE);
+ }
+ return sc->serverCertChain ? SECSuccess : SECFailure;
+}
+
+static SECStatus
+ssl_PopulateKeyPair(sslServerCert *sc, sslKeyPair *keyPair)
+{
+ if (sc->serverKeyPair) {
+ ssl_FreeKeyPair(sc->serverKeyPair);
+ sc->serverKeyPair = NULL;
+ }
+ if (keyPair) {
+ KeyType keyType = SECKEY_GetPublicKeyType(keyPair->pubKey);
+ PORT_Assert(keyType == SECKEY_GetPrivateKeyType(keyPair->privKey));
+
+ if (keyType == ecKey) {
+ sc->namedCurve = ssl_ECPubKey2NamedGroup(keyPair->pubKey);
+ if (!sc->namedCurve) {
+ /* Unsupported curve. */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ /* Get the size of the cert's public key, and remember it. */
+ sc->serverKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->pubKey);
+ if (sc->serverKeyBits == 0 ||
+ (keyType == rsaKey && sc->serverKeyBits > SSL_MAX_RSA_KEY_BITS)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SECKEY_CacheStaticFlags(keyPair->privKey);
+ sc->serverKeyPair = ssl_GetKeyPairRef(keyPair);
+
+ if (SSL_CERT_IS(sc, ssl_auth_rsa_decrypt)) {
+ /* This will update the global session ticket key pair with this
+ * key, if a value hasn't been set already. */
+ if (ssl_MaybeSetSelfEncryptKeyPair(keyPair) != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ } else {
+ sc->serverKeyPair = NULL;
+ sc->namedCurve = NULL;
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl_PopulateOCSPResponses(sslServerCert *sc,
+ const SECItemArray *stapledOCSPResponses)
+{
+ if (sc->certStatusArray) {
+ SECITEM_FreeArray(sc->certStatusArray, PR_TRUE);
+ }
+ if (stapledOCSPResponses) {
+ sc->certStatusArray = SECITEM_DupArray(NULL, stapledOCSPResponses);
+ return sc->certStatusArray ? SECSuccess : SECFailure;
+ } else {
+ sc->certStatusArray = NULL;
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+ssl_PopulateSignedCertTimestamps(sslServerCert *sc,
+ const SECItem *signedCertTimestamps)
+{
+ if (sc->signedCertTimestamps.len) {
+ SECITEM_FreeItem(&sc->signedCertTimestamps, PR_FALSE);
+ }
+ if (signedCertTimestamps && signedCertTimestamps->len) {
+ return SECITEM_CopyItem(NULL, &sc->signedCertTimestamps,
+ signedCertTimestamps);
+ }
+ return SECSuccess;
+}
+
+/* Installs the given delegated credential (DC) and DC private key into the
+ * certificate.
+ *
+ * It's the caller's responsibility to ensure that the DC is well-formed and
+ * that the DC public key matches the DC private key.
+ */
+static SECStatus
+ssl_PopulateDelegatedCredential(sslServerCert *sc,
+ const SECItem *delegCred,
+ const SECKEYPrivateKey *delegCredPrivKey)
+{
+ sslDelegatedCredential *dc = NULL;
+
+ if (sc->delegCred.len) {
+ SECITEM_FreeItem(&sc->delegCred, PR_FALSE);
+ }
+
+ if (sc->delegCredKeyPair) {
+ ssl_FreeKeyPair(sc->delegCredKeyPair);
+ sc->delegCredKeyPair = NULL;
+ }
+
+ /* Both the DC and its private are present. */
+ if (delegCred && delegCredPrivKey) {
+ SECStatus rv;
+ SECKEYPublicKey *pub;
+ SECKEYPrivateKey *priv;
+
+ if (!delegCred->data || delegCred->len == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ /* Parse the DC. */
+ rv = tls13_ReadDelegatedCredential(delegCred->data, delegCred->len, &dc);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Make a copy of the DC. */
+ rv = SECITEM_CopyItem(NULL, &sc->delegCred, delegCred);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Make a copy of the DC private key. */
+ priv = SECKEY_CopyPrivateKey(delegCredPrivKey);
+ if (!priv) {
+ goto loser;
+ }
+
+ /* parse public key from the DC. */
+ pub = SECKEY_ExtractPublicKey(dc->spki);
+ if (!pub) {
+ goto loser;
+ }
+
+ sc->delegCredKeyPair = ssl_NewKeyPair(priv, pub);
+
+ /* Attempting to configure either the DC or DC private key, but not both. */
+ } else if (delegCred || delegCredPrivKey) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ tls13_DestroyDelegatedCredential(dc);
+ return SECSuccess;
+
+loser:
+ tls13_DestroyDelegatedCredential(dc);
+ return SECFailure;
+}
+
+/* Find any existing certificates that overlap with the new certificate and
+ * either remove any supported authentication types that overlap with the new
+ * certificate or - if they have no types left - remove them entirely. */
+static void
+ssl_ClearMatchingCerts(sslSocket *ss, sslAuthTypeMask authTypes,
+ const sslNamedGroupDef *namedCurve)
+{
+ PRCList *cursor = PR_NEXT_LINK(&ss->serverCerts);
+
+ while (cursor != &ss->serverCerts) {
+ sslServerCert *sc = (sslServerCert *)cursor;
+ cursor = PR_NEXT_LINK(cursor);
+ if ((sc->authTypes & authTypes) == 0) {
+ continue;
+ }
+ /* namedCurve will be NULL only for legacy functions. */
+ if (namedCurve != NULL && sc->namedCurve != namedCurve) {
+ continue;
+ }
+
+ sc->authTypes &= ~authTypes;
+ if (sc->authTypes == 0) {
+ PR_REMOVE_LINK(&sc->link);
+ ssl_FreeServerCert(sc);
+ }
+ }
+}
+
+static SECStatus
+ssl_ConfigCert(sslSocket *ss, sslAuthTypeMask authTypes,
+ CERTCertificate *cert, sslKeyPair *keyPair,
+ const SSLExtraServerCertData *data)
+{
+ SECStatus rv;
+ sslServerCert *sc = NULL;
+ int error_code = SEC_ERROR_NO_MEMORY;
+
+ PORT_Assert(cert);
+ PORT_Assert(keyPair);
+ PORT_Assert(data);
+ PORT_Assert(authTypes);
+
+ if (!cert || !keyPair || !data || !authTypes) {
+ error_code = SEC_ERROR_INVALID_ARGS;
+ goto loser;
+ }
+
+ sc = ssl_NewServerCert();
+ if (!sc) {
+ goto loser;
+ }
+
+ sc->authTypes = authTypes;
+ rv = ssl_PopulateServerCert(sc, cert, data->certChain);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = ssl_PopulateKeyPair(sc, keyPair);
+ if (rv != SECSuccess) {
+ error_code = PORT_GetError();
+ goto loser;
+ }
+ rv = ssl_PopulateOCSPResponses(sc, data->stapledOCSPResponses);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = ssl_PopulateSignedCertTimestamps(sc, data->signedCertTimestamps);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = ssl_PopulateDelegatedCredential(sc, data->delegCred,
+ data->delegCredPrivKey);
+ if (rv != SECSuccess) {
+ error_code = PORT_GetError();
+ goto loser;
+ }
+ ssl_ClearMatchingCerts(ss, sc->authTypes, sc->namedCurve);
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ return SECSuccess;
+
+loser:
+ ssl_FreeServerCert(sc);
+ PORT_SetError(error_code);
+ return SECFailure;
+}
+
+static SSLAuthType
+ssl_GetEcdhAuthType(CERTCertificate *cert)
+{
+ SECOidTag sigTag = SECOID_GetAlgorithmTag(&cert->signature);
+ switch (sigTag) {
+ case SEC_OID_PKCS1_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
+ case SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION:
+ return ssl_auth_ecdh_rsa;
+ case SEC_OID_ANSIX962_ECDSA_SHA1_SIGNATURE:
+ case SEC_OID_ANSIX962_ECDSA_SHA224_SIGNATURE:
+ case SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE:
+ case SEC_OID_ANSIX962_ECDSA_SHA384_SIGNATURE:
+ case SEC_OID_ANSIX962_ECDSA_SHA512_SIGNATURE:
+ case SEC_OID_ANSIX962_ECDSA_SIGNATURE_RECOMMENDED_DIGEST:
+ case SEC_OID_ANSIX962_ECDSA_SIGNATURE_SPECIFIED_DIGEST:
+ return ssl_auth_ecdh_ecdsa;
+ default:
+ return ssl_auth_null;
+ }
+}
+
+/* This function examines the type of certificate and its key usage and
+ * chooses which authTypes apply. For some certificates
+ * this can mean that multiple authTypes.
+ *
+ * If the targetAuthType is not ssl_auth_null, then only that type will be used.
+ * If that choice is invalid, then this function will fail. */
+static sslAuthTypeMask
+ssl_GetCertificateAuthTypes(CERTCertificate *cert, SSLAuthType targetAuthType)
+{
+ sslAuthTypeMask authTypes = 0;
+ SECOidTag tag;
+
+ tag = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
+ switch (tag) {
+ case SEC_OID_X500_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_RSA_ENCRYPTION:
+ if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
+ authTypes |= 1 << ssl_auth_rsa_sign;
+ }
+
+ if (cert->keyUsage & KU_KEY_ENCIPHERMENT) {
+ /* If ku_sig=true we configure signature and encryption slots with the
+ * same cert. This is bad form, but there are enough dual-usage RSA
+ * certs that we can't really break by limiting this to one type. */
+ authTypes |= 1 << ssl_auth_rsa_decrypt;
+ }
+ break;
+
+ case SEC_OID_PKCS1_RSA_PSS_SIGNATURE:
+ if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
+ authTypes |= 1 << ssl_auth_rsa_pss;
+ }
+ break;
+
+ case SEC_OID_ANSIX9_DSA_SIGNATURE:
+ if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
+ authTypes |= 1 << ssl_auth_dsa;
+ }
+ break;
+
+ case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
+ if (cert->keyUsage & KU_DIGITAL_SIGNATURE) {
+ authTypes |= 1 << ssl_auth_ecdsa;
+ }
+ /* Again, bad form to have dual usage and we don't prevent it. */
+ if (cert->keyUsage & KU_KEY_ENCIPHERMENT) {
+ authTypes |= 1 << ssl_GetEcdhAuthType(cert);
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ /* Check that we successfully picked an authType */
+ if (targetAuthType != ssl_auth_null) {
+ authTypes &= 1 << targetAuthType;
+ }
+ return authTypes;
+}
+
+/* This function adopts pubKey and destroys it if things go wrong. */
+static sslKeyPair *
+ssl_MakeKeyPairForCert(SECKEYPrivateKey *key, CERTCertificate *cert)
+{
+ sslKeyPair *keyPair = NULL;
+ SECKEYPublicKey *pubKey = NULL;
+ SECKEYPrivateKey *privKeyCopy = NULL;
+ PK11SlotInfo *bestSlot;
+
+ pubKey = CERT_ExtractPublicKey(cert);
+ if (!pubKey) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return NULL;
+ }
+
+ if (SECKEY_GetPublicKeyType(pubKey) != SECKEY_GetPrivateKeyType(key)) {
+ SECKEY_DestroyPublicKey(pubKey);
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return NULL;
+ }
+
+ if (key->pkcs11Slot) {
+ bestSlot = PK11_ReferenceSlot(key->pkcs11Slot);
+ if (bestSlot) {
+ privKeyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key);
+ PK11_FreeSlot(bestSlot);
+ }
+ }
+ if (!privKeyCopy) {
+ CK_MECHANISM_TYPE keyMech = PK11_MapSignKeyType(key->keyType);
+ /* XXX Maybe should be bestSlotMultiple? */
+ bestSlot = PK11_GetBestSlot(keyMech, NULL /* wincx */);
+ if (bestSlot) {
+ privKeyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key);
+ PK11_FreeSlot(bestSlot);
+ }
+ }
+ if (!privKeyCopy) {
+ privKeyCopy = SECKEY_CopyPrivateKey(key);
+ }
+ if (privKeyCopy) {
+ keyPair = ssl_NewKeyPair(privKeyCopy, pubKey);
+ }
+ if (!keyPair) {
+ if (privKeyCopy) {
+ SECKEY_DestroyPrivateKey(privKeyCopy);
+ }
+ SECKEY_DestroyPublicKey(pubKey);
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ }
+ return keyPair;
+}
+
+/* Configure a certificate and private key.
+ *
+ * This function examines the certificate and key to determine the type (or
+ * types) of authentication the certificate supports. As long as certificates
+ * are different (different authTypes and maybe keys in different ec groups),
+ * then this function can be called multiple times.
+ */
+SECStatus
+SSL_ConfigServerCert(PRFileDesc *fd, CERTCertificate *cert,
+ SECKEYPrivateKey *key,
+ const SSLExtraServerCertData *data, unsigned int data_len)
+{
+ sslSocket *ss;
+ sslKeyPair *keyPair;
+ SECStatus rv;
+ SSLExtraServerCertData dataCopy = {
+ ssl_auth_null, NULL, NULL, NULL, NULL, NULL
+ };
+ sslAuthTypeMask authTypes;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ if (!cert || !key) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (data) {
+ if (data_len > sizeof(dataCopy)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ PORT_Memcpy(&dataCopy, data, data_len);
+ }
+
+ authTypes = ssl_GetCertificateAuthTypes(cert, dataCopy.authType);
+ if (!authTypes) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ keyPair = ssl_MakeKeyPairForCert(key, cert);
+ if (!keyPair) {
+ return SECFailure;
+ }
+
+ rv = ssl_ConfigCert(ss, authTypes, cert, keyPair, &dataCopy);
+ ssl_FreeKeyPair(keyPair);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/*******************************************************************/
+/* Deprecated functions.
+ *
+ * The remainder of this file contains deprecated functions for server
+ * certificate configuration. These configure certificates incorrectly, but in
+ * a way that allows old code to continue working without change. All these
+ * functions create certificate slots based on SSLKEAType values. Some values
+ * of SSLKEAType cause multiple certificates to be configured.
+ */
+
+SECStatus
+SSL_ConfigSecureServer(PRFileDesc *fd, CERTCertificate *cert,
+ SECKEYPrivateKey *key, SSLKEAType kea)
+{
+ return SSL_ConfigSecureServerWithCertChain(fd, cert, NULL, key, kea);
+}
+
+/* This implements a limited check that is consistent with the checks performed
+ * by older versions of NSS. This is less rigorous than the checks in
+ * ssl_ConfigCertByUsage(), only checking against the type of key and ignoring
+ * things like usage. */
+static PRBool
+ssl_CertSuitableForAuthType(CERTCertificate *cert, sslAuthTypeMask authTypes)
+{
+ SECOidTag tag = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
+ sslAuthTypeMask mask = 0;
+ switch (tag) {
+ case SEC_OID_X500_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_RSA_ENCRYPTION:
+ mask |= 1 << ssl_auth_rsa_decrypt;
+ mask |= 1 << ssl_auth_rsa_sign;
+ break;
+ case SEC_OID_ANSIX9_DSA_SIGNATURE:
+ mask |= 1 << ssl_auth_dsa;
+ break;
+ case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
+ mask |= 1 << ssl_auth_ecdsa;
+ mask |= 1 << ssl_auth_ecdh_rsa;
+ mask |= 1 << ssl_auth_ecdh_ecdsa;
+ break;
+ default:
+ break;
+ }
+ PORT_Assert(authTypes);
+ /* Simply test that no inappropriate auth types are set. */
+ return (authTypes & ~mask) == 0;
+}
+
+/* Lookup a cert for the legacy configuration functions. An exact match on
+ * authTypes and ignoring namedCurve will ensure that values configured using
+ * legacy functions are overwritten by other legacy functions. */
+static sslServerCert *
+ssl_FindCertWithMask(sslSocket *ss, sslAuthTypeMask authTypes)
+{
+ PRCList *cursor;
+
+ for (cursor = PR_NEXT_LINK(&ss->serverCerts);
+ cursor != &ss->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *cert = (sslServerCert *)cursor;
+ if (cert->authTypes == authTypes) {
+ return cert;
+ }
+ }
+ return NULL;
+}
+
+/* This finds an existing server cert in a matching slot that can be reused.
+ * Failing that, it removes any other certs that might conflict and makes a new
+ * server cert slot of the right type. */
+static sslServerCert *
+ssl_FindOrMakeCert(sslSocket *ss, sslAuthTypeMask authTypes)
+{
+ sslServerCert *sc;
+
+ /* Reuse a perfect match. Note that there is a problem here with use of
+ * multiple EC certificates that have keys on different curves: these
+ * deprecated functions will match the first found and overwrite that
+ * certificate, potentially leaving the other values with a duplicate curve.
+ * Configuring multiple EC certificates are only possible with the new
+ * functions, so this is not something that is worth fixing. */
+ sc = ssl_FindCertWithMask(ss, authTypes);
+ if (sc) {
+ PR_REMOVE_LINK(&sc->link);
+ return sc;
+ }
+
+ /* Ignore the namedCurve parameter. Like above, this means that legacy
+ * functions will clobber values set with the new functions blindly. */
+ ssl_ClearMatchingCerts(ss, authTypes, NULL);
+
+ sc = ssl_NewServerCert();
+ if (sc) {
+ sc->authTypes = authTypes;
+ }
+ return sc;
+}
+
+static sslAuthTypeMask
+ssl_KeaTypeToAuthTypeMask(SSLKEAType keaType)
+{
+ switch (keaType) {
+ case ssl_kea_rsa:
+ return (1 << ssl_auth_rsa_decrypt) |
+ (1 << ssl_auth_rsa_sign);
+
+ case ssl_kea_dh:
+ return 1 << ssl_auth_dsa;
+
+ case ssl_kea_ecdh:
+ return (1 << ssl_auth_ecdsa) |
+ (1 << ssl_auth_ecdh_rsa) |
+ (1 << ssl_auth_ecdh_ecdsa);
+
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ }
+ return 0;
+}
+
+static SECStatus
+ssl_AddCertChain(sslSocket *ss, CERTCertificate *cert,
+ const CERTCertificateList *certChainOpt,
+ SECKEYPrivateKey *key, sslAuthTypeMask authTypes)
+{
+ sslServerCert *sc;
+ sslKeyPair *keyPair;
+ SECStatus rv;
+ PRErrorCode err = SEC_ERROR_NO_MEMORY;
+
+ if (!ssl_CertSuitableForAuthType(cert, authTypes)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ sc = ssl_FindOrMakeCert(ss, authTypes);
+ if (!sc) {
+ goto loser;
+ }
+
+ rv = ssl_PopulateServerCert(sc, cert, certChainOpt);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ keyPair = ssl_MakeKeyPairForCert(key, cert);
+ if (!keyPair) {
+ /* Error code is set by ssl_MakeKeyPairForCert */
+ goto loser;
+ }
+ rv = ssl_PopulateKeyPair(sc, keyPair);
+ ssl_FreeKeyPair(keyPair);
+ if (rv != SECSuccess) {
+ err = PORT_GetError();
+ goto loser;
+ }
+
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ return SECSuccess;
+
+loser:
+ ssl_FreeServerCert(sc);
+ PORT_SetError(err);
+ return SECFailure;
+}
+
+/* Public deprecated function */
+SECStatus
+SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert,
+ const CERTCertificateList *certChainOpt,
+ SECKEYPrivateKey *key, SSLKEAType certType)
+{
+ sslSocket *ss;
+ sslAuthTypeMask authTypes;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ if (!cert != !key) { /* Configure both, or neither */
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ authTypes = ssl_KeaTypeToAuthTypeMask(certType);
+ if (!authTypes) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!cert) {
+ sslServerCert *sc = ssl_FindCertWithMask(ss, authTypes);
+ if (sc) {
+ (void)ssl_PopulateServerCert(sc, NULL, NULL);
+ (void)ssl_PopulateKeyPair(sc, NULL);
+ /* Leave the entry linked here because the old API expects that.
+ * There might be OCSP stapling values or signed certificate
+ * timestamps still present that will subsequently be used. */
+ }
+ return SECSuccess;
+ }
+
+ return ssl_AddCertChain(ss, cert, certChainOpt, key, authTypes);
+}
+
+/* Public deprecated function */
+SECStatus
+SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses,
+ SSLKEAType certType)
+{
+ sslSocket *ss;
+ sslServerCert *sc;
+ sslAuthTypeMask authTypes;
+ SECStatus rv;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetStapledOCSPResponses",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ authTypes = ssl_KeaTypeToAuthTypeMask(certType);
+ if (!authTypes) {
+ SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetStapledOCSPResponses",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!responses) {
+ sc = ssl_FindCertWithMask(ss, authTypes);
+ if (sc) {
+ (void)ssl_PopulateOCSPResponses(sc, NULL);
+ }
+ return SECSuccess;
+ }
+
+ sc = ssl_FindOrMakeCert(ss, authTypes);
+ if (!sc) {
+ return SECFailure;
+ }
+
+ rv = ssl_PopulateOCSPResponses(sc, responses);
+ if (rv == SECSuccess) {
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ } else {
+ ssl_FreeServerCert(sc);
+ }
+ return rv;
+}
+
+/* Public deprecated function */
+SECStatus
+SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts,
+ SSLKEAType certType)
+{
+ sslSocket *ss;
+ sslServerCert *sc;
+ sslAuthTypeMask authTypes;
+ SECStatus rv;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSignedCertTimestamps",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ authTypes = ssl_KeaTypeToAuthTypeMask(certType);
+ if (!authTypes) {
+ SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetSignedCertTimestamps",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!scts) {
+ sc = ssl_FindCertWithMask(ss, authTypes);
+ if (sc) {
+ (void)ssl_PopulateSignedCertTimestamps(sc, NULL);
+ }
+ return SECSuccess;
+ }
+
+ sc = ssl_FindOrMakeCert(ss, authTypes);
+ if (!sc) {
+ return SECFailure;
+ }
+
+ rv = ssl_PopulateSignedCertTimestamps(sc, scts);
+ if (rv == SECSuccess) {
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ } else {
+ ssl_FreeServerCert(sc);
+ }
+ return rv;
+}
+
+/* Public deprecated function. */
+SSLKEAType
+NSS_FindCertKEAType(CERTCertificate *cert)
+{
+ int tag;
+
+ if (!cert)
+ return ssl_kea_null;
+
+ tag = SECOID_GetAlgorithmTag(&(cert->subjectPublicKeyInfo.algorithm));
+ switch (tag) {
+ case SEC_OID_X500_RSA_ENCRYPTION:
+ case SEC_OID_PKCS1_RSA_ENCRYPTION:
+ return ssl_kea_rsa;
+ case SEC_OID_ANSIX9_DSA_SIGNATURE: /* hah, signature, not a key? */
+ case SEC_OID_X942_DIFFIE_HELMAN_KEY:
+ return ssl_kea_dh;
+ case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
+ return ssl_kea_ecdh;
+ default:
+ return ssl_kea_null;
+ }
+}
diff --git a/security/nss/lib/ssl/sslcert.h b/security/nss/lib/ssl/sslcert.h
new file mode 100644
index 0000000000..8c2dadae46
--- /dev/null
+++ b/security/nss/lib/ssl/sslcert.h
@@ -0,0 +1,67 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslcert_h_
+#define __sslcert_h_
+
+#include "cert.h"
+#include "secitem.h"
+#include "keyhi.h"
+
+/* This type is a bitvector that is indexed by SSLAuthType values. Note that
+ * the bit for ssl_auth_null(0) - the least significant bit - isn't used. */
+typedef PRUint16 sslAuthTypeMask;
+PR_STATIC_ASSERT(sizeof(sslAuthTypeMask) * 8 >= ssl_auth_size);
+
+typedef struct sslServerCertStr {
+ PRCList link; /* The linked list link */
+
+ /* The auth types that this certificate provides. */
+ sslAuthTypeMask authTypes;
+ /* For ssl_auth_ecdsa and ssl_auth_ecdh_*. This is only the named curve
+ * of the end-entity certificate key. The keys in other certificates in
+ * the chain aren't directly relevant to the operation of TLS (though it
+ * might make certificate validation difficult, libssl doesn't care). */
+ const sslNamedGroupDef *namedCurve;
+
+ /* Configuration state for server sockets */
+ CERTCertificate *serverCert;
+ CERTCertificateList *serverCertChain;
+ sslKeyPair *serverKeyPair;
+ unsigned int serverKeyBits;
+ /* Each certificate needs its own status. */
+ SECItemArray *certStatusArray;
+ /* Serialized signed certificate timestamps to be sent to the client
+ ** in a TLS extension (server only). Each certificate needs its own
+ ** timestamps item.
+ */
+ SECItem signedCertTimestamps;
+
+ /* The delegated credential (DC) to send to clients who indicate support for
+ * the ietf-draft-tls-subcerts extension.
+ */
+ SECItem delegCred;
+ /* The key pair used to sign the handshake when serving a DC. */
+ sslKeyPair *delegCredKeyPair;
+} sslServerCert;
+
+#define SSL_CERT_IS(c, t) ((c)->authTypes & (1 << (t)))
+#define SSL_CERT_IS_ONLY(c, t) ((c)->authTypes == (1 << (t)))
+#define SSL_CERT_IS_EC(c) \
+ ((c)->authTypes & ((1 << ssl_auth_ecdsa) | \
+ (1 << ssl_auth_ecdh_rsa) | \
+ (1 << ssl_auth_ecdh_ecdsa)))
+
+extern sslServerCert *ssl_NewServerCert();
+extern sslServerCert *ssl_CopyServerCert(const sslServerCert *oc);
+extern const sslServerCert *ssl_FindServerCert(
+ const sslSocket *ss, SSLAuthType authType,
+ const sslNamedGroupDef *namedCurve);
+extern void ssl_FreeServerCert(sslServerCert *sc);
+
+#endif /* __sslcert_h_ */
diff --git a/security/nss/lib/ssl/sslcon.c b/security/nss/lib/ssl/sslcon.c
new file mode 100644
index 0000000000..a6ef2a4a34
--- /dev/null
+++ b/security/nss/lib/ssl/sslcon.c
@@ -0,0 +1,248 @@
+/*
+ * Basic SSL handshake functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nssrenam.h"
+#include "cert.h"
+#include "secitem.h"
+#include "sechash.h"
+#include "cryptohi.h" /* for SGN_ funcs */
+#include "keyhi.h" /* for SECKEY_ high level functions. */
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "ssl3prot.h"
+#include "sslerr.h"
+#include "pk11func.h"
+#include "prinit.h"
+
+/*
+** Put a string tag in the library so that we can examine an executable
+** and see what kind of security it supports.
+*/
+const char *ssl_version = "SECURITY_VERSION:"
+ " +us"
+ " +export"
+#ifdef TRACE
+ " +trace"
+#endif
+#ifdef DEBUG
+ " +debug"
+#endif
+ ;
+
+/***********************************************************************
+ * Gathers in and handles records/messages until either the handshake is
+ * complete or application data is available.
+ *
+ * Called from ssl_Do1stHandshake() via function pointer ss->handshake.
+ * Caller must hold handshake lock.
+ * This function acquires and releases the RecvBufLock.
+ *
+ * returns SECSuccess for success.
+ * returns SECFailure on error, setting PR_WOULD_BLOCK_ERROR if only blocked.
+ *
+ * The gather functions called by ssl_GatherRecord1stHandshake are expected
+ * to return values interpreted as follows:
+ * 1 : the function completed without error.
+ * 0 : the function read EOF.
+ * -1 : read error, or PR_WOULD_BLOCK_ERROR, or handleRecord error.
+ *
+ * This code is similar to, and easily confused with, DoRecv() in sslsecur.c
+ *
+ * This function is called from ssl_Do1stHandshake().
+ * The following functions put ssl_GatherRecord1stHandshake into ss->handshake:
+ * ssl_BeginClientHandshake
+ * ssl3_RestartHandshakeAfterCertReq
+ * ssl3_RestartHandshakeAfterServerCert
+ * ssl_BeginServerHandshake
+ */
+SECStatus
+ssl_GatherRecord1stHandshake(sslSocket *ss)
+{
+ int rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+
+ ssl_GetRecvBufLock(ss);
+
+ /* Wait for handshake to complete, or application data to arrive. */
+ rv = ssl3_GatherCompleteHandshake(ss, 0);
+ SSL_TRC(10, ("%d: SSL[%d]: handshake gathering, rv=%d",
+ SSL_GETPID(), ss->fd, rv));
+
+ ssl_ReleaseRecvBufLock(ss);
+
+ if (rv <= 0) {
+ if (rv == 0) {
+ /* EOF. Loser */
+ PORT_SetError(PR_END_OF_FILE_ERROR);
+ }
+ if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) {
+ SSL_TRC(10, ("%d: SSL[%d]: handshake blocked (need %d)",
+ SSL_GETPID(), ss->fd, ss->gs.remainder));
+ }
+ return SECFailure; /* rv is < 0 here. */
+ }
+
+ ss->handshake = NULL;
+ return SECSuccess;
+}
+
+/* This function is called at the beginning of a handshake to ensure that at
+ * least one SSL/TLS version is enabled. */
+static SECStatus
+ssl_CheckConfigSanity(sslSocket *ss)
+{
+ if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) {
+ SSL_DBG(("%d: SSL[%d]: Can't handshake! all versions disabled.",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(SSL_ERROR_SSL_DISABLED);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/* Sends out the initial client Hello message on the connection.
+ * Acquires and releases the socket's xmitBufLock.
+ */
+SECStatus
+ssl_BeginClientHandshake(sslSocket *ss)
+{
+ sslSessionID *sid = NULL;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+
+ ss->sec.isServer = PR_FALSE;
+
+ rv = ssl_CheckConfigSanity(ss);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Get peer name of server */
+ rv = ssl_GetPeerInfo(ss);
+ if (rv < 0) {
+#ifdef HPUX11
+ /*
+ * On some HP-UX B.11.00 systems, getpeername() occasionally
+ * fails with ENOTCONN after a successful completion of
+ * non-blocking connect. I found that if we do a write()
+ * and then retry getpeername(), it will work.
+ */
+ if (PR_GetError() == PR_NOT_CONNECTED_ERROR) {
+ char dummy;
+ (void)PR_Write(ss->fd->lower, &dummy, 0);
+ rv = ssl_GetPeerInfo(ss);
+ if (rv < 0) {
+ goto loser;
+ }
+ }
+#else
+ goto loser;
+#endif
+ }
+
+ SSL_TRC(3, ("%d: SSL[%d]: sending client-hello", SSL_GETPID(), ss->fd));
+
+ /* If there's an sid set from an external cache, use it. */
+ if (ss->sec.ci.sid && ss->sec.ci.sid->cached == in_external_cache) {
+ sid = ss->sec.ci.sid;
+ SSL_TRC(3, ("%d: SSL[%d]: using external token", SSL_GETPID(), ss->fd));
+ } else if (!ss->opt.noCache) {
+ /* Try to find server in our session-id cache */
+ sid = ssl_LookupSID(ssl_Time(ss), &ss->sec.ci.peer,
+ ss->sec.ci.port, ss->peerID, ss->url);
+ }
+
+ if (sid) {
+ if (sid->version >= ss->vrange.min && sid->version <= ss->vrange.max) {
+ PORT_Assert(!ss->sec.localCert);
+ ss->sec.localCert = CERT_DupCertificate(sid->localCert);
+ } else {
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ sid = NULL;
+ }
+ }
+ if (!sid) {
+ sid = ssl3_NewSessionID(ss, PR_FALSE);
+ if (!sid) {
+ goto loser;
+ }
+ /* This session is a dummy, which we don't want to resume. */
+ sid->u.ssl3.keys.resumable = PR_FALSE;
+ }
+ ss->sec.ci.sid = sid;
+
+ ss->gs.state = GS_INIT;
+ ss->handshake = ssl_GatherRecord1stHandshake;
+
+ /* ssl3_SendClientHello will override this if it succeeds. */
+ ss->version = SSL_LIBRARY_VERSION_3_0;
+
+ ssl_GetSSL3HandshakeLock(ss);
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_SendClientHello(ss, client_hello_initial);
+ ssl_ReleaseXmitBufLock(ss);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+
+ return rv;
+
+loser:
+ return SECFailure;
+}
+
+SECStatus
+ssl_BeginServerHandshake(sslSocket *ss)
+{
+ SECStatus rv;
+
+ ss->sec.isServer = PR_TRUE;
+ ss->ssl3.hs.ws = wait_client_hello;
+
+ rv = ssl_CheckConfigSanity(ss);
+ if (rv != SECSuccess)
+ goto loser;
+
+ ss->handshake = ssl_GatherRecord1stHandshake;
+ return SECSuccess;
+
+loser:
+ return SECFailure;
+}
+
+/* This function doesn't really belong in this file.
+** It's here to keep AIX compilers from optimizing it away,
+** and not including it in the DSO.
+*/
+
+#include "nss.h"
+extern const char __nss_ssl_version[];
+
+PRBool
+NSSSSL_VersionCheck(const char *importedVersion)
+{
+#define NSS_VERSION_VARIABLE __nss_ssl_version
+#include "verref.h"
+
+ /*
+ * This is the secret handshake algorithm.
+ *
+ * This release has a simple version compatibility
+ * check algorithm. This release is not backward
+ * compatible with previous major releases. It is
+ * not compatible with future major, minor, or
+ * patch releases.
+ */
+ return NSS_VersionCheck(importedVersion);
+}
+
+const char *
+NSSSSL_GetVersion(void)
+{
+ return NSS_VERSION;
+}
diff --git a/security/nss/lib/ssl/ssldef.c b/security/nss/lib/ssl/ssldef.c
new file mode 100644
index 0000000000..3ed1979507
--- /dev/null
+++ b/security/nss/lib/ssl/ssldef.c
@@ -0,0 +1,226 @@
+/*
+ * "Default" SSLSocket methods, used by sockets that do neither SSL nor socks.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "cert.h"
+#include "ssl.h"
+#include "sslimpl.h"
+
+#if defined(WIN32)
+#define MAP_ERROR(from, to) \
+ if (err == from) { \
+ PORT_SetError(to); \
+ }
+#define DEFINE_ERROR PRErrorCode err = PR_GetError();
+#else
+#define MAP_ERROR(from, to)
+#define DEFINE_ERROR
+#endif
+
+int
+ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->connect(lower, sa, ss->cTimeout);
+ return rv;
+}
+
+int
+ssl_DefBind(sslSocket *ss, const PRNetAddr *addr)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->bind(lower, addr);
+ return rv;
+}
+
+int
+ssl_DefListen(sslSocket *ss, int backlog)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->listen(lower, backlog);
+ return rv;
+}
+
+int
+ssl_DefShutdown(sslSocket *ss, int how)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->shutdown(lower, how);
+ return rv;
+}
+
+int
+ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ PORT_Assert(buf && len > 0);
+
+ rv = lower->methods->recv(lower, (void *)buf, len, flags, ss->rTimeout);
+ if (rv < 0) {
+ DEFINE_ERROR
+ MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR)
+ } else if (rv > len) {
+ PORT_Assert(rv <= len);
+ PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
+ rv = SECFailure;
+ }
+ return rv;
+}
+
+/* Default (unencrypted) send.
+ * For blocking sockets, always returns len or SECFailure, no short writes.
+ * For non-blocking sockets:
+ * Returns positive count if any data was written, else returns SECFailure.
+ * Short writes may occur.
+ */
+int
+ssl_DefSend(sslSocket *ss, const unsigned char *buf, int len, int flags)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int sent = 0;
+
+#if NSS_DISABLE_NAGLE_DELAYS
+ /* Although this is overkill, we disable Nagle delays completely for
+ ** SSL sockets.
+ */
+ if (ss->opt.useSecurity && !ss->delayDisabled) {
+ ssl_EnableNagleDelay(ss, PR_FALSE); /* ignore error */
+ ss->delayDisabled = 1;
+ }
+#endif
+ do {
+ int rv = lower->methods->send(lower, (const void *)(buf + sent),
+ len - sent, flags, ss->wTimeout);
+ if (rv < 0) {
+ PRErrorCode err = PR_GetError();
+ if (err == PR_WOULD_BLOCK_ERROR) {
+ ss->lastWriteBlocked = 1;
+ return sent ? sent : SECFailure;
+ }
+ ss->lastWriteBlocked = 0;
+ MAP_ERROR(PR_CONNECT_ABORTED_ERROR, PR_CONNECT_RESET_ERROR)
+ /* Loser */
+ return rv;
+ }
+ sent += rv;
+
+ if (IS_DTLS(ss) && (len > sent)) {
+ /* We got a partial write so just return it */
+ return sent;
+ }
+ } while (len > sent);
+ ss->lastWriteBlocked = 0;
+ return sent;
+}
+
+int
+ssl_DefRead(sslSocket *ss, unsigned char *buf, int len)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->read(lower, (void *)buf, len);
+ if (rv < 0) {
+ DEFINE_ERROR
+ MAP_ERROR(PR_SOCKET_SHUTDOWN_ERROR, PR_CONNECT_RESET_ERROR)
+ }
+ return rv;
+}
+
+int
+ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int sent = 0;
+
+ do {
+ int rv = lower->methods->write(lower, (const void *)(buf + sent),
+ len - sent);
+ if (rv < 0) {
+ PRErrorCode err = PR_GetError();
+ if (err == PR_WOULD_BLOCK_ERROR) {
+ ss->lastWriteBlocked = 1;
+ return sent ? sent : SECFailure;
+ }
+ ss->lastWriteBlocked = 0;
+ MAP_ERROR(PR_CONNECT_ABORTED_ERROR, PR_CONNECT_RESET_ERROR)
+ /* Loser */
+ return rv;
+ }
+ sent += rv;
+ } while (len > sent);
+ ss->lastWriteBlocked = 0;
+ return sent;
+}
+
+int
+ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->getpeername(lower, name);
+ return rv;
+}
+
+int
+ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name)
+{
+ PRFileDesc *lower = ss->fd->lower;
+ int rv;
+
+ rv = lower->methods->getsockname(lower, name);
+ return rv;
+}
+
+int
+ssl_DefClose(sslSocket *ss)
+{
+ PRFileDesc *fd;
+ PRFileDesc *popped;
+ int rv;
+
+ fd = ss->fd;
+
+ /* First, remove the SSL layer PRFileDesc from the socket's stack,
+ ** then invoke the SSL layer's PRFileDesc destructor.
+ ** This must happen before the next layer down is closed.
+ */
+ PORT_Assert(fd->higher == NULL);
+ if (fd->higher) {
+ PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
+ return SECFailure;
+ }
+ ss->fd = NULL;
+
+ /* PR_PopIOLayer will swap the contents of the top two PRFileDescs on
+ ** the stack, and then remove the second one. This way, the address
+ ** of the PRFileDesc on the top of the stack doesn't change.
+ */
+ popped = PR_PopIOLayer(fd, PR_TOP_IO_LAYER);
+ popped->dtor(popped);
+
+ /* fd is now the PRFileDesc for the next layer down.
+ ** Now close the underlying socket.
+ */
+ rv = fd->methods->close(fd);
+
+ ssl_FreeSocket(ss);
+
+ SSL_TRC(5, ("%d: SSL[%d]: closing, rv=%d errno=%d",
+ SSL_GETPID(), fd, rv, PORT_GetError()));
+ return rv;
+}
diff --git a/security/nss/lib/ssl/sslencode.c b/security/nss/lib/ssl/sslencode.c
new file mode 100644
index 0000000000..fcd90227d7
--- /dev/null
+++ b/security/nss/lib/ssl/sslencode.c
@@ -0,0 +1,383 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "prnetdb.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+
+/* Helper function to encode an unsigned integer into a buffer. */
+static void
+ssl_EncodeUintX(PRUint8 *to, PRUint64 value, unsigned int bytes)
+{
+ PRUint64 encoded;
+
+ PORT_Assert(bytes > 0 && bytes <= sizeof(encoded));
+
+ encoded = PR_htonll(value);
+ PORT_Memcpy(to, ((unsigned char *)(&encoded)) + (sizeof(encoded) - bytes),
+ bytes);
+}
+
+/* Grow a buffer to hold newLen bytes of data. When used for recv/xmit buffers,
+ * the caller must hold xmitBufLock or recvBufLock, as appropriate. */
+SECStatus
+sslBuffer_Grow(sslBuffer *b, unsigned int newLen)
+{
+ PORT_Assert(b);
+ if (b->fixed) {
+ PORT_Assert(newLen <= b->space);
+ if (newLen > b->space) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ return SECSuccess;
+ }
+
+ /* If buf is non-NULL, space must be non-zero;
+ * if buf is NULL, space must be zero. */
+ PORT_Assert((b->buf && b->space) || (!b->buf && !b->space));
+ newLen = PR_MAX(newLen, b->len + 1024);
+ if (newLen > b->space) {
+ unsigned char *newBuf;
+ if (b->buf) {
+ newBuf = (unsigned char *)PORT_Realloc(b->buf, newLen);
+ } else {
+ newBuf = (unsigned char *)PORT_Alloc(newLen);
+ }
+ if (!newBuf) {
+ return SECFailure;
+ }
+ b->buf = newBuf;
+ b->space = newLen;
+ }
+ return SECSuccess;
+}
+
+/* Appends len copies of c to b */
+SECStatus
+sslBuffer_Fill(sslBuffer *b, PRUint8 c, size_t len)
+{
+ PORT_Assert(b);
+ SECStatus rv = sslBuffer_Grow(b, b->len + len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (len > 0) {
+ memset(SSL_BUFFER_NEXT(b), c, len);
+ }
+ b->len += len;
+ return SECSuccess;
+}
+
+SECStatus
+sslBuffer_Append(sslBuffer *b, const void *data, unsigned int len)
+{
+ SECStatus rv = sslBuffer_Grow(b, b->len + len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+ if (len > 0) {
+ PORT_Assert(data);
+ PORT_Memcpy(SSL_BUFFER_NEXT(b), data, len);
+ }
+ b->len += len;
+ return SECSuccess;
+}
+
+SECStatus
+sslBuffer_AppendNumber(sslBuffer *b, PRUint64 v, unsigned int size)
+{
+ SECStatus rv = sslBuffer_Grow(b, b->len + size);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ ssl_EncodeUintX(SSL_BUFFER_NEXT(b), v, size);
+ b->len += size;
+ return SECSuccess;
+}
+
+SECStatus
+sslBuffer_AppendVariable(sslBuffer *b, const PRUint8 *data, unsigned int len,
+ unsigned int size)
+{
+ PORT_Assert(size <= 4 && size > 0);
+ PORT_Assert(b);
+ if (len >= (1ULL << (8 * size))) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (sslBuffer_Grow(b, b->len + len + size) != SECSuccess) {
+ return SECFailure;
+ }
+
+ ssl_EncodeUintX(SSL_BUFFER_NEXT(b), len, size);
+ b->len += size;
+ if (len != 0) {
+ PORT_Assert(data);
+ /* We sometimes pass NULL, 0 and memcpy() doesn't want NULL. */
+ PORT_Memcpy(SSL_BUFFER_NEXT(b), data, len);
+ }
+ b->len += len;
+ return SECSuccess;
+}
+
+SECStatus
+sslBuffer_AppendBuffer(sslBuffer *b, const sslBuffer *append)
+{
+ return sslBuffer_Append(b, append->buf, append->len);
+}
+
+SECStatus
+sslBuffer_AppendBufferVariable(sslBuffer *b, const sslBuffer *append,
+ unsigned int size)
+{
+ return sslBuffer_AppendVariable(b, append->buf, append->len, size);
+}
+
+SECStatus
+sslBuffer_Skip(sslBuffer *b, unsigned int size, unsigned int *savedOffset)
+{
+ if (sslBuffer_Grow(b, b->len + size) != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (savedOffset) {
+ *savedOffset = b->len;
+ }
+ b->len += size;
+ return SECSuccess;
+}
+
+/* A common problem is that a buffer is used to construct a variable length
+ * structure of unknown length. The length field for that structure is then
+ * populated afterwards. This function makes this process a little easier.
+ *
+ * To use this, before encoding the variable length structure, skip the spot
+ * where the length would be using sslBuffer_Skip(). After encoding the
+ * structure, and before encoding anything else, call this function passing the
+ * value returned from sslBuffer_Skip() as |at| to have the length inserted.
+ */
+SECStatus
+sslBuffer_InsertLength(sslBuffer *b, unsigned int at, unsigned int size)
+{
+ unsigned int len;
+
+ PORT_Assert(b->len >= at + size);
+ PORT_Assert(b->space >= at + size);
+ len = b->len - (at + size);
+
+ PORT_Assert(size <= 4 && size > 0);
+ if (len >= (1ULL << (8 * size))) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ssl_EncodeUintX(SSL_BUFFER_BASE(b) + at, len, size);
+ return SECSuccess;
+}
+
+SECStatus
+sslBuffer_InsertNumber(sslBuffer *b, unsigned int at,
+ PRUint64 v, unsigned int size)
+{
+ PORT_Assert(b->len >= at + size);
+ PORT_Assert(b->space >= at + size);
+
+ PORT_Assert(size <= 4 && size > 0);
+ if (v >= (1ULL << (8 * size))) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ssl_EncodeUintX(SSL_BUFFER_BASE(b) + at, v, size);
+ return SECSuccess;
+}
+
+void
+sslBuffer_Clear(sslBuffer *b)
+{
+ if (!b->fixed) {
+ if (b->buf) {
+ PORT_Free(b->buf);
+ b->buf = NULL;
+ }
+ b->space = 0;
+ }
+ b->len = 0;
+}
+
+SECStatus
+sslRead_Read(sslReader *reader, unsigned int count, sslReadBuffer *out)
+{
+ if (!reader || !out) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (reader->buf.len < reader->offset ||
+ count > SSL_READER_REMAINING(reader)) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+
+ out->buf = SSL_READER_CURRENT(reader);
+ out->len = count;
+ reader->offset += count;
+
+ return SECSuccess;
+}
+
+SECStatus
+sslRead_ReadVariable(sslReader *reader, unsigned int sizeLen, sslReadBuffer *out)
+{
+ PRUint64 variableLen = 0;
+ SECStatus rv = sslRead_ReadNumber(reader, sizeLen, &variableLen);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+ if (!variableLen) {
+ // It is ok to have an empty variable.
+ out->len = variableLen;
+ return SECSuccess;
+ }
+ return sslRead_Read(reader, variableLen, out);
+}
+
+SECStatus
+sslRead_ReadNumber(sslReader *reader, unsigned int bytes, PRUint64 *num)
+{
+ if (!reader || !num) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (reader->buf.len < reader->offset ||
+ bytes > SSL_READER_REMAINING(reader) ||
+ bytes > 8) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+ unsigned int i;
+ PRUint64 number = 0;
+ for (i = 0; i < bytes; i++) {
+ number = (number << 8) + reader->buf.buf[i + reader->offset];
+ }
+
+ reader->offset = reader->offset + bytes;
+ *num = number;
+ return SECSuccess;
+}
+
+/**************************************************************************
+ * Append Handshake functions.
+ * All these functions set appropriate error codes.
+ * Most rely on ssl3_AppendHandshake to set the error code.
+ **************************************************************************/
+#define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
+#define MIN_SEND_BUF_LENGTH 4000
+
+static SECStatus
+ssl3_AppendHandshakeInternal(sslSocket *ss, const void *void_src, unsigned int bytes, PRBool suppressHash)
+{
+ unsigned char *src = (unsigned char *)void_src;
+ int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* protects sendBuf. */
+
+ if (!bytes)
+ return SECSuccess;
+ if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
+ rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
+ PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
+ if (rv != SECSuccess)
+ return SECFailure; /* sslBuffer_Grow sets a memory error code. */
+ room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
+ }
+
+ PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char *)void_src, bytes));
+ // TODO: Move firstHsDone and version check into callers as a suppression.
+ if (!suppressHash && (!ss->firstHsDone || ss->version < SSL_LIBRARY_VERSION_TLS_1_3)) {
+ rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
+ if (rv != SECSuccess)
+ return SECFailure; /* error code set by ssl3_UpdateHandshakeHashes */
+ }
+
+ while (bytes > room) {
+ if (room > 0)
+ PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
+ room);
+ ss->sec.ci.sendBuf.len += room;
+ rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code set by ssl3_FlushHandshake */
+ }
+ bytes -= room;
+ src += room;
+ room = ss->sec.ci.sendBuf.space;
+ PORT_Assert(ss->sec.ci.sendBuf.len == 0);
+ }
+ PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
+ ss->sec.ci.sendBuf.len += bytes;
+ return SECSuccess;
+}
+
+SECStatus
+ssl3_AppendHandshakeSuppressHash(sslSocket *ss, const void *void_src, unsigned int bytes)
+{
+ return ssl3_AppendHandshakeInternal(ss, void_src, bytes, PR_TRUE);
+}
+
+SECStatus
+ssl3_AppendHandshake(sslSocket *ss, const void *void_src, unsigned int bytes)
+{
+ return ssl3_AppendHandshakeInternal(ss, void_src, bytes, PR_FALSE);
+}
+
+SECStatus
+ssl3_AppendHandshakeNumber(sslSocket *ss, PRUint64 num, unsigned int lenSize)
+{
+ PRUint8 b[sizeof(num)];
+ SSL_TRC(60, ("%d: number:", SSL_GETPID()));
+ ssl_EncodeUintX(b, num, lenSize);
+ return ssl3_AppendHandshake(ss, b, lenSize);
+}
+
+SECStatus
+ssl3_AppendHandshakeVariable(sslSocket *ss, const PRUint8 *src,
+ unsigned int bytes, unsigned int lenSize)
+{
+ SECStatus rv;
+
+ PORT_Assert((bytes < (1 << 8) && lenSize == 1) ||
+ (bytes < (1L << 16) && lenSize == 2) ||
+ (bytes < (1L << 24) && lenSize == 3));
+
+ SSL_TRC(60, ("%d: append variable:", SSL_GETPID()));
+ rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code set by AppendHandshake. */
+ }
+ SSL_TRC(60, ("data:"));
+ return ssl3_AppendHandshake(ss, src, bytes);
+}
+
+SECStatus
+ssl3_AppendBufferToHandshake(sslSocket *ss, sslBuffer *buf)
+{
+ return ssl3_AppendHandshake(ss, buf->buf, buf->len);
+}
+
+SECStatus
+ssl3_AppendBufferToHandshakeVariable(sslSocket *ss, sslBuffer *buf,
+ unsigned int lenSize)
+{
+ return ssl3_AppendHandshakeVariable(ss, buf->buf, buf->len, lenSize);
+}
diff --git a/security/nss/lib/ssl/sslencode.h b/security/nss/lib/ssl/sslencode.h
new file mode 100644
index 0000000000..011034aa19
--- /dev/null
+++ b/security/nss/lib/ssl/sslencode.h
@@ -0,0 +1,94 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslencode_h_
+#define __sslencode_h_
+
+/* A buffer object, used for assembling messages. */
+typedef struct sslBufferStr {
+ PRUint8 *buf;
+ unsigned int len;
+ unsigned int space;
+ /* Set to true if the storage for the buffer is fixed, such as a stack
+ * variable or a view on another buffer. Growing a fixed buffer fails. */
+ PRBool fixed;
+} sslBuffer;
+
+#define SSL_BUFFER_EMPTY \
+ { \
+ NULL, 0, 0, PR_FALSE \
+ }
+#define SSL_BUFFER_FIXED(b, maxlen) \
+ { \
+ b, 0, maxlen, PR_TRUE \
+ }
+#define SSL_BUFFER_FIXED_LEN(b, len) \
+ { \
+ b, len, 0, PR_TRUE \
+ }
+#define SSL_BUFFER(b) SSL_BUFFER_FIXED(b, sizeof(b))
+#define SSL_BUFFER_BASE(b) ((b)->buf)
+#define SSL_BUFFER_LEN(b) ((b)->len)
+#define SSL_BUFFER_NEXT(b) ((b)->buf + (b)->len)
+#define SSL_BUFFER_SPACE(b) ((b)->space - (b)->len)
+
+SECStatus sslBuffer_Grow(sslBuffer *b, unsigned int newLen);
+SECStatus sslBuffer_Fill(sslBuffer *b, PRUint8 c, size_t len);
+SECStatus sslBuffer_Append(sslBuffer *b, const void *data, unsigned int len);
+SECStatus sslBuffer_AppendNumber(sslBuffer *b, PRUint64 v, unsigned int size);
+SECStatus sslBuffer_AppendVariable(sslBuffer *b, const PRUint8 *data,
+ unsigned int len, unsigned int size);
+SECStatus sslBuffer_AppendBuffer(sslBuffer *b, const sslBuffer *append);
+SECStatus sslBuffer_AppendBufferVariable(sslBuffer *b, const sslBuffer *append,
+ unsigned int size);
+SECStatus sslBuffer_Skip(sslBuffer *b, unsigned int size,
+ unsigned int *savedOffset);
+SECStatus sslBuffer_InsertLength(sslBuffer *b, unsigned int at,
+ unsigned int size);
+SECStatus sslBuffer_InsertNumber(sslBuffer *b, unsigned int at,
+ PRUint64 v, unsigned int size);
+void sslBuffer_Clear(sslBuffer *b);
+
+SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src,
+ unsigned int bytes);
+SECStatus ssl3_AppendHandshakeSuppressHash(sslSocket *ss, const void *void_src,
+ unsigned int bytes);
+SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss,
+ SSLHandshakeType t, unsigned int length);
+SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRUint64 num,
+ unsigned int lenSize);
+SECStatus ssl3_AppendHandshakeVariable(sslSocket *ss, const PRUint8 *src,
+ unsigned int bytes, unsigned int lenSize);
+SECStatus ssl3_AppendBufferToHandshake(sslSocket *ss, sslBuffer *buf);
+SECStatus ssl3_AppendBufferToHandshakeVariable(sslSocket *ss, sslBuffer *buf,
+ unsigned int lenSize);
+
+typedef struct {
+ const PRUint8 *buf;
+ unsigned int len;
+} sslReadBuffer;
+typedef struct {
+ sslReadBuffer buf;
+ unsigned int offset;
+} sslReader;
+#define SSL_READER(b, l) \
+ { \
+ { b, l }, 0 \
+ }
+#define SSL_READER_CURRENT(r) \
+ ((r)->buf.buf + (r)->offset)
+#define SSL_READER_REMAINING(r) \
+ ((r)->buf.len - (r)->offset)
+SECStatus sslRead_Read(sslReader *reader, unsigned int count,
+ sslReadBuffer *out);
+SECStatus sslRead_ReadVariable(sslReader *reader, unsigned int sizeLen,
+ sslReadBuffer *out);
+SECStatus sslRead_ReadNumber(sslReader *reader, unsigned int bytes,
+ PRUint64 *val);
+
+#endif /* __sslencode_h_ */
diff --git a/security/nss/lib/ssl/sslenum.c b/security/nss/lib/ssl/sslenum.c
new file mode 100644
index 0000000000..b5272d4a85
--- /dev/null
+++ b/security/nss/lib/ssl/sslenum.c
@@ -0,0 +1,157 @@
+/*
+ * Table enumerating all implemented cipher suites
+ * Part of public API.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ssl.h"
+#include "sslproto.h"
+
+/*
+ * The ordering of cipher suites in this table must match the ordering in
+ * the cipherSuites table in ssl3con.c.
+ *
+ * If new ECC cipher suites are added, also update the ssl3CipherSuite arrays
+ * in ssl3ecc.c.
+ *
+ * Finally, update the ssl_V3_SUITES_IMPLEMENTED macro in sslimpl.h.
+ *
+ * The ordering is as follows:
+ * * No-encryption cipher suites last
+ * * Export/weak/obsolete cipher suites before no-encryption cipher suites
+ * * Order by key exchange algorithm: ECDHE, then DHE, then ECDH, RSA.
+ * * Within key agreement sections, prefer AEAD over non-AEAD cipher suites.
+ * * Within AEAD sections, order by symmetric encryption algorithm which
+ * integrates message authentication algorithm: AES-128-GCM, then
+ * ChaCha20-Poly1305, then AES-256-GCM,
+ * * Within non-AEAD sections, order by symmetric encryption algorithm:
+ * AES-128, then Camellia-128, then AES-256, then Camellia-256, then SEED,
+ * then FIPS-3DES, then 3DES, then RC4. AES is commonly accepted as a
+ * strong cipher internationally, and is often hardware-accelerated.
+ * Camellia also has wide international support across standards
+ * organizations. SEED is only recommended by the Korean government. 3DES
+ * only provides 112 bits of security. RC4 is now deprecated or forbidden
+ * by many standards organizations.
+ * * Within non-AEAD symmetric algorithm sections, order by message
+ * authentication algorithm: HMAC-SHA256, then HMAC-SHA384, then HMAC-SHA1,
+ * then HMAC-MD5.
+ * * Within symmetric algorithm sections, order by message authentication
+ * algorithm: GCM, then HMAC-SHA1, then HMAC-SHA256, then HMAC-MD5.
+ * * Within message authentication algorithm sections, order by asymmetric
+ * signature algorithm: ECDSA, then RSA, then DSS.
+ * * As a special case, the PSK ciphers, which are only enabled when
+ * TLS 1.3 PSK-resumption is in use, come first.
+ *
+ * Exception: Because some servers ignore the high-order byte of the cipher
+ * suite ID, we must be careful about adding cipher suites with IDs larger
+ * than 0x00ff; see bug 946147. For these broken servers, the first three
+ * cipher suites, with the MSB zeroed, look like:
+ * TLS_RSA_WITH_AES_128_CBC_SHA { 0x00,0x2F }
+ * TLS_RSA_WITH_3DES_EDE_CBC_SHA { 0x00,0x0A }
+ * TLS_RSA_WITH_DES_CBC_SHA { 0x00,0x09 }
+ * The broken server only supports the third and fourth ones and will select
+ * the third one.
+ */
+const PRUint16 SSL_ImplementedCiphers[] = {
+ TLS_AES_128_GCM_SHA256,
+ TLS_CHACHA20_POLY1305_SHA256,
+ TLS_AES_256_GCM_SHA384,
+
+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
+ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
+ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
+ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
+ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
+ /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA must appear before
+ * TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA to work around bug 946147.
+ */
+ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
+ TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
+ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
+ TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
+ TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
+ TLS_ECDHE_RSA_WITH_RC4_128_SHA,
+
+ TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
+ TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
+ TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,
+ TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
+ TLS_DHE_DSS_WITH_AES_256_GCM_SHA384,
+ TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
+ TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
+ TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
+ TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
+ TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
+ TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
+ TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
+ TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
+ TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
+ TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
+ TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
+ TLS_DHE_DSS_WITH_RC4_128_SHA,
+
+ TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
+ TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
+ TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
+ TLS_ECDH_RSA_WITH_RC4_128_SHA,
+
+ TLS_RSA_WITH_AES_128_GCM_SHA256,
+ TLS_RSA_WITH_AES_256_GCM_SHA384,
+ TLS_RSA_WITH_AES_128_CBC_SHA,
+ TLS_RSA_WITH_AES_128_CBC_SHA256,
+ TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
+ TLS_RSA_WITH_AES_256_CBC_SHA,
+ TLS_RSA_WITH_AES_256_CBC_SHA256,
+ TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
+ TLS_RSA_WITH_SEED_CBC_SHA,
+ TLS_RSA_WITH_3DES_EDE_CBC_SHA,
+ TLS_RSA_WITH_RC4_128_SHA,
+ TLS_RSA_WITH_RC4_128_MD5,
+
+ /* 56-bit DES "domestic" cipher suites */
+ TLS_DHE_RSA_WITH_DES_CBC_SHA,
+ TLS_DHE_DSS_WITH_DES_CBC_SHA,
+ TLS_RSA_WITH_DES_CBC_SHA,
+
+ /* ciphersuites with no encryption */
+ TLS_ECDHE_ECDSA_WITH_NULL_SHA,
+ TLS_ECDHE_RSA_WITH_NULL_SHA,
+ TLS_ECDH_RSA_WITH_NULL_SHA,
+ TLS_ECDH_ECDSA_WITH_NULL_SHA,
+ TLS_RSA_WITH_NULL_SHA,
+ TLS_RSA_WITH_NULL_SHA256,
+ TLS_RSA_WITH_NULL_MD5,
+
+ 0
+};
+
+const PRUint16 SSL_NumImplementedCiphers =
+ (sizeof SSL_ImplementedCiphers) / (sizeof SSL_ImplementedCiphers[0]) - 1;
+
+const PRUint16*
+SSL_GetImplementedCiphers(void)
+{
+ return SSL_ImplementedCiphers;
+}
+
+PRUint16
+SSL_GetNumImplementedCiphers(void)
+{
+ return SSL_NumImplementedCiphers;
+}
diff --git a/security/nss/lib/ssl/sslerr.c b/security/nss/lib/ssl/sslerr.c
new file mode 100644
index 0000000000..edb941257d
--- /dev/null
+++ b/security/nss/lib/ssl/sslerr.c
@@ -0,0 +1,41 @@
+/*
+ * Function to set error code only when meaningful error has not already
+ * been set.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "prerror.h"
+#include "secerr.h"
+#include "sslerr.h"
+#include "seccomon.h"
+
+/* look at the current value of PR_GetError, and evaluate it to see
+ * if it is meaningful or meaningless (out of context).
+ * If it is meaningless, replace it with the hiLevelError.
+ * Returns the chosen error value.
+ */
+int
+ssl_MapLowLevelError(int hiLevelError)
+{
+ int oldErr = PORT_GetError();
+
+ switch (oldErr) {
+
+ case 0:
+ case PR_IO_ERROR:
+ case SEC_ERROR_IO:
+ case SEC_ERROR_BAD_DATA:
+ case SEC_ERROR_LIBRARY_FAILURE:
+ case SEC_ERROR_EXTENSION_NOT_FOUND:
+ case SSL_ERROR_BAD_CLIENT:
+ case SSL_ERROR_BAD_SERVER:
+ case SSL_ERROR_SESSION_NOT_FOUND:
+ PORT_SetError(hiLevelError);
+ return hiLevelError;
+
+ default: /* leave the majority of error codes alone. */
+ return oldErr;
+ }
+}
diff --git a/security/nss/lib/ssl/sslerr.h b/security/nss/lib/ssl/sslerr.h
new file mode 100644
index 0000000000..837fca7ba1
--- /dev/null
+++ b/security/nss/lib/ssl/sslerr.h
@@ -0,0 +1,298 @@
+/*
+ * Enumeration of all SSL-specific error codes.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef __SSL_ERR_H_
+#define __SSL_ERR_H_
+
+/* clang-format off */
+
+#define SSL_ERROR_BASE (-0x3000)
+#define SSL_ERROR_LIMIT (SSL_ERROR_BASE + 1000)
+
+#define IS_SSL_ERROR(code) \
+ (((code) >= SSL_ERROR_BASE) && ((code) < SSL_ERROR_LIMIT))
+
+#ifndef NO_SECURITY_ERROR_ENUM
+typedef enum {
+ SSL_ERROR_EXPORT_ONLY_SERVER = (SSL_ERROR_BASE + 0),
+ /* error 0 is obsolete */
+ SSL_ERROR_US_ONLY_SERVER = (SSL_ERROR_BASE + 1),
+ /* error 1 is obsolete */
+ SSL_ERROR_NO_CYPHER_OVERLAP = (SSL_ERROR_BASE + 2),
+ /*
+ * Received an alert reporting what we did wrong. (more alerts below)
+ */
+ SSL_ERROR_NO_CERTIFICATE /*_ALERT */ = (SSL_ERROR_BASE + 3),
+ SSL_ERROR_BAD_CERTIFICATE = (SSL_ERROR_BASE + 4),
+ /* error 4 is obsolete */
+ SSL_ERROR_UNUSED_5 = (SSL_ERROR_BASE + 5),
+ /* error 5 is obsolete */
+ SSL_ERROR_BAD_CLIENT = (SSL_ERROR_BASE + 6),
+ SSL_ERROR_BAD_SERVER = (SSL_ERROR_BASE + 7),
+ SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE = (SSL_ERROR_BASE + 8),
+ /* error 8 is obsolete */
+ SSL_ERROR_UNSUPPORTED_VERSION = (SSL_ERROR_BASE + 9),
+ SSL_ERROR_UNUSED_10 = (SSL_ERROR_BASE + 10),
+ /* error 10 is obsolete */
+ SSL_ERROR_WRONG_CERTIFICATE = (SSL_ERROR_BASE + 11),
+ /* error 11 is obsolete */
+ SSL_ERROR_BAD_CERT_DOMAIN = (SSL_ERROR_BASE + 12),
+ SSL_ERROR_POST_WARNING = (SSL_ERROR_BASE + 13),
+ /* error 13 is obsolete */
+ SSL_ERROR_SSL2_DISABLED = (SSL_ERROR_BASE + 14),
+ /* error 14 is obsolete */
+ SSL_ERROR_BAD_MAC_READ = (SSL_ERROR_BASE + 15),
+ /*
+ * Received an alert reporting what we did wrong.
+ * (two more alerts above, and many more below)
+ */
+ SSL_ERROR_BAD_MAC_ALERT = (SSL_ERROR_BASE + 16),
+ SSL_ERROR_BAD_CERT_ALERT = (SSL_ERROR_BASE + 17),
+ SSL_ERROR_REVOKED_CERT_ALERT = (SSL_ERROR_BASE + 18),
+ SSL_ERROR_EXPIRED_CERT_ALERT = (SSL_ERROR_BASE + 19),
+
+ SSL_ERROR_SSL_DISABLED = (SSL_ERROR_BASE + 20),
+ SSL_ERROR_FORTEZZA_PQG = (SSL_ERROR_BASE + 21),
+ /* error 21 is obsolete */
+ SSL_ERROR_UNKNOWN_CIPHER_SUITE = (SSL_ERROR_BASE + 22),
+ SSL_ERROR_NO_CIPHERS_SUPPORTED = (SSL_ERROR_BASE + 23),
+ SSL_ERROR_BAD_BLOCK_PADDING = (SSL_ERROR_BASE + 24),
+ SSL_ERROR_RX_RECORD_TOO_LONG = (SSL_ERROR_BASE + 25),
+ SSL_ERROR_TX_RECORD_TOO_LONG = (SSL_ERROR_BASE + 26),
+ /*
+ * Received a malformed (too long or short) SSL handshake.
+ */
+ SSL_ERROR_RX_MALFORMED_HELLO_REQUEST = (SSL_ERROR_BASE + 27),
+ SSL_ERROR_RX_MALFORMED_CLIENT_HELLO = (SSL_ERROR_BASE + 28),
+ SSL_ERROR_RX_MALFORMED_SERVER_HELLO = (SSL_ERROR_BASE + 29),
+ SSL_ERROR_RX_MALFORMED_CERTIFICATE = (SSL_ERROR_BASE + 30),
+ SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH = (SSL_ERROR_BASE + 31),
+ SSL_ERROR_RX_MALFORMED_CERT_REQUEST = (SSL_ERROR_BASE + 32),
+ SSL_ERROR_RX_MALFORMED_HELLO_DONE = (SSL_ERROR_BASE + 33),
+ SSL_ERROR_RX_MALFORMED_CERT_VERIFY = (SSL_ERROR_BASE + 34),
+ SSL_ERROR_RX_MALFORMED_CLIENT_KEY_EXCH = (SSL_ERROR_BASE + 35),
+ SSL_ERROR_RX_MALFORMED_FINISHED = (SSL_ERROR_BASE + 36),
+ /*
+ * Received a malformed (too long or short) SSL record.
+ */
+ SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER = (SSL_ERROR_BASE + 37),
+ SSL_ERROR_RX_MALFORMED_ALERT = (SSL_ERROR_BASE + 38),
+ SSL_ERROR_RX_MALFORMED_HANDSHAKE = (SSL_ERROR_BASE + 39),
+ SSL_ERROR_RX_MALFORMED_APPLICATION_DATA = (SSL_ERROR_BASE + 40),
+ /*
+ * Received an SSL handshake that was inappropriate for the state we're in.
+ * E.g. Server received message from server, or wrong state in state machine.
+ */
+ SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST = (SSL_ERROR_BASE + 41),
+ SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO = (SSL_ERROR_BASE + 42),
+ SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO = (SSL_ERROR_BASE + 43),
+ SSL_ERROR_RX_UNEXPECTED_CERTIFICATE = (SSL_ERROR_BASE + 44),
+ SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH = (SSL_ERROR_BASE + 45),
+ SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST = (SSL_ERROR_BASE + 46),
+ SSL_ERROR_RX_UNEXPECTED_HELLO_DONE = (SSL_ERROR_BASE + 47),
+ SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY = (SSL_ERROR_BASE + 48),
+ SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH = (SSL_ERROR_BASE + 49),
+ SSL_ERROR_RX_UNEXPECTED_FINISHED = (SSL_ERROR_BASE + 50),
+ /*
+ * Received an SSL record that was inappropriate for the state we're in.
+ */
+ SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER = (SSL_ERROR_BASE + 51),
+ SSL_ERROR_RX_UNEXPECTED_ALERT = (SSL_ERROR_BASE + 52),
+ SSL_ERROR_RX_UNEXPECTED_HANDSHAKE = (SSL_ERROR_BASE + 53),
+ SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA = (SSL_ERROR_BASE + 54),
+ /*
+ * Received record/message with unknown discriminant.
+ */
+ SSL_ERROR_RX_UNKNOWN_RECORD_TYPE = (SSL_ERROR_BASE + 55),
+ SSL_ERROR_RX_UNKNOWN_HANDSHAKE = (SSL_ERROR_BASE + 56),
+ SSL_ERROR_RX_UNKNOWN_ALERT = (SSL_ERROR_BASE + 57),
+ /*
+ * Received an alert reporting what we did wrong. (more alerts above)
+ */
+ SSL_ERROR_CLOSE_NOTIFY_ALERT = (SSL_ERROR_BASE + 58),
+ SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT = (SSL_ERROR_BASE + 59),
+ SSL_ERROR_DECOMPRESSION_FAILURE_ALERT = (SSL_ERROR_BASE + 60),
+ SSL_ERROR_HANDSHAKE_FAILURE_ALERT = (SSL_ERROR_BASE + 61),
+ SSL_ERROR_ILLEGAL_PARAMETER_ALERT = (SSL_ERROR_BASE + 62),
+ SSL_ERROR_UNSUPPORTED_CERT_ALERT = (SSL_ERROR_BASE + 63),
+ SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT = (SSL_ERROR_BASE + 64),
+
+ SSL_ERROR_GENERATE_RANDOM_FAILURE = (SSL_ERROR_BASE + 65),
+ SSL_ERROR_SIGN_HASHES_FAILURE = (SSL_ERROR_BASE + 66),
+ SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE = (SSL_ERROR_BASE + 67),
+ SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 68),
+ SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 69),
+
+ SSL_ERROR_ENCRYPTION_FAILURE = (SSL_ERROR_BASE + 70),
+ SSL_ERROR_DECRYPTION_FAILURE = (SSL_ERROR_BASE + 71),
+ /* error 71 is obsolete */
+ SSL_ERROR_SOCKET_WRITE_FAILURE = (SSL_ERROR_BASE + 72),
+
+ SSL_ERROR_MD5_DIGEST_FAILURE = (SSL_ERROR_BASE + 73),
+ SSL_ERROR_SHA_DIGEST_FAILURE = (SSL_ERROR_BASE + 74),
+ SSL_ERROR_MAC_COMPUTATION_FAILURE = (SSL_ERROR_BASE + 75),
+ SSL_ERROR_SYM_KEY_CONTEXT_FAILURE = (SSL_ERROR_BASE + 76),
+ SSL_ERROR_SYM_KEY_UNWRAP_FAILURE = (SSL_ERROR_BASE + 77),
+ SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED = (SSL_ERROR_BASE + 78),
+ /* error 78 is obsolete */
+ SSL_ERROR_IV_PARAM_FAILURE = (SSL_ERROR_BASE + 79),
+ SSL_ERROR_INIT_CIPHER_SUITE_FAILURE = (SSL_ERROR_BASE + 80),
+ SSL_ERROR_SESSION_KEY_GEN_FAILURE = (SSL_ERROR_BASE + 81),
+ SSL_ERROR_NO_SERVER_KEY_FOR_ALG = (SSL_ERROR_BASE + 82),
+ SSL_ERROR_TOKEN_INSERTION_REMOVAL = (SSL_ERROR_BASE + 83),
+ SSL_ERROR_TOKEN_SLOT_NOT_FOUND = (SSL_ERROR_BASE + 84),
+ SSL_ERROR_NO_COMPRESSION_OVERLAP = (SSL_ERROR_BASE + 85),
+ SSL_ERROR_HANDSHAKE_NOT_COMPLETED = (SSL_ERROR_BASE + 86),
+ SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE = (SSL_ERROR_BASE + 87),
+ SSL_ERROR_CERT_KEA_MISMATCH = (SSL_ERROR_BASE + 88),
+ SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA = (SSL_ERROR_BASE + 89),
+ /* error 89 is obsolete */
+ SSL_ERROR_SESSION_NOT_FOUND = (SSL_ERROR_BASE + 90),
+
+ SSL_ERROR_DECRYPTION_FAILED_ALERT = (SSL_ERROR_BASE + 91),
+ SSL_ERROR_RECORD_OVERFLOW_ALERT = (SSL_ERROR_BASE + 92),
+ SSL_ERROR_UNKNOWN_CA_ALERT = (SSL_ERROR_BASE + 93),
+ SSL_ERROR_ACCESS_DENIED_ALERT = (SSL_ERROR_BASE + 94),
+ SSL_ERROR_DECODE_ERROR_ALERT = (SSL_ERROR_BASE + 95),
+ SSL_ERROR_DECRYPT_ERROR_ALERT = (SSL_ERROR_BASE + 96),
+ SSL_ERROR_EXPORT_RESTRICTION_ALERT = (SSL_ERROR_BASE + 97),
+ SSL_ERROR_PROTOCOL_VERSION_ALERT = (SSL_ERROR_BASE + 98),
+ SSL_ERROR_INSUFFICIENT_SECURITY_ALERT = (SSL_ERROR_BASE + 99),
+ SSL_ERROR_INTERNAL_ERROR_ALERT = (SSL_ERROR_BASE + 100),
+ SSL_ERROR_USER_CANCELED_ALERT = (SSL_ERROR_BASE + 101),
+ SSL_ERROR_NO_RENEGOTIATION_ALERT = (SSL_ERROR_BASE + 102),
+
+ SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED = (SSL_ERROR_BASE + 103),
+
+ SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT = (SSL_ERROR_BASE + 104),
+ SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT = (SSL_ERROR_BASE + 105),
+ SSL_ERROR_UNRECOGNIZED_NAME_ALERT = (SSL_ERROR_BASE + 106),
+ SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT = (SSL_ERROR_BASE + 107),
+ SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT = (SSL_ERROR_BASE + 108),
+
+ SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 109),
+ SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 110),
+
+ SSL_ERROR_DECOMPRESSION_FAILURE = (SSL_ERROR_BASE + 111),
+ SSL_ERROR_RENEGOTIATION_NOT_ALLOWED = (SSL_ERROR_BASE + 112),
+ SSL_ERROR_UNSAFE_NEGOTIATION = (SSL_ERROR_BASE + 113),
+
+ SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD = (SSL_ERROR_BASE + 114),
+
+ SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY = (SSL_ERROR_BASE + 115),
+
+ SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID = (SSL_ERROR_BASE + 116),
+
+ SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2 = (SSL_ERROR_BASE + 117),
+ /* error 117 is obsolete */
+ SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS = (SSL_ERROR_BASE + 118),
+ SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS = (SSL_ERROR_BASE + 119),
+
+ SSL_ERROR_INVALID_VERSION_RANGE = (SSL_ERROR_BASE + 120),
+ SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION = (SSL_ERROR_BASE + 121),
+
+ SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST = (SSL_ERROR_BASE + 122),
+ SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST = (SSL_ERROR_BASE + 123),
+
+ SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION = (SSL_ERROR_BASE + 124),
+
+ SSL_ERROR_RX_UNEXPECTED_CERT_STATUS = (SSL_ERROR_BASE + 125),
+
+ SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM = (SSL_ERROR_BASE + 126),
+ SSL_ERROR_DIGEST_FAILURE = (SSL_ERROR_BASE + 127),
+ SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 128),
+
+ SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK = (SSL_ERROR_BASE + 129),
+ SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL = (SSL_ERROR_BASE + 130),
+
+ SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT = (SSL_ERROR_BASE + 131),
+
+ SSL_ERROR_WEAK_SERVER_CERT_KEY = (SSL_ERROR_BASE + 132),
+
+ SSL_ERROR_RX_SHORT_DTLS_READ = (SSL_ERROR_BASE + 133),
+
+ SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 134),
+ SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM = (SSL_ERROR_BASE + 135),
+
+ SSL_ERROR_MISSING_EXTENDED_MASTER_SECRET = (SSL_ERROR_BASE + 136),
+ SSL_ERROR_UNEXPECTED_EXTENDED_MASTER_SECRET = (SSL_ERROR_BASE + 137),
+
+ SSL_ERROR_RX_MALFORMED_KEY_SHARE = (SSL_ERROR_BASE + 138),
+ SSL_ERROR_MISSING_KEY_SHARE = (SSL_ERROR_BASE + 139),
+ SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE = (SSL_ERROR_BASE + 140),
+ SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE = (SSL_ERROR_BASE + 141),
+
+ SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS = (SSL_ERROR_BASE + 142),
+ SSL_ERROR_MISSING_EXTENSION_ALERT = (SSL_ERROR_BASE + 143),
+
+ SSL_ERROR_KEY_EXCHANGE_FAILURE = (SSL_ERROR_BASE + 144),
+ SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION = (SSL_ERROR_BASE + 145),
+ SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS = (SSL_ERROR_BASE + 146),
+ SSL_ERROR_MALFORMED_PRE_SHARED_KEY = (SSL_ERROR_BASE + 147),
+ SSL_ERROR_MALFORMED_EARLY_DATA = (SSL_ERROR_BASE + 148),
+ SSL_ERROR_END_OF_EARLY_DATA_ALERT = (SSL_ERROR_BASE + 149),
+ /* error 149 is obsolete */
+ SSL_ERROR_MISSING_ALPN_EXTENSION = (SSL_ERROR_BASE + 150),
+ SSL_ERROR_RX_UNEXPECTED_EXTENSION = (SSL_ERROR_BASE + 151),
+ SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION = (SSL_ERROR_BASE + 152),
+ SSL_ERROR_TOO_MANY_RECORDS = (SSL_ERROR_BASE + 153),
+ SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST = (SSL_ERROR_BASE + 154),
+ SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST = (SSL_ERROR_BASE + 155),
+ SSL_ERROR_BAD_2ND_CLIENT_HELLO = (SSL_ERROR_BASE + 156),
+ SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION = (SSL_ERROR_BASE + 157),
+ SSL_ERROR_MALFORMED_PSK_KEY_EXCHANGE_MODES = (SSL_ERROR_BASE + 158),
+ SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES = (SSL_ERROR_BASE + 159),
+ SSL_ERROR_DOWNGRADE_WITH_EARLY_DATA = (SSL_ERROR_BASE + 160),
+ SSL_ERROR_TOO_MUCH_EARLY_DATA = (SSL_ERROR_BASE + 161),
+ SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA = (SSL_ERROR_BASE + 162),
+ SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA = (SSL_ERROR_BASE + 163),
+
+ SSL_ERROR_UNSUPPORTED_EXPERIMENTAL_API = (SSL_ERROR_BASE + 164),
+
+ SSL_ERROR_APPLICATION_ABORT = (SSL_ERROR_BASE + 165),
+ SSL_ERROR_APP_CALLBACK_ERROR = (SSL_ERROR_BASE + 166),
+ SSL_ERROR_NO_TIMERS_FOUND = (SSL_ERROR_BASE + 167),
+ SSL_ERROR_MISSING_COOKIE_EXTENSION = (SSL_ERROR_BASE + 168),
+
+ SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE = (SSL_ERROR_BASE + 169),
+ SSL_ERROR_RX_MALFORMED_KEY_UPDATE = (SSL_ERROR_BASE + 170),
+ SSL_ERROR_TOO_MANY_KEY_UPDATES = (SSL_ERROR_BASE + 171),
+ SSL_ERROR_HANDSHAKE_FAILED = (SSL_ERROR_BASE + 172),
+ SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR = (SSL_ERROR_BASE + 173),
+ SSL_ERROR_RX_MALFORMED_DTLS_ACK = (SSL_ERROR_BASE + 174),
+ SSL_ERROR_DH_KEY_TOO_LONG = (SSL_ERROR_BASE + 175),
+ SSL_ERROR_RX_MALFORMED_ESNI_KEYS = (SSL_ERROR_BASE + 176),
+ SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION = (SSL_ERROR_BASE + 177),
+ SSL_ERROR_MISSING_ESNI_EXTENSION = (SSL_ERROR_BASE + 178),
+ SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE = (SSL_ERROR_BASE + 179),
+ SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION = (SSL_ERROR_BASE + 180),
+ SSL_ERROR_RX_CERTIFICATE_REQUIRED_ALERT = (SSL_ERROR_BASE + 181),
+ SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH = (SSL_ERROR_BASE + 182),
+ SSL_ERROR_DC_BAD_SIGNATURE = (SSL_ERROR_BASE + 183),
+ SSL_ERROR_DC_INVALID_KEY_USAGE = (SSL_ERROR_BASE + 184),
+ SSL_ERROR_DC_EXPIRED = (SSL_ERROR_BASE + 185),
+ SSL_ERROR_DC_INAPPROPRIATE_VALIDITY_PERIOD = (SSL_ERROR_BASE + 186),
+ SSL_ERROR_FEATURE_DISABLED = (SSL_ERROR_BASE + 187),
+ /* ECH rejected, public name authentication succeeded,
+ * and at least one of the retry_configs is compatible. */
+ SSL_ERROR_ECH_RETRY_WITH_ECH = (SSL_ERROR_BASE + 188),
+ /* ECH rejected, public name authentication succeeded,
+ * but none of the retry_configs are compatible. */
+ SSL_ERROR_ECH_RETRY_WITHOUT_ECH = (SSL_ERROR_BASE + 189),
+ /* ECH rejected and public name authentication failed. */
+ SSL_ERROR_ECH_FAILED = (SSL_ERROR_BASE + 190),
+ SSL_ERROR_ECH_REQUIRED_ALERT = (SSL_ERROR_BASE + 191),
+ SSL_ERROR_END_OF_LIST /* let the c compiler determine the value of this. */
+} SSLErrorCodes;
+
+#define SSL_ERROR_RX_MALFORMED_ECH_CONFIG SSL_ERROR_RX_MALFORMED_ESNI_KEYS
+#define SSL_ERROR_RX_MALFORMED_ECH_EXTENSION SSL_ERROR_RX_MALFORMED_ESNI_EXTENSION
+#define SSL_ERROR_MISSING_ECH_EXTENSION SSL_ERROR_MISSING_ESNI_EXTENSION
+#endif /* NO_SECURITY_ERROR_ENUM */
+
+/* clang-format on */
+
+#endif /* __SSL_ERR_H_ */
diff --git a/security/nss/lib/ssl/sslerrstrs.c b/security/nss/lib/ssl/sslerrstrs.c
new file mode 100644
index 0000000000..4e3db6d73c
--- /dev/null
+++ b/security/nss/lib/ssl/sslerrstrs.c
@@ -0,0 +1,36 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "prerror.h"
+#include "sslerr.h"
+#include "prinit.h"
+#include "nssutil.h"
+#include "ssl.h"
+
+#define ER3(name, value, str) { #name, str },
+
+static const struct PRErrorMessage ssltext[] = {
+#include "SSLerrs.h"
+ { 0, 0 }
+};
+
+static const struct PRErrorTable ssl_et = {
+ ssltext, "sslerr", SSL_ERROR_BASE,
+ (sizeof ssltext) / (sizeof ssltext[0])
+};
+
+static PRStatus
+ssl_InitializePRErrorTableOnce(void)
+{
+ return PR_ErrorInstallTable(&ssl_et);
+}
+
+static PRCallOnceType once;
+
+SECStatus
+ssl_InitializePRErrorTable(void)
+{
+ return (PR_SUCCESS == PR_CallOnce(&once, ssl_InitializePRErrorTableOnce))
+ ? SECSuccess
+ : SECFailure;
+}
diff --git a/security/nss/lib/ssl/sslexp.h b/security/nss/lib/ssl/sslexp.h
new file mode 100644
index 0000000000..6eeafa5029
--- /dev/null
+++ b/security/nss/lib/ssl/sslexp.h
@@ -0,0 +1,1087 @@
+/*
+ * This file contains prototypes for experimental SSL functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslexp_h_
+#define __sslexp_h_
+
+#include "ssl.h"
+#include "sslerr.h"
+#include "pk11hpke.h"
+
+SEC_BEGIN_PROTOS
+
+/* The functions in this header file are not guaranteed to remain available in
+ * future NSS versions. Code that uses these functions needs to safeguard
+ * against the function not being available. */
+
+#define SSL_EXPERIMENTAL_API(name, arglist, args) \
+ (SSL_GetExperimentalAPI(name) \
+ ? ((SECStatus(*) arglist)SSL_GetExperimentalAPI(name))args \
+ : SECFailure)
+#define SSL_DEPRECATED_EXPERIMENTAL_API \
+ (PR_SetError(SSL_ERROR_UNSUPPORTED_EXPERIMENTAL_API, 0), SECFailure)
+
+/*
+ * SSL_GetExtensionSupport() returns whether NSS supports a particular TLS
+ * extension.
+ *
+ * - ssl_ext_none indicates that NSS does not support the extension and
+ * extension hooks can be installed.
+ *
+ * - ssl_ext_native indicates that NSS supports the extension natively, but
+ * allows an application to override that support and install its own
+ * extension hooks.
+ *
+ * - ssl_ext_native_only indicates that NSS supports the extension natively
+ * and does not permit custom extension hooks to be installed. These
+ * extensions are critical to the functioning of NSS.
+ */
+typedef enum {
+ ssl_ext_none,
+ ssl_ext_native,
+ ssl_ext_native_only
+} SSLExtensionSupport;
+
+#define SSL_GetExtensionSupport(extension, support) \
+ SSL_EXPERIMENTAL_API("SSL_GetExtensionSupport", \
+ (PRUint16 _extension, \
+ SSLExtensionSupport * _support), \
+ (extension, support))
+
+/*
+ * Custom extension hooks.
+ *
+ * The SSL_InstallExtensionHooks() registers two callback functions for use
+ * with the identified extension type.
+ *
+ * Installing extension hooks disables the checks in TLS 1.3 that ensure that
+ * extensions are only added to the correct messages. The application is
+ * responsible for ensuring that extensions are only sent with the right message
+ * or messages.
+ *
+ * Installing an extension handler does not disable checks for whether an
+ * extension can be used in a message that is a response to an extension in
+ * another message. Extensions in ServerHello, EncryptedExtensions and the
+ * server Certificate messages are rejected unless the client sends an extension
+ * in the ClientHello. Similarly, a client Certificate message cannot contain
+ * extensions that don't appear in a CertificateRequest (in TLS 1.3).
+ *
+ * Setting both |writer| and |handler| to NULL removes any existing hooks for
+ * that extension.
+ *
+ * == SSLExtensionWriter
+ *
+ * An SSLExtensionWriter function is responsible for constructing the contents
+ * of an extension. This function is called during the construction of all
+ * handshake messages where an extension might be included.
+ *
+ * - The |fd| argument is the socket file descriptor.
+ *
+ * - The |message| argument is the TLS handshake message type. The writer will
+ * be called for every handshake message that NSS sends. Most extensions
+ * should only be sent in a subset of messages. NSS doesn’t check that
+ * extension writers don’t violate protocol rules regarding which message an
+ * extension can be sent in.
+ *
+ * - The |data| argument is a pointer to a buffer that should be written to with
+ * any data for the extension.
+ *
+ * - The |len| argument is an outparam indicating how many bytes were written to
+ * |data|. The value referenced by |len| is initialized to zero, so an
+ * extension that is empty does not need to write to this value.
+ *
+ * - The |maxLen| indicates the maximum number of bytes that can be written to
+ * |data|.
+ *
+ * - The |arg| argument is the value of the writerArg that was passed during
+ * installation.
+ *
+ * An SSLExtensionWriter function returns PR_TRUE if an extension should be
+ * written, and PR_FALSE otherwise.
+ *
+ * If there is an error, return PR_FALSE; if the error is truly fatal, the
+ * application can mark the connection as failed. However, recursively calling
+ * functions that alter the file descriptor in the callback - such as PR_Close()
+ * - should be avoided.
+ *
+ * Note: The ClientHello message can be sent twice in TLS 1.3. An
+ * SSLExtensionWriter will be called twice with the same arguments in that case;
+ * NSS does not distinguish between a first and second ClientHello. It is up to
+ * the application to track this if it needs to act differently each time. In
+ * most cases the correct behaviour is to provide an identical extension on each
+ * invocation.
+ *
+ * == SSLExtensionHandler
+ *
+ * An SSLExtensionHandler function consumes a handshake message. This function
+ * is called when an extension is present.
+ *
+ * - The |fd| argument is the socket file descriptor.
+ *
+ * - The |message| argument is the TLS handshake message type. This can be used
+ * to validate that the extension was included in the correct handshake
+ * message.
+ *
+ * - The |data| argument points to the contents of the extension.
+ *
+ * - The |len| argument contains the length of the extension.
+ *
+ * - The |alert| argument is an outparam that allows an application to choose
+ * which alert is sent in the case of a fatal error.
+ *
+ * - The |arg| argument is the value of the handlerArg that was passed during
+ * installation.
+ *
+ * An SSLExtensionHandler function returns SECSuccess when the extension is
+ * process successfully. It can return SECFailure to cause the handshake to
+ * fail. If the value of alert is written to, NSS will generate a fatal alert
+ * using the provided alert code. The value of |alert| is otherwise not used.
+ */
+typedef PRBool(PR_CALLBACK *SSLExtensionWriter)(
+ PRFileDesc *fd, SSLHandshakeType message,
+ PRUint8 *data, unsigned int *len, unsigned int maxLen, void *arg);
+
+typedef SECStatus(PR_CALLBACK *SSLExtensionHandler)(
+ PRFileDesc *fd, SSLHandshakeType message,
+ const PRUint8 *data, unsigned int len,
+ SSLAlertDescription *alert, void *arg);
+
+#define SSL_InstallExtensionHooks(fd, extension, writer, writerArg, \
+ handler, handlerArg) \
+ SSL_EXPERIMENTAL_API("SSL_InstallExtensionHooks", \
+ (PRFileDesc * _fd, PRUint16 _extension, \
+ SSLExtensionWriter _writer, void *_writerArg, \
+ SSLExtensionHandler _handler, void *_handlerArg), \
+ (fd, extension, writer, writerArg, \
+ handler, handlerArg))
+
+/*
+ * Create an anti-replay context for supporting 0-RTT in TLS 1.3 on servers.
+ *
+ * To use 0-RTT on a server, you must create an anti-replay context using
+ * SSL_CreateAntiReplayContext and set that on the socket with
+ * SSL_SetAntiReplayContext. Failing to set a context on the server will result
+ * in all 0-RTT being rejected. Connections will complete, but early data will
+ * be rejected.
+ *
+ * Anti-replay contexts are reference counted and are released with
+ * SSL_ReleaseAntiReplayContext.
+ *
+ * NSS uses a Bloom filter to track the ClientHello messages that it receives
+ * (specifically, it uses the PSK binder). This function initializes a pair of
+ * Bloom filters. The two filters are alternated over time, with new
+ * ClientHello messages recorded in the current filter and, if they are not
+ * already present, being checked against the previous filter. If the
+ * ClientHello is found, then early data is rejected, but the handshake is
+ * allowed to proceed.
+ *
+ * The false-positive probability of Bloom filters means that some valid
+ * handshakes will be marked as potential replays. Early data will be rejected
+ * for a false positive. To minimize this and to allow a trade-off of space
+ * against accuracy, the size of the Bloom filter can be set by this function.
+ *
+ * The first tuning parameter to consider is |window|, which determines the
+ * window over which ClientHello messages will be tracked. This also causes
+ * early data to be rejected if a ClientHello contains a ticket age parameter
+ * that is outside of this window (see Section 8.3 of RFC 8446 for details).
+ * Set |window| to account for any potential sources of clock error. |window|
+ * is the entire width of the window, which is symmetrical. Therefore to allow
+ * 5 seconds of clock error in both directions, set the value to 10 seconds
+ * (i.e., 10 * PR_USEC_PER_SEC).
+ *
+ * After calling this function, early data will be rejected until |window|
+ * elapses. This prevents replay across crashes and restarts. Only call this
+ * function once to avoid inadvertently disabling 0-RTT (use PR_CallOnce() to
+ * avoid this problem).
+ *
+ * The primary tuning parameter is |bits| which determines the amount of memory
+ * allocated to each Bloom filter. NSS will allocate two Bloom filters, each
+ * |2^(bits - 3)| octets in size. The value of |bits| is primarily driven by
+ * the number of connections that are expected in any time window. Note that
+ * this needs to account for there being two filters both of which have
+ * (presumably) independent false positive rates. The following formulae can be
+ * used to find a value of |bits| and |k| given a chosen false positive
+ * probability |p| and the number of requests expected in a given window |n|:
+ *
+ * bits = log2(n) + log2(-ln(1 - sqrt(1 - p))) + 1.0575327458897952
+ * k = -log2(p)
+ *
+ * ... where log2 and ln are base 2 and e logarithms respectively. For a target
+ * false positive rate of 1% and 1000 handshake attempts, this produces bits=14
+ * and k=7. This results in two Bloom filters that are 2kB each in size. Note
+ * that rounding |k| and |bits| up causes the false positive probability for
+ * these values to be a much lower 0.123%.
+ *
+ * IMPORTANT: This anti-replay scheme has several weaknesses. See the TLS 1.3
+ * specification for the details of the generic problems with this technique.
+ *
+ * In addition to the generic anti-replay weaknesses, the state that the server
+ * maintains is in local memory only. Servers that operate in a cluster, even
+ * those that use shared memory for tickets, will not share anti-replay state.
+ * Early data can be replayed at least once with every server instance that will
+ * accept tickets that are encrypted with the same key.
+ */
+typedef struct SSLAntiReplayContextStr SSLAntiReplayContext;
+#define SSL_CreateAntiReplayContext(now, window, k, bits, ctx) \
+ SSL_EXPERIMENTAL_API("SSL_CreateAntiReplayContext", \
+ (PRTime _now, PRTime _window, \
+ unsigned int _k, unsigned int _bits, \
+ SSLAntiReplayContext **_ctx), \
+ (now, window, k, bits, ctx))
+
+#define SSL_SetAntiReplayContext(fd, ctx) \
+ SSL_EXPERIMENTAL_API("SSL_SetAntiReplayContext", \
+ (PRFileDesc * _fd, SSLAntiReplayContext * _ctx), \
+ (fd, ctx))
+
+#define SSL_ReleaseAntiReplayContext(ctx) \
+ SSL_EXPERIMENTAL_API("SSL_ReleaseAntiReplayContext", \
+ (SSLAntiReplayContext * _ctx), \
+ (ctx))
+
+/*
+ * This function allows a server application to generate a session ticket that
+ * will embed the provided token.
+ *
+ * This function will cause a NewSessionTicket message to be sent by a server.
+ * This happens even if SSL_ENABLE_SESSION_TICKETS is disabled. This allows a
+ * server to suppress the usually automatic generation of a session ticket at
+ * the completion of the handshake - which do not include any token - and to
+ * control when session tickets are transmitted.
+ *
+ * This function will fail unless the socket has an active TLS 1.3 session.
+ * Earlier versions of TLS do not support the spontaneous sending of the
+ * NewSessionTicket message. It will also fail when external PSK
+ * authentication has been negotiated.
+ */
+#define SSL_SendSessionTicket(fd, appToken, appTokenLen) \
+ SSL_EXPERIMENTAL_API("SSL_SendSessionTicket", \
+ (PRFileDesc * _fd, const PRUint8 *_appToken, \
+ unsigned int _appTokenLen), \
+ (fd, appToken, appTokenLen))
+
+/*
+ * A stateless retry handler gives an application some control over NSS handling
+ * of ClientHello messages.
+ *
+ * SSL_HelloRetryRequestCallback() installs a callback that allows an
+ * application to control how NSS sends HelloRetryRequest messages. This
+ * handler is only used on servers and will only be called if the server selects
+ * TLS 1.3. Support for older TLS versions could be added in other releases.
+ *
+ * The SSLHelloRetryRequestCallback is invoked during the processing of a
+ * TLS 1.3 ClientHello message. It takes the following arguments:
+ *
+ * - |firstHello| indicates if the NSS believes that this is an initial
+ * ClientHello. An initial ClientHello will never include a cookie extension,
+ * though it may contain a session ticket.
+ *
+ * - |clientToken| includes a token previously provided by the application. If
+ * |clientTokenLen| is 0, then |clientToken| may be NULL.
+ *
+ * - If |firstHello| is PR_FALSE, the value that was provided in the
+ * |retryToken| outparam of previous invocations of this callback will be
+ * present here.
+ *
+ * - If |firstHello| is PR_TRUE, and the handshake is resuming a session, then
+ * this will contain any value that was passed in the |token| parameter of
+ * SSL_SendNewSessionTicket() method (see below). If this is not resuming a
+ * session, then the token will be empty (and this value could be NULL).
+ *
+ * - |clientTokenLen| is the length of |clientToken|.
+ *
+ * - |retryToken| is an item that callback can write to. This provides NSS with
+ * a token. This token is encrypted and integrity protected and embedded in
+ * the cookie extension of a HelloRetryRequest. The value of this field is
+ * only used if the handler returns ssl_stateless_retry_check. NSS allocates
+ * space for this value.
+ *
+ * - |retryTokenLen| is an outparam for the length of the token. If this value
+ * is not set, or set to 0, an empty token will be sent.
+ *
+ * - |retryTokenMax| is the size of the space allocated for retryToken. An
+ * application cannot write more than this many bytes to retryToken.
+ *
+ * - |arg| is the same value that was passed to
+ * SSL_InstallStatelessRetryHandler().
+ *
+ * The handler can validate any the value of |clientToken|, query the socket
+ * status (using SSL_GetPreliminaryChannelInfo() for example) and decide how to
+ * proceed:
+ *
+ * - Returning ssl_hello_retry_fail causes the handshake to fail. This might be
+ * used if the token is invalid or the application wishes to abort the
+ * handshake.
+ *
+ * - Returning ssl_hello_retry_accept causes the handshake to proceed.
+ *
+ * - Returning ssl_hello_retry_request causes NSS to send a HelloRetryRequest
+ * message and request a second ClientHello. NSS generates a cookie extension
+ * and embeds the value of |retryToken|. The value of |retryToken| value may
+ * be left empty if the application does not require any additional context to
+ * validate a second ClientHello attempt. This return code cannot be used to
+ * reject a second ClientHello (i.e., when firstHello is PR_FALSE); NSS will
+ * abort the handshake if this value is returned from a second call.
+ *
+ * - Returning ssl_hello_retry_reject_0rtt causes NSS to proceed normally, but
+ * to reject 0-RTT. Use this if there is something in the token that
+ * indicates that 0-RTT might be unsafe.
+ *
+ * An application that chooses to perform a stateless retry can discard the
+ * server socket. All necessary state to continue the TLS handshake will be
+ * included in the cookie extension. This makes it possible to use a new socket
+ * to handle the remainder of the handshake. The existing socket can be safely
+ * discarded.
+ *
+ * If the same socket is retained, the information in the cookie will be checked
+ * for consistency against the existing state of the socket. Any discrepancy
+ * will result in the connection being closed.
+ *
+ * Tokens should be kept as small as possible. NSS sets a limit on the size of
+ * tokens, which it passes in |retryTokenMax|. Depending on circumstances,
+ * observing a smaller limit might be desirable or even necessary. For
+ * instance, having HelloRetryRequest and ClientHello fit in a single packet has
+ * significant performance benefits.
+ */
+typedef enum {
+ ssl_hello_retry_fail,
+ ssl_hello_retry_accept,
+ ssl_hello_retry_request,
+ ssl_hello_retry_reject_0rtt
+} SSLHelloRetryRequestAction;
+
+typedef SSLHelloRetryRequestAction(PR_CALLBACK *SSLHelloRetryRequestCallback)(
+ PRBool firstHello, const PRUint8 *clientToken, unsigned int clientTokenLen,
+ PRUint8 *retryToken, unsigned int *retryTokenLen, unsigned int retryTokMax,
+ void *arg);
+
+#define SSL_HelloRetryRequestCallback(fd, cb, arg) \
+ SSL_EXPERIMENTAL_API("SSL_HelloRetryRequestCallback", \
+ (PRFileDesc * _fd, \
+ SSLHelloRetryRequestCallback _cb, void *_arg), \
+ (fd, cb, arg))
+
+/* Update traffic keys (TLS 1.3 only).
+ *
+ * The |requestUpdate| flag determines whether to request an update from the
+ * remote peer.
+ */
+#define SSL_KeyUpdate(fd, requestUpdate) \
+ SSL_EXPERIMENTAL_API("SSL_KeyUpdate", \
+ (PRFileDesc * _fd, PRBool _requestUpdate), \
+ (fd, requestUpdate))
+
+/* This function allows a server application to trigger
+ * re-authentication (TLS 1.3 only) after handshake.
+ *
+ * This function will cause a CertificateRequest message to be sent by
+ * a server. This can be called once at a time, and is not allowed
+ * until an answer is received.
+ *
+ * This function is not allowed for use with DTLS or when external
+ * PSK authentication has been negotiated. SECFailure is returned
+ * in both cases.
+ *
+ * The AuthCertificateCallback is called when the answer is received.
+ * If the answer is accepted by the server, the value returned by
+ * SSL_PeerCertificate() is replaced. If you need to remember all the
+ * certificates, you will need to call SSL_PeerCertificate() and save
+ * what you get before calling this.
+ *
+ * If the AuthCertificateCallback returns SECFailure, the connection
+ * is aborted.
+ */
+#define SSL_SendCertificateRequest(fd) \
+ SSL_EXPERIMENTAL_API("SSL_SendCertificateRequest", \
+ (PRFileDesc * _fd), \
+ (fd))
+
+/*
+ * Session cache API.
+ */
+
+/*
+ * Information that can be retrieved about a resumption token.
+ * See SSL_GetResumptionTokenInfo for details about how to use this API.
+ * Note that peerCert points to a certificate in the NSS database and must be
+ * copied by the application if it should be used after NSS shutdown or after
+ * calling SSL_DestroyResumptionTokenInfo.
+ */
+typedef struct SSLResumptionTokenInfoStr {
+ PRUint16 length;
+ CERTCertificate *peerCert;
+ PRUint8 *alpnSelection;
+ PRUint32 alpnSelectionLen;
+ PRUint32 maxEarlyDataSize;
+ PRTime expirationTime; /* added in NSS 3.41 */
+} SSLResumptionTokenInfo;
+
+/*
+ * Allows applications to retrieve information about a resumption token.
+ * This does not require a TLS session.
+ *
+ * - The |tokenData| argument is a pointer to the resumption token as byte array
+ * of length |tokenLen|.
+ * - The |token| argument is a pointer to a SSLResumptionTokenInfo struct of
+ * of |len|. The struct gets filled by this function.
+ * See SSL_DestroyResumptionTokenInfo for information about how to manage the
+ * |token| memory.
+ */
+#define SSL_GetResumptionTokenInfo(tokenData, tokenLen, token, len) \
+ SSL_EXPERIMENTAL_API("SSL_GetResumptionTokenInfo", \
+ (const PRUint8 *_tokenData, unsigned int _tokenLen, \
+ SSLResumptionTokenInfo *_token, PRUintn _len), \
+ (tokenData, tokenLen, token, len))
+
+/*
+ * SSL_GetResumptionTokenInfo allocates memory in order to populate |tokenInfo|.
+ * Any SSLResumptionTokenInfo struct filled with SSL_GetResumptionTokenInfo
+ * has to be freed with SSL_DestroyResumptionTokenInfo.
+ */
+#define SSL_DestroyResumptionTokenInfo(tokenInfo) \
+ SSL_EXPERIMENTAL_API( \
+ "SSL_DestroyResumptionTokenInfo", \
+ (SSLResumptionTokenInfo * _tokenInfo), \
+ (tokenInfo))
+
+/*
+ * This is the function signature for function pointers used as resumption
+ * token callback. The caller has to copy the memory at |resumptionToken| with
+ * length |len| before returning.
+ *
+ * - The |fd| argument is the socket file descriptor.
+ * - The |resumptionToken| is a pointer to the resumption token as byte array
+ * of length |len|.
+ * - The |ctx| is a void pointer to the context set by the application in
+ * SSL_SetResumptionTokenCallback.
+ */
+typedef SECStatus(PR_CALLBACK *SSLResumptionTokenCallback)(
+ PRFileDesc *fd, const PRUint8 *resumptionToken, unsigned int len,
+ void *ctx);
+
+/*
+ * This allows setting a callback for external session caches to store
+ * resumption tokens.
+ *
+ * - The |fd| argument is the socket file descriptor.
+ * - The |cb| is a function pointer to an implementation of
+ * SSLResumptionTokenCallback.
+ * - The |ctx| is a pointer to some application specific context, which is
+ * returned when |cb| is called.
+ */
+#define SSL_SetResumptionTokenCallback(fd, cb, ctx) \
+ SSL_EXPERIMENTAL_API( \
+ "SSL_SetResumptionTokenCallback", \
+ (PRFileDesc * _fd, SSLResumptionTokenCallback _cb, void *_ctx), \
+ (fd, cb, ctx))
+
+/*
+ * This allows setting a resumption token for a session.
+ * The function returns SECSuccess iff the resumption token can be used,
+ * SECFailure in any other case. The caller should remove the |token| from its
+ * cache when the function returns SECFailure.
+ *
+ * - The |fd| argument is the socket file descriptor.
+ * - The |token| is a pointer to the resumption token as byte array
+ * of length |len|.
+ */
+#define SSL_SetResumptionToken(fd, token, len) \
+ SSL_EXPERIMENTAL_API( \
+ "SSL_SetResumptionToken", \
+ (PRFileDesc * _fd, const PRUint8 *_token, const unsigned int _len), \
+ (fd, token, len))
+
+/* TLS 1.3 allows a server to set a limit on the number of bytes of early data
+ * that can be received. This allows that limit to be set. This function has no
+ * effect on a client. */
+#define SSL_SetMaxEarlyDataSize(fd, size) \
+ SSL_EXPERIMENTAL_API("SSL_SetMaxEarlyDataSize", \
+ (PRFileDesc * _fd, PRUint32 _size), \
+ (fd, size))
+
+/* Client:
+ * If |enabled|, a GREASE ECH extension will be sent in every ClientHello,
+ * unless a valid and supported ECHConfig is configured to the socket
+ * (in which case real ECH takes precedence). If |!enabled|, it is not sent.
+ *
+ * Server:
+ * If |enabled|, a GREASE ECH extensions will be sent in every HelloRetryRequest,
+ * provided that the corresponding ClientHello contained an ECH extension. If ECH
+ * is enabled, the real ECH HRR extension takes precedence.
+ */
+#define SSL_EnableTls13GreaseEch(fd, enabled) \
+ SSL_EXPERIMENTAL_API("SSL_EnableTls13GreaseEch", \
+ (PRFileDesc * _fd, PRBool _enabled), (fd, enabled))
+
+/*
+ * Client:
+ * When sending a GREASE ECH extension in a ClientHello, pad it as though the
+ * hypothetical ECHConfig had |maximum_name_length| equal to |size|. |size| may
+ * vary between 1 and 255 and defaults to 100.
+ *
+ * Server:
+ * Has no effect.
+ */
+#define SSL_SetTls13GreaseEchSize(fd, size) \
+ SSL_EXPERIMENTAL_API("SSL_SetTls13GreaseEchSize", \
+ (PRFileDesc * _fd, PRUint8 _size), (fd, size))
+
+/* If |enabled|, a server receiving a Client Hello containing an encrypted_client_hello
+ * of type inner will respond with the ECH
+ * acceptance signal. This signals the client to continue with the inner
+ * transcript rather than outer. */
+#define SSL_EnableTls13BackendEch(fd, enabled) \
+ SSL_EXPERIMENTAL_API("SSL_EnableTls13BackendEch", \
+ (PRFileDesc * _fd, PRBool _enabled), (fd, enabled))
+
+/* This allows an extension writer to supply different values for inner and
+ * outer ClientHello when using encrypted ClientHello.
+ *
+ * When enabled, each extension writer can be called more than once for the same
+ * message; it must provide the same response when called for the same message
+ * type. When calling the writer to construct the outer ClientHello, the
+ * function will be called with ssl_hs_ech_outer_client_hello as the message
+ * type (a value from outside the range of valid TLS handshake messages).
+ *
+ * When disabled, the extension writer is called once for the outer ClientHello
+ * and the value is copied to the inner ClientHello.
+ *
+ * Enabling this affects all extension writers. The order in which extension
+ * writers are added is also important. Any extension writer that writes
+ * different values for inner and outer ClientHello will prevent later
+ * extensions from being compressed.
+ */
+#define SSL_CallExtensionWriterOnEchInner(fd, enabled) \
+ SSL_EXPERIMENTAL_API("SSL_CallExtensionWriterOnEchInner", \
+ (PRFileDesc * _fd, PRBool _enabled), (fd, enabled))
+
+/* Called by the client after an initial ECH connection fails with
+ * SSL_ERROR_ECH_RETRY_WITH_ECH. Returns compatible ECHConfigs, which
+ * are configured via SetClientEchConfigs for an ECH retry attempt.
+ * These configs MUST NOT be used for more than the single retry
+ * attempt. Subsequent connections MUST use advertised ECHConfigs. */
+#define SSL_GetEchRetryConfigs(fd, out) \
+ SSL_EXPERIMENTAL_API("SSL_GetEchRetryConfigs", \
+ (PRFileDesc * _fd, \
+ SECItem * _out), \
+ (fd, out))
+
+/* Called to remove all ECHConfigs from a socket (fd). */
+#define SSL_RemoveEchConfigs(fd) \
+ SSL_EXPERIMENTAL_API("SSL_RemoveEchConfigs", \
+ (PRFileDesc * _fd), \
+ (fd))
+
+/* Set the ECHConfig and key pair on a socket (server side)
+ *
+ * fd -- the socket
+ * pubKey -- the server's SECKEYPublicKey for HPKE/ECH.
+ * privateKey -- the server's SECKEYPrivateKey for HPKE/ECH.
+ * record/recordLen -- the encoded DNS record (not base64)
+ */
+#define SSL_SetServerEchConfigs(fd, pubKey, \
+ privKey, record, recordLen) \
+ SSL_EXPERIMENTAL_API("SSL_SetServerEchConfigs", \
+ (PRFileDesc * _fd, \
+ const SECKEYPublicKey *_pubKey, \
+ const SECKEYPrivateKey *_privKey, \
+ const PRUint8 *_record, unsigned int _recordLen), \
+ (fd, pubKey, privKey, \
+ record, recordLen))
+
+/* Set ECHConfig(s) on a client. The first supported ECHConfig will be used.
+ *
+ * fd -- the socket
+ * echConfigs/echConfigsLen -- the ECHConfigs structure (not base64)
+ */
+#define SSL_SetClientEchConfigs(fd, echConfigs, echConfigsLen) \
+ SSL_EXPERIMENTAL_API("SSL_SetClientEchConfigs", \
+ (PRFileDesc * _fd, \
+ const PRUint8 *_echConfigs, \
+ unsigned int _echConfigsLen), \
+ (fd, echConfigs, echConfigsLen))
+
+/*
+ * Generate an encoded ECHConfig structure (presumably server side).
+ *
+ * configId -- an identifier for the configuration.
+ * publicName -- the public_name value to be placed in SNI.
+ * maxNameLen -- the maximum length of protected names
+ * kemId -- the HKPE KEM ID value
+ * pubKey -- the public key for the key pair
+ * hpkeSuites -- the HPKE cipher suites that can be used
+ * hpkeSuitesCount -- the number of suites in hpkeSuites
+ * out/outlen/maxlen -- where to output the data
+ */
+typedef struct HpkeSymmetricSuiteStr {
+ HpkeKdfId kdfId;
+ HpkeAeadId aeadId;
+} HpkeSymmetricSuite;
+#define SSL_EncodeEchConfigId(configId, publicName, maxNameLen, \
+ kemId, pubKey, hpkeSuites, hpkeSuiteCount, \
+ out, outlen, maxlen) \
+ SSL_EXPERIMENTAL_API("SSL_EncodeEchConfigId", \
+ (PRUint8 _configId, const char *_publicName, \
+ unsigned int _maxNameLen, HpkeKemId _kemId, \
+ const SECKEYPublicKey *_pubKey, \
+ const HpkeSymmetricSuite *_hpkeSuites, \
+ unsigned int _hpkeSuiteCount, \
+ PRUint8 *_out, unsigned int *_outlen, \
+ unsigned int _maxlen), \
+ (configId, publicName, maxNameLen, \
+ kemId, pubKey, hpkeSuites, hpkeSuiteCount, \
+ out, outlen, maxlen))
+
+/* SSL_SetSecretCallback installs a callback that TLS calls when it installs new
+ * traffic secrets.
+ *
+ * SSLSecretCallback is called with the current epoch and the corresponding
+ * secret; this matches the epoch used in DTLS 1.3, even if the socket is
+ * operating in stream mode:
+ *
+ * - client_early_traffic_secret corresponds to epoch 1
+ * - {client|server}_handshake_traffic_secret is epoch 2
+ * - {client|server}_application_traffic_secret_{N} is epoch 3+N
+ *
+ * The callback is invoked separately for read secrets (client secrets on the
+ * server; server secrets on the client), and write secrets.
+ *
+ * This callback is only called if (D)TLS 1.3 is negotiated.
+ */
+typedef void(PR_CALLBACK *SSLSecretCallback)(
+ PRFileDesc *fd, PRUint16 epoch, SSLSecretDirection dir, PK11SymKey *secret,
+ void *arg);
+
+#define SSL_SecretCallback(fd, cb, arg) \
+ SSL_EXPERIMENTAL_API("SSL_SecretCallback", \
+ (PRFileDesc * _fd, SSLSecretCallback _cb, void *_arg), \
+ (fd, cb, arg))
+
+/* SSL_RecordLayerWriteCallback() is used to replace the TLS record layer. This
+ * function installs a callback that TLS calls when it would otherwise encrypt
+ * and write a record to the underlying NSPR IO layer. The application is
+ * responsible for ensuring that these records are encrypted and written.
+ *
+ * Calling this API also disables reads from the underlying NSPR layer. The
+ * application is expected to push data when it is available using
+ * SSL_RecordLayerData().
+ *
+ * When data would be written, the provided SSLRecordWriteCallback with the
+ * epoch, TLS content type, and the data. The data provided to the callback is
+ * not split into record-sized writes. If the callback returns SECFailure, the
+ * write will be considered to have failed; in particular, PR_WOULD_BLOCK_ERROR
+ * is not handled specially.
+ *
+ * If TLS 1.3 is in use, the epoch indicates the expected level of protection
+ * that the record would receive, this matches that used in DTLS 1.3:
+ *
+ * - epoch 0 corresponds to no record protection
+ * - epoch 1 corresponds to 0-RTT
+ * - epoch 2 corresponds to TLS handshake
+ * - epoch 3 and higher are application data
+ *
+ * Prior versions of TLS use epoch 1 and higher for application data.
+ *
+ * This API is not supported for DTLS.
+ */
+typedef SECStatus(PR_CALLBACK *SSLRecordWriteCallback)(
+ PRFileDesc *fd, PRUint16 epoch, SSLContentType contentType,
+ const PRUint8 *data, unsigned int len, void *arg);
+
+#define SSL_RecordLayerWriteCallback(fd, writeCb, arg) \
+ SSL_EXPERIMENTAL_API("SSL_RecordLayerWriteCallback", \
+ (PRFileDesc * _fd, SSLRecordWriteCallback _wCb, \
+ void *_arg), \
+ (fd, writeCb, arg))
+
+/* SSL_RecordLayerData() is used to provide new data to TLS. The application
+ * indicates the epoch (see the description of SSL_RecordLayerWriteCallback()),
+ * content type, and the data that was received. The application is responsible
+ * for removing any encryption or other protection before passing data to this
+ * function.
+ *
+ * This returns SECSuccess if the data was successfully processed. If this
+ * function is used to drive the handshake and the caller needs to know when the
+ * handshake is complete, a call to SSL_ForceHandshake will return SECSuccess
+ * when the handshake is complete.
+ *
+ * This API is not supported for DTLS sockets.
+ */
+#define SSL_RecordLayerData(fd, epoch, ct, data, len) \
+ SSL_EXPERIMENTAL_API("SSL_RecordLayerData", \
+ (PRFileDesc * _fd, PRUint16 _epoch, \
+ SSLContentType _contentType, \
+ const PRUint8 *_data, unsigned int _len), \
+ (fd, epoch, ct, data, len))
+
+/*
+ * SSL_GetCurrentEpoch() returns the read and write epochs that the socket is
+ * currently using. NULL values for readEpoch or writeEpoch are ignored.
+ *
+ * See SSL_RecordLayerWriteCallback() for details on epochs.
+ */
+#define SSL_GetCurrentEpoch(fd, readEpoch, writeEpoch) \
+ SSL_EXPERIMENTAL_API("SSL_GetCurrentEpoch", \
+ (PRFileDesc * _fd, PRUint16 * _readEpoch, \
+ PRUint16 * _writeEpoch), \
+ (fd, readEpoch, writeEpoch))
+
+/*
+ * The following AEAD functions expose an AEAD primitive that uses a ciphersuite
+ * to set parameters. The ciphersuite determines the Hash function used by
+ * HKDF, the AEAD function, and the size of key and IV. This is only supported
+ * for TLS 1.3.
+ *
+ * The key and IV are generated using the TLS KDF with a custom label. That is
+ * HKDF-Expand-Label(secret, labelPrefix + " key" or " iv", "", L).
+ *
+ * The encrypt and decrypt functions use a nonce construction identical to that
+ * used in TLS. The lower bits of the IV are XORed with the 64-bit counter to
+ * produce the nonce. Otherwise, this is an AEAD interface similar to that
+ * described in RFC 5116.
+ *
+ * Note: SSL_MakeAead internally calls SSL_MakeVariantAead with a variant of
+ * "stream", behaving as noted above. If "datagram" variant is passed instead,
+ * the Label prefix used in HKDF-Expand is "dtls13" instead of "tls13 ". See
+ * 7.1 of RFC 8446 and draft-ietf-tls-dtls13-34. */
+typedef struct SSLAeadContextStr SSLAeadContext;
+
+#define SSL_MakeAead(version, cipherSuite, secret, \
+ labelPrefix, labelPrefixLen, ctx) \
+ SSL_EXPERIMENTAL_API("SSL_MakeAead", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _secret, \
+ const char *_labelPrefix, \
+ unsigned int _labelPrefixLen, \
+ SSLAeadContext **_ctx), \
+ (version, cipherSuite, secret, \
+ labelPrefix, labelPrefixLen, ctx))
+
+#define SSL_MakeVariantAead(version, cipherSuite, variant, secret, \
+ labelPrefix, labelPrefixLen, ctx) \
+ SSL_EXPERIMENTAL_API("SSL_MakeVariantAead", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ SSLProtocolVariant _variant, \
+ PK11SymKey * _secret, \
+ const char *_labelPrefix, \
+ unsigned int _labelPrefixLen, \
+ SSLAeadContext **_ctx), \
+ (version, cipherSuite, variant, secret, \
+ labelPrefix, labelPrefixLen, ctx))
+
+#define SSL_AeadEncrypt(ctx, counter, aad, aadLen, in, inLen, \
+ output, outputLen, maxOutputLen) \
+ SSL_EXPERIMENTAL_API("SSL_AeadEncrypt", \
+ (const SSLAeadContext *_ctx, PRUint64 _counter, \
+ const PRUint8 *_aad, unsigned int _aadLen, \
+ const PRUint8 *_in, unsigned int _inLen, \
+ PRUint8 *_out, unsigned int *_outLen, \
+ unsigned int _maxOut), \
+ (ctx, counter, aad, aadLen, in, inLen, \
+ output, outputLen, maxOutputLen))
+
+#define SSL_AeadDecrypt(ctx, counter, aad, aadLen, in, inLen, \
+ output, outputLen, maxOutputLen) \
+ SSL_EXPERIMENTAL_API("SSL_AeadDecrypt", \
+ (const SSLAeadContext *_ctx, PRUint64 _counter, \
+ const PRUint8 *_aad, unsigned int _aadLen, \
+ const PRUint8 *_in, unsigned int _inLen, \
+ PRUint8 *_output, unsigned int *_outLen, \
+ unsigned int _maxOut), \
+ (ctx, counter, aad, aadLen, in, inLen, \
+ output, outputLen, maxOutputLen))
+
+#define SSL_DestroyAead(ctx) \
+ SSL_EXPERIMENTAL_API("SSL_DestroyAead", \
+ (SSLAeadContext * _ctx), \
+ (ctx))
+
+/* SSL_HkdfExtract and SSL_HkdfExpandLabel implement the functions from TLS,
+ * using the version and ciphersuite to set parameters. This allows callers to
+ * use these TLS functions as a KDF. This is only supported for TLS 1.3.
+ *
+ * SSL_HkdfExtract produces a key with a mechanism that is suitable for input to
+ * SSL_HkdfExpandLabel (and SSL_HkdfExpandLabelWithMech). */
+#define SSL_HkdfExtract(version, cipherSuite, salt, ikm, keyp) \
+ SSL_EXPERIMENTAL_API("SSL_HkdfExtract", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _salt, PK11SymKey * _ikm, \
+ PK11SymKey * *_keyp), \
+ (version, cipherSuite, salt, ikm, keyp))
+
+/* SSL_HkdfExpandLabel and SSL_HkdfVariantExpandLabel produce a key with a
+ * mechanism that is suitable for input to SSL_HkdfExpandLabel or SSL_MakeAead.
+ *
+ * Note: SSL_HkdfVariantExpandLabel internally calls SSL_HkdfExpandLabel with
+ * a default "stream" variant. If "datagram" variant is passed instead, the
+ * Label prefix used in HKDF-Expand is "dtls13" instead of "tls13 ". See 7.1 of
+ * RFC 8446 and draft-ietf-tls-dtls13-34. */
+#define SSL_HkdfExpandLabel(version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, keyp) \
+ SSL_EXPERIMENTAL_API("SSL_HkdfExpandLabel", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _prk, \
+ const PRUint8 *_hsHash, unsigned int _hsHashLen, \
+ const char *_label, unsigned int _labelLen, \
+ PK11SymKey **_keyp), \
+ (version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, keyp))
+
+#define SSL_HkdfVariantExpandLabel(version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, variant, \
+ keyp) \
+ SSL_EXPERIMENTAL_API("SSL_HkdfVariantExpandLabel", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _prk, \
+ const PRUint8 *_hsHash, unsigned int _hsHashLen, \
+ const char *_label, unsigned int _labelLen, \
+ SSLProtocolVariant _variant, \
+ PK11SymKey **_keyp), \
+ (version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, variant, \
+ keyp))
+
+/* SSL_HkdfExpandLabelWithMech and SSL_HkdfVariantExpandLabelWithMech use the KDF
+ * from the selected TLS version and cipher suite, as with the other calls, but
+ * the provided mechanism and key size. This allows the key to be used more widely.
+ *
+ * Note: SSL_HkdfExpandLabelWithMech internally calls SSL_HkdfVariantExpandLabelWithMech
+ * with a default "stream" variant. If "datagram" variant is passed instead, the
+ * Label prefix used in HKDF-Expand is "dtls13" instead of "tls13 ". See 7.1 of
+ * RFC 8446 and draft-ietf-tls-dtls13-34. */
+#define SSL_HkdfExpandLabelWithMech(version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, \
+ mech, keySize, keyp) \
+ SSL_EXPERIMENTAL_API("SSL_HkdfExpandLabelWithMech", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _prk, \
+ const PRUint8 *_hsHash, unsigned int _hsHashLen, \
+ const char *_label, unsigned int _labelLen, \
+ CK_MECHANISM_TYPE _mech, unsigned int _keySize, \
+ PK11SymKey **_keyp), \
+ (version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, \
+ mech, keySize, keyp))
+
+#define SSL_HkdfVariantExpandLabelWithMech(version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, \
+ mech, keySize, variant, keyp) \
+ SSL_EXPERIMENTAL_API("SSL_HkdfVariantExpandLabelWithMech", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _prk, \
+ const PRUint8 *_hsHash, unsigned int _hsHashLen, \
+ const char *_label, unsigned int _labelLen, \
+ CK_MECHANISM_TYPE _mech, unsigned int _keySize, \
+ SSLProtocolVariant _variant, \
+ PK11SymKey **_keyp), \
+ (version, cipherSuite, prk, \
+ hsHash, hsHashLen, label, labelLen, \
+ mech, keySize, variant, keyp))
+
+/* SSL_SetTimeFunc overrides the default time function (PR_Now()) and provides
+ * an alternative source of time for the socket. This is used in testing, and in
+ * applications that need better control over how the clock is accessed. Set the
+ * function to NULL to use PR_Now().*/
+typedef PRTime(PR_CALLBACK *SSLTimeFunc)(void *arg);
+
+#define SSL_SetTimeFunc(fd, f, arg) \
+ SSL_EXPERIMENTAL_API("SSL_SetTimeFunc", \
+ (PRFileDesc * _fd, SSLTimeFunc _f, void *_arg), \
+ (fd, f, arg))
+
+/* Create a delegated credential (DC) for the draft-ietf-tls-subcerts extension
+ * using the given certificate |cert| and its signing key |certPriv| and write
+ * the serialized DC to |out|. The
+ * parameters are:
+ * - the DC public key |dcPub|;
+ * - the DC signature scheme |dcCertVerifyAlg|, used to verify the handshake.
+ * - the DC time-to-live |dcValidFor|, the number of seconds from now for which
+ * the DC should be valid; and
+ * - the current time |now|.
+ *
+ * The signing algorithm used to verify the DC signature is deduced from
+ * |cert|.
+ *
+ * It's the caller's responsibility to ensure the input parameters are all
+ * valid. This procedure is meant primarily for testing; for this purpose it is
+ * useful to do no validation.
+ */
+#define SSL_DelegateCredential(cert, certPriv, dcPub, dcCertVerifyAlg, \
+ dcValidFor, now, out) \
+ SSL_EXPERIMENTAL_API("SSL_DelegateCredential", \
+ (const CERTCertificate *_cert, \
+ const SECKEYPrivateKey *_certPriv, \
+ const SECKEYPublicKey *_dcPub, \
+ SSLSignatureScheme _dcCertVerifyAlg, \
+ PRUint32 _dcValidFor, \
+ PRTime _now, \
+ SECItem *_out), \
+ (cert, certPriv, dcPub, dcCertVerifyAlg, dcValidFor, \
+ now, out))
+
+/* New functions created to permit get/set the CipherSuites Order for the
+ * handshake (Client Hello).
+ *
+ * The *Get function puts the current set of active (enabled and policy set as
+ * PR_TRUE) cipher suites in the cipherOrder outparam. Cipher suites that
+ * aren't active aren't included. The paramenters are:
+ * - PRFileDesc *fd = FileDescriptor to get information.
+ * - PRUint16 *cipherOrder = The memory allocated for cipherOrder needs to be
+ * SSL_GetNumImplementedCiphers() * sizeof(PRUint16) or more.
+ * - PRUint16 numCiphers = The number of active ciphersuites listed in
+ * *cipherOrder is written here.
+ *
+ * The *Set function permits reorder the CipherSuites list for the Handshake
+ * (Client Hello). The default ordering defined in ssl3con.c is enough in
+ * almost all cases. But, if the client needs some hardening or performance
+ * adjusts related to CipherSuites, this can be done with this function.
+ * The caller has to be aware about the risk of call this function while a
+ * handshake are being processed in this fd/socket. For example, if you disable
+ * a cipher after the handshake and this cipher was choosen for that
+ * connection, something bad will happen.
+ * The parameters are:
+ * - PRFileDesc *fd = FileDescriptor to change.
+ * - const PRUint16 *cipherOrder = Must receive all ciphers to be ordered, in
+ * the desired order. They will be set in the begin of the list. Only
+ * suites listed by SSL_ImplementedCiphers() can be included.
+ * - PRUint16 numCiphers = Must receive the number of items in *cipherOrder.
+ * */
+#define SSL_CipherSuiteOrderGet(fd, cipherOrder, numCiphers) \
+ SSL_EXPERIMENTAL_API("SSL_CipherSuiteOrderGet", \
+ (PRFileDesc * _fd, PRUint16 * _cipherOrder, \
+ unsigned int *_numCiphers), \
+ (fd, cipherOrder, numCiphers))
+
+#define SSL_CipherSuiteOrderSet(fd, cipherOrder, numCiphers) \
+ SSL_EXPERIMENTAL_API("SSL_CipherSuiteOrderSet", \
+ (PRFileDesc * _fd, const PRUint16 *_cipherOrder, \
+ PRUint16 _numCiphers), \
+ (fd, cipherOrder, numCiphers))
+
+/*
+ * The following functions expose a masking primitive that uses ciphersuite and
+ * version information to set paramaters for the masking key and mask generation
+ * logic. This is only supported for TLS 1.3.
+ *
+ * The key and IV are generated using the TLS KDF with a custom label. That is
+ * HKDF-Expand-Label(secret, label, "", L), where |label| is an input to
+ * SSL_CreateMaskingContext.
+ *
+ * The mask generation logic in SSL_CreateMask is determined by the underlying
+ * symmetric cipher:
+ * - For AES-ECB, mask = AES-ECB(mask_key, sample). |len| must be <= 16 as
+ * the output is limited to a single block.
+ * - For CHACHA20, mask = ChaCha20(mask_key, sample[0..3], sample[4..15], {0}.len)
+ * That is, the low 4 bytes of |sample| used as the counter, the remaining 12 bytes
+ * the nonce. We encrypt |len| bytes of zeros, returning the raw key stream.
+ *
+ * The caller must pre-allocate at least |len| bytes for output. If the underlying
+ * cipher cannot produce the requested amount of data, SECFailure is returned.
+ */
+
+typedef struct SSLMaskingContextStr {
+ CK_MECHANISM_TYPE mech;
+ PRUint16 version;
+ PRUint16 cipherSuite;
+ PK11SymKey *secret;
+} SSLMaskingContext;
+
+#define SSL_CreateMaskingContext(version, cipherSuite, secret, \
+ label, labelLen, ctx) \
+ SSL_EXPERIMENTAL_API("SSL_CreateMaskingContext", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ PK11SymKey * _secret, \
+ const char *_label, \
+ unsigned int _labelLen, \
+ SSLMaskingContext **_ctx), \
+ (version, cipherSuite, secret, label, labelLen, ctx))
+
+#define SSL_CreateVariantMaskingContext(version, cipherSuite, variant, \
+ secret, label, labelLen, ctx) \
+ SSL_EXPERIMENTAL_API("SSL_CreateVariantMaskingContext", \
+ (PRUint16 _version, PRUint16 _cipherSuite, \
+ SSLProtocolVariant _variant, \
+ PK11SymKey * _secret, \
+ const char *_label, \
+ unsigned int _labelLen, \
+ SSLMaskingContext **_ctx), \
+ (version, cipherSuite, variant, secret, \
+ label, labelLen, ctx))
+
+#define SSL_DestroyMaskingContext(ctx) \
+ SSL_EXPERIMENTAL_API("SSL_DestroyMaskingContext", \
+ (SSLMaskingContext * _ctx), \
+ (ctx))
+
+#define SSL_CreateMask(ctx, sample, sampleLen, mask, maskLen) \
+ SSL_EXPERIMENTAL_API("SSL_CreateMask", \
+ (SSLMaskingContext * _ctx, const PRUint8 *_sample, \
+ unsigned int _sampleLen, PRUint8 *_mask, \
+ unsigned int _maskLen), \
+ (ctx, sample, sampleLen, mask, maskLen))
+
+#define SSL_SetDtls13VersionWorkaround(fd, enabled) \
+ SSL_EXPERIMENTAL_API("SSL_SetDtls13VersionWorkaround", \
+ (PRFileDesc * _fd, PRBool _enabled), (fd, enabled))
+
+/* SSL_AddExternalPsk() and SSL_AddExternalPsk0Rtt() can be used to
+ * set an external PSK on a socket. If successful, this PSK will
+ * be used in all subsequent connection attempts for this socket.
+ * This has no effect if the maximum TLS version is < 1.3.
+ *
+ * This API currently only accepts a single PSK, so multiple calls to
+ * either function will fail. An EPSK can be replaced by calling
+ * SSL_RemoveExternalPsk followed by SSL_AddExternalPsk.
+ * For both functions, the label is expected to be a unique identifier
+ * for the external PSK. Should en external PSK have the same label
+ * as a configured resumption PSK identity, the external PSK will
+ * take precedence.
+ *
+ * If you want to enable early data, you need to also provide a
+ * cipher suite for 0-RTT and a limit for the early data using
+ * SSL_AddExternalPsk0Rtt(). If you want to explicitly disallow
+ * certificate authentication, use SSL_AuthCertificateHook to set
+ * a callback that rejects all certificate chains.
+ */
+#define SSL_AddExternalPsk(fd, psk, identity, identityLen, hash) \
+ SSL_EXPERIMENTAL_API("SSL_AddExternalPsk", \
+ (PRFileDesc * _fd, PK11SymKey * _psk, \
+ const PRUint8 *_identity, unsigned int _identityLen, \
+ SSLHashType _hash), \
+ (fd, psk, identity, identityLen, hash))
+
+#define SSL_AddExternalPsk0Rtt(fd, psk, identity, identityLen, hash, \
+ zeroRttSuite, maxEarlyData) \
+ SSL_EXPERIMENTAL_API("SSL_AddExternalPsk0Rtt", \
+ (PRFileDesc * _fd, PK11SymKey * _psk, \
+ const PRUint8 *_identity, unsigned int _identityLen, \
+ SSLHashType _hash, PRUint16 _zeroRttSuite, \
+ PRUint32 _maxEarlyData), \
+ (fd, psk, identity, identityLen, hash, \
+ zeroRttSuite, maxEarlyData))
+
+/* SSLExp_RemoveExternalPsk() removes an external PSK from socket
+ * configuration. Returns SECSuccess if the PSK was removed
+ * successfully, and SECFailure otherwise. */
+#define SSL_RemoveExternalPsk(fd, identity, identityLen) \
+ SSL_EXPERIMENTAL_API("SSL_RemoveExternalPsk", \
+ (PRFileDesc * _fd, const PRUint8 *_identity, \
+ unsigned int _identityLen), \
+ (fd, identity, identityLen))
+
+/* Deprecated experimental APIs */
+#define SSL_UseAltServerHelloType(fd, enable) SSL_DEPRECATED_EXPERIMENTAL_API
+#define SSL_SetupAntiReplay(a, b, c) SSL_DEPRECATED_EXPERIMENTAL_API
+#define SSL_InitAntiReplay(a, b, c) SSL_DEPRECATED_EXPERIMENTAL_API
+#define SSL_EnableESNI(a, b, c, d) SSL_DEPRECATED_EXPERIMENTAL_API
+#define SSL_EncodeESNIKeys(a, b, c, d, e, f, g, h, i, j) SSL_DEPRECATED_EXPERIMENTAL_API
+#define SSL_SetESNIKeyPair(a, b, c, d) SSL_DEPRECATED_EXPERIMENTAL_API
+#define SSL_EncodeEchConfig(a, b, c, d, e, f, g, h, i) SSL_DEPRECATED_EXPERIMENTAL_API
+
+SEC_END_PROTOS
+
+#endif /* __sslexp_h_ */
diff --git a/security/nss/lib/ssl/sslgrp.c b/security/nss/lib/ssl/sslgrp.c
new file mode 100644
index 0000000000..eb53ad381c
--- /dev/null
+++ b/security/nss/lib/ssl/sslgrp.c
@@ -0,0 +1,164 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file contains prototypes for the public SSL functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "pk11func.h"
+#include "ssl.h"
+#include "sslimpl.h"
+
+struct {
+ sslEphemeralKeyPair *keyPair;
+ PRCallOnceType once;
+} gECDHEKeyPairs[SSL_NAMED_GROUP_COUNT];
+
+typedef struct sslSocketAndGroupArgStr {
+ const sslNamedGroupDef *group;
+ const sslSocket *ss;
+} sslSocketAndGroupArg;
+
+/* Function to clear out the ECDHE keys. */
+static SECStatus
+ssl_CleanupECDHEKeys(void *appData, void *nssData)
+{
+ unsigned int i;
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; i++) {
+ if (gECDHEKeyPairs[i].keyPair) {
+ ssl_FreeEphemeralKeyPair(gECDHEKeyPairs[i].keyPair);
+ }
+ }
+ memset(gECDHEKeyPairs, 0, sizeof(gECDHEKeyPairs));
+ return SECSuccess;
+}
+
+/* Only run the cleanup once. */
+static PRCallOnceType cleanupECDHEKeysOnce;
+static PRStatus
+ssl_SetupCleanupECDHEKeysOnce(void)
+{
+ SECStatus rv = NSS_RegisterShutdown(ssl_CleanupECDHEKeys, NULL);
+ return (rv != SECSuccess) ? PR_FAILURE : PR_SUCCESS;
+}
+
+/* This creates a key pair for each of the supported EC groups. If that works,
+ * we assume that the token supports that group. Since this is relatively
+ * expensive, this is only done for the first socket that is used. That means
+ * that if tokens are added or removed, then this will not pick up any changes.
+ */
+static PRStatus
+ssl_CreateStaticECDHEKeyPair(void *arg)
+{
+ const sslSocketAndGroupArg *typed_arg = (sslSocketAndGroupArg *)arg;
+ const sslNamedGroupDef *group = typed_arg->group;
+ const sslSocket *ss = typed_arg->ss;
+ unsigned int i = group - ssl_named_groups;
+ SECStatus rv;
+
+ PORT_Assert(group->keaType == ssl_kea_ecdh);
+ PORT_Assert(i < SSL_NAMED_GROUP_COUNT);
+ rv = ssl_CreateECDHEphemeralKeyPair(ss, group,
+ &gECDHEKeyPairs[i].keyPair);
+ if (rv != SECSuccess) {
+ gECDHEKeyPairs[i].keyPair = NULL;
+ SSL_TRC(5, ("%d: SSL[-]: disabling group %d",
+ SSL_GETPID(), group->name));
+ }
+
+ return PR_SUCCESS;
+}
+
+void
+ssl_FilterSupportedGroups(sslSocket *ss)
+{
+ unsigned int i;
+ PRStatus prv;
+ sslSocketAndGroupArg arg = { NULL, ss };
+
+ prv = PR_CallOnce(&cleanupECDHEKeysOnce, ssl_SetupCleanupECDHEKeysOnce);
+ PORT_Assert(prv == PR_SUCCESS);
+ if (prv != PR_SUCCESS) {
+ return;
+ }
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ PRUint32 policy;
+ SECStatus srv;
+ unsigned int index;
+ const sslNamedGroupDef *group = ss->namedGroupPreferences[i];
+ if (!group) {
+ continue;
+ }
+
+ srv = NSS_GetAlgorithmPolicy(group->oidTag, &policy);
+ if (srv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) {
+ ss->namedGroupPreferences[i] = NULL;
+ continue;
+ }
+
+ if (group->assumeSupported) {
+ continue;
+ }
+
+ /* For EC groups, we have to test that a key pair can be created. This
+ * is gross, and expensive, so only do it once. */
+ index = group - ssl_named_groups;
+ PORT_Assert(index < SSL_NAMED_GROUP_COUNT);
+
+ arg.group = group;
+ prv = PR_CallOnceWithArg(&gECDHEKeyPairs[index].once,
+ ssl_CreateStaticECDHEKeyPair,
+ (void *)&arg);
+ PORT_Assert(prv == PR_SUCCESS);
+ if (prv != PR_SUCCESS) {
+ continue;
+ }
+
+ if (!gECDHEKeyPairs[index].keyPair) {
+ ss->namedGroupPreferences[i] = NULL;
+ }
+ }
+}
+
+/*
+ * Creates the static "ephemeral" public and private ECDH keys used by server in
+ * ECDHE_RSA and ECDHE_ECDSA handshakes when we reuse the same key.
+ */
+SECStatus
+ssl_CreateStaticECDHEKey(sslSocket *ss, const sslNamedGroupDef *ecGroup)
+{
+ sslEphemeralKeyPair *keyPair;
+ /* We index gECDHEKeyPairs by the named group. Pointer arithmetic! */
+ unsigned int index = ecGroup - ssl_named_groups;
+ PRStatus prv;
+ sslSocketAndGroupArg arg = { ecGroup, ss };
+
+ prv = PR_CallOnceWithArg(&gECDHEKeyPairs[index].once,
+ ssl_CreateStaticECDHEKeyPair,
+ (void *)&arg);
+ PORT_Assert(prv == PR_SUCCESS);
+ if (prv != PR_SUCCESS) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ keyPair = gECDHEKeyPairs[index].keyPair;
+ if (!keyPair) {
+ /* Attempting to use a key pair for an unsupported group. */
+ PORT_Assert(keyPair);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ keyPair = ssl_CopyEphemeralKeyPair(keyPair);
+ if (!keyPair)
+ return SECFailure;
+
+ PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
+ PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/sslimpl.h b/security/nss/lib/ssl/sslimpl.h
new file mode 100644
index 0000000000..4486d0df5f
--- /dev/null
+++ b/security/nss/lib/ssl/sslimpl.h
@@ -0,0 +1,2020 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL and should be the first thing included by
+ * any SSL implementation file.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslimpl_h_
+#define __sslimpl_h_
+
+#ifdef DEBUG
+#undef NDEBUG
+#else
+#undef NDEBUG
+#define NDEBUG
+#endif
+#include "secport.h"
+#include "secerr.h"
+#include "sslerr.h"
+#include "sslexp.h"
+#include "ssl3prot.h"
+#include "hasht.h"
+#include "nssilock.h"
+#include "pkcs11t.h"
+#if defined(XP_UNIX)
+#include "unistd.h"
+#endif
+#include "nssrwlk.h"
+#include "prthread.h"
+#include "prclist.h"
+#include "private/pprthred.h"
+
+#include "sslt.h" /* for some formerly private types, now public */
+
+typedef struct sslSocketStr sslSocket;
+typedef struct sslNamedGroupDefStr sslNamedGroupDef;
+typedef struct sslEchConfigStr sslEchConfig;
+typedef struct sslEchConfigContentsStr sslEchConfigContents;
+typedef struct sslEchCookieDataStr sslEchCookieData;
+typedef struct sslEchXtnStateStr sslEchXtnState;
+typedef struct sslPskStr sslPsk;
+typedef struct sslDelegatedCredentialStr sslDelegatedCredential;
+typedef struct sslEphemeralKeyPairStr sslEphemeralKeyPair;
+typedef struct TLS13KeyShareEntryStr TLS13KeyShareEntry;
+
+#include "sslencode.h"
+#include "sslexp.h"
+#include "ssl3ext.h"
+#include "sslspec.h"
+
+#if defined(DEBUG) || defined(TRACE)
+#ifdef __cplusplus
+#define Debug 1
+#else
+extern int Debug;
+#endif
+#else
+#undef Debug
+#endif
+
+#if defined(DEBUG) && !defined(TRACE) && !defined(NISCC_TEST)
+#define TRACE
+#endif
+
+#ifdef TRACE
+#define SSL_TRC(a, b) \
+ if (ssl_trace >= (a)) \
+ ssl_Trace b
+#define PRINT_BUF(a, b) \
+ if (ssl_trace >= (a)) \
+ ssl_PrintBuf b
+#define PRINT_KEY(a, b) \
+ if (ssl_trace >= (a)) \
+ ssl_PrintKey b
+#else
+#define SSL_TRC(a, b)
+#define PRINT_BUF(a, b)
+#define PRINT_KEY(a, b)
+#endif
+
+#ifdef DEBUG
+#define SSL_DBG(b) \
+ if (ssl_debug) \
+ ssl_Trace b
+#else
+#define SSL_DBG(b)
+#endif
+
+#define LSB(x) ((unsigned char)((x)&0xff))
+#define MSB(x) ((unsigned char)(((unsigned)(x)) >> 8))
+
+#define CONST_CAST(T, X) ((T *)(X))
+
+/************************************************************************/
+
+typedef enum { SSLAppOpRead = 0,
+ SSLAppOpWrite,
+ SSLAppOpRDWR,
+ SSLAppOpPost,
+ SSLAppOpHeader
+} SSLAppOperation;
+
+#define SSL3_SESSIONID_BYTES 32
+
+#define SSL_MIN_CHALLENGE_BYTES 16
+#define SSL_MAX_CHALLENGE_BYTES 32
+
+#define SSL3_MASTER_SECRET_LENGTH 48
+
+/* number of wrap mechanisms potentially used to wrap master secrets. */
+#define SSL_NUM_WRAP_MECHS 15
+#define SSL_NUM_WRAP_KEYS 6
+
+/* This makes the cert cache entry exactly 4k. */
+#define SSL_MAX_CACHED_CERT_LEN 4060
+
+#ifndef BPB
+#define BPB 8 /* Bits Per Byte */
+#endif
+
+/* The default value from RFC 4347 is 1s, which is too slow. */
+#define DTLS_RETRANSMIT_INITIAL_MS 50
+/* The maximum time to wait between retransmissions. */
+#define DTLS_RETRANSMIT_MAX_MS 10000
+/* Time to wait in FINISHED state for retransmissions. */
+#define DTLS_RETRANSMIT_FINISHED_MS 30000
+
+/* default number of entries in namedGroupPreferences */
+#define SSL_NAMED_GROUP_COUNT 31
+
+/* The maximum DH and RSA bit-length supported. */
+#define SSL_MAX_DH_KEY_BITS 8192
+#define SSL_MAX_RSA_KEY_BITS 8192
+
+/* Types and names of elliptic curves used in TLS */
+typedef enum {
+ ec_type_explicitPrime = 1, /* not supported */
+ ec_type_explicitChar2Curve = 2, /* not supported */
+ ec_type_named = 3
+} ECType;
+
+typedef enum {
+ ticket_allow_early_data = 1,
+ ticket_allow_psk_ke = 2,
+ ticket_allow_psk_dhe_ke = 4,
+ ticket_allow_psk_auth = 8,
+ ticket_allow_psk_sign_auth = 16
+} TLS13SessionTicketFlags;
+
+typedef enum {
+ update_not_requested = 0,
+ update_requested = 1
+} tls13KeyUpdateRequest;
+
+struct sslNamedGroupDefStr {
+ /* The name is the value that is encoded on the wire in TLS. */
+ SSLNamedGroup name;
+ /* The number of bits in the group. */
+ unsigned int bits;
+ /* The key exchange algorithm this group provides. */
+ SSLKEAType keaType;
+ /* The OID that identifies the group to PKCS11. This also determines
+ * whether the group is enabled in policy. */
+ SECOidTag oidTag;
+ /* Assume that the group is always supported. */
+ PRBool assumeSupported;
+};
+
+typedef struct sslConnectInfoStr sslConnectInfo;
+typedef struct sslGatherStr sslGather;
+typedef struct sslSecurityInfoStr sslSecurityInfo;
+typedef struct sslSessionIDStr sslSessionID;
+typedef struct sslSocketOpsStr sslSocketOps;
+
+typedef struct ssl3StateStr ssl3State;
+typedef struct ssl3CertNodeStr ssl3CertNode;
+typedef struct sslKeyPairStr sslKeyPair;
+typedef struct ssl3DHParamsStr ssl3DHParams;
+
+struct ssl3CertNodeStr {
+ struct ssl3CertNodeStr *next;
+ CERTCertificate *cert;
+};
+
+typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss);
+
+void ssl_CacheSessionID(sslSocket *ss);
+void ssl_UncacheSessionID(sslSocket *ss);
+void ssl_ServerCacheSessionID(sslSessionID *sid, PRTime creationTime);
+void ssl_ServerUncacheSessionID(sslSessionID *sid);
+
+typedef sslSessionID *(*sslSessionIDLookupFunc)(PRTime ssl_now,
+ const PRIPv6Addr *addr,
+ unsigned char *sid,
+ unsigned int sidLen,
+ CERTCertDBHandle *dbHandle);
+
+/* Socket ops */
+struct sslSocketOpsStr {
+ int (*connect)(sslSocket *, const PRNetAddr *);
+ PRFileDesc *(*accept)(sslSocket *, PRNetAddr *);
+ int (*bind)(sslSocket *, const PRNetAddr *);
+ int (*listen)(sslSocket *, int);
+ int (*shutdown)(sslSocket *, int);
+ int (*close)(sslSocket *);
+
+ int (*recv)(sslSocket *, unsigned char *, int, int);
+
+ /* points to the higher-layer send func, e.g. ssl_SecureSend. */
+ int (*send)(sslSocket *, const unsigned char *, int, int);
+ int (*read)(sslSocket *, unsigned char *, int);
+ int (*write)(sslSocket *, const unsigned char *, int);
+
+ int (*getpeername)(sslSocket *, PRNetAddr *);
+ int (*getsockname)(sslSocket *, PRNetAddr *);
+};
+
+/* Flags interpreted by ssl send functions. */
+#define ssl_SEND_FLAG_FORCE_INTO_BUFFER 0x40000000
+#define ssl_SEND_FLAG_NO_BUFFER 0x20000000
+#define ssl_SEND_FLAG_NO_RETRANSMIT 0x08000000 /* DTLS only */
+#define ssl_SEND_FLAG_MASK 0x7f000000
+
+/*
+** SSL3 cipher suite policy and preference struct.
+*/
+typedef struct {
+#if !defined(_WIN32)
+ unsigned int cipher_suite : 16;
+ unsigned int policy : 8;
+ unsigned int enabled : 1;
+ unsigned int isPresent : 1;
+#else
+ ssl3CipherSuite cipher_suite;
+ PRUint8 policy;
+ unsigned char enabled : 1;
+ unsigned char isPresent : 1;
+#endif
+} ssl3CipherSuiteCfg;
+
+#define ssl_V3_SUITES_IMPLEMENTED 71
+
+#define MAX_DTLS_SRTP_CIPHER_SUITES 4
+
+/* MAX_SIGNATURE_SCHEMES allows for all the values we support. */
+#define MAX_SIGNATURE_SCHEMES 18
+
+typedef struct sslOptionsStr {
+ /* If SSL_SetNextProtoNego has been called, then this contains the
+ * list of supported protocols. */
+ SECItem nextProtoNego;
+ PRUint16 recordSizeLimit;
+
+ PRUint32 maxEarlyDataSize;
+ unsigned int useSecurity : 1;
+ unsigned int useSocks : 1;
+ unsigned int requestCertificate : 1;
+ unsigned int requireCertificate : 2;
+ unsigned int handshakeAsClient : 1;
+ unsigned int handshakeAsServer : 1;
+ unsigned int noCache : 1;
+ unsigned int fdx : 1;
+ unsigned int detectRollBack : 1;
+ unsigned int noLocks : 1;
+ unsigned int enableSessionTickets : 1;
+ unsigned int enableDeflate : 1; /* Deprecated. */
+ unsigned int enableRenegotiation : 2;
+ unsigned int requireSafeNegotiation : 1;
+ unsigned int enableFalseStart : 1;
+ unsigned int cbcRandomIV : 1;
+ unsigned int enableOCSPStapling : 1;
+ unsigned int enableALPN : 1;
+ unsigned int reuseServerECDHEKey : 1;
+ unsigned int enableFallbackSCSV : 1;
+ unsigned int enableServerDhe : 1;
+ unsigned int enableExtendedMS : 1;
+ unsigned int enableSignedCertTimestamps : 1;
+ unsigned int requireDHENamedGroups : 1;
+ unsigned int enable0RttData : 1;
+ unsigned int enableTls13CompatMode : 1;
+ unsigned int enableDtlsShortHeader : 1;
+ unsigned int enableHelloDowngradeCheck : 1;
+ unsigned int enableV2CompatibleHello : 1;
+ unsigned int enablePostHandshakeAuth : 1;
+ unsigned int enableDelegatedCredentials : 1;
+ unsigned int enableDtls13VersionCompat : 1;
+ unsigned int suppressEndOfEarlyData : 1;
+ unsigned int enableTls13GreaseEch : 1;
+ unsigned int enableTls13BackendEch : 1;
+ unsigned int callExtensionWriterOnEchInner : 1;
+ unsigned int enableGrease : 1;
+ unsigned int enableChXtnPermutation : 1;
+} sslOptions;
+
+typedef enum { sslHandshakingUndetermined = 0,
+ sslHandshakingAsClient,
+ sslHandshakingAsServer
+} sslHandshakingType;
+
+#define SSL_LOCK_RANK_SPEC 255
+
+/* These are the valid values for shutdownHow.
+** These values are each 1 greater than the NSPR values, and the code
+** depends on that relation to efficiently convert PR_SHUTDOWN values
+** into ssl_SHUTDOWN values. These values use one bit for read, and
+** another bit for write, and can be used as bitmasks.
+*/
+#define ssl_SHUTDOWN_NONE 0 /* NOT shutdown at all */
+#define ssl_SHUTDOWN_RCV 1 /* PR_SHUTDOWN_RCV +1 */
+#define ssl_SHUTDOWN_SEND 2 /* PR_SHUTDOWN_SEND +1 */
+#define ssl_SHUTDOWN_BOTH 3 /* PR_SHUTDOWN_BOTH +1 */
+
+/*
+** A gather object. Used to read some data until a count has been
+** satisfied. Primarily for support of async sockets.
+** Everything in here is protected by the recvBufLock.
+*/
+struct sslGatherStr {
+ int state; /* see GS_ values below. */
+
+ /* "buf" holds received plaintext SSL records, after decrypt and MAC check.
+ * recv'd ciphertext records are put in inbuf (see below), then decrypted
+ * into buf.
+ */
+ sslBuffer buf; /*recvBufLock*/
+
+ /* number of bytes previously read into hdr or inbuf.
+ ** (offset - writeOffset) is the number of ciphertext bytes read in but
+ ** not yet deciphered.
+ */
+ unsigned int offset;
+
+ /* number of bytes to read in next call to ssl_DefRecv (recv) */
+ unsigned int remainder;
+
+ /* DoRecv uses the next two values to extract application data.
+ ** The difference between writeOffset and readOffset is the amount of
+ ** data available to the application. Note that the actual offset of
+ ** the data in "buf" is recordOffset (above), not readOffset.
+ ** In the current implementation, this is made available before the
+ ** MAC is checked!!
+ */
+ unsigned int readOffset; /* Spot where DATA reader (e.g. application
+ ** or handshake code) will read next.
+ ** Always zero for SSl3 application data.
+ */
+ /* offset in buf/inbuf/hdr into which new data will be read from socket. */
+ unsigned int writeOffset;
+
+ /* Buffer for ssl3 to read (encrypted) data from the socket */
+ sslBuffer inbuf; /*recvBufLock*/
+
+ /* The ssl[23]_GatherData functions read data into this buffer, rather
+ ** than into buf or inbuf, while in the GS_HEADER state.
+ ** The portion of the SSL record header put here always comes off the wire
+ ** as plaintext, never ciphertext.
+ ** For SSL3/TLS, the plaintext portion is 5 bytes long. For DTLS it
+ ** varies based on version and header type.
+ */
+ unsigned char hdr[13];
+ unsigned int hdrLen;
+
+ /* Buffer for DTLS data read off the wire as a single datagram */
+ sslBuffer dtlsPacket;
+
+ /* the start of the buffered DTLS record in dtlsPacket */
+ unsigned int dtlsPacketOffset;
+
+ /* tracks whether we've seen a v3-type record before and must reject
+ * any further v2-type records. */
+ PRBool rejectV2Records;
+};
+
+/* sslGather.state */
+#define GS_INIT 0
+#define GS_HEADER 1
+#define GS_DATA 2
+
+#define WRAPPED_MASTER_SECRET_SIZE 48
+
+typedef struct {
+ PRUint8 wrapped_master_secret[WRAPPED_MASTER_SECRET_SIZE];
+ PRUint8 wrapped_master_secret_len;
+ PRUint8 resumable;
+ PRUint8 extendedMasterSecretUsed;
+} ssl3SidKeys; /* 52 bytes */
+
+typedef enum { never_cached,
+ in_client_cache,
+ in_server_cache,
+ invalid_cache, /* no longer in any cache. */
+ in_external_cache
+} Cached;
+
+#include "sslcert.h"
+
+struct sslSessionIDStr {
+ /* The global cache lock must be held when accessing these members when the
+ * sid is in any cache.
+ */
+ sslSessionID *next; /* chain used for client sockets, only */
+ Cached cached;
+ int references;
+ PRTime lastAccessTime;
+
+ /* The rest of the members, except for the members of u.ssl3.locked, may
+ * be modified only when the sid is not in any cache.
+ */
+
+ CERTCertificate *peerCert;
+ SECItemArray peerCertStatus; /* client only */
+ const char *peerID; /* client only */
+ const char *urlSvrName; /* client only */
+ const sslNamedGroupDef *namedCurve; /* (server) for certificate lookup */
+ CERTCertificate *localCert;
+
+ PRIPv6Addr addr;
+ PRUint16 port;
+
+ SSL3ProtocolVersion version;
+
+ PRTime creationTime;
+ PRTime expirationTime;
+
+ SSLAuthType authType;
+ PRUint32 authKeyBits;
+ SSLKEAType keaType;
+ PRUint32 keaKeyBits;
+ SSLNamedGroup keaGroup;
+ SSLSignatureScheme sigScheme;
+
+ union {
+ struct {
+ /* values that are copied into the server's on-disk SID cache. */
+ PRUint8 sessionIDLength;
+ PRUint8 sessionID[SSL3_SESSIONID_BYTES];
+
+ ssl3CipherSuite cipherSuite;
+ PRUint8 policy;
+ ssl3SidKeys keys;
+ /* mechanism used to wrap master secret */
+ CK_MECHANISM_TYPE masterWrapMech;
+
+ /* The following values pertain to the slot that wrapped the
+ ** master secret. (used only in client)
+ */
+ SECMODModuleID masterModuleID;
+ /* what module wrapped the master secret */
+ CK_SLOT_ID masterSlotID;
+ PRUint16 masterWrapIndex;
+ /* what's the key index for the wrapping key */
+ PRUint16 masterWrapSeries;
+ /* keep track of the slot series, so we don't
+ * accidently try to use new keys after the
+ * card gets removed and replaced.*/
+
+ /* The following values pertain to the slot that did the signature
+ ** for client auth. (used only in client)
+ */
+ SECMODModuleID clAuthModuleID;
+ CK_SLOT_ID clAuthSlotID;
+ PRUint16 clAuthSeries;
+
+ char masterValid;
+ char clAuthValid;
+
+ SECItem srvName;
+
+ /* Signed certificate timestamps received in a TLS extension.
+ ** (used only in client).
+ */
+ SECItem signedCertTimestamps;
+
+ /* The ALPN value negotiated in the original connection.
+ * Used for TLS 1.3. */
+ SECItem alpnSelection;
+
+ /* This lock is lazily initialized by CacheSID when a sid is first
+ * cached. Before then, there is no need to lock anything because
+ * the sid isn't being shared by anything.
+ */
+ PRRWLock *lock;
+
+ /* The lock must be held while reading or writing these members
+ * because they change while the sid is cached.
+ */
+ struct {
+ /* The session ticket, if we have one, is sent as an extension
+ * in the ClientHello message. This field is used only by
+ * clients. It is protected by lock when lock is non-null
+ * (after the sid has been added to the client session cache).
+ */
+ NewSessionTicket sessionTicket;
+ } locked;
+ } ssl3;
+ } u;
+};
+
+struct ssl3CipherSuiteDefStr {
+ ssl3CipherSuite cipher_suite;
+ SSL3BulkCipher bulk_cipher_alg;
+ SSL3MACAlgorithm mac_alg;
+ SSL3KeyExchangeAlgorithm key_exchange_alg;
+ SSLHashType prf_hash;
+};
+
+/*
+** There are tables of these, all const.
+*/
+typedef struct {
+ /* An identifier for this struct. */
+ SSL3KeyExchangeAlgorithm kea;
+ /* The type of key exchange used by the cipher suite. */
+ SSLKEAType exchKeyType;
+ /* If the cipher suite uses a signature, the type of key used in the
+ * signature. */
+ KeyType signKeyType;
+ /* In most cases, cipher suites depend on their signature type for
+ * authentication, ECDH certificates being the exception. */
+ SSLAuthType authKeyType;
+ /* True if the key exchange for the suite is ephemeral. Or to be more
+ * precise: true if the ServerKeyExchange message is always required. */
+ PRBool ephemeral;
+ /* An OID describing the key exchange */
+ SECOidTag oid;
+} ssl3KEADef;
+
+typedef enum {
+ ssl_0rtt_none, /* 0-RTT not present */
+ ssl_0rtt_sent, /* 0-RTT sent (no decision yet) */
+ ssl_0rtt_accepted, /* 0-RTT sent and accepted */
+ ssl_0rtt_ignored, /* 0-RTT sent but rejected/ignored */
+ ssl_0rtt_done /* 0-RTT accepted, but finished */
+} sslZeroRttState;
+
+typedef enum {
+ ssl_0rtt_ignore_none, /* not ignoring */
+ ssl_0rtt_ignore_trial, /* ignoring with trial decryption */
+ ssl_0rtt_ignore_hrr /* ignoring until ClientHello (due to HRR) */
+} sslZeroRttIgnore;
+
+typedef enum {
+ idle_handshake,
+ wait_client_hello,
+ wait_end_of_early_data,
+ wait_client_cert,
+ wait_client_key,
+ wait_cert_verify,
+ wait_change_cipher,
+ wait_finished,
+ wait_server_hello,
+ wait_certificate_status,
+ wait_server_cert,
+ wait_server_key,
+ wait_cert_request,
+ wait_hello_done,
+ wait_new_session_ticket,
+ wait_encrypted_extensions,
+ wait_invalid /* Invalid value. There is no handshake message "invalid". */
+} SSL3WaitState;
+
+typedef enum {
+ client_hello_initial, /* The first attempt. */
+ client_hello_retry, /* If we receive HelloRetryRequest. */
+ client_hello_retransmit, /* In DTLS, if we receive HelloVerifyRequest. */
+ client_hello_renegotiation /* A renegotiation attempt. */
+} sslClientHelloType;
+
+typedef struct SessionTicketDataStr SessionTicketData;
+
+typedef SECStatus (*sslRestartTarget)(sslSocket *);
+
+/*
+** A DTLS queued message (potentially to be retransmitted)
+*/
+typedef struct DTLSQueuedMessageStr {
+ PRCList link; /* The linked list link */
+ ssl3CipherSpec *cwSpec; /* The cipher spec to use, null for none */
+ SSLContentType type; /* The message type */
+ unsigned char *data; /* The data */
+ PRUint16 len; /* The data length */
+} DTLSQueuedMessage;
+
+struct TLS13KeyShareEntryStr {
+ PRCList link; /* The linked list link */
+ const sslNamedGroupDef *group; /* The group for the entry */
+ SECItem key_exchange; /* The share itself */
+};
+
+typedef struct TLS13EarlyDataStr {
+ PRCList link; /* The linked list link */
+ unsigned int consumed; /* How much has been read. */
+ SECItem data; /* The data */
+} TLS13EarlyData;
+
+typedef enum {
+ handshake_hash_unknown = 0,
+ handshake_hash_combo = 1, /* The MD5/SHA-1 combination */
+ handshake_hash_single = 2, /* A single hash */
+ handshake_hash_record
+} SSL3HandshakeHashType;
+
+// A DTLS Timer.
+typedef void (*DTLSTimerCb)(sslSocket *);
+
+typedef struct {
+ const char *label;
+ DTLSTimerCb cb;
+ PRIntervalTime started;
+ PRUint32 timeout;
+} dtlsTimer;
+
+/* TLS 1.3 client GREASE entry indices. */
+typedef enum {
+ grease_cipher,
+ grease_extension1,
+ grease_extension2,
+ grease_group,
+ grease_sigalg,
+ grease_version,
+ grease_alpn,
+ grease_entries
+} tls13ClientGreaseEntry;
+
+/* TLS 1.3 client GREASE values struct. */
+typedef struct tls13ClientGreaseStr {
+ PRUint16 idx[grease_entries];
+ PRUint8 pskKem;
+} tls13ClientGrease;
+
+/*
+** This is the "hs" member of the "ssl3" struct.
+** This entire struct is protected by ssl3HandshakeLock
+*/
+typedef struct SSL3HandshakeStateStr {
+ SSL3Random server_random;
+ SSL3Random client_random;
+ SSL3Random client_inner_random; /* TLS 1.3 ECH Inner. */
+ SSL3WaitState ws; /* May also contain SSL3WaitState | 0x80 for TLS 1.3 */
+
+ /* This group of members is used for handshake running hashes. */
+ SSL3HandshakeHashType hashType;
+ sslBuffer messages; /* Accumulated handshake messages */
+ sslBuffer echInnerMessages; /* Accumulated ECH Inner handshake messages */
+ /* PKCS #11 mode:
+ * SSL 3.0 - TLS 1.1 use both |md5| and |sha|. |md5| is used for MD5 and
+ * |sha| for SHA-1.
+ * TLS 1.2 and later use only |sha| variants, for SHA-256.
+ * Under normal (non-1.3 ECH) handshakes, only |sha| and |shaPostHandshake|
+ * are used. When doing 1.3 ECH, |sha| contains the transcript hash
+ * corresponding to the outer Client Hello. To facilitate secure retry and
+ * disablement, |shaEchInner|, tracks, in parallel, the transcript hash
+ * corresponding to the inner Client Hello. Once we process the SH
+ * extensions, coalesce into |sha|. */
+ PK11Context *md5;
+ PK11Context *sha;
+ PK11Context *shaEchInner;
+ PK11Context *shaPostHandshake;
+ SSLSignatureScheme signatureScheme;
+ const ssl3KEADef *kea_def;
+ ssl3CipherSuite cipher_suite;
+ const ssl3CipherSuiteDef *suite_def;
+ sslBuffer msg_body; /* protected by recvBufLock */
+ /* partial handshake message from record layer */
+ unsigned int header_bytes;
+ /* number of bytes consumed from handshake */
+ /* message for message type and header length */
+ SSLHandshakeType msg_type;
+ unsigned long msg_len;
+ PRBool isResuming; /* we are resuming (not used in TLS 1.3) */
+ PRBool sendingSCSV; /* instead of empty RI */
+
+ /* The session ticket received in a NewSessionTicket message is temporarily
+ * stored in newSessionTicket until the handshake is finished; then it is
+ * moved to the sid.
+ */
+ PRBool receivedNewSessionTicket;
+ NewSessionTicket newSessionTicket;
+
+ PRUint16 finishedBytes; /* size of single finished below */
+ union {
+ TLSFinished tFinished[2]; /* client, then server */
+ SSL3Finished sFinished[2];
+ PRUint8 data[72];
+ } finishedMsgs;
+
+ /* True when handshake is blocked on client certificate selection */
+ PRBool clientCertificatePending;
+ /* Parameters stored whilst waiting for client certificate */
+ SSLSignatureScheme *clientAuthSignatureSchemes;
+ unsigned int clientAuthSignatureSchemesLen;
+
+ PRBool authCertificatePending;
+ /* Which function should SSL_RestartHandshake* call if we're blocked?
+ * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake,
+ * or ssl3_AlwaysFail */
+ sslRestartTarget restartTarget;
+
+ PRBool canFalseStart; /* Can/did we False Start */
+ /* Which preliminaryinfo values have been set. */
+ PRUint32 preliminaryInfo;
+
+ /* Parsed extensions */
+ PRCList remoteExtensions; /* Parsed incoming extensions */
+ PRCList echOuterExtensions; /* If ECH, hold CHOuter extensions for decompression. */
+
+ /* This group of values is used for DTLS */
+ PRUint16 sendMessageSeq; /* The sending message sequence
+ * number */
+ PRCList lastMessageFlight; /* The last message flight we
+ * sent */
+ PRUint16 maxMessageSent; /* The largest message we sent */
+ PRUint16 recvMessageSeq; /* The receiving message sequence
+ * number */
+ sslBuffer recvdFragments; /* The fragments we have received in
+ * a bitmask */
+ PRInt32 recvdHighWater; /* The high water mark for fragments
+ * received. -1 means no reassembly
+ * in progress. */
+ SECItem cookie; /* The Hello(Retry|Verify)Request cookie. */
+ dtlsTimer timers[3]; /* Holder for timers. */
+ dtlsTimer *rtTimer; /* Retransmit timer. */
+ dtlsTimer *ackTimer; /* Ack timer (DTLS 1.3 only). */
+ dtlsTimer *hdTimer; /* Read cipher holddown timer (DLTS 1.3 only) */
+ PRUint32 rtRetries; /* The retry counter */
+ SECItem srvVirtName; /* for server: name that was negotiated
+ * with a client. For client - is
+ * always set to NULL.*/
+
+ /* This group of values is used for TLS 1.3 and above */
+ PK11SymKey *currentSecret; /* The secret down the "left hand side"
+ * of the TLS 1.3 key schedule. */
+ PK11SymKey *resumptionMasterSecret; /* The resumption_master_secret. */
+ PK11SymKey *dheSecret; /* The (EC)DHE shared secret. */
+ PK11SymKey *clientEarlyTrafficSecret; /* The secret we use for 0-RTT. */
+ PK11SymKey *clientHsTrafficSecret; /* The source keys for handshake */
+ PK11SymKey *serverHsTrafficSecret; /* traffic keys. */
+ PK11SymKey *clientTrafficSecret; /* The source keys for application */
+ PK11SymKey *serverTrafficSecret; /* traffic keys */
+ PK11SymKey *earlyExporterSecret; /* for 0-RTT exporters */
+ PK11SymKey *exporterSecret; /* for exporters */
+ PRCList cipherSpecs; /* The cipher specs in the sequence they
+ * will be applied. */
+ sslZeroRttState zeroRttState; /* Are we doing a 0-RTT handshake? */
+ sslZeroRttIgnore zeroRttIgnore; /* Are we ignoring 0-RTT? */
+ ssl3CipherSuite zeroRttSuite; /* The cipher suite we used for 0-RTT. */
+ PRCList bufferedEarlyData; /* Buffered TLS 1.3 early data
+ * on server.*/
+ PRBool helloRetry; /* True if HelloRetryRequest has been sent
+ * or received. */
+ PRBool receivedCcs; /* A server received ChangeCipherSpec
+ * before the handshake started. */
+ PRBool rejectCcs; /* Excessive ChangeCipherSpecs are rejected. */
+ PRBool clientCertRequested; /* True if CertificateRequest received. */
+ PRBool endOfFlight; /* Processed a full flight (DTLS 1.3). */
+ ssl3KEADef kea_def_mutable; /* Used to hold the writable kea_def
+ * we use for TLS 1.3 */
+ PRUint16 ticketNonce; /* A counter we use for tickets. */
+ SECItem fakeSid; /* ... (server) the SID the client used. */
+ PRCList psks; /* A list of PSKs, resumption and/or external. */
+
+ /* rttEstimate is used to guess the round trip time between server and client.
+ * When the server sends ServerHello it sets this to the current time.
+ * Only after it receives a message from the client's second flight does it
+ * set the value to something resembling an RTT estimate. */
+ PRTime rttEstimate;
+
+ /* The following lists contain DTLSHandshakeRecordEntry */
+ PRCList dtlsSentHandshake; /* Used to map records to handshake fragments. */
+ PRCList dtlsRcvdHandshake; /* Handshake records we have received
+ * used to generate ACKs. */
+
+ /* TLS 1.3 ECH state. */
+ PRUint8 greaseEchSize;
+ PRBool echAccepted; /* Client/Server: True if we've commited to using CHInner. */
+ PRBool echDecided;
+ HpkeContext *echHpkeCtx; /* Client/Server: HPKE context for ECH. */
+ const char *echPublicName; /* Client: If rejected, the ECHConfig.publicName to
+ * use for certificate verification. */
+ sslBuffer greaseEchBuf; /* Client: Remember GREASE ECH, as advertised, for CH2 (HRR case).
+ Server: Remember HRR Grease Value, for transcript calculations */
+ PRBool echInvalidExtension; /* Client: True if the server offered an invalid extension for the ClientHelloInner */
+
+ /* TLS 1.3 GREASE state. */
+ tls13ClientGrease *grease;
+
+ /* ClientHello Extension Permutation state. */
+ sslExtensionBuilder *chExtensionPermutation;
+} SSL3HandshakeState;
+
+#define SSL_ASSERT_HASHES_EMPTY(ss) \
+ do { \
+ PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); \
+ PORT_Assert(ss->ssl3.hs.messages.len == 0); \
+ PORT_Assert(ss->ssl3.hs.echInnerMessages.len == 0); \
+ } while (0)
+
+/*
+** This is the "ssl3" struct, as in "ss->ssl3".
+** note:
+** usually, crSpec == cwSpec and prSpec == pwSpec.
+** Sometimes, crSpec == pwSpec and prSpec == cwSpec.
+** But there are never more than 2 actual specs.
+** No spec must ever be modified if either "current" pointer points to it.
+*/
+struct ssl3StateStr {
+
+ /*
+ ** The following Specs and Spec pointers must be protected using the
+ ** Spec Lock.
+ */
+ ssl3CipherSpec *crSpec; /* current read spec. */
+ ssl3CipherSpec *prSpec; /* pending read spec. */
+ ssl3CipherSpec *cwSpec; /* current write spec. */
+ ssl3CipherSpec *pwSpec; /* pending write spec. */
+
+ /* This is true after the peer requests a key update; false after a key
+ * update is initiated locally. */
+ PRBool peerRequestedKeyUpdate;
+
+ /* This is true if we deferred sending a key update as
+ * post-handshake auth is in progress. */
+ PRBool keyUpdateDeferred;
+ tls13KeyUpdateRequest deferredKeyUpdateRequest;
+
+ /* This is true after the server requests client certificate;
+ * false after the client certificate is received. Used by the
+ * server. */
+ PRBool clientCertRequested;
+
+ CERTCertificate *clientCertificate; /* used by client */
+ SECKEYPrivateKey *clientPrivateKey; /* used by client */
+ CERTCertificateList *clientCertChain; /* used by client */
+ PRBool sendEmptyCert; /* used by client */
+
+ PRUint8 policy;
+ /* This says what cipher suites we can do, and should
+ * be either SSL_ALLOWED or SSL_RESTRICTED
+ */
+ PLArenaPool *peerCertArena;
+ /* These are used to keep track of the peer CA */
+ void *peerCertChain;
+ /* chain while we are trying to validate it. */
+ CERTDistNames *ca_list;
+ /* used by server. trusted CAs for this socket. */
+ SSL3HandshakeState hs;
+
+ PRUint16 mtu; /* Our estimate of the MTU */
+
+ /* DTLS-SRTP cipher suite preferences (if any) */
+ PRUint16 dtlsSRTPCiphers[MAX_DTLS_SRTP_CIPHER_SUITES];
+ PRUint16 dtlsSRTPCipherCount;
+ PRBool fatalAlertSent;
+ PRBool dheWeakGroupEnabled; /* used by server */
+ const sslNamedGroupDef *dhePreferredGroup;
+
+ /* TLS 1.2 introduces separate signature algorithm negotiation.
+ * TLS 1.3 combined signature and hash into a single enum.
+ * This is our preference order. */
+ SSLSignatureScheme signatureSchemes[MAX_SIGNATURE_SCHEMES];
+ unsigned int signatureSchemeCount;
+
+ /* The version to check if we fell back from our highest version
+ * of TLS. Default is 0 in which case we check against the maximum
+ * configured version for this socket. Used only on the client. */
+ SSL3ProtocolVersion downgradeCheckVersion;
+};
+
+/* Ethernet MTU but without subtracting the headers,
+ * so slightly larger than expected */
+#define DTLS_MAX_MTU 1500U
+#define IS_DTLS(ss) (ss->protocolVariant == ssl_variant_datagram)
+
+typedef struct {
+ /* |seqNum| eventually contains the reconstructed sequence number. */
+ sslSequenceNumber seqNum;
+ /* The header of the cipherText. */
+ PRUint8 *hdr;
+ unsigned int hdrLen;
+
+ /* |buf| is the payload of the ciphertext. */
+ sslBuffer *buf;
+} SSL3Ciphertext;
+
+struct sslKeyPairStr {
+ SECKEYPrivateKey *privKey;
+ SECKEYPublicKey *pubKey;
+ PRInt32 refCount; /* use PR_Atomic calls for this. */
+};
+
+struct sslEphemeralKeyPairStr {
+ PRCList link;
+ const sslNamedGroupDef *group;
+ sslKeyPair *keys;
+};
+
+struct ssl3DHParamsStr {
+ SSLNamedGroup name;
+ SECItem prime; /* p */
+ SECItem base; /* g */
+};
+
+typedef struct SSLWrappedSymWrappingKeyStr {
+ PRUint8 wrappedSymmetricWrappingkey[SSL_MAX_RSA_KEY_BITS / 8];
+ CK_MECHANISM_TYPE symWrapMechanism;
+ /* unwrapped symmetric wrapping key uses this mechanism */
+ CK_MECHANISM_TYPE asymWrapMechanism;
+ /* mechanism used to wrap the SymmetricWrappingKey using
+ * server's public and/or private keys. */
+ PRInt16 wrapMechIndex;
+ PRUint16 wrapKeyIndex;
+ PRUint16 wrappedSymKeyLen;
+} SSLWrappedSymWrappingKey;
+
+typedef struct SessionTicketStr {
+ PRBool valid;
+ SSL3ProtocolVersion ssl_version;
+ ssl3CipherSuite cipher_suite;
+ SSLAuthType authType;
+ PRUint32 authKeyBits;
+ SSLKEAType keaType;
+ PRUint32 keaKeyBits;
+ SSLNamedGroup originalKeaGroup;
+ SSLSignatureScheme signatureScheme;
+ const sslNamedGroupDef *namedCurve; /* For certificate lookup. */
+
+ /*
+ * msWrapMech contains a meaningful value only if ms_is_wrapped is true.
+ */
+ PRUint8 ms_is_wrapped;
+ CK_MECHANISM_TYPE msWrapMech;
+ PRUint16 ms_length;
+ PRUint8 master_secret[48];
+ PRBool extendedMasterSecretUsed;
+ ClientAuthenticationType client_auth_type;
+ SECItem peer_cert;
+ PRTime timestamp;
+ PRUint32 flags;
+ SECItem srvName; /* negotiated server name */
+ SECItem alpnSelection;
+ PRUint32 maxEarlyData;
+ PRUint32 ticketAgeBaseline;
+ SECItem applicationToken;
+} SessionTicket;
+
+/*
+ * SSL2 buffers used in SSL3.
+ * writeBuf in the SecurityInfo maintained by sslsecur.c is used
+ * to hold the data just about to be passed to the kernel
+ * sendBuf in the ConnectInfo maintained by sslcon.c is used
+ * to hold handshake messages as they are accumulated
+ */
+
+/*
+** This is "ci", as in "ss->sec.ci".
+**
+** Protection: All the variables in here are protected by
+** firstHandshakeLock AND ssl3HandshakeLock
+*/
+struct sslConnectInfoStr {
+ /* outgoing handshakes appended to this. */
+ sslBuffer sendBuf; /*xmitBufLock*/
+
+ PRIPv6Addr peer;
+ unsigned short port;
+
+ sslSessionID *sid;
+};
+
+/* Note: The entire content of this struct and whatever it points to gets
+ * blown away by SSL_ResetHandshake(). This is "sec" as in "ss->sec".
+ *
+ * Unless otherwise specified below, the contents of this struct are
+ * protected by firstHandshakeLock AND ssl3HandshakeLock.
+ */
+struct sslSecurityInfoStr {
+
+#define SSL_ROLE(ss) (ss->sec.isServer ? "server" : "client")
+
+ PRBool isServer;
+ sslBuffer writeBuf; /*xmitBufLock*/
+
+ CERTCertificate *localCert;
+ CERTCertificate *peerCert;
+ SECKEYPublicKey *peerKey;
+
+ SSLAuthType authType;
+ PRUint32 authKeyBits;
+ SSLSignatureScheme signatureScheme;
+ SSLKEAType keaType;
+ PRUint32 keaKeyBits;
+ const sslNamedGroupDef *keaGroup;
+ const sslNamedGroupDef *originalKeaGroup;
+ /* The selected certificate (for servers only). */
+ const sslServerCert *serverCert;
+
+ /* These are used during a connection handshake */
+ sslConnectInfo ci;
+};
+
+/*
+** SSL Socket struct
+**
+** Protection: XXX
+*/
+struct sslSocketStr {
+ PRFileDesc *fd;
+
+ /* Pointer to operations vector for this socket */
+ const sslSocketOps *ops;
+
+ /* SSL socket options */
+ sslOptions opt;
+ /* Enabled version range */
+ SSLVersionRange vrange;
+
+ /* A function that returns the current time. */
+ SSLTimeFunc now;
+ void *nowArg;
+
+ /* State flags */
+ unsigned long clientAuthRequested;
+ unsigned long delayDisabled; /* Nagle delay disabled */
+ unsigned long firstHsDone; /* first handshake is complete. */
+ unsigned long enoughFirstHsDone; /* enough of the first handshake is
+ * done for callbacks to be able to
+ * retrieve channel security
+ * parameters from the SSL socket. */
+ unsigned long handshakeBegun;
+ unsigned long lastWriteBlocked;
+ unsigned long recvdCloseNotify; /* received SSL EOF. */
+ unsigned long TCPconnected;
+ unsigned long appDataBuffered;
+ unsigned long peerRequestedProtection; /* from old renegotiation */
+
+ /* version of the protocol to use */
+ SSL3ProtocolVersion version;
+ SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. */
+
+ sslSecurityInfo sec; /* not a pointer any more */
+
+ /* protected by firstHandshakeLock AND ssl3HandshakeLock. */
+ const char *url;
+
+ sslHandshakeFunc handshake; /*firstHandshakeLock*/
+
+ /* the following variable is only used with socks or other proxies. */
+ char *peerID; /* String uniquely identifies target server. */
+
+ /* ECDHE and DHE keys: In TLS 1.3, we might have to maintain multiple of
+ * these on the client side. The server inserts a single value into this
+ * list for all versions. */
+ PRCList /*<sslEphemeralKeyPair>*/ ephemeralKeyPairs;
+
+ /* Callbacks */
+ SSLAuthCertificate authCertificate;
+ void *authCertificateArg;
+ SSLGetClientAuthData getClientAuthData;
+ void *getClientAuthDataArg;
+ SSLSNISocketConfig sniSocketConfig;
+ void *sniSocketConfigArg;
+ SSLAlertCallback alertReceivedCallback;
+ void *alertReceivedCallbackArg;
+ SSLAlertCallback alertSentCallback;
+ void *alertSentCallbackArg;
+ SSLBadCertHandler handleBadCert;
+ void *badCertArg;
+ SSLHandshakeCallback handshakeCallback;
+ void *handshakeCallbackData;
+ SSLCanFalseStartCallback canFalseStartCallback;
+ void *canFalseStartCallbackData;
+ void *pkcs11PinArg;
+ SSLNextProtoCallback nextProtoCallback;
+ void *nextProtoArg;
+ SSLHelloRetryRequestCallback hrrCallback;
+ void *hrrCallbackArg;
+ PRCList extensionHooks;
+ SSLResumptionTokenCallback resumptionTokenCallback;
+ void *resumptionTokenContext;
+ SSLSecretCallback secretCallback;
+ void *secretCallbackArg;
+ SSLRecordWriteCallback recordWriteCallback;
+ void *recordWriteCallbackArg;
+
+ PRIntervalTime rTimeout; /* timeout for NSPR I/O */
+ PRIntervalTime wTimeout; /* timeout for NSPR I/O */
+ PRIntervalTime cTimeout; /* timeout for NSPR I/O */
+
+ PZLock *recvLock; /* lock against multiple reader threads. */
+ PZLock *sendLock; /* lock against multiple sender threads. */
+
+ PZMonitor *recvBufLock; /* locks low level recv buffers. */
+ PZMonitor *xmitBufLock; /* locks low level xmit buffers. */
+
+ /* Only one thread may operate on the socket until the initial handshake
+ ** is complete. This Monitor ensures that. Since SSL2 handshake is
+ ** only done once, this is also effectively the SSL2 handshake lock.
+ */
+ PZMonitor *firstHandshakeLock;
+
+ /* This monitor protects the ssl3 handshake state machine data.
+ ** Only one thread (reader or writer) may be in the ssl3 handshake state
+ ** machine at any time. */
+ PZMonitor *ssl3HandshakeLock;
+
+ /* reader/writer lock, protects the secret data needed to encrypt and MAC
+ ** outgoing records, and to decrypt and MAC check incoming ciphertext
+ ** records. */
+ NSSRWLock *specLock;
+
+ /* handle to perm cert db (and implicitly to the temp cert db) used
+ ** with this socket.
+ */
+ CERTCertDBHandle *dbHandle;
+
+ PRThread *writerThread; /* thread holds SSL_LOCK_WRITER lock */
+
+ PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */
+
+ sslHandshakingType handshaking;
+
+ /* Gather object used for gathering data */
+ sslGather gs; /*recvBufLock*/
+
+ sslBuffer saveBuf; /*xmitBufLock*/
+ sslBuffer pendingBuf; /*xmitBufLock*/
+
+ /* Configuration state for server sockets */
+ /* One server cert and key for each authentication type. */
+ PRCList /* <sslServerCert> */ serverCerts;
+
+ ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED];
+
+ /* A list of groups that are sorted according to user preferences pointing
+ * to entries of ssl_named_groups. By default this list contains pointers
+ * to all elements in ssl_named_groups in the default order.
+ * This list also determines which groups are enabled. This
+ * starts with all being enabled and can be modified either by negotiation
+ * (in which case groups not supported by a peer are masked off), or by
+ * calling SSL_DHEGroupPrefSet().
+ * Note that renegotiation will ignore groups that were disabled in the
+ * first handshake.
+ */
+ const sslNamedGroupDef *namedGroupPreferences[SSL_NAMED_GROUP_COUNT];
+ /* The number of additional shares to generate for the TLS 1.3 ClientHello */
+ unsigned int additionalShares;
+
+ /* SSL3 state info. Formerly was a pointer */
+ ssl3State ssl3;
+
+ /*
+ * TLS extension related data.
+ */
+ /* True when the current session is a stateless resume. */
+ PRBool statelessResume;
+ TLSExtensionData xtnData;
+
+ /* Whether we are doing stream or datagram mode */
+ SSLProtocolVariant protocolVariant;
+
+ /* TLS 1.3 Encrypted Client Hello. */
+ PRCList echConfigs; /* Client/server: Must not change while hs
+ * is in-progress. */
+ SECKEYPublicKey *echPubKey; /* Server: The ECH keypair used in HPKE. */
+ SECKEYPrivateKey *echPrivKey; /* As above. */
+
+ /* Anti-replay for TLS 1.3 0-RTT. */
+ SSLAntiReplayContext *antiReplay;
+
+ /* An out-of-band PSK. */
+ sslPsk *psk;
+};
+
+struct sslSelfEncryptKeysStr {
+ PRCallOnceType setup;
+ PRUint8 keyName[SELF_ENCRYPT_KEY_NAME_LEN];
+ PK11SymKey *encKey;
+ PK11SymKey *macKey;
+};
+typedef struct sslSelfEncryptKeysStr sslSelfEncryptKeys;
+
+extern char ssl_debug;
+extern char ssl_trace;
+extern FILE *ssl_trace_iob;
+extern FILE *ssl_keylog_iob;
+extern PZLock *ssl_keylog_lock;
+static const PRUint32 ssl_ticket_lifetime = 2 * 24 * 60 * 60; // 2 days.
+
+extern const char *const ssl3_cipherName[];
+
+extern sslSessionIDLookupFunc ssl_sid_lookup;
+
+extern const sslNamedGroupDef ssl_named_groups[];
+
+/************************************************************************/
+
+SEC_BEGIN_PROTOS
+
+/* Internal initialization and installation of the SSL error tables */
+extern SECStatus ssl_Init(void);
+extern SECStatus ssl_InitializePRErrorTable(void);
+
+/* Implementation of ops for default (non socks, non secure) case */
+extern int ssl_DefConnect(sslSocket *ss, const PRNetAddr *addr);
+extern PRFileDesc *ssl_DefAccept(sslSocket *ss, PRNetAddr *addr);
+extern int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr);
+extern int ssl_DefListen(sslSocket *ss, int backlog);
+extern int ssl_DefShutdown(sslSocket *ss, int how);
+extern int ssl_DefClose(sslSocket *ss);
+extern int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
+extern int ssl_DefSend(sslSocket *ss, const unsigned char *buf,
+ int len, int flags);
+extern int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len);
+extern int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len);
+extern int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name);
+extern int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name);
+extern int ssl_DefGetsockopt(sslSocket *ss, PRSockOption optname,
+ void *optval, PRInt32 *optlen);
+extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname,
+ const void *optval, PRInt32 optlen);
+
+/* Implementation of ops for socks only case */
+extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr);
+extern PRFileDesc *ssl_SocksAccept(sslSocket *ss, PRNetAddr *addr);
+extern int ssl_SocksBind(sslSocket *ss, const PRNetAddr *addr);
+extern int ssl_SocksListen(sslSocket *ss, int backlog);
+extern int ssl_SocksGetsockname(sslSocket *ss, PRNetAddr *name);
+extern int ssl_SocksRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
+extern int ssl_SocksSend(sslSocket *ss, const unsigned char *buf,
+ int len, int flags);
+extern int ssl_SocksRead(sslSocket *ss, unsigned char *buf, int len);
+extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len);
+
+/* Implementation of ops for secure only case */
+extern int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *addr);
+extern PRFileDesc *ssl_SecureAccept(sslSocket *ss, PRNetAddr *addr);
+extern int ssl_SecureRecv(sslSocket *ss, unsigned char *buf,
+ int len, int flags);
+extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf,
+ int len, int flags);
+extern int ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len);
+extern int ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len);
+extern int ssl_SecureShutdown(sslSocket *ss, int how);
+extern int ssl_SecureClose(sslSocket *ss);
+
+/* Implementation of ops for secure socks case */
+extern int ssl_SecureSocksConnect(sslSocket *ss, const PRNetAddr *addr);
+extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr);
+extern PRFileDesc *ssl_FindTop(sslSocket *ss);
+
+/* Gather funcs. */
+extern sslGather *ssl_NewGather(void);
+extern SECStatus ssl3_InitGather(sslGather *gs);
+extern void ssl3_DestroyGather(sslGather *gs);
+extern SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss);
+
+extern SECStatus ssl_CreateSecurityInfo(sslSocket *ss);
+extern SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os);
+extern void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset);
+extern void ssl_DestroySecurityInfo(sslSecurityInfo *sec);
+
+extern void ssl_PrintBuf(const sslSocket *ss, const char *msg, const void *cp,
+ int len);
+extern void ssl_PrintKey(const sslSocket *ss, const char *msg, PK11SymKey *key);
+
+extern int ssl_SendSavedWriteData(sslSocket *ss);
+extern SECStatus ssl_SaveWriteData(sslSocket *ss,
+ const void *p, unsigned int l);
+extern SECStatus ssl_BeginClientHandshake(sslSocket *ss);
+extern SECStatus ssl_BeginServerHandshake(sslSocket *ss);
+extern SECStatus ssl_Do1stHandshake(sslSocket *ss);
+
+extern SECStatus ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret,
+ PRBool derive);
+extern void ssl_DestroyKeyMaterial(ssl3KeyMaterial *keyMaterial);
+extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server);
+extern sslSessionID *ssl_LookupSID(PRTime now, const PRIPv6Addr *addr,
+ PRUint16 port, const char *peerID,
+ const char *urlSvrName);
+extern void ssl_FreeSID(sslSessionID *sid);
+extern void ssl_DestroySID(sslSessionID *sid, PRBool freeIt);
+extern sslSessionID *ssl_ReferenceSID(sslSessionID *sid);
+
+extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in,
+ int len, int flags);
+
+extern PRBool ssl_FdIsBlocking(PRFileDesc *fd);
+
+extern PRBool ssl_SocketIsBlocking(sslSocket *ss);
+
+extern void ssl3_SetAlwaysBlock(sslSocket *ss);
+
+extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled);
+
+extern SECStatus ssl_FinishHandshake(sslSocket *ss);
+
+extern SECStatus ssl_CipherPolicySet(PRInt32 which, PRInt32 policy);
+
+extern SECStatus ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled);
+
+extern SECStatus ssl3_ConstrainRangeByPolicy(void);
+
+extern SECStatus ssl3_InitState(sslSocket *ss);
+extern SECStatus Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen,
+ unsigned int maxOutputLen, const unsigned char *input,
+ unsigned int inputLen);
+extern void ssl3_RestartHandshakeHashes(sslSocket *ss);
+typedef SECStatus (*sslUpdateHandshakeHashes)(sslSocket *ss,
+ const unsigned char *b,
+ unsigned int l);
+extern SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss,
+ const unsigned char *b,
+ unsigned int l);
+extern SECStatus ssl3_UpdatePostHandshakeHashes(sslSocket *ss,
+ const unsigned char *b,
+ unsigned int l);
+SECStatus
+ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType type,
+ PRUint32 dtlsSeq,
+ const PRUint8 *b, PRUint32 length,
+ sslUpdateHandshakeHashes cb);
+SECStatus ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType type,
+ const PRUint8 *b, PRUint32 length);
+SECStatus ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType type,
+ const PRUint8 *b, PRUint32 length);
+SECStatus ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType type,
+ const PRUint8 *b, PRUint32 length);
+SECStatus ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType type,
+ const PRUint8 *b, PRUint32 length);
+
+/* Returns PR_TRUE if we are still waiting for the server to complete its
+ * response to our client second round. Once we've received the Finished from
+ * the server then there is no need to check false start.
+ */
+extern PRBool ssl3_WaitingForServerSecondRound(sslSocket *ss);
+
+extern PRInt32 ssl3_SendRecord(sslSocket *ss, ssl3CipherSpec *cwSpec,
+ SSLContentType type,
+ const PRUint8 *pIn, PRInt32 nIn,
+ PRInt32 flags);
+
+/* Clear any PRCList, optionally calling f on the value. */
+void ssl_ClearPRCList(PRCList *list, void (*f)(void *));
+
+/*
+ * Make sure there is room in the write buffer for padding and
+ * cryptographic expansions.
+ */
+#define SSL3_BUFFER_FUDGE 100
+
+#define SSL_LOCK_READER(ss) \
+ if (ss->recvLock) \
+ PZ_Lock(ss->recvLock)
+#define SSL_UNLOCK_READER(ss) \
+ if (ss->recvLock) \
+ PZ_Unlock(ss->recvLock)
+#define SSL_LOCK_WRITER(ss) \
+ if (ss->sendLock) \
+ PZ_Lock(ss->sendLock)
+#define SSL_UNLOCK_WRITER(ss) \
+ if (ss->sendLock) \
+ PZ_Unlock(ss->sendLock)
+
+/* firstHandshakeLock -> recvBufLock */
+#define ssl_Get1stHandshakeLock(ss) \
+ { \
+ if (!ss->opt.noLocks) { \
+ PORT_Assert(PZ_InMonitor((ss)->firstHandshakeLock) || \
+ !ssl_HaveRecvBufLock(ss)); \
+ PZ_EnterMonitor((ss)->firstHandshakeLock); \
+ } \
+ }
+#define ssl_Release1stHandshakeLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ PZ_ExitMonitor((ss)->firstHandshakeLock); \
+ }
+#define ssl_Have1stHandshakeLock(ss) \
+ (PZ_InMonitor((ss)->firstHandshakeLock))
+
+/* ssl3HandshakeLock -> xmitBufLock */
+#define ssl_GetSSL3HandshakeLock(ss) \
+ { \
+ if (!ss->opt.noLocks) { \
+ PORT_Assert(!ssl_HaveXmitBufLock(ss)); \
+ PZ_EnterMonitor((ss)->ssl3HandshakeLock); \
+ } \
+ }
+#define ssl_ReleaseSSL3HandshakeLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ PZ_ExitMonitor((ss)->ssl3HandshakeLock); \
+ }
+#define ssl_HaveSSL3HandshakeLock(ss) \
+ (PZ_InMonitor((ss)->ssl3HandshakeLock))
+
+#define ssl_GetSpecReadLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ NSSRWLock_LockRead((ss)->specLock); \
+ }
+#define ssl_ReleaseSpecReadLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ NSSRWLock_UnlockRead((ss)->specLock); \
+ }
+/* NSSRWLock_HaveReadLock is not exported so there's no
+ * ssl_HaveSpecReadLock macro. */
+
+#define ssl_GetSpecWriteLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ NSSRWLock_LockWrite((ss)->specLock); \
+ }
+#define ssl_ReleaseSpecWriteLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ NSSRWLock_UnlockWrite((ss)->specLock); \
+ }
+#define ssl_HaveSpecWriteLock(ss) \
+ (NSSRWLock_HaveWriteLock((ss)->specLock))
+
+/* recvBufLock -> ssl3HandshakeLock -> xmitBufLock */
+#define ssl_GetRecvBufLock(ss) \
+ { \
+ if (!ss->opt.noLocks) { \
+ PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss)); \
+ PORT_Assert(!ssl_HaveXmitBufLock(ss)); \
+ PZ_EnterMonitor((ss)->recvBufLock); \
+ } \
+ }
+#define ssl_ReleaseRecvBufLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ PZ_ExitMonitor((ss)->recvBufLock); \
+ }
+#define ssl_HaveRecvBufLock(ss) \
+ (PZ_InMonitor((ss)->recvBufLock))
+
+/* xmitBufLock -> specLock */
+#define ssl_GetXmitBufLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ PZ_EnterMonitor((ss)->xmitBufLock); \
+ }
+#define ssl_ReleaseXmitBufLock(ss) \
+ { \
+ if (!ss->opt.noLocks) \
+ PZ_ExitMonitor((ss)->xmitBufLock); \
+ }
+#define ssl_HaveXmitBufLock(ss) \
+ (PZ_InMonitor((ss)->xmitBufLock))
+
+/* Placeholder value used in version ranges when SSL 3.0 and all
+ * versions of TLS are disabled.
+ */
+#define SSL_LIBRARY_VERSION_NONE 0
+
+/* SSL_LIBRARY_VERSION_MIN_SUPPORTED is the minimum version that this version
+ * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
+ * runtime to determine which versions are supported by the version of libssl
+ * in use.
+ */
+#define SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM SSL_LIBRARY_VERSION_TLS_1_1
+#define SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM SSL_LIBRARY_VERSION_3_0
+
+/* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version
+ * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
+ * runtime to determine which versions are supported by the version of libssl
+ * in use.
+ */
+#ifndef NSS_DISABLE_TLS_1_3
+#define SSL_LIBRARY_VERSION_MAX_SUPPORTED SSL_LIBRARY_VERSION_TLS_1_3
+#else
+#define SSL_LIBRARY_VERSION_MAX_SUPPORTED SSL_LIBRARY_VERSION_TLS_1_2
+#endif
+
+#define SSL_ALL_VERSIONS_DISABLED(vrange) \
+ ((vrange)->min == SSL_LIBRARY_VERSION_NONE)
+
+extern PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
+ SSL3ProtocolVersion version);
+
+/* These functions are called from secnav, even though they're "private". */
+
+extern int SSL_RestartHandshakeAfterCertReq(struct sslSocketStr *ss,
+ CERTCertificate *cert,
+ SECKEYPrivateKey *key,
+ CERTCertificateList *certChain);
+extern sslSocket *ssl_FindSocket(PRFileDesc *fd);
+extern void ssl_FreeSocket(struct sslSocketStr *ssl);
+extern SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level,
+ SSL3AlertDescription desc);
+extern SECStatus ssl3_DecodeError(sslSocket *ss);
+
+extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error);
+extern SECStatus ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate);
+
+/*
+ * for dealing with SSL 3.0 clients sending SSL 2.0 format hellos
+ */
+extern SECStatus ssl3_HandleV2ClientHello(
+ sslSocket *ss, unsigned char *buffer, unsigned int length, PRUint8 padding);
+
+SECStatus
+ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
+ PRBool realSid, PRUint16 version, PRBool isEchInner,
+ const sslBuffer *extensions, sslBuffer *preamble);
+SECStatus ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions);
+SECStatus ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type);
+
+/*
+ * input into the SSL3 machinery from the actualy network reading code
+ */
+SECStatus ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cipher);
+SECStatus ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
+ DTLSEpoch epoch,
+ sslSequenceNumber seqNum,
+ sslBuffer *databuf);
+SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize);
+
+int ssl3_GatherAppDataRecord(sslSocket *ss, int flags);
+int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags);
+
+/* Create a new ref counted key pair object from two keys. */
+extern sslKeyPair *ssl_NewKeyPair(SECKEYPrivateKey *privKey,
+ SECKEYPublicKey *pubKey);
+
+/* get a new reference (bump ref count) to an ssl3KeyPair. */
+extern sslKeyPair *ssl_GetKeyPairRef(sslKeyPair *keyPair);
+
+/* Decrement keypair's ref count and free if zero. */
+extern void ssl_FreeKeyPair(sslKeyPair *keyPair);
+
+extern sslEphemeralKeyPair *ssl_NewEphemeralKeyPair(
+ const sslNamedGroupDef *group,
+ SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey);
+extern sslEphemeralKeyPair *ssl_CopyEphemeralKeyPair(
+ sslEphemeralKeyPair *keyPair);
+extern void ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair *keyPair);
+extern sslEphemeralKeyPair *ssl_LookupEphemeralKeyPair(
+ sslSocket *ss, const sslNamedGroupDef *groupDef);
+extern PRBool ssl_HaveEphemeralKeyPair(const sslSocket *ss,
+ const sslNamedGroupDef *groupDef);
+extern void ssl_FreeEphemeralKeyPairs(sslSocket *ss);
+
+extern SECStatus ssl_AppendPaddedDHKeyShare(sslBuffer *buf,
+ const SECKEYPublicKey *pubKey,
+ PRBool appendLength);
+extern PRBool ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
+ const SSLSignatureScheme *peerSchemes,
+ unsigned int peerSchemeCount,
+ PRBool requireSha1,
+ PRBool slotDoesPss);
+extern const ssl3DHParams *ssl_GetDHEParams(const sslNamedGroupDef *groupDef);
+extern SECStatus ssl_SelectDHEGroup(sslSocket *ss,
+ const sslNamedGroupDef **groupDef);
+extern SECStatus ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
+ const ssl3DHParams *params,
+ sslEphemeralKeyPair **keyPair);
+extern PRBool ssl_IsValidDHEShare(const SECItem *dh_p, const SECItem *dh_Ys);
+extern SECStatus ssl_ValidateDHENamedGroup(sslSocket *ss,
+ const SECItem *dh_p,
+ const SECItem *dh_g,
+ const sslNamedGroupDef **groupDef,
+ const ssl3DHParams **dhParams);
+
+extern PRBool ssl_IsECCEnabled(const sslSocket *ss);
+extern PRBool ssl_IsDHEEnabled(const sslSocket *ss);
+
+/* Macro for finding a curve equivalent in strength to RSA key's */
+#define SSL_RSASTRENGTH_TO_ECSTRENGTH(s) \
+ ((s <= 1024) ? 160 \
+ : ((s <= 2048) ? 224 \
+ : ((s <= 3072) ? 256 \
+ : ((s <= 7168) ? 384 \
+ : 521))))
+
+extern const sslNamedGroupDef *ssl_LookupNamedGroup(SSLNamedGroup group);
+extern PRBool ssl_NamedGroupEnabled(const sslSocket *ss, const sslNamedGroupDef *group);
+extern SECStatus ssl_NamedGroup2ECParams(PLArenaPool *arena,
+ const sslNamedGroupDef *curve,
+ SECKEYECParams *params);
+extern const sslNamedGroupDef *ssl_ECPubKey2NamedGroup(
+ const SECKEYPublicKey *pubKey);
+
+extern const sslNamedGroupDef *ssl_GetECGroupForServerSocket(sslSocket *ss);
+extern void ssl_FilterSupportedGroups(sslSocket *ss);
+
+extern SECStatus ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool on);
+extern SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *on);
+
+extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on);
+extern SECStatus ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *on);
+
+extern SECStatus ssl3_SetPolicy(ssl3CipherSuite which, PRInt32 policy);
+extern SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *policy);
+
+extern void ssl3_InitSocketPolicy(sslSocket *ss);
+
+extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache);
+extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b,
+ PRUint32 length,
+ PRBool endOfRecord);
+
+extern void ssl3_DestroySSL3Info(sslSocket *ss);
+
+extern SECStatus ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b,
+ PRUint32 *length,
+ SSL3ProtocolVersion *version);
+extern SECStatus ssl3_NegotiateVersion(sslSocket *ss,
+ SSL3ProtocolVersion peerVersion,
+ PRBool allowLargerPeerVersion);
+extern SECStatus ssl_ClientSetCipherSuite(sslSocket *ss,
+ SSL3ProtocolVersion version,
+ ssl3CipherSuite suite,
+ PRBool initHashes);
+
+extern SECStatus ssl_GetPeerInfo(sslSocket *ss);
+
+/* ECDH functions */
+extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket *ss,
+ SECKEYPublicKey *svrPubKey);
+extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss,
+ PRUint8 *b, PRUint32 length);
+extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss,
+ PRUint8 *b, PRUint32 length,
+ sslKeyPair *serverKeys);
+extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss);
+extern SECStatus ssl_ImportECDHKeyShare(
+ SECKEYPublicKey *peerKey,
+ PRUint8 *b, PRUint32 length, const sslNamedGroupDef *curve);
+
+extern SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
+ PRUint8 *hashBuf,
+ unsigned int bufLen,
+ SSL3Hashes *hashes);
+extern SECStatus ssl3_AppendSignatureAndHashAlgorithm(
+ sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash);
+extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes,
+ PRUint8 **b, PRUint32 *length);
+extern SECStatus ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num,
+ PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length);
+extern SECStatus ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num,
+ PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length);
+extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i,
+ PRUint32 bytes, PRUint8 **b,
+ PRUint32 *length);
+extern SECStatus ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
+ PRBool isTls13,
+ SSLSignatureScheme *scheme);
+extern PRBool ssl_SignatureSchemeEnabled(const sslSocket *ss,
+ SSLSignatureScheme scheme);
+extern PRBool ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme);
+extern SECStatus ssl_CheckSignatureSchemeConsistency(
+ sslSocket *ss, SSLSignatureScheme scheme, CERTSubjectPublicKeyInfo *spki);
+extern SECStatus ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
+ SSLSignatureScheme **schemesOut,
+ unsigned int *numSchemesOut,
+ unsigned char **b,
+ unsigned int *len);
+extern SECStatus ssl_ConsumeSignatureScheme(
+ sslSocket *ss, PRUint8 **b, PRUint32 *length, SSLSignatureScheme *out);
+extern SECStatus ssl3_SignHashesWithPrivKey(SSL3Hashes *hash,
+ SECKEYPrivateKey *key,
+ SSLSignatureScheme scheme,
+ PRBool isTls,
+ SECItem *buf);
+extern SECStatus ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash,
+ SECKEYPrivateKey *key, SECItem *buf);
+extern SECStatus ssl_VerifySignedHashesWithPubKey(sslSocket *ss,
+ SECKEYPublicKey *spki,
+ SSLSignatureScheme scheme,
+ SSL3Hashes *hash,
+ SECItem *buf);
+extern SECStatus ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme,
+ SSL3Hashes *hash, SECItem *buf);
+extern SECStatus ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
+ PK11SymKey *secret);
+extern void ssl3_FreeSniNameArray(TLSExtensionData *xtnData);
+
+/* Hello Extension related routines. */
+extern void ssl3_SetSIDSessionTicket(sslSessionID *sid,
+ /*in/out*/ NewSessionTicket *session_ticket);
+SECStatus ssl3_EncodeSessionTicket(sslSocket *ss,
+ const NewSessionTicket *ticket,
+ const PRUint8 *appToken,
+ unsigned int appTokenLen,
+ PK11SymKey *secret, SECItem *ticket_data);
+SECStatus SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
+ unsigned int tokenLen);
+
+SECStatus ssl_MaybeSetSelfEncryptKeyPair(const sslKeyPair *keyPair);
+SECStatus ssl_GetSelfEncryptKeys(sslSocket *ss, unsigned char *keyName,
+ PK11SymKey **encKey, PK11SymKey **macKey);
+void ssl_ResetSelfEncryptKeys();
+
+extern SECStatus ssl3_ValidateAppProtocol(const unsigned char *data,
+ unsigned int length);
+
+/* Construct a new NSPR socket for the app to use */
+extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
+extern void ssl_FreePRSocket(PRFileDesc *fd);
+
+/* Internal config function so SSL3 can initialize the present state of
+ * various ciphers */
+extern unsigned int ssl3_config_match_init(sslSocket *);
+
+/* Return PR_TRUE if suite is usable. This if the suite is permitted by policy,
+ * enabled, has a certificate (as needed), has a viable key agreement method, is
+ * usable with the negotiated TLS version, and is otherwise usable. */
+PRBool ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
+ const SSLVersionRange *vrange, const sslSocket *ss);
+
+/* calls for accessing wrapping keys across processes. */
+extern SECStatus
+ssl_GetWrappingKey(unsigned int symWrapMechIndex,
+ unsigned int wrapKeyIndex, SSLWrappedSymWrappingKey *wswk);
+
+/* The caller passes in the new value it wants
+ * to set. This code tests the wrapped sym key entry in the file on disk.
+ * If it is uninitialized, this function writes the caller's value into
+ * the disk entry, and returns false.
+ * Otherwise, it overwrites the caller's wswk with the value obtained from
+ * the disk, and returns PR_TRUE.
+ * This is all done while holding the locks/semaphores necessary to make
+ * the operation atomic.
+ */
+extern SECStatus
+ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk);
+
+/* get rid of the symmetric wrapping key references. */
+extern SECStatus SSL3_ShutdownServerCache(void);
+
+extern SECStatus ssl_InitSymWrapKeysLock(void);
+
+extern SECStatus ssl_FreeSymWrapKeysLock(void);
+
+extern SECStatus ssl_InitSessionCacheLocks(PRBool lazyInit);
+
+extern SECStatus ssl_FreeSessionCacheLocks(void);
+
+CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg);
+SECStatus ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
+ PRUint16 version, PRUint16 *suitep);
+SECStatus ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
+ PRBool initHashes);
+SECStatus ssl3_InitHandshakeHashes(sslSocket *ss);
+void ssl3_CoalesceEchHandshakeHashes(sslSocket *ss);
+SECStatus ssl3_ServerCallSNICallback(sslSocket *ss);
+SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
+SECStatus ssl3_CompleteHandleCertificate(sslSocket *ss,
+ PRUint8 *b, PRUint32 length);
+void ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode);
+SECStatus ssl3_HandleNoCertificate(sslSocket *ss);
+SECStatus ssl3_SendEmptyCertificate(sslSocket *ss);
+void ssl3_CleanupPeerCerts(sslSocket *ss);
+SECStatus ssl3_SendCertificateStatus(sslSocket *ss);
+SECStatus ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey);
+SECStatus ssl3_HandleServerSpki(sslSocket *ss);
+SECStatus ssl3_AuthCertificate(sslSocket *ss);
+SECStatus ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b,
+ PRUint32 length);
+SECStatus ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
+ PRBool grease, sslBuffer *buf);
+SECStatus ssl3_EncodeFilteredSigAlgs(const sslSocket *ss,
+ const SSLSignatureScheme *schemes,
+ PRUint32 numSchemes, PRBool grease, sslBuffer *buf);
+SECStatus ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae, PRBool forCert,
+ unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
+ unsigned int *numFilteredSchemes);
+SECStatus ssl_GetCertificateRequestCAs(const sslSocket *ss,
+ unsigned int *calenp,
+ const SECItem **namesp,
+ unsigned int *nnamesp);
+SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b,
+ PRUint32 *length, CERTDistNames *ca_list);
+SECStatus ssl3_BeginHandleCertificateRequest(
+ sslSocket *ss, const SSLSignatureScheme *signatureSchemes,
+ unsigned int signatureSchemeCount, CERTDistNames *ca_list);
+SECStatus ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
+ const sslBuffer *extensionBuf,
+ sslBuffer *messageBuf);
+SECStatus ssl3_SendServerHello(sslSocket *ss);
+SECStatus ssl3_SendChangeCipherSpecsInt(sslSocket *ss);
+SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss,
+ ssl3CipherSpec *spec,
+ SSL3Hashes *hashes,
+ PRUint32 sender);
+SECStatus ssl_CreateECDHEphemeralKeyPair(const sslSocket *ss,
+ const sslNamedGroupDef *ecGroup,
+ sslEphemeralKeyPair **keyPair);
+SECStatus ssl_CreateStaticECDHEKey(sslSocket *ss,
+ const sslNamedGroupDef *ecGroup);
+SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
+SECStatus ssl3_GetNewRandom(SSL3Random random);
+PK11SymKey *ssl3_GetWrappingKey(sslSocket *ss,
+ PK11SlotInfo *masterSecretSlot,
+ CK_MECHANISM_TYPE masterWrapMech,
+ void *pwArg);
+SECStatus ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid,
+ PK11SymKey *secret);
+const ssl3CipherSuiteDef *ssl_LookupCipherSuiteDef(ssl3CipherSuite suite);
+const ssl3CipherSuiteCfg *ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite,
+ const ssl3CipherSuiteCfg *suites);
+PRBool ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
+ const SSLVersionRange *vrange);
+
+SECStatus ssl3_SelectServerCert(sslSocket *ss);
+SECStatus ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey,
+ CERTCertificate *cert,
+ void *pwArg,
+ PRBool *supportsRsaPss);
+SECStatus ssl_PickSignatureScheme(sslSocket *ss,
+ CERTCertificate *cert,
+ SECKEYPublicKey *pubKey,
+ SECKEYPrivateKey *privKey,
+ const SSLSignatureScheme *peerSchemes,
+ unsigned int peerSchemeCount,
+ PRBool requireSha1,
+ SSLSignatureScheme *schemPtr);
+SECStatus ssl_PickClientSignatureScheme(sslSocket *ss,
+ CERTCertificate *clientCertificate,
+ SECKEYPrivateKey *privKey,
+ const SSLSignatureScheme *schemes,
+ unsigned int numSchemes,
+ SSLSignatureScheme *schemePtr);
+SECOidTag ssl3_HashTypeToOID(SSLHashType hashType);
+SECOidTag ssl3_AuthTypeToOID(SSLAuthType hashType);
+SSLHashType ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme);
+SSLAuthType ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme);
+
+SECStatus ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes);
+SECStatus ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
+ SSLContentType contentType, sslBuffer *wrBuf,
+ PRBool *needsLength);
+PRBool ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
+ PRBool isTls13);
+
+/* Pull in DTLS functions */
+#include "dtlscon.h"
+
+/* Pull in TLS 1.3 functions */
+#include "tls13con.h"
+#include "dtls13con.h"
+
+/********************** misc calls *********************/
+
+#ifdef DEBUG
+extern void ssl3_CheckCipherSuiteOrderConsistency();
+#endif
+
+extern int ssl_MapLowLevelError(int hiLevelError);
+
+PRTime ssl_Time(const sslSocket *ss);
+PRBool ssl_TicketTimeValid(const sslSocket *ss, const NewSessionTicket *ticket);
+
+extern void SSL_AtomicIncrementLong(long *x);
+
+SECStatus ssl3_ApplyNSSPolicy(void);
+
+extern SECStatus
+ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
+ const char *label, unsigned int labelLen,
+ const unsigned char *val, unsigned int valLen,
+ unsigned char *out, unsigned int outLen);
+
+extern void
+ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret);
+
+PRBool ssl_AlpnTagAllowed(const sslSocket *ss, const SECItem *tag);
+
+#ifdef TRACE
+#define SSL_TRACE(msg) ssl_Trace msg
+#else
+#define SSL_TRACE(msg)
+#endif
+
+void ssl_Trace(const char *format, ...);
+
+void ssl_CacheExternalToken(sslSocket *ss);
+SECStatus ssl_DecodeResumptionToken(sslSessionID *sid, const PRUint8 *encodedTicket,
+ PRUint32 encodedTicketLen);
+PRBool ssl_IsResumptionTokenUsable(sslSocket *ss, sslSessionID *sid);
+
+/* unwrap helper function to handle the case where the wrapKey doesn't wind
+ * * up in the correct token for the master secret */
+PK11SymKey *ssl_unwrapSymKey(PK11SymKey *wrapKey,
+ CK_MECHANISM_TYPE wrapType, SECItem *param,
+ SECItem *wrappedKey,
+ CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
+ int keySize, CK_FLAGS keyFlags, void *pinArg);
+
+/* determine if the current ssl connection is operating in FIPS mode */
+PRBool ssl_isFIPS(sslSocket *ss);
+
+/* Experimental APIs. Remove when stable. */
+
+SECStatus SSLExp_SetResumptionTokenCallback(PRFileDesc *fd,
+ SSLResumptionTokenCallback cb,
+ void *ctx);
+SECStatus SSLExp_SetResumptionToken(PRFileDesc *fd, const PRUint8 *token,
+ unsigned int len);
+
+SECStatus SSLExp_GetResumptionTokenInfo(const PRUint8 *tokenData, unsigned int tokenLen,
+ SSLResumptionTokenInfo *token, unsigned int version);
+
+SECStatus SSLExp_DestroyResumptionTokenInfo(SSLResumptionTokenInfo *token);
+
+SECStatus SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb,
+ void *arg);
+SECStatus SSLExp_RecordLayerWriteCallback(PRFileDesc *fd,
+ SSLRecordWriteCallback write,
+ void *arg);
+SECStatus SSLExp_RecordLayerData(PRFileDesc *fd, PRUint16 epoch,
+ SSLContentType contentType,
+ const PRUint8 *data, unsigned int len);
+SECStatus SSLExp_GetCurrentEpoch(PRFileDesc *fd, PRUint16 *readEpoch,
+ PRUint16 *writeEpoch);
+
+#define SSLResumptionTokenVersion 2
+
+SECStatus SSLExp_MakeAead(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *secret,
+ const char *labelPrefix, unsigned int labelPrefixLen,
+ SSLAeadContext **ctx);
+
+SECStatus SSLExp_MakeVariantAead(PRUint16 version, PRUint16 cipherSuite, SSLProtocolVariant variant,
+ PK11SymKey *secret, const char *labelPrefix,
+ unsigned int labelPrefixLen, SSLAeadContext **ctx);
+SECStatus SSLExp_DestroyAead(SSLAeadContext *ctx);
+SECStatus SSLExp_AeadEncrypt(const SSLAeadContext *ctx, PRUint64 counter,
+ const PRUint8 *aad, unsigned int aadLen,
+ const PRUint8 *plaintext, unsigned int plaintextLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOut);
+SECStatus SSLExp_AeadDecrypt(const SSLAeadContext *ctx, PRUint64 counter,
+ const PRUint8 *aad, unsigned int aadLen,
+ const PRUint8 *plaintext, unsigned int plaintextLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOut);
+
+SECStatus SSLExp_HkdfExtract(PRUint16 version, PRUint16 cipherSuite,
+ PK11SymKey *salt, PK11SymKey *ikm, PK11SymKey **keyp);
+SECStatus SSLExp_HkdfExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ PK11SymKey **key);
+SECStatus SSLExp_HkdfVariantExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ SSLProtocolVariant variant, PK11SymKey **key);
+SECStatus
+SSLExp_HkdfExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE mech, unsigned int keySize,
+ PK11SymKey **keyp);
+SECStatus
+SSLExp_HkdfVariantExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE mech, unsigned int keySize,
+ SSLProtocolVariant variant, PK11SymKey **keyp);
+
+SECStatus SSLExp_SetDtls13VersionWorkaround(PRFileDesc *fd, PRBool enabled);
+
+SECStatus SSLExp_SetTimeFunc(PRFileDesc *fd, SSLTimeFunc f, void *arg);
+
+extern SECStatus ssl_CreateMaskingContextInner(PRUint16 version, PRUint16 cipherSuite,
+ SSLProtocolVariant variant,
+ PK11SymKey *secret,
+ const char *label,
+ unsigned int labelLen,
+ SSLMaskingContext **ctx);
+
+extern SECStatus ssl_CreateMaskInner(SSLMaskingContext *ctx, const PRUint8 *sample,
+ unsigned int sampleLen, PRUint8 *outMask,
+ unsigned int maskLen);
+
+extern SECStatus ssl_DestroyMaskingContextInner(SSLMaskingContext *ctx);
+
+SECStatus SSLExp_CreateMaskingContext(PRUint16 version, PRUint16 cipherSuite,
+ PK11SymKey *secret,
+ const char *label,
+ unsigned int labelLen,
+ SSLMaskingContext **ctx);
+
+SECStatus SSLExp_CreateVariantMaskingContext(PRUint16 version, PRUint16 cipherSuite,
+ SSLProtocolVariant variant,
+ PK11SymKey *secret,
+ const char *label,
+ unsigned int labelLen,
+ SSLMaskingContext **ctx);
+
+SECStatus SSLExp_CreateMask(SSLMaskingContext *ctx, const PRUint8 *sample,
+ unsigned int sampleLen, PRUint8 *mask,
+ unsigned int len);
+
+SECStatus SSLExp_DestroyMaskingContext(SSLMaskingContext *ctx);
+
+SECStatus SSLExp_EnableTls13GreaseEch(PRFileDesc *fd, PRBool enabled);
+SECStatus SSLExp_SetTls13GreaseEchSize(PRFileDesc *fd, PRUint8 size);
+
+SECStatus SSLExp_EnableTls13BackendEch(PRFileDesc *fd, PRBool enabled);
+SECStatus SSLExp_CallExtensionWriterOnEchInner(PRFileDesc *fd, PRBool enabled);
+
+SEC_END_PROTOS
+
+#if defined(XP_UNIX) || defined(XP_OS2)
+#define SSL_GETPID getpid
+#elif defined(WIN32)
+extern int __cdecl _getpid(void);
+#define SSL_GETPID _getpid
+#else
+#define SSL_GETPID() 0
+#endif
+
+#endif /* __sslimpl_h_ */
diff --git a/security/nss/lib/ssl/sslinfo.c b/security/nss/lib/ssl/sslinfo.c
new file mode 100644
index 0000000000..fe32565c66
--- /dev/null
+++ b/security/nss/lib/ssl/sslinfo.c
@@ -0,0 +1,578 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "pk11pub.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "tls13hkdf.h"
+#include "tls13psk.h"
+#include "tls13subcerts.h"
+
+SECStatus
+SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len)
+{
+ sslSocket *ss;
+ SSLChannelInfo inf;
+ sslSessionID *sid;
+
+ /* Check if we can properly return the length of data written and that
+ * we're not asked to return more information than we know how to provide.
+ */
+ if (!info || len < sizeof inf.length || len > sizeof inf) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelInfo",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ memset(&inf, 0, sizeof inf);
+ inf.length = PR_MIN(sizeof inf, len);
+
+ if (ss->opt.useSecurity && ss->enoughFirstHsDone) {
+ SSLCipherSuiteInfo cinfo;
+ SECStatus rv;
+
+ sid = ss->sec.ci.sid;
+ inf.protocolVersion = ss->version;
+ inf.authKeyBits = ss->sec.authKeyBits;
+ inf.keaKeyBits = ss->sec.keaKeyBits;
+
+ ssl_GetSpecReadLock(ss);
+ /* XXX The cipher suite should be in the specs and this
+ * function should get it from cwSpec rather than from the "hs".
+ * See bug 275744 comment 69 and bug 766137.
+ */
+ inf.cipherSuite = ss->ssl3.hs.cipher_suite;
+ ssl_ReleaseSpecReadLock(ss);
+ inf.compressionMethod = ssl_compression_null;
+ inf.compressionMethodName = "NULL";
+
+ /* Fill in the cipher details from the cipher suite. */
+ rv = SSL_GetCipherSuiteInfo(inf.cipherSuite,
+ &cinfo, sizeof(cinfo));
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code already set. */
+ }
+ inf.symCipher = cinfo.symCipher;
+ inf.macAlgorithm = cinfo.macAlgorithm;
+ /* Get these fromm |ss->sec| because that is accurate
+ * even with TLS 1.3 disaggregated cipher suites. */
+ inf.keaType = ss->sec.keaType;
+ inf.originalKeaGroup = ss->sec.originalKeaGroup
+ ? ss->sec.originalKeaGroup->name
+ : ssl_grp_none;
+ inf.keaGroup = ss->sec.keaGroup
+ ? ss->sec.keaGroup->name
+ : ssl_grp_none;
+ inf.keaKeyBits = ss->sec.keaKeyBits;
+ inf.authType = ss->sec.authType;
+ inf.authKeyBits = ss->sec.authKeyBits;
+ inf.signatureScheme = ss->sec.signatureScheme;
+ /* If this is a resumed session, signatureScheme isn't set in ss->sec.
+ * Use the signature scheme from the previous handshake. */
+ if (inf.signatureScheme == ssl_sig_none && sid->sigScheme) {
+ inf.signatureScheme = sid->sigScheme;
+ }
+ inf.resumed = ss->statelessResume || ss->ssl3.hs.isResuming;
+ if (inf.resumed) {
+ inf.pskType = ssl_psk_resume;
+ } else if (inf.authType == ssl_auth_psk) {
+ inf.pskType = ssl_psk_external;
+ } else {
+ inf.pskType = ssl_psk_none;
+ }
+ inf.peerDelegCred = tls13_IsVerifyingWithDelegatedCredential(ss);
+ inf.echAccepted = ss->ssl3.hs.echAccepted;
+
+ if (sid) {
+ unsigned int sidLen;
+
+ inf.creationTime = sid->creationTime / PR_USEC_PER_SEC;
+ inf.lastAccessTime = sid->lastAccessTime / PR_USEC_PER_SEC;
+ inf.expirationTime = sid->expirationTime / PR_USEC_PER_SEC;
+ inf.extendedMasterSecretUsed =
+ (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ||
+ sid->u.ssl3.keys.extendedMasterSecretUsed)
+ ? PR_TRUE
+ : PR_FALSE;
+
+ inf.earlyDataAccepted =
+ (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_done);
+ sidLen = sid->u.ssl3.sessionIDLength;
+ sidLen = PR_MIN(sidLen, sizeof inf.sessionID);
+ inf.sessionIDLength = sidLen;
+ memcpy(inf.sessionID, sid->u.ssl3.sessionID, sidLen);
+ inf.isFIPS = ssl_isFIPS(ss);
+ }
+ }
+
+ memcpy(info, &inf, inf.length);
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_GetPreliminaryChannelInfo(PRFileDesc *fd,
+ SSLPreliminaryChannelInfo *info,
+ PRUintn len)
+{
+ sslSocket *ss;
+ SSLPreliminaryChannelInfo inf;
+
+ /* Check if we can properly return the length of data written and that
+ * we're not asked to return more information than we know how to provide.
+ */
+ if (!info || len < sizeof inf.length || len > sizeof inf) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetPreliminaryChannelInfo",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ /* All fields MUST be zero initialized! */
+ memset(&inf, 0, sizeof(inf));
+ inf.length = PR_MIN(sizeof(inf), len);
+
+ inf.valuesSet = ss->ssl3.hs.preliminaryInfo;
+ inf.protocolVersion = ss->version;
+ inf.cipherSuite = ss->ssl3.hs.cipher_suite;
+ inf.canSendEarlyData = !ss->sec.isServer &&
+ (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
+ /* We shouldn't be able to send early data if the handshake is done. */
+ PORT_Assert(!ss->firstHsDone || !inf.canSendEarlyData);
+
+ if (ss->sec.ci.sid) {
+ PRUint32 ticketMaxEarlyData =
+ ss->sec.ci.sid->u.ssl3.locked.sessionTicket.max_early_data_size;
+
+ /* Resumption token info. */
+ inf.ticketSupportsEarlyData = (ticketMaxEarlyData > 0);
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ if (ss->statelessResume) {
+ inf.maxEarlyDataSize = ticketMaxEarlyData;
+ } else if (ss->psk) {
+ /* We may have cleared the handshake list, so check the socket.
+ * This is permissable since we only support one EPSK at a time. */
+ inf.maxEarlyDataSize = ss->psk->maxEarlyData;
+ }
+ }
+ }
+ inf.zeroRttCipherSuite = ss->ssl3.hs.zeroRttSuite;
+
+ inf.peerDelegCred = tls13_IsVerifyingWithDelegatedCredential(ss);
+ inf.authKeyBits = ss->sec.authKeyBits;
+ inf.signatureScheme = ss->sec.signatureScheme;
+ inf.echAccepted = ss->ssl3.hs.echAccepted;
+ /* Only expose this if the application should use it for verification. */
+ inf.echPublicName = (inf.echAccepted == PR_FALSE) ? ss->ssl3.hs.echPublicName : NULL;
+
+ memcpy(info, &inf, inf.length);
+ return SECSuccess;
+}
+
+/* name */
+#define CS_(x) x, #x
+#define CS(x) CS_(TLS_##x)
+
+/* legacy values for authAlgorithm */
+#define S_DSA "DSA", ssl_auth_dsa
+/* S_RSA is incorrect for signature-based suites */
+/* ECDH suites incorrectly report S_RSA or S_ECDSA */
+#define S_RSA "RSA", ssl_auth_rsa_decrypt
+#define S_ECDSA "ECDSA", ssl_auth_ecdsa
+#define S_PSK "PSK", ssl_auth_psk
+#define S_ANY "TLS 1.3", ssl_auth_tls13_any
+
+/* real authentication algorithm */
+#define A_DSA ssl_auth_dsa
+#define A_RSAD ssl_auth_rsa_decrypt
+#define A_RSAS ssl_auth_rsa_sign
+#define A_ECDSA ssl_auth_ecdsa
+#define A_ECDH_R ssl_auth_ecdh_rsa
+#define A_ECDH_E ssl_auth_ecdh_ecdsa
+#define A_PSK ssl_auth_psk
+/* Report ssl_auth_null for export suites that can't decide between
+ * ssl_auth_rsa_sign and ssl_auth_rsa_decrypt. */
+#define A_EXP ssl_auth_null
+#define A_ANY ssl_auth_tls13_any
+
+/* key exchange */
+#define K_DHE "DHE", ssl_kea_dh
+#define K_RSA "RSA", ssl_kea_rsa
+#define K_KEA "KEA", ssl_kea_kea
+#define K_ECDH "ECDH", ssl_kea_ecdh
+#define K_ECDHE "ECDHE", ssl_kea_ecdh
+#define K_ECDHE_PSK "ECDHE-PSK", ssl_kea_ecdh_psk
+#define K_DHE_PSK "DHE-PSK", ssl_kea_dh_psk
+#define K_ANY "TLS 1.3", ssl_kea_tls13_any
+
+/* record protection cipher */
+#define C_SEED "SEED", ssl_calg_seed
+#define C_CAMELLIA "CAMELLIA", ssl_calg_camellia
+#define C_AES "AES", ssl_calg_aes
+#define C_RC4 "RC4", ssl_calg_rc4
+#define C_RC2 "RC2", ssl_calg_rc2
+#define C_DES "DES", ssl_calg_des
+#define C_3DES "3DES", ssl_calg_3des
+#define C_NULL "NULL", ssl_calg_null
+#define C_SJ "SKIPJACK", ssl_calg_sj
+#define C_AESGCM "AES-GCM", ssl_calg_aes_gcm
+#define C_CHACHA20 "CHACHA20POLY1305", ssl_calg_chacha20
+
+/* "block cipher" sizes */
+#define B_256 256, 256, 256
+#define B_128 128, 128, 128
+#define B_3DES 192, 156, 112
+#define B_SJ 96, 80, 80
+#define B_DES 64, 56, 56
+#define B_56 128, 56, 56
+#define B_40 128, 40, 40
+#define B_0 0, 0, 0
+
+/* "mac algorithm" and size */
+#define M_AEAD_128 "AEAD", ssl_mac_aead, 128
+#define M_SHA384 "SHA384", ssl_hmac_sha384, 384
+#define M_SHA256 "SHA256", ssl_hmac_sha256, 256
+#define M_SHA "SHA1", ssl_mac_sha, 160
+#define M_MD5 "MD5", ssl_mac_md5, 128
+#define M_NULL "NULL", ssl_mac_null, 0
+
+/* flags: FIPS, exportable, nonstandard, reserved */
+#define F_FIPS_STD 1, 0, 0, 0
+#define F_FIPS_NSTD 1, 0, 1, 0
+#define F_NFIPS_STD 0, 0, 0, 0
+#define F_NFIPS_NSTD 0, 0, 1, 0 /* i.e., trash */
+#define F_EXPORT 0, 1, 0, 0 /* i.e., trash */
+
+// RFC 5705
+#define MAX_CONTEXT_LEN PR_UINT16_MAX - 1
+
+static const SSLCipherSuiteInfo suiteInfo[] = {
+ /* <------ Cipher suite --------------------> <auth> <KEA> <bulk cipher> <MAC> <FIPS> */
+ { 0, CS_(TLS_AES_128_GCM_SHA256), S_ANY, K_ANY, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_ANY, ssl_hash_sha256 },
+ { 0, CS_(TLS_CHACHA20_POLY1305_SHA256), S_ANY, K_ANY, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_ANY, ssl_hash_sha256 },
+ { 0, CS_(TLS_AES_256_GCM_SHA384), S_ANY, K_ANY, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_ANY, ssl_hash_sha384 },
+
+ { 0, CS(RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_RSAD, ssl_hash_sha256 },
+ { 0, CS(DHE_RSA_WITH_CHACHA20_POLY1305_SHA256), S_RSA, K_DHE, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_RSAS, ssl_hash_sha256 },
+
+ { 0, CS(DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, F_NFIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, F_NFIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, F_FIPS_STD, A_RSAS, ssl_hash_sha256 },
+ { 0, CS(DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, F_FIPS_STD, A_DSA, ssl_hash_sha256 },
+ { 0, CS(RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, F_NFIPS_STD, A_RSAD, ssl_hash_none },
+ { 0, CS(RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, F_FIPS_STD, A_RSAD, ssl_hash_sha256 },
+ { 0, CS(RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, F_FIPS_STD, A_RSAD, ssl_hash_none },
+
+ { 0, CS(DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, F_NFIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, F_NFIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_RSAS, ssl_hash_sha256 },
+ { 0, CS(DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_RSAS, ssl_hash_sha256 },
+ { 0, CS(DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_AES_128_GCM_SHA256), S_DSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_DSA, ssl_hash_sha256 },
+ { 0, CS(DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_DSA, ssl_hash_sha256 },
+ { 0, CS(RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED, B_128, M_SHA, F_FIPS_STD, A_RSAD, ssl_hash_none },
+ { 0, CS(RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, F_NFIPS_STD, A_RSAD, ssl_hash_none },
+ { 0, CS(RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_RSAD, ssl_hash_none },
+ { 0, CS(RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, F_NFIPS_STD, A_RSAD, ssl_hash_none },
+ { 0, CS(RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, F_FIPS_STD, A_RSAD, ssl_hash_sha256 },
+ { 0, CS(RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, F_FIPS_STD, A_RSAD, ssl_hash_none },
+
+ { 0, CS(DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_RSAD, ssl_hash_none },
+
+ { 0, CS(DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, F_NFIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, F_NFIPS_STD, A_DSA, ssl_hash_none },
+ { 0, CS(RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, F_NFIPS_STD, A_RSAD, ssl_hash_none },
+
+ { 0, CS(RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL, B_0, M_SHA256, F_EXPORT, A_RSAD, ssl_hash_sha256 },
+ { 0, CS(RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL, B_0, M_SHA, F_EXPORT, A_RSAD, ssl_hash_none },
+ { 0, CS(RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL, B_0, M_MD5, F_EXPORT, A_RSAD, ssl_hash_none },
+
+ /* ECC cipher suites */
+ { 0, CS(ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_RSAS, ssl_hash_sha256 },
+ { 0, CS(ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_ECDSA, ssl_hash_sha256 },
+ { 0, CS(ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_ECDH_E, ssl_hash_none },
+ { 0, CS(ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_ECDH_E, ssl_hash_none },
+ { 0, CS(ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_ECDH_E, ssl_hash_none },
+ { 0, CS(ECDH_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, F_FIPS_STD, A_ECDH_E, ssl_hash_none },
+ { 0, CS(ECDH_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_256, M_SHA, F_FIPS_STD, A_ECDH_E, ssl_hash_none },
+
+ { 0, CS(ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_ECDSA, ssl_hash_none },
+ { 0, CS(ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_ECDSA, ssl_hash_none },
+ { 0, CS(ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_ECDSA, ssl_hash_none },
+ { 0, CS(ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_ECDSA, ssl_hash_none },
+ { 0, CS(ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_ECDSA, ssl_hash_sha256 },
+ { 0, CS(ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_ECDSA, ssl_hash_none },
+ { 0, CS(ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256), S_ECDSA, K_ECDHE, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_ECDSA, ssl_hash_sha256 },
+
+ { 0, CS(ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_ECDH_R, ssl_hash_none },
+ { 0, CS(ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_ECDH_R, ssl_hash_none },
+ { 0, CS(ECDH_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDH, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_ECDH_R, ssl_hash_none },
+ { 0, CS(ECDH_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDH, C_AES, B_128, M_SHA, F_FIPS_STD, A_ECDH_R, ssl_hash_none },
+ { 0, CS(ECDH_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDH, C_AES, B_256, M_SHA, F_FIPS_STD, A_ECDH_R, ssl_hash_none },
+
+ { 0, CS(ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_RSAS, ssl_hash_sha256 },
+ { 0, CS(ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_RSAS, ssl_hash_none },
+ { 0, CS(ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256), S_RSA, K_ECDHE, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_RSAS, ssl_hash_sha256 },
+ { 0, CS(ECDHE_RSA_WITH_AES_256_CBC_SHA384), S_RSA, K_ECDHE, C_AES, B_256, M_SHA384, F_FIPS_STD, A_RSAS, ssl_hash_sha384 },
+ { 0, CS(ECDHE_ECDSA_WITH_AES_256_CBC_SHA384), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA384, F_FIPS_STD, A_ECDSA, ssl_hash_sha384 },
+ { 0, CS(ECDHE_ECDSA_WITH_AES_256_GCM_SHA384), S_ECDSA, K_ECDHE, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_ECDSA, ssl_hash_sha384 },
+ { 0, CS(ECDHE_RSA_WITH_AES_256_GCM_SHA384), S_RSA, K_ECDHE, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_RSAS, ssl_hash_sha384 },
+
+ { 0, CS(DHE_DSS_WITH_AES_256_GCM_SHA384), S_DSA, K_DHE, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_DSA, ssl_hash_sha384 },
+ { 0, CS(DHE_RSA_WITH_AES_256_GCM_SHA384), S_RSA, K_DHE, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_RSAS, ssl_hash_sha384 },
+ { 0, CS(RSA_WITH_AES_256_GCM_SHA384), S_RSA, K_RSA, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_RSAD, ssl_hash_sha384 },
+};
+
+#define NUM_SUITEINFOS ((sizeof suiteInfo) / (sizeof suiteInfo[0]))
+
+SECStatus
+SSL_GetCipherSuiteInfo(PRUint16 cipherSuite,
+ SSLCipherSuiteInfo *info, PRUintn len)
+{
+ unsigned int i;
+
+ /* Check if we can properly return the length of data written and that
+ * we're not asked to return more information than we know how to provide.
+ */
+ if (!info || len < sizeof suiteInfo[0].length ||
+ len > sizeof suiteInfo[0]) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ len = PR_MIN(len, sizeof suiteInfo[0]);
+ for (i = 0; i < NUM_SUITEINFOS; i++) {
+ if (suiteInfo[i].cipherSuite == cipherSuite) {
+ memcpy(info, &suiteInfo[i], len);
+ info->length = len;
+ return SECSuccess;
+ }
+ }
+
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+}
+
+SECItem *
+SSL_GetNegotiatedHostInfo(PRFileDesc *fd)
+{
+ SECItem *sniName = NULL;
+ sslSocket *ss;
+ char *name = NULL;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNegotiatedHostInfo",
+ SSL_GETPID(), fd));
+ return NULL;
+ }
+
+ if (ss->sec.isServer) {
+ if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* TLS */
+ SECItem *crsName;
+ ssl_GetSpecReadLock(ss); /*********************************/
+ crsName = &ss->ssl3.hs.srvVirtName;
+ if (crsName->data) {
+ sniName = SECITEM_DupItem(crsName);
+ }
+ ssl_ReleaseSpecReadLock(ss); /*----------------------------*/
+ }
+ return sniName;
+ }
+ name = SSL_RevealURL(fd);
+ if (name) {
+ sniName = PORT_ZNew(SECItem);
+ if (!sniName) {
+ PORT_Free(name);
+ return NULL;
+ }
+ sniName->data = (void *)name;
+ sniName->len = PORT_Strlen(name);
+ }
+ return sniName;
+}
+
+/*
+ * HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
+ * "exporter", Hash(context_value), key_length)
+ */
+static SECStatus
+tls13_Exporter(sslSocket *ss, PK11SymKey *secret,
+ const char *label, unsigned int labelLen,
+ const unsigned char *context, unsigned int contextLen,
+ unsigned char *out, unsigned int outLen)
+{
+ SSL3Hashes contextHash;
+ PK11SymKey *innerSecret = NULL;
+ SECStatus rv;
+
+ static const char *kExporterInnerLabel = "exporter";
+
+ if (!secret) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SSLHashType hashAlg;
+ /* Early export requires a PSK. As in 0-RTT, default
+ * to the first PSK if no suite is negotiated yet. */
+ if (secret == ss->ssl3.hs.earlyExporterSecret && !ss->ssl3.hs.suite_def) {
+ if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ hashAlg = ((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->hash;
+ } else {
+ hashAlg = tls13_GetHash(ss);
+ }
+
+ /* Pre-hash the context. */
+ rv = tls13_ComputeHash(ss, &contextHash, context, contextLen, hashAlg);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ rv = tls13_DeriveSecretNullHash(ss, secret, label, labelLen,
+ &innerSecret, hashAlg);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ rv = tls13_HkdfExpandLabelRaw(innerSecret,
+ hashAlg,
+ contextHash.u.raw, contextHash.len,
+ kExporterInnerLabel,
+ strlen(kExporterInnerLabel),
+ ss->protocolVariant, out, outLen);
+ PK11_FreeSymKey(innerSecret);
+ return rv;
+}
+
+SECStatus
+SSL_ExportKeyingMaterial(PRFileDesc *fd,
+ const char *label, unsigned int labelLen,
+ PRBool hasContext,
+ const unsigned char *context, unsigned int contextLen,
+ unsigned char *out, unsigned int outLen)
+{
+ sslSocket *ss;
+ unsigned char *val = NULL;
+ unsigned int valLen, i;
+ SECStatus rv = SECFailure;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in ExportKeyingMaterial",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!label || !labelLen || !out || !outLen ||
+ (hasContext && (!context || !contextLen))) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ return tls13_Exporter(ss, ss->ssl3.hs.exporterSecret,
+ label, labelLen,
+ context, hasContext ? contextLen : 0,
+ out, outLen);
+ }
+
+ if (hasContext && contextLen > MAX_CONTEXT_LEN) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* construct PRF arguments */
+ valLen = SSL3_RANDOM_LENGTH * 2;
+ if (hasContext) {
+ valLen += 2 /* PRUint16 length */ + contextLen;
+ }
+ val = PORT_Alloc(valLen);
+ if (!val) {
+ return SECFailure;
+ }
+ i = 0;
+ PORT_Memcpy(val + i, ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH);
+ i += SSL3_RANDOM_LENGTH;
+ PORT_Memcpy(val + i, ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
+ i += SSL3_RANDOM_LENGTH;
+ if (hasContext) {
+ val[i++] = contextLen >> 8;
+ val[i++] = contextLen;
+ PORT_Memcpy(val + i, context, contextLen);
+ i += contextLen;
+ }
+ PORT_Assert(i == valLen);
+
+ /* Allow TLS keying material to be exported sooner, when the master
+ * secret is available and we have sent ChangeCipherSpec.
+ */
+ ssl_GetSpecReadLock(ss);
+ if (!ss->ssl3.cwSpec->masterSecret) {
+ PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
+ rv = SECFailure;
+ } else {
+ rv = ssl3_TLSPRFWithMasterSecret(ss, ss->ssl3.cwSpec, label, labelLen,
+ val, valLen, out, outLen);
+ }
+ ssl_ReleaseSpecReadLock(ss);
+
+ PORT_ZFree(val, valLen);
+ return rv;
+}
+
+SECStatus
+SSL_ExportEarlyKeyingMaterial(PRFileDesc *fd,
+ const char *label, unsigned int labelLen,
+ const unsigned char *context,
+ unsigned int contextLen,
+ unsigned char *out, unsigned int outLen)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_ExportEarlyKeyingMaterial",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!label || !labelLen || !out || !outLen ||
+ (!context && contextLen)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ return tls13_Exporter(ss, ss->ssl3.hs.earlyExporterSecret,
+ label, labelLen, context, contextLen,
+ out, outLen);
+}
diff --git a/security/nss/lib/ssl/sslinit.c b/security/nss/lib/ssl/sslinit.c
new file mode 100644
index 0000000000..07d57ce6ed
--- /dev/null
+++ b/security/nss/lib/ssl/sslinit.c
@@ -0,0 +1,60 @@
+/*
+ * NSS utility functions
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "prtypes.h"
+#include "prinit.h"
+#include "seccomon.h"
+#include "secerr.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+
+static int ssl_isInited = 0;
+static PRCallOnceType ssl_init = { 0 };
+PR_STATIC_ASSERT(sizeof(unsigned long) <= sizeof(PRUint64));
+
+PRStatus
+ssl_InitCallOnce(void *arg)
+{
+ int *error = (int *)arg;
+ SECStatus rv;
+
+ rv = ssl_InitializePRErrorTable();
+ if (rv != SECSuccess) {
+ *error = SEC_ERROR_NO_MEMORY;
+ return PR_FAILURE;
+ }
+#ifdef DEBUG
+ ssl3_CheckCipherSuiteOrderConsistency();
+#endif
+
+ rv = ssl3_ApplyNSSPolicy();
+ if (rv != SECSuccess) {
+ *error = PORT_GetError();
+ return PR_FAILURE;
+ }
+ return PR_SUCCESS;
+}
+
+SECStatus
+ssl_Init(void)
+{
+ PRStatus nrv;
+
+ /* short circuit test if we are already inited */
+ if (!ssl_isInited) {
+ int error;
+ /* only do this once at init time, block all others until we are done */
+ nrv = PR_CallOnceWithArg(&ssl_init, ssl_InitCallOnce, &error);
+ if (nrv != PR_SUCCESS) {
+ PORT_SetError(error);
+ return SECFailure;
+ }
+ ssl_isInited = 1;
+ }
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/sslmutex.c b/security/nss/lib/ssl/sslmutex.c
new file mode 100644
index 0000000000..0e3c37f072
--- /dev/null
+++ b/security/nss/lib/ssl/sslmutex.c
@@ -0,0 +1,658 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "seccomon.h"
+/* This ifdef should match the one in sslsnce.c */
+#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_OS2)
+
+#include "sslmutex.h"
+#include "prerr.h"
+
+static SECStatus
+single_process_sslMutex_Init(sslMutex* pMutex)
+{
+ PR_ASSERT(pMutex != 0 && pMutex->u.sslLock == 0);
+
+ pMutex->u.sslLock = PR_NewLock();
+ if (!pMutex->u.sslLock) {
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+single_process_sslMutex_Destroy(sslMutex* pMutex)
+{
+ PR_ASSERT(pMutex != 0);
+ PR_ASSERT(pMutex->u.sslLock != 0);
+ if (!pMutex->u.sslLock) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ PR_DestroyLock(pMutex->u.sslLock);
+ return SECSuccess;
+}
+
+static SECStatus
+single_process_sslMutex_Unlock(sslMutex* pMutex)
+{
+ PR_ASSERT(pMutex != 0);
+ PR_ASSERT(pMutex->u.sslLock != 0);
+ if (!pMutex->u.sslLock) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ PR_Unlock(pMutex->u.sslLock);
+ return SECSuccess;
+}
+
+static SECStatus
+single_process_sslMutex_Lock(sslMutex* pMutex)
+{
+ PR_ASSERT(pMutex != 0);
+ PR_ASSERT(pMutex->u.sslLock != 0);
+ if (!pMutex->u.sslLock) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ PR_Lock(pMutex->u.sslLock);
+ return SECSuccess;
+}
+
+#if defined(LINUX) || defined(AIX) || defined(BSDI) || \
+ (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD) || defined(__GLIBC__)
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <string.h>
+#include <errno.h>
+#include "unix_err.h"
+#include "pratom.h"
+
+#define SSL_MUTEX_MAGIC 0xfeedfd
+#define NONBLOCKING_POSTS 1 /* maybe this is faster */
+
+#if NONBLOCKING_POSTS
+
+#ifndef FNONBLOCK
+#define FNONBLOCK O_NONBLOCK
+#endif
+
+static int
+setNonBlocking(int fd, int nonBlocking)
+{
+ int flags;
+ int err;
+
+ flags = fcntl(fd, F_GETFL, 0);
+ if (0 > flags)
+ return flags;
+ if (nonBlocking)
+ flags |= FNONBLOCK;
+ else
+ flags &= ~FNONBLOCK;
+ err = fcntl(fd, F_SETFL, flags);
+ return err;
+}
+#endif
+
+SECStatus
+sslMutex_Init(sslMutex* pMutex, int shared)
+{
+ int err;
+ PR_ASSERT(pMutex);
+ pMutex->isMultiProcess = (PRBool)(shared != 0);
+ if (!shared) {
+ return single_process_sslMutex_Init(pMutex);
+ }
+ pMutex->u.pipeStr.mPipes[0] = -1;
+ pMutex->u.pipeStr.mPipes[1] = -1;
+ pMutex->u.pipeStr.mPipes[2] = -1;
+ pMutex->u.pipeStr.nWaiters = 0;
+
+ err = pipe(pMutex->u.pipeStr.mPipes);
+ if (err) {
+ nss_MD_unix_map_default_error(errno);
+ return err;
+ }
+#if NONBLOCKING_POSTS
+ err = setNonBlocking(pMutex->u.pipeStr.mPipes[1], 1);
+ if (err)
+ goto loser;
+#endif
+
+ pMutex->u.pipeStr.mPipes[2] = SSL_MUTEX_MAGIC;
+
+#if defined(LINUX) && defined(i386)
+ /* Pipe starts out empty */
+ return SECSuccess;
+#else
+ /* Pipe starts with one byte. */
+ return sslMutex_Unlock(pMutex);
+#endif
+
+loser:
+ nss_MD_unix_map_default_error(errno);
+ close(pMutex->u.pipeStr.mPipes[0]);
+ close(pMutex->u.pipeStr.mPipes[1]);
+ return SECFailure;
+}
+
+SECStatus
+sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal)
+{
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Destroy(pMutex);
+ }
+ if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ close(pMutex->u.pipeStr.mPipes[0]);
+ close(pMutex->u.pipeStr.mPipes[1]);
+
+ if (processLocal) {
+ return SECSuccess;
+ }
+
+ pMutex->u.pipeStr.mPipes[0] = -1;
+ pMutex->u.pipeStr.mPipes[1] = -1;
+ pMutex->u.pipeStr.mPipes[2] = -1;
+ pMutex->u.pipeStr.nWaiters = 0;
+
+ return SECSuccess;
+}
+
+#if defined(LINUX) && defined(i386)
+/* No memory barrier needed for this platform */
+
+/* nWaiters includes the holder of the lock (if any) and the number
+** threads waiting for it. After incrementing nWaiters, if the count
+** is exactly 1, then you have the lock and may proceed. If the
+** count is greater than 1, then you must wait on the pipe.
+*/
+
+SECStatus
+sslMutex_Unlock(sslMutex* pMutex)
+{
+ PRInt32 newValue;
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Unlock(pMutex);
+ }
+
+ if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ /* Do Memory Barrier here. */
+ newValue = PR_ATOMIC_DECREMENT(&pMutex->u.pipeStr.nWaiters);
+ if (newValue > 0) {
+ int cc;
+ char c = 1;
+ do {
+ cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1);
+ } while (cc < 0 && (errno == EINTR || errno == EAGAIN));
+ if (cc != 1) {
+ if (cc < 0)
+ nss_MD_unix_map_default_error(errno);
+ else
+ PORT_SetError(PR_UNKNOWN_ERROR);
+ return SECFailure;
+ }
+ }
+ return SECSuccess;
+}
+
+SECStatus
+sslMutex_Lock(sslMutex* pMutex)
+{
+ PRInt32 newValue;
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Lock(pMutex);
+ }
+
+ if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ newValue = PR_ATOMIC_INCREMENT(&pMutex->u.pipeStr.nWaiters);
+ /* Do Memory Barrier here. */
+ if (newValue > 1) {
+ int cc;
+ char c;
+ do {
+ cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1);
+ } while (cc < 0 && errno == EINTR);
+ if (cc != 1) {
+ if (cc < 0)
+ nss_MD_unix_map_default_error(errno);
+ else
+ PORT_SetError(PR_UNKNOWN_ERROR);
+ return SECFailure;
+ }
+ }
+ return SECSuccess;
+}
+
+#else
+
+/* Using Atomic operations requires the use of a memory barrier instruction
+** on PowerPC, Sparc, and Alpha. NSPR's PR_Atomic functions do not perform
+** them, and NSPR does not provide a function that does them (e.g. PR_Barrier).
+** So, we don't use them on those platforms.
+*/
+
+SECStatus
+sslMutex_Unlock(sslMutex* pMutex)
+{
+ int cc;
+ char c = 1;
+
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Unlock(pMutex);
+ }
+
+ if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ do {
+ cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1);
+ } while (cc < 0 && (errno == EINTR || errno == EAGAIN));
+ if (cc != 1) {
+ if (cc < 0)
+ nss_MD_unix_map_default_error(errno);
+ else
+ PORT_SetError(PR_UNKNOWN_ERROR);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+sslMutex_Lock(sslMutex* pMutex)
+{
+ int cc;
+ char c;
+
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Lock(pMutex);
+ }
+
+ if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+
+ do {
+ cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1);
+ } while (cc < 0 && errno == EINTR);
+ if (cc != 1) {
+ if (cc < 0)
+ nss_MD_unix_map_default_error(errno);
+ else
+ PORT_SetError(PR_UNKNOWN_ERROR);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+#endif
+
+#elif defined(WIN32)
+
+#include "win32err.h"
+
+/* on Windows, we need to find the optimal type of locking mechanism to use
+ for the sslMutex.
+
+ There are 3 cases :
+ 1) single-process, use a PRLock, as for all other platforms
+ 2) Win95 multi-process, use a Win32 mutex
+ 3) on WINNT multi-process, use a PRLock + a Win32 mutex
+
+*/
+
+#ifdef WINNT
+
+SECStatus
+sslMutex_2LevelInit(sslMutex *sem)
+{
+ /* the following adds a PRLock to sslMutex . This is done in each
+ process of a multi-process server and is only needed on WINNT, if
+ using fibers. We can't tell if native threads or fibers are used, so
+ we always do it on WINNT
+ */
+ PR_ASSERT(sem);
+ if (sem) {
+ /* we need to reset the sslLock in the children or the single_process init
+ function below will assert */
+ sem->u.sslLock = NULL;
+ }
+ return single_process_sslMutex_Init(sem);
+}
+
+static SECStatus
+sslMutex_2LevelDestroy(sslMutex *sem)
+{
+ return single_process_sslMutex_Destroy(sem);
+}
+
+#endif
+
+SECStatus
+sslMutex_Init(sslMutex *pMutex, int shared)
+{
+#ifdef WINNT
+ SECStatus retvalue;
+#endif
+ HANDLE hMutex;
+ SECURITY_ATTRIBUTES attributes = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
+
+ PR_ASSERT(pMutex != 0 && (pMutex->u.sslMutx == 0 ||
+ pMutex->u.sslMutx ==
+ INVALID_HANDLE_VALUE));
+
+ pMutex->isMultiProcess = (PRBool)(shared != 0);
+
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Init(pMutex);
+ }
+
+#ifdef WINNT
+ /* we need a lock on WINNT for fibers in the parent process */
+ retvalue = sslMutex_2LevelInit(pMutex);
+ if (SECSuccess != retvalue)
+ return SECFailure;
+#endif
+
+ if (!pMutex || ((hMutex = pMutex->u.sslMutx) != 0 &&
+ hMutex !=
+ INVALID_HANDLE_VALUE)) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ attributes.bInheritHandle = (shared ? TRUE : FALSE);
+ hMutex = CreateMutex(&attributes, FALSE, NULL);
+ if (hMutex == NULL) {
+ hMutex = INVALID_HANDLE_VALUE;
+ nss_MD_win32_map_default_error(GetLastError());
+ return SECFailure;
+ }
+ pMutex->u.sslMutx = hMutex;
+ return SECSuccess;
+}
+
+SECStatus
+sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal)
+{
+ HANDLE hMutex;
+ int rv;
+ int retvalue = SECSuccess;
+
+ PR_ASSERT(pMutex != 0);
+ if (!pMutex) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Destroy(pMutex);
+ }
+
+/* multi-process mode */
+#ifdef WINNT
+ /* on NT, get rid of the PRLock used for fibers within a process */
+ retvalue = sslMutex_2LevelDestroy(pMutex);
+#endif
+
+ PR_ASSERT(pMutex->u.sslMutx != 0 &&
+ pMutex->u.sslMutx != INVALID_HANDLE_VALUE);
+ if ((hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+
+ rv = CloseHandle(hMutex); /* ignore error */
+ if (!processLocal && rv) {
+ pMutex->u.sslMutx = hMutex = INVALID_HANDLE_VALUE;
+ }
+ if (!rv) {
+ nss_MD_win32_map_default_error(GetLastError());
+ retvalue = SECFailure;
+ }
+ return retvalue;
+}
+
+int
+sslMutex_Unlock(sslMutex *pMutex)
+{
+ BOOL success = FALSE;
+ HANDLE hMutex;
+
+ PR_ASSERT(pMutex != 0);
+ if (!pMutex) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Unlock(pMutex);
+ }
+
+ PR_ASSERT(pMutex->u.sslMutx != 0 &&
+ pMutex->u.sslMutx != INVALID_HANDLE_VALUE);
+ if ((hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+ success = ReleaseMutex(hMutex);
+ if (!success) {
+ nss_MD_win32_map_default_error(GetLastError());
+ return SECFailure;
+ }
+#ifdef WINNT
+ return single_process_sslMutex_Unlock(pMutex);
+/* release PRLock for other fibers in the process */
+#else
+ return SECSuccess;
+#endif
+}
+
+int
+sslMutex_Lock(sslMutex *pMutex)
+{
+ HANDLE hMutex;
+ DWORD event;
+ DWORD lastError;
+ SECStatus rv;
+ SECStatus retvalue = SECSuccess;
+
+ PR_ASSERT(pMutex != 0);
+ if (!pMutex) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure;
+ }
+
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Lock(pMutex);
+ }
+#ifdef WINNT
+ /* lock first to preserve from other threads/fibers in the same process */
+ retvalue = single_process_sslMutex_Lock(pMutex);
+#endif
+ PR_ASSERT(pMutex->u.sslMutx != 0 &&
+ pMutex->u.sslMutx != INVALID_HANDLE_VALUE);
+ if ((hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return SECFailure; /* what else ? */
+ }
+ /* acquire the mutex to be the only owner accross all other processes */
+ event = WaitForSingleObject(hMutex, INFINITE);
+ switch (event) {
+ case WAIT_OBJECT_0:
+ case WAIT_ABANDONED:
+ rv = SECSuccess;
+ break;
+
+ case WAIT_TIMEOUT:
+#if defined(WAIT_IO_COMPLETION)
+ case WAIT_IO_COMPLETION:
+#endif
+ default: /* should never happen. nothing we can do. */
+ PR_ASSERT(PR_FALSE && "WaitForSingleObject returned invalid value.");
+ PORT_SetError(PR_UNKNOWN_ERROR);
+ rv = SECFailure;
+ break;
+
+ case WAIT_FAILED: /* failure returns this */
+ rv = SECFailure;
+ lastError = GetLastError(); /* for debugging */
+ nss_MD_win32_map_default_error(lastError);
+ break;
+ }
+
+ if (!(SECSuccess == retvalue && SECSuccess == rv)) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+#elif defined(XP_UNIX) && !defined(DARWIN)
+
+#include <errno.h>
+#include "unix_err.h"
+
+SECStatus
+sslMutex_Init(sslMutex* pMutex, int shared)
+{
+ int rv;
+ PR_ASSERT(pMutex);
+ pMutex->isMultiProcess = (PRBool)(shared != 0);
+ if (!shared) {
+ return single_process_sslMutex_Init(pMutex);
+ }
+ do {
+ rv = sem_init(&pMutex->u.sem, shared, 1);
+ } while (rv < 0 && errno == EINTR);
+ if (rv < 0) {
+ nss_MD_unix_map_default_error(errno);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal)
+{
+ int rv;
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Destroy(pMutex);
+ }
+
+ /* semaphores are global resources. See SEM_DESTROY(3) man page */
+ if (processLocal) {
+ return SECSuccess;
+ }
+ do {
+ rv = sem_destroy(&pMutex->u.sem);
+ } while (rv < 0 && errno == EINTR);
+ if (rv < 0) {
+ nss_MD_unix_map_default_error(errno);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+sslMutex_Unlock(sslMutex* pMutex)
+{
+ int rv;
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Unlock(pMutex);
+ }
+ do {
+ rv = sem_post(&pMutex->u.sem);
+ } while (rv < 0 && errno == EINTR);
+ if (rv < 0) {
+ nss_MD_unix_map_default_error(errno);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+sslMutex_Lock(sslMutex* pMutex)
+{
+ int rv;
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Lock(pMutex);
+ }
+ do {
+ rv = sem_wait(&pMutex->u.sem);
+ } while (rv < 0 && errno == EINTR);
+ if (rv < 0) {
+ nss_MD_unix_map_default_error(errno);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+#else
+
+SECStatus
+sslMutex_Init(sslMutex* pMutex, int shared)
+{
+ PR_ASSERT(pMutex);
+ pMutex->isMultiProcess = (PRBool)(shared != 0);
+ if (!shared) {
+ return single_process_sslMutex_Init(pMutex);
+ }
+ PORT_Assert(PR_FALSE && "sslMutex_Init not implemented for multi-process applications !");
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return SECFailure;
+}
+
+SECStatus
+sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal)
+{
+ PR_ASSERT(pMutex);
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Destroy(pMutex);
+ }
+ PORT_Assert(PR_FALSE && "sslMutex_Destroy not implemented for multi-process applications !");
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return SECFailure;
+}
+
+SECStatus
+sslMutex_Unlock(sslMutex* pMutex)
+{
+ PR_ASSERT(pMutex);
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Unlock(pMutex);
+ }
+ PORT_Assert(PR_FALSE && "sslMutex_Unlock not implemented for multi-process applications !");
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return SECFailure;
+}
+
+SECStatus
+sslMutex_Lock(sslMutex* pMutex)
+{
+ PR_ASSERT(pMutex);
+ if (PR_FALSE == pMutex->isMultiProcess) {
+ return single_process_sslMutex_Lock(pMutex);
+ }
+ PORT_Assert(PR_FALSE && "sslMutex_Lock not implemented for multi-process applications !");
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return SECFailure;
+}
+
+#endif
+
+#endif
diff --git a/security/nss/lib/ssl/sslmutex.h b/security/nss/lib/ssl/sslmutex.h
new file mode 100644
index 0000000000..f99b4d0242
--- /dev/null
+++ b/security/nss/lib/ssl/sslmutex.h
@@ -0,0 +1,129 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef __SSLMUTEX_H_
+#define __SSLMUTEX_H_ 1
+
+/* What SSL really wants is portable process-shared unnamed mutexes in
+ * shared memory, that have the property that if the process that holds
+ * them dies, they are released automatically, and that (unlike fcntl
+ * record locking) lock to the thread, not to the process.
+ * NSPR doesn't provide that.
+ * Windows has mutexes that meet that description, but they're not portable.
+ * POSIX mutexes are not automatically released when the holder dies,
+ * and other processes/threads cannot release the mutex on behalf of the
+ * dead holder.
+ * POSIX semaphores can be used to accomplish this on systems that implement
+ * process-shared unnamed POSIX semaphores, because a watchdog thread can
+ * discover and release semaphores that were held by a dead process.
+ * On systems that do not support process-shared POSIX unnamed semaphores,
+ * they can be emulated using pipes.
+ * The performance cost of doing that is not yet measured.
+ *
+ * So, this API looks a lot like POSIX pthread mutexes.
+ */
+
+#include "prtypes.h"
+#include "prlock.h"
+
+#if defined(NETBSD)
+#include <sys/param.h> /* for __NetBSD_Version__ */
+#endif
+
+#if defined(WIN32)
+
+#include <wtypes.h>
+
+typedef struct {
+ PRBool isMultiProcess;
+#ifdef WINNT
+ /* on WINNT we need both the PRLock and the Win32 mutex for fibers */
+ struct {
+#else
+ union {
+#endif
+ PRLock *sslLock;
+ HANDLE sslMutx;
+ } u;
+} sslMutex;
+
+typedef int sslPID;
+
+#elif defined(LINUX) || defined(AIX) || defined(BSDI) || \
+ (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD) || defined(__GLIBC__)
+
+#include <sys/types.h>
+#include "prtypes.h"
+
+typedef struct {
+ PRBool isMultiProcess;
+ union {
+ PRLock *sslLock;
+ struct {
+ int mPipes[3];
+ PRInt32 nWaiters;
+ } pipeStr;
+ } u;
+} sslMutex;
+typedef pid_t sslPID;
+
+/* other types of unix, except OS X */
+#elif defined(XP_UNIX) && !defined(DARWIN)
+
+#include <sys/types.h> /* for pid_t */
+#include <semaphore.h> /* for sem_t, and sem_* functions */
+
+typedef struct {
+ PRBool isMultiProcess;
+ union {
+ PRLock *sslLock;
+ sem_t sem;
+ } u;
+} sslMutex;
+
+typedef pid_t sslPID;
+
+#else /* no support for cross-process locking */
+
+/* what platform is this ?? */
+
+typedef struct {
+ PRBool isMultiProcess;
+ union {
+ PRLock *sslLock;
+ /* include cross-process locking mechanism here */
+ } u;
+} sslMutex;
+
+#ifdef DARWIN
+typedef pid_t sslPID;
+#else
+typedef int sslPID;
+#endif
+
+#endif
+
+#include "seccomon.h"
+
+SEC_BEGIN_PROTOS
+
+extern SECStatus sslMutex_Init(sslMutex *sem, int shared);
+
+/* If processLocal is set to true, then just free resources which are *only* associated
+ * with the current process. Leave any shared resources (including the state of
+ * shared memory) intact. */
+extern SECStatus sslMutex_Destroy(sslMutex *sem, PRBool processLocal);
+
+extern SECStatus sslMutex_Unlock(sslMutex *sem);
+
+extern SECStatus sslMutex_Lock(sslMutex *sem);
+
+#ifdef WINNT
+
+extern SECStatus sslMutex_2LevelInit(sslMutex *sem);
+
+#endif
+
+SEC_END_PROTOS
+
+#endif
diff --git a/security/nss/lib/ssl/sslnonce.c b/security/nss/lib/ssl/sslnonce.c
new file mode 100644
index 0000000000..35f67a3514
--- /dev/null
+++ b/security/nss/lib/ssl/sslnonce.c
@@ -0,0 +1,1228 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file implements the CLIENT Session ID cache.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "cert.h"
+#include "pk11pub.h"
+#include "secitem.h"
+#include "ssl.h"
+#include "nss.h"
+
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "nssilock.h"
+#include "sslencode.h"
+#if defined(XP_UNIX) || defined(XP_WIN) || defined(_WINDOWS)
+#include <time.h>
+#endif
+
+static sslSessionID *cache = NULL;
+static PZLock *cacheLock = NULL;
+
+/* sids can be in one of 5 states:
+ *
+ * never_cached, created, but not yet put into cache.
+ * in_client_cache, in the client cache's linked list.
+ * in_server_cache, entry came from the server's cache file.
+ * invalid_cache has been removed from the cache.
+ * in_external_cache sid comes from an external cache.
+ */
+
+#define LOCK_CACHE lock_cache()
+#define UNLOCK_CACHE PZ_Unlock(cacheLock)
+
+static SECStatus
+ssl_InitClientSessionCacheLock(void)
+{
+ cacheLock = PZ_NewLock(nssILockCache);
+ return cacheLock ? SECSuccess : SECFailure;
+}
+
+static SECStatus
+ssl_FreeClientSessionCacheLock(void)
+{
+ if (cacheLock) {
+ PZ_DestroyLock(cacheLock);
+ cacheLock = NULL;
+ return SECSuccess;
+ }
+ PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+ return SECFailure;
+}
+
+static PRBool LocksInitializedEarly = PR_FALSE;
+
+static SECStatus
+FreeSessionCacheLocks()
+{
+ SECStatus rv1, rv2;
+ rv1 = ssl_FreeSymWrapKeysLock();
+ rv2 = ssl_FreeClientSessionCacheLock();
+ if ((SECSuccess == rv1) && (SECSuccess == rv2)) {
+ return SECSuccess;
+ }
+ return SECFailure;
+}
+
+static SECStatus
+InitSessionCacheLocks(void)
+{
+ SECStatus rv1, rv2;
+ PRErrorCode rc;
+ rv1 = ssl_InitSymWrapKeysLock();
+ rv2 = ssl_InitClientSessionCacheLock();
+ if ((SECSuccess == rv1) && (SECSuccess == rv2)) {
+ return SECSuccess;
+ }
+ rc = PORT_GetError();
+ FreeSessionCacheLocks();
+ PORT_SetError(rc);
+ return SECFailure;
+}
+
+/* free the session cache locks if they were initialized early */
+SECStatus
+ssl_FreeSessionCacheLocks()
+{
+ PORT_Assert(PR_TRUE == LocksInitializedEarly);
+ if (!LocksInitializedEarly) {
+ PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+ return SECFailure;
+ }
+ FreeSessionCacheLocks();
+ LocksInitializedEarly = PR_FALSE;
+ return SECSuccess;
+}
+
+static PRCallOnceType lockOnce;
+
+/* free the session cache locks if they were initialized lazily */
+static SECStatus
+ssl_ShutdownLocks(void *appData, void *nssData)
+{
+ PORT_Assert(PR_FALSE == LocksInitializedEarly);
+ if (LocksInitializedEarly) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ FreeSessionCacheLocks();
+ memset(&lockOnce, 0, sizeof(lockOnce));
+ return SECSuccess;
+}
+
+static PRStatus
+initSessionCacheLocksLazily(void)
+{
+ SECStatus rv = InitSessionCacheLocks();
+ if (SECSuccess != rv) {
+ return PR_FAILURE;
+ }
+ rv = NSS_RegisterShutdown(ssl_ShutdownLocks, NULL);
+ PORT_Assert(SECSuccess == rv);
+ if (SECSuccess != rv) {
+ return PR_FAILURE;
+ }
+ return PR_SUCCESS;
+}
+
+/* lazyInit means that the call is not happening during a 1-time
+ * initialization function, but rather during dynamic, lazy initialization
+ */
+SECStatus
+ssl_InitSessionCacheLocks(PRBool lazyInit)
+{
+ if (LocksInitializedEarly) {
+ return SECSuccess;
+ }
+
+ if (lazyInit) {
+ return (PR_SUCCESS ==
+ PR_CallOnce(&lockOnce, initSessionCacheLocksLazily))
+ ? SECSuccess
+ : SECFailure;
+ }
+
+ if (SECSuccess == InitSessionCacheLocks()) {
+ LocksInitializedEarly = PR_TRUE;
+ return SECSuccess;
+ }
+
+ return SECFailure;
+}
+
+static void
+lock_cache(void)
+{
+ ssl_InitSessionCacheLocks(PR_TRUE);
+ PZ_Lock(cacheLock);
+}
+
+/* BEWARE: This function gets called for both client and server SIDs !!
+ * If the unreferenced sid is not in the cache, Free sid and its contents.
+ */
+void
+ssl_DestroySID(sslSessionID *sid, PRBool freeIt)
+{
+ SSL_TRC(8, ("SSL: destroy sid: sid=0x%x cached=%d", sid, sid->cached));
+ PORT_Assert(sid->references == 0);
+ PORT_Assert(sid->cached != in_client_cache);
+
+ if (sid->u.ssl3.locked.sessionTicket.ticket.data) {
+ SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket,
+ PR_FALSE);
+ }
+ if (sid->u.ssl3.srvName.data) {
+ SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE);
+ }
+ if (sid->u.ssl3.signedCertTimestamps.data) {
+ SECITEM_FreeItem(&sid->u.ssl3.signedCertTimestamps, PR_FALSE);
+ }
+
+ if (sid->u.ssl3.lock) {
+ PR_DestroyRWLock(sid->u.ssl3.lock);
+ }
+
+ PORT_Free((void *)sid->peerID);
+ PORT_Free((void *)sid->urlSvrName);
+
+ if (sid->peerCert) {
+ CERT_DestroyCertificate(sid->peerCert);
+ }
+ if (sid->peerCertStatus.items) {
+ SECITEM_FreeArray(&sid->peerCertStatus, PR_FALSE);
+ }
+
+ if (sid->localCert) {
+ CERT_DestroyCertificate(sid->localCert);
+ }
+
+ SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE);
+
+ if (freeIt) {
+ PORT_ZFree(sid, sizeof(sslSessionID));
+ }
+}
+
+/* BEWARE: This function gets called for both client and server SIDs !!
+ * Decrement reference count, and
+ * free sid if ref count is zero, and sid is not in the cache.
+ * Does NOT remove from the cache first.
+ * If the sid is still in the cache, it is left there until next time
+ * the cache list is traversed.
+ */
+static void
+ssl_FreeLockedSID(sslSessionID *sid)
+{
+ PORT_Assert(sid->references >= 1);
+ if (--sid->references == 0) {
+ ssl_DestroySID(sid, PR_TRUE);
+ }
+}
+
+/* BEWARE: This function gets called for both client and server SIDs !!
+ * Decrement reference count, and
+ * free sid if ref count is zero, and sid is not in the cache.
+ * Does NOT remove from the cache first.
+ * These locks are necessary because the sid _might_ be in the cache list.
+ */
+void
+ssl_FreeSID(sslSessionID *sid)
+{
+ if (sid) {
+ LOCK_CACHE;
+ ssl_FreeLockedSID(sid);
+ UNLOCK_CACHE;
+ }
+}
+
+sslSessionID *
+ssl_ReferenceSID(sslSessionID *sid)
+{
+ LOCK_CACHE;
+ sid->references++;
+ UNLOCK_CACHE;
+ return sid;
+}
+
+/************************************************************************/
+
+/*
+** Lookup sid entry in cache by Address, port, and peerID string.
+** If found, Increment reference count, and return pointer to caller.
+** If it has timed out or ref count is zero, remove from list and free it.
+*/
+
+sslSessionID *
+ssl_LookupSID(PRTime now, const PRIPv6Addr *addr, PRUint16 port, const char *peerID,
+ const char *urlSvrName)
+{
+ sslSessionID **sidp;
+ sslSessionID *sid;
+
+ if (!urlSvrName)
+ return NULL;
+ LOCK_CACHE;
+ sidp = &cache;
+ while ((sid = *sidp) != 0) {
+ PORT_Assert(sid->cached == in_client_cache);
+ PORT_Assert(sid->references >= 1);
+
+ SSL_TRC(8, ("SSL: lookup: sid=0x%x", sid));
+
+ if (sid->expirationTime < now) {
+ /*
+ ** This session-id timed out.
+ ** Don't even care who it belongs to, blow it out of our cache.
+ */
+ SSL_TRC(7, ("SSL: lookup, throwing sid out, age=%d refs=%d",
+ now - sid->creationTime, sid->references));
+
+ *sidp = sid->next; /* delink it from the list. */
+ sid->cached = invalid_cache; /* mark not on list. */
+ ssl_FreeLockedSID(sid); /* drop ref count, free. */
+ } else if (!memcmp(&sid->addr, addr, sizeof(PRIPv6Addr)) && /* server IP addr matches */
+ (sid->port == port) && /* server port matches */
+ /* proxy (peerID) matches */
+ (((peerID == NULL) && (sid->peerID == NULL)) ||
+ ((peerID != NULL) && (sid->peerID != NULL) &&
+ PORT_Strcmp(sid->peerID, peerID) == 0)) &&
+ /* is cacheable */
+ (sid->u.ssl3.keys.resumable) &&
+ /* server hostname matches. */
+ (sid->urlSvrName != NULL) &&
+ (0 == PORT_Strcmp(urlSvrName, sid->urlSvrName))) {
+ /* Hit */
+ sid->lastAccessTime = now;
+ sid->references++;
+ break;
+ } else {
+ sidp = &sid->next;
+ }
+ }
+ UNLOCK_CACHE;
+ return sid;
+}
+
+/*
+** Add an sid to the cache or return a previously cached entry to the cache.
+** Although this is static, it is called via ss->sec.cache().
+*/
+static void
+CacheSID(sslSessionID *sid, PRTime creationTime)
+{
+ PORT_Assert(sid);
+ PORT_Assert(sid->cached == never_cached);
+
+ SSL_TRC(8, ("SSL: Cache: sid=0x%x cached=%d addr=0x%08x%08x%08x%08x port=0x%04x "
+ "time=%x cached=%d",
+ sid, sid->cached, sid->addr.pr_s6_addr32[0],
+ sid->addr.pr_s6_addr32[1], sid->addr.pr_s6_addr32[2],
+ sid->addr.pr_s6_addr32[3], sid->port, sid->creationTime,
+ sid->cached));
+
+ if (!sid->urlSvrName) {
+ /* don't cache this SID because it can never be matched */
+ return;
+ }
+
+ if (sid->u.ssl3.sessionIDLength == 0 &&
+ sid->u.ssl3.locked.sessionTicket.ticket.data == NULL)
+ return;
+
+ /* Client generates the SessionID if this was a stateless resume. */
+ if (sid->u.ssl3.sessionIDLength == 0) {
+ SECStatus rv;
+ rv = PK11_GenerateRandom(sid->u.ssl3.sessionID,
+ SSL3_SESSIONID_BYTES);
+ if (rv != SECSuccess)
+ return;
+ sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
+ }
+ PRINT_BUF(8, (0, "sessionID:",
+ sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength));
+
+ sid->u.ssl3.lock = PR_NewRWLock(PR_RWLOCK_RANK_NONE, NULL);
+ if (!sid->u.ssl3.lock) {
+ return;
+ }
+ PORT_Assert(sid->creationTime != 0);
+ if (!sid->creationTime) {
+ sid->lastAccessTime = sid->creationTime = creationTime;
+ }
+ PORT_Assert(sid->expirationTime != 0);
+ if (!sid->expirationTime) {
+ sid->expirationTime = sid->creationTime + (PR_MIN(ssl_ticket_lifetime,
+ sid->u.ssl3.locked.sessionTicket.ticket_lifetime_hint) *
+ PR_USEC_PER_SEC);
+ }
+
+ /*
+ * Put sid into the cache. Bump reference count to indicate that
+ * cache is holding a reference. Uncache will reduce the cache
+ * reference.
+ */
+ LOCK_CACHE;
+ sid->references++;
+ sid->cached = in_client_cache;
+ sid->next = cache;
+ cache = sid;
+ UNLOCK_CACHE;
+}
+
+/*
+ * If sid "zap" is in the cache,
+ * removes sid from cache, and decrements reference count.
+ * Caller must hold cache lock.
+ */
+static void
+UncacheSID(sslSessionID *zap)
+{
+ sslSessionID **sidp = &cache;
+ sslSessionID *sid;
+
+ if (zap->cached != in_client_cache) {
+ return;
+ }
+
+ SSL_TRC(8, ("SSL: Uncache: zap=0x%x cached=%d addr=0x%08x%08x%08x%08x port=0x%04x "
+ "time=%x cipherSuite=%d",
+ zap, zap->cached, zap->addr.pr_s6_addr32[0],
+ zap->addr.pr_s6_addr32[1], zap->addr.pr_s6_addr32[2],
+ zap->addr.pr_s6_addr32[3], zap->port, zap->creationTime,
+ zap->u.ssl3.cipherSuite));
+
+ /* See if it's in the cache, if so nuke it */
+ while ((sid = *sidp) != 0) {
+ if (sid == zap) {
+ /*
+ ** Bingo. Reduce reference count by one so that when
+ ** everyone is done with the sid we can free it up.
+ */
+ *sidp = zap->next;
+ zap->cached = invalid_cache;
+ ssl_FreeLockedSID(zap);
+ return;
+ }
+ sidp = &sid->next;
+ }
+}
+
+/* If sid "zap" is in the cache,
+ * removes sid from cache, and decrements reference count.
+ * Although this function is static, it is called externally via
+ * ssl_UncacheSessionID.
+ */
+static void
+LockAndUncacheSID(sslSessionID *zap)
+{
+ LOCK_CACHE;
+ UncacheSID(zap);
+ UNLOCK_CACHE;
+}
+
+SECStatus
+ReadVariableFromBuffer(sslReader *reader, sslReadBuffer *readerBuffer,
+ uint8_t lenBytes, SECItem *dest)
+{
+ if (sslRead_ReadVariable(reader, lenBytes, readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer->len) {
+ SECItem tempItem = { siBuffer, (unsigned char *)readerBuffer->buf,
+ readerBuffer->len };
+ SECStatus rv = SECITEM_CopyItem(NULL, dest, &tempItem);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+ return SECSuccess;
+}
+
+/* Fill sid with the values from the encoded resumption token.
+ * sid has to be allocated.
+ * We don't care about locks here as this cache entry is externally stored.
+ */
+SECStatus
+ssl_DecodeResumptionToken(sslSessionID *sid, const PRUint8 *encodedToken,
+ PRUint32 encodedTokenLen)
+{
+ PORT_Assert(encodedTokenLen);
+ PORT_Assert(encodedToken);
+ PORT_Assert(sid);
+ if (!sid || !encodedToken || !encodedTokenLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (encodedToken[0] != SSLResumptionTokenVersion) {
+ /* Unknown token format version. */
+ PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
+ return SECFailure;
+ }
+
+ /* These variables are used across macros. Don't use them outside. */
+ sslReader reader = SSL_READER(encodedToken, encodedTokenLen);
+ reader.offset += 1; // We read the version already. Skip the first byte.
+ sslReadBuffer readerBuffer = { 0 };
+ PRUint64 tmpInt = 0;
+
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->lastAccessTime = (PRTime)tmpInt;
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->expirationTime = (PRTime)tmpInt;
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.locked.sessionTicket.received_timestamp = (PRTime)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.locked.sessionTicket.ticket_lifetime_hint = (PRUint32)tmpInt;
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.locked.sessionTicket.flags = (PRUint32)tmpInt;
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.locked.sessionTicket.ticket_age_add = (PRUint32)tmpInt;
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.locked.sessionTicket.max_early_data_size = (PRUint32)tmpInt;
+
+ if (sslRead_ReadVariable(&reader, 3, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer.len) {
+ PORT_Assert(!sid->peerCert);
+ SECItem tempItem = { siBuffer, (unsigned char *)readerBuffer.buf,
+ readerBuffer.len };
+ sid->peerCert = CERT_NewTempCertificate(NULL, /* dbHandle */
+ &tempItem,
+ NULL, PR_FALSE, PR_TRUE);
+ if (!sid->peerCert) {
+ return SECFailure;
+ }
+ }
+
+ if (sslRead_ReadVariable(&reader, 2, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer.len) {
+ SECITEM_AllocArray(NULL, &sid->peerCertStatus, 1);
+ if (!sid->peerCertStatus.items) {
+ return SECFailure;
+ }
+ SECItem tempItem = { siBuffer, (unsigned char *)readerBuffer.buf,
+ readerBuffer.len };
+ SECITEM_CopyItem(NULL, &sid->peerCertStatus.items[0], &tempItem);
+ }
+
+ if (sslRead_ReadVariable(&reader, 1, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer.len) {
+ PORT_Assert(readerBuffer.buf);
+ if (sid->peerID) {
+ PORT_Free((void *)sid->peerID);
+ }
+ sid->peerID = PORT_Strdup((const char *)readerBuffer.buf);
+ }
+
+ if (sslRead_ReadVariable(&reader, 1, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer.len) {
+ if (sid->urlSvrName) {
+ PORT_Free((void *)sid->urlSvrName);
+ }
+ PORT_Assert(readerBuffer.buf);
+ sid->urlSvrName = PORT_Strdup((const char *)readerBuffer.buf);
+ }
+
+ if (sslRead_ReadVariable(&reader, 3, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer.len) {
+ PORT_Assert(!sid->localCert);
+ SECItem tempItem = { siBuffer, (unsigned char *)readerBuffer.buf,
+ readerBuffer.len };
+ sid->localCert = CERT_NewTempCertificate(NULL, /* dbHandle */
+ &tempItem,
+ NULL, PR_FALSE, PR_TRUE);
+ }
+
+ if (sslRead_ReadNumber(&reader, 8, &sid->addr.pr_s6_addr64[0]) != SECSuccess) {
+ return SECFailure;
+ }
+ if (sslRead_ReadNumber(&reader, 8, &sid->addr.pr_s6_addr64[1]) != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (sslRead_ReadNumber(&reader, 2, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->port = (PRUint16)tmpInt;
+ if (sslRead_ReadNumber(&reader, 2, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->version = (PRUint16)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->creationTime = (PRTime)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 2, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->authType = (SSLAuthType)tmpInt;
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->authKeyBits = (PRUint32)tmpInt;
+ if (sslRead_ReadNumber(&reader, 2, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->keaType = (SSLKEAType)tmpInt;
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->keaKeyBits = (PRUint32)tmpInt;
+ if (sslRead_ReadNumber(&reader, 3, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->keaGroup = (SSLNamedGroup)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 3, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->sigScheme = (SSLSignatureScheme)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 1, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.sessionIDLength = (PRUint8)tmpInt;
+
+ if (sslRead_ReadVariable(&reader, 1, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (readerBuffer.len) {
+ PORT_Assert(readerBuffer.buf);
+ PORT_Memcpy(sid->u.ssl3.sessionID, readerBuffer.buf, readerBuffer.len);
+ }
+
+ if (sslRead_ReadNumber(&reader, 2, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.cipherSuite = (PRUint16)tmpInt;
+ if (sslRead_ReadNumber(&reader, 1, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.policy = (PRUint8)tmpInt;
+
+ if (sslRead_ReadVariable(&reader, 1, &readerBuffer) != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ PORT_Assert(readerBuffer.len == WRAPPED_MASTER_SECRET_SIZE);
+ if (readerBuffer.len != WRAPPED_MASTER_SECRET_SIZE) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ PORT_Assert(readerBuffer.buf);
+ PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret, readerBuffer.buf,
+ readerBuffer.len);
+
+ if (sslRead_ReadNumber(&reader, 1, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.keys.wrapped_master_secret_len = (PRUint8)tmpInt;
+ if (sslRead_ReadNumber(&reader, 1, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.keys.extendedMasterSecretUsed = (PRUint8)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.masterWrapMech = (unsigned long)tmpInt;
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.masterModuleID = (unsigned long)tmpInt;
+ if (sslRead_ReadNumber(&reader, 8, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.masterSlotID = (unsigned long)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 4, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.masterWrapIndex = (PRUint32)tmpInt;
+ if (sslRead_ReadNumber(&reader, 2, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.masterWrapSeries = (PRUint16)tmpInt;
+
+ if (sslRead_ReadNumber(&reader, 1, &tmpInt) != SECSuccess) {
+ return SECFailure;
+ }
+ sid->u.ssl3.masterValid = (char)tmpInt;
+
+ if (ReadVariableFromBuffer(&reader, &readerBuffer, 1,
+ &sid->u.ssl3.srvName) != SECSuccess) {
+ return SECFailure;
+ }
+ if (ReadVariableFromBuffer(&reader, &readerBuffer, 2,
+ &sid->u.ssl3.signedCertTimestamps) != SECSuccess) {
+ return SECFailure;
+ }
+ if (ReadVariableFromBuffer(&reader, &readerBuffer, 1,
+ &sid->u.ssl3.alpnSelection) != SECSuccess) {
+ return SECFailure;
+ }
+ if (ReadVariableFromBuffer(&reader, &readerBuffer, 2,
+ &sid->u.ssl3.locked.sessionTicket.ticket) != SECSuccess) {
+ return SECFailure;
+ }
+ if (!sid->u.ssl3.locked.sessionTicket.ticket.len) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* At this point we must have read everything. */
+ PORT_Assert(reader.offset == reader.buf.len);
+ if (reader.offset != reader.buf.len) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+PRBool
+ssl_IsResumptionTokenUsable(sslSocket *ss, sslSessionID *sid)
+{
+ PORT_Assert(ss);
+ PORT_Assert(sid);
+
+ // Check that the ticket didn't expire.
+ PRTime endTime = 0;
+ NewSessionTicket *ticket = &sid->u.ssl3.locked.sessionTicket;
+ if (ticket->ticket_lifetime_hint != 0) {
+ endTime = ticket->received_timestamp +
+ (PRTime)(ticket->ticket_lifetime_hint * PR_USEC_PER_SEC);
+ if (endTime <= ssl_Time(ss)) {
+ return PR_FALSE;
+ }
+ }
+
+ // Check that the session entry didn't expire.
+ if (sid->expirationTime < ssl_Time(ss)) {
+ return PR_FALSE;
+ }
+
+ // Check that the server name (SNI) matches the one set for this session.
+ // Don't use the token if there's no server name.
+ if (sid->urlSvrName == NULL || PORT_Strcmp(ss->url, sid->urlSvrName) != 0) {
+ return PR_FALSE;
+ }
+
+ // This shouldn't be false, but let's check it anyway.
+ if (!sid->u.ssl3.keys.resumable) {
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+/* Encode a session ticket into a byte array that can be handed out to a cache.
+ * Needed memory in encodedToken has to be allocated according to
+ * *encodedTokenLen. */
+static SECStatus
+ssl_EncodeResumptionToken(sslSessionID *sid, sslBuffer *encodedTokenBuf)
+{
+ PORT_Assert(encodedTokenBuf);
+ PORT_Assert(sid);
+ if (!sid || !sid->u.ssl3.locked.sessionTicket.ticket.len ||
+ !encodedTokenBuf || !sid->u.ssl3.keys.resumable || !sid->urlSvrName) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* Encoding format:
+ * 0-byte: version
+ * Integers are encoded according to their length.
+ * SECItems are prepended with a 64-bit length field followed by the bytes.
+ * Optional bytes are encoded as a 0-length item if not present.
+ */
+ SECStatus rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ SSLResumptionTokenVersion, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->lastAccessTime, 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->expirationTime, 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ // session ticket
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.locked.sessionTicket.received_timestamp,
+ 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.locked.sessionTicket.ticket_lifetime_hint,
+ 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.locked.sessionTicket.flags,
+ 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.locked.sessionTicket.ticket_age_add,
+ 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.locked.sessionTicket.max_early_data_size,
+ 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendVariable(encodedTokenBuf, sid->peerCert->derCert.data,
+ sid->peerCert->derCert.len, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (sid->peerCertStatus.len > 1) {
+ /* This is not implemented so it shouldn't happen.
+ * If it gets implemented, this has to change.
+ */
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (sid->peerCertStatus.len == 1 && sid->peerCertStatus.items[0].len) {
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ sid->peerCertStatus.items[0].data,
+ sid->peerCertStatus.items[0].len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ } else {
+ rv = sslBuffer_AppendVariable(encodedTokenBuf, NULL, 0, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ PRUint64 len = sid->peerID ? strlen(sid->peerID) : 0;
+ if (len > PR_UINT8_MAX) {
+ // This string really shouldn't be that long.
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ (const unsigned char *)sid->peerID, len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ len = sid->urlSvrName ? strlen(sid->urlSvrName) : 0;
+ if (!len) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (len > PR_UINT8_MAX) {
+ // This string really shouldn't be that long.
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ (const unsigned char *)sid->urlSvrName,
+ len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (sid->localCert) {
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ sid->localCert->derCert.data,
+ sid->localCert->derCert.len, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ } else {
+ rv = sslBuffer_AppendVariable(encodedTokenBuf, NULL, 0, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->addr.pr_s6_addr64[0], 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->addr.pr_s6_addr64[1], 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->port, 2);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->version, 2);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->creationTime, 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->authType, 2);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->authKeyBits, 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->keaType, 2);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->keaKeyBits, 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->keaGroup, 3);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->sigScheme, 3);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.sessionIDLength, 1);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(encodedTokenBuf, sid->u.ssl3.sessionID,
+ SSL3_SESSIONID_BYTES, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.cipherSuite, 2);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.policy, 1);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ sid->u.ssl3.keys.wrapped_master_secret,
+ WRAPPED_MASTER_SECRET_SIZE, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.keys.wrapped_master_secret_len,
+ 1);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf,
+ sid->u.ssl3.keys.extendedMasterSecretUsed,
+ 1);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.masterWrapMech, 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.masterModuleID, 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.masterSlotID, 8);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.masterWrapIndex, 4);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.masterWrapSeries, 2);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(encodedTokenBuf, sid->u.ssl3.masterValid, 1);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendVariable(encodedTokenBuf, sid->u.ssl3.srvName.data,
+ sid->u.ssl3.srvName.len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ sid->u.ssl3.signedCertTimestamps.data,
+ sid->u.ssl3.signedCertTimestamps.len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ sid->u.ssl3.alpnSelection.data,
+ sid->u.ssl3.alpnSelection.len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ PORT_Assert(sid->u.ssl3.locked.sessionTicket.ticket.len > 1);
+ rv = sslBuffer_AppendVariable(encodedTokenBuf,
+ sid->u.ssl3.locked.sessionTicket.ticket.data,
+ sid->u.ssl3.locked.sessionTicket.ticket.len,
+ 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+void
+ssl_CacheExternalToken(sslSocket *ss)
+{
+ PORT_Assert(ss);
+ sslSessionID *sid = ss->sec.ci.sid;
+ PORT_Assert(sid);
+ PORT_Assert(sid->cached == never_cached);
+ PORT_Assert(ss->resumptionTokenCallback);
+
+ SSL_TRC(8, ("SSL [%d]: Cache External: sid=0x%x cached=%d "
+ "addr=0x%08x%08x%08x%08x port=0x%04x time=%x cached=%d",
+ ss->fd,
+ sid, sid->cached, sid->addr.pr_s6_addr32[0],
+ sid->addr.pr_s6_addr32[1], sid->addr.pr_s6_addr32[2],
+ sid->addr.pr_s6_addr32[3], sid->port, sid->creationTime,
+ sid->cached));
+
+ /* This is only available for stateless resumption. */
+ if (sid->u.ssl3.locked.sessionTicket.ticket.data == NULL) {
+ return;
+ }
+
+ /* Don't export token if the session used client authentication. */
+ if (sid->u.ssl3.clAuthValid) {
+ return;
+ }
+
+ if (!sid->creationTime) {
+ sid->lastAccessTime = sid->creationTime = ssl_Time(ss);
+ }
+ if (!sid->expirationTime) {
+ sid->expirationTime = sid->creationTime + (PR_MIN(ssl_ticket_lifetime,
+ sid->u.ssl3.locked.sessionTicket.ticket_lifetime_hint) *
+ PR_USEC_PER_SEC);
+ }
+
+ sslBuffer encodedToken = SSL_BUFFER_EMPTY;
+
+ if (ssl_EncodeResumptionToken(sid, &encodedToken) != SECSuccess) {
+ SSL_TRC(3, ("SSL [%d]: encoding resumption token failed", ss->fd));
+ return;
+ }
+ PORT_Assert(SSL_BUFFER_LEN(&encodedToken) > 0);
+ PRINT_BUF(40, (ss, "SSL: encoded resumption token",
+ SSL_BUFFER_BASE(&encodedToken),
+ SSL_BUFFER_LEN(&encodedToken)));
+ SECStatus rv = ss->resumptionTokenCallback(
+ ss->fd, SSL_BUFFER_BASE(&encodedToken), SSL_BUFFER_LEN(&encodedToken),
+ ss->resumptionTokenContext);
+ if (rv == SECSuccess) {
+ sid->cached = in_external_cache;
+ }
+ sslBuffer_Clear(&encodedToken);
+}
+
+void
+ssl_CacheSessionID(sslSocket *ss)
+{
+ sslSecurityInfo *sec = &ss->sec;
+ PORT_Assert(sec);
+ PORT_Assert(sec->ci.sid->cached == never_cached);
+
+ if (sec->ci.sid && !sec->ci.sid->u.ssl3.keys.resumable) {
+ return;
+ }
+
+ if (!sec->isServer && ss->resumptionTokenCallback) {
+ ssl_CacheExternalToken(ss);
+ return;
+ }
+
+ PORT_Assert(!ss->resumptionTokenCallback);
+ if (sec->isServer) {
+ ssl_ServerCacheSessionID(sec->ci.sid, ssl_Time(ss));
+ return;
+ }
+
+ CacheSID(sec->ci.sid, ssl_Time(ss));
+}
+
+void
+ssl_UncacheSessionID(sslSocket *ss)
+{
+ if (ss->opt.noCache) {
+ return;
+ }
+
+ sslSecurityInfo *sec = &ss->sec;
+ PORT_Assert(sec);
+
+ if (sec->ci.sid) {
+ if (sec->isServer) {
+ ssl_ServerUncacheSessionID(sec->ci.sid);
+ } else if (!ss->resumptionTokenCallback) {
+ LockAndUncacheSID(sec->ci.sid);
+ }
+ }
+}
+
+/* wipe out the entire client session cache. */
+void
+SSL_ClearSessionCache(void)
+{
+ LOCK_CACHE;
+ while (cache != NULL)
+ UncacheSID(cache);
+ UNLOCK_CACHE;
+}
+
+PRBool
+ssl_TicketTimeValid(const sslSocket *ss, const NewSessionTicket *ticket)
+{
+ PRTime endTime;
+
+ if (ticket->ticket_lifetime_hint == 0) {
+ return PR_TRUE;
+ }
+
+ endTime = ticket->received_timestamp +
+ (PRTime)(ticket->ticket_lifetime_hint * PR_USEC_PER_SEC);
+ return endTime > ssl_Time(ss);
+}
+
+void
+ssl3_SetSIDSessionTicket(sslSessionID *sid,
+ /*in/out*/ NewSessionTicket *newSessionTicket)
+{
+ PORT_Assert(sid);
+ PORT_Assert(newSessionTicket);
+ PORT_Assert(newSessionTicket->ticket.data);
+ PORT_Assert(newSessionTicket->ticket.len != 0);
+
+ /* If this is in the client cache, we are updating an existing entry that is
+ * already cached or was once cached, so we need to acquire and release the
+ * write lock. Otherwise, this is a new session that isn't shared with
+ * anything yet, so no locking is needed.
+ */
+ if (sid->u.ssl3.lock) {
+ PR_RWLock_Wlock(sid->u.ssl3.lock);
+ /* Another thread may have evicted, or it may be in external cache. */
+ PORT_Assert(sid->cached != never_cached);
+ }
+ /* If this was in the client cache, then we might have to free the old
+ * ticket. In TLS 1.3, we might get a replacement ticket if the server
+ * sends more than one ticket. */
+ if (sid->u.ssl3.locked.sessionTicket.ticket.data) {
+ PORT_Assert(sid->cached != never_cached ||
+ sid->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket,
+ PR_FALSE);
+ }
+
+ PORT_Assert(!sid->u.ssl3.locked.sessionTicket.ticket.data);
+
+ /* Do a shallow copy, moving the ticket data. */
+ sid->u.ssl3.locked.sessionTicket = *newSessionTicket;
+ newSessionTicket->ticket.data = NULL;
+ newSessionTicket->ticket.len = 0;
+
+ if (sid->u.ssl3.lock) {
+ PR_RWLock_Unlock(sid->u.ssl3.lock);
+ }
+}
diff --git a/security/nss/lib/ssl/sslprimitive.c b/security/nss/lib/ssl/sslprimitive.c
new file mode 100644
index 0000000000..2afecfb165
--- /dev/null
+++ b/security/nss/lib/ssl/sslprimitive.c
@@ -0,0 +1,482 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * SSL Primitives: Public HKDF and AEAD Functions
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "blapit.h"
+#include "keyhi.h"
+#include "pk11pub.h"
+#include "sechash.h"
+#include "ssl.h"
+#include "sslexp.h"
+#include "sslerr.h"
+#include "sslproto.h"
+
+#include "sslimpl.h"
+#include "tls13con.h"
+#include "tls13hkdf.h"
+
+struct SSLAeadContextStr {
+ /* sigh, the API creates a single context, but then uses either encrypt
+ * and decrypt on that context. We should take an encrypt/decrypt
+ * variable here, but for now create two contexts. */
+ PK11Context *encryptContext;
+ PK11Context *decryptContext;
+ int tagLen;
+ int ivLen;
+ unsigned char iv[MAX_IV_LENGTH];
+};
+
+SECStatus
+SSLExp_MakeVariantAead(PRUint16 version, PRUint16 cipherSuite, SSLProtocolVariant variant,
+ PK11SymKey *secret, const char *labelPrefix,
+ unsigned int labelPrefixLen, SSLAeadContext **ctx)
+{
+ SSLAeadContext *out = NULL;
+ char label[255]; // Maximum length label.
+ static const char *const keySuffix = "key";
+ static const char *const ivSuffix = "iv";
+ CK_MECHANISM_TYPE mech;
+ SECItem nullParams = { siBuffer, NULL, 0 };
+ PK11SymKey *key = NULL;
+
+ PORT_Assert(strlen(keySuffix) >= strlen(ivSuffix));
+ if (secret == NULL || ctx == NULL ||
+ (labelPrefix == NULL && labelPrefixLen > 0) ||
+ labelPrefixLen + strlen(keySuffix) > sizeof(label)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ SSLHashType hash;
+ const ssl3BulkCipherDef *cipher;
+ SECStatus rv = tls13_GetHashAndCipher(version, cipherSuite,
+ &hash, &cipher);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ out = PORT_ZNew(SSLAeadContext);
+ if (out == NULL) {
+ goto loser;
+ }
+ mech = ssl3_Alg2Mech(cipher->calg);
+ out->ivLen = cipher->iv_size + cipher->explicit_nonce_size;
+ out->tagLen = cipher->tag_size;
+
+ memcpy(label, labelPrefix, labelPrefixLen);
+ memcpy(label + labelPrefixLen, ivSuffix, strlen(ivSuffix));
+ unsigned int labelLen = labelPrefixLen + strlen(ivSuffix);
+ unsigned int ivLen = cipher->iv_size + cipher->explicit_nonce_size;
+ rv = tls13_HkdfExpandLabelRaw(secret, hash,
+ NULL, 0, // Handshake hash.
+ label, labelLen, variant,
+ out->iv, ivLen);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ memcpy(label + labelPrefixLen, keySuffix, strlen(keySuffix));
+ labelLen = labelPrefixLen + strlen(keySuffix);
+ rv = tls13_HkdfExpandLabel(secret, hash,
+ NULL, 0, // Handshake hash.
+ label, labelLen, mech, cipher->key_size,
+ variant, &key);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* We really need to change the API to Create a context for each
+ * encrypt and decrypt rather than a single call that does both. it's
+ * almost certain that the underlying application tries to use the same
+ * context for both. */
+ out->encryptContext = PK11_CreateContextBySymKey(mech,
+ CKA_NSS_MESSAGE | CKA_ENCRYPT,
+ key, &nullParams);
+ if (out->encryptContext == NULL) {
+ goto loser;
+ }
+
+ out->decryptContext = PK11_CreateContextBySymKey(mech,
+ CKA_NSS_MESSAGE | CKA_DECRYPT,
+ key, &nullParams);
+ if (out->decryptContext == NULL) {
+ goto loser;
+ }
+
+ PK11_FreeSymKey(key);
+ *ctx = out;
+ return SECSuccess;
+
+loser:
+ PK11_FreeSymKey(key);
+ SSLExp_DestroyAead(out);
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_MakeAead(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *secret,
+ const char *labelPrefix, unsigned int labelPrefixLen, SSLAeadContext **ctx)
+{
+ return SSLExp_MakeVariantAead(version, cipherSuite, ssl_variant_stream, secret,
+ labelPrefix, labelPrefixLen, ctx);
+}
+
+SECStatus
+SSLExp_DestroyAead(SSLAeadContext *ctx)
+{
+ if (!ctx) {
+ return SECSuccess;
+ }
+ if (ctx->encryptContext) {
+ PK11_DestroyContext(ctx->encryptContext, PR_TRUE);
+ }
+ if (ctx->decryptContext) {
+ PK11_DestroyContext(ctx->decryptContext, PR_TRUE);
+ }
+
+ PORT_ZFree(ctx, sizeof(*ctx));
+ return SECSuccess;
+}
+
+/* Bug 1529440 exists to refactor this and the other AEAD uses. */
+static SECStatus
+ssl_AeadInner(const SSLAeadContext *ctx, PK11Context *context,
+ PRBool decrypt, PRUint64 counter,
+ const PRUint8 *aad, unsigned int aadLen,
+ const PRUint8 *in, unsigned int inLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOut)
+{
+ if (ctx == NULL || (aad == NULL && aadLen > 0) || in == NULL ||
+ out == NULL || outLen == NULL) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ // Setup the nonce.
+ PRUint8 nonce[sizeof(counter)] = { 0 };
+ sslBuffer nonceBuf = SSL_BUFFER_FIXED(nonce, sizeof(counter));
+ SECStatus rv = sslBuffer_AppendNumber(&nonceBuf, counter, sizeof(counter));
+ if (rv != SECSuccess) {
+ PORT_Assert(0);
+ return SECFailure;
+ }
+ /* at least on encrypt, we should not be using CKG_NO_GENERATE, but
+ * the current experimental API has the application tracking the counter
+ * rather than token. We should look at the QUIC code and see if the
+ * counter can be moved internally where it belongs. That would
+ * also get rid of the formatting code above and have the API
+ * call tls13_AEAD directly in SSLExp_Aead* */
+ return tls13_AEAD(context, decrypt, CKG_NO_GENERATE, 0, ctx->iv, NULL,
+ ctx->ivLen, nonce, sizeof(counter), aad, aadLen,
+ out, outLen, maxOut, ctx->tagLen, in, inLen);
+}
+
+SECStatus
+SSLExp_AeadEncrypt(const SSLAeadContext *ctx, PRUint64 counter,
+ const PRUint8 *aad, unsigned int aadLen,
+ const PRUint8 *plaintext, unsigned int plaintextLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOut)
+{
+ // false == encrypt
+ return ssl_AeadInner(ctx, ctx->encryptContext, PR_FALSE, counter,
+ aad, aadLen, plaintext, plaintextLen,
+ out, outLen, maxOut);
+}
+
+SECStatus
+SSLExp_AeadDecrypt(const SSLAeadContext *ctx, PRUint64 counter,
+ const PRUint8 *aad, unsigned int aadLen,
+ const PRUint8 *ciphertext, unsigned int ciphertextLen,
+ PRUint8 *out, unsigned int *outLen, unsigned int maxOut)
+{
+ // true == decrypt
+ return ssl_AeadInner(ctx, ctx->decryptContext, PR_TRUE, counter,
+ aad, aadLen, ciphertext, ciphertextLen,
+ out, outLen, maxOut);
+}
+
+SECStatus
+SSLExp_HkdfExtract(PRUint16 version, PRUint16 cipherSuite,
+ PK11SymKey *salt, PK11SymKey *ikm, PK11SymKey **keyp)
+{
+ if (keyp == NULL) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SSLHashType hash;
+ SECStatus rv = tls13_GetHashAndCipher(version, cipherSuite,
+ &hash, NULL);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+ return tls13_HkdfExtract(salt, ikm, hash, keyp);
+}
+
+SECStatus
+SSLExp_HkdfExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen, PK11SymKey **keyp)
+{
+ return SSLExp_HkdfVariantExpandLabel(version, cipherSuite, prk, hsHash, hsHashLen,
+ label, labelLen, ssl_variant_stream, keyp);
+}
+
+SECStatus
+SSLExp_HkdfVariantExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ SSLProtocolVariant variant, PK11SymKey **keyp)
+{
+ if (prk == NULL || keyp == NULL ||
+ label == NULL || labelLen == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SSLHashType hash;
+ SECStatus rv = tls13_GetHashAndCipher(version, cipherSuite,
+ &hash, NULL);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+ return tls13_HkdfExpandLabel(prk, hash, hsHash, hsHashLen, label, labelLen,
+ CKM_HKDF_DERIVE,
+ tls13_GetHashSizeForHash(hash), variant, keyp);
+}
+
+SECStatus
+SSLExp_HkdfExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE mech, unsigned int keySize,
+ PK11SymKey **keyp)
+{
+ return SSLExp_HkdfVariantExpandLabelWithMech(version, cipherSuite, prk, hsHash, hsHashLen,
+ label, labelLen, mech, keySize,
+ ssl_variant_stream, keyp);
+}
+
+SECStatus
+SSLExp_HkdfVariantExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
+ const PRUint8 *hsHash, unsigned int hsHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE mech, unsigned int keySize,
+ SSLProtocolVariant variant, PK11SymKey **keyp)
+{
+ if (prk == NULL || keyp == NULL ||
+ label == NULL || labelLen == 0 ||
+ mech == CKM_INVALID_MECHANISM || keySize == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SSLHashType hash;
+ SECStatus rv = tls13_GetHashAndCipher(version, cipherSuite,
+ &hash, NULL);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+ return tls13_HkdfExpandLabel(prk, hash, hsHash, hsHashLen, label, labelLen,
+ mech, keySize, variant, keyp);
+}
+
+SECStatus
+ssl_CreateMaskingContextInner(PRUint16 version, PRUint16 cipherSuite,
+ SSLProtocolVariant variant,
+ PK11SymKey *secret,
+ const char *label,
+ unsigned int labelLen,
+ SSLMaskingContext **ctx)
+{
+ if (!secret || !ctx || (!label && labelLen)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SSLMaskingContext *out = PORT_ZNew(SSLMaskingContext);
+ if (out == NULL) {
+ goto loser;
+ }
+
+ SSLHashType hash;
+ const ssl3BulkCipherDef *cipher;
+ SECStatus rv = tls13_GetHashAndCipher(version, cipherSuite,
+ &hash, &cipher);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser; /* Code already set. */
+ }
+
+ out->mech = tls13_SequenceNumberEncryptionMechanism(cipher->calg);
+ if (out->mech == CKM_INVALID_MECHANISM) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ // Derive the masking key
+ rv = tls13_HkdfExpandLabel(secret, hash,
+ NULL, 0, // Handshake hash.
+ label, labelLen,
+ out->mech,
+ cipher->key_size, variant,
+ &out->secret);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ out->version = version;
+ out->cipherSuite = cipherSuite;
+
+ *ctx = out;
+ return SECSuccess;
+loser:
+ SSLExp_DestroyMaskingContext(out);
+ return SECFailure;
+}
+
+SECStatus
+ssl_CreateMaskInner(SSLMaskingContext *ctx, const PRUint8 *sample,
+ unsigned int sampleLen, PRUint8 *outMask,
+ unsigned int maskLen)
+{
+ if (!ctx || !sample || !sampleLen || !outMask || !maskLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ctx->secret == NULL) {
+ PORT_SetError(SEC_ERROR_NO_KEY);
+ return SECFailure;
+ }
+
+ SECStatus rv = SECFailure;
+ unsigned int outMaskLen = 0;
+ int paramLen = 0;
+
+ /* Internal output len/buf, for use if the caller allocated and requested
+ * less than one block of output. |oneBlock| should have size equal to the
+ * largest block size supported below. */
+ PRUint8 oneBlock[AES_BLOCK_SIZE];
+ PRUint8 *outMask_ = outMask;
+ unsigned int maskLen_ = maskLen;
+
+ switch (ctx->mech) {
+ case CKM_AES_ECB:
+ if (sampleLen < AES_BLOCK_SIZE) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (maskLen_ < AES_BLOCK_SIZE) {
+ outMask_ = oneBlock;
+ maskLen_ = sizeof(oneBlock);
+ }
+ rv = PK11_Encrypt(ctx->secret,
+ ctx->mech,
+ NULL,
+ outMask_, &outMaskLen, maskLen_,
+ sample, AES_BLOCK_SIZE);
+ if (rv == SECSuccess &&
+ maskLen < AES_BLOCK_SIZE) {
+ memcpy(outMask, outMask_, maskLen);
+ }
+ break;
+ case CKM_NSS_CHACHA20_CTR:
+ paramLen = 16;
+ /* fall through */
+ case CKM_CHACHA20:
+ paramLen = (paramLen) ? paramLen : sizeof(CK_CHACHA20_PARAMS);
+ if (sampleLen < paramLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SECItem param;
+ param.type = siBuffer;
+ param.len = paramLen;
+ param.data = (PRUint8 *)sample; // const-cast :(
+ unsigned char zeros[128] = { 0 };
+
+ if (maskLen > sizeof(zeros)) {
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ return SECFailure;
+ }
+
+ rv = PK11_Encrypt(ctx->secret,
+ ctx->mech,
+ &param,
+ outMask, &outMaskLen,
+ maskLen,
+ zeros, maskLen);
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_PKCS11_FUNCTION_FAILED);
+ return SECFailure;
+ }
+
+ // Ensure we produced at least as much material as requested.
+ if (outMaskLen < maskLen) {
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+ssl_DestroyMaskingContextInner(SSLMaskingContext *ctx)
+{
+ if (!ctx) {
+ return SECSuccess;
+ }
+
+ PK11_FreeSymKey(ctx->secret);
+ PORT_ZFree(ctx, sizeof(*ctx));
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_CreateMask(SSLMaskingContext *ctx, const PRUint8 *sample,
+ unsigned int sampleLen, PRUint8 *outMask,
+ unsigned int maskLen)
+{
+ return ssl_CreateMaskInner(ctx, sample, sampleLen, outMask, maskLen);
+}
+
+SECStatus
+SSLExp_CreateMaskingContext(PRUint16 version, PRUint16 cipherSuite,
+ PK11SymKey *secret,
+ const char *label,
+ unsigned int labelLen,
+ SSLMaskingContext **ctx)
+{
+ return ssl_CreateMaskingContextInner(version, cipherSuite, ssl_variant_stream, secret,
+ label, labelLen, ctx);
+}
+
+SECStatus
+SSLExp_CreateVariantMaskingContext(PRUint16 version, PRUint16 cipherSuite,
+ SSLProtocolVariant variant,
+ PK11SymKey *secret,
+ const char *label,
+ unsigned int labelLen,
+ SSLMaskingContext **ctx)
+{
+ return ssl_CreateMaskingContextInner(version, cipherSuite, variant, secret,
+ label, labelLen, ctx);
+}
+
+SECStatus
+SSLExp_DestroyMaskingContext(SSLMaskingContext *ctx)
+{
+ return ssl_DestroyMaskingContextInner(ctx);
+}
diff --git a/security/nss/lib/ssl/sslproto.h b/security/nss/lib/ssl/sslproto.h
new file mode 100644
index 0000000000..beaee5178f
--- /dev/null
+++ b/security/nss/lib/ssl/sslproto.h
@@ -0,0 +1,294 @@
+/*
+ * Various and sundry protocol constants. DON'T CHANGE THESE. These values
+ * are mostly defined by the SSL3 or TLS protocol specifications.
+ * Cipher kinds and ciphersuites are part of the public API.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslproto_h_
+#define __sslproto_h_
+
+/* clang-format off */
+
+/* All versions less than 3_0 are treated as SSL version 2 */
+#define SSL_LIBRARY_VERSION_2 0x0002
+#define SSL_LIBRARY_VERSION_3_0 0x0300
+#define SSL_LIBRARY_VERSION_TLS_1_0 0x0301
+#define SSL_LIBRARY_VERSION_TLS_1_1 0x0302
+#define SSL_LIBRARY_VERSION_TLS_1_2 0x0303
+#define SSL_LIBRARY_VERSION_TLS_1_3 0x0304
+
+/* Note: this is the internal format, not the wire format */
+#define SSL_LIBRARY_VERSION_DTLS_1_0 SSL_LIBRARY_VERSION_TLS_1_1
+#define SSL_LIBRARY_VERSION_DTLS_1_2 SSL_LIBRARY_VERSION_TLS_1_2
+#define SSL_LIBRARY_VERSION_DTLS_1_3 SSL_LIBRARY_VERSION_TLS_1_3
+
+/* deprecated old name */
+#define SSL_LIBRARY_VERSION_3_1_TLS SSL_LIBRARY_VERSION_TLS_1_0
+
+/* The DTLS versions used in the spec */
+#define SSL_LIBRARY_VERSION_DTLS_1_0_WIRE ((~0x0100) & 0xffff)
+#define SSL_LIBRARY_VERSION_DTLS_1_2_WIRE ((~0x0102) & 0xffff)
+#define SSL_LIBRARY_VERSION_DTLS_1_3_WIRE ((~0x0103) & 0xffff)
+
+/* Certificate types */
+#define SSL_CT_X509_CERTIFICATE 0x01
+#if 0 /* XXX Not implemented yet */
+#define SSL_PKCS6_CERTIFICATE 0x02
+#endif
+#define SSL_AT_MD5_WITH_RSA_ENCRYPTION 0x01
+
+/* Error codes */
+#define SSL_PE_NO_CYPHERS 0x0001
+#define SSL_PE_NO_CERTIFICATE 0x0002
+#define SSL_PE_BAD_CERTIFICATE 0x0004
+#define SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE 0x0006
+
+/* Deprecated SSL 3.0 & libssl names replaced by IANA-registered TLS names. */
+#ifndef SSL_DISABLE_DEPRECATED_CIPHER_SUITE_NAMES
+#define SSL_NULL_WITH_NULL_NULL TLS_NULL_WITH_NULL_NULL
+#define SSL_RSA_WITH_NULL_MD5 TLS_RSA_WITH_NULL_MD5
+#define SSL_RSA_WITH_NULL_SHA TLS_RSA_WITH_NULL_SHA
+#define SSL_RSA_WITH_RC4_128_MD5 TLS_RSA_WITH_RC4_128_MD5
+#define SSL_RSA_WITH_RC4_128_SHA TLS_RSA_WITH_RC4_128_SHA
+#define SSL_RSA_WITH_IDEA_CBC_SHA TLS_RSA_WITH_IDEA_CBC_SHA
+#define SSL_RSA_WITH_DES_CBC_SHA TLS_RSA_WITH_DES_CBC_SHA
+#define SSL_RSA_WITH_3DES_EDE_CBC_SHA TLS_RSA_WITH_3DES_EDE_CBC_SHA
+#define SSL_DH_DSS_WITH_DES_CBC_SHA TLS_DH_DSS_WITH_DES_CBC_SHA
+#define SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
+#define SSL_DH_RSA_WITH_DES_CBC_SHA TLS_DH_RSA_WITH_DES_CBC_SHA
+#define SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
+#define SSL_DHE_DSS_WITH_DES_CBC_SHA TLS_DHE_DSS_WITH_DES_CBC_SHA
+#define SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
+#define SSL_DHE_RSA_WITH_DES_CBC_SHA TLS_DHE_RSA_WITH_DES_CBC_SHA
+#define SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
+#define SSL_DH_ANON_WITH_RC4_128_MD5 TLS_DH_anon_WITH_RC4_128_MD5
+#define SSL_DH_ANON_WITH_DES_CBC_SHA TLS_DH_anon_WITH_DES_CBC_SHA
+#define SSL_DH_ANON_WITH_3DES_EDE_CBC_SHA TLS_DH_anon_WITH_3DES_EDE_CBC_SHA
+#define TLS_DH_ANON_WITH_AES_128_CBC_SHA TLS_DH_anon_WITH_AES_128_CBC_SHA
+#define TLS_DH_ANON_WITH_AES_256_CBC_SHA TLS_DH_anon_WITH_AES_256_CBC_SHA
+#define TLS_DH_ANON_WITH_CAMELLIA_128_CBC_SHA TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA
+#define TLS_DH_ANON_WITH_CAMELLIA_256_CBC_SHA TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA
+#endif
+
+#define TLS_NULL_WITH_NULL_NULL 0x0000
+
+#define TLS_RSA_WITH_NULL_MD5 0x0001
+#define TLS_RSA_WITH_NULL_SHA 0x0002
+#define TLS_RSA_WITH_RC4_128_MD5 0x0004
+#define TLS_RSA_WITH_RC4_128_SHA 0x0005
+#define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007
+#define TLS_RSA_WITH_DES_CBC_SHA 0x0009
+#define TLS_RSA_WITH_3DES_EDE_CBC_SHA 0x000a
+
+#define TLS_DH_DSS_WITH_DES_CBC_SHA 0x000c
+#define TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA 0x000d
+#define TLS_DH_RSA_WITH_DES_CBC_SHA 0x000f
+#define TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA 0x0010
+
+#define TLS_DHE_DSS_WITH_DES_CBC_SHA 0x0012
+#define TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA 0x0013
+#define TLS_DHE_RSA_WITH_DES_CBC_SHA 0x0015
+#define TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016
+
+#define TLS_DH_anon_WITH_RC4_128_MD5 0x0018
+#define TLS_DH_anon_WITH_DES_CBC_SHA 0x001a
+#define TLS_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001b
+
+#define TLS_RSA_WITH_AES_128_CBC_SHA 0x002F
+#define TLS_DH_DSS_WITH_AES_128_CBC_SHA 0x0030
+#define TLS_DH_RSA_WITH_AES_128_CBC_SHA 0x0031
+#define TLS_DHE_DSS_WITH_AES_128_CBC_SHA 0x0032
+#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x0033
+#define TLS_DH_anon_WITH_AES_128_CBC_SHA 0x0034
+
+#define TLS_RSA_WITH_AES_256_CBC_SHA 0x0035
+#define TLS_DH_DSS_WITH_AES_256_CBC_SHA 0x0036
+#define TLS_DH_RSA_WITH_AES_256_CBC_SHA 0x0037
+#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA 0x0038
+#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x0039
+#define TLS_DH_anon_WITH_AES_256_CBC_SHA 0x003A
+#define TLS_RSA_WITH_NULL_SHA256 0x003B
+#define TLS_RSA_WITH_AES_128_CBC_SHA256 0x003C
+#define TLS_RSA_WITH_AES_256_CBC_SHA256 0x003D
+
+#define TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 0x0040
+#define TLS_RSA_WITH_CAMELLIA_128_CBC_SHA 0x0041
+#define TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0x0042
+#define TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0x0043
+#define TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0x0044
+#define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x0045
+#define TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA 0x0046
+
+#define TLS_DHE_DSS_WITH_RC4_128_SHA 0x0066
+#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x0067
+#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 0x006A
+#define TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x006B
+
+#define TLS_RSA_WITH_CAMELLIA_256_CBC_SHA 0x0084
+#define TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0x0085
+#define TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0x0086
+#define TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0x0087
+#define TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x0088
+#define TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA 0x0089
+
+#define TLS_RSA_WITH_SEED_CBC_SHA 0x0096
+
+#define TLS_RSA_WITH_AES_128_GCM_SHA256 0x009C
+#define TLS_RSA_WITH_AES_256_GCM_SHA384 0x009D
+#define TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x009E
+#define TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 0x009F
+#define TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 0x00A2
+#define TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 0x00A3
+
+/* TLS "Signaling Cipher Suite Value" (SCSV). May be requested by client.
+ * Must NEVER be chosen by server. SSL 3.0 server acknowledges by sending
+ * back an empty Renegotiation Info (RI) server hello extension.
+ */
+#define TLS_EMPTY_RENEGOTIATION_INFO_SCSV 0x00FF
+
+/* TLS_FALLBACK_SCSV is a signaling cipher suite value that indicates that a
+ * handshake is the result of TLS version fallback.
+ */
+#define TLS_FALLBACK_SCSV 0x5600
+
+/* Cipher Suite Values starting with 0xC000 are defined in informational
+ * RFCs.
+ */
+#define TLS_ECDH_ECDSA_WITH_NULL_SHA 0xC001
+#define TLS_ECDH_ECDSA_WITH_RC4_128_SHA 0xC002
+#define TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC003
+#define TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004
+#define TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005
+
+#define TLS_ECDHE_ECDSA_WITH_NULL_SHA 0xC006
+#define TLS_ECDHE_ECDSA_WITH_RC4_128_SHA 0xC007
+#define TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA 0xC008
+#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009
+#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A
+
+#define TLS_ECDH_RSA_WITH_NULL_SHA 0xC00B
+#define TLS_ECDH_RSA_WITH_RC4_128_SHA 0xC00C
+#define TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA 0xC00D
+#define TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E
+#define TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F
+
+#define TLS_ECDHE_RSA_WITH_NULL_SHA 0xC010
+#define TLS_ECDHE_RSA_WITH_RC4_128_SHA 0xC011
+#define TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA 0xC012
+#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013
+#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014
+
+#define TLS_ECDH_anon_WITH_NULL_SHA 0xC015
+#define TLS_ECDH_anon_WITH_RC4_128_SHA 0xC016
+#define TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA 0xC017
+#define TLS_ECDH_anon_WITH_AES_128_CBC_SHA 0xC018
+#define TLS_ECDH_anon_WITH_AES_256_CBC_SHA 0xC019
+
+#define TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023
+#define TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024
+#define TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027
+#define TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028
+
+#define TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B
+#define TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C
+#define TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D
+#define TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F
+#define TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030
+#define TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031
+
+/* draft-ietf-tls-chacha20-poly1305-04 */
+#define TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8
+#define TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9
+#define TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA
+
+/* Special TLS 1.3 cipher suites that really just specify AEAD */
+#define TLS_AES_128_GCM_SHA256 0x1301
+#define TLS_AES_256_GCM_SHA384 0x1302
+#define TLS_CHACHA20_POLY1305_SHA256 0x1303
+
+/* PSK cipher suites. NSS doesn't actually support these, but we
+ * exposed them when TLS 1.3 used them so we need to keep them
+ * in the API. */
+#define TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC
+#define TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD
+#define TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256 0xD001
+#define TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384 0xD002
+#define TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 0x00AA /* RFC 5487 */
+#define TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 0x00AB /* RFC 5487 */
+
+/* DTLS-SRTP cipher suites from RFC 5764 */
+/* If you modify this, also modify MAX_DTLS_SRTP_CIPHER_SUITES in sslimpl.h */
+#define SRTP_AES128_CM_HMAC_SHA1_80 0x0001
+#define SRTP_AES128_CM_HMAC_SHA1_32 0x0002
+#define SRTP_NULL_HMAC_SHA1_80 0x0005
+#define SRTP_NULL_HMAC_SHA1_32 0x0006
+
+/* DO NOT USE. (deprecated, will be removed) */
+#define SSL_HL_ERROR_HBYTES 3
+#define SSL_HL_CLIENT_HELLO_HBYTES 9
+#define SSL_HL_CLIENT_MASTER_KEY_HBYTES 10
+#define SSL_HL_CLIENT_FINISHED_HBYTES 1
+#define SSL_HL_SERVER_HELLO_HBYTES 11
+#define SSL_HL_SERVER_VERIFY_HBYTES 1
+#define SSL_HL_SERVER_FINISHED_HBYTES 1
+#define SSL_HL_REQUEST_CERTIFICATE_HBYTES 2
+#define SSL_HL_CLIENT_CERTIFICATE_HBYTES 6
+#define SSL_MT_ERROR 0
+#define SSL_MT_CLIENT_HELLO 1
+#define SSL_MT_CLIENT_MASTER_KEY 2
+#define SSL_MT_CLIENT_FINISHED 3
+#define SSL_MT_SERVER_HELLO 4
+#define SSL_MT_SERVER_VERIFY 5
+#define SSL_MT_SERVER_FINISHED 6
+#define SSL_MT_REQUEST_CERTIFICATE 7
+#define SSL_MT_CLIENT_CERTIFICATE 8
+#define SSL_CK_RC4_128_WITH_MD5 0x01
+#define SSL_CK_RC4_128_EXPORT40_WITH_MD5 0x02
+#define SSL_CK_RC2_128_CBC_WITH_MD5 0x03
+#define SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 0x04
+#define SSL_CK_IDEA_128_CBC_WITH_MD5 0x05
+#define SSL_CK_DES_64_CBC_WITH_MD5 0x06
+#define SSL_CK_DES_192_EDE3_CBC_WITH_MD5 0x07
+#define SSL_EN_RC4_128_WITH_MD5 0xFF01
+#define SSL_EN_RC4_128_EXPORT40_WITH_MD5 0xFF02
+#define SSL_EN_RC2_128_CBC_WITH_MD5 0xFF03
+#define SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5 0xFF04
+#define SSL_EN_IDEA_128_CBC_WITH_MD5 0xFF05
+#define SSL_EN_DES_64_CBC_WITH_MD5 0xFF06
+#define SSL_EN_DES_192_EDE3_CBC_WITH_MD5 0xFF07
+#define TLS_RSA_EXPORT_WITH_RC4_40_MD5 0x0003
+#define TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 0x0006
+#define TLS_RSA_EXPORT_WITH_DES40_CBC_SHA 0x0008
+#define TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA 0x0062
+#define TLS_RSA_EXPORT1024_WITH_RC4_56_SHA 0x0064
+#define TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 0x0014
+#define TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA 0x000e
+#define TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA 0x0063
+#define TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA 0x0065
+#define TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA 0x000b
+#define TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA 0x0011
+#define TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 0x0017
+#define TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA 0x0019
+#define SSL_FORTEZZA_DMS_WITH_NULL_SHA 0x001c
+#define SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA 0x001d
+#define SSL_FORTEZZA_DMS_WITH_RC4_128_SHA 0x001e
+#define SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA 0xffe0
+#define SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA 0xffe1
+#define SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA 0xfeff
+#define SSL_RSA_FIPS_WITH_DES_CBC_SHA 0xfefe
+#define SSL_RSA_EXPORT_WITH_RC4_40_MD5 TLS_RSA_EXPORT_WITH_RC4_40_MD5
+#define SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5 TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
+#define SSL_RSA_EXPORT_WITH_DES40_CBC_SHA TLS_RSA_EXPORT_WITH_DES40_CBC_SHA
+#define SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
+#define SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
+#define SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
+#define SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
+#define SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
+#define SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5 TLS_DH_anon_EXPORT_WITH_RC4_40_MD5
+
+/* clang-format on */
+
+#endif /* __sslproto_h_ */
diff --git a/security/nss/lib/ssl/sslreveal.c b/security/nss/lib/ssl/sslreveal.c
new file mode 100644
index 0000000000..cc16f574db
--- /dev/null
+++ b/security/nss/lib/ssl/sslreveal.c
@@ -0,0 +1,108 @@
+/*
+ * Accessor functions for SSLSocket private members.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "cert.h"
+#include "ssl.h"
+#include "certt.h"
+#include "sslimpl.h"
+
+/* given PRFileDesc, returns a copy of certificate associated with the socket
+ * the caller should delete the cert when done with SSL_DestroyCertificate
+ */
+CERTCertificate *
+SSL_RevealCert(PRFileDesc *fd)
+{
+ CERTCertificate *cert = NULL;
+ sslSocket *sslsocket = NULL;
+
+ sslsocket = ssl_FindSocket(fd);
+
+ /* CERT_DupCertificate increases reference count and returns pointer to
+ * the same cert
+ */
+ if (sslsocket && sslsocket->sec.peerCert)
+ cert = CERT_DupCertificate(sslsocket->sec.peerCert);
+
+ return cert;
+}
+
+/* given PRFileDesc, returns a pointer to PinArg associated with the socket
+ */
+void *
+SSL_RevealPinArg(PRFileDesc *fd)
+{
+ sslSocket *sslsocket = NULL;
+ void *PinArg = NULL;
+
+ sslsocket = ssl_FindSocket(fd);
+
+ /* is pkcs11PinArg part of the sslSocket or sslSecurityInfo ? */
+ if (sslsocket)
+ PinArg = sslsocket->pkcs11PinArg;
+
+ return PinArg;
+}
+
+/* given PRFileDesc, returns a pointer to the URL associated with the socket
+ * the caller should free url when done
+ */
+char *
+SSL_RevealURL(PRFileDesc *fd)
+{
+ sslSocket *sslsocket = NULL;
+ char *url = NULL;
+
+ sslsocket = ssl_FindSocket(fd);
+
+ if (sslsocket && sslsocket->url)
+ url = PL_strdup(sslsocket->url);
+
+ return url;
+}
+
+/* given PRFileDesc, returns status information related to extensions
+ * negotiated with peer during the handshake.
+ */
+
+SECStatus
+SSL_HandshakeNegotiatedExtension(PRFileDesc *socket,
+ SSLExtensionType extId,
+ PRBool *pYes)
+{
+ /* some decisions derived from SSL_GetChannelInfo */
+ sslSocket *sslsocket = NULL;
+
+ if (!pYes) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ sslsocket = ssl_FindSocket(socket);
+ if (!sslsocket) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeNegotiatedExtension",
+ SSL_GETPID(), socket));
+ return SECFailure;
+ }
+
+ *pYes = PR_FALSE;
+
+ /* according to public API SSL_GetChannelInfo, this doesn't need a lock */
+ if (sslsocket->opt.useSecurity) {
+ /* now we know this socket went through ssl3_InitState() and
+ * ss->xtnData got initialized, which is the only member accessed by
+ * ssl3_ExtensionNegotiated();
+ * Member xtnData appears to get accessed in functions that handle
+ * the handshake (hello messages and extension sending),
+ * therefore the handshake lock should be sufficient.
+ */
+ ssl_GetSSL3HandshakeLock(sslsocket);
+ *pYes = ssl3_ExtensionNegotiated(sslsocket, extId);
+ ssl_ReleaseSSL3HandshakeLock(sslsocket);
+ }
+
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/sslsecur.c b/security/nss/lib/ssl/sslsecur.c
new file mode 100644
index 0000000000..4a05637039
--- /dev/null
+++ b/security/nss/lib/ssl/sslsecur.c
@@ -0,0 +1,1385 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * Various SSL functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "cert.h"
+#include "secitem.h"
+#include "keyhi.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "secoid.h" /* for SECOID_GetALgorithmTag */
+#include "pk11func.h" /* for PK11_GenerateRandom */
+#include "nss.h" /* for NSS_RegisterShutdown */
+#include "prinit.h" /* for PR_CallOnceWithArg */
+#include "tls13ech.h"
+#include "tls13psk.h"
+
+/* Step through the handshake functions.
+ *
+ * Called from: SSL_ForceHandshake (below),
+ * ssl_SecureRecv (below) and
+ * ssl_SecureSend (below)
+ * from: WaitForResponse in sslsocks.c
+ * ssl_SocksRecv in sslsocks.c
+ * ssl_SocksSend in sslsocks.c
+ *
+ * Caller must hold the (write) handshakeLock.
+ */
+SECStatus
+ssl_Do1stHandshake(sslSocket *ss)
+{
+ SECStatus rv = SECSuccess;
+
+ while (ss->handshake && rv == SECSuccess) {
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss));
+
+ rv = (*ss->handshake)(ss);
+ };
+
+ PORT_Assert(ss->opt.noLocks || !ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || !ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || !ssl_HaveSSL3HandshakeLock(ss));
+
+ return rv;
+}
+
+SECStatus
+ssl_FinishHandshake(sslSocket *ss)
+{
+ PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->ssl3.hs.echAccepted ||
+ (ss->opt.enableTls13BackendEch &&
+ ss->xtnData.ech &&
+ ss->xtnData.ech->receivedInnerXtn) ==
+ ssl3_ExtensionNegotiated(ss, ssl_tls13_encrypted_client_hello_xtn));
+
+ /* If ECH was OFFERED to (echHpkeCtx is set on the client) DISABLED by the
+ * server through negotiation of a TLS version < 1.3, an 'ech_required'
+ * alert MUST be sent to inform the server about the intention / possible
+ * misconfiguration. */
+ if (!ss->sec.isServer && ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echAccepted) {
+ SSL3_SendAlert(ss, alert_fatal, ech_required);
+ /* "If [one, none] of the retry_configs contains a supported version,
+ * the client can regard ECH as securely [replaced, disabled] by the
+ * server." */
+ if (ss->xtnData.ech && ss->xtnData.ech->retryConfigs.len) {
+ PORT_SetError(SSL_ERROR_ECH_RETRY_WITH_ECH);
+ ss->xtnData.ech->retryConfigsValid = PR_TRUE;
+ } else {
+ PORT_SetError(SSL_ERROR_ECH_RETRY_WITHOUT_ECH);
+ }
+ return SECFailure;
+ }
+
+ SSL_TRC(3, ("%d: SSL[%d]: handshake is completed", SSL_GETPID(), ss->fd));
+
+ ss->firstHsDone = PR_TRUE;
+ ss->enoughFirstHsDone = PR_TRUE;
+ ss->gs.writeOffset = 0;
+ ss->gs.readOffset = 0;
+
+ if (ss->handshakeCallback) {
+ PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) ==
+ ssl_preinfo_all);
+ (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
+ }
+
+ ssl_FreeEphemeralKeyPairs(ss);
+
+ return SECSuccess;
+}
+
+/*
+ * Handshake function that blocks. Used to force a
+ * retry on a connection on the next read/write.
+ */
+static SECStatus
+ssl3_AlwaysBlock(sslSocket *ss)
+{
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+}
+
+/*
+ * set the initial handshake state machine to block
+ */
+void
+ssl3_SetAlwaysBlock(sslSocket *ss)
+{
+ if (!ss->firstHsDone) {
+ ss->handshake = ssl3_AlwaysBlock;
+ }
+}
+
+static SECStatus
+ssl_SetTimeout(PRFileDesc *fd, PRIntervalTime timeout)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SetTimeout", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ SSL_LOCK_READER(ss);
+ ss->rTimeout = timeout;
+ if (ss->opt.fdx) {
+ SSL_LOCK_WRITER(ss);
+ }
+ ss->wTimeout = timeout;
+ if (ss->opt.fdx) {
+ SSL_UNLOCK_WRITER(ss);
+ }
+ SSL_UNLOCK_READER(ss);
+ return SECSuccess;
+}
+
+/* Acquires and releases HandshakeLock.
+*/
+SECStatus
+SSL_ResetHandshake(PRFileDesc *s, PRBool asServer)
+{
+ sslSocket *ss;
+ SECStatus status;
+ PRNetAddr addr;
+
+ ss = ssl_FindSocket(s);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in ResetHandshake", SSL_GETPID(), s));
+ return SECFailure;
+ }
+
+ /* Don't waste my time */
+ if (!ss->opt.useSecurity)
+ return SECSuccess;
+
+ SSL_LOCK_READER(ss);
+ SSL_LOCK_WRITER(ss);
+
+ /* Reset handshake state */
+ ssl_Get1stHandshakeLock(ss);
+
+ ss->firstHsDone = PR_FALSE;
+ ss->enoughFirstHsDone = PR_FALSE;
+ if (asServer) {
+ ss->handshake = ssl_BeginServerHandshake;
+ ss->handshaking = sslHandshakingAsServer;
+ } else {
+ ss->handshake = ssl_BeginClientHandshake;
+ ss->handshaking = sslHandshakingAsClient;
+ }
+
+ ssl_GetRecvBufLock(ss);
+ status = ssl3_InitGather(&ss->gs);
+ ssl_ReleaseRecvBufLock(ss);
+ if (status != SECSuccess)
+ goto loser;
+
+ ssl_GetSSL3HandshakeLock(ss);
+ ss->ssl3.hs.canFalseStart = PR_FALSE;
+ ss->ssl3.hs.restartTarget = NULL;
+
+ /*
+ ** Blow away old security state and get a fresh setup.
+ */
+ ssl_GetXmitBufLock(ss);
+ ssl_ResetSecurityInfo(&ss->sec, PR_TRUE);
+ status = ssl_CreateSecurityInfo(ss);
+ ssl_ReleaseXmitBufLock(ss);
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
+ ssl3_ResetExtensionData(&ss->xtnData, ss);
+ tls13_ResetHandshakePsks(ss, &ss->ssl3.hs.psks);
+
+ if (ss->ssl3.hs.echHpkeCtx) {
+ PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
+ ss->ssl3.hs.echHpkeCtx = NULL;
+ PORT_Assert(ss->ssl3.hs.echPublicName);
+ PORT_Free((void *)ss->ssl3.hs.echPublicName); /* CONST */
+ ss->ssl3.hs.echPublicName = NULL;
+ }
+ /* Make sure greaseEchBuf is freed in ECH setups without echHpkeCtx. */
+ if (ss->ssl3.hs.echHpkeCtx ||
+ ss->opt.enableTls13BackendEch ||
+ ss->opt.enableTls13GreaseEch) {
+ sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
+ }
+
+ tls13_ClientGreaseDestroy(ss);
+
+ tls_ClientHelloExtensionPermutationDestroy(ss);
+
+ if (!ss->TCPconnected)
+ ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
+
+loser:
+ SSL_UNLOCK_WRITER(ss);
+ SSL_UNLOCK_READER(ss);
+
+ return status;
+}
+
+/* For SSLv2, does nothing but return an error.
+** For SSLv3, flushes SID cache entry (if requested),
+** and then starts new client hello or hello request.
+** Acquires and releases HandshakeLock.
+*/
+SECStatus
+SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache)
+{
+ sslSocket *ss;
+ SECStatus rv;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!ss->opt.useSecurity)
+ return SECSuccess;
+
+ ssl_Get1stHandshakeLock(ss);
+
+ ssl_GetSSL3HandshakeLock(ss);
+ rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */
+ ssl_ReleaseSSL3HandshakeLock(ss);
+
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+/*
+** Same as above, but with an I/O timeout.
+ */
+SSL_IMPORT SECStatus
+SSL_ReHandshakeWithTimeout(PRFileDesc *fd,
+ PRBool flushCache,
+ PRIntervalTime timeout)
+{
+ if (SECSuccess != ssl_SetTimeout(fd, timeout)) {
+ return SECFailure;
+ }
+ return SSL_ReHandshake(fd, flushCache);
+}
+
+SECStatus
+SSL_RedoHandshake(PRFileDesc *fd)
+{
+ return SSL_ReHandshake(fd, PR_TRUE);
+}
+
+/* Register an application callback to be called when SSL handshake completes.
+** Acquires and releases HandshakeLock.
+*/
+SECStatus
+SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb,
+ void *client_data)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in HandshakeCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!ss->opt.useSecurity) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ ss->handshakeCallback = cb;
+ ss->handshakeCallbackData = client_data;
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+/* Register an application callback to be called when false start may happen.
+** Acquires and releases HandshakeLock.
+*/
+SECStatus
+SSL_SetCanFalseStartCallback(PRFileDesc *fd, SSLCanFalseStartCallback cb,
+ void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCanFalseStartCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!ss->opt.useSecurity) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ ss->canFalseStartCallback = cb;
+ ss->canFalseStartCallbackData = arg;
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_RecommendedCanFalseStart(PRFileDesc *fd, PRBool *canFalseStart)
+{
+ sslSocket *ss;
+
+ *canFalseStart = PR_FALSE;
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_RecommendedCanFalseStart",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ /* Require a forward-secret key exchange. */
+ *canFalseStart = ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
+ ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
+ ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
+ ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa;
+
+ return SECSuccess;
+}
+
+/* Try to make progress on an SSL handshake by attempting to read the
+** next handshake from the peer, and sending any responses.
+** For non-blocking sockets, returns PR_ERROR_WOULD_BLOCK if it cannot
+** read the next handshake from the underlying socket.
+** Returns when handshake is complete, or application data has
+** arrived that must be taken by application before handshake can continue,
+** or a fatal error occurs.
+** Application should use handshake completion callback to tell which.
+*/
+SECStatus
+SSL_ForceHandshake(PRFileDesc *fd)
+{
+ sslSocket *ss;
+ SECStatus rv = SECFailure;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in ForceHandshake",
+ SSL_GETPID(), fd));
+ return rv;
+ }
+
+ /* Don't waste my time */
+ if (!ss->opt.useSecurity)
+ return SECSuccess;
+
+ if (!ssl_SocketIsBlocking(ss)) {
+ ssl_GetXmitBufLock(ss);
+ if (ss->pendingBuf.len != 0) {
+ int sent = ssl_SendSavedWriteData(ss);
+ if ((sent < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) {
+ ssl_ReleaseXmitBufLock(ss);
+ return SECFailure;
+ }
+ }
+ ssl_ReleaseXmitBufLock(ss);
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+
+ if (ss->version >= SSL_LIBRARY_VERSION_3_0) {
+ int gatherResult;
+
+ ssl_GetRecvBufLock(ss);
+ gatherResult = ssl3_GatherCompleteHandshake(ss, 0);
+ ssl_ReleaseRecvBufLock(ss);
+ if (gatherResult > 0) {
+ rv = SECSuccess;
+ } else {
+ if (gatherResult == 0) {
+ PORT_SetError(PR_END_OF_FILE_ERROR);
+ }
+ /* We can rely on ssl3_GatherCompleteHandshake to set
+ * PR_WOULD_BLOCK_ERROR as needed here. */
+ rv = SECFailure;
+ }
+ } else {
+ PORT_Assert(!ss->firstHsDone);
+ rv = ssl_Do1stHandshake(ss);
+ }
+
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+/*
+ ** Same as above, but with an I/O timeout.
+ */
+SSL_IMPORT SECStatus
+SSL_ForceHandshakeWithTimeout(PRFileDesc *fd,
+ PRIntervalTime timeout)
+{
+ if (SECSuccess != ssl_SetTimeout(fd, timeout)) {
+ return SECFailure;
+ }
+ return SSL_ForceHandshake(fd);
+}
+
+/************************************************************************/
+
+/*
+** Save away write data that is trying to be written before the security
+** handshake has been completed. When the handshake is completed, we will
+** flush this data out.
+** Caller must hold xmitBufLock
+*/
+SECStatus
+ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ rv = sslBuffer_Append(&ss->pendingBuf, data, len);
+ SSL_TRC(5, ("%d: SSL[%d]: saving %u bytes of data (%u total saved so far)",
+ SSL_GETPID(), ss->fd, len, ss->pendingBuf.len));
+ return rv;
+}
+
+/*
+** Send saved write data. This will flush out data sent prior to a
+** complete security handshake. Hopefully there won't be too much of it.
+** Returns count of the bytes sent, NOT a SECStatus.
+** Caller must hold xmitBufLock
+*/
+int
+ssl_SendSavedWriteData(sslSocket *ss)
+{
+ int rv = 0;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ if (ss->pendingBuf.len != 0) {
+ SSL_TRC(5, ("%d: SSL[%d]: sending %d bytes of saved data",
+ SSL_GETPID(), ss->fd, ss->pendingBuf.len));
+ rv = ssl_DefSend(ss, ss->pendingBuf.buf, ss->pendingBuf.len, 0);
+ if (rv < 0) {
+ return rv;
+ }
+ ss->pendingBuf.len -= rv;
+ if (ss->pendingBuf.len > 0 && rv > 0) {
+ /* UGH !! This shifts the whole buffer down by copying it */
+ PORT_Memmove(ss->pendingBuf.buf, ss->pendingBuf.buf + rv,
+ ss->pendingBuf.len);
+ }
+ }
+ return rv;
+}
+
+/************************************************************************/
+
+/*
+** Receive some application data on a socket. Reads SSL records from the input
+** stream, decrypts them and then copies them to the output buffer.
+** Called from ssl_SecureRecv() below.
+**
+** Caller does NOT hold 1stHandshakeLock because that handshake is over.
+** Caller doesn't call this until initial handshake is complete.
+** The call to ssl3_GatherAppDataRecord may encounter handshake
+** messages from a subsequent handshake.
+**
+** This code is similar to, and easily confused with,
+** ssl_GatherRecord1stHandshake() in sslcon.c
+*/
+static int
+DoRecv(sslSocket *ss, unsigned char *out, int len, int flags)
+{
+ int rv;
+ int amount;
+ int available;
+
+ /* ssl3_GatherAppDataRecord may call ssl_FinishHandshake, which needs the
+ * 1stHandshakeLock. */
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetRecvBufLock(ss);
+
+ available = ss->gs.writeOffset - ss->gs.readOffset;
+ if (available == 0) {
+ /* Wait for application data to arrive. */
+ rv = ssl3_GatherAppDataRecord(ss, 0);
+ if (rv <= 0) {
+ if (rv == 0) {
+ /* EOF */
+ SSL_TRC(10, ("%d: SSL[%d]: ssl_recv EOF",
+ SSL_GETPID(), ss->fd));
+ goto done;
+ }
+ if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
+ /* Some random error */
+ goto done;
+ }
+
+ /*
+ ** Gather record is blocked waiting for more record data to
+ ** arrive. Try to process what we have already received
+ */
+ } else {
+ /* Gather record has finished getting a complete record */
+ }
+
+ /* See if any clear data is now available */
+ available = ss->gs.writeOffset - ss->gs.readOffset;
+ if (available == 0) {
+ /*
+ ** No partial data is available. Force error code to
+ ** EWOULDBLOCK so that caller will try again later. Note
+ ** that the error code is probably EWOULDBLOCK already,
+ ** but if it isn't (for example, if we received a zero
+ ** length record) then this will force it to be correct.
+ */
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ rv = SECFailure;
+ goto done;
+ }
+ SSL_TRC(30, ("%d: SSL[%d]: partial data ready, available=%d",
+ SSL_GETPID(), ss->fd, available));
+ }
+
+ if (IS_DTLS(ss) && (len < available)) {
+ /* DTLS does not allow you to do partial reads */
+ SSL_TRC(30, ("%d: SSL[%d]: DTLS short read. len=%d available=%d",
+ SSL_GETPID(), ss->fd, len, available));
+ ss->gs.readOffset += available;
+ PORT_SetError(SSL_ERROR_RX_SHORT_DTLS_READ);
+ rv = SECFailure;
+ goto done;
+ }
+
+ /* Dole out clear data to reader */
+ amount = PR_MIN(len, available);
+ PORT_Memcpy(out, ss->gs.buf.buf + ss->gs.readOffset, amount);
+ if (!(flags & PR_MSG_PEEK)) {
+ ss->gs.readOffset += amount;
+ }
+ PORT_Assert(ss->gs.readOffset <= ss->gs.writeOffset);
+ rv = amount;
+
+#ifdef DEBUG
+ /* In Debug builds free and zero gather plaintext buffer after its content
+ * has been used/copied for advanced ASAN coverage/utilization.
+ * This frees the buffer after reception of application data,
+ * non-application data is freed at the end of
+ * ssl3con.c/ssl3_HandleRecord(). */
+ if (ss->gs.writeOffset == ss->gs.readOffset) {
+ sslBuffer_Clear(&ss->gs.buf);
+ }
+#endif
+
+ SSL_TRC(30, ("%d: SSL[%d]: amount=%d available=%d",
+ SSL_GETPID(), ss->fd, amount, available));
+ PRINT_BUF(4, (ss, "DoRecv receiving plaintext:", out, amount));
+
+done:
+ ssl_ReleaseRecvBufLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return rv;
+}
+
+/************************************************************************/
+
+SECStatus
+ssl_CreateSecurityInfo(sslSocket *ss)
+{
+ SECStatus status;
+
+ ssl_GetXmitBufLock(ss);
+ status = sslBuffer_Grow(&ss->sec.writeBuf, 4096);
+ ssl_ReleaseXmitBufLock(ss);
+
+ return status;
+}
+
+SECStatus
+ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os)
+{
+ ss->sec.isServer = os->sec.isServer;
+
+ ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert);
+ if (os->sec.peerCert && !ss->sec.peerCert)
+ goto loser;
+
+ return SECSuccess;
+
+loser:
+ return SECFailure;
+}
+
+/* Reset sec back to its initial state.
+** Caller holds any relevant locks.
+*/
+void
+ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset)
+{
+ if (sec->localCert) {
+ CERT_DestroyCertificate(sec->localCert);
+ sec->localCert = NULL;
+ }
+ if (sec->peerCert) {
+ CERT_DestroyCertificate(sec->peerCert);
+ sec->peerCert = NULL;
+ }
+ if (sec->peerKey) {
+ SECKEY_DestroyPublicKey(sec->peerKey);
+ sec->peerKey = NULL;
+ }
+
+ /* cleanup the ci */
+ if (sec->ci.sid != NULL) {
+ ssl_FreeSID(sec->ci.sid);
+ }
+ PORT_ZFree(sec->ci.sendBuf.buf, sec->ci.sendBuf.space);
+ if (doMemset) {
+ memset(&sec->ci, 0, sizeof sec->ci);
+ }
+}
+
+/*
+** Called from SSL_ResetHandshake (above), and
+** from ssl_FreeSocket in sslsock.c
+** Caller should hold relevant locks (e.g. XmitBufLock)
+*/
+void
+ssl_DestroySecurityInfo(sslSecurityInfo *sec)
+{
+ ssl_ResetSecurityInfo(sec, PR_FALSE);
+
+ PORT_ZFree(sec->writeBuf.buf, sec->writeBuf.space);
+ sec->writeBuf.buf = 0;
+
+ memset(sec, 0, sizeof *sec);
+}
+
+/************************************************************************/
+
+int
+ssl_SecureConnect(sslSocket *ss, const PRNetAddr *sa)
+{
+ PRFileDesc *osfd = ss->fd->lower;
+ int rv;
+
+ if (ss->opt.handshakeAsServer) {
+ ss->handshake = ssl_BeginServerHandshake;
+ ss->handshaking = sslHandshakingAsServer;
+ } else {
+ ss->handshake = ssl_BeginClientHandshake;
+ ss->handshaking = sslHandshakingAsClient;
+ }
+
+ /* connect to server */
+ rv = osfd->methods->connect(osfd, sa, ss->cTimeout);
+ if (rv == PR_SUCCESS) {
+ ss->TCPconnected = 1;
+ } else {
+ int err = PR_GetError();
+ SSL_DBG(("%d: SSL[%d]: connect failed, errno=%d",
+ SSL_GETPID(), ss->fd, err));
+ if (err == PR_IS_CONNECTED_ERROR) {
+ ss->TCPconnected = 1;
+ }
+ }
+
+ SSL_TRC(5, ("%d: SSL[%d]: secure connect completed, rv == %d",
+ SSL_GETPID(), ss->fd, rv));
+ return rv;
+}
+
+/*
+ * Also, in the unlikely event that the TCP pipe is full and the peer stops
+ * reading, the SSL3_SendAlert call in ssl_SecureClose and ssl_SecureShutdown
+ * may block indefinitely in blocking mode, and may fail (without retrying)
+ * in non-blocking mode.
+ */
+
+int
+ssl_SecureClose(sslSocket *ss)
+{
+ int rv;
+
+ if (!(ss->shutdownHow & ssl_SHUTDOWN_SEND) &&
+ ss->firstHsDone) {
+
+ /* We don't want the final alert to be Nagle delayed. */
+ if (!ss->delayDisabled) {
+ ssl_EnableNagleDelay(ss, PR_FALSE);
+ ss->delayDisabled = 1;
+ }
+
+ (void)SSL3_SendAlert(ss, alert_warning, close_notify);
+ }
+ rv = ssl_DefClose(ss);
+ return rv;
+}
+
+/* Caller handles all locking */
+int
+ssl_SecureShutdown(sslSocket *ss, int nsprHow)
+{
+ PRFileDesc *osfd = ss->fd->lower;
+ int rv;
+ PRIntn sslHow = nsprHow + 1;
+
+ if ((unsigned)nsprHow > PR_SHUTDOWN_BOTH) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return PR_FAILURE;
+ }
+
+ if ((sslHow & ssl_SHUTDOWN_SEND) != 0 &&
+ !(ss->shutdownHow & ssl_SHUTDOWN_SEND) &&
+ ss->firstHsDone) {
+
+ (void)SSL3_SendAlert(ss, alert_warning, close_notify);
+ }
+
+ rv = osfd->methods->shutdown(osfd, nsprHow);
+
+ ss->shutdownHow |= sslHow;
+
+ return rv;
+}
+
+/************************************************************************/
+
+static SECStatus
+tls13_CheckKeyUpdate(sslSocket *ss, SSLSecretDirection dir)
+{
+ PRBool keyUpdate;
+ ssl3CipherSpec *spec;
+ sslSequenceNumber seqNum;
+ sslSequenceNumber margin;
+ tls13KeyUpdateRequest keyUpdateRequest;
+ SECStatus rv = SECSuccess;
+
+ /* Bug 1413368: enable for DTLS */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 || IS_DTLS(ss)) {
+ return SECSuccess;
+ }
+
+ /* If both sides update at the same number, then this will cause two updates
+ * to happen at once. The problem is that the KeyUpdate itself consumes a
+ * sequence number, and that will trigger the reading side to request an
+ * update.
+ *
+ * If we have the writing side update first, the writer will be the one that
+ * drives the update. An update by the writer doesn't need a response, so
+ * it is more efficient overall. The margins here are pretty arbitrary, but
+ * having the write margin larger reduces the number of times that a
+ * KeyUpdate is sent by a reader. */
+ ssl_GetSpecReadLock(ss);
+ if (dir == ssl_secret_read) {
+ spec = ss->ssl3.crSpec;
+ margin = spec->cipherDef->max_records / 8;
+ } else {
+ spec = ss->ssl3.cwSpec;
+ margin = spec->cipherDef->max_records / 4;
+ }
+ seqNum = spec->nextSeqNum;
+ keyUpdate = seqNum > spec->cipherDef->max_records - margin;
+ ssl_ReleaseSpecReadLock(ss);
+ if (!keyUpdate) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(5, ("%d: SSL[%d]: automatic key update at %llx for %s cipher spec",
+ SSL_GETPID(), ss->fd, seqNum,
+ (dir == ssl_secret_read) ? "read" : "write"));
+ keyUpdateRequest = (dir == ssl_secret_read) ? update_requested : update_not_requested;
+ ssl_GetSSL3HandshakeLock(ss);
+ if (ss->ssl3.clientCertRequested) {
+ ss->ssl3.keyUpdateDeferred = PR_TRUE;
+ ss->ssl3.deferredKeyUpdateRequest = keyUpdateRequest;
+ } else {
+ rv = tls13_SendKeyUpdate(ss, keyUpdateRequest,
+ dir == ssl_secret_write /* buffer */);
+ }
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ return rv;
+}
+
+int
+ssl_SecureRecv(sslSocket *ss, unsigned char *buf, int len, int flags)
+{
+ int rv = 0;
+
+ if (ss->shutdownHow & ssl_SHUTDOWN_RCV) {
+ PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR);
+ return PR_FAILURE;
+ }
+ if (flags & ~PR_MSG_PEEK) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return PR_FAILURE;
+ }
+
+ if (!ssl_SocketIsBlocking(ss) && !ss->opt.fdx) {
+ ssl_GetXmitBufLock(ss);
+ if (ss->pendingBuf.len != 0) {
+ rv = ssl_SendSavedWriteData(ss);
+ if ((rv < 0) && (PORT_GetError() != PR_WOULD_BLOCK_ERROR)) {
+ ssl_ReleaseXmitBufLock(ss);
+ return SECFailure;
+ }
+ }
+ ssl_ReleaseXmitBufLock(ss);
+ }
+
+ rv = 0;
+ if (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ return tls13_Read0RttData(ss, buf, len);
+ }
+
+ /* If any of these is non-zero, the initial handshake is not done. */
+ if (!ss->firstHsDone) {
+ ssl_Get1stHandshakeLock(ss);
+ if (ss->handshake) {
+ rv = ssl_Do1stHandshake(ss);
+ }
+ ssl_Release1stHandshakeLock(ss);
+ } else {
+ if (tls13_CheckKeyUpdate(ss, ssl_secret_read) != SECSuccess) {
+ rv = PR_FAILURE;
+ }
+ }
+ if (rv < 0) {
+ if (PORT_GetError() == PR_WOULD_BLOCK_ERROR &&
+ !PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ return tls13_Read0RttData(ss, buf, len);
+ }
+ return rv;
+ }
+
+ if (len == 0)
+ return 0;
+
+ rv = DoRecv(ss, (unsigned char *)buf, len, flags);
+ SSL_TRC(2, ("%d: SSL[%d]: recving %d bytes securely (errno=%d)",
+ SSL_GETPID(), ss->fd, rv, PORT_GetError()));
+ return rv;
+}
+
+int
+ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len)
+{
+ return ssl_SecureRecv(ss, buf, len, 0);
+}
+
+/* Caller holds the SSL Socket's write lock. SSL_LOCK_WRITER(ss) */
+int
+ssl_SecureSend(sslSocket *ss, const unsigned char *buf, int len, int flags)
+{
+ int rv = 0;
+ PRBool zeroRtt = PR_FALSE;
+
+ SSL_TRC(2, ("%d: SSL[%d]: SecureSend: sending %d bytes",
+ SSL_GETPID(), ss->fd, len));
+
+ if (ss->shutdownHow & ssl_SHUTDOWN_SEND) {
+ PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR);
+ rv = PR_FAILURE;
+ goto done;
+ }
+ if (flags) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ rv = PR_FAILURE;
+ goto done;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ if (ss->pendingBuf.len != 0) {
+ PORT_Assert(ss->pendingBuf.len > 0);
+ rv = ssl_SendSavedWriteData(ss);
+ if (rv >= 0 && ss->pendingBuf.len != 0) {
+ PORT_Assert(ss->pendingBuf.len > 0);
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ rv = SECFailure;
+ }
+ }
+ ssl_ReleaseXmitBufLock(ss);
+ if (rv < 0) {
+ goto done;
+ }
+
+ if (len > 0)
+ ss->writerThread = PR_GetCurrentThread();
+
+ /* Check to see if we can write even though we're not finished.
+ *
+ * Case 1: False start
+ * Case 2: TLS 1.3 0-RTT
+ */
+ if (!ss->firstHsDone) {
+ PRBool allowEarlySend = PR_FALSE;
+ PRBool firstClientWrite = PR_FALSE;
+
+ ssl_Get1stHandshakeLock(ss);
+ /* The client can sometimes send before the handshake is fully
+ * complete. In TLS 1.2: false start; in TLS 1.3: 0-RTT. */
+ if (!ss->sec.isServer &&
+ (ss->opt.enableFalseStart || ss->opt.enable0RttData)) {
+ ssl_GetSSL3HandshakeLock(ss);
+ zeroRtt = ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted;
+ allowEarlySend = ss->ssl3.hs.canFalseStart || zeroRtt;
+ firstClientWrite = ss->ssl3.hs.ws == idle_handshake;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ }
+ /* Allow the server to send 0.5 RTT data in TLS 1.3. Requesting a
+ * certificate implies that the server might condition its sending on
+ * client authentication, so force servers that do that to wait.
+ *
+ * What might not be obvious here is that this allows 0.5 RTT when doing
+ * PSK-based resumption. As a result, 0.5 RTT is always enabled when
+ * early data is accepted.
+ *
+ * This check might be more conservative than absolutely necessary.
+ * It's possible that allowing 0.5 RTT data when the server requests,
+ * but does not require client authentication is safe because we can
+ * expect the server to check for a client certificate properly. */
+ if (ss->sec.isServer &&
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ !tls13_ShouldRequestClientAuth(ss)) {
+ ssl_GetSSL3HandshakeLock(ss);
+ allowEarlySend = TLS13_IN_HS_STATE(ss, wait_finished);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ }
+ if (!allowEarlySend && ss->handshake) {
+ rv = ssl_Do1stHandshake(ss);
+ }
+ if (firstClientWrite) {
+ /* Wait until after sending ClientHello and double-check 0-RTT. */
+ ssl_GetSSL3HandshakeLock(ss);
+ zeroRtt = ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ }
+ ssl_Release1stHandshakeLock(ss);
+ }
+
+ if (rv < 0) {
+ ss->writerThread = NULL;
+ goto done;
+ }
+
+ if (ss->firstHsDone) {
+ if (tls13_CheckKeyUpdate(ss, ssl_secret_write) != SECSuccess) {
+ rv = PR_FAILURE;
+ goto done;
+ }
+ }
+
+ if (zeroRtt) {
+ /* There's a limit to the number of early data octets we can send.
+ *
+ * Note that taking this lock doesn't prevent the cipher specs from
+ * being changed out between here and when records are ultimately
+ * encrypted. The only effect of that is to occasionally do an
+ * unnecessary short write when data is identified as 0-RTT here but
+ * 1-RTT later.
+ */
+ ssl_GetSpecReadLock(ss);
+ len = tls13_LimitEarlyData(ss, ssl_ct_application_data, len);
+ ssl_ReleaseSpecReadLock(ss);
+ }
+
+ /* Check for zero length writes after we do housekeeping so we make forward
+ * progress.
+ */
+ if (len == 0) {
+ rv = 0;
+ goto done;
+ }
+ PORT_Assert(buf != NULL);
+ if (!buf) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ rv = PR_FAILURE;
+ goto done;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_SendApplicationData(ss, buf, len, flags);
+ ssl_ReleaseXmitBufLock(ss);
+ ss->writerThread = NULL;
+done:
+ if (rv < 0) {
+ SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count, error %d",
+ SSL_GETPID(), ss->fd, rv, PORT_GetError()));
+ } else {
+ SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count",
+ SSL_GETPID(), ss->fd, rv));
+ }
+ return rv;
+}
+
+int
+ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len)
+{
+ return ssl_SecureSend(ss, buf, len, 0);
+}
+
+SECStatus
+SSLExp_RecordLayerWriteCallback(PRFileDesc *fd, SSLRecordWriteCallback cb,
+ void *arg)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: invalid socket for SSL_RecordLayerWriteCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ if (IS_DTLS(ss)) {
+ SSL_DBG(("%d: SSL[%d]: DTLS socket for SSL_RecordLayerWriteCallback",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* This needs both HS and Xmit locks because this value is checked under
+ * both locks. HS to disable reading from the underlying IO layer; Xmit to
+ * prevent writing. */
+ ssl_GetSSL3HandshakeLock(ss);
+ ssl_GetXmitBufLock(ss);
+ ss->recordWriteCallback = cb;
+ ss->recordWriteCallbackArg = arg;
+ ssl_ReleaseXmitBufLock(ss);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ return SECSuccess;
+}
+
+SECStatus
+SSL_AlertReceivedCallback(PRFileDesc *fd, SSLAlertCallback cb, void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: unable to find socket in SSL_AlertReceivedCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ss->alertReceivedCallback = cb;
+ ss->alertReceivedCallbackArg = arg;
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_AlertSentCallback(PRFileDesc *fd, SSLAlertCallback cb, void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: unable to find socket in SSL_AlertSentCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ss->alertSentCallback = cb;
+ ss->alertSentCallbackArg = arg;
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSLBadCertHook",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ss->handleBadCert = f;
+ ss->badCertArg = arg;
+
+ return SECSuccess;
+}
+
+/*
+ * Allow the application to pass the url or hostname into the SSL library
+ * so that we can do some checking on it. It will be used for the value in
+ * SNI extension of client hello message.
+ */
+SECStatus
+SSL_SetURL(PRFileDesc *fd, const char *url)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ SECStatus rv = SECSuccess;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSLSetURL",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (ss->url) {
+ PORT_Free((void *)ss->url); /* CONST */
+ }
+
+ ss->url = (const char *)PORT_Strdup(url);
+ if (ss->url == NULL) {
+ rv = SECFailure;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+/*
+ * Allow the application to pass the set of trust anchors
+ */
+SECStatus
+SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ CERTDistNames *names = NULL;
+
+ if (!certList) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ names = CERT_DistNamesFromCertList(certList);
+ if (names == NULL) {
+ return SECFailure;
+ }
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+ if (ss->ssl3.ca_list) {
+ CERT_FreeDistNames(ss->ssl3.ca_list);
+ }
+ ss->ssl3.ca_list = names;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+/*
+** Returns Negative number on error, zero or greater on success.
+** Returns the amount of data immediately available to be read.
+*/
+int
+SSL_DataPending(PRFileDesc *fd)
+{
+ sslSocket *ss;
+ int rv = 0;
+
+ ss = ssl_FindSocket(fd);
+
+ if (ss && ss->opt.useSecurity) {
+ ssl_GetRecvBufLock(ss);
+ rv = ss->gs.writeOffset - ss->gs.readOffset;
+ ssl_ReleaseRecvBufLock(ss);
+ }
+
+ return rv;
+}
+
+SECStatus
+SSL_InvalidateSession(PRFileDesc *fd)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ SECStatus rv = SECFailure;
+
+ if (ss) {
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (ss->sec.ci.sid) {
+ ssl_UncacheSessionID(ss);
+ rv = SECSuccess;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ }
+ return rv;
+}
+
+SECItem *
+SSL_GetSessionID(PRFileDesc *fd)
+{
+ sslSocket *ss;
+ SECItem *item = NULL;
+
+ ss = ssl_FindSocket(fd);
+ if (ss) {
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (ss->opt.useSecurity && ss->firstHsDone && ss->sec.ci.sid) {
+ item = (SECItem *)PORT_Alloc(sizeof(SECItem));
+ if (item) {
+ sslSessionID *sid = ss->sec.ci.sid;
+ item->len = sid->u.ssl3.sessionIDLength;
+ item->data = (unsigned char *)PORT_Alloc(item->len);
+ PORT_Memcpy(item->data, sid->u.ssl3.sessionID, item->len);
+ }
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ }
+ return item;
+}
+
+SECStatus
+SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss)
+ return SECFailure;
+ if (!dbHandle) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ss->dbHandle = dbHandle;
+ return SECSuccess;
+}
+
+/* DO NOT USE. This function was exported in ssl.def with the wrong signature;
+ * this implementation exists to maintain link-time compatibility.
+ */
+int
+SSL_RestartHandshakeAfterCertReq(sslSocket *ss,
+ CERTCertificate *cert,
+ SECKEYPrivateKey *key,
+ CERTCertificateList *certChain)
+{
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return -1;
+}
+
+/* DO NOT USE. This function was exported in ssl.def with the wrong signature;
+ * this implementation exists to maintain link-time compatibility.
+ */
+int
+SSL_RestartHandshakeAfterServerCert(sslSocket *ss)
+{
+ PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
+ return -1;
+}
+
+/* See documentation in ssl.h */
+SECStatus
+SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode error)
+{
+ SECStatus rv;
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ rv = ssl3_AuthCertificateComplete(ss, error);
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+SECStatus
+SSL_ClientCertCallbackComplete(PRFileDesc *fd, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey,
+ CERTCertificate *clientCertificate)
+{
+ SECStatus rv;
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_ClientCertCallbackComplete",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ /* There exists a codepath which exercises each lock.
+ * Socket is blocked whilst waiting on this callback anyway. */
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetRecvBufLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (!ss->ssl3.hs.clientCertificatePending) {
+ /* Application invoked callback at wrong time */
+ SSL_DBG(("%d: SSL[%d]: socket not waiting for SSL_ClientCertCallbackComplete",
+ SSL_GETPID(), fd));
+ PORT_SetError(PR_INVALID_STATE_ERROR);
+ rv = SECFailure;
+ goto cleanup;
+ }
+
+ rv = ssl3_ClientCertCallbackComplete(ss, outcome, clientPrivateKey, clientCertificate);
+
+cleanup:
+ ssl_ReleaseRecvBufLock(ss);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return rv;
+}
+
+/* For more info see ssl.h */
+SECStatus
+SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func,
+ void *arg)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ss->sniSocketConfig = func;
+ ss->sniSocketConfigArg = arg;
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/sslsnce.c b/security/nss/lib/ssl/sslsnce.c
new file mode 100644
index 0000000000..49f041c972
--- /dev/null
+++ b/security/nss/lib/ssl/sslsnce.c
@@ -0,0 +1,2251 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This file implements the SERVER Session ID cache.
+ * NOTE: The contents of this file are NOT used by the client.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Note: ssl_FreeSID() in sslnonce.c gets used for both client and server
+ * cache sids!
+ *
+ * About record locking among different server processes:
+ *
+ * All processes that are part of the same conceptual server (serving on
+ * the same address and port) MUST share a common SSL session cache.
+ * This code makes the content of the shared cache accessible to all
+ * processes on the same "server". This code works on Unix and Win32 only.
+ *
+ * We use NSPR anonymous shared memory and move data to & from shared memory.
+ * We must do explicit locking of the records for all reads and writes.
+ * The set of Cache entries are divided up into "sets" of 128 entries.
+ * Each set is protected by a lock. There may be one or more sets protected
+ * by each lock. That is, locks to sets are 1:N.
+ * There is one lock for the entire cert cache.
+ * There is one lock for the set of wrapped sym wrap keys.
+ *
+ * The anonymous shared memory is laid out as if it were declared like this:
+ *
+ * struct {
+ * cacheDescriptor desc;
+ * sidCacheLock sidCacheLocks[ numSIDCacheLocks];
+ * sidCacheLock keyCacheLock;
+ * sidCacheLock certCacheLock;
+ * sidCacheSet sidCacheSets[ numSIDCacheSets ];
+ * sidCacheEntry sidCacheData[ numSIDCacheEntries];
+ * certCacheEntry certCacheData[numCertCacheEntries];
+ * SSLWrappedSymWrappingKey keyCacheData[SSL_NUM_WRAP_KEYS][SSL_NUM_WRAP_MECHS];
+ * PRUint8 keyNameSuffix[SELF_ENCRYPT_KEY_VAR_NAME_LEN]
+ * encKeyCacheEntry ticketEncKey; // Wrapped
+ * encKeyCacheEntry ticketMacKey; // Wrapped
+ * PRBool ticketKeysValid;
+ * sidCacheLock srvNameCacheLock;
+ * srvNameCacheEntry srvNameData[ numSrvNameCacheEntries ];
+ * } cacheMemCacheData;
+ */
+#include "seccomon.h"
+
+#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_OS2)
+
+#include "cert.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "pk11func.h"
+#include "base64.h"
+#include "keyhi.h"
+#include "blapit.h"
+#include "nss.h" /* for NSS_RegisterShutdown */
+#include "sechash.h"
+#include "selfencrypt.h"
+#include <stdio.h>
+
+#if defined(XP_UNIX)
+
+#include <syslog.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <errno.h>
+#include <signal.h>
+#include "unix_err.h"
+
+#else
+
+#ifdef XP_WIN32
+#include <wtypes.h>
+#include "win32err.h"
+#endif
+
+#endif
+#include <sys/types.h>
+
+#include "nspr.h"
+#include "sslmutex.h"
+
+/*
+** Format of a cache entry in the shared memory.
+*/
+PR_STATIC_ASSERT(sizeof(PRTime) == 8);
+struct sidCacheEntryStr {
+ /* 16 */ PRIPv6Addr addr; /* client's IP address */
+ /* 8 */ PRTime creationTime;
+ /* 8 */ PRTime lastAccessTime;
+ /* 8 */ PRTime expirationTime;
+ /* 2 */ PRUint16 version;
+ /* 1 */ PRUint8 valid;
+ /* 1 */ PRUint8 sessionIDLength;
+ /* 32 */ PRUint8 sessionID[SSL3_SESSIONID_BYTES];
+ /* 2 */ PRUint16 authType;
+ /* 2 */ PRUint16 authKeyBits;
+ /* 2 */ PRUint16 keaType;
+ /* 2 */ PRUint16 keaKeyBits;
+ /* 4 */ PRUint32 signatureScheme;
+ /* 4 */ PRUint32 keaGroup;
+ /* 92 - common header total */
+
+ union {
+ struct {
+ /* 2 */ ssl3CipherSuite cipherSuite;
+ /* 52 */ ssl3SidKeys keys; /* keys, wrapped as needed. */
+
+ /* 4 */ PRUint32 masterWrapMech;
+ /* 4 */ PRInt32 certIndex;
+ /* 4 */ PRInt32 srvNameIndex;
+ /* 32 */ PRUint8 srvNameHash[SHA256_LENGTH]; /* SHA256 name hash */
+ /* 2 */ PRUint16 namedCurve;
+/*100 */} ssl3;
+
+/* force sizeof(sidCacheEntry) to be a multiple of cache line size */
+struct {
+ /*116 */ PRUint8 filler[116]; /* 92+116==208, a multiple of 16 */
+} forceSize;
+ } u;
+};
+typedef struct sidCacheEntryStr sidCacheEntry;
+
+/* The length of this struct is supposed to be a power of 2, e.g. 4KB */
+struct certCacheEntryStr {
+ PRUint16 certLength; /* 2 */
+ PRUint16 sessionIDLength; /* 2 */
+ PRUint8 sessionID[SSL3_SESSIONID_BYTES]; /* 32 */
+ PRUint8 cert[SSL_MAX_CACHED_CERT_LEN]; /* 4060 */
+}; /* total 4096 */
+typedef struct certCacheEntryStr certCacheEntry;
+
+struct sidCacheLockStr {
+ PRUint32 timeStamp;
+ sslMutex mutex;
+ sslPID pid;
+};
+typedef struct sidCacheLockStr sidCacheLock;
+
+struct sidCacheSetStr {
+ PRIntn next;
+};
+typedef struct sidCacheSetStr sidCacheSet;
+
+struct encKeyCacheEntryStr {
+ PRUint8 bytes[512];
+ PRInt32 length;
+};
+typedef struct encKeyCacheEntryStr encKeyCacheEntry;
+
+#define SSL_MAX_DNS_HOST_NAME 1024
+
+struct srvNameCacheEntryStr {
+ PRUint16 type; /* 2 */
+ PRUint16 nameLen; /* 2 */
+ PRUint8 name[SSL_MAX_DNS_HOST_NAME + 12]; /* 1034 */
+ PRUint8 nameHash[SHA256_LENGTH]; /* 32 */
+ /* 1072 */
+};
+typedef struct srvNameCacheEntryStr srvNameCacheEntry;
+
+struct cacheDescStr {
+
+ PRUint32 cacheMemSize;
+
+ PRUint32 numSIDCacheLocks;
+ PRUint32 numSIDCacheSets;
+ PRUint32 numSIDCacheSetsPerLock;
+
+ PRUint32 numSIDCacheEntries;
+ PRUint32 sidCacheSize;
+
+ PRUint32 numCertCacheEntries;
+ PRUint32 certCacheSize;
+
+ PRUint32 numKeyCacheEntries;
+ PRUint32 keyCacheSize;
+
+ PRUint32 numSrvNameCacheEntries;
+ PRUint32 srvNameCacheSize;
+
+ PRUint32 ssl3Timeout;
+
+ PRUint32 numSIDCacheLocksInitialized;
+
+ /* These values are volatile, and are accessed through sharedCache-> */
+ PRUint32 nextCertCacheEntry; /* certCacheLock protects */
+ PRBool stopPolling;
+ PRBool everInherited;
+
+ /* The private copies of these values are pointers into shared mem */
+ /* The copies of these values in shared memory are merely offsets */
+ sidCacheLock *sidCacheLocks;
+ sidCacheLock *keyCacheLock;
+ sidCacheLock *certCacheLock;
+ sidCacheLock *srvNameCacheLock;
+ sidCacheSet *sidCacheSets;
+ sidCacheEntry *sidCacheData;
+ certCacheEntry *certCacheData;
+ SSLWrappedSymWrappingKey *keyCacheData;
+ PRUint8 *ticketKeyNameSuffix;
+ encKeyCacheEntry *ticketEncKey;
+ encKeyCacheEntry *ticketMacKey;
+ PRUint32 *ticketKeysValid;
+ srvNameCacheEntry *srvNameCacheData;
+
+ /* Only the private copies of these pointers are valid */
+ char *cacheMem;
+ struct cacheDescStr *sharedCache; /* shared copy of this struct */
+ PRFileMap *cacheMemMap;
+ PRThread *poller;
+ PRUint32 mutexTimeout;
+ PRBool shared;
+};
+typedef struct cacheDescStr cacheDesc;
+
+static cacheDesc globalCache;
+
+static const char envVarName[] = { SSL_ENV_VAR_NAME };
+
+static PRBool isMultiProcess = PR_FALSE;
+
+#define DEF_SID_CACHE_ENTRIES 10000
+#define DEF_CERT_CACHE_ENTRIES 250
+#define MIN_CERT_CACHE_ENTRIES 125 /* the effective size in old releases. */
+#define DEF_KEY_CACHE_ENTRIES 250
+#define DEF_NAME_CACHE_ENTRIES 1000
+
+#define SID_CACHE_ENTRIES_PER_SET 128
+#define SID_ALIGNMENT 16
+
+#define DEF_SSL3_TIMEOUT 86400L /* 24 hours */
+#define MAX_SSL3_TIMEOUT 86400L /* 24 hours */
+#define MIN_SSL3_TIMEOUT 5 /* seconds */
+
+#if defined(AIX) || defined(LINUX) || defined(NETBSD) || defined(OPENBSD)
+#define MAX_SID_CACHE_LOCKS 8 /* two FDs per lock */
+#else
+#define MAX_SID_CACHE_LOCKS 256
+#endif
+
+#define SID_HOWMANY(val, size) (((val) + ((size)-1)) / (size))
+#define SID_ROUNDUP(val, size) ((size)*SID_HOWMANY((val), (size)))
+
+static sslPID myPid;
+static PRUint32 ssl_max_sid_cache_locks = MAX_SID_CACHE_LOCKS;
+
+/* forward static function declarations */
+static PRUint32 SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s,
+ unsigned nl);
+#if defined(XP_UNIX)
+static SECStatus LaunchLockPoller(cacheDesc *cache);
+static SECStatus StopLockPoller(cacheDesc *cache);
+#endif
+
+struct inheritanceStr {
+ PRUint32 cacheMemSize;
+ PRUint32 fmStrLen;
+};
+
+typedef struct inheritanceStr inheritance;
+
+#if defined(_WIN32) || defined(XP_OS2)
+
+#define DEFAULT_CACHE_DIRECTORY "\\temp"
+
+#endif /* _win32 */
+
+#if defined(XP_UNIX)
+
+#define DEFAULT_CACHE_DIRECTORY "/tmp"
+
+#endif /* XP_UNIX */
+
+/************************************************************************/
+
+/* SSL Session Cache has a smaller set of functions to initialize than
+ * ssl does. some ssl_functions can't be initialized before NSS has been
+ * initialized, and the cache may be configured before NSS is initialized
+ * so thus the special init function */
+static SECStatus
+ssl_InitSessionCache()
+{
+ /* currently only one function, which is itself idempotent */
+ return ssl_InitializePRErrorTable();
+}
+
+/* This is used to set locking times for the cache. It is not used to set the
+ * PRTime attributes of sessions, which are driven by ss->now(). */
+static PRUint32
+ssl_CacheNow()
+{
+ return PR_Now() / PR_USEC_PER_SEC;
+}
+
+static PRUint32
+LockSidCacheLock(sidCacheLock *lock, PRUint32 now)
+{
+ SECStatus rv = sslMutex_Lock(&lock->mutex);
+ if (rv != SECSuccess)
+ return 0;
+ if (!now) {
+ now = ssl_CacheNow();
+ }
+
+ lock->timeStamp = now;
+ lock->pid = myPid;
+ return now;
+}
+
+static SECStatus
+UnlockSidCacheLock(sidCacheLock *lock)
+{
+ SECStatus rv;
+
+ lock->pid = 0;
+ rv = sslMutex_Unlock(&lock->mutex);
+ return rv;
+}
+
+/* Returns non-zero |now| or ssl_CacheNow() on success, zero on failure. */
+static PRUint32
+LockSet(cacheDesc *cache, PRUint32 set, PRUint32 now)
+{
+ PRUint32 lockNum = set % cache->numSIDCacheLocks;
+ sidCacheLock *lock = cache->sidCacheLocks + lockNum;
+
+ return LockSidCacheLock(lock, now);
+}
+
+static SECStatus
+UnlockSet(cacheDesc *cache, PRUint32 set)
+{
+ PRUint32 lockNum = set % cache->numSIDCacheLocks;
+ sidCacheLock *lock = cache->sidCacheLocks + lockNum;
+
+ return UnlockSidCacheLock(lock);
+}
+
+/************************************************************************/
+
+/* Put a certificate in the cache. Update the cert index in the sce.
+*/
+static PRUint32
+CacheCert(cacheDesc *cache, CERTCertificate *cert, sidCacheEntry *sce)
+{
+ PRUint32 now;
+ certCacheEntry cce;
+
+ if ((cert->derCert.len > SSL_MAX_CACHED_CERT_LEN) ||
+ (cert->derCert.len <= 0) ||
+ (cert->derCert.data == NULL)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return 0;
+ }
+
+ cce.sessionIDLength = sce->sessionIDLength;
+ PORT_Memcpy(cce.sessionID, sce->sessionID, cce.sessionIDLength);
+
+ cce.certLength = cert->derCert.len;
+ PORT_Memcpy(cce.cert, cert->derCert.data, cce.certLength);
+
+ /* get lock on cert cache */
+ now = LockSidCacheLock(cache->certCacheLock, 0);
+ if (now) {
+
+ /* Find where to place the next cert cache entry. */
+ cacheDesc *sharedCache = cache->sharedCache;
+ PRUint32 ndx = sharedCache->nextCertCacheEntry;
+
+ /* write the entry */
+ cache->certCacheData[ndx] = cce;
+
+ /* remember where we put it. */
+ sce->u.ssl3.certIndex = ndx;
+
+ /* update the "next" cache entry index */
+ sharedCache->nextCertCacheEntry =
+ (ndx + 1) % cache->numCertCacheEntries;
+
+ UnlockSidCacheLock(cache->certCacheLock);
+ }
+ return now;
+}
+
+/* Server configuration hash tables need to account the SECITEM.type
+ * field as well. These functions accomplish that. */
+static PLHashNumber
+Get32BitNameHash(const SECItem *name)
+{
+ PLHashNumber rv = SECITEM_Hash(name);
+
+ PRUint8 *rvc = (PRUint8 *)&rv;
+ rvc[name->len % sizeof(rv)] ^= name->type;
+
+ return rv;
+}
+
+/* Put a name in the cache. Update the cert index in the sce.
+*/
+static PRUint32
+CacheSrvName(cacheDesc *cache, SECItem *name, sidCacheEntry *sce)
+{
+ PRUint32 now;
+ PRUint32 ndx;
+ srvNameCacheEntry snce;
+
+ if (!name || name->len <= 0 ||
+ name->len > SSL_MAX_DNS_HOST_NAME) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return 0;
+ }
+
+ snce.type = name->type;
+ snce.nameLen = name->len;
+ PORT_Memcpy(snce.name, name->data, snce.nameLen);
+ HASH_HashBuf(HASH_AlgSHA256, snce.nameHash, name->data, name->len);
+
+ /* get index of the next name */
+ ndx = Get32BitNameHash(name);
+ /* get lock on cert cache */
+ now = LockSidCacheLock(cache->srvNameCacheLock, 0);
+ if (now) {
+ if (cache->numSrvNameCacheEntries > 0) {
+ /* Fit the index into array */
+ ndx %= cache->numSrvNameCacheEntries;
+ /* write the entry */
+ cache->srvNameCacheData[ndx] = snce;
+ /* remember where we put it. */
+ sce->u.ssl3.srvNameIndex = ndx;
+ /* Copy hash into sid hash */
+ PORT_Memcpy(sce->u.ssl3.srvNameHash, snce.nameHash, SHA256_LENGTH);
+ }
+ UnlockSidCacheLock(cache->srvNameCacheLock);
+ }
+ return now;
+}
+
+/*
+** Convert local SID to shared memory one
+*/
+static void
+ConvertFromSID(sidCacheEntry *to, sslSessionID *from)
+{
+ to->valid = 1;
+ to->version = from->version;
+ to->addr = from->addr;
+ to->creationTime = from->creationTime;
+ to->lastAccessTime = from->lastAccessTime;
+ to->expirationTime = from->expirationTime;
+ to->authType = from->authType;
+ to->authKeyBits = from->authKeyBits;
+ to->keaType = from->keaType;
+ to->keaKeyBits = from->keaKeyBits;
+ to->keaGroup = from->keaGroup;
+ to->signatureScheme = from->sigScheme;
+
+ to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite;
+ to->u.ssl3.keys = from->u.ssl3.keys;
+ to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech;
+ to->sessionIDLength = from->u.ssl3.sessionIDLength;
+ to->u.ssl3.certIndex = -1;
+ to->u.ssl3.srvNameIndex = -1;
+ PORT_Memcpy(to->sessionID, from->u.ssl3.sessionID,
+ to->sessionIDLength);
+ to->u.ssl3.namedCurve = 0U;
+ if (from->authType == ssl_auth_ecdsa ||
+ from->authType == ssl_auth_ecdh_rsa ||
+ from->authType == ssl_auth_ecdh_ecdsa) {
+ PORT_Assert(from->namedCurve);
+ to->u.ssl3.namedCurve = (PRUint16)from->namedCurve->name;
+ }
+
+ SSL_TRC(8, ("%d: SSL3: ConvertSID: time=%d addr=0x%08x%08x%08x%08x "
+ "cipherSuite=%d",
+ myPid, to->creationTime / PR_USEC_PER_SEC,
+ to->addr.pr_s6_addr32[0], to->addr.pr_s6_addr32[1],
+ to->addr.pr_s6_addr32[2], to->addr.pr_s6_addr32[3],
+ to->u.ssl3.cipherSuite));
+}
+
+/*
+** Convert shared memory cache-entry to local memory based one
+** This is only called from ServerSessionIDLookup().
+*/
+static sslSessionID *
+ConvertToSID(sidCacheEntry *from,
+ certCacheEntry *pcce,
+ srvNameCacheEntry *psnce,
+ CERTCertDBHandle *dbHandle)
+{
+ sslSessionID *to;
+
+ to = PORT_ZNew(sslSessionID);
+ if (!to) {
+ return 0;
+ }
+
+ to->u.ssl3.sessionIDLength = from->sessionIDLength;
+ to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite;
+ to->u.ssl3.keys = from->u.ssl3.keys;
+ to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech;
+ if (from->u.ssl3.srvNameIndex != -1 && psnce) {
+ SECItem name;
+ SECStatus rv;
+ name.type = psnce->type;
+ name.len = psnce->nameLen;
+ name.data = psnce->name;
+ rv = SECITEM_CopyItem(NULL, &to->u.ssl3.srvName, &name);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ PORT_Memcpy(to->u.ssl3.sessionID, from->sessionID, from->sessionIDLength);
+
+ to->urlSvrName = NULL;
+
+ to->u.ssl3.masterModuleID = (SECMODModuleID)-1; /* invalid value */
+ to->u.ssl3.masterSlotID = (CK_SLOT_ID)-1; /* invalid value */
+ to->u.ssl3.masterWrapIndex = 0;
+ to->u.ssl3.masterWrapSeries = 0;
+ to->u.ssl3.masterValid = PR_FALSE;
+
+ to->u.ssl3.clAuthModuleID = (SECMODModuleID)-1; /* invalid value */
+ to->u.ssl3.clAuthSlotID = (CK_SLOT_ID)-1; /* invalid value */
+ to->u.ssl3.clAuthSeries = 0;
+ to->u.ssl3.clAuthValid = PR_FALSE;
+
+ if (from->u.ssl3.certIndex != -1 && pcce) {
+ SECItem derCert;
+
+ derCert.len = pcce->certLength;
+ derCert.data = pcce->cert;
+
+ to->peerCert = CERT_NewTempCertificate(dbHandle, &derCert, NULL,
+ PR_FALSE, PR_TRUE);
+ if (to->peerCert == NULL)
+ goto loser;
+ }
+ if (from->authType == ssl_auth_ecdsa ||
+ from->authType == ssl_auth_ecdh_rsa ||
+ from->authType == ssl_auth_ecdh_ecdsa) {
+ to->namedCurve =
+ ssl_LookupNamedGroup((SSLNamedGroup)from->u.ssl3.namedCurve);
+ }
+
+ to->version = from->version;
+ to->creationTime = from->creationTime;
+ to->lastAccessTime = from->lastAccessTime;
+ to->expirationTime = from->expirationTime;
+ to->cached = in_server_cache;
+ to->addr = from->addr;
+ to->references = 1;
+ to->authType = from->authType;
+ to->authKeyBits = from->authKeyBits;
+ to->keaType = from->keaType;
+ to->keaKeyBits = from->keaKeyBits;
+ to->keaGroup = from->keaGroup;
+ to->sigScheme = from->signatureScheme;
+
+ return to;
+
+loser:
+ if (to) {
+ SECITEM_FreeItem(&to->u.ssl3.srvName, PR_FALSE);
+ PORT_Free(to);
+ }
+ return NULL;
+}
+
+/*
+** Perform some mumbo jumbo on the ip-address and the session-id value to
+** compute a hash value.
+*/
+static PRUint32
+SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl)
+{
+ PRUint32 rv;
+ PRUint32 x[8];
+
+ memset(x, 0, sizeof x);
+ if (nl > sizeof x)
+ nl = sizeof x;
+ memcpy(x, s, nl);
+
+ rv = (addr->pr_s6_addr32[0] ^ addr->pr_s6_addr32[1] ^
+ addr->pr_s6_addr32[2] ^ addr->pr_s6_addr32[3] ^
+ x[0] ^ x[1] ^ x[2] ^ x[3] ^ x[4] ^ x[5] ^ x[6] ^ x[7]) %
+ cache->numSIDCacheSets;
+ return rv;
+}
+
+/*
+** Look something up in the cache. This will invalidate old entries
+** in the process. Caller has locked the cache set!
+** Returns PR_TRUE if found a valid match. PR_FALSE otherwise.
+*/
+static sidCacheEntry *
+FindSID(cacheDesc *cache, PRUint32 setNum, PRUint32 now,
+ const PRIPv6Addr *addr, unsigned char *sessionID,
+ unsigned sessionIDLength)
+{
+ PRUint32 ndx = cache->sidCacheSets[setNum].next;
+ int i;
+
+ sidCacheEntry *set = cache->sidCacheData +
+ (setNum * SID_CACHE_ENTRIES_PER_SET);
+
+ for (i = SID_CACHE_ENTRIES_PER_SET; i > 0; --i) {
+ sidCacheEntry *sce;
+
+ ndx = (ndx - 1) % SID_CACHE_ENTRIES_PER_SET;
+ sce = set + ndx;
+
+ if (!sce->valid)
+ continue;
+
+ if (now > sce->expirationTime) {
+ /* SessionID has timed out. Invalidate the entry. */
+ SSL_TRC(7, ("%d: timed out sid entry addr=%08x%08x%08x%08x now=%x "
+ "time+=%x",
+ myPid, sce->addr.pr_s6_addr32[0],
+ sce->addr.pr_s6_addr32[1], sce->addr.pr_s6_addr32[2],
+ sce->addr.pr_s6_addr32[3], now,
+ sce->expirationTime));
+ sce->valid = 0;
+ continue;
+ }
+
+ /*
+ ** Next, examine specific session-id/addr data to see if the cache
+ ** entry matches our addr+session-id value
+ */
+ if (sessionIDLength == sce->sessionIDLength &&
+ !memcmp(&sce->addr, addr, sizeof(PRIPv6Addr)) &&
+ !memcmp(sce->sessionID, sessionID, sessionIDLength)) {
+ /* Found it */
+ return sce;
+ }
+ }
+
+ PORT_SetError(SSL_ERROR_SESSION_NOT_FOUND);
+ return NULL;
+}
+
+/************************************************************************/
+
+/* This is the primary function for finding entries in the server's sid cache.
+ * Although it is static, this function is called via the global function
+ * pointer ssl_sid_lookup.
+ *
+ * sslNow is the time that the calling socket understands, which might be
+ * different than what the cache uses to maintain its locks.
+ */
+static sslSessionID *
+ServerSessionIDLookup(PRTime sslNow, const PRIPv6Addr *addr,
+ unsigned char *sessionID,
+ unsigned int sessionIDLength,
+ CERTCertDBHandle *dbHandle)
+{
+ sslSessionID *sid = 0;
+ sidCacheEntry *psce;
+ certCacheEntry *pcce = 0;
+ srvNameCacheEntry *psnce = 0;
+ cacheDesc *cache = &globalCache;
+ PRUint32 now;
+ PRUint32 set;
+ PRInt32 cndx;
+ sidCacheEntry sce;
+ certCacheEntry cce;
+ srvNameCacheEntry snce;
+
+ set = SIDindex(cache, addr, sessionID, sessionIDLength);
+ now = LockSet(cache, set, 0);
+ if (!now)
+ return NULL;
+
+ psce = FindSID(cache, set, now, addr, sessionID, sessionIDLength);
+ if (psce) {
+ if ((cndx = psce->u.ssl3.certIndex) != -1) {
+ PRUint32 gotLock = LockSidCacheLock(cache->certCacheLock, now);
+ if (gotLock) {
+ pcce = &cache->certCacheData[cndx];
+
+ /* See if the cert's session ID matches the sce cache. */
+ if ((pcce->sessionIDLength == psce->sessionIDLength) &&
+ !PORT_Memcmp(pcce->sessionID, psce->sessionID,
+ pcce->sessionIDLength)) {
+ cce = *pcce;
+ } else {
+ /* The cert doesen't match the SID cache entry,
+ ** so invalidate the SID cache entry.
+ */
+ psce->valid = 0;
+ psce = 0;
+ pcce = 0;
+ }
+ UnlockSidCacheLock(cache->certCacheLock);
+ } else {
+ /* what the ??. Didn't get the cert cache lock.
+ ** Don't invalidate the SID cache entry, but don't find it.
+ */
+ PORT_AssertNotReached("Didn't get cert Cache Lock!");
+ psce = 0;
+ pcce = 0;
+ }
+ }
+ if (psce && ((cndx = psce->u.ssl3.srvNameIndex) != -1)) {
+ PRUint32 gotLock = LockSidCacheLock(cache->srvNameCacheLock,
+ now);
+ if (gotLock) {
+ psnce = &cache->srvNameCacheData[cndx];
+
+ if (!PORT_Memcmp(psnce->nameHash, psce->u.ssl3.srvNameHash,
+ SHA256_LENGTH)) {
+ snce = *psnce;
+ } else {
+ /* The name doesen't match the SID cache entry,
+ ** so invalidate the SID cache entry.
+ */
+ psce->valid = 0;
+ psce = 0;
+ psnce = 0;
+ }
+ UnlockSidCacheLock(cache->srvNameCacheLock);
+ } else {
+ /* what the ??. Didn't get the cert cache lock.
+ ** Don't invalidate the SID cache entry, but don't find it.
+ */
+ PORT_AssertNotReached("Didn't get name Cache Lock!");
+ psce = 0;
+ psnce = 0;
+ }
+ }
+ if (psce) {
+ psce->lastAccessTime = sslNow;
+ sce = *psce; /* grab a copy while holding the lock */
+ }
+ }
+ UnlockSet(cache, set);
+ if (psce) {
+ /* sce conains a copy of the cache entry.
+ ** Convert shared memory format to local format
+ */
+ sid = ConvertToSID(&sce, pcce ? &cce : 0, psnce ? &snce : 0, dbHandle);
+ }
+ return sid;
+}
+
+/*
+** Place a sid into the cache, if it isn't already there.
+*/
+void
+ssl_ServerCacheSessionID(sslSessionID *sid, PRTime creationTime)
+{
+ PORT_Assert(sid);
+
+ sidCacheEntry sce;
+ PRUint32 now = 0;
+ cacheDesc *cache = &globalCache;
+
+ if (sid->u.ssl3.sessionIDLength == 0) {
+ return;
+ }
+
+ if (sid->cached == never_cached || sid->cached == invalid_cache) {
+ PRUint32 set;
+ SECItem *name;
+
+ PORT_Assert(sid->creationTime != 0);
+ if (!sid->creationTime)
+ sid->lastAccessTime = sid->creationTime = creationTime;
+ /* override caller's expiration time, which uses client timeout
+ * duration, not server timeout duration.
+ */
+ sid->expirationTime =
+ sid->creationTime + cache->ssl3Timeout * PR_USEC_PER_SEC;
+ SSL_TRC(8, ("%d: SSL: CacheMT: cached=%d addr=0x%08x%08x%08x%08x time=%x "
+ "cipherSuite=%d",
+ myPid, sid->cached,
+ sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1],
+ sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3],
+ sid->creationTime / PR_USEC_PER_SEC,
+ sid->u.ssl3.cipherSuite));
+ PRINT_BUF(8, (0, "sessionID:", sid->u.ssl3.sessionID,
+ sid->u.ssl3.sessionIDLength));
+
+ ConvertFromSID(&sce, sid);
+
+ name = &sid->u.ssl3.srvName;
+ if (name->len && name->data) {
+ now = CacheSrvName(cache, name, &sce);
+ }
+ if (sid->peerCert != NULL) {
+ now = CacheCert(cache, sid->peerCert, &sce);
+ }
+
+ set = SIDindex(cache, &sce.addr, sce.sessionID, sce.sessionIDLength);
+ now = LockSet(cache, set, now);
+ if (now) {
+ PRUint32 next = cache->sidCacheSets[set].next;
+ PRUint32 ndx = set * SID_CACHE_ENTRIES_PER_SET + next;
+
+ /* Write out new cache entry */
+ cache->sidCacheData[ndx] = sce;
+
+ cache->sidCacheSets[set].next =
+ (next + 1) % SID_CACHE_ENTRIES_PER_SET;
+
+ UnlockSet(cache, set);
+ sid->cached = in_server_cache;
+ }
+ }
+}
+
+/*
+** Although this is static, it is called from ssl via global function pointer
+** ssl_sid_uncache. This invalidates the referenced cache entry.
+*/
+void
+ssl_ServerUncacheSessionID(sslSessionID *sid)
+{
+ cacheDesc *cache = &globalCache;
+ PRUint8 *sessionID;
+ unsigned int sessionIDLength;
+ PRErrorCode err;
+ PRUint32 set;
+ PRUint32 now;
+ sidCacheEntry *psce;
+
+ if (sid == NULL)
+ return;
+
+ /* Uncaching a SID should never change the error code.
+ ** So save it here and restore it before exiting.
+ */
+ err = PR_GetError();
+
+ sessionID = sid->u.ssl3.sessionID;
+ sessionIDLength = sid->u.ssl3.sessionIDLength;
+ SSL_TRC(8, ("%d: SSL3: UncacheMT: valid=%d addr=0x%08x%08x%08x%08x time=%x "
+ "cipherSuite=%d",
+ myPid, sid->cached,
+ sid->addr.pr_s6_addr32[0], sid->addr.pr_s6_addr32[1],
+ sid->addr.pr_s6_addr32[2], sid->addr.pr_s6_addr32[3],
+ sid->creationTime / PR_USEC_PER_SEC,
+ sid->u.ssl3.cipherSuite));
+ PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength));
+ set = SIDindex(cache, &sid->addr, sessionID, sessionIDLength);
+ now = LockSet(cache, set, 0);
+ if (now) {
+ psce = FindSID(cache, set, now, &sid->addr, sessionID, sessionIDLength);
+ if (psce) {
+ psce->valid = 0;
+ }
+ UnlockSet(cache, set);
+ }
+ sid->cached = invalid_cache;
+ PORT_SetError(err);
+}
+
+#ifdef XP_OS2
+
+#define INCL_DOSPROCESS
+#include <os2.h>
+
+long
+gettid(void)
+{
+ PTIB ptib;
+ PPIB ppib;
+ DosGetInfoBlocks(&ptib, &ppib);
+ return ((long)ptib->tib_ordinal); /* thread id */
+}
+#endif
+
+static void
+CloseCache(cacheDesc *cache)
+{
+ int locks_initialized = cache->numSIDCacheLocksInitialized;
+
+ if (cache->cacheMem) {
+ if (cache->sharedCache) {
+ sidCacheLock *pLock = cache->sidCacheLocks;
+ for (; locks_initialized > 0; --locks_initialized, ++pLock) {
+ /* If everInherited is true, this shared cache was (and may
+ ** still be) in use by multiple processes. We do not wish to
+ ** destroy the mutexes while they are still in use, but we do
+ ** want to free mutex resources associated with this process.
+ */
+ sslMutex_Destroy(&pLock->mutex,
+ cache->sharedCache->everInherited);
+ }
+ }
+ if (cache->shared) {
+ PR_MemUnmap(cache->cacheMem, cache->cacheMemSize);
+ } else {
+ PORT_Free(cache->cacheMem);
+ }
+ cache->cacheMem = NULL;
+ }
+ if (cache->cacheMemMap) {
+ PR_CloseFileMap(cache->cacheMemMap);
+ cache->cacheMemMap = NULL;
+ }
+ memset(cache, 0, sizeof *cache);
+}
+
+static SECStatus
+InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries,
+ int maxSrvNameCacheEntries, PRUint32 ssl3_timeout,
+ const char *directory, PRBool shared)
+{
+ ptrdiff_t ptr;
+ sidCacheLock *pLock;
+ char *cacheMem;
+ PRFileMap *cacheMemMap;
+ char *cfn = NULL; /* cache file name */
+ int locks_initialized = 0;
+ int locks_to_initialize = 0;
+ PRUint32 init_time;
+
+ if ((!cache) || (maxCacheEntries < 0) || (!directory)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (cache->cacheMem) {
+ /* Already done */
+ return SECSuccess;
+ }
+
+ /* make sure loser can clean up properly */
+ cache->shared = shared;
+ cache->cacheMem = cacheMem = NULL;
+ cache->cacheMemMap = cacheMemMap = NULL;
+ cache->sharedCache = (cacheDesc *)0;
+
+ cache->numSIDCacheLocksInitialized = 0;
+ cache->nextCertCacheEntry = 0;
+ cache->stopPolling = PR_FALSE;
+ cache->everInherited = PR_FALSE;
+ cache->poller = NULL;
+ cache->mutexTimeout = 0;
+
+ cache->numSIDCacheEntries = maxCacheEntries ? maxCacheEntries
+ : DEF_SID_CACHE_ENTRIES;
+ cache->numSIDCacheSets =
+ SID_HOWMANY(cache->numSIDCacheEntries, SID_CACHE_ENTRIES_PER_SET);
+
+ cache->numSIDCacheEntries =
+ cache->numSIDCacheSets * SID_CACHE_ENTRIES_PER_SET;
+
+ cache->numSIDCacheLocks =
+ PR_MIN(cache->numSIDCacheSets, ssl_max_sid_cache_locks);
+
+ cache->numSIDCacheSetsPerLock =
+ SID_HOWMANY(cache->numSIDCacheSets, cache->numSIDCacheLocks);
+
+ cache->numCertCacheEntries = (maxCertCacheEntries > 0) ? maxCertCacheEntries
+ : 0;
+ cache->numSrvNameCacheEntries = (maxSrvNameCacheEntries >= 0) ? maxSrvNameCacheEntries
+ : DEF_NAME_CACHE_ENTRIES;
+
+ /* compute size of shared memory, and offsets of all pointers */
+ ptr = 0;
+ cache->cacheMem = (char *)ptr;
+ ptr += SID_ROUNDUP(sizeof(cacheDesc), SID_ALIGNMENT);
+
+ cache->sidCacheLocks = (sidCacheLock *)ptr;
+ cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks;
+ cache->certCacheLock = cache->keyCacheLock + 1;
+ cache->srvNameCacheLock = cache->certCacheLock + 1;
+ ptr = (ptrdiff_t)(cache->srvNameCacheLock + 1);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->sidCacheSets = (sidCacheSet *)ptr;
+ ptr = (ptrdiff_t)(cache->sidCacheSets + cache->numSIDCacheSets);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->sidCacheData = (sidCacheEntry *)ptr;
+ ptr = (ptrdiff_t)(cache->sidCacheData + cache->numSIDCacheEntries);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->certCacheData = (certCacheEntry *)ptr;
+ cache->sidCacheSize =
+ (char *)cache->certCacheData - (char *)cache->sidCacheData;
+
+ if (cache->numCertCacheEntries < MIN_CERT_CACHE_ENTRIES) {
+ /* This is really a poor way to computer this! */
+ cache->numCertCacheEntries = cache->sidCacheSize / sizeof(certCacheEntry);
+ if (cache->numCertCacheEntries < MIN_CERT_CACHE_ENTRIES)
+ cache->numCertCacheEntries = MIN_CERT_CACHE_ENTRIES;
+ }
+ ptr = (ptrdiff_t)(cache->certCacheData + cache->numCertCacheEntries);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->keyCacheData = (SSLWrappedSymWrappingKey *)ptr;
+ cache->certCacheSize =
+ (char *)cache->keyCacheData - (char *)cache->certCacheData;
+
+ cache->numKeyCacheEntries = SSL_NUM_WRAP_KEYS * SSL_NUM_WRAP_MECHS;
+ ptr = (ptrdiff_t)(cache->keyCacheData + cache->numKeyCacheEntries);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->keyCacheSize = (char *)ptr - (char *)cache->keyCacheData;
+
+ cache->ticketKeyNameSuffix = (PRUint8 *)ptr;
+ ptr = (ptrdiff_t)(cache->ticketKeyNameSuffix +
+ SELF_ENCRYPT_KEY_VAR_NAME_LEN);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->ticketEncKey = (encKeyCacheEntry *)ptr;
+ ptr = (ptrdiff_t)(cache->ticketEncKey + 1);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->ticketMacKey = (encKeyCacheEntry *)ptr;
+ ptr = (ptrdiff_t)(cache->ticketMacKey + 1);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->ticketKeysValid = (PRUint32 *)ptr;
+ ptr = (ptrdiff_t)(cache->ticketKeysValid + 1);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->srvNameCacheData = (srvNameCacheEntry *)ptr;
+ cache->srvNameCacheSize =
+ cache->numSrvNameCacheEntries * sizeof(srvNameCacheEntry);
+ ptr = (ptrdiff_t)(cache->srvNameCacheData + cache->numSrvNameCacheEntries);
+ ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT);
+
+ cache->cacheMemSize = ptr;
+
+ if (ssl3_timeout) {
+ if (ssl3_timeout > MAX_SSL3_TIMEOUT) {
+ ssl3_timeout = MAX_SSL3_TIMEOUT;
+ }
+ if (ssl3_timeout < MIN_SSL3_TIMEOUT) {
+ ssl3_timeout = MIN_SSL3_TIMEOUT;
+ }
+ cache->ssl3Timeout = ssl3_timeout;
+ } else {
+ cache->ssl3Timeout = DEF_SSL3_TIMEOUT;
+ }
+
+ if (shared) {
+/* Create file names */
+#if defined(XP_UNIX)
+ /* there's some confusion here about whether PR_OpenAnonFileMap wants
+ ** a directory name or a file name for its first argument.
+ cfn = PR_smprintf("%s/.sslsvrcache.%d", directory, myPid);
+ */
+ cfn = PR_smprintf("%s", directory);
+#elif defined(XP_WIN32)
+ cfn = PR_smprintf("%s/svrcache_%d_%x.ssl", directory, myPid,
+ GetCurrentThreadId());
+#elif defined(XP_OS2)
+ cfn = PR_smprintf("%s/svrcache_%d_%x.ssl", directory, myPid,
+ gettid());
+#else
+#error "Don't know how to create file name for this platform!"
+#endif
+ if (!cfn) {
+ goto loser;
+ }
+
+ /* Create cache */
+ cacheMemMap = PR_OpenAnonFileMap(cfn, cache->cacheMemSize,
+ PR_PROT_READWRITE);
+
+ PR_smprintf_free(cfn);
+ if (!cacheMemMap) {
+ goto loser;
+ }
+
+ cacheMem = PR_MemMap(cacheMemMap, 0, cache->cacheMemSize);
+ } else {
+ cacheMem = PORT_Alloc(cache->cacheMemSize);
+ }
+
+ if (!cacheMem) {
+ goto loser;
+ }
+
+ /* Initialize shared memory. This may not be necessary on all platforms */
+ memset(cacheMem, 0, cache->cacheMemSize);
+
+ /* Copy cache descriptor header into shared memory */
+ memcpy(cacheMem, cache, sizeof *cache);
+
+ /* save private copies of these values */
+ cache->cacheMemMap = cacheMemMap;
+ cache->cacheMem = cacheMem;
+ cache->sharedCache = (cacheDesc *)cacheMem;
+
+ /* Fix pointers in our private copy of cache descriptor to point to
+ ** spaces in shared memory
+ */
+ cache->sidCacheLocks = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->sidCacheLocks);
+ cache->keyCacheLock = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->keyCacheLock);
+ cache->certCacheLock = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->certCacheLock);
+ cache->srvNameCacheLock = (sidCacheLock *)(cache->cacheMem + (ptrdiff_t)cache->srvNameCacheLock);
+ cache->sidCacheSets = (sidCacheSet *)(cache->cacheMem + (ptrdiff_t)cache->sidCacheSets);
+ cache->sidCacheData = (sidCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->sidCacheData);
+ cache->certCacheData = (certCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->certCacheData);
+ cache->keyCacheData = (SSLWrappedSymWrappingKey *)(cache->cacheMem + (ptrdiff_t)cache->keyCacheData);
+ cache->ticketKeyNameSuffix = (PRUint8 *)(cache->cacheMem + (ptrdiff_t)cache->ticketKeyNameSuffix);
+ cache->ticketEncKey = (encKeyCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->ticketEncKey);
+ cache->ticketMacKey = (encKeyCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->ticketMacKey);
+ cache->ticketKeysValid = (PRUint32 *)(cache->cacheMem + (ptrdiff_t)cache->ticketKeysValid);
+ cache->srvNameCacheData = (srvNameCacheEntry *)(cache->cacheMem + (ptrdiff_t)cache->srvNameCacheData);
+
+ /* initialize the locks */
+ init_time = ssl_CacheNow();
+ pLock = cache->sidCacheLocks;
+ for (locks_to_initialize = cache->numSIDCacheLocks + 3;
+ locks_initialized < locks_to_initialize;
+ ++locks_initialized, ++pLock) {
+
+ SECStatus err = sslMutex_Init(&pLock->mutex, shared);
+ if (err) {
+ cache->numSIDCacheLocksInitialized = locks_initialized;
+ goto loser;
+ }
+ pLock->timeStamp = init_time;
+ pLock->pid = 0;
+ }
+ cache->numSIDCacheLocksInitialized = locks_initialized;
+
+ return SECSuccess;
+
+loser:
+ CloseCache(cache);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+}
+
+PRUint32
+SSL_GetMaxServerCacheLocks(void)
+{
+ return ssl_max_sid_cache_locks + 2;
+ /* The extra two are the cert cache lock and the key cache lock. */
+}
+
+SECStatus
+SSL_SetMaxServerCacheLocks(PRUint32 maxLocks)
+{
+ /* Minimum is 1 sid cache lock, 1 cert cache lock and 1 key cache lock.
+ ** We'd like to test for a maximum value, but not all platforms' header
+ ** files provide a symbol or function or other means of determining
+ ** the maximum, other than trial and error.
+ */
+ if (maxLocks < 3) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ssl_max_sid_cache_locks = maxLocks - 2;
+ /* The extra two are the cert cache lock and the key cache lock. */
+ return SECSuccess;
+}
+
+PR_STATIC_ASSERT(sizeof(sidCacheEntry) % 16 == 0);
+PR_STATIC_ASSERT(sizeof(certCacheEntry) == 4096);
+PR_STATIC_ASSERT(sizeof(srvNameCacheEntry) == 1072);
+
+static SECStatus
+ssl_ConfigServerSessionIDCacheInstanceWithOpt(cacheDesc *cache,
+ PRUint32 ssl3_timeout,
+ const char *directory,
+ PRBool shared,
+ int maxCacheEntries,
+ int maxCertCacheEntries,
+ int maxSrvNameCacheEntries)
+{
+ SECStatus rv;
+
+ rv = ssl_InitSessionCache();
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ myPid = SSL_GETPID();
+ if (!directory) {
+ directory = DEFAULT_CACHE_DIRECTORY;
+ }
+ rv = InitCache(cache, maxCacheEntries, maxCertCacheEntries,
+ maxSrvNameCacheEntries, ssl3_timeout, directory, shared);
+ if (rv) {
+ return SECFailure;
+ }
+
+ ssl_sid_lookup = ServerSessionIDLookup;
+ return SECSuccess;
+}
+
+SECStatus
+SSL_ConfigServerSessionIDCacheInstance(cacheDesc *cache,
+ int maxCacheEntries,
+ PRUint32 ssl2_timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory, PRBool shared)
+{
+ return ssl_ConfigServerSessionIDCacheInstanceWithOpt(cache,
+ ssl3_timeout,
+ directory,
+ shared,
+ maxCacheEntries,
+ -1, -1);
+}
+
+SECStatus
+SSL_ConfigServerSessionIDCache(int maxCacheEntries,
+ PRUint32 ssl2_timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory)
+{
+ ssl_InitSessionCacheLocks(PR_FALSE);
+ return SSL_ConfigServerSessionIDCacheInstance(&globalCache,
+ maxCacheEntries, ssl2_timeout, ssl3_timeout, directory, PR_FALSE);
+}
+
+SECStatus
+SSL_ShutdownServerSessionIDCacheInstance(cacheDesc *cache)
+{
+ CloseCache(cache);
+ return SECSuccess;
+}
+
+SECStatus
+SSL_ShutdownServerSessionIDCache(void)
+{
+#if defined(XP_UNIX)
+ /* Stop the thread that polls cache for expired locks on Unix */
+ StopLockPoller(&globalCache);
+#endif
+ SSL3_ShutdownServerCache();
+ return SSL_ShutdownServerSessionIDCacheInstance(&globalCache);
+}
+
+/* Use this function, instead of SSL_ConfigServerSessionIDCache,
+ * if the cache will be shared by multiple processes.
+ */
+static SECStatus
+ssl_ConfigMPServerSIDCacheWithOpt(PRUint32 ssl3_timeout,
+ const char *directory,
+ int maxCacheEntries,
+ int maxCertCacheEntries,
+ int maxSrvNameCacheEntries)
+{
+ char *envValue;
+ char *inhValue;
+ cacheDesc *cache = &globalCache;
+ PRUint32 fmStrLen;
+ SECStatus result;
+ PRStatus prStatus;
+ SECStatus putEnvFailed;
+ inheritance inherit;
+ char fmString[PR_FILEMAP_STRING_BUFSIZE];
+
+ isMultiProcess = PR_TRUE;
+ result = ssl_ConfigServerSessionIDCacheInstanceWithOpt(cache,
+ ssl3_timeout, directory, PR_TRUE,
+ maxCacheEntries, maxCacheEntries, maxSrvNameCacheEntries);
+ if (result != SECSuccess)
+ return result;
+
+ prStatus = PR_ExportFileMapAsString(cache->cacheMemMap,
+ sizeof fmString, fmString);
+ if ((prStatus != PR_SUCCESS) || !(fmStrLen = strlen(fmString))) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ inherit.cacheMemSize = cache->cacheMemSize;
+ inherit.fmStrLen = fmStrLen;
+
+ inhValue = BTOA_DataToAscii((unsigned char *)&inherit, sizeof inherit);
+ if (!inhValue || !strlen(inhValue)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ envValue = PR_smprintf("%s,%s", inhValue, fmString);
+ if (!envValue || !strlen(envValue)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ PORT_Free(inhValue);
+
+ putEnvFailed = (SECStatus)NSS_PutEnv(envVarName, envValue);
+ PR_smprintf_free(envValue);
+ if (putEnvFailed) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ result = SECFailure;
+ }
+
+#if defined(XP_UNIX)
+ /* Launch thread to poll cache for expired locks on Unix */
+ LaunchLockPoller(cache);
+#endif
+ return result;
+}
+
+/* Use this function, instead of SSL_ConfigServerSessionIDCache,
+ * if the cache will be shared by multiple processes.
+ */
+SECStatus
+SSL_ConfigMPServerSIDCache(int maxCacheEntries,
+ PRUint32 ssl2_timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory)
+{
+ return ssl_ConfigMPServerSIDCacheWithOpt(ssl3_timeout,
+ directory,
+ maxCacheEntries,
+ -1, -1);
+}
+
+SECStatus
+SSL_ConfigServerSessionIDCacheWithOpt(
+ PRUint32 ssl2_timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory,
+ int maxCacheEntries,
+ int maxCertCacheEntries,
+ int maxSrvNameCacheEntries,
+ PRBool enableMPCache)
+{
+ if (!enableMPCache) {
+ ssl_InitSessionCacheLocks(PR_FALSE);
+ return ssl_ConfigServerSessionIDCacheInstanceWithOpt(&globalCache,
+ ssl3_timeout, directory, PR_FALSE,
+ maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries);
+ } else {
+ return ssl_ConfigMPServerSIDCacheWithOpt(ssl3_timeout, directory,
+ maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries);
+ }
+}
+
+SECStatus
+SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char *envString)
+{
+ unsigned char *decoString = NULL;
+ char *fmString = NULL;
+ char *myEnvString = NULL;
+ unsigned int decoLen;
+ inheritance inherit;
+ cacheDesc my;
+#ifdef WINNT
+ sidCacheLock *newLocks;
+ int locks_initialized = 0;
+ int locks_to_initialize = 0;
+#endif
+ SECStatus status = ssl_InitSessionCache();
+
+ if (status != SECSuccess) {
+ return status;
+ }
+
+ myPid = SSL_GETPID();
+
+ /* If this child was created by fork(), and not by exec() on unix,
+ ** then isMultiProcess will already be set.
+ ** If not, we'll set it below.
+ */
+ if (isMultiProcess) {
+ if (cache && cache->sharedCache) {
+ cache->sharedCache->everInherited = PR_TRUE;
+ }
+ return SECSuccess; /* already done. */
+ }
+
+ ssl_InitSessionCacheLocks(PR_FALSE);
+
+ ssl_sid_lookup = ServerSessionIDLookup;
+
+ if (!envString) {
+ envString = PR_GetEnvSecure(envVarName);
+ if (!envString) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ }
+ myEnvString = PORT_Strdup(envString);
+ if (!myEnvString)
+ return SECFailure;
+ fmString = strchr(myEnvString, ',');
+ if (!fmString)
+ goto loser;
+ *fmString++ = 0;
+
+ decoString = ATOB_AsciiToData(myEnvString, &decoLen);
+ if (!decoString) {
+ goto loser;
+ }
+ if (decoLen != sizeof inherit) {
+ goto loser;
+ }
+
+ PORT_Memcpy(&inherit, decoString, sizeof inherit);
+
+ if (strlen(fmString) != inherit.fmStrLen) {
+ goto loser;
+ }
+
+ memset(cache, 0, sizeof *cache);
+ cache->cacheMemSize = inherit.cacheMemSize;
+
+ /* Create cache */
+ cache->cacheMemMap = PR_ImportFileMapFromString(fmString);
+ if (!cache->cacheMemMap) {
+ goto loser;
+ }
+ cache->cacheMem = PR_MemMap(cache->cacheMemMap, 0, cache->cacheMemSize);
+ if (!cache->cacheMem) {
+ goto loser;
+ }
+ cache->sharedCache = (cacheDesc *)cache->cacheMem;
+
+ if (cache->sharedCache->cacheMemSize != cache->cacheMemSize) {
+ goto loser;
+ }
+
+ /* We're now going to overwrite the local cache instance with the
+ ** shared copy of the cache struct, then update several values in
+ ** the local cache using the values for cache->cacheMemMap and
+ ** cache->cacheMem computed just above. So, we copy cache into
+ ** the automatic variable "my", to preserve the variables while
+ ** cache is overwritten.
+ */
+ my = *cache; /* save values computed above. */
+ memcpy(cache, cache->sharedCache, sizeof *cache); /* overwrite */
+
+ /* Fix pointers in our private copy of cache descriptor to point to
+ ** spaces in shared memory, whose address is now in "my".
+ */
+ cache->sidCacheLocks = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->sidCacheLocks);
+ cache->keyCacheLock = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->keyCacheLock);
+ cache->certCacheLock = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->certCacheLock);
+ cache->srvNameCacheLock = (sidCacheLock *)(my.cacheMem + (ptrdiff_t)cache->srvNameCacheLock);
+ cache->sidCacheSets = (sidCacheSet *)(my.cacheMem + (ptrdiff_t)cache->sidCacheSets);
+ cache->sidCacheData = (sidCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->sidCacheData);
+ cache->certCacheData = (certCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->certCacheData);
+ cache->keyCacheData = (SSLWrappedSymWrappingKey *)(my.cacheMem + (ptrdiff_t)cache->keyCacheData);
+ cache->ticketKeyNameSuffix = (PRUint8 *)(my.cacheMem + (ptrdiff_t)cache->ticketKeyNameSuffix);
+ cache->ticketEncKey = (encKeyCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->ticketEncKey);
+ cache->ticketMacKey = (encKeyCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->ticketMacKey);
+ cache->ticketKeysValid = (PRUint32 *)(my.cacheMem + (ptrdiff_t)cache->ticketKeysValid);
+ cache->srvNameCacheData = (srvNameCacheEntry *)(my.cacheMem + (ptrdiff_t)cache->srvNameCacheData);
+
+ cache->cacheMemMap = my.cacheMemMap;
+ cache->cacheMem = my.cacheMem;
+ cache->sharedCache = (cacheDesc *)cache->cacheMem;
+
+#ifdef WINNT
+ /* On Windows NT we need to "fix" the sidCacheLocks here to support fibers
+ ** When NT fibers are used in a multi-process server, a second level of
+ ** locking is needed to prevent a deadlock, in case a fiber acquires the
+ ** cross-process mutex, yields, and another fiber is later scheduled on
+ ** the same native thread and tries to acquire the cross-process mutex.
+ ** We do this by using a PRLock in the sslMutex. However, it is stored in
+ ** shared memory as part of sidCacheLocks, and we don't want to overwrite
+ ** the PRLock of the parent process. So we need to make new, private
+ ** copies of sidCacheLocks before modifying the sslMutex with our own
+ ** PRLock
+ */
+
+ /* note from jpierre : this should be free'd in child processes when
+ ** a function is added to delete the SSL session cache in the future.
+ */
+ locks_to_initialize = cache->numSIDCacheLocks + 3;
+ newLocks = PORT_NewArray(sidCacheLock, locks_to_initialize);
+ if (!newLocks)
+ goto loser;
+ /* copy the old locks */
+ memcpy(newLocks, cache->sidCacheLocks,
+ locks_to_initialize * sizeof(sidCacheLock));
+ cache->sidCacheLocks = newLocks;
+ /* fix the locks */
+ for (; locks_initialized < locks_to_initialize; ++locks_initialized) {
+ /* now, make a local PRLock in this sslMutex for this child process */
+ SECStatus err;
+ err = sslMutex_2LevelInit(&newLocks[locks_initialized].mutex);
+ if (err != SECSuccess) {
+ cache->numSIDCacheLocksInitialized = locks_initialized;
+ goto loser;
+ }
+ }
+ cache->numSIDCacheLocksInitialized = locks_initialized;
+
+ /* also fix the key and cert cache which use the last 2 lock entries */
+ cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks;
+ cache->certCacheLock = cache->keyCacheLock + 1;
+ cache->srvNameCacheLock = cache->certCacheLock + 1;
+#endif
+
+ PORT_Free(myEnvString);
+ PORT_Free(decoString);
+
+ /* mark that we have inherited this. */
+ cache->sharedCache->everInherited = PR_TRUE;
+ isMultiProcess = PR_TRUE;
+
+ return SECSuccess;
+
+loser:
+ PORT_Free(myEnvString);
+ if (decoString)
+ PORT_Free(decoString);
+ CloseCache(cache);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+}
+
+SECStatus
+SSL_InheritMPServerSIDCache(const char *envString)
+{
+ return SSL_InheritMPServerSIDCacheInstance(&globalCache, envString);
+}
+
+#if defined(XP_UNIX)
+
+#define SID_LOCK_EXPIRATION_TIMEOUT 30 /* seconds */
+
+static void
+LockPoller(void *arg)
+{
+ cacheDesc *cache = (cacheDesc *)arg;
+ cacheDesc *sharedCache = cache->sharedCache;
+ sidCacheLock *pLock;
+ PRIntervalTime timeout;
+ PRUint32 now;
+ PRUint32 then;
+ int locks_polled = 0;
+ int locks_to_poll = cache->numSIDCacheLocks + 2;
+ PRUint32 expiration = cache->mutexTimeout;
+
+ timeout = PR_SecondsToInterval(expiration);
+ while (!sharedCache->stopPolling) {
+ PR_Sleep(timeout);
+ if (sharedCache->stopPolling)
+ break;
+
+ now = ssl_CacheNow();
+ then = now - expiration;
+ for (pLock = cache->sidCacheLocks, locks_polled = 0;
+ locks_to_poll > locks_polled && !sharedCache->stopPolling;
+ ++locks_polled, ++pLock) {
+ pid_t pid;
+
+ if (pLock->timeStamp < then &&
+ pLock->timeStamp != 0 &&
+ (pid = pLock->pid) != 0) {
+
+ /* maybe we should try the lock? */
+ int result = kill(pid, 0);
+ if (result < 0 && errno == ESRCH) {
+ SECStatus rv;
+ /* No process exists by that pid any more.
+ ** Treat this mutex as abandoned.
+ */
+ pLock->timeStamp = now;
+ pLock->pid = 0;
+ rv = sslMutex_Unlock(&pLock->mutex);
+ if (rv != SECSuccess) {
+ /* Now what? */
+ }
+ }
+ }
+ } /* end of loop over locks */
+ } /* end of entire polling loop */
+}
+
+/* Launch thread to poll cache for expired locks */
+static SECStatus
+LaunchLockPoller(cacheDesc *cache)
+{
+ const char *timeoutString;
+ PRThread *pollerThread;
+
+ cache->mutexTimeout = SID_LOCK_EXPIRATION_TIMEOUT;
+ timeoutString = PR_GetEnvSecure("NSS_SSL_SERVER_CACHE_MUTEX_TIMEOUT");
+ if (timeoutString) {
+ long newTime = strtol(timeoutString, 0, 0);
+ if (newTime == 0)
+ return SECSuccess; /* application doesn't want poller thread */
+ if (newTime > 0)
+ cache->mutexTimeout = (PRUint32)newTime;
+ /* if error (newTime < 0) ignore it and use default */
+ }
+
+ pollerThread =
+ PR_CreateThread(PR_USER_THREAD, LockPoller, cache, PR_PRIORITY_NORMAL,
+ PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0);
+ if (!pollerThread) {
+ return SECFailure;
+ }
+ cache->poller = pollerThread;
+ return SECSuccess;
+}
+
+/* Stop the thread that polls cache for expired locks */
+static SECStatus
+StopLockPoller(cacheDesc *cache)
+{
+ if (!cache->poller) {
+ return SECSuccess;
+ }
+ cache->sharedCache->stopPolling = PR_TRUE;
+ if (PR_Interrupt(cache->poller) != PR_SUCCESS) {
+ return SECFailure;
+ }
+ if (PR_JoinThread(cache->poller) != PR_SUCCESS) {
+ return SECFailure;
+ }
+ cache->poller = NULL;
+ return SECSuccess;
+}
+#endif
+
+/************************************************************************
+ * Code dealing with shared wrapped symmetric wrapping keys below *
+ ************************************************************************/
+
+/* The asymmetric key we use for wrapping the self-encryption keys. This is a
+ * global structure that can be initialized without a socket. Access is
+ * synchronized on the reader-writer lock. This is setup either by calling
+ * SSL_SetSessionTicketKeyPair() or by configuring a certificate of the
+ * ssl_auth_rsa_decrypt type. */
+static struct {
+ PRCallOnceType setup;
+ PRRWLock *lock;
+ SECKEYPublicKey *pubKey;
+ SECKEYPrivateKey *privKey;
+ PRBool configured;
+} ssl_self_encrypt_key_pair;
+
+/* The symmetric self-encryption keys. This requires a socket to construct
+ * and requires that the global structure be initialized before use.
+ */
+static sslSelfEncryptKeys ssl_self_encrypt_keys;
+
+/* Externalize the self encrypt keys. Purely used for testing. */
+sslSelfEncryptKeys *
+ssl_GetSelfEncryptKeysInt()
+{
+ return &ssl_self_encrypt_keys;
+}
+
+static void
+ssl_CleanupSelfEncryptKeyPair()
+{
+ if (ssl_self_encrypt_key_pair.pubKey) {
+ PORT_Assert(ssl_self_encrypt_key_pair.privKey);
+ SECKEY_DestroyPublicKey(ssl_self_encrypt_key_pair.pubKey);
+ SECKEY_DestroyPrivateKey(ssl_self_encrypt_key_pair.privKey);
+ }
+}
+
+void
+ssl_ResetSelfEncryptKeys()
+{
+ if (ssl_self_encrypt_keys.encKey) {
+ PORT_Assert(ssl_self_encrypt_keys.macKey);
+ PK11_FreeSymKey(ssl_self_encrypt_keys.encKey);
+ PK11_FreeSymKey(ssl_self_encrypt_keys.macKey);
+ }
+ PORT_Memset(&ssl_self_encrypt_keys, 0,
+ sizeof(ssl_self_encrypt_keys));
+}
+
+static SECStatus
+ssl_SelfEncryptShutdown(void *appData, void *nssData)
+{
+ ssl_CleanupSelfEncryptKeyPair();
+ PR_DestroyRWLock(ssl_self_encrypt_key_pair.lock);
+ PORT_Memset(&ssl_self_encrypt_key_pair, 0,
+ sizeof(ssl_self_encrypt_key_pair));
+
+ ssl_ResetSelfEncryptKeys();
+ return SECSuccess;
+}
+
+static PRStatus
+ssl_SelfEncryptSetup(void)
+{
+ SECStatus rv = NSS_RegisterShutdown(ssl_SelfEncryptShutdown, NULL);
+ if (rv != SECSuccess) {
+ return PR_FAILURE;
+ }
+ ssl_self_encrypt_key_pair.lock = PR_NewRWLock(PR_RWLOCK_RANK_NONE, NULL);
+ if (!ssl_self_encrypt_key_pair.lock) {
+ return PR_FAILURE;
+ }
+ return PR_SUCCESS;
+}
+
+/* Configure a self encryption key pair. |explicitConfig| is set to true for
+ * calls to SSL_SetSessionTicketKeyPair(), false for implicit configuration.
+ * This assumes that the setup has been run. */
+static SECStatus
+ssl_SetSelfEncryptKeyPair(SECKEYPublicKey *pubKey,
+ SECKEYPrivateKey *privKey,
+ PRBool explicitConfig)
+{
+ SECKEYPublicKey *pubKeyCopy, *oldPubKey;
+ SECKEYPrivateKey *privKeyCopy, *oldPrivKey;
+
+ PORT_Assert(ssl_self_encrypt_key_pair.lock);
+ pubKeyCopy = SECKEY_CopyPublicKey(pubKey);
+ privKeyCopy = SECKEY_CopyPrivateKey(privKey);
+
+ if (!pubKeyCopy || !privKeyCopy) {
+ SECKEY_DestroyPublicKey(pubKeyCopy);
+ SECKEY_DestroyPrivateKey(privKeyCopy);
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
+ }
+
+ PR_RWLock_Wlock(ssl_self_encrypt_key_pair.lock);
+ oldPubKey = ssl_self_encrypt_key_pair.pubKey;
+ oldPrivKey = ssl_self_encrypt_key_pair.privKey;
+ ssl_self_encrypt_key_pair.pubKey = pubKeyCopy;
+ ssl_self_encrypt_key_pair.privKey = privKeyCopy;
+ ssl_self_encrypt_key_pair.configured = explicitConfig;
+ PR_RWLock_Unlock(ssl_self_encrypt_key_pair.lock);
+
+ if (oldPubKey) {
+ PORT_Assert(oldPrivKey);
+ SECKEY_DestroyPublicKey(oldPubKey);
+ SECKEY_DestroyPrivateKey(oldPrivKey);
+ }
+
+ return SECSuccess;
+}
+
+/* This is really the self-encryption keys but it has the
+ * wrong name for historical API stability reasons. */
+SECStatus
+SSL_SetSessionTicketKeyPair(SECKEYPublicKey *pubKey,
+ SECKEYPrivateKey *privKey)
+{
+ if (SECKEY_GetPublicKeyType(pubKey) != rsaKey ||
+ SECKEY_GetPrivateKeyType(privKey) != rsaKey) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (PR_SUCCESS != PR_CallOnce(&ssl_self_encrypt_key_pair.setup,
+ &ssl_SelfEncryptSetup)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ return ssl_SetSelfEncryptKeyPair(pubKey, privKey, PR_TRUE);
+}
+
+/* When configuring a server cert, we should save the RSA key in case it is
+ * needed for self-encryption. This saves the latest copy, unless there has
+ * been an explicit call to SSL_SetSessionTicketKeyPair(). */
+SECStatus
+ssl_MaybeSetSelfEncryptKeyPair(const sslKeyPair *keyPair)
+{
+ PRBool configured;
+
+ if (PR_SUCCESS != PR_CallOnce(&ssl_self_encrypt_key_pair.setup,
+ &ssl_SelfEncryptSetup)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ PR_RWLock_Rlock(ssl_self_encrypt_key_pair.lock);
+ configured = ssl_self_encrypt_key_pair.configured;
+ PR_RWLock_Unlock(ssl_self_encrypt_key_pair.lock);
+ if (configured) {
+ return SECSuccess;
+ }
+ return ssl_SetSelfEncryptKeyPair(keyPair->pubKey,
+ keyPair->privKey, PR_FALSE);
+}
+
+static SECStatus
+ssl_GetSelfEncryptKeyPair(SECKEYPublicKey **pubKey,
+ SECKEYPrivateKey **privKey)
+{
+ if (PR_SUCCESS != PR_CallOnce(&ssl_self_encrypt_key_pair.setup,
+ &ssl_SelfEncryptSetup)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ SECKEYPublicKey *pubKeyCopy = NULL;
+ SECKEYPrivateKey *privKeyCopy = NULL;
+ PRBool noKey = PR_FALSE;
+
+ PR_RWLock_Rlock(ssl_self_encrypt_key_pair.lock);
+ if (ssl_self_encrypt_key_pair.pubKey && ssl_self_encrypt_key_pair.privKey) {
+ pubKeyCopy = SECKEY_CopyPublicKey(ssl_self_encrypt_key_pair.pubKey);
+ privKeyCopy = SECKEY_CopyPrivateKey(ssl_self_encrypt_key_pair.privKey);
+ } else {
+ noKey = PR_TRUE;
+ }
+ PR_RWLock_Unlock(ssl_self_encrypt_key_pair.lock);
+
+ if (noKey) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (!pubKeyCopy || !privKeyCopy) {
+ SECKEY_DestroyPublicKey(pubKeyCopy);
+ SECKEY_DestroyPrivateKey(privKeyCopy);
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
+ }
+
+ *pubKey = pubKeyCopy;
+ *privKey = privKeyCopy;
+ return SECSuccess;
+}
+
+static SECStatus
+ssl_GenerateSelfEncryptKeys(void *pwArg, PRUint8 *keyName,
+ PK11SymKey **aesKey, PK11SymKey **macKey);
+
+static PRStatus
+ssl_GenerateSelfEncryptKeysOnce(void *arg)
+{
+ SECStatus rv;
+
+ /* Get a copy of the session keys from shared memory. */
+ PORT_Memcpy(ssl_self_encrypt_keys.keyName,
+ SELF_ENCRYPT_KEY_NAME_PREFIX,
+ sizeof(SELF_ENCRYPT_KEY_NAME_PREFIX));
+ /* This function calls ssl_GetSelfEncryptKeyPair(), which initializes the
+ * key pair stuff. That allows this to use the same shutdown function. */
+ rv = ssl_GenerateSelfEncryptKeys(arg, ssl_self_encrypt_keys.keyName,
+ &ssl_self_encrypt_keys.encKey,
+ &ssl_self_encrypt_keys.macKey);
+ if (rv != SECSuccess) {
+ return PR_FAILURE;
+ }
+
+ return PR_SUCCESS;
+}
+
+SECStatus
+ssl_GetSelfEncryptKeys(sslSocket *ss, PRUint8 *keyName,
+ PK11SymKey **encKey, PK11SymKey **macKey)
+{
+ if (PR_SUCCESS != PR_CallOnceWithArg(&ssl_self_encrypt_keys.setup,
+ &ssl_GenerateSelfEncryptKeysOnce,
+ ss->pkcs11PinArg)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (!ssl_self_encrypt_keys.encKey || !ssl_self_encrypt_keys.macKey) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ PORT_Memcpy(keyName, ssl_self_encrypt_keys.keyName,
+ sizeof(ssl_self_encrypt_keys.keyName));
+ *encKey = ssl_self_encrypt_keys.encKey;
+ *macKey = ssl_self_encrypt_keys.macKey;
+ return SECSuccess;
+}
+
+/* If lockTime is zero, it implies that the lock is not held, and must be
+ * aquired here.
+ */
+static SECStatus
+getSvrWrappingKey(unsigned int symWrapMechIndex,
+ unsigned int wrapKeyIndex,
+ SSLWrappedSymWrappingKey *wswk,
+ cacheDesc *cache,
+ PRUint32 lockTime)
+{
+ PRUint32 ndx = (wrapKeyIndex * SSL_NUM_WRAP_MECHS) + symWrapMechIndex;
+ SSLWrappedSymWrappingKey *pwswk = cache->keyCacheData + ndx;
+ PRUint32 now = 0;
+ PRBool rv = SECFailure;
+
+ if (!cache->cacheMem) { /* cache is uninitialized */
+ PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED);
+ return SECFailure;
+ }
+ if (!lockTime) {
+ now = LockSidCacheLock(cache->keyCacheLock, 0);
+ if (!now) {
+ return SECFailure;
+ }
+ }
+ if (pwswk->wrapKeyIndex == wrapKeyIndex &&
+ pwswk->wrapMechIndex == symWrapMechIndex &&
+ pwswk->wrappedSymKeyLen != 0) {
+ *wswk = *pwswk;
+ rv = SECSuccess;
+ }
+ if (now) {
+ UnlockSidCacheLock(cache->keyCacheLock);
+ }
+ return rv;
+}
+
+SECStatus
+ssl_GetWrappingKey(unsigned int wrapMechIndex,
+ unsigned int wrapKeyIndex,
+ SSLWrappedSymWrappingKey *wswk)
+{
+ PORT_Assert(wrapMechIndex < SSL_NUM_WRAP_MECHS);
+ PORT_Assert(wrapKeyIndex < SSL_NUM_WRAP_KEYS);
+ if (wrapMechIndex >= SSL_NUM_WRAP_MECHS ||
+ wrapKeyIndex >= SSL_NUM_WRAP_KEYS) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ return getSvrWrappingKey(wrapMechIndex, wrapKeyIndex, wswk,
+ &globalCache, 0);
+}
+
+/* Wrap and cache a session ticket key. */
+static SECStatus
+WrapSelfEncryptKey(SECKEYPublicKey *svrPubKey, PK11SymKey *symKey,
+ const char *keyName, encKeyCacheEntry *cacheEntry)
+{
+ SECItem wrappedKey = { siBuffer, NULL, 0 };
+
+ wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey);
+ PORT_Assert(wrappedKey.len <= sizeof(cacheEntry->bytes));
+ if (wrappedKey.len > sizeof(cacheEntry->bytes))
+ return PR_FALSE;
+ wrappedKey.data = cacheEntry->bytes;
+
+ if (PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, symKey, &wrappedKey) !=
+ SECSuccess) {
+ SSL_DBG(("%d: SSL[%s]: Unable to wrap self encrypt key %s.",
+ SSL_GETPID(), "unknown", keyName));
+ return SECFailure;
+ }
+ cacheEntry->length = wrappedKey.len;
+ return SECSuccess;
+}
+
+static SECStatus
+GenerateSelfEncryptKeys(void *pwArg, PRUint8 *keyName, PK11SymKey **aesKey,
+ PK11SymKey **macKey)
+{
+ PK11SlotInfo *slot;
+ CK_MECHANISM_TYPE mechanismArray[2];
+ PK11SymKey *aesKeyTmp = NULL;
+ PK11SymKey *macKeyTmp = NULL;
+ cacheDesc *cache = &globalCache;
+ PRUint8 ticketKeyNameSuffixLocal[SELF_ENCRYPT_KEY_VAR_NAME_LEN];
+ PRUint8 *ticketKeyNameSuffix;
+
+ if (!cache->cacheMem) {
+ /* cache is not initalized. Use stack buffer */
+ ticketKeyNameSuffix = ticketKeyNameSuffixLocal;
+ } else {
+ ticketKeyNameSuffix = cache->ticketKeyNameSuffix;
+ }
+
+ if (PK11_GenerateRandom(ticketKeyNameSuffix,
+ SELF_ENCRYPT_KEY_VAR_NAME_LEN) !=
+ SECSuccess) {
+ SSL_DBG(("%d: SSL[%s]: Unable to generate random key name bytes.",
+ SSL_GETPID(), "unknown"));
+ return SECFailure;
+ }
+
+ mechanismArray[0] = CKM_AES_CBC;
+ mechanismArray[1] = CKM_SHA256_HMAC;
+
+ slot = PK11_GetBestSlotMultiple(mechanismArray, 2, pwArg);
+ if (slot) {
+ aesKeyTmp = PK11_KeyGen(slot, mechanismArray[0], NULL,
+ AES_256_KEY_LENGTH, pwArg);
+ macKeyTmp = PK11_KeyGen(slot, mechanismArray[1], NULL,
+ SHA256_LENGTH, pwArg);
+ PK11_FreeSlot(slot);
+ }
+
+ if (aesKeyTmp == NULL || macKeyTmp == NULL) {
+ SSL_DBG(("%d: SSL[%s]: Unable to generate session ticket keys.",
+ SSL_GETPID(), "unknown"));
+ goto loser;
+ }
+ PORT_Memcpy(keyName, ticketKeyNameSuffix, SELF_ENCRYPT_KEY_VAR_NAME_LEN);
+ *aesKey = aesKeyTmp;
+ *macKey = macKeyTmp;
+ return SECSuccess;
+
+loser:
+ if (aesKeyTmp)
+ PK11_FreeSymKey(aesKeyTmp);
+ if (macKeyTmp)
+ PK11_FreeSymKey(macKeyTmp);
+ return SECFailure;
+}
+
+static SECStatus
+GenerateAndWrapSelfEncryptKeys(SECKEYPublicKey *svrPubKey, void *pwArg,
+ PRUint8 *keyName, PK11SymKey **aesKey,
+ PK11SymKey **macKey)
+{
+ PK11SymKey *aesKeyTmp = NULL;
+ PK11SymKey *macKeyTmp = NULL;
+ cacheDesc *cache = &globalCache;
+ SECStatus rv;
+
+ rv = GenerateSelfEncryptKeys(pwArg, keyName, &aesKeyTmp, &macKeyTmp);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (cache->cacheMem) {
+ /* Export the keys to the shared cache in wrapped form. */
+ rv = WrapSelfEncryptKey(svrPubKey, aesKeyTmp, "enc key", cache->ticketEncKey);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = WrapSelfEncryptKey(svrPubKey, macKeyTmp, "mac key", cache->ticketMacKey);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ *aesKey = aesKeyTmp;
+ *macKey = macKeyTmp;
+ return SECSuccess;
+
+loser:
+ PK11_FreeSymKey(aesKeyTmp);
+ PK11_FreeSymKey(macKeyTmp);
+ return SECFailure;
+}
+
+static SECStatus
+UnwrapCachedSelfEncryptKeys(SECKEYPrivateKey *svrPrivKey, PRUint8 *keyName,
+ PK11SymKey **aesKey, PK11SymKey **macKey)
+{
+ SECItem wrappedKey = { siBuffer, NULL, 0 };
+ PK11SymKey *aesKeyTmp = NULL;
+ PK11SymKey *macKeyTmp = NULL;
+ cacheDesc *cache = &globalCache;
+
+ wrappedKey.data = cache->ticketEncKey->bytes;
+ wrappedKey.len = cache->ticketEncKey->length;
+ PORT_Assert(wrappedKey.len <= sizeof(cache->ticketEncKey->bytes));
+ aesKeyTmp = PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
+ CKM_AES_CBC, CKA_DECRYPT, 0);
+
+ wrappedKey.data = cache->ticketMacKey->bytes;
+ wrappedKey.len = cache->ticketMacKey->length;
+ PORT_Assert(wrappedKey.len <= sizeof(cache->ticketMacKey->bytes));
+ macKeyTmp = PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
+ CKM_SHA256_HMAC, CKA_SIGN, 0);
+
+ if (aesKeyTmp == NULL || macKeyTmp == NULL) {
+ SSL_DBG(("%d: SSL[%s]: Unable to unwrap session ticket keys.",
+ SSL_GETPID(), "unknown"));
+ goto loser;
+ }
+ SSL_DBG(("%d: SSL[%s]: Successfully unwrapped session ticket keys.",
+ SSL_GETPID(), "unknown"));
+
+ PORT_Memcpy(keyName, cache->ticketKeyNameSuffix,
+ SELF_ENCRYPT_KEY_VAR_NAME_LEN);
+ *aesKey = aesKeyTmp;
+ *macKey = macKeyTmp;
+ return SECSuccess;
+
+loser:
+ if (aesKeyTmp)
+ PK11_FreeSymKey(aesKeyTmp);
+ if (macKeyTmp)
+ PK11_FreeSymKey(macKeyTmp);
+ return SECFailure;
+}
+
+static SECStatus
+ssl_GenerateSelfEncryptKeys(void *pwArg, PRUint8 *keyName,
+ PK11SymKey **encKey, PK11SymKey **macKey)
+{
+ SECKEYPrivateKey *svrPrivKey = NULL;
+ SECKEYPublicKey *svrPubKey = NULL;
+ PRUint32 now;
+ cacheDesc *cache = &globalCache;
+
+ SECStatus rv = ssl_GetSelfEncryptKeyPair(&svrPubKey, &svrPrivKey);
+ if (rv != SECSuccess || !cache->cacheMem) {
+ /* No key pair for wrapping, or the cache is uninitialized. Generate
+ * keys and return them without caching. */
+ rv = GenerateSelfEncryptKeys(pwArg, keyName, encKey, macKey);
+ } else {
+ now = LockSidCacheLock(cache->keyCacheLock, 0);
+ if (!now) {
+ goto loser;
+ }
+
+ if (*(cache->ticketKeysValid)) {
+ rv = UnwrapCachedSelfEncryptKeys(svrPrivKey, keyName, encKey, macKey);
+ } else {
+ /* Keys do not exist, create them. */
+ rv = GenerateAndWrapSelfEncryptKeys(svrPubKey, pwArg, keyName,
+ encKey, macKey);
+ if (rv == SECSuccess) {
+ *(cache->ticketKeysValid) = 1;
+ }
+ }
+ UnlockSidCacheLock(cache->keyCacheLock);
+ }
+ SECKEY_DestroyPublicKey(svrPubKey);
+ SECKEY_DestroyPrivateKey(svrPrivKey);
+ return rv;
+
+loser:
+ UnlockSidCacheLock(cache->keyCacheLock);
+ SECKEY_DestroyPublicKey(svrPubKey);
+ SECKEY_DestroyPrivateKey(svrPrivKey);
+ return SECFailure;
+}
+
+/* The caller passes in the new value it wants
+ * to set. This code tests the wrapped sym key entry in the shared memory.
+ * If it is uninitialized, this function writes the caller's value into
+ * the disk entry, and returns false.
+ * Otherwise, it overwrites the caller's wswk with the value obtained from
+ * the disk, and returns PR_TRUE.
+ * This is all done while holding the locks/mutexes necessary to make
+ * the operation atomic.
+ */
+SECStatus
+ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk)
+{
+ cacheDesc *cache = &globalCache;
+ PRBool rv = SECFailure;
+ PRUint32 ndx;
+ PRUint32 now;
+ SSLWrappedSymWrappingKey myWswk;
+
+ if (!cache->cacheMem) { /* cache is uninitialized */
+ PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED);
+ return SECFailure;
+ }
+
+ PORT_Assert(wswk->wrapMechIndex < SSL_NUM_WRAP_MECHS);
+ PORT_Assert(wswk->wrapKeyIndex < SSL_NUM_WRAP_KEYS);
+ if (wswk->wrapMechIndex >= SSL_NUM_WRAP_MECHS ||
+ wswk->wrapKeyIndex >= SSL_NUM_WRAP_KEYS) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ndx = (wswk->wrapKeyIndex * SSL_NUM_WRAP_MECHS) + wswk->wrapMechIndex;
+ PORT_Memset(&myWswk, 0, sizeof myWswk); /* eliminate UMRs. */
+
+ now = LockSidCacheLock(cache->keyCacheLock, 0);
+ if (!now) {
+ return SECFailure;
+ }
+ rv = getSvrWrappingKey(wswk->wrapMechIndex, wswk->wrapKeyIndex,
+ &myWswk, cache, now);
+ if (rv == SECSuccess) {
+ /* we found it on disk, copy it out to the caller. */
+ PORT_Memcpy(wswk, &myWswk, sizeof *wswk);
+ } else {
+ /* Wasn't on disk, and we're still holding the lock, so write it. */
+ cache->keyCacheData[ndx] = *wswk;
+ }
+ UnlockSidCacheLock(cache->keyCacheLock);
+ return rv;
+}
+
+#else /* MAC version or other platform */
+
+#include "seccomon.h"
+#include "cert.h"
+#include "ssl.h"
+#include "sslimpl.h"
+
+SECStatus
+SSL_ConfigServerSessionIDCache(int maxCacheEntries,
+ PRUint32 ssl2_timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigServerSessionIDCache)");
+ return SECFailure;
+}
+
+SECStatus
+SSL_ConfigMPServerSIDCache(int maxCacheEntries,
+ PRUint32 ssl2_timeout,
+ PRUint32 ssl3_timeout,
+ const char *directory)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigMPServerSIDCache)");
+ return SECFailure;
+}
+
+SECStatus
+SSL_InheritMPServerSIDCache(const char *envString)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_InheritMPServerSIDCache)");
+ return SECFailure;
+}
+
+SECStatus
+ssl_GetWrappingKey(unsigned int wrapMechIndex,
+ unsigned int wrapKeyIndex,
+ SSLWrappedSymWrappingKey *wswk)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_GetWrappingKey)");
+ return SECFailure;
+}
+
+/* This is a kind of test-and-set. The caller passes in the new value it wants
+ * to set. This code tests the wrapped sym key entry in the shared memory.
+ * If it is uninitialized, this function writes the caller's value into
+ * the disk entry, and returns false.
+ * Otherwise, it overwrites the caller's wswk with the value obtained from
+ * the disk, and returns PR_TRUE.
+ * This is all done while holding the locks/mutexes necessary to make
+ * the operation atomic.
+ */
+SECStatus
+ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_SetWrappingKey)");
+ return SECFailure;
+}
+
+PRUint32
+SSL_GetMaxServerCacheLocks(void)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_GetMaxServerCacheLocks)");
+ return -1;
+}
+
+SECStatus
+SSL_SetMaxServerCacheLocks(PRUint32 maxLocks)
+{
+ PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_SetMaxServerCacheLocks)");
+ return SECFailure;
+}
+
+#endif /* XP_UNIX || XP_WIN32 */
diff --git a/security/nss/lib/ssl/sslsock.c b/security/nss/lib/ssl/sslsock.c
new file mode 100644
index 0000000000..9a778218aa
--- /dev/null
+++ b/security/nss/lib/ssl/sslsock.c
@@ -0,0 +1,4635 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * vtables (and methods that call through them) for the 4 types of
+ * SSLSockets supported. Only one type is still supported.
+ * Various other functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "seccomon.h"
+#include "cert.h"
+#include "keyhi.h"
+#include "ssl.h"
+#include "sslexp.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "nspr.h"
+#include "private/pprio.h"
+#include "nss.h"
+#include "pk11pqg.h"
+#include "pk11pub.h"
+#include "tls13ech.h"
+#include "tls13psk.h"
+#include "tls13subcerts.h"
+
+static const sslSocketOps ssl_default_ops = { /* No SSL. */
+ ssl_DefConnect,
+ NULL,
+ ssl_DefBind,
+ ssl_DefListen,
+ ssl_DefShutdown,
+ ssl_DefClose,
+ ssl_DefRecv,
+ ssl_DefSend,
+ ssl_DefRead,
+ ssl_DefWrite,
+ ssl_DefGetpeername,
+ ssl_DefGetsockname
+};
+
+static const sslSocketOps ssl_secure_ops = { /* SSL. */
+ ssl_SecureConnect,
+ NULL,
+ ssl_DefBind,
+ ssl_DefListen,
+ ssl_SecureShutdown,
+ ssl_SecureClose,
+ ssl_SecureRecv,
+ ssl_SecureSend,
+ ssl_SecureRead,
+ ssl_SecureWrite,
+ ssl_DefGetpeername,
+ ssl_DefGetsockname
+};
+
+/*
+** default settings for socket enables
+*/
+static sslOptions ssl_defaults = {
+ .nextProtoNego = { siBuffer, NULL, 0 },
+ .maxEarlyDataSize = 1 << 16,
+ .recordSizeLimit = MAX_FRAGMENT_LENGTH + 1,
+ .useSecurity = PR_TRUE,
+ .useSocks = PR_FALSE,
+ .requestCertificate = PR_FALSE,
+ .requireCertificate = SSL_REQUIRE_FIRST_HANDSHAKE,
+ .handshakeAsClient = PR_FALSE,
+ .handshakeAsServer = PR_FALSE,
+ .noCache = PR_FALSE,
+ .fdx = PR_FALSE,
+ .detectRollBack = PR_TRUE,
+ .noLocks = PR_FALSE,
+ .enableSessionTickets = PR_FALSE,
+ .enableDeflate = PR_FALSE,
+ .enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN,
+ .requireSafeNegotiation = PR_FALSE,
+ .enableFalseStart = PR_FALSE,
+ .cbcRandomIV = PR_TRUE,
+ .enableOCSPStapling = PR_FALSE,
+ .enableDelegatedCredentials = PR_FALSE,
+ .enableALPN = PR_TRUE,
+ .reuseServerECDHEKey = PR_FALSE,
+ .enableFallbackSCSV = PR_FALSE,
+ .enableServerDhe = PR_TRUE,
+ .enableExtendedMS = PR_TRUE,
+ .enableSignedCertTimestamps = PR_FALSE,
+ .requireDHENamedGroups = PR_FALSE,
+ .enable0RttData = PR_FALSE,
+ .enableTls13CompatMode = PR_FALSE,
+ .enableDtls13VersionCompat = PR_FALSE,
+ .enableDtlsShortHeader = PR_FALSE,
+ .enableHelloDowngradeCheck = PR_TRUE,
+ .enableV2CompatibleHello = PR_FALSE,
+ .enablePostHandshakeAuth = PR_FALSE,
+ .suppressEndOfEarlyData = PR_FALSE,
+ .enableTls13GreaseEch = PR_FALSE,
+ .enableTls13BackendEch = PR_FALSE,
+ .callExtensionWriterOnEchInner = PR_FALSE,
+ .enableGrease = PR_FALSE,
+ .enableChXtnPermutation = PR_FALSE
+};
+
+/*
+ * default range of enabled SSL/TLS protocols
+ */
+static SSLVersionRange versions_defaults_stream = {
+ SSL_LIBRARY_VERSION_TLS_1_2,
+ SSL_LIBRARY_VERSION_TLS_1_3
+};
+
+static SSLVersionRange versions_defaults_datagram = {
+ SSL_LIBRARY_VERSION_TLS_1_2,
+ SSL_LIBRARY_VERSION_TLS_1_2
+};
+
+#define VERSIONS_DEFAULTS(variant) \
+ (variant == ssl_variant_stream ? &versions_defaults_stream : &versions_defaults_datagram)
+#define VERSIONS_POLICY_MIN(variant) \
+ (variant == ssl_variant_stream ? NSS_TLS_VERSION_MIN_POLICY : NSS_DTLS_VERSION_MIN_POLICY)
+#define VERSIONS_POLICY_MAX(variant) \
+ (variant == ssl_variant_stream ? NSS_TLS_VERSION_MAX_POLICY : NSS_DTLS_VERSION_MAX_POLICY)
+
+sslSessionIDLookupFunc ssl_sid_lookup;
+
+static PRDescIdentity ssl_layer_id;
+
+PRBool locksEverDisabled; /* implicitly PR_FALSE */
+PRBool ssl_force_locks; /* implicitly PR_FALSE */
+int ssl_lock_readers = 1; /* default true. */
+char ssl_debug;
+char ssl_trace;
+FILE *ssl_trace_iob;
+
+#ifdef NSS_ALLOW_SSLKEYLOGFILE
+FILE *ssl_keylog_iob;
+PZLock *ssl_keylog_lock;
+#endif
+
+char lockStatus[] = "Locks are ENABLED. ";
+#define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
+
+/* SRTP_NULL_HMAC_SHA1_80 and SRTP_NULL_HMAC_SHA1_32 are not implemented. */
+static const PRUint16 srtpCiphers[] = {
+ SRTP_AES128_CM_HMAC_SHA1_80,
+ SRTP_AES128_CM_HMAC_SHA1_32,
+ 0
+};
+
+/* This list is in preference order. Note that while some smaller groups appear
+ * early in the list, smaller groups are generally ignored when iterating
+ * through this list. ffdhe_custom must not appear in this list. */
+#define ECGROUP(name, size, oid, assumeSupported) \
+ { \
+ ssl_grp_ec_##name, size, ssl_kea_ecdh, \
+ SEC_OID_SECG_EC_##oid, assumeSupported \
+ }
+#define FFGROUP(size) \
+ { \
+ ssl_grp_ffdhe_##size, size, ssl_kea_dh, \
+ SEC_OID_TLS_FFDHE_##size, PR_TRUE \
+ }
+
+const sslNamedGroupDef ssl_named_groups[] = {
+ /* Note that 256 for 25519 is a lie, but we only use it for checking bit
+ * security and expect 256 bits there (not 255). */
+ { ssl_grp_ec_curve25519, 256, ssl_kea_ecdh, SEC_OID_CURVE25519, PR_TRUE },
+ ECGROUP(secp256r1, 256, SECP256R1, PR_TRUE),
+ ECGROUP(secp384r1, 384, SECP384R1, PR_TRUE),
+ ECGROUP(secp521r1, 521, SECP521R1, PR_TRUE),
+ FFGROUP(2048),
+ FFGROUP(3072),
+ FFGROUP(4096),
+ FFGROUP(6144),
+ FFGROUP(8192),
+ ECGROUP(secp192r1, 192, SECP192R1, PR_FALSE),
+ ECGROUP(secp160r2, 160, SECP160R2, PR_FALSE),
+ ECGROUP(secp160k1, 160, SECP160K1, PR_FALSE),
+ ECGROUP(secp160r1, 160, SECP160R1, PR_FALSE),
+ ECGROUP(sect163k1, 163, SECT163K1, PR_FALSE),
+ ECGROUP(sect163r1, 163, SECT163R1, PR_FALSE),
+ ECGROUP(sect163r2, 163, SECT163R2, PR_FALSE),
+ ECGROUP(secp192k1, 192, SECP192K1, PR_FALSE),
+ ECGROUP(sect193r1, 193, SECT193R1, PR_FALSE),
+ ECGROUP(sect193r2, 193, SECT193R2, PR_FALSE),
+ ECGROUP(secp224r1, 224, SECP224R1, PR_FALSE),
+ ECGROUP(secp224k1, 224, SECP224K1, PR_FALSE),
+ ECGROUP(sect233k1, 233, SECT233K1, PR_FALSE),
+ ECGROUP(sect233r1, 233, SECT233R1, PR_FALSE),
+ ECGROUP(sect239k1, 239, SECT239K1, PR_FALSE),
+ ECGROUP(secp256k1, 256, SECP256K1, PR_FALSE),
+ ECGROUP(sect283k1, 283, SECT283K1, PR_FALSE),
+ ECGROUP(sect283r1, 283, SECT283R1, PR_FALSE),
+ ECGROUP(sect409k1, 409, SECT409K1, PR_FALSE),
+ ECGROUP(sect409r1, 409, SECT409R1, PR_FALSE),
+ ECGROUP(sect571k1, 571, SECT571K1, PR_FALSE),
+ ECGROUP(sect571r1, 571, SECT571R1, PR_FALSE),
+};
+PR_STATIC_ASSERT(SSL_NAMED_GROUP_COUNT == PR_ARRAY_SIZE(ssl_named_groups));
+
+#undef ECGROUP
+#undef FFGROUP
+
+/* forward declarations. */
+static sslSocket *ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant variant);
+static SECStatus ssl_MakeLocks(sslSocket *ss);
+static void ssl_SetDefaultsFromEnvironment(void);
+static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack,
+ PRDescIdentity id);
+
+/************************************************************************/
+
+/*
+** Lookup a socket structure from a file descriptor.
+** Only functions called through the PRIOMethods table should use this.
+** Other app-callable functions should use ssl_FindSocket.
+*/
+static sslSocket *
+ssl_GetPrivate(PRFileDesc *fd)
+{
+ sslSocket *ss;
+
+ PORT_Assert(fd != NULL);
+ PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
+ PORT_Assert(fd->identity == ssl_layer_id);
+
+ if (fd->methods->file_type != PR_DESC_LAYERED ||
+ fd->identity != ssl_layer_id) {
+ PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
+ return NULL;
+ }
+
+ ss = (sslSocket *)fd->secret;
+ /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
+ * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
+ * contents of the PRFileDesc pointed by ss->fd and the new layer.
+ * See bug 807250.
+ */
+ ss->fd = fd;
+ return ss;
+}
+
+/* This function tries to find the SSL layer in the stack.
+ * It searches for the first SSL layer at or below the argument fd,
+ * and failing that, it searches for the nearest SSL layer above the
+ * argument fd. It returns the private sslSocket from the found layer.
+ */
+sslSocket *
+ssl_FindSocket(PRFileDesc *fd)
+{
+ PRFileDesc *layer;
+ sslSocket *ss;
+
+ PORT_Assert(fd != NULL);
+ PORT_Assert(ssl_layer_id != 0);
+
+ layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
+ if (layer == NULL) {
+ PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
+ return NULL;
+ }
+
+ ss = (sslSocket *)layer->secret;
+ /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
+ * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
+ * contents of the PRFileDesc pointed by ss->fd and the new layer.
+ * See bug 807250.
+ */
+ ss->fd = layer;
+ return ss;
+}
+
+static sslSocket *
+ssl_DupSocket(sslSocket *os)
+{
+ sslSocket *ss;
+ SECStatus rv;
+
+ ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant);
+ if (!ss) {
+ return NULL;
+ }
+
+ ss->opt = os->opt;
+ ss->opt.useSocks = PR_FALSE;
+ rv = SECITEM_CopyItem(NULL, &ss->opt.nextProtoNego, &os->opt.nextProtoNego);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ ss->vrange = os->vrange;
+ ss->now = os->now;
+ ss->nowArg = os->nowArg;
+
+ ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID);
+ ss->url = !os->url ? NULL : PORT_Strdup(os->url);
+
+ ss->ops = os->ops;
+ ss->rTimeout = os->rTimeout;
+ ss->wTimeout = os->wTimeout;
+ ss->cTimeout = os->cTimeout;
+ ss->dbHandle = os->dbHandle;
+
+ /* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
+ PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
+ PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, os->ssl3.dtlsSRTPCiphers,
+ sizeof(PRUint16) * os->ssl3.dtlsSRTPCipherCount);
+ ss->ssl3.dtlsSRTPCipherCount = os->ssl3.dtlsSRTPCipherCount;
+ PORT_Memcpy(ss->ssl3.signatureSchemes, os->ssl3.signatureSchemes,
+ sizeof(ss->ssl3.signatureSchemes[0]) *
+ os->ssl3.signatureSchemeCount);
+ ss->ssl3.signatureSchemeCount = os->ssl3.signatureSchemeCount;
+ ss->ssl3.downgradeCheckVersion = os->ssl3.downgradeCheckVersion;
+
+ ss->ssl3.dheWeakGroupEnabled = os->ssl3.dheWeakGroupEnabled;
+
+ if (ss->opt.useSecurity) {
+ PRCList *cursor;
+
+ for (cursor = PR_NEXT_LINK(&os->serverCerts);
+ cursor != &os->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *sc = ssl_CopyServerCert((sslServerCert *)cursor);
+ if (!sc)
+ goto loser;
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ }
+
+ for (cursor = PR_NEXT_LINK(&os->ephemeralKeyPairs);
+ cursor != &os->ephemeralKeyPairs;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslEphemeralKeyPair *okp = (sslEphemeralKeyPair *)cursor;
+ sslEphemeralKeyPair *skp = ssl_CopyEphemeralKeyPair(okp);
+ if (!skp)
+ goto loser;
+ PR_APPEND_LINK(&skp->link, &ss->ephemeralKeyPairs);
+ }
+
+ for (cursor = PR_NEXT_LINK(&os->extensionHooks);
+ cursor != &os->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslCustomExtensionHooks *oh = (sslCustomExtensionHooks *)cursor;
+ sslCustomExtensionHooks *sh = PORT_ZNew(sslCustomExtensionHooks);
+ if (!sh) {
+ goto loser;
+ }
+ *sh = *oh;
+ PR_APPEND_LINK(&sh->link, &ss->extensionHooks);
+ }
+
+ /*
+ * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL.
+ * XXX We should detect this, and not just march on with NULL pointers.
+ */
+ ss->authCertificate = os->authCertificate;
+ ss->authCertificateArg = os->authCertificateArg;
+ ss->getClientAuthData = os->getClientAuthData;
+ ss->getClientAuthDataArg = os->getClientAuthDataArg;
+ ss->sniSocketConfig = os->sniSocketConfig;
+ ss->sniSocketConfigArg = os->sniSocketConfigArg;
+ ss->alertReceivedCallback = os->alertReceivedCallback;
+ ss->alertReceivedCallbackArg = os->alertReceivedCallbackArg;
+ ss->alertSentCallback = os->alertSentCallback;
+ ss->alertSentCallbackArg = os->alertSentCallbackArg;
+ ss->handleBadCert = os->handleBadCert;
+ ss->badCertArg = os->badCertArg;
+ ss->handshakeCallback = os->handshakeCallback;
+ ss->handshakeCallbackData = os->handshakeCallbackData;
+ ss->canFalseStartCallback = os->canFalseStartCallback;
+ ss->canFalseStartCallbackData = os->canFalseStartCallbackData;
+ ss->pkcs11PinArg = os->pkcs11PinArg;
+ ss->nextProtoCallback = os->nextProtoCallback;
+ ss->nextProtoArg = os->nextProtoArg;
+ PORT_Memcpy((void *)ss->namedGroupPreferences,
+ os->namedGroupPreferences,
+ sizeof(ss->namedGroupPreferences));
+ ss->additionalShares = os->additionalShares;
+ ss->resumptionTokenCallback = os->resumptionTokenCallback;
+ ss->resumptionTokenContext = os->resumptionTokenContext;
+
+ rv = tls13_CopyEchConfigs(&os->echConfigs, &ss->echConfigs);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (os->echPrivKey && os->echPubKey) {
+ ss->echPrivKey = SECKEY_CopyPrivateKey(os->echPrivKey);
+ ss->echPubKey = SECKEY_CopyPublicKey(os->echPubKey);
+ if (!ss->echPrivKey || !ss->echPubKey) {
+ goto loser;
+ }
+ }
+
+ if (os->antiReplay) {
+ ss->antiReplay = tls13_RefAntiReplayContext(os->antiReplay);
+ PORT_Assert(ss->antiReplay); /* Can't fail. */
+ if (!ss->antiReplay) {
+ goto loser;
+ }
+ }
+ if (os->psk) {
+ ss->psk = tls13_CopyPsk(os->psk);
+ if (!ss->psk) {
+ goto loser;
+ }
+ }
+
+ /* Create security data */
+ rv = ssl_CopySecurityInfo(ss, os);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ return ss;
+
+loser:
+ ssl_FreeSocket(ss);
+ return NULL;
+}
+
+static void
+ssl_DestroyLocks(sslSocket *ss)
+{
+ /* Destroy locks. */
+ if (ss->firstHandshakeLock) {
+ PZ_DestroyMonitor(ss->firstHandshakeLock);
+ ss->firstHandshakeLock = NULL;
+ }
+ if (ss->ssl3HandshakeLock) {
+ PZ_DestroyMonitor(ss->ssl3HandshakeLock);
+ ss->ssl3HandshakeLock = NULL;
+ }
+ if (ss->specLock) {
+ NSSRWLock_Destroy(ss->specLock);
+ ss->specLock = NULL;
+ }
+
+ if (ss->recvLock) {
+ PZ_DestroyLock(ss->recvLock);
+ ss->recvLock = NULL;
+ }
+ if (ss->sendLock) {
+ PZ_DestroyLock(ss->sendLock);
+ ss->sendLock = NULL;
+ }
+ if (ss->xmitBufLock) {
+ PZ_DestroyMonitor(ss->xmitBufLock);
+ ss->xmitBufLock = NULL;
+ }
+ if (ss->recvBufLock) {
+ PZ_DestroyMonitor(ss->recvBufLock);
+ ss->recvBufLock = NULL;
+ }
+}
+
+/* Caller holds any relevant locks */
+static void
+ssl_DestroySocketContents(sslSocket *ss)
+{
+ PRCList *cursor;
+
+ /* Free up socket */
+ ssl_DestroySecurityInfo(&ss->sec);
+
+ ssl3_DestroySSL3Info(ss);
+
+ PORT_Free(ss->saveBuf.buf);
+ PORT_Free(ss->pendingBuf.buf);
+ ssl3_DestroyGather(&ss->gs);
+
+ if (ss->peerID != NULL)
+ PORT_Free(ss->peerID);
+ if (ss->url != NULL)
+ PORT_Free((void *)ss->url); /* CONST */
+
+ /* Clean up server certificates and sundries. */
+ while (!PR_CLIST_IS_EMPTY(&ss->serverCerts)) {
+ cursor = PR_LIST_TAIL(&ss->serverCerts);
+ PR_REMOVE_LINK(cursor);
+ ssl_FreeServerCert((sslServerCert *)cursor);
+ }
+
+ /* Remove extension handlers. */
+ ssl_ClearPRCList(&ss->extensionHooks, NULL);
+
+ ssl_FreeEphemeralKeyPairs(ss);
+ SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
+ ssl3_FreeSniNameArray(&ss->xtnData);
+
+ ssl_ClearPRCList(&ss->ssl3.hs.dtlsSentHandshake, NULL);
+ ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL);
+ tls13_DestroyPskList(&ss->ssl3.hs.psks);
+
+ tls13_ReleaseAntiReplayContext(ss->antiReplay);
+
+ tls13_DestroyPsk(ss->psk);
+
+ tls13_DestroyEchConfigs(&ss->echConfigs);
+ SECKEY_DestroyPrivateKey(ss->echPrivKey);
+ SECKEY_DestroyPublicKey(ss->echPubKey);
+}
+
+/*
+ * free an sslSocket struct, and all the stuff that hangs off of it
+ */
+void
+ssl_FreeSocket(sslSocket *ss)
+{
+ /* Get every lock you can imagine!
+ ** Caller already holds these:
+ ** SSL_LOCK_READER(ss);
+ ** SSL_LOCK_WRITER(ss);
+ */
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetRecvBufLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+ ssl_GetXmitBufLock(ss);
+ ssl_GetSpecWriteLock(ss);
+
+ ssl_DestroySocketContents(ss);
+
+ /* Release all the locks acquired above. */
+ SSL_UNLOCK_READER(ss);
+ SSL_UNLOCK_WRITER(ss);
+ ssl_Release1stHandshakeLock(ss);
+ ssl_ReleaseRecvBufLock(ss);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_ReleaseXmitBufLock(ss);
+ ssl_ReleaseSpecWriteLock(ss);
+
+ ssl_DestroyLocks(ss);
+
+#ifdef DEBUG
+ PORT_Memset(ss, 0x1f, sizeof *ss);
+#endif
+ PORT_Free(ss);
+ return;
+}
+
+/************************************************************************/
+SECStatus
+ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
+{
+ PRFileDesc *osfd = ss->fd->lower;
+ SECStatus rv = SECFailure;
+ PRSocketOptionData opt;
+
+ opt.option = PR_SockOpt_NoDelay;
+ opt.value.no_delay = (PRBool)!enabled;
+
+ if (osfd->methods->setsocketoption) {
+ rv = (SECStatus)osfd->methods->setsocketoption(osfd, &opt);
+ } else {
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ }
+
+ return rv;
+}
+
+static void
+ssl_ChooseOps(sslSocket *ss)
+{
+ ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
+}
+
+/* Called from SSL_Enable (immediately below) */
+static SECStatus
+PrepareSocket(sslSocket *ss)
+{
+ SECStatus rv = SECSuccess;
+
+ ssl_ChooseOps(ss);
+ return rv;
+}
+
+SECStatus
+SSL_Enable(PRFileDesc *fd, int which, PRIntn on)
+{
+ return SSL_OptionSet(fd, which, on);
+}
+
+static PRBool ssl_VersionIsSupportedByPolicy(
+ SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version);
+
+/* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in
+ * ssl.h in the section "SSL version range setting API".
+ */
+static void
+ssl_EnableTLS(SSLVersionRange *vrange, PRIntn enable)
+{
+ if (enable) {
+ /* don't turn it on if tls1.0 disallowed by by policy */
+ if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream,
+ SSL_LIBRARY_VERSION_TLS_1_0)) {
+ return;
+ }
+ }
+ if (SSL_ALL_VERSIONS_DISABLED(vrange)) {
+ if (enable) {
+ vrange->min = SSL_LIBRARY_VERSION_TLS_1_0;
+ vrange->max = SSL_LIBRARY_VERSION_TLS_1_0;
+ } /* else don't change anything */
+ return;
+ }
+
+ if (enable) {
+ /* Expand the range of enabled version to include TLS 1.0 */
+ vrange->min = PR_MIN(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
+ vrange->max = PR_MAX(vrange->max, SSL_LIBRARY_VERSION_TLS_1_0);
+ } else {
+ /* Disable all TLS versions, leaving only SSL 3.0 if it was enabled */
+ if (vrange->min == SSL_LIBRARY_VERSION_3_0) {
+ vrange->max = SSL_LIBRARY_VERSION_3_0;
+ } else {
+ /* Only TLS was enabled, so now no versions are. */
+ vrange->min = SSL_LIBRARY_VERSION_NONE;
+ vrange->max = SSL_LIBRARY_VERSION_NONE;
+ }
+ }
+}
+
+/* Implements the semantics for SSL_OptionSet(SSL_ENABLE_SSL3, on) described in
+ * ssl.h in the section "SSL version range setting API".
+ */
+static void
+ssl_EnableSSL3(SSLVersionRange *vrange, PRIntn enable)
+{
+ if (enable) {
+ /* don't turn it on if ssl3 disallowed by by policy */
+ if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream,
+ SSL_LIBRARY_VERSION_3_0)) {
+ return;
+ }
+ }
+ if (SSL_ALL_VERSIONS_DISABLED(vrange)) {
+ if (enable) {
+ vrange->min = SSL_LIBRARY_VERSION_3_0;
+ vrange->max = SSL_LIBRARY_VERSION_3_0;
+ } /* else don't change anything */
+ return;
+ }
+
+ if (enable) {
+ /* Expand the range of enabled versions to include SSL 3.0. We know
+ * SSL 3.0 or some version of TLS is already enabled at this point, so
+ * we don't need to change vrange->max.
+ */
+ vrange->min = SSL_LIBRARY_VERSION_3_0;
+ } else {
+ /* Disable SSL 3.0, leaving TLS unaffected. */
+ if (vrange->max > SSL_LIBRARY_VERSION_3_0) {
+ vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
+ } else {
+ /* Only SSL 3.0 was enabled, so now no versions are. */
+ vrange->min = SSL_LIBRARY_VERSION_NONE;
+ vrange->max = SSL_LIBRARY_VERSION_NONE;
+ }
+ }
+}
+
+SECStatus
+SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRIntn val)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ SECStatus rv = SECSuccess;
+ PRBool holdingLocks;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ holdingLocks = (!ss->opt.noLocks);
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ switch (which) {
+ case SSL_SOCKS:
+ ss->opt.useSocks = PR_FALSE;
+ rv = PrepareSocket(ss);
+ if (val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+ break;
+
+ case SSL_SECURITY:
+ ss->opt.useSecurity = val;
+ rv = PrepareSocket(ss);
+ break;
+
+ case SSL_REQUEST_CERTIFICATE:
+ ss->opt.requestCertificate = val;
+ break;
+
+ case SSL_REQUIRE_CERTIFICATE:
+ ss->opt.requireCertificate = val;
+ break;
+
+ case SSL_HANDSHAKE_AS_CLIENT:
+ if (ss->opt.handshakeAsServer && val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ break;
+ }
+ ss->opt.handshakeAsClient = val;
+ break;
+
+ case SSL_HANDSHAKE_AS_SERVER:
+ if (ss->opt.handshakeAsClient && val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ break;
+ }
+ ss->opt.handshakeAsServer = val;
+ break;
+
+ case SSL_ENABLE_TLS:
+ if (IS_DTLS(ss)) {
+ if (val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure; /* not allowed */
+ }
+ break;
+ }
+ ssl_EnableTLS(&ss->vrange, val);
+ break;
+
+ case SSL_ENABLE_SSL3:
+ if (IS_DTLS(ss)) {
+ if (val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure; /* not allowed */
+ }
+ break;
+ }
+ ssl_EnableSSL3(&ss->vrange, val);
+ break;
+
+ case SSL_ENABLE_SSL2:
+ case SSL_V2_COMPATIBLE_HELLO:
+ /* We no longer support SSL v2.
+ * However, if an old application requests to disable SSL v2,
+ * we shouldn't fail.
+ */
+ if (val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+ break;
+
+ case SSL_NO_CACHE:
+ ss->opt.noCache = val;
+ break;
+
+ case SSL_ENABLE_FDX:
+ if (val && ss->opt.noLocks) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+ ss->opt.fdx = val;
+ break;
+
+ case SSL_ROLLBACK_DETECTION:
+ ss->opt.detectRollBack = val;
+ break;
+
+ case SSL_NO_STEP_DOWN:
+ break;
+
+ case SSL_BYPASS_PKCS11:
+ break;
+
+ case SSL_NO_LOCKS:
+ if (val && ss->opt.fdx) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+ if (val && ssl_force_locks)
+ val = PR_FALSE; /* silent override */
+ ss->opt.noLocks = val;
+ if (val) {
+ locksEverDisabled = PR_TRUE;
+ strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
+ } else if (!holdingLocks) {
+ rv = ssl_MakeLocks(ss);
+ if (rv != SECSuccess) {
+ ss->opt.noLocks = PR_TRUE;
+ }
+ }
+ break;
+
+ case SSL_ENABLE_SESSION_TICKETS:
+ ss->opt.enableSessionTickets = val;
+ break;
+
+ case SSL_ENABLE_DEFLATE:
+ ss->opt.enableDeflate = val;
+ break;
+
+ case SSL_ENABLE_RENEGOTIATION:
+ if (IS_DTLS(ss) && val != SSL_RENEGOTIATE_NEVER) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ break;
+ }
+ ss->opt.enableRenegotiation = val;
+ break;
+
+ case SSL_REQUIRE_SAFE_NEGOTIATION:
+ ss->opt.requireSafeNegotiation = val;
+ break;
+
+ case SSL_ENABLE_FALSE_START:
+ ss->opt.enableFalseStart = val;
+ break;
+
+ case SSL_CBC_RANDOM_IV:
+ ss->opt.cbcRandomIV = val;
+ break;
+
+ case SSL_ENABLE_OCSP_STAPLING:
+ ss->opt.enableOCSPStapling = val;
+ break;
+
+ case SSL_ENABLE_DELEGATED_CREDENTIALS:
+ ss->opt.enableDelegatedCredentials = val;
+ break;
+
+ case SSL_ENABLE_NPN:
+ break;
+
+ case SSL_ENABLE_ALPN:
+ ss->opt.enableALPN = val;
+ break;
+
+ case SSL_REUSE_SERVER_ECDHE_KEY:
+ ss->opt.reuseServerECDHEKey = val;
+ break;
+
+ case SSL_ENABLE_FALLBACK_SCSV:
+ ss->opt.enableFallbackSCSV = val;
+ break;
+
+ case SSL_ENABLE_SERVER_DHE:
+ ss->opt.enableServerDhe = val;
+ break;
+
+ case SSL_ENABLE_EXTENDED_MASTER_SECRET:
+ ss->opt.enableExtendedMS = val;
+ break;
+
+ case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
+ ss->opt.enableSignedCertTimestamps = val;
+ break;
+
+ case SSL_REQUIRE_DH_NAMED_GROUPS:
+ ss->opt.requireDHENamedGroups = val;
+ break;
+
+ case SSL_ENABLE_0RTT_DATA:
+ ss->opt.enable0RttData = val;
+ break;
+
+ case SSL_RECORD_SIZE_LIMIT:
+ if (val < 64 || val > (MAX_FRAGMENT_LENGTH + 1)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ } else {
+ ss->opt.recordSizeLimit = val;
+ }
+ break;
+
+ case SSL_ENABLE_TLS13_COMPAT_MODE:
+ ss->opt.enableTls13CompatMode = val;
+ break;
+
+ case SSL_ENABLE_DTLS_SHORT_HEADER:
+ ss->opt.enableDtlsShortHeader = val;
+ break;
+
+ case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
+ ss->opt.enableHelloDowngradeCheck = val;
+ break;
+
+ case SSL_ENABLE_V2_COMPATIBLE_HELLO:
+ ss->opt.enableV2CompatibleHello = val;
+ break;
+
+ case SSL_ENABLE_POST_HANDSHAKE_AUTH:
+ ss->opt.enablePostHandshakeAuth = val;
+ break;
+
+ case SSL_SUPPRESS_END_OF_EARLY_DATA:
+ ss->opt.suppressEndOfEarlyData = val;
+ break;
+
+ case SSL_ENABLE_GREASE:
+ ss->opt.enableGrease = val;
+ break;
+
+ case SSL_ENABLE_CH_EXTENSION_PERMUTATION:
+ ss->opt.enableChXtnPermutation = val;
+ break;
+
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+
+ /* We can't use the macros for releasing the locks here,
+ * because ss->opt.noLocks might have changed just above.
+ * We must release these locks (monitors) here, if we aquired them above,
+ * regardless of the current value of ss->opt.noLocks.
+ */
+ if (holdingLocks) {
+ PZ_ExitMonitor((ss)->ssl3HandshakeLock);
+ PZ_ExitMonitor((ss)->firstHandshakeLock);
+ }
+
+ return rv;
+}
+
+SECStatus
+SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRIntn *pVal)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ SECStatus rv = SECSuccess;
+ PRIntn val = PR_FALSE;
+
+ if (!pVal) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
+ *pVal = PR_FALSE;
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ switch (which) {
+ case SSL_SOCKS:
+ val = PR_FALSE;
+ break;
+ case SSL_SECURITY:
+ val = ss->opt.useSecurity;
+ break;
+ case SSL_REQUEST_CERTIFICATE:
+ val = ss->opt.requestCertificate;
+ break;
+ case SSL_REQUIRE_CERTIFICATE:
+ val = ss->opt.requireCertificate;
+ break;
+ case SSL_HANDSHAKE_AS_CLIENT:
+ val = ss->opt.handshakeAsClient;
+ break;
+ case SSL_HANDSHAKE_AS_SERVER:
+ val = ss->opt.handshakeAsServer;
+ break;
+ case SSL_ENABLE_TLS:
+ val = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0;
+ break;
+ case SSL_ENABLE_SSL3:
+ val = ss->vrange.min == SSL_LIBRARY_VERSION_3_0;
+ break;
+ case SSL_ENABLE_SSL2:
+ case SSL_V2_COMPATIBLE_HELLO:
+ val = PR_FALSE;
+ break;
+ case SSL_NO_CACHE:
+ val = ss->opt.noCache;
+ break;
+ case SSL_ENABLE_FDX:
+ val = ss->opt.fdx;
+ break;
+ case SSL_ROLLBACK_DETECTION:
+ val = ss->opt.detectRollBack;
+ break;
+ case SSL_NO_STEP_DOWN:
+ val = PR_FALSE;
+ break;
+ case SSL_BYPASS_PKCS11:
+ val = PR_FALSE;
+ break;
+ case SSL_NO_LOCKS:
+ val = ss->opt.noLocks;
+ break;
+ case SSL_ENABLE_SESSION_TICKETS:
+ val = ss->opt.enableSessionTickets;
+ break;
+ case SSL_ENABLE_DEFLATE:
+ val = ss->opt.enableDeflate;
+ break;
+ case SSL_ENABLE_RENEGOTIATION:
+ val = ss->opt.enableRenegotiation;
+ break;
+ case SSL_REQUIRE_SAFE_NEGOTIATION:
+ val = ss->opt.requireSafeNegotiation;
+ break;
+ case SSL_ENABLE_FALSE_START:
+ val = ss->opt.enableFalseStart;
+ break;
+ case SSL_CBC_RANDOM_IV:
+ val = ss->opt.cbcRandomIV;
+ break;
+ case SSL_ENABLE_OCSP_STAPLING:
+ val = ss->opt.enableOCSPStapling;
+ break;
+ case SSL_ENABLE_DELEGATED_CREDENTIALS:
+ val = ss->opt.enableDelegatedCredentials;
+ break;
+ case SSL_ENABLE_NPN:
+ val = PR_FALSE;
+ break;
+ case SSL_ENABLE_ALPN:
+ val = ss->opt.enableALPN;
+ break;
+ case SSL_REUSE_SERVER_ECDHE_KEY:
+ val = ss->opt.reuseServerECDHEKey;
+ break;
+ case SSL_ENABLE_FALLBACK_SCSV:
+ val = ss->opt.enableFallbackSCSV;
+ break;
+ case SSL_ENABLE_SERVER_DHE:
+ val = ss->opt.enableServerDhe;
+ break;
+ case SSL_ENABLE_EXTENDED_MASTER_SECRET:
+ val = ss->opt.enableExtendedMS;
+ break;
+ case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
+ val = ss->opt.enableSignedCertTimestamps;
+ break;
+ case SSL_REQUIRE_DH_NAMED_GROUPS:
+ val = ss->opt.requireDHENamedGroups;
+ break;
+ case SSL_ENABLE_0RTT_DATA:
+ val = ss->opt.enable0RttData;
+ break;
+ case SSL_RECORD_SIZE_LIMIT:
+ val = ss->opt.recordSizeLimit;
+ break;
+ case SSL_ENABLE_TLS13_COMPAT_MODE:
+ val = ss->opt.enableTls13CompatMode;
+ break;
+ case SSL_ENABLE_DTLS_SHORT_HEADER:
+ val = ss->opt.enableDtlsShortHeader;
+ break;
+ case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
+ val = ss->opt.enableHelloDowngradeCheck;
+ break;
+ case SSL_ENABLE_V2_COMPATIBLE_HELLO:
+ val = ss->opt.enableV2CompatibleHello;
+ break;
+ case SSL_ENABLE_POST_HANDSHAKE_AUTH:
+ val = ss->opt.enablePostHandshakeAuth;
+ break;
+ case SSL_SUPPRESS_END_OF_EARLY_DATA:
+ val = ss->opt.suppressEndOfEarlyData;
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ *pVal = val;
+ return rv;
+}
+
+SECStatus
+SSL_OptionGetDefault(PRInt32 which, PRIntn *pVal)
+{
+ SECStatus rv = SECSuccess;
+ PRIntn val = PR_FALSE;
+
+ if (!pVal) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ssl_SetDefaultsFromEnvironment();
+
+ switch (which) {
+ case SSL_SOCKS:
+ val = PR_FALSE;
+ break;
+ case SSL_SECURITY:
+ val = ssl_defaults.useSecurity;
+ break;
+ case SSL_REQUEST_CERTIFICATE:
+ val = ssl_defaults.requestCertificate;
+ break;
+ case SSL_REQUIRE_CERTIFICATE:
+ val = ssl_defaults.requireCertificate;
+ break;
+ case SSL_HANDSHAKE_AS_CLIENT:
+ val = ssl_defaults.handshakeAsClient;
+ break;
+ case SSL_HANDSHAKE_AS_SERVER:
+ val = ssl_defaults.handshakeAsServer;
+ break;
+ case SSL_ENABLE_TLS:
+ val = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0;
+ break;
+ case SSL_ENABLE_SSL3:
+ val = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0;
+ break;
+ case SSL_ENABLE_SSL2:
+ case SSL_V2_COMPATIBLE_HELLO:
+ val = PR_FALSE;
+ break;
+ case SSL_NO_CACHE:
+ val = ssl_defaults.noCache;
+ break;
+ case SSL_ENABLE_FDX:
+ val = ssl_defaults.fdx;
+ break;
+ case SSL_ROLLBACK_DETECTION:
+ val = ssl_defaults.detectRollBack;
+ break;
+ case SSL_NO_STEP_DOWN:
+ val = PR_FALSE;
+ break;
+ case SSL_BYPASS_PKCS11:
+ val = PR_FALSE;
+ break;
+ case SSL_NO_LOCKS:
+ val = ssl_defaults.noLocks;
+ break;
+ case SSL_ENABLE_SESSION_TICKETS:
+ val = ssl_defaults.enableSessionTickets;
+ break;
+ case SSL_ENABLE_DEFLATE:
+ val = ssl_defaults.enableDeflate;
+ break;
+ case SSL_ENABLE_RENEGOTIATION:
+ val = ssl_defaults.enableRenegotiation;
+ break;
+ case SSL_REQUIRE_SAFE_NEGOTIATION:
+ val = ssl_defaults.requireSafeNegotiation;
+ break;
+ case SSL_ENABLE_FALSE_START:
+ val = ssl_defaults.enableFalseStart;
+ break;
+ case SSL_CBC_RANDOM_IV:
+ val = ssl_defaults.cbcRandomIV;
+ break;
+ case SSL_ENABLE_OCSP_STAPLING:
+ val = ssl_defaults.enableOCSPStapling;
+ break;
+ case SSL_ENABLE_DELEGATED_CREDENTIALS:
+ val = ssl_defaults.enableDelegatedCredentials;
+ break;
+ case SSL_ENABLE_NPN:
+ val = PR_FALSE;
+ break;
+ case SSL_ENABLE_ALPN:
+ val = ssl_defaults.enableALPN;
+ break;
+ case SSL_REUSE_SERVER_ECDHE_KEY:
+ val = ssl_defaults.reuseServerECDHEKey;
+ break;
+ case SSL_ENABLE_FALLBACK_SCSV:
+ val = ssl_defaults.enableFallbackSCSV;
+ break;
+ case SSL_ENABLE_SERVER_DHE:
+ val = ssl_defaults.enableServerDhe;
+ break;
+ case SSL_ENABLE_EXTENDED_MASTER_SECRET:
+ val = ssl_defaults.enableExtendedMS;
+ break;
+ case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
+ val = ssl_defaults.enableSignedCertTimestamps;
+ break;
+ case SSL_ENABLE_0RTT_DATA:
+ val = ssl_defaults.enable0RttData;
+ break;
+ case SSL_RECORD_SIZE_LIMIT:
+ val = ssl_defaults.recordSizeLimit;
+ break;
+ case SSL_ENABLE_TLS13_COMPAT_MODE:
+ val = ssl_defaults.enableTls13CompatMode;
+ break;
+ case SSL_ENABLE_DTLS_SHORT_HEADER:
+ val = ssl_defaults.enableDtlsShortHeader;
+ break;
+ case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
+ val = ssl_defaults.enableHelloDowngradeCheck;
+ break;
+ case SSL_ENABLE_V2_COMPATIBLE_HELLO:
+ val = ssl_defaults.enableV2CompatibleHello;
+ break;
+ case SSL_ENABLE_POST_HANDSHAKE_AUTH:
+ val = ssl_defaults.enablePostHandshakeAuth;
+ break;
+ case SSL_SUPPRESS_END_OF_EARLY_DATA:
+ val = ssl_defaults.suppressEndOfEarlyData;
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ rv = SECFailure;
+ }
+
+ *pVal = val;
+ return rv;
+}
+
+/* XXX Use Global Lock to protect this stuff. */
+SECStatus
+SSL_EnableDefault(int which, PRIntn val)
+{
+ return SSL_OptionSetDefault(which, val);
+}
+
+SECStatus
+SSL_OptionSetDefault(PRInt32 which, PRIntn val)
+{
+ SECStatus status = ssl_Init();
+
+ if (status != SECSuccess) {
+ return status;
+ }
+
+ ssl_SetDefaultsFromEnvironment();
+
+ switch (which) {
+ case SSL_SOCKS:
+ ssl_defaults.useSocks = PR_FALSE;
+ if (val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ break;
+
+ case SSL_SECURITY:
+ ssl_defaults.useSecurity = val;
+ break;
+
+ case SSL_REQUEST_CERTIFICATE:
+ ssl_defaults.requestCertificate = val;
+ break;
+
+ case SSL_REQUIRE_CERTIFICATE:
+ ssl_defaults.requireCertificate = val;
+ break;
+
+ case SSL_HANDSHAKE_AS_CLIENT:
+ if (ssl_defaults.handshakeAsServer && val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ssl_defaults.handshakeAsClient = val;
+ break;
+
+ case SSL_HANDSHAKE_AS_SERVER:
+ if (ssl_defaults.handshakeAsClient && val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ssl_defaults.handshakeAsServer = val;
+ break;
+
+ case SSL_ENABLE_TLS:
+ ssl_EnableTLS(&versions_defaults_stream, val);
+ break;
+
+ case SSL_ENABLE_SSL3:
+ ssl_EnableSSL3(&versions_defaults_stream, val);
+ break;
+
+ case SSL_ENABLE_SSL2:
+ case SSL_V2_COMPATIBLE_HELLO:
+ /* We no longer support SSL v2.
+ * However, if an old application requests to disable SSL v2,
+ * we shouldn't fail.
+ */
+ if (val) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ break;
+
+ case SSL_NO_CACHE:
+ ssl_defaults.noCache = val;
+ break;
+
+ case SSL_ENABLE_FDX:
+ if (val && ssl_defaults.noLocks) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ssl_defaults.fdx = val;
+ break;
+
+ case SSL_ROLLBACK_DETECTION:
+ ssl_defaults.detectRollBack = val;
+ break;
+
+ case SSL_NO_STEP_DOWN:
+ break;
+
+ case SSL_BYPASS_PKCS11:
+ break;
+
+ case SSL_NO_LOCKS:
+ if (val && ssl_defaults.fdx) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (val && ssl_force_locks)
+ val = PR_FALSE; /* silent override */
+ ssl_defaults.noLocks = val;
+ if (val) {
+ locksEverDisabled = PR_TRUE;
+ strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
+ }
+ break;
+
+ case SSL_ENABLE_SESSION_TICKETS:
+ ssl_defaults.enableSessionTickets = val;
+ break;
+
+ case SSL_ENABLE_DEFLATE:
+ ssl_defaults.enableDeflate = val;
+ break;
+
+ case SSL_ENABLE_RENEGOTIATION:
+ ssl_defaults.enableRenegotiation = val;
+ break;
+
+ case SSL_REQUIRE_SAFE_NEGOTIATION:
+ ssl_defaults.requireSafeNegotiation = val;
+ break;
+
+ case SSL_ENABLE_FALSE_START:
+ ssl_defaults.enableFalseStart = val;
+ break;
+
+ case SSL_CBC_RANDOM_IV:
+ ssl_defaults.cbcRandomIV = val;
+ break;
+
+ case SSL_ENABLE_OCSP_STAPLING:
+ ssl_defaults.enableOCSPStapling = val;
+ break;
+
+ case SSL_ENABLE_DELEGATED_CREDENTIALS:
+ ssl_defaults.enableDelegatedCredentials = val;
+ break;
+
+ case SSL_ENABLE_NPN:
+ break;
+
+ case SSL_ENABLE_ALPN:
+ ssl_defaults.enableALPN = val;
+ break;
+
+ case SSL_REUSE_SERVER_ECDHE_KEY:
+ ssl_defaults.reuseServerECDHEKey = val;
+ break;
+
+ case SSL_ENABLE_FALLBACK_SCSV:
+ ssl_defaults.enableFallbackSCSV = val;
+ break;
+
+ case SSL_ENABLE_SERVER_DHE:
+ ssl_defaults.enableServerDhe = val;
+ break;
+
+ case SSL_ENABLE_EXTENDED_MASTER_SECRET:
+ ssl_defaults.enableExtendedMS = val;
+ break;
+
+ case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
+ ssl_defaults.enableSignedCertTimestamps = val;
+ break;
+
+ case SSL_ENABLE_0RTT_DATA:
+ ssl_defaults.enable0RttData = val;
+ break;
+
+ case SSL_RECORD_SIZE_LIMIT:
+ if (val < 64 || val > (MAX_FRAGMENT_LENGTH + 1)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ssl_defaults.recordSizeLimit = val;
+ break;
+
+ case SSL_ENABLE_TLS13_COMPAT_MODE:
+ ssl_defaults.enableTls13CompatMode = val;
+ break;
+
+ case SSL_ENABLE_DTLS_SHORT_HEADER:
+ ssl_defaults.enableDtlsShortHeader = val;
+ break;
+
+ case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
+ ssl_defaults.enableHelloDowngradeCheck = val;
+ break;
+
+ case SSL_ENABLE_V2_COMPATIBLE_HELLO:
+ ssl_defaults.enableV2CompatibleHello = val;
+ break;
+
+ case SSL_ENABLE_POST_HANDSHAKE_AUTH:
+ ssl_defaults.enablePostHandshakeAuth = val;
+ break;
+
+ case SSL_SUPPRESS_END_OF_EARLY_DATA:
+ ssl_defaults.suppressEndOfEarlyData = val;
+ break;
+
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SetMaxEarlyDataSize(PRFileDesc *fd, PRUint32 size)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure; /* Error code already set. */
+ }
+
+ ss->opt.maxEarlyDataSize = size;
+ return SECSuccess;
+}
+
+/* function tells us if the cipher suite is one that we no longer support. */
+static PRBool
+ssl_IsRemovedCipherSuite(PRInt32 suite)
+{
+ switch (suite) {
+ case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
+ case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
+ case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
+ return PR_TRUE;
+ default:
+ return PR_FALSE;
+ }
+}
+
+/* Part of the public NSS API.
+ * Since this is a global (not per-socket) setting, we cannot use the
+ * HandshakeLock to protect this. Probably want a global lock.
+ */
+SECStatus
+SSL_SetPolicy(long which, int policy)
+{
+ if (ssl_IsRemovedCipherSuite(which))
+ return SECSuccess;
+ return SSL_CipherPolicySet(which, policy);
+}
+
+SECStatus
+ssl_CipherPolicySet(PRInt32 which, PRInt32 policy)
+{
+ SECStatus rv = SECSuccess;
+
+ if (ssl_IsRemovedCipherSuite(which)) {
+ rv = SECSuccess;
+ } else {
+ rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
+ }
+ return rv;
+}
+SECStatus
+SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
+{
+ SECStatus rv = ssl_Init();
+
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ if (NSS_IsPolicyLocked()) {
+ PORT_SetError(SEC_ERROR_POLICY_LOCKED);
+ return SECFailure;
+ }
+ return ssl_CipherPolicySet(which, policy);
+}
+
+SECStatus
+SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
+{
+ SECStatus rv;
+
+ if (!oPolicy) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (ssl_IsRemovedCipherSuite(which)) {
+ *oPolicy = SSL_NOT_ALLOWED;
+ rv = SECSuccess;
+ } else {
+ rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
+ }
+ return rv;
+}
+
+/* Part of the public NSS API.
+ * Since this is a global (not per-socket) setting, we cannot use the
+ * HandshakeLock to protect this. Probably want a global lock.
+ * These changes have no effect on any sslSockets already created.
+ */
+SECStatus
+SSL_EnableCipher(long which, PRBool enabled)
+{
+ if (ssl_IsRemovedCipherSuite(which))
+ return SECSuccess;
+ return SSL_CipherPrefSetDefault(which, enabled);
+}
+
+SECStatus
+ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
+{
+ if (ssl_IsRemovedCipherSuite(which))
+ return SECSuccess;
+ return ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
+}
+
+SECStatus
+SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
+{
+ SECStatus rv = ssl_Init();
+ PRInt32 locks;
+
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ rv = NSS_OptionGet(NSS_DEFAULT_LOCKS, &locks);
+ if ((rv == SECSuccess) && (locks & NSS_DEFAULT_SSL_LOCK)) {
+ return SECSuccess;
+ }
+ return ssl_CipherPrefSetDefault(which, enabled);
+}
+
+SECStatus
+SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
+{
+ SECStatus rv;
+
+ if (!enabled) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (ssl_IsRemovedCipherSuite(which)) {
+ *enabled = PR_FALSE;
+ rv = SECSuccess;
+ } else {
+ rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
+ }
+ return rv;
+}
+
+SECStatus
+SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ PRInt32 locks;
+ SECStatus rv;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ rv = NSS_OptionGet(NSS_DEFAULT_LOCKS, &locks);
+ if ((rv == SECSuccess) && (locks & NSS_DEFAULT_SSL_LOCK)) {
+ return SECSuccess;
+ }
+ if (ssl_IsRemovedCipherSuite(which))
+ return SECSuccess;
+ return ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
+}
+
+SECStatus
+SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
+{
+ SECStatus rv;
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!enabled) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
+ *enabled = PR_FALSE;
+ return SECFailure;
+ }
+ if (ssl_IsRemovedCipherSuite(which)) {
+ *enabled = PR_FALSE;
+ rv = SECSuccess;
+ } else {
+ rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
+ }
+ return rv;
+}
+
+/* The client can call this function to be aware of the current
+ * CipherSuites order. */
+SECStatus
+SSLExp_CipherSuiteOrderGet(PRFileDesc *fd, PRUint16 *cipherOrder,
+ unsigned int *numCiphers)
+{
+ if (!fd) {
+ SSL_DBG(("%d: SSL: file descriptor in CipherSuiteOrderGet is null",
+ SSL_GETPID()));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (!cipherOrder || !numCiphers) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in CipherSuiteOrderGet", SSL_GETPID(),
+ fd));
+ return SECFailure; /* Error code already set. */
+ }
+
+ unsigned int enabled = 0;
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+ for (unsigned int i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ const ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
+ if (suiteCfg && suiteCfg->enabled &&
+ suiteCfg->policy != SSL_NOT_ALLOWED) {
+ cipherOrder[enabled++] = suiteCfg->cipher_suite;
+ }
+ }
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ *numCiphers = enabled;
+ return SECSuccess;
+}
+
+/* This function permits reorder the CipherSuites List for the Handshake
+ * (Client Hello). */
+SECStatus
+SSLExp_CipherSuiteOrderSet(PRFileDesc *fd, const PRUint16 *cipherOrder,
+ unsigned int numCiphers)
+{
+ if (!fd) {
+ SSL_DBG(("%d: SSL: file descriptor in CipherSuiteOrderGet is null",
+ SSL_GETPID()));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (!cipherOrder || !numCiphers || numCiphers > ssl_V3_SUITES_IMPLEMENTED) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in CipherSuiteOrderSet", SSL_GETPID(),
+ fd));
+ return SECFailure; /* Error code already set. */
+ }
+ ssl3CipherSuiteCfg tmpSuiteCfg[ssl_V3_SUITES_IMPLEMENTED];
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+ /* For each cipherSuite given as input, verify that it is
+ * known to NSS and only present in the list once. */
+ for (unsigned int i = 0; i < numCiphers; i++) {
+ const ssl3CipherSuiteCfg *suiteCfg =
+ ssl_LookupCipherSuiteCfg(cipherOrder[i], ss->cipherSuites);
+ if (!suiteCfg) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECFailure;
+ }
+ for (unsigned int j = i + 1; j < numCiphers; j++) {
+ /* This is a duplicate entry. */
+ if (cipherOrder[i] == cipherOrder[j]) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECFailure;
+ }
+ }
+ tmpSuiteCfg[i] = *suiteCfg;
+ tmpSuiteCfg[i].enabled = PR_TRUE;
+ }
+ /* Find all defined ciphersuites not present in the input list and append
+ * them after the preferred. This guarantees that the socket will always
+ * have a complete list of size ssl_V3_SUITES_IMPLEMENTED */
+ unsigned int cfgIdx = numCiphers;
+ for (unsigned int i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
+ PRBool received = PR_FALSE;
+ for (unsigned int j = 0; j < numCiphers; j++) {
+ if (ss->cipherSuites[i].cipher_suite ==
+ tmpSuiteCfg[j].cipher_suite) {
+ received = PR_TRUE;
+ break;
+ }
+ }
+ if (!received) {
+ tmpSuiteCfg[cfgIdx] = ss->cipherSuites[i];
+ tmpSuiteCfg[cfgIdx++].enabled = PR_FALSE;
+ }
+ }
+ PORT_Assert(cfgIdx == ssl_V3_SUITES_IMPLEMENTED);
+ /* now we can rewrite the socket with the desired order */
+ PORT_Memcpy(ss->cipherSuites, tmpSuiteCfg, sizeof(tmpSuiteCfg));
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECSuccess;
+}
+
+SECStatus
+NSS_SetDomesticPolicy(void)
+{
+ SECStatus status = SECSuccess;
+ const PRUint16 *cipher;
+ SECStatus rv;
+ PRUint32 policy;
+
+ /* If we've already defined some policy oids, skip changing them */
+ rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
+ if ((rv == SECSuccess) && (policy & NSS_USE_POLICY_IN_SSL)) {
+ return ssl_Init(); /* make sure the policies have been loaded */
+ }
+
+ for (cipher = SSL_ImplementedCiphers; *cipher != 0; ++cipher) {
+ status = SSL_SetPolicy(*cipher, SSL_ALLOWED);
+ if (status != SECSuccess)
+ break;
+ }
+ return status;
+}
+
+SECStatus
+NSS_SetExportPolicy(void)
+{
+ return NSS_SetDomesticPolicy();
+}
+
+SECStatus
+NSS_SetFrancePolicy(void)
+{
+ return NSS_SetDomesticPolicy();
+}
+
+SECStatus
+SSL_NamedGroupConfig(PRFileDesc *fd, const SSLNamedGroup *groups,
+ unsigned int numGroups)
+{
+ unsigned int i;
+ unsigned int j = 0;
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+ return SECFailure;
+ }
+
+ if (!groups) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (numGroups > SSL_NAMED_GROUP_COUNT) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ memset((void *)ss->namedGroupPreferences, 0,
+ sizeof(ss->namedGroupPreferences));
+ for (i = 0; i < numGroups; ++i) {
+ const sslNamedGroupDef *groupDef = ssl_LookupNamedGroup(groups[i]);
+ if (!ssl_NamedGroupEnabled(ss, groupDef)) {
+ ss->namedGroupPreferences[j++] = groupDef;
+ }
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_DHEGroupPrefSet(PRFileDesc *fd, const SSLDHEGroupType *groups,
+ PRUint16 num_groups)
+{
+ sslSocket *ss;
+ const SSLDHEGroupType *list;
+ unsigned int count;
+ int i, k, j;
+ const sslNamedGroupDef *enabled[SSL_NAMED_GROUP_COUNT] = { 0 };
+ static const SSLDHEGroupType default_dhe_groups[] = {
+ ssl_ff_dhe_2048_group
+ };
+
+ if ((num_groups && !groups) || (!num_groups && groups) ||
+ num_groups > SSL_NAMED_GROUP_COUNT) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_DHEGroupPrefSet", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (groups) {
+ list = groups;
+ count = num_groups;
+ } else {
+ list = default_dhe_groups;
+ count = PR_ARRAY_SIZE(default_dhe_groups);
+ }
+
+ /* save enabled ec groups and clear ss->namedGroupPreferences */
+ k = 0;
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ss->namedGroupPreferences[i] &&
+ ss->namedGroupPreferences[i]->keaType != ssl_kea_dh) {
+ enabled[k++] = ss->namedGroupPreferences[i];
+ }
+ ss->namedGroupPreferences[i] = NULL;
+ }
+
+ ss->ssl3.dhePreferredGroup = NULL;
+ for (i = 0; i < count; ++i) {
+ PRBool duplicate = PR_FALSE;
+ SSLNamedGroup name;
+ const sslNamedGroupDef *groupDef;
+ switch (list[i]) {
+ case ssl_ff_dhe_2048_group:
+ name = ssl_grp_ffdhe_2048;
+ break;
+ case ssl_ff_dhe_3072_group:
+ name = ssl_grp_ffdhe_3072;
+ break;
+ case ssl_ff_dhe_4096_group:
+ name = ssl_grp_ffdhe_4096;
+ break;
+ case ssl_ff_dhe_6144_group:
+ name = ssl_grp_ffdhe_6144;
+ break;
+ case ssl_ff_dhe_8192_group:
+ name = ssl_grp_ffdhe_8192;
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ groupDef = ssl_LookupNamedGroup(name);
+ PORT_Assert(groupDef);
+ if (!ss->ssl3.dhePreferredGroup) {
+ ss->ssl3.dhePreferredGroup = groupDef;
+ }
+ PORT_Assert(k < SSL_NAMED_GROUP_COUNT);
+ for (j = 0; j < k; ++j) {
+ /* skip duplicates */
+ if (enabled[j] == groupDef) {
+ duplicate = PR_TRUE;
+ break;
+ }
+ }
+ if (!duplicate) {
+ enabled[k++] = groupDef;
+ }
+ }
+ for (i = 0; i < k; ++i) {
+ ss->namedGroupPreferences[i] = enabled[i];
+ }
+
+ return SECSuccess;
+}
+
+PRCallOnceType gWeakDHParamsRegisterOnce;
+int gWeakDHParamsRegisterError;
+
+PRCallOnceType gWeakDHParamsOnce;
+int gWeakDHParamsError;
+/* As our code allocates type PQGParams, we'll keep it around,
+ * even though we only make use of it's parameters through gWeakDHParam. */
+static PQGParams *gWeakParamsPQG;
+static ssl3DHParams *gWeakDHParams;
+#define WEAK_DHE_SIZE 1024
+
+static PRStatus
+ssl3_CreateWeakDHParams(void)
+{
+ PQGVerify *vfy;
+ SECStatus rv, passed;
+
+ PORT_Assert(!gWeakDHParams && !gWeakParamsPQG);
+
+ rv = PK11_PQG_ParamGenV2(WEAK_DHE_SIZE, 160, 64 /*maximum seed that will work*/,
+ &gWeakParamsPQG, &vfy);
+ if (rv != SECSuccess) {
+ gWeakDHParamsError = PORT_GetError();
+ return PR_FAILURE;
+ }
+
+ rv = PK11_PQG_VerifyParams(gWeakParamsPQG, vfy, &passed);
+ if (rv != SECSuccess || passed != SECSuccess) {
+ SSL_DBG(("%d: PK11_PQG_VerifyParams failed in ssl3_CreateWeakDHParams",
+ SSL_GETPID()));
+ gWeakDHParamsError = PORT_GetError();
+ return PR_FAILURE;
+ }
+
+ gWeakDHParams = PORT_ArenaNew(gWeakParamsPQG->arena, ssl3DHParams);
+ if (!gWeakDHParams) {
+ gWeakDHParamsError = PORT_GetError();
+ return PR_FAILURE;
+ }
+
+ gWeakDHParams->name = ssl_grp_ffdhe_custom;
+ gWeakDHParams->prime.data = gWeakParamsPQG->prime.data;
+ gWeakDHParams->prime.len = gWeakParamsPQG->prime.len;
+ gWeakDHParams->base.data = gWeakParamsPQG->base.data;
+ gWeakDHParams->base.len = gWeakParamsPQG->base.len;
+
+ PK11_PQG_DestroyVerify(vfy);
+ return PR_SUCCESS;
+}
+
+static SECStatus
+ssl3_WeakDHParamsShutdown(void *appData, void *nssData)
+{
+ if (gWeakParamsPQG) {
+ PK11_PQG_DestroyParams(gWeakParamsPQG);
+ gWeakParamsPQG = NULL;
+ gWeakDHParams = NULL;
+ }
+ return SECSuccess;
+}
+
+static PRStatus
+ssl3_WeakDHParamsRegisterShutdown(void)
+{
+ SECStatus rv;
+ rv = NSS_RegisterShutdown(ssl3_WeakDHParamsShutdown, NULL);
+ if (rv != SECSuccess) {
+ gWeakDHParamsRegisterError = PORT_GetError();
+ }
+ return (PRStatus)rv;
+}
+
+/* global init strategy inspired by ssl3_CreateECDHEphemeralKeys */
+SECStatus
+SSL_EnableWeakDHEPrimeGroup(PRFileDesc *fd, PRBool enabled)
+{
+ sslSocket *ss;
+ PRStatus status;
+
+ if (enabled) {
+ status = PR_CallOnce(&gWeakDHParamsRegisterOnce,
+ ssl3_WeakDHParamsRegisterShutdown);
+ if (status != PR_SUCCESS) {
+ PORT_SetError(gWeakDHParamsRegisterError);
+ return SECFailure;
+ }
+
+ status = PR_CallOnce(&gWeakDHParamsOnce, ssl3_CreateWeakDHParams);
+ if (status != PR_SUCCESS) {
+ PORT_SetError(gWeakDHParamsError);
+ return SECFailure;
+ }
+ }
+
+ if (!fd)
+ return SECSuccess;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_DHEGroupPrefSet", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ss->ssl3.dheWeakGroupEnabled = enabled;
+ return SECSuccess;
+}
+
+#include "dhe-param.c"
+
+const ssl3DHParams *
+ssl_GetDHEParams(const sslNamedGroupDef *groupDef)
+{
+ switch (groupDef->name) {
+ case ssl_grp_ffdhe_2048:
+ return &ff_dhe_2048_params;
+ case ssl_grp_ffdhe_3072:
+ return &ff_dhe_3072_params;
+ case ssl_grp_ffdhe_4096:
+ return &ff_dhe_4096_params;
+ case ssl_grp_ffdhe_6144:
+ return &ff_dhe_6144_params;
+ case ssl_grp_ffdhe_8192:
+ return &ff_dhe_8192_params;
+ case ssl_grp_ffdhe_custom:
+ PORT_Assert(gWeakDHParams);
+ return gWeakDHParams;
+ default:
+ PORT_Assert(0);
+ }
+ return NULL;
+}
+
+/* This validates dh_Ys against the group prime. */
+PRBool
+ssl_IsValidDHEShare(const SECItem *dh_p, const SECItem *dh_Ys)
+{
+ unsigned int size_p = SECKEY_BigIntegerBitLength(dh_p);
+ unsigned int size_y = SECKEY_BigIntegerBitLength(dh_Ys);
+ unsigned int commonPart;
+ int cmp;
+
+ if (dh_p->len == 0 || dh_Ys->len == 0) {
+ return PR_FALSE;
+ }
+ /* Check that the prime is at least odd. */
+ if ((dh_p->data[dh_p->len - 1] & 0x01) == 0) {
+ return PR_FALSE;
+ }
+ /* dh_Ys can't be 1, or bigger than dh_p. */
+ if (size_y <= 1 || size_y > size_p) {
+ return PR_FALSE;
+ }
+ /* If dh_Ys is shorter, then it's definitely smaller than p-1. */
+ if (size_y < size_p) {
+ return PR_TRUE;
+ }
+
+ /* Compare the common part of each, minus the final octet. */
+ commonPart = (size_p + 7) / 8;
+ PORT_Assert(commonPart <= dh_Ys->len);
+ PORT_Assert(commonPart <= dh_p->len);
+ cmp = PORT_Memcmp(dh_Ys->data + dh_Ys->len - commonPart,
+ dh_p->data + dh_p->len - commonPart, commonPart - 1);
+ if (cmp < 0) {
+ return PR_TRUE;
+ }
+ if (cmp > 0) {
+ return PR_FALSE;
+ }
+
+ /* The last octet of the prime is the only thing that is different and that
+ * has to be two greater than the share, otherwise we have Ys == p - 1,
+ * and that means small subgroups. */
+ if (dh_Ys->data[dh_Ys->len - 1] >= (dh_p->data[dh_p->len - 1] - 1)) {
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+/* Checks that the provided DH parameters match those in one of the named groups
+ * that we have enabled. The groups are defined in dhe-param.c and are those
+ * defined in Appendix A of draft-ietf-tls-negotiated-ff-dhe.
+ *
+ * |groupDef| and |dhParams| are optional outparams that identify the group and
+ * its parameters respectively (if this is successful). */
+SECStatus
+ssl_ValidateDHENamedGroup(sslSocket *ss,
+ const SECItem *dh_p,
+ const SECItem *dh_g,
+ const sslNamedGroupDef **groupDef,
+ const ssl3DHParams **dhParams)
+{
+ unsigned int i;
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ const ssl3DHParams *params;
+ if (!ss->namedGroupPreferences[i]) {
+ continue;
+ }
+ if (ss->namedGroupPreferences[i]->keaType != ssl_kea_dh) {
+ continue;
+ }
+
+ params = ssl_GetDHEParams(ss->namedGroupPreferences[i]);
+ PORT_Assert(params);
+ if (SECITEM_ItemsAreEqual(&params->prime, dh_p)) {
+ if (!SECITEM_ItemsAreEqual(&params->base, dh_g)) {
+ return SECFailure;
+ }
+ if (groupDef)
+ *groupDef = ss->namedGroupPreferences[i];
+ if (dhParams)
+ *dhParams = params;
+ return SECSuccess;
+ }
+ }
+
+ return SECFailure;
+}
+
+/* Ensure DH parameters have been selected. This just picks the first enabled
+ * FFDHE group in ssl_named_groups, or the weak one if it was enabled. */
+SECStatus
+ssl_SelectDHEGroup(sslSocket *ss, const sslNamedGroupDef **groupDef)
+{
+ unsigned int i;
+ static const sslNamedGroupDef weak_group_def = {
+ ssl_grp_ffdhe_custom, WEAK_DHE_SIZE, ssl_kea_dh,
+ SEC_OID_TLS_DHE_CUSTOM, PR_TRUE
+ };
+ PRInt32 minDH;
+ SECStatus rv;
+
+ // make sure we select a group consistent with our
+ // current policy policy
+ rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
+ if (rv != SECSuccess || minDH <= 0) {
+ minDH = DH_MIN_P_BITS;
+ }
+
+ /* Only select weak groups in TLS 1.2 and earlier, but not if the client has
+ * indicated that it supports an FFDHE named group. */
+ if (ss->ssl3.dheWeakGroupEnabled &&
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ !ss->xtnData.peerSupportsFfdheGroups &&
+ weak_group_def.bits >= minDH) {
+ *groupDef = &weak_group_def;
+ return SECSuccess;
+ }
+ if (ss->ssl3.dhePreferredGroup &&
+ ssl_NamedGroupEnabled(ss, ss->ssl3.dhePreferredGroup) &&
+ ss->ssl3.dhePreferredGroup->bits >= minDH) {
+ *groupDef = ss->ssl3.dhePreferredGroup;
+ return SECSuccess;
+ }
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ss->namedGroupPreferences[i] &&
+ ss->namedGroupPreferences[i]->keaType == ssl_kea_dh &&
+ ss->namedGroupPreferences[i]->bits >= minDH) {
+ *groupDef = ss->namedGroupPreferences[i];
+ return SECSuccess;
+ }
+ }
+
+ *groupDef = NULL;
+ PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
+ return SECFailure;
+}
+
+/* LOCKS ??? XXX */
+static PRFileDesc *
+ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant)
+{
+ sslSocket *ns = NULL;
+ PRStatus rv;
+ PRNetAddr addr;
+ SECStatus status = ssl_Init();
+
+ if (status != SECSuccess) {
+ return NULL;
+ }
+
+ if (model == NULL) {
+ /* Just create a default socket if we're given NULL for the model */
+ ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks), variant);
+ } else {
+ sslSocket *ss = ssl_FindSocket(model);
+ if (ss == NULL || ss->protocolVariant != variant) {
+ SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
+ SSL_GETPID(), model));
+ return NULL;
+ }
+ ns = ssl_DupSocket(ss);
+ }
+ if (ns == NULL)
+ return NULL;
+
+ rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
+ if (rv != PR_SUCCESS) {
+ ssl_FreeSocket(ns);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return NULL;
+ }
+#if defined(DEBUG) || defined(FORCE_PR_ASSERT)
+ {
+ sslSocket *ss = ssl_FindSocket(fd);
+ PORT_Assert(ss == ns);
+ }
+#endif
+ ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
+ return fd;
+}
+
+PRFileDesc *
+SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
+{
+ return ssl_ImportFD(model, fd, ssl_variant_stream);
+}
+
+PRFileDesc *
+DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd)
+{
+ return ssl_ImportFD(model, fd, ssl_variant_datagram);
+}
+
+/* SSL_SetNextProtoCallback is used to select an application protocol
+ * for ALPN. */
+SECStatus
+SSL_SetNextProtoCallback(PRFileDesc *fd, SSLNextProtoCallback callback,
+ void *arg)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoCallback", SSL_GETPID(),
+ fd));
+ return SECFailure;
+ }
+
+ ssl_GetSSL3HandshakeLock(ss);
+ ss->nextProtoCallback = callback;
+ ss->nextProtoArg = arg;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+/* ssl_NextProtoNegoCallback is set as an ALPN callback when
+ * SSL_SetNextProtoNego is used.
+ */
+static SECStatus
+ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
+ const unsigned char *protos, unsigned int protos_len,
+ unsigned char *protoOut, unsigned int *protoOutLen,
+ unsigned int protoMaxLen)
+{
+ unsigned int i, j;
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in ssl_NextProtoNegoCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ if (ss->opt.nextProtoNego.len == 0) {
+ SSL_DBG(("%d: SSL[%d]: ssl_NextProtoNegoCallback ALPN disabled",
+ SSL_GETPID(), fd));
+ SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
+ return SECFailure;
+ }
+
+ PORT_Assert(protoMaxLen <= 255);
+ if (protoMaxLen > 255) {
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ return SECFailure;
+ }
+
+ /* For each protocol in client preference, see if we support it. */
+ for (j = 0; j < ss->opt.nextProtoNego.len;) {
+ for (i = 0; i < protos_len;) {
+ if (protos[i] == ss->opt.nextProtoNego.data[j] &&
+ PORT_Memcmp(&protos[i + 1], &ss->opt.nextProtoNego.data[j + 1],
+ protos[i]) == 0) {
+ /* We found a match. */
+ const unsigned char *result = &protos[i];
+ memcpy(protoOut, result + 1, result[0]);
+ *protoOutLen = result[0];
+ return SECSuccess;
+ }
+ i += 1 + (unsigned int)protos[i];
+ }
+ j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
+ unsigned int length)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (length > 0 && ssl3_ValidateAppProtocol(data, length) != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* NPN required that the client's fallback protocol is first in the
+ * list. However, ALPN sends protocols in preference order. So move the
+ * first protocol to the end of the list. */
+ ssl_GetSSL3HandshakeLock(ss);
+ SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
+ if (length > 0) {
+ SECITEM_AllocItem(NULL, &ss->opt.nextProtoNego, length);
+ size_t firstLen = data[0] + 1;
+ /* firstLen <= length is ensured by ssl3_ValidateAppProtocol. */
+ PORT_Memcpy(ss->opt.nextProtoNego.data + (length - firstLen), data, firstLen);
+ PORT_Memcpy(ss->opt.nextProtoNego.data, data + firstLen, length - firstLen);
+ }
+ ssl_ReleaseSSL3HandshakeLock(ss);
+
+ return SSL_SetNextProtoCallback(fd, ssl_NextProtoNegoCallback, NULL);
+}
+
+SECStatus
+SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf,
+ unsigned int *bufLen, unsigned int bufLenMax)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNextProto", SSL_GETPID(),
+ fd));
+ return SECFailure;
+ }
+
+ if (!state || !buf || !bufLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ *state = ss->xtnData.nextProtoState;
+
+ if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
+ ss->xtnData.nextProto.data) {
+ if (ss->xtnData.nextProto.len > bufLenMax) {
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ return SECFailure;
+ }
+ PORT_Memcpy(buf, ss->xtnData.nextProto.data, ss->xtnData.nextProto.len);
+ *bufLen = ss->xtnData.nextProto.len;
+ } else {
+ *bufLen = 0;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_SetSRTPCiphers(PRFileDesc *fd,
+ const PRUint16 *ciphers,
+ unsigned int numCiphers)
+{
+ sslSocket *ss;
+ unsigned int i;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss || !IS_DTLS(ss)) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSRTPCiphers",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (numCiphers > MAX_DTLS_SRTP_CIPHER_SUITES) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss->ssl3.dtlsSRTPCipherCount = 0;
+ for (i = 0; i < numCiphers; i++) {
+ const PRUint16 *srtpCipher = srtpCiphers;
+
+ while (*srtpCipher) {
+ if (ciphers[i] == *srtpCipher)
+ break;
+ srtpCipher++;
+ }
+ if (*srtpCipher) {
+ ss->ssl3.dtlsSRTPCiphers[ss->ssl3.dtlsSRTPCipherCount++] =
+ ciphers[i];
+ } else {
+ SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher "
+ "suite specified: 0x%04hx",
+ SSL_GETPID(), fd,
+ ciphers[i]));
+ }
+ }
+
+ if (ss->ssl3.dtlsSRTPCipherCount == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetSRTPCipher",
+ SSL_GETPID(), fd));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (!ss->xtnData.dtlsSRTPCipherSuite) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ *cipher = ss->xtnData.dtlsSRTPCipherSuite;
+ return SECSuccess;
+}
+
+PRFileDesc *
+SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd)
+{
+ sslSocket *sm = NULL, *ss = NULL;
+ PRCList *cursor;
+ SECStatus rv;
+
+ if (model == NULL) {
+ PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
+ return NULL;
+ }
+ sm = ssl_FindSocket(model);
+ if (sm == NULL) {
+ SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ReconfigFD",
+ SSL_GETPID(), model));
+ return NULL;
+ }
+ ss = ssl_FindSocket(fd);
+ PORT_Assert(ss);
+ if (ss == NULL) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return NULL;
+ }
+
+ ss->opt = sm->opt;
+ ss->vrange = sm->vrange;
+ ss->now = sm->now;
+ ss->nowArg = sm->nowArg;
+ PORT_Memcpy(ss->cipherSuites, sm->cipherSuites, sizeof sm->cipherSuites);
+ PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, sm->ssl3.dtlsSRTPCiphers,
+ sizeof(PRUint16) * sm->ssl3.dtlsSRTPCipherCount);
+ ss->ssl3.dtlsSRTPCipherCount = sm->ssl3.dtlsSRTPCipherCount;
+ PORT_Memcpy(ss->ssl3.signatureSchemes, sm->ssl3.signatureSchemes,
+ sizeof(ss->ssl3.signatureSchemes[0]) *
+ sm->ssl3.signatureSchemeCount);
+ ss->ssl3.signatureSchemeCount = sm->ssl3.signatureSchemeCount;
+ ss->ssl3.downgradeCheckVersion = sm->ssl3.downgradeCheckVersion;
+
+ if (!ss->opt.useSecurity) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return NULL;
+ }
+ while (!PR_CLIST_IS_EMPTY(&ss->serverCerts)) {
+ cursor = PR_LIST_TAIL(&ss->serverCerts);
+ PR_REMOVE_LINK(cursor);
+ ssl_FreeServerCert((sslServerCert *)cursor);
+ }
+ for (cursor = PR_NEXT_LINK(&sm->serverCerts);
+ cursor != &sm->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *sc = ssl_CopyServerCert((sslServerCert *)cursor);
+ if (!sc)
+ return NULL;
+ PR_APPEND_LINK(&sc->link, &ss->serverCerts);
+ }
+
+ ssl_FreeEphemeralKeyPairs(ss);
+ for (cursor = PR_NEXT_LINK(&sm->ephemeralKeyPairs);
+ cursor != &sm->ephemeralKeyPairs;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslEphemeralKeyPair *mkp = (sslEphemeralKeyPair *)cursor;
+ sslEphemeralKeyPair *skp = ssl_CopyEphemeralKeyPair(mkp);
+ if (!skp)
+ return NULL;
+ PR_APPEND_LINK(&skp->link, &ss->ephemeralKeyPairs);
+ }
+
+ while (!PR_CLIST_IS_EMPTY(&ss->extensionHooks)) {
+ cursor = PR_LIST_TAIL(&ss->extensionHooks);
+ PR_REMOVE_LINK(cursor);
+ PORT_Free(cursor);
+ }
+ for (cursor = PR_NEXT_LINK(&sm->extensionHooks);
+ cursor != &sm->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslCustomExtensionHooks *hook = (sslCustomExtensionHooks *)cursor;
+ rv = SSL_InstallExtensionHooks(ss->fd, hook->type,
+ hook->writer, hook->writerArg,
+ hook->handler, hook->handlerArg);
+ if (rv != SECSuccess) {
+ return NULL;
+ }
+ }
+
+ PORT_Memcpy((void *)ss->namedGroupPreferences,
+ sm->namedGroupPreferences,
+ sizeof(ss->namedGroupPreferences));
+ ss->additionalShares = sm->additionalShares;
+
+ /* copy trust anchor names */
+ if (sm->ssl3.ca_list) {
+ if (ss->ssl3.ca_list) {
+ CERT_FreeDistNames(ss->ssl3.ca_list);
+ }
+ ss->ssl3.ca_list = CERT_DupDistNames(sm->ssl3.ca_list);
+ if (!ss->ssl3.ca_list) {
+ return NULL;
+ }
+ }
+
+ /* Copy ECH. */
+ tls13_DestroyEchConfigs(&ss->echConfigs);
+ SECKEY_DestroyPrivateKey(ss->echPrivKey);
+ SECKEY_DestroyPublicKey(ss->echPubKey);
+ rv = tls13_CopyEchConfigs(&sm->echConfigs, &ss->echConfigs);
+ if (rv != SECSuccess) {
+ return NULL;
+ }
+ if (sm->echPrivKey && sm->echPubKey) {
+ /* Might be client (no keys). */
+ ss->echPrivKey = SECKEY_CopyPrivateKey(sm->echPrivKey);
+ ss->echPubKey = SECKEY_CopyPublicKey(sm->echPubKey);
+ if (!ss->echPrivKey || !ss->echPubKey) {
+ return NULL;
+ }
+ }
+
+ /* Copy anti-replay context. */
+ if (ss->antiReplay) {
+ tls13_ReleaseAntiReplayContext(ss->antiReplay);
+ ss->antiReplay = NULL;
+ }
+ if (sm->antiReplay) {
+ ss->antiReplay = tls13_RefAntiReplayContext(sm->antiReplay);
+ PORT_Assert(ss->antiReplay);
+ if (!ss->antiReplay) {
+ return NULL;
+ }
+ }
+
+ tls13_ResetHandshakePsks(sm, &ss->ssl3.hs.psks);
+
+ if (sm->authCertificate)
+ ss->authCertificate = sm->authCertificate;
+ if (sm->authCertificateArg)
+ ss->authCertificateArg = sm->authCertificateArg;
+ if (sm->getClientAuthData)
+ ss->getClientAuthData = sm->getClientAuthData;
+ if (sm->getClientAuthDataArg)
+ ss->getClientAuthDataArg = sm->getClientAuthDataArg;
+ if (sm->sniSocketConfig)
+ ss->sniSocketConfig = sm->sniSocketConfig;
+ if (sm->sniSocketConfigArg)
+ ss->sniSocketConfigArg = sm->sniSocketConfigArg;
+ if (sm->alertReceivedCallback) {
+ ss->alertReceivedCallback = sm->alertReceivedCallback;
+ ss->alertReceivedCallbackArg = sm->alertReceivedCallbackArg;
+ }
+ if (sm->alertSentCallback) {
+ ss->alertSentCallback = sm->alertSentCallback;
+ ss->alertSentCallbackArg = sm->alertSentCallbackArg;
+ }
+ if (sm->handleBadCert)
+ ss->handleBadCert = sm->handleBadCert;
+ if (sm->badCertArg)
+ ss->badCertArg = sm->badCertArg;
+ if (sm->handshakeCallback)
+ ss->handshakeCallback = sm->handshakeCallback;
+ if (sm->handshakeCallbackData)
+ ss->handshakeCallbackData = sm->handshakeCallbackData;
+ if (sm->pkcs11PinArg)
+ ss->pkcs11PinArg = sm->pkcs11PinArg;
+
+ return fd;
+}
+
+SECStatus
+ssl3_GetEffectiveVersionPolicy(SSLProtocolVariant variant,
+ SSLVersionRange *effectivePolicy)
+{
+ SECStatus rv;
+ PRUint32 policyFlag;
+ PRInt32 minPolicy, maxPolicy;
+
+ if (variant == ssl_variant_stream) {
+ effectivePolicy->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM;
+ effectivePolicy->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
+ } else {
+ effectivePolicy->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM;
+ effectivePolicy->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
+ }
+
+ rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policyFlag);
+ if ((rv != SECSuccess) || !(policyFlag & NSS_USE_POLICY_IN_SSL)) {
+ /* Policy is not active, report library extents. */
+ return SECSuccess;
+ }
+
+ rv = NSS_OptionGet(VERSIONS_POLICY_MIN(variant), &minPolicy);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = NSS_OptionGet(VERSIONS_POLICY_MAX(variant), &maxPolicy);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (minPolicy > effectivePolicy->max ||
+ maxPolicy < effectivePolicy->min ||
+ minPolicy > maxPolicy) {
+ return SECFailure;
+ }
+ effectivePolicy->min = PR_MAX(effectivePolicy->min, minPolicy);
+ effectivePolicy->max = PR_MIN(effectivePolicy->max, maxPolicy);
+ return SECSuccess;
+}
+
+/*
+ * Assumes that rangeParam values are within the supported boundaries,
+ * but should contain all potentially allowed versions, even if they contain
+ * conflicting versions.
+ * Will return the overlap, or a NONE range if system policy is invalid.
+ */
+static SECStatus
+ssl3_CreateOverlapWithPolicy(SSLProtocolVariant protocolVariant,
+ SSLVersionRange *input,
+ SSLVersionRange *overlap)
+{
+ SECStatus rv;
+ SSLVersionRange effectivePolicyBoundary;
+ SSLVersionRange vrange;
+
+ PORT_Assert(input != NULL);
+
+ rv = ssl3_GetEffectiveVersionPolicy(protocolVariant,
+ &effectivePolicyBoundary);
+ if (rv == SECFailure) {
+ /* SECFailure means internal failure or invalid configuration. */
+ overlap->min = overlap->max = SSL_LIBRARY_VERSION_NONE;
+ return SECFailure;
+ }
+
+ vrange.min = PR_MAX(input->min, effectivePolicyBoundary.min);
+ vrange.max = PR_MIN(input->max, effectivePolicyBoundary.max);
+
+ if (vrange.max < vrange.min) {
+ /* there was no overlap, turn off range altogether */
+ overlap->min = overlap->max = SSL_LIBRARY_VERSION_NONE;
+ return SECFailure;
+ }
+
+ *overlap = vrange;
+ return SECSuccess;
+}
+
+static PRBool
+ssl_VersionIsSupportedByPolicy(SSLProtocolVariant protocolVariant,
+ SSL3ProtocolVersion version)
+{
+ SECStatus rv;
+ SSLVersionRange effectivePolicyBoundary;
+
+ rv = ssl3_GetEffectiveVersionPolicy(protocolVariant,
+ &effectivePolicyBoundary);
+ if (rv == SECFailure) {
+ /* SECFailure means internal failure or invalid configuration. */
+ return PR_FALSE;
+ }
+ return version >= effectivePolicyBoundary.min &&
+ version <= effectivePolicyBoundary.max;
+}
+
+/*
+ * This is called at SSL init time to constrain the existing range based
+ * on user supplied policy.
+ */
+SECStatus
+ssl3_ConstrainRangeByPolicy(void)
+{
+ /* We ignore failures in ssl3_CreateOverlapWithPolicy. Although an empty
+ * overlap disables all connectivity, it's an allowed state.
+ */
+ ssl3_CreateOverlapWithPolicy(ssl_variant_stream,
+ VERSIONS_DEFAULTS(ssl_variant_stream),
+ VERSIONS_DEFAULTS(ssl_variant_stream));
+ ssl3_CreateOverlapWithPolicy(ssl_variant_datagram,
+ VERSIONS_DEFAULTS(ssl_variant_datagram),
+ VERSIONS_DEFAULTS(ssl_variant_datagram));
+ return SECSuccess;
+}
+
+PRBool
+ssl3_VersionIsSupportedByCode(SSLProtocolVariant protocolVariant,
+ SSL3ProtocolVersion version)
+{
+ switch (protocolVariant) {
+ case ssl_variant_stream:
+ return (version >= SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM &&
+ version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
+ case ssl_variant_datagram:
+ return (version >= SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM &&
+ version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
+ }
+
+ /* Can't get here */
+ PORT_Assert(PR_FALSE);
+ return PR_FALSE;
+}
+
+PRBool
+ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
+ SSL3ProtocolVersion version)
+{
+ if (!ssl_VersionIsSupportedByPolicy(protocolVariant, version)) {
+ return PR_FALSE;
+ }
+ return ssl3_VersionIsSupportedByCode(protocolVariant, version);
+}
+
+const SECItem *
+SSL_PeerSignedCertTimestamps(PRFileDesc *fd)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerSignedCertTimestamps",
+ SSL_GETPID(), fd));
+ return NULL;
+ }
+
+ if (!ss->sec.ci.sid) {
+ PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+ return NULL;
+ }
+
+ return &ss->sec.ci.sid->u.ssl3.signedCertTimestamps;
+}
+
+SECStatus
+SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant,
+ SSLVersionRange *vrange)
+{
+ SECStatus rv;
+
+ if (!vrange) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ switch (protocolVariant) {
+ case ssl_variant_stream:
+ vrange->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM;
+ vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
+ /* We don't allow SSLv3 and TLSv1.3 together.
+ * However, don't check yet, apply the policy first.
+ * Because if the effective supported range doesn't use TLS 1.3,
+ * then we don't need to increase the minimum. */
+ break;
+ case ssl_variant_datagram:
+ vrange->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM;
+ vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ rv = ssl3_CreateOverlapWithPolicy(protocolVariant, vrange, vrange);
+ if (rv != SECSuccess) {
+ /* Library default and policy don't overlap. */
+ return rv;
+ }
+
+ /* We don't allow SSLv3 and TLSv1.3 together */
+ if (vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant,
+ SSLVersionRange *vrange)
+{
+ if ((protocolVariant != ssl_variant_stream &&
+ protocolVariant != ssl_variant_datagram) ||
+ !vrange) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ *vrange = *VERSIONS_DEFAULTS(protocolVariant);
+ return ssl3_CreateOverlapWithPolicy(protocolVariant, vrange, vrange);
+}
+
+static PRBool
+ssl3_HasConflictingSSLVersions(const SSLVersionRange *vrange)
+{
+ return (vrange->min <= SSL_LIBRARY_VERSION_3_0 &&
+ vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3);
+}
+
+static SECStatus
+ssl3_CheckRangeValidAndConstrainByPolicy(SSLProtocolVariant protocolVariant,
+ SSLVersionRange *vrange)
+{
+ SECStatus rv;
+
+ if (vrange->min > vrange->max ||
+ !ssl3_VersionIsSupportedByCode(protocolVariant, vrange->min) ||
+ !ssl3_VersionIsSupportedByCode(protocolVariant, vrange->max) ||
+ ssl3_HasConflictingSSLVersions(vrange)) {
+ PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
+ return SECFailure;
+ }
+
+ /* Try to adjust the received range using our policy.
+ * If there's overlap, we'll use the (possibly reduced) range.
+ * If there isn't overlap, it's failure. */
+
+ rv = ssl3_CreateOverlapWithPolicy(protocolVariant, vrange, vrange);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ /* We don't allow SSLv3 and TLSv1.3 together */
+ if (vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_VersionRangeSetDefault(SSLProtocolVariant protocolVariant,
+ const SSLVersionRange *vrange)
+{
+ SSLVersionRange constrainedRange;
+ SECStatus rv;
+
+ if (!vrange) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ constrainedRange = *vrange;
+ rv = ssl3_CheckRangeValidAndConstrainByPolicy(protocolVariant,
+ &constrainedRange);
+ if (rv != SECSuccess)
+ return rv;
+
+ *VERSIONS_DEFAULTS(protocolVariant) = constrainedRange;
+ return SECSuccess;
+}
+
+SECStatus
+SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeGet",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!vrange) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ *vrange = ss->vrange;
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return ssl3_CreateOverlapWithPolicy(ss->protocolVariant, vrange, vrange);
+}
+
+SECStatus
+SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange)
+{
+ SSLVersionRange constrainedRange;
+ sslSocket *ss;
+ SECStatus rv;
+
+ if (!vrange) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeSet",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ constrainedRange = *vrange;
+ rv = ssl3_CheckRangeValidAndConstrainByPolicy(ss->protocolVariant,
+ &constrainedRange);
+ if (rv != SECSuccess)
+ return rv;
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (ss->ssl3.downgradeCheckVersion &&
+ ss->vrange.max > ss->ssl3.downgradeCheckVersion) {
+ PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECFailure;
+ }
+
+ ss->vrange = constrainedRange;
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+SECStatus
+SSL_SetDowngradeCheckVersion(PRFileDesc *fd, PRUint16 version)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ SECStatus rv = SECFailure;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetDowngradeCheckVersion",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (version && !ssl3_VersionIsSupported(ss->protocolVariant, version)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (version && version < ss->vrange.max) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+ ss->ssl3.downgradeCheckVersion = version;
+ rv = SECSuccess;
+
+loser:
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+const SECItemArray *
+SSL_PeerStapledOCSPResponses(PRFileDesc *fd)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerStapledOCSPResponses",
+ SSL_GETPID(), fd));
+ return NULL;
+ }
+
+ if (!ss->sec.ci.sid) {
+ PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
+ return NULL;
+ }
+
+ return &ss->sec.ci.sid->peerCertStatus;
+}
+
+/************************************************************************/
+/* The following functions are the TOP LEVEL SSL functions.
+** They all get called through the NSPRIOMethods table below.
+*/
+
+static PRFileDesc *PR_CALLBACK
+ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
+{
+ sslSocket *ss;
+ sslSocket *ns = NULL;
+ PRFileDesc *newfd = NULL;
+ PRFileDesc *osfd;
+ PRStatus status;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
+ return NULL;
+ }
+
+ /* IF this is a listen socket, there shouldn't be any I/O going on */
+ SSL_LOCK_READER(ss);
+ SSL_LOCK_WRITER(ss);
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ ss->cTimeout = timeout;
+
+ osfd = ss->fd->lower;
+
+ /* First accept connection */
+ newfd = osfd->methods->accept(osfd, sockaddr, timeout);
+ if (newfd == NULL) {
+ SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
+ SSL_GETPID(), ss->fd, PORT_GetError()));
+ } else {
+ /* Create ssl module */
+ ns = ssl_DupSocket(ss);
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ SSL_UNLOCK_WRITER(ss);
+ SSL_UNLOCK_READER(ss); /* ss isn't used below here. */
+
+ if (ns == NULL)
+ goto loser;
+
+ /* push ssl module onto the new socket */
+ status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
+ if (status != PR_SUCCESS)
+ goto loser;
+
+ /* Now start server connection handshake with client.
+ ** Don't need locks here because nobody else has a reference to ns yet.
+ */
+ if (ns->opt.useSecurity) {
+ if (ns->opt.handshakeAsClient) {
+ ns->handshake = ssl_BeginClientHandshake;
+ ss->handshaking = sslHandshakingAsClient;
+ } else {
+ ns->handshake = ssl_BeginServerHandshake;
+ ss->handshaking = sslHandshakingAsServer;
+ }
+ }
+ ns->TCPconnected = 1;
+ return newfd;
+
+loser:
+ if (ns != NULL)
+ ssl_FreeSocket(ns);
+ if (newfd != NULL)
+ PR_Close(newfd);
+ return NULL;
+}
+
+static PRStatus PR_CALLBACK
+ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
+{
+ sslSocket *ss;
+ PRStatus rv;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+
+ /* IF this is a listen socket, there shouldn't be any I/O going on */
+ SSL_LOCK_READER(ss);
+ SSL_LOCK_WRITER(ss);
+
+ ss->cTimeout = timeout;
+ rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
+
+ SSL_UNLOCK_WRITER(ss);
+ SSL_UNLOCK_READER(ss);
+
+ return rv;
+}
+
+static PRStatus PR_CALLBACK
+ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
+{
+ sslSocket *ss = ssl_GetPrivate(fd);
+ PRStatus rv;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+ SSL_LOCK_READER(ss);
+ SSL_LOCK_WRITER(ss);
+
+ rv = (PRStatus)(*ss->ops->bind)(ss, addr);
+
+ SSL_UNLOCK_WRITER(ss);
+ SSL_UNLOCK_READER(ss);
+ return rv;
+}
+
+static PRStatus PR_CALLBACK
+ssl_Listen(PRFileDesc *fd, PRIntn backlog)
+{
+ sslSocket *ss = ssl_GetPrivate(fd);
+ PRStatus rv;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+ SSL_LOCK_READER(ss);
+ SSL_LOCK_WRITER(ss);
+
+ rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
+
+ SSL_UNLOCK_WRITER(ss);
+ SSL_UNLOCK_READER(ss);
+ return rv;
+}
+
+static PRStatus PR_CALLBACK
+ssl_Shutdown(PRFileDesc *fd, PRIntn how)
+{
+ sslSocket *ss = ssl_GetPrivate(fd);
+ PRStatus rv;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+ if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
+ SSL_LOCK_READER(ss);
+ }
+ if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
+ SSL_LOCK_WRITER(ss);
+ }
+
+ rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
+
+ if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
+ SSL_UNLOCK_WRITER(ss);
+ }
+ if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
+ SSL_UNLOCK_READER(ss);
+ }
+ return rv;
+}
+
+static PRStatus PR_CALLBACK
+ssl_Close(PRFileDesc *fd)
+{
+ sslSocket *ss;
+ PRStatus rv;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+
+ /* There must not be any I/O going on */
+ SSL_LOCK_READER(ss);
+ SSL_LOCK_WRITER(ss);
+
+ /* By the time this function returns,
+ ** ss is an invalid pointer, and the locks to which it points have
+ ** been unlocked and freed. So, this is the ONE PLACE in all of SSL
+ ** where the LOCK calls and the corresponding UNLOCK calls are not in
+ ** the same function scope. The unlock calls are in ssl_FreeSocket().
+ */
+ rv = (PRStatus)(*ss->ops->close)(ss);
+
+ return rv;
+}
+
+static int PR_CALLBACK
+ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
+ PRIntervalTime timeout)
+{
+ sslSocket *ss;
+ int rv;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ SSL_LOCK_READER(ss);
+ ss->rTimeout = timeout;
+ if (!ss->opt.fdx)
+ ss->wTimeout = timeout;
+ rv = (*ss->ops->recv)(ss, (unsigned char *)buf, len, flags);
+ SSL_UNLOCK_READER(ss);
+ return rv;
+}
+
+static int PR_CALLBACK
+ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
+ PRIntervalTime timeout)
+{
+ sslSocket *ss;
+ int rv;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ SSL_LOCK_WRITER(ss);
+ ss->wTimeout = timeout;
+ if (!ss->opt.fdx)
+ ss->rTimeout = timeout;
+ rv = (*ss->ops->send)(ss, (const unsigned char *)buf, len, flags);
+ SSL_UNLOCK_WRITER(ss);
+ return rv;
+}
+
+static int PR_CALLBACK
+ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
+{
+ sslSocket *ss;
+ int rv;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ SSL_LOCK_READER(ss);
+ ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
+ if (!ss->opt.fdx)
+ ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
+ rv = (*ss->ops->read)(ss, (unsigned char *)buf, len);
+ SSL_UNLOCK_READER(ss);
+ return rv;
+}
+
+static int PR_CALLBACK
+ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
+{
+ sslSocket *ss;
+ int rv;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ SSL_LOCK_WRITER(ss);
+ ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
+ if (!ss->opt.fdx)
+ ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
+ rv = (*ss->ops->write)(ss, (const unsigned char *)buf, len);
+ SSL_UNLOCK_WRITER(ss);
+ return rv;
+}
+
+static PRStatus PR_CALLBACK
+ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
+{
+ sslSocket *ss;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+ return (PRStatus)(*ss->ops->getpeername)(ss, addr);
+}
+
+/*
+*/
+SECStatus
+ssl_GetPeerInfo(sslSocket *ss)
+{
+ PRFileDesc *osfd;
+ int rv;
+ PRNetAddr sin;
+
+ osfd = ss->fd->lower;
+
+ PORT_Memset(&sin, 0, sizeof(sin));
+ rv = osfd->methods->getpeername(osfd, &sin);
+ if (rv < 0) {
+ return SECFailure;
+ }
+ ss->TCPconnected = 1;
+ if (sin.inet.family == PR_AF_INET) {
+ PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
+ ss->sec.ci.port = sin.inet.port;
+ } else if (sin.ipv6.family == PR_AF_INET6) {
+ ss->sec.ci.peer = sin.ipv6.ip;
+ ss->sec.ci.port = sin.ipv6.port;
+ } else {
+ PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+static PRStatus PR_CALLBACK
+ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
+{
+ sslSocket *ss;
+
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
+ return PR_FAILURE;
+ }
+ return (PRStatus)(*ss->ops->getsockname)(ss, name);
+}
+
+SECStatus
+SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID)
+{
+ sslSocket *ss;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSockPeerID",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (ss->peerID) {
+ PORT_Free(ss->peerID);
+ ss->peerID = NULL;
+ }
+ if (peerID)
+ ss->peerID = PORT_Strdup(peerID);
+ return (ss->peerID || !peerID) ? SECSuccess : SECFailure;
+}
+
+#define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
+
+static PRInt16 PR_CALLBACK
+ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
+{
+ sslSocket *ss;
+ PRInt16 new_flags = how_flags; /* should select on these flags. */
+ PRNetAddr addr;
+
+ *p_out_flags = 0;
+ ss = ssl_GetPrivate(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
+ SSL_GETPID(), fd));
+ return 0; /* don't poll on this socket */
+ }
+
+ if (ss->opt.useSecurity &&
+ ss->handshaking != sslHandshakingUndetermined &&
+ !ss->firstHsDone &&
+ (how_flags & PR_POLL_RW)) {
+ if (!ss->TCPconnected) {
+ ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
+ }
+ /* If it's not connected, then presumably the application is polling
+ ** on read or write appropriately, so don't change it.
+ */
+ if (ss->TCPconnected) {
+ if (!ss->handshakeBegun) {
+ /* If the handshake has not begun, poll on read or write
+ ** based on the local application's role in the handshake,
+ ** not based on what the application requested.
+ */
+ new_flags &= ~PR_POLL_RW;
+ if (ss->handshaking == sslHandshakingAsClient) {
+ new_flags |= PR_POLL_WRITE;
+ } else { /* handshaking as server */
+ new_flags |= PR_POLL_READ;
+ }
+ } else if (ss->lastWriteBlocked) {
+ /* First handshake is in progress */
+ if (new_flags & PR_POLL_READ) {
+ /* The caller is waiting for data to be received,
+ ** but the initial handshake is blocked on write, or the
+ ** client's first handshake record has not been written.
+ ** The code should select on write, not read.
+ */
+ new_flags &= ~PR_POLL_READ; /* don't select on read. */
+ new_flags |= PR_POLL_WRITE; /* do select on write. */
+ }
+ } else if (new_flags & PR_POLL_WRITE) {
+ /* The caller is trying to write, but the handshake is
+ ** blocked waiting for data to read, and the first
+ ** handshake has been sent. So do NOT to poll on write
+ ** unless we did false start or we are doing 0-RTT.
+ */
+ if (!(ss->ssl3.hs.canFalseStart ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)) {
+ new_flags &= ~PR_POLL_WRITE; /* don't select on write. */
+ }
+ new_flags |= PR_POLL_READ; /* do select on read. */
+ }
+ }
+ } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
+ *p_out_flags = PR_POLL_READ; /* it's ready already. */
+ return new_flags;
+ } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
+ (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
+ new_flags |= PR_POLL_WRITE; /* also select on write. */
+ }
+
+ if (ss->ssl3.hs.restartTarget != NULL) {
+ /* Read and write will block until the asynchronous callback completes
+ * (e.g. until SSL_AuthCertificateComplete is called), so don't tell
+ * the caller to poll the socket unless there is pending write data.
+ */
+ if (ss->lastWriteBlocked && ss->pendingBuf.len != 0) {
+ /* Ignore any newly-received data on the socket, but do wait for
+ * the socket to become writable again. Here, it is OK for an error
+ * to be detected, because our logic for sending pending write data
+ * will allow us to report the error to the caller without the risk
+ * of the application spinning.
+ */
+ new_flags &= (PR_POLL_WRITE | PR_POLL_EXCEPT);
+ } else {
+ /* Unfortunately, clearing new_flags will make it impossible for
+ * the application to detect errors that it would otherwise be
+ * able to detect with PR_POLL_EXCEPT, until the asynchronous
+ * callback completes. However, we must clear all the flags to
+ * prevent the application from spinning (alternating between
+ * calling PR_Poll that would return PR_POLL_EXCEPT, and send/recv
+ * which won't actually report the I/O error while we are waiting
+ * for the asynchronous callback to complete).
+ */
+ new_flags = 0;
+ }
+ }
+
+ SSL_TRC(20, ("%d: SSL[%d]: ssl_Poll flags %x -> %x",
+ SSL_GETPID(), fd, how_flags, new_flags));
+
+ if (new_flags && (fd->lower->methods->poll != NULL)) {
+ PRInt16 lower_out_flags = 0;
+ PRInt16 lower_new_flags;
+ lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
+ &lower_out_flags);
+ if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
+ PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
+ if (lower_out_flags & PR_POLL_READ)
+ out_flags |= PR_POLL_WRITE;
+ if (lower_out_flags & PR_POLL_WRITE)
+ out_flags |= PR_POLL_READ;
+ *p_out_flags = out_flags;
+ new_flags = how_flags;
+ } else {
+ *p_out_flags = lower_out_flags;
+ new_flags = lower_new_flags;
+ }
+ }
+
+ return new_flags;
+}
+
+static PRInt32 PR_CALLBACK
+ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
+ const void *headers, PRInt32 hlen,
+ PRTransmitFileFlags flags, PRIntervalTime timeout)
+{
+ PRSendFileData sfd;
+
+ sfd.fd = fd;
+ sfd.file_offset = 0;
+ sfd.file_nbytes = 0;
+ sfd.header = headers;
+ sfd.hlen = hlen;
+ sfd.trailer = NULL;
+ sfd.tlen = 0;
+
+ return sd->methods->sendfile(sd, &sfd, flags, timeout);
+}
+
+PRBool
+ssl_FdIsBlocking(PRFileDesc *fd)
+{
+ PRSocketOptionData opt;
+ PRStatus status;
+
+ opt.option = PR_SockOpt_Nonblocking;
+ opt.value.non_blocking = PR_FALSE;
+ status = PR_GetSocketOption(fd, &opt);
+ if (status != PR_SUCCESS)
+ return PR_FALSE;
+ return (PRBool)!opt.value.non_blocking;
+}
+
+PRBool
+ssl_SocketIsBlocking(sslSocket *ss)
+{
+ return ssl_FdIsBlocking(ss->fd);
+}
+
+PRInt32 sslFirstBufSize = 8 * 1024;
+PRInt32 sslCopyLimit = 1024;
+
+static PRInt32 PR_CALLBACK
+ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
+ PRIntervalTime timeout)
+{
+ PRInt32 i;
+ PRInt32 bufLen;
+ PRInt32 left;
+ PRInt32 rv;
+ PRInt32 sent = 0;
+ const PRInt32 first_len = sslFirstBufSize;
+ const PRInt32 limit = sslCopyLimit;
+ PRBool blocking;
+ PRIOVec myIov;
+ char buf[MAX_FRAGMENT_LENGTH];
+
+ if (vectors < 0) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return -1;
+ }
+ if (vectors > PR_MAX_IOVECTOR_SIZE) {
+ PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
+ return -1;
+ }
+ for (i = 0; i < vectors; i++) {
+ if (iov[i].iov_len < 0) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return -1;
+ }
+ }
+ blocking = ssl_FdIsBlocking(fd);
+
+#define K16 ((int)sizeof(buf))
+#define KILL_VECTORS \
+ while (vectors && !iov->iov_len) { \
+ ++iov; \
+ --vectors; \
+ }
+#define GET_VECTOR \
+ do { \
+ myIov = *iov++; \
+ --vectors; \
+ KILL_VECTORS \
+ } while (0)
+#define HANDLE_ERR(rv, len) \
+ if (rv != len) { \
+ if (rv < 0) { \
+ if (!blocking && \
+ (PR_GetError() == PR_WOULD_BLOCK_ERROR) && \
+ (sent > 0)) { \
+ return sent; \
+ } else { \
+ return -1; \
+ } \
+ } \
+ /* Only a nonblocking socket can have partial sends */ \
+ PR_ASSERT(!blocking); \
+ return sent + rv; \
+ }
+#define SEND(bfr, len) \
+ do { \
+ rv = ssl_Send(fd, bfr, len, 0, timeout); \
+ HANDLE_ERR(rv, len) \
+ sent += len; \
+ } while (0)
+
+ /* Make sure the first write is at least 8 KB, if possible. */
+ KILL_VECTORS
+ if (!vectors)
+ return ssl_Send(fd, 0, 0, 0, timeout);
+ GET_VECTOR;
+ if (!vectors) {
+ return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
+ }
+ if (myIov.iov_len < first_len) {
+ PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
+ bufLen = myIov.iov_len;
+ left = first_len - bufLen;
+ while (vectors && left) {
+ int toCopy;
+ GET_VECTOR;
+ toCopy = PR_MIN(left, myIov.iov_len);
+ PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
+ bufLen += toCopy;
+ left -= toCopy;
+ myIov.iov_base += toCopy;
+ myIov.iov_len -= toCopy;
+ }
+ SEND(buf, bufLen);
+ }
+
+ while (vectors || myIov.iov_len) {
+ PRInt32 addLen;
+ if (!myIov.iov_len) {
+ GET_VECTOR;
+ }
+ while (myIov.iov_len >= K16) {
+ SEND(myIov.iov_base, K16);
+ myIov.iov_base += K16;
+ myIov.iov_len -= K16;
+ }
+ if (!myIov.iov_len)
+ continue;
+
+ if (!vectors || myIov.iov_len > limit) {
+ addLen = 0;
+ } else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
+ /* Addlen is already computed. */;
+ } else if (vectors > 1 &&
+ iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
+ addLen = limit - myIov.iov_len;
+ } else
+ addLen = 0;
+
+ if (!addLen) {
+ SEND(myIov.iov_base, myIov.iov_len);
+ myIov.iov_len = 0;
+ continue;
+ }
+ PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
+ bufLen = myIov.iov_len;
+ do {
+ GET_VECTOR;
+ PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
+ myIov.iov_base += addLen;
+ myIov.iov_len -= addLen;
+ bufLen += addLen;
+
+ left = PR_MIN(limit, K16 - bufLen);
+ if (!vectors /* no more left */
+ || myIov.iov_len > 0 /* we didn't use that one all up */
+ || bufLen >= K16 /* it's full. */) {
+ addLen = 0;
+ } else if ((addLen = iov->iov_len % K16) <= left) {
+ /* Addlen is already computed. */;
+ } else if (vectors > 1 &&
+ iov[1].iov_len % K16 + addLen <= left + limit) {
+ addLen = left;
+ } else
+ addLen = 0;
+
+ } while (addLen);
+ SEND(buf, bufLen);
+ }
+ return sent;
+}
+
+/*
+ * These functions aren't implemented.
+ */
+
+static PRInt32 PR_CALLBACK
+ssl_Available(PRFileDesc *fd)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return SECFailure;
+}
+
+static PRInt64 PR_CALLBACK
+ssl_Available64(PRFileDesc *fd)
+{
+ PRInt64 res;
+
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ LL_I2L(res, -1L);
+ return res;
+}
+
+static PRStatus PR_CALLBACK
+ssl_FSync(PRFileDesc *fd)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return PR_FAILURE;
+}
+
+static PRInt32 PR_CALLBACK
+ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return SECFailure;
+}
+
+static PRInt64 PR_CALLBACK
+ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how)
+{
+ PRInt64 res;
+
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ LL_I2L(res, -1L);
+ return res;
+}
+
+static PRStatus PR_CALLBACK
+ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return PR_FAILURE;
+}
+
+static PRStatus PR_CALLBACK
+ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return PR_FAILURE;
+}
+
+static PRInt32 PR_CALLBACK
+ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
+ PRNetAddr *addr, PRIntervalTime timeout)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return SECFailure;
+}
+
+static PRInt32 PR_CALLBACK
+ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
+ const PRNetAddr *addr, PRIntervalTime timeout)
+{
+ PORT_Assert(0);
+ PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
+ return SECFailure;
+}
+
+static const PRIOMethods ssl_methods = {
+ PR_DESC_LAYERED,
+ ssl_Close, /* close */
+ ssl_Read, /* read */
+ ssl_Write, /* write */
+ ssl_Available, /* available */
+ ssl_Available64, /* available64 */
+ ssl_FSync, /* fsync */
+ ssl_Seek, /* seek */
+ ssl_Seek64, /* seek64 */
+ ssl_FileInfo, /* fileInfo */
+ ssl_FileInfo64, /* fileInfo64 */
+ ssl_WriteV, /* writev */
+ ssl_Connect, /* connect */
+ ssl_Accept, /* accept */
+ ssl_Bind, /* bind */
+ ssl_Listen, /* listen */
+ ssl_Shutdown, /* shutdown */
+ ssl_Recv, /* recv */
+ ssl_Send, /* send */
+ ssl_RecvFrom, /* recvfrom */
+ ssl_SendTo, /* sendto */
+ ssl_Poll, /* poll */
+ PR_EmulateAcceptRead, /* acceptread */
+ ssl_TransmitFile, /* transmitfile */
+ ssl_GetSockName, /* getsockname */
+ ssl_GetPeerName, /* getpeername */
+ NULL, /* getsockopt OBSOLETE */
+ NULL, /* setsockopt OBSOLETE */
+ NULL, /* getsocketoption */
+ NULL, /* setsocketoption */
+ PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/
+ NULL, /* reserved for future use */
+ NULL, /* reserved for future use */
+ NULL, /* reserved for future use */
+ NULL, /* reserved for future use */
+ NULL /* reserved for future use */
+};
+
+static PRIOMethods combined_methods;
+
+static void
+ssl_SetupIOMethods(void)
+{
+ PRIOMethods *new_methods = &combined_methods;
+ const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
+ const PRIOMethods *my_methods = &ssl_methods;
+
+ *new_methods = *nspr_methods;
+
+ new_methods->file_type = my_methods->file_type;
+ new_methods->close = my_methods->close;
+ new_methods->read = my_methods->read;
+ new_methods->write = my_methods->write;
+ new_methods->available = my_methods->available;
+ new_methods->available64 = my_methods->available64;
+ new_methods->fsync = my_methods->fsync;
+ new_methods->seek = my_methods->seek;
+ new_methods->seek64 = my_methods->seek64;
+ new_methods->fileInfo = my_methods->fileInfo;
+ new_methods->fileInfo64 = my_methods->fileInfo64;
+ new_methods->writev = my_methods->writev;
+ new_methods->connect = my_methods->connect;
+ new_methods->accept = my_methods->accept;
+ new_methods->bind = my_methods->bind;
+ new_methods->listen = my_methods->listen;
+ new_methods->shutdown = my_methods->shutdown;
+ new_methods->recv = my_methods->recv;
+ new_methods->send = my_methods->send;
+ new_methods->recvfrom = my_methods->recvfrom;
+ new_methods->sendto = my_methods->sendto;
+ new_methods->poll = my_methods->poll;
+ new_methods->acceptread = my_methods->acceptread;
+ new_methods->transmitfile = my_methods->transmitfile;
+ new_methods->getsockname = my_methods->getsockname;
+ new_methods->getpeername = my_methods->getpeername;
+ /* new_methods->getsocketoption = my_methods->getsocketoption; */
+ /* new_methods->setsocketoption = my_methods->setsocketoption; */
+ new_methods->sendfile = my_methods->sendfile;
+}
+
+static PRCallOnceType initIoLayerOnce;
+
+static PRStatus
+ssl_InitIOLayer(void)
+{
+ ssl_layer_id = PR_GetUniqueIdentity("SSL");
+ ssl_SetupIOMethods();
+ return PR_SUCCESS;
+}
+
+static PRStatus
+ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
+{
+ PRFileDesc *layer = NULL;
+ PRStatus status;
+
+ status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
+ if (status != PR_SUCCESS) {
+ goto loser;
+ }
+ if (ns == NULL) {
+ goto loser;
+ }
+ layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
+ if (layer == NULL)
+ goto loser;
+ layer->secret = (PRFilePrivate *)ns;
+
+ /* Here, "stack" points to the PRFileDesc on the top of the stack.
+ ** "layer" points to a new FD that is to be inserted into the stack.
+ ** If layer is being pushed onto the top of the stack, then
+ ** PR_PushIOLayer switches the contents of stack and layer, and then
+ ** puts stack on top of layer, so that after it is done, the top of
+ ** stack is the same "stack" as it was before, and layer is now the
+ ** FD for the former top of stack.
+ ** After this call, stack always points to the top PRFD on the stack.
+ ** If this function fails, the contents of stack and layer are as
+ ** they were before the call.
+ */
+ status = PR_PushIOLayer(stack, id, layer);
+ if (status != PR_SUCCESS)
+ goto loser;
+
+ ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
+ return PR_SUCCESS;
+
+loser:
+ if (layer) {
+ layer->dtor(layer); /* free layer */
+ }
+ return PR_FAILURE;
+}
+
+/* if this fails, caller must destroy socket. */
+static SECStatus
+ssl_MakeLocks(sslSocket *ss)
+{
+ ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
+ if (!ss->firstHandshakeLock)
+ goto loser;
+ ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL);
+ if (!ss->ssl3HandshakeLock)
+ goto loser;
+ ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
+ if (!ss->specLock)
+ goto loser;
+ ss->recvBufLock = PZ_NewMonitor(nssILockSSL);
+ if (!ss->recvBufLock)
+ goto loser;
+ ss->xmitBufLock = PZ_NewMonitor(nssILockSSL);
+ if (!ss->xmitBufLock)
+ goto loser;
+ ss->writerThread = NULL;
+ if (ssl_lock_readers) {
+ ss->recvLock = PZ_NewLock(nssILockSSL);
+ if (!ss->recvLock)
+ goto loser;
+ ss->sendLock = PZ_NewLock(nssILockSSL);
+ if (!ss->sendLock)
+ goto loser;
+ }
+ return SECSuccess;
+loser:
+ ssl_DestroyLocks(ss);
+ return SECFailure;
+}
+
+#if defined(XP_UNIX) || defined(XP_WIN32)
+#define NSS_HAVE_GETENV 1
+#endif
+
+#define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */
+
+static void
+ssl_SetDefaultsFromEnvironment(void)
+{
+#if defined(NSS_HAVE_GETENV)
+ static int firsttime = 1;
+
+ if (firsttime) {
+ char *ev;
+ firsttime = 0;
+#ifdef DEBUG
+ ssl_trace_iob = NULL;
+ ev = PR_GetEnvSecure("SSLDEBUGFILE");
+ if (ev && ev[0]) {
+ ssl_trace_iob = fopen(ev, "w");
+ }
+ if (!ssl_trace_iob) {
+ ssl_trace_iob = stderr;
+ }
+#ifdef TRACE
+ ev = PR_GetEnvSecure("SSLTRACE");
+ if (ev && ev[0]) {
+ ssl_trace = atoi(ev);
+ SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
+ }
+#endif /* TRACE */
+ ev = PR_GetEnvSecure("SSLDEBUG");
+ if (ev && ev[0]) {
+ ssl_debug = atoi(ev);
+ SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
+ }
+#endif /* DEBUG */
+#ifdef NSS_ALLOW_SSLKEYLOGFILE
+ ssl_keylog_iob = NULL;
+ ev = PR_GetEnvSecure("SSLKEYLOGFILE");
+ if (ev && ev[0]) {
+ ssl_keylog_iob = fopen(ev, "a");
+ if (!ssl_keylog_iob) {
+ SSL_TRACE(("SSL: failed to open key log file"));
+ } else {
+ if (ftell(ssl_keylog_iob) == 0) {
+ fputs("# SSL/TLS secrets log file, generated by NSS\n",
+ ssl_keylog_iob);
+ }
+ SSL_TRACE(("SSL: logging SSL/TLS secrets to %s", ev));
+ ssl_keylog_lock = PR_NewLock();
+ if (!ssl_keylog_lock) {
+ SSL_TRACE(("SSL: failed to create key log lock"));
+ fclose(ssl_keylog_iob);
+ ssl_keylog_iob = NULL;
+ }
+ }
+ }
+#endif
+ ev = PR_GetEnvSecure("SSLFORCELOCKS");
+ if (ev && ev[0] == '1') {
+ ssl_force_locks = PR_TRUE;
+ ssl_defaults.noLocks = 0;
+ strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED. ");
+ SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
+ }
+ ev = PR_GetEnvSecure("NSS_SSL_ENABLE_RENEGOTIATION");
+ if (ev) {
+ if (ev[0] == '1' || LOWER(ev[0]) == 'u')
+ ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED;
+ else if (ev[0] == '0' || LOWER(ev[0]) == 'n')
+ ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
+ else if (ev[0] == '2' || LOWER(ev[0]) == 'r')
+ ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN;
+ else if (ev[0] == '3' || LOWER(ev[0]) == 't')
+ ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_TRANSITIONAL;
+ SSL_TRACE(("SSL: enableRenegotiation set to %d",
+ ssl_defaults.enableRenegotiation));
+ }
+ ev = PR_GetEnvSecure("NSS_SSL_REQUIRE_SAFE_NEGOTIATION");
+ if (ev && ev[0] == '1') {
+ ssl_defaults.requireSafeNegotiation = PR_TRUE;
+ SSL_TRACE(("SSL: requireSafeNegotiation set to %d",
+ PR_TRUE));
+ }
+ ev = PR_GetEnvSecure("NSS_SSL_CBC_RANDOM_IV");
+ if (ev && ev[0] == '0') {
+ ssl_defaults.cbcRandomIV = PR_FALSE;
+ SSL_TRACE(("SSL: cbcRandomIV set to 0"));
+ }
+ }
+#endif /* NSS_HAVE_GETENV */
+}
+
+const sslNamedGroupDef *
+ssl_LookupNamedGroup(SSLNamedGroup group)
+{
+ unsigned int i;
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ssl_named_groups[i].name == group) {
+ return &ssl_named_groups[i];
+ }
+ }
+ return NULL;
+}
+
+PRBool
+ssl_NamedGroupEnabled(const sslSocket *ss, const sslNamedGroupDef *groupDef)
+{
+ unsigned int i;
+
+ if (!groupDef) {
+ return PR_FALSE;
+ }
+
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (ss->namedGroupPreferences[i] &&
+ ss->namedGroupPreferences[i] == groupDef) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+/* Returns a reference counted object that contains a key pair.
+ * Or NULL on failure. Initial ref count is 1.
+ * Uses the keys in the pair as input. Adopts the keys given.
+ */
+sslKeyPair *
+ssl_NewKeyPair(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey)
+{
+ sslKeyPair *pair;
+
+ if (!privKey || !pubKey) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return NULL;
+ }
+ pair = PORT_ZNew(sslKeyPair);
+ if (!pair)
+ return NULL; /* error code is set. */
+ pair->privKey = privKey;
+ pair->pubKey = pubKey;
+ pair->refCount = 1;
+ return pair; /* success */
+}
+
+sslKeyPair *
+ssl_GetKeyPairRef(sslKeyPair *keyPair)
+{
+ PR_ATOMIC_INCREMENT(&keyPair->refCount);
+ return keyPair;
+}
+
+void
+ssl_FreeKeyPair(sslKeyPair *keyPair)
+{
+ if (!keyPair) {
+ return;
+ }
+
+ PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount);
+ if (!newCount) {
+ SECKEY_DestroyPrivateKey(keyPair->privKey);
+ SECKEY_DestroyPublicKey(keyPair->pubKey);
+ PORT_Free(keyPair);
+ }
+}
+
+/* Ephemeral key handling. */
+sslEphemeralKeyPair *
+ssl_NewEphemeralKeyPair(const sslNamedGroupDef *group,
+ SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey)
+{
+ sslKeyPair *keys;
+ sslEphemeralKeyPair *pair;
+
+ if (!group) {
+ PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
+ return NULL;
+ }
+
+ keys = ssl_NewKeyPair(privKey, pubKey);
+ if (!keys) {
+ return NULL;
+ }
+
+ pair = PORT_ZNew(sslEphemeralKeyPair);
+ if (!pair) {
+ ssl_FreeKeyPair(keys);
+ return NULL; /* error already set */
+ }
+
+ PR_INIT_CLIST(&pair->link);
+ pair->group = group;
+ pair->keys = keys;
+
+ return pair;
+}
+
+sslEphemeralKeyPair *
+ssl_CopyEphemeralKeyPair(sslEphemeralKeyPair *keyPair)
+{
+ sslEphemeralKeyPair *pair;
+
+ pair = PORT_ZNew(sslEphemeralKeyPair);
+ if (!pair) {
+ return NULL; /* error already set */
+ }
+
+ PR_INIT_CLIST(&pair->link);
+ pair->group = keyPair->group;
+ pair->keys = ssl_GetKeyPairRef(keyPair->keys);
+
+ return pair;
+}
+
+void
+ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair *keyPair)
+{
+ if (!keyPair) {
+ return;
+ }
+
+ ssl_FreeKeyPair(keyPair->keys);
+ PR_REMOVE_LINK(&keyPair->link);
+ PORT_Free(keyPair);
+}
+
+PRBool
+ssl_HaveEphemeralKeyPair(const sslSocket *ss, const sslNamedGroupDef *groupDef)
+{
+ return ssl_LookupEphemeralKeyPair((sslSocket *)ss, groupDef) != NULL;
+}
+
+sslEphemeralKeyPair *
+ssl_LookupEphemeralKeyPair(sslSocket *ss, const sslNamedGroupDef *groupDef)
+{
+ PRCList *cursor;
+ for (cursor = PR_NEXT_LINK(&ss->ephemeralKeyPairs);
+ cursor != &ss->ephemeralKeyPairs;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor;
+ if (keyPair->group == groupDef) {
+ return keyPair;
+ }
+ }
+ return NULL;
+}
+
+void
+ssl_FreeEphemeralKeyPairs(sslSocket *ss)
+{
+ while (!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)) {
+ PRCList *cursor = PR_LIST_TAIL(&ss->ephemeralKeyPairs);
+ ssl_FreeEphemeralKeyPair((sslEphemeralKeyPair *)cursor);
+ }
+}
+
+PRTime
+ssl_Time(const sslSocket *ss)
+{
+ if (!ss->now) {
+ return PR_Now();
+ }
+ return ss->now(ss->nowArg);
+}
+
+/*
+** Create a newsocket structure for a file descriptor.
+*/
+static sslSocket *
+ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant)
+{
+ SECStatus rv;
+ sslSocket *ss;
+ int i;
+ ssl_SetDefaultsFromEnvironment();
+
+ if (ssl_force_locks)
+ makeLocks = PR_TRUE;
+
+ /* Make a new socket and get it ready */
+ ss = PORT_ZNew(sslSocket);
+ if (!ss) {
+ return NULL;
+ }
+ ss->opt = ssl_defaults;
+ if (protocolVariant == ssl_variant_datagram) {
+ ss->opt.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
+ }
+ ss->opt.useSocks = PR_FALSE;
+ ss->opt.noLocks = !makeLocks;
+ ss->vrange = *VERSIONS_DEFAULTS(protocolVariant);
+ ss->protocolVariant = protocolVariant;
+ /* Ignore overlap failures, because returning NULL would trigger assertion
+ * failures elsewhere. We don't want this scenario to be fatal, it's just
+ * a state where no SSL connectivity is possible. */
+ ssl3_CreateOverlapWithPolicy(ss->protocolVariant, &ss->vrange, &ss->vrange);
+ ss->peerID = NULL;
+ ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
+ ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
+ ss->cTimeout = PR_INTERVAL_NO_TIMEOUT;
+ ss->url = NULL;
+
+ PR_INIT_CLIST(&ss->serverCerts);
+ PR_INIT_CLIST(&ss->ephemeralKeyPairs);
+ PR_INIT_CLIST(&ss->extensionHooks);
+ PR_INIT_CLIST(&ss->echConfigs);
+
+ ss->dbHandle = CERT_GetDefaultCertDB();
+
+ /* Provide default implementation of hooks */
+ ss->authCertificate = SSL_AuthCertificate;
+ ss->authCertificateArg = (void *)ss->dbHandle;
+ ss->sniSocketConfig = NULL;
+ ss->sniSocketConfigArg = NULL;
+ ss->getClientAuthData = NULL;
+ ss->alertReceivedCallback = NULL;
+ ss->alertReceivedCallbackArg = NULL;
+ ss->alertSentCallback = NULL;
+ ss->alertSentCallbackArg = NULL;
+ ss->handleBadCert = NULL;
+ ss->badCertArg = NULL;
+ ss->pkcs11PinArg = NULL;
+
+ ssl_ChooseOps(ss);
+ ssl3_InitSocketPolicy(ss);
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ ss->namedGroupPreferences[i] = &ssl_named_groups[i];
+ }
+ ss->additionalShares = 0;
+ PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
+ PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
+ PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
+ PR_INIT_CLIST(&ss->ssl3.hs.bufferedEarlyData);
+ ssl3_InitExtensionData(&ss->xtnData, ss);
+ PR_INIT_CLIST(&ss->ssl3.hs.dtlsSentHandshake);
+ PR_INIT_CLIST(&ss->ssl3.hs.dtlsRcvdHandshake);
+ PR_INIT_CLIST(&ss->ssl3.hs.psks);
+ dtls_InitTimers(ss);
+
+ ss->echPrivKey = NULL;
+ ss->echPubKey = NULL;
+ ss->antiReplay = NULL;
+ ss->psk = NULL;
+
+ if (makeLocks) {
+ rv = ssl_MakeLocks(ss);
+ if (rv != SECSuccess)
+ goto loser;
+ }
+ rv = ssl_CreateSecurityInfo(ss);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = ssl3_InitGather(&ss->gs);
+ if (rv != SECSuccess)
+ goto loser;
+ rv = ssl3_InitState(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ return ss;
+
+loser:
+ ssl_DestroySocketContents(ss);
+ ssl_DestroyLocks(ss);
+ PORT_Free(ss);
+ return NULL;
+}
+
+/**
+ * DEPRECATED: Will always return false.
+ */
+SECStatus
+SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *srvPrivkey,
+ PRUint32 protocolmask, PRUint16 *ciphersuites, int nsuites,
+ PRBool *pcanbypass, void *pwArg)
+{
+ if (!pcanbypass) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ *pcanbypass = PR_FALSE;
+ return SECSuccess;
+}
+
+/* Functions that are truly experimental use EXP, functions that are no longer
+ * experimental use PUB.
+ *
+ * When initially defining a new API, add that API here using the EXP() macro
+ * and name the function with a SSLExp_ prefix. Define the experimental API as
+ * a macro in sslexp.h using the SSL_EXPERIMENTAL_API() macro defined there.
+ *
+ * Once an API is stable and proven, move the macro definition in sslexp.h to a
+ * proper function declaration in ssl.h. Keeping the function in this list
+ * ensures that code built against the release that contained the experimental
+ * API will continue to work; use PUB() to reference the public function.
+ */
+#define EXP(n) \
+ { \
+ "SSL_" #n, SSLExp_##n \
+ }
+#define PUB(n) \
+ { \
+ "SSL_" #n, SSL_##n \
+ }
+struct {
+ const char *const name;
+ void *function;
+} ssl_experimental_functions[] = {
+#ifndef SSL_DISABLE_EXPERIMENTAL_API
+ EXP(AddExternalPsk),
+ EXP(AddExternalPsk0Rtt),
+ EXP(AeadDecrypt),
+ EXP(AeadEncrypt),
+ EXP(CallExtensionWriterOnEchInner),
+ EXP(CipherSuiteOrderGet),
+ EXP(CipherSuiteOrderSet),
+ EXP(CreateAntiReplayContext),
+ EXP(CreateMask),
+ EXP(CreateMaskingContext),
+ EXP(CreateVariantMaskingContext),
+ EXP(DelegateCredential),
+ EXP(DestroyAead),
+ EXP(DestroyMaskingContext),
+ EXP(DestroyResumptionTokenInfo),
+ EXP(EnableTls13BackendEch),
+ EXP(EnableTls13GreaseEch),
+ EXP(SetTls13GreaseEchSize),
+ EXP(EncodeEchConfigId),
+ EXP(GetCurrentEpoch),
+ EXP(GetEchRetryConfigs),
+ EXP(GetExtensionSupport),
+ EXP(GetResumptionTokenInfo),
+ EXP(HelloRetryRequestCallback),
+ EXP(InstallExtensionHooks),
+ EXP(HkdfExtract),
+ EXP(HkdfExpandLabel),
+ EXP(HkdfExpandLabelWithMech),
+ EXP(HkdfVariantExpandLabel),
+ EXP(HkdfVariantExpandLabelWithMech),
+ EXP(KeyUpdate),
+ EXP(MakeAead),
+ EXP(MakeVariantAead),
+ EXP(RecordLayerData),
+ EXP(RecordLayerWriteCallback),
+ EXP(ReleaseAntiReplayContext),
+ EXP(RemoveEchConfigs),
+ EXP(RemoveExternalPsk),
+ EXP(SecretCallback),
+ EXP(SendCertificateRequest),
+ EXP(SendSessionTicket),
+ EXP(SetAntiReplayContext),
+ EXP(SetClientEchConfigs),
+ EXP(SetDtls13VersionWorkaround),
+ EXP(SetMaxEarlyDataSize),
+ EXP(SetResumptionTokenCallback),
+ EXP(SetResumptionToken),
+ EXP(SetServerEchConfigs),
+ EXP(SetTimeFunc),
+#endif
+ { "", NULL }
+};
+#undef EXP
+#undef PUB
+
+void *
+SSL_GetExperimentalAPI(const char *name)
+{
+ unsigned int i;
+ for (i = 0; i < PR_ARRAY_SIZE(ssl_experimental_functions); ++i) {
+ if (strcmp(name, ssl_experimental_functions[i].name) == 0) {
+ return ssl_experimental_functions[i].function;
+ }
+ }
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_EXPERIMENTAL_API);
+ return NULL;
+}
+
+void
+ssl_ClearPRCList(PRCList *list, void (*f)(void *))
+{
+ PRCList *cursor;
+
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ cursor = PR_LIST_TAIL(list);
+
+ PR_REMOVE_LINK(cursor);
+ if (f) {
+ f(cursor);
+ }
+ PORT_Free(cursor);
+ }
+}
+
+SECStatus
+SSLExp_EnableTls13GreaseEch(PRFileDesc *fd, PRBool enabled)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+ ss->opt.enableTls13GreaseEch = enabled;
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SetTls13GreaseEchSize(PRFileDesc *fd, PRUint8 size)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss || size == 0) {
+ return SECFailure;
+ }
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ ss->ssl3.hs.greaseEchSize = size;
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_EnableTls13BackendEch(PRFileDesc *fd, PRBool enabled)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+ ss->opt.enableTls13BackendEch = enabled;
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_CallExtensionWriterOnEchInner(PRFileDesc *fd, PRBool enabled)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+ ss->opt.callExtensionWriterOnEchInner = enabled;
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SetDtls13VersionWorkaround(PRFileDesc *fd, PRBool enabled)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+ ss->opt.enableDtls13VersionCompat = enabled;
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SetTimeFunc(PRFileDesc *fd, SSLTimeFunc f, void *arg)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTimeFunc",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+ ss->now = f;
+ ss->nowArg = arg;
+ return SECSuccess;
+}
+
+/* Experimental APIs for session cache handling. */
+
+SECStatus
+SSLExp_SetResumptionTokenCallback(PRFileDesc *fd,
+ SSLResumptionTokenCallback cb,
+ void *ctx)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetResumptionTokenCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+ ss->resumptionTokenCallback = cb;
+ ss->resumptionTokenContext = ctx;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SetResumptionToken(PRFileDesc *fd, const PRUint8 *token,
+ unsigned int len)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ sslSessionID *sid = NULL;
+
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetResumptionToken",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (ss->firstHsDone || ss->ssl3.hs.ws != idle_handshake ||
+ ss->sec.isServer || len == 0 || !token) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ // We override any previously set session.
+ if (ss->sec.ci.sid) {
+ ssl_FreeSID(ss->sec.ci.sid);
+ ss->sec.ci.sid = NULL;
+ }
+
+ PRINT_BUF(50, (ss, "incoming resumption token", token, len));
+
+ sid = ssl3_NewSessionID(ss, PR_FALSE);
+ if (!sid) {
+ goto loser;
+ }
+
+ /* Populate NewSessionTicket values */
+ SECStatus rv = ssl_DecodeResumptionToken(sid, token, len);
+ if (rv != SECSuccess) {
+ // If decoding fails, we assume the token is bad.
+ PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
+ goto loser;
+ }
+
+ // Make sure that the token is currently usable.
+ if (!ssl_IsResumptionTokenUsable(ss, sid)) {
+ PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
+ goto loser;
+ }
+
+ // Generate a new random session ID for this ticket.
+ rv = PK11_GenerateRandom(sid->u.ssl3.sessionID, SSL3_SESSIONID_BYTES);
+ if (rv != SECSuccess) {
+ goto loser; // Code set by PK11_GenerateRandom.
+ }
+ sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
+ /* Use the sid->cached as marker that this is from an external cache and
+ * we don't have to look up anything in the NSS internal cache. */
+ sid->cached = in_external_cache;
+ sid->lastAccessTime = ssl_Time(ss);
+
+ ss->sec.ci.sid = sid;
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECSuccess;
+
+loser:
+ ssl_FreeSID(sid);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_DestroyResumptionTokenInfo(SSLResumptionTokenInfo *token)
+{
+ if (!token) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if (token->peerCert) {
+ CERT_DestroyCertificate(token->peerCert);
+ }
+ PORT_Free(token->alpnSelection);
+ PORT_Memset(token, 0, token->length);
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_GetResumptionTokenInfo(const PRUint8 *tokenData, unsigned int tokenLen,
+ SSLResumptionTokenInfo *tokenOut, PRUintn len)
+{
+ if (!tokenData || !tokenOut || !tokenLen ||
+ len > sizeof(SSLResumptionTokenInfo)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ sslSessionID sid = { 0 };
+ SSLResumptionTokenInfo token;
+
+ /* Populate sid values */
+ if (ssl_DecodeResumptionToken(&sid, tokenData, tokenLen) != SECSuccess) {
+ // If decoding fails, we assume the token is bad.
+ PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
+ return SECFailure;
+ }
+
+ token.peerCert = CERT_DupCertificate(sid.peerCert);
+
+ token.alpnSelectionLen = sid.u.ssl3.alpnSelection.len;
+ token.alpnSelection = PORT_ZAlloc(token.alpnSelectionLen);
+ if (!token.alpnSelection) {
+ return SECFailure;
+ }
+ if (token.alpnSelectionLen > 0) {
+ PORT_Assert(sid.u.ssl3.alpnSelection.data);
+ PORT_Memcpy(token.alpnSelection, sid.u.ssl3.alpnSelection.data,
+ token.alpnSelectionLen);
+ }
+
+ if (sid.u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) {
+ token.maxEarlyDataSize =
+ sid.u.ssl3.locked.sessionTicket.max_early_data_size;
+ } else {
+ token.maxEarlyDataSize = 0;
+ }
+ token.expirationTime = sid.expirationTime;
+
+ token.length = PR_MIN(sizeof(SSLResumptionTokenInfo), len);
+ PORT_Memcpy(tokenOut, &token, token.length);
+
+ ssl_DestroySID(&sid, PR_FALSE);
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/sslspec.c b/security/nss/lib/ssl/sslspec.c
new file mode 100644
index 0000000000..c5bedad7a6
--- /dev/null
+++ b/security/nss/lib/ssl/sslspec.c
@@ -0,0 +1,277 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * Handling of cipher specs.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ssl.h"
+#include "sslexp.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "pk11func.h"
+#include "secitem.h"
+
+#include "sslimpl.h"
+
+/* Record protection algorithms, indexed by SSL3BulkCipher.
+ *
+ * The |max_records| field (|mr| below) is set to a number that is higher than
+ * recommended in some literature (esp. TLS 1.3) because we currently abort the
+ * connection when this limit is reached and we want to ensure that we only
+ * rarely hit this limit. See bug 1268745 for details.
+ */
+#define MR_MAX RECORD_SEQ_MAX /* 2^48-1 */
+#define MR_128 (0x5aULL << 28) /* For AES and similar. */
+#define MR_LOW (1ULL << 20) /* For weak ciphers. */
+/* clang-format off */
+static const ssl3BulkCipherDef ssl_bulk_cipher_defs[] = {
+ /* |--------- Lengths ---------| */
+ /* cipher calg : s : */
+ /* : e b n */
+ /* oid short_name mr : c l o */
+ /* k r o t n */
+ /* e e i c a c */
+ /* y t type v k g e */
+ {cipher_null, ssl_calg_null, 0, 0, type_stream, 0, 0, 0, 0,
+ SEC_OID_NULL_CIPHER, "NULL", MR_MAX},
+ {cipher_rc4, ssl_calg_rc4, 16,16, type_stream, 0, 0, 0, 0,
+ SEC_OID_RC4, "RC4", MR_LOW},
+ {cipher_des, ssl_calg_des, 8, 8, type_block, 8, 8, 0, 0,
+ SEC_OID_DES_CBC, "DES-CBC", MR_LOW},
+ {cipher_3des, ssl_calg_3des, 24,24, type_block, 8, 8, 0, 0,
+ SEC_OID_DES_EDE3_CBC, "3DES-EDE-CBC", MR_LOW},
+ {cipher_aes_128, ssl_calg_aes, 16,16, type_block, 16,16, 0, 0,
+ SEC_OID_AES_128_CBC, "AES-128", MR_128},
+ {cipher_aes_256, ssl_calg_aes, 32,32, type_block, 16,16, 0, 0,
+ SEC_OID_AES_256_CBC, "AES-256", MR_128},
+ {cipher_camellia_128, ssl_calg_camellia, 16,16, type_block, 16,16, 0, 0,
+ SEC_OID_CAMELLIA_128_CBC, "Camellia-128", MR_128},
+ {cipher_camellia_256, ssl_calg_camellia, 32,32, type_block, 16,16, 0, 0,
+ SEC_OID_CAMELLIA_256_CBC, "Camellia-256", MR_128},
+ {cipher_seed, ssl_calg_seed, 16,16, type_block, 16,16, 0, 0,
+ SEC_OID_SEED_CBC, "SEED-CBC", MR_128},
+ {cipher_aes_128_gcm, ssl_calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8,
+ SEC_OID_AES_128_GCM, "AES-128-GCM", MR_128},
+ {cipher_aes_256_gcm, ssl_calg_aes_gcm, 32,32, type_aead, 4, 0,16, 8,
+ SEC_OID_AES_256_GCM, "AES-256-GCM", MR_128},
+ {cipher_chacha20, ssl_calg_chacha20, 32,32, type_aead, 12, 0,16, 0,
+ SEC_OID_CHACHA20_POLY1305, "ChaCha20-Poly1305", MR_MAX},
+ {cipher_missing, ssl_calg_null, 0, 0, type_stream, 0, 0, 0, 0,
+ SEC_OID_UNKNOWN, "missing", 0U},
+};
+/* clang-format on */
+
+const ssl3BulkCipherDef *
+ssl_GetBulkCipherDef(const ssl3CipherSuiteDef *suiteDef)
+{
+ SSL3BulkCipher bulkCipher = suiteDef->bulk_cipher_alg;
+ PORT_Assert(bulkCipher < PR_ARRAY_SIZE(ssl_bulk_cipher_defs));
+ PORT_Assert(ssl_bulk_cipher_defs[bulkCipher].cipher == bulkCipher);
+ return &ssl_bulk_cipher_defs[bulkCipher];
+}
+
+/* indexed by SSL3MACAlgorithm */
+static const ssl3MACDef ssl_mac_defs[] = {
+ /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
+ /* mac mmech pad_size mac_size */
+ { ssl_mac_null, CKM_INVALID_MECHANISM, 0, 0, 0 },
+ { ssl_mac_md5, CKM_SSL3_MD5_MAC, 48, MD5_LENGTH, SEC_OID_HMAC_MD5 },
+ { ssl_mac_sha, CKM_SSL3_SHA1_MAC, 40, SHA1_LENGTH, SEC_OID_HMAC_SHA1 },
+ { ssl_hmac_md5, CKM_MD5_HMAC, 0, MD5_LENGTH, SEC_OID_HMAC_MD5 },
+ { ssl_hmac_sha, CKM_SHA_1_HMAC, 0, SHA1_LENGTH, SEC_OID_HMAC_SHA1 },
+ { ssl_hmac_sha256, CKM_SHA256_HMAC, 0, SHA256_LENGTH, SEC_OID_HMAC_SHA256 },
+ { ssl_mac_aead, CKM_INVALID_MECHANISM, 0, 0, 0 },
+ { ssl_hmac_sha384, CKM_SHA384_HMAC, 0, SHA384_LENGTH, SEC_OID_HMAC_SHA384 }
+};
+
+const ssl3MACDef *
+ssl_GetMacDefByAlg(SSL3MACAlgorithm mac)
+{
+ /* Cast here for clang: https://bugs.llvm.org/show_bug.cgi?id=16154 */
+ PORT_Assert((size_t)mac < PR_ARRAY_SIZE(ssl_mac_defs));
+ PORT_Assert(ssl_mac_defs[mac].mac == mac);
+ return &ssl_mac_defs[mac];
+}
+
+const ssl3MACDef *
+ssl_GetMacDef(const sslSocket *ss, const ssl3CipherSuiteDef *suiteDef)
+{
+ SSL3MACAlgorithm mac = suiteDef->mac_alg;
+ if (ss->version > SSL_LIBRARY_VERSION_3_0) {
+ switch (mac) {
+ case ssl_mac_md5:
+ mac = ssl_hmac_md5;
+ break;
+ case ssl_mac_sha:
+ mac = ssl_hmac_sha;
+ break;
+ default:
+ break;
+ }
+ }
+ return ssl_GetMacDefByAlg(mac);
+}
+
+ssl3CipherSpec *
+ssl_FindCipherSpecByEpoch(sslSocket *ss, SSLSecretDirection direction,
+ DTLSEpoch epoch)
+{
+ PRCList *cur_p;
+ for (cur_p = PR_LIST_HEAD(&ss->ssl3.hs.cipherSpecs);
+ cur_p != &ss->ssl3.hs.cipherSpecs;
+ cur_p = PR_NEXT_LINK(cur_p)) {
+ ssl3CipherSpec *spec = (ssl3CipherSpec *)cur_p;
+
+ if (spec->epoch != epoch) {
+ continue;
+ }
+ if (direction != spec->direction) {
+ continue;
+ }
+ return spec;
+ }
+ return NULL;
+}
+
+ssl3CipherSpec *
+ssl_CreateCipherSpec(sslSocket *ss, SSLSecretDirection direction)
+{
+ ssl3CipherSpec *spec = PORT_ZNew(ssl3CipherSpec);
+ if (!spec) {
+ return NULL;
+ }
+ spec->refCt = 1;
+ spec->version = ss->version;
+ spec->direction = direction;
+ spec->recordSizeLimit = MAX_FRAGMENT_LENGTH;
+ SSL_TRC(10, ("%d: SSL[%d]: new %s spec %d ct=%d",
+ SSL_GETPID(), ss->fd, SPEC_DIR(spec), spec,
+ spec->refCt));
+ return spec;
+}
+
+void
+ssl_SaveCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ PR_APPEND_LINK(&spec->link, &ss->ssl3.hs.cipherSpecs);
+}
+
+/* Called from ssl3_InitState. */
+/* Caller must hold the SpecWriteLock. */
+SECStatus
+ssl_SetupNullCipherSpec(sslSocket *ss, SSLSecretDirection dir)
+{
+ ssl3CipherSpec *spec;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
+
+ spec = ssl_CreateCipherSpec(ss, dir);
+ if (!spec) {
+ return SECFailure;
+ }
+
+ /* Set default versions. This value will be used to generate and send
+ * alerts if a version is not negotiated. These values are overridden when
+ * sending a ClientHello and when a version is negotiated. */
+ spec->version = SSL_LIBRARY_VERSION_TLS_1_0;
+ spec->recordVersion = IS_DTLS(ss)
+ ? SSL_LIBRARY_VERSION_DTLS_1_0_WIRE
+ : SSL_LIBRARY_VERSION_TLS_1_0;
+ spec->cipherDef = &ssl_bulk_cipher_defs[cipher_null];
+ PORT_Assert(spec->cipherDef->cipher == cipher_null);
+ spec->macDef = &ssl_mac_defs[ssl_mac_null];
+ PORT_Assert(spec->macDef->mac == ssl_mac_null);
+ spec->cipher = Null_Cipher;
+
+ spec->phase = "cleartext";
+ dtls_InitRecvdRecords(&spec->recvdRecords);
+
+ ssl_SaveCipherSpec(ss, spec);
+ if (dir == ssl_secret_read) {
+ ss->ssl3.crSpec = spec;
+ } else {
+ ss->ssl3.cwSpec = spec;
+ }
+ return SECSuccess;
+}
+
+void
+ssl_CipherSpecAddRef(ssl3CipherSpec *spec)
+{
+ ++spec->refCt;
+ SSL_TRC(10, ("%d: SSL[-]: Increment ref ct for %s spec %d. new ct = %d",
+ SSL_GETPID(), SPEC_DIR(spec), spec, spec->refCt));
+}
+
+void
+ssl_DestroyKeyMaterial(ssl3KeyMaterial *keyMaterial)
+{
+ PK11_FreeSymKey(keyMaterial->key);
+ PK11_FreeSymKey(keyMaterial->macKey);
+ if (keyMaterial->macContext != NULL) {
+ PK11_DestroyContext(keyMaterial->macContext, PR_TRUE);
+ }
+}
+
+static void
+ssl_FreeCipherSpec(ssl3CipherSpec *spec)
+{
+ SSL_TRC(10, ("%d: SSL[-]: Freeing %s spec %d. epoch=%d",
+ SSL_GETPID(), SPEC_DIR(spec), spec, spec->epoch));
+
+ PR_REMOVE_LINK(&spec->link);
+
+ /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
+ if (spec->cipherContext) {
+ PK11_DestroyContext(spec->cipherContext, PR_TRUE);
+ }
+ PK11_FreeSymKey(spec->masterSecret);
+ ssl_DestroyKeyMaterial(&spec->keyMaterial);
+ ssl_DestroyMaskingContextInner(spec->maskContext);
+
+ PORT_ZFree(spec, sizeof(*spec));
+}
+
+/* This function is never called on a spec which is on the
+ * cipherSpecs list. */
+void
+ssl_CipherSpecRelease(ssl3CipherSpec *spec)
+{
+ if (!spec) {
+ return;
+ }
+
+ PORT_Assert(spec->refCt > 0);
+ --spec->refCt;
+ SSL_TRC(10, ("%d: SSL[-]: decrement refct for %s spec %d. epoch=%d new ct = %d",
+ SSL_GETPID(), SPEC_DIR(spec), spec, spec->epoch, spec->refCt));
+ if (!spec->refCt) {
+ ssl_FreeCipherSpec(spec);
+ }
+}
+
+void
+ssl_DestroyCipherSpecs(PRCList *list)
+{
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ ssl3CipherSpec *spec = (ssl3CipherSpec *)PR_LIST_TAIL(list);
+ ssl_FreeCipherSpec(spec);
+ }
+}
+
+void
+ssl_CipherSpecReleaseByEpoch(sslSocket *ss, SSLSecretDirection dir,
+ DTLSEpoch epoch)
+{
+ ssl3CipherSpec *spec;
+ SSL_TRC(10, ("%d: SSL[%d]: releasing %s cipher spec for epoch %d",
+ SSL_GETPID(), ss->fd,
+ (dir == ssl_secret_read) ? "read" : "write", epoch));
+
+ spec = ssl_FindCipherSpecByEpoch(ss, dir, epoch);
+ if (spec) {
+ ssl_CipherSpecRelease(spec);
+ }
+}
diff --git a/security/nss/lib/ssl/sslspec.h b/security/nss/lib/ssl/sslspec.h
new file mode 100644
index 0000000000..061d888aed
--- /dev/null
+++ b/security/nss/lib/ssl/sslspec.h
@@ -0,0 +1,200 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslspec_h_
+#define __sslspec_h_
+
+#include "sslexp.h"
+#include "prclist.h"
+
+typedef enum {
+ TrafficKeyClearText = 0,
+ TrafficKeyEarlyApplicationData = 1,
+ TrafficKeyHandshake = 2,
+ TrafficKeyApplicationData = 3
+} TrafficKeyType;
+
+#define SPEC_DIR(spec) \
+ ((spec->direction == ssl_secret_read) ? "read" : "write")
+
+typedef struct ssl3CipherSpecStr ssl3CipherSpec;
+typedef struct ssl3BulkCipherDefStr ssl3BulkCipherDef;
+typedef struct ssl3MACDefStr ssl3MACDef;
+typedef struct ssl3CipherSuiteDefStr ssl3CipherSuiteDef;
+typedef PRUint64 sslSequenceNumber;
+typedef PRUint16 DTLSEpoch;
+
+/* The SSL bulk cipher definition */
+typedef enum {
+ cipher_null,
+ cipher_rc4,
+ cipher_des,
+ cipher_3des,
+ cipher_aes_128,
+ cipher_aes_256,
+ cipher_camellia_128,
+ cipher_camellia_256,
+ cipher_seed,
+ cipher_aes_128_gcm,
+ cipher_aes_256_gcm,
+ cipher_chacha20,
+ cipher_missing /* reserved for no such supported cipher */
+ /* This enum must match ssl3_cipherName[] in ssl3con.c. */
+} SSL3BulkCipher;
+
+typedef enum {
+ type_stream,
+ type_block,
+ type_aead
+} CipherType;
+
+/*
+** There are tables of these, all const.
+*/
+struct ssl3BulkCipherDefStr {
+ SSL3BulkCipher cipher;
+ SSLCipherAlgorithm calg;
+ unsigned int key_size;
+ unsigned int secret_key_size;
+ CipherType type;
+ unsigned int iv_size;
+ unsigned int block_size;
+ unsigned int tag_size; /* for AEAD ciphers. */
+ unsigned int explicit_nonce_size; /* for AEAD ciphers. */
+ SECOidTag oid;
+ const char *short_name;
+ /* The maximum number of records that can be sent/received with the same
+ * symmetric key before the connection will be terminated. */
+ PRUint64 max_records;
+};
+
+/* to make some of these old enums public without namespace pollution,
+** it was necessary to prepend ssl_ to the names.
+** These #defines preserve compatibility with the old code here in libssl.
+*/
+typedef SSLMACAlgorithm SSL3MACAlgorithm;
+
+/*
+ * There are tables of these, all const.
+ */
+struct ssl3MACDefStr {
+ SSL3MACAlgorithm mac;
+ CK_MECHANISM_TYPE mmech;
+ int pad_size;
+ int mac_size;
+ SECOidTag oid;
+};
+
+#define MAX_IV_LENGTH 24
+
+typedef struct {
+ PK11SymKey *key;
+ PK11SymKey *macKey;
+ PK11Context *macContext;
+ PRUint8 iv[MAX_IV_LENGTH];
+} ssl3KeyMaterial;
+
+typedef SECStatus (*SSLCipher)(void *context,
+ unsigned char *out,
+ unsigned int *outlen,
+ unsigned int maxout,
+ const unsigned char *in,
+ unsigned int inlen);
+typedef SECStatus (*SSLAEADCipher)(PK11Context *context,
+ CK_GENERATOR_FUNCTION ivGen,
+ unsigned int fixedbits,
+ unsigned char *iv, unsigned int ivlen,
+ const unsigned char *aad,
+ unsigned int aadlen,
+ unsigned char *out, unsigned int *outlen,
+ unsigned int maxout, unsigned char *tag,
+ unsigned int taglen,
+ const unsigned char *in, unsigned int inlen);
+
+/* The DTLS anti-replay window in number of packets. Defined here because we
+ * need it in the cipher spec. Note that this is a ring buffer but left and
+ * right represent the true window, with modular arithmetic used to map them
+ * onto the buffer.
+ */
+#define DTLS_RECVD_RECORDS_WINDOW 1024
+#define RECORD_SEQ_MASK ((1ULL << 48) - 1)
+#define RECORD_SEQ_MAX RECORD_SEQ_MASK
+PR_STATIC_ASSERT(DTLS_RECVD_RECORDS_WINDOW % 8 == 0);
+
+typedef struct DTLSRecvdRecordsStr {
+ unsigned char data[DTLS_RECVD_RECORDS_WINDOW / 8];
+ sslSequenceNumber left;
+ sslSequenceNumber right;
+} DTLSRecvdRecords;
+
+/*
+ * These are the "specs" used for reading and writing records. Access to the
+ * pointers to these specs, and all the specs' contents (direct and indirect) is
+ * protected by the reader/writer lock ss->specLock.
+ */
+struct ssl3CipherSpecStr {
+ PRCList link;
+ PRUint8 refCt;
+
+ SSLSecretDirection direction;
+ SSL3ProtocolVersion version;
+ SSL3ProtocolVersion recordVersion;
+
+ const ssl3BulkCipherDef *cipherDef;
+ const ssl3MACDef *macDef;
+
+ SSLCipher cipher;
+ void *cipherContext;
+
+ PK11SymKey *masterSecret;
+ ssl3KeyMaterial keyMaterial;
+
+ DTLSEpoch epoch;
+ const char *phase;
+
+ /* The next sequence number to be sent or received. */
+ sslSequenceNumber nextSeqNum;
+ DTLSRecvdRecords recvdRecords;
+
+ /* The number of 0-RTT bytes that can be sent or received in TLS 1.3. This
+ * will be zero for everything but 0-RTT. */
+ PRUint32 earlyDataRemaining;
+ /* The maximum plaintext length. This differs from the configured or
+ * negotiated value for TLS 1.3; it is reduced by one to account for the
+ * content type octet. */
+ PRUint16 recordSizeLimit;
+
+ /* DTLS 1.3: Sequence number masking context. */
+ SSLMaskingContext *maskContext;
+
+ /* DTLS 1.3: Count of decryption failures for the given key. */
+ PRUint64 deprotectionFailures;
+};
+
+typedef void (*sslCipherSpecChangedFunc)(void *arg,
+ PRBool sending,
+ ssl3CipherSpec *newSpec);
+
+const ssl3BulkCipherDef *ssl_GetBulkCipherDef(const ssl3CipherSuiteDef *cipher_def);
+const ssl3MACDef *ssl_GetMacDefByAlg(SSL3MACAlgorithm mac);
+const ssl3MACDef *ssl_GetMacDef(const sslSocket *ss, const ssl3CipherSuiteDef *suiteDef);
+
+ssl3CipherSpec *ssl_CreateCipherSpec(sslSocket *ss, SSLSecretDirection direction);
+void ssl_SaveCipherSpec(sslSocket *ss, ssl3CipherSpec *spec);
+void ssl_CipherSpecAddRef(ssl3CipherSpec *spec);
+void ssl_CipherSpecRelease(ssl3CipherSpec *spec);
+void ssl_DestroyCipherSpecs(PRCList *list);
+SECStatus ssl_SetupNullCipherSpec(sslSocket *ss, SSLSecretDirection dir);
+
+ssl3CipherSpec *ssl_FindCipherSpecByEpoch(sslSocket *ss,
+ SSLSecretDirection direction,
+ DTLSEpoch epoch);
+void ssl_CipherSpecReleaseByEpoch(sslSocket *ss, SSLSecretDirection direction,
+ DTLSEpoch epoch);
+
+#endif /* __sslspec_h_ */
diff --git a/security/nss/lib/ssl/sslt.h b/security/nss/lib/ssl/sslt.h
new file mode 100644
index 0000000000..d12b3c91ff
--- /dev/null
+++ b/security/nss/lib/ssl/sslt.h
@@ -0,0 +1,583 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file contains prototypes for the public SSL functions.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __sslt_h_
+#define __sslt_h_
+
+#include "certt.h"
+#include "keyhi.h"
+#include "prtypes.h"
+#include "secitem.h"
+
+typedef enum {
+ ssl_hs_hello_request = 0,
+ ssl_hs_client_hello = 1,
+ ssl_hs_server_hello = 2,
+ ssl_hs_hello_verify_request = 3,
+ ssl_hs_new_session_ticket = 4,
+ ssl_hs_end_of_early_data = 5,
+ ssl_hs_hello_retry_request = 6,
+ ssl_hs_encrypted_extensions = 8,
+ ssl_hs_certificate = 11,
+ ssl_hs_server_key_exchange = 12,
+ ssl_hs_certificate_request = 13,
+ ssl_hs_server_hello_done = 14,
+ ssl_hs_certificate_verify = 15,
+ ssl_hs_client_key_exchange = 16,
+ ssl_hs_finished = 20,
+ ssl_hs_certificate_status = 22,
+ ssl_hs_key_update = 24,
+ ssl_hs_next_proto = 67,
+ ssl_hs_message_hash = 254, /* Not a real message. */
+ ssl_hs_ech_outer_client_hello = 257, /* Not a real message. */
+} SSLHandshakeType;
+
+typedef enum {
+ ssl_ct_change_cipher_spec = 20,
+ ssl_ct_alert = 21,
+ ssl_ct_handshake = 22,
+ ssl_ct_application_data = 23,
+ ssl_ct_ack = 26
+} SSLContentType;
+
+typedef enum {
+ ssl_secret_read = 1,
+ ssl_secret_write = 2,
+} SSLSecretDirection;
+
+typedef struct SSL3StatisticsStr {
+ /* statistics from ssl3_SendClientHello (sch) */
+ long sch_sid_cache_hits;
+ long sch_sid_cache_misses;
+ long sch_sid_cache_not_ok;
+
+ /* statistics from ssl3_HandleServerHello (hsh) */
+ long hsh_sid_cache_hits;
+ long hsh_sid_cache_misses;
+ long hsh_sid_cache_not_ok;
+
+ /* statistics from ssl3_HandleClientHello (hch) */
+ long hch_sid_cache_hits;
+ long hch_sid_cache_misses;
+ long hch_sid_cache_not_ok;
+
+ /* statistics related to stateless resume */
+ long sch_sid_stateless_resumes;
+ long hsh_sid_stateless_resumes;
+ long hch_sid_stateless_resumes;
+ long hch_sid_ticket_parse_failures;
+} SSL3Statistics;
+
+/* Key Exchange algorithm values */
+typedef enum {
+ ssl_kea_null = 0,
+ ssl_kea_rsa = 1,
+ ssl_kea_dh = 2,
+ ssl_kea_fortezza = 3, /* deprecated, now unused */
+ ssl_kea_ecdh = 4,
+ ssl_kea_ecdh_psk = 5,
+ ssl_kea_dh_psk = 6,
+ ssl_kea_tls13_any = 7,
+ ssl_kea_size /* number of ssl_kea_ algorithms */
+} SSLKEAType;
+
+/* The following defines are for backwards compatibility.
+** They will be removed in a forthcoming release to reduce namespace pollution.
+** programs that use the kt_ symbols should convert to the ssl_kt_ symbols
+** soon.
+*/
+#define kt_null ssl_kea_null
+#define kt_rsa ssl_kea_rsa
+#define kt_dh ssl_kea_dh
+#define kt_fortezza ssl_kea_fortezza /* deprecated, now unused */
+#define kt_ecdh ssl_kea_ecdh
+#define kt_kea_size ssl_kea_size
+
+/* Values of this enum match the SignatureAlgorithm enum from
+ * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
+typedef enum {
+ ssl_sign_null = 0, /* "anonymous" in TLS */
+ ssl_sign_rsa = 1,
+ ssl_sign_dsa = 2,
+ ssl_sign_ecdsa = 3
+} SSLSignType;
+
+/* Values of this enum match the HashAlgorithm enum from
+ * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
+typedef enum {
+ /* ssl_hash_none is used internally to mean the pre-1.2 combination of MD5
+ * and SHA1. The other values are only used in TLS 1.2. */
+ ssl_hash_none = 0,
+ ssl_hash_md5 = 1,
+ ssl_hash_sha1 = 2,
+ ssl_hash_sha224 = 3,
+ ssl_hash_sha256 = 4,
+ ssl_hash_sha384 = 5,
+ ssl_hash_sha512 = 6
+} SSLHashType;
+
+/* Deprecated */
+typedef struct SSLSignatureAndHashAlgStr {
+ SSLHashType hashAlg;
+ SSLSignType sigAlg;
+} SSLSignatureAndHashAlg;
+
+typedef enum {
+ ssl_sig_none = 0,
+ ssl_sig_rsa_pkcs1_sha1 = 0x0201,
+ ssl_sig_rsa_pkcs1_sha256 = 0x0401,
+ ssl_sig_rsa_pkcs1_sha384 = 0x0501,
+ ssl_sig_rsa_pkcs1_sha512 = 0x0601,
+ /* For ECDSA, the pairing of the hash with a specific curve is only enforced
+ * in TLS 1.3; in TLS 1.2 any curve can be used with each of these. */
+ ssl_sig_ecdsa_secp256r1_sha256 = 0x0403,
+ ssl_sig_ecdsa_secp384r1_sha384 = 0x0503,
+ ssl_sig_ecdsa_secp521r1_sha512 = 0x0603,
+ ssl_sig_rsa_pss_rsae_sha256 = 0x0804,
+ ssl_sig_rsa_pss_rsae_sha384 = 0x0805,
+ ssl_sig_rsa_pss_rsae_sha512 = 0x0806,
+ ssl_sig_ed25519 = 0x0807,
+ ssl_sig_ed448 = 0x0808,
+ ssl_sig_rsa_pss_pss_sha256 = 0x0809,
+ ssl_sig_rsa_pss_pss_sha384 = 0x080a,
+ ssl_sig_rsa_pss_pss_sha512 = 0x080b,
+
+ ssl_sig_dsa_sha1 = 0x0202,
+ ssl_sig_dsa_sha256 = 0x0402,
+ ssl_sig_dsa_sha384 = 0x0502,
+ ssl_sig_dsa_sha512 = 0x0602,
+ ssl_sig_ecdsa_sha1 = 0x0203,
+
+ /* The following value (which can't be used in the protocol), represents
+ * the RSA signature using SHA-1 and MD5 that is used in TLS 1.0 and 1.1.
+ * This is reported as a signature scheme when TLS 1.0 or 1.1 is used.
+ * This should not be passed to SSL_SignatureSchemePrefSet(); this
+ * signature scheme is always used and cannot be disabled. */
+ ssl_sig_rsa_pkcs1_sha1md5 = 0x10101,
+} SSLSignatureScheme;
+
+/* Deprecated names maintained only for source compatibility. */
+#define ssl_sig_rsa_pss_sha256 ssl_sig_rsa_pss_rsae_sha256
+#define ssl_sig_rsa_pss_sha384 ssl_sig_rsa_pss_rsae_sha384
+#define ssl_sig_rsa_pss_sha512 ssl_sig_rsa_pss_rsae_sha512
+
+/*
+** SSLAuthType describes the type of key that is used to authenticate a
+** connection. That is, the type of key in the end-entity certificate.
+*/
+typedef enum {
+ ssl_auth_null = 0,
+ ssl_auth_rsa_decrypt = 1, /* RSA key exchange. */
+ ssl_auth_dsa = 2,
+ ssl_auth_kea = 3, /* unused */
+ ssl_auth_ecdsa = 4,
+ ssl_auth_ecdh_rsa = 5, /* ECDH cert with an RSA signature. */
+ ssl_auth_ecdh_ecdsa = 6, /* ECDH cert with an ECDSA signature. */
+ ssl_auth_rsa_sign = 7, /* RSA signing with an rsaEncryption key. */
+ ssl_auth_rsa_pss = 8, /* RSA signing with a PSS key. */
+ ssl_auth_psk = 9,
+ ssl_auth_tls13_any = 10,
+ ssl_auth_size /* number of authentication types */
+} SSLAuthType;
+
+typedef enum {
+ ssl_psk_none = 0,
+ ssl_psk_resume = 1,
+ ssl_psk_external = 2,
+} SSLPskType;
+
+/* This is defined for backward compatibility reasons */
+#define ssl_auth_rsa ssl_auth_rsa_decrypt
+
+typedef enum {
+ ssl_calg_null = 0,
+ ssl_calg_rc4 = 1,
+ ssl_calg_rc2 = 2,
+ ssl_calg_des = 3,
+ ssl_calg_3des = 4,
+ ssl_calg_idea = 5,
+ ssl_calg_fortezza = 6, /* deprecated, now unused */
+ ssl_calg_aes = 7,
+ ssl_calg_camellia = 8,
+ ssl_calg_seed = 9,
+ ssl_calg_aes_gcm = 10,
+ ssl_calg_chacha20 = 11
+} SSLCipherAlgorithm;
+
+typedef enum {
+ ssl_mac_null = 0,
+ ssl_mac_md5 = 1,
+ ssl_mac_sha = 2,
+ ssl_hmac_md5 = 3, /* TLS HMAC version of mac_md5 */
+ ssl_hmac_sha = 4, /* TLS HMAC version of mac_sha */
+ ssl_hmac_sha256 = 5,
+ ssl_mac_aead = 6,
+ ssl_hmac_sha384 = 7
+} SSLMACAlgorithm;
+
+typedef enum {
+ ssl_compression_null = 0,
+ ssl_compression_deflate = 1 /* RFC 3749 */
+} SSLCompressionMethod;
+
+typedef enum {
+ ssl_grp_ec_sect163k1 = 1,
+ ssl_grp_ec_sect163r1 = 2,
+ ssl_grp_ec_sect163r2 = 3,
+ ssl_grp_ec_sect193r1 = 4,
+ ssl_grp_ec_sect193r2 = 5,
+ ssl_grp_ec_sect233k1 = 6,
+ ssl_grp_ec_sect233r1 = 7,
+ ssl_grp_ec_sect239k1 = 8,
+ ssl_grp_ec_sect283k1 = 9,
+ ssl_grp_ec_sect283r1 = 10,
+ ssl_grp_ec_sect409k1 = 11,
+ ssl_grp_ec_sect409r1 = 12,
+ ssl_grp_ec_sect571k1 = 13,
+ ssl_grp_ec_sect571r1 = 14,
+ ssl_grp_ec_secp160k1 = 15,
+ ssl_grp_ec_secp160r1 = 16,
+ ssl_grp_ec_secp160r2 = 17,
+ ssl_grp_ec_secp192k1 = 18,
+ ssl_grp_ec_secp192r1 = 19,
+ ssl_grp_ec_secp224k1 = 20,
+ ssl_grp_ec_secp224r1 = 21,
+ ssl_grp_ec_secp256k1 = 22,
+ ssl_grp_ec_secp256r1 = 23,
+ ssl_grp_ec_secp384r1 = 24,
+ ssl_grp_ec_secp521r1 = 25,
+ ssl_grp_ec_curve25519 = 29, /* RFC4492 */
+ ssl_grp_ffdhe_2048 = 256, /* RFC7919 */
+ ssl_grp_ffdhe_3072 = 257,
+ ssl_grp_ffdhe_4096 = 258,
+ ssl_grp_ffdhe_6144 = 259,
+ ssl_grp_ffdhe_8192 = 260,
+ ssl_grp_none = 65537, /* special value */
+ ssl_grp_ffdhe_custom = 65538 /* special value */
+} SSLNamedGroup;
+
+typedef struct SSLExtraServerCertDataStr {
+ /* When this struct is passed to SSL_ConfigServerCert, and authType is set
+ * to a value other than ssl_auth_null, this limits the use of the key to
+ * the type defined; otherwise, the certificate is configured for all
+ * compatible types. */
+ SSLAuthType authType;
+ /* The remainder of the certificate chain. */
+ const CERTCertificateList* certChain;
+ /* A set of one or more stapled OCSP responses for the certificate. This is
+ * used to generate the OCSP stapling answer provided by the server. */
+ const SECItemArray* stapledOCSPResponses;
+ /* A serialized sign_certificate_timestamp extension, used to answer
+ * requests from clients for this data. */
+ const SECItem* signedCertTimestamps;
+
+ /* Delegated credentials.
+ *
+ * A serialized delegated credential (DC) to use for authentication to peers
+ * who indicate support for this extension (ietf-drafts-tls-subcerts). DCs
+ * are used opportunistically if (1) the client indicates support, (2) TLS
+ * 1.3 or higher is negotiated, and (3) the selected certificate is
+ * configured with a DC.
+ *
+ * Note that it's the caller's responsibility to ensure that the DC is
+ * well-formed.
+ */
+ const SECItem* delegCred;
+
+ /* The secret key corresponding to the |delegCred|.
+ *
+ * Note that it's the caller's responsibility to ensure that this matches
+ * the DC public key.
+ */
+ const SECKEYPrivateKey* delegCredPrivKey;
+} SSLExtraServerCertData;
+
+typedef struct SSLChannelInfoStr {
+ /* On return, SSL_GetChannelInfo sets |length| to the smaller of
+ * the |len| argument and the length of the struct used by NSS.
+ * Callers must ensure the application uses a version of NSS that
+ * isn't older than the version used at compile time. */
+ PRUint32 length;
+ PRUint16 protocolVersion;
+ PRUint16 cipherSuite;
+
+ /* The strength of the key used to authenticate the peer. Before
+ * interpreting this value, check authType, signatureScheme, and
+ * peerDelegCred, to determine the type of the key and how it was used.
+ *
+ * Typically, this is the length of the key from the peer's end-entity
+ * certificate. If delegated credentials are used (i.e., peerDelegCred is
+ * PR_TRUE), then this is the strength of the delegated credential key. */
+ PRUint32 authKeyBits;
+
+ /* key exchange algorithm info */
+ PRUint32 keaKeyBits;
+
+ /* session info */
+ PRUint32 creationTime; /* seconds since Jan 1, 1970 */
+ PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */
+ PRUint32 expirationTime; /* seconds since Jan 1, 1970 */
+ PRUint32 sessionIDLength; /* up to 32 */
+ PRUint8 sessionID[32];
+
+ /* The following fields are added in NSS 3.12.5. */
+
+ /* compression method info */
+ const char* compressionMethodName;
+ SSLCompressionMethod compressionMethod;
+
+ /* The following fields are added in NSS 3.21.
+ * This field only has meaning in TLS < 1.3 and will be set to
+ * PR_FALSE in TLS 1.3.
+ */
+ PRBool extendedMasterSecretUsed;
+
+ /* The following fields were added in NSS 3.25.
+ * This field only has meaning in TLS >= 1.3, and indicates on the
+ * client side that the server accepted early (0-RTT) data.
+ */
+ PRBool earlyDataAccepted;
+
+ /* The following fields were added in NSS 3.28. */
+ /* These fields have the same meaning as in SSLCipherSuiteInfo. */
+ SSLKEAType keaType;
+ SSLNamedGroup keaGroup;
+ SSLCipherAlgorithm symCipher;
+ SSLMACAlgorithm macAlgorithm;
+ SSLAuthType authType;
+ SSLSignatureScheme signatureScheme;
+
+ /* The following fields were added in NSS 3.34. */
+ /* When the session was resumed this holds the key exchange group of the
+ * original handshake. */
+ SSLNamedGroup originalKeaGroup;
+ /* This field is PR_TRUE when the session is resumed and PR_FALSE
+ * otherwise. */
+ PRBool resumed;
+
+ /* Indicates whether the peer used a delegated credential (DC) for
+ * authentication.
+ */
+ PRBool peerDelegCred;
+
+ /* The following fields were added in NSS 3.54. */
+ /* Indicates what type of PSK, if any, was used in a handshake. */
+ SSLPskType pskType;
+
+ /* The following fields were added in NSS 3.60 */
+ /* This field is PR_TRUE when the connection is established
+ * with TLS 1.3 Encrypted Client Hello. */
+ PRBool echAccepted;
+
+ /* The following field was added in NSS 3.66 */
+ /* This filed is PR_TRUE if the FIPS indicator is true for the
+ * current connection */
+ PRBool isFIPS;
+
+ /* When adding new fields to this structure, please document the
+ * NSS version in which they were added. */
+} SSLChannelInfo;
+
+/* Preliminary channel info */
+#define ssl_preinfo_version (1U << 0)
+#define ssl_preinfo_cipher_suite (1U << 1)
+#define ssl_preinfo_0rtt_cipher_suite (1U << 2)
+/* ssl_preinfo_peer_auth covers peerDelegCred, authKeyBits,
+ * and scheme. Not included in ssl_preinfo_all as it is client-only. */
+#define ssl_preinfo_peer_auth (1U << 3)
+#define ssl_preinfo_ech (1U << 4)
+/* ssl_preinfo_all doesn't contain ssl_preinfo_0rtt_cipher_suite because that
+ * field is only set if 0-RTT is sent (client) or accepted (server). */
+#define ssl_preinfo_all (ssl_preinfo_version | ssl_preinfo_cipher_suite | ssl_preinfo_ech)
+
+typedef struct SSLPreliminaryChannelInfoStr {
+ /* On return, SSL_GetPreliminaryChannelInfo sets |length| to the smaller of
+ * the |len| argument and the length of the struct used by NSS.
+ * Callers must ensure the application uses a version of NSS that
+ * isn't older than the version used at compile time. */
+ PRUint32 length;
+ /* A bitfield over SSLPreliminaryValueSet that describes which
+ * preliminary values are set (see ssl_preinfo_*). */
+ PRUint32 valuesSet;
+ /* Protocol version: test (valuesSet & ssl_preinfo_version) */
+ PRUint16 protocolVersion;
+ /* Cipher suite: test (valuesSet & ssl_preinfo_cipher_suite) */
+ PRUint16 cipherSuite;
+
+ /* The following fields were added in NSS 3.29. */
+ /* |canSendEarlyData| is true when a 0-RTT is enabled. This can only be
+ * true after sending the ClientHello and before the handshake completes.
+ */
+ PRBool canSendEarlyData;
+
+ /* The following fields were added in NSS 3.31. */
+ /* The number of early data octets that a client is permitted to send on
+ * this connection. The value will be zero if the connection was not
+ * resumed or early data is not permitted. For a client, this value only
+ * has meaning if |canSendEarlyData| is true. For a server, this indicates
+ * the value that was advertised in the session ticket that was used to
+ * resume this session. */
+ PRUint32 maxEarlyDataSize;
+
+ /* The following fields were added in NSS 3.43. */
+ /* This reports the cipher suite used for 0-RTT if it sent or accepted. For
+ * a client, this is set earlier than |cipherSuite|, and will match that
+ * value if 0-RTT is accepted by the server. The server only sets this
+ * after accepting 0-RTT, so this will contain the same value. */
+ PRUint16 zeroRttCipherSuite;
+
+ /* The following fields were added in NSS 3.48. */
+ /* These fields contain information about the key that will be used in
+ * the CertificateVerify message. If Delegated Credentials are being used,
+ * this is the DC-contained SPKI, else the EE-cert SPKI. These fields are
+ * valid only after the Certificate message is handled. This can be determined
+ * by checking the valuesSet field against |ssl_preinfo_peer_auth|. */
+ PRBool peerDelegCred;
+ PRUint32 authKeyBits;
+ SSLSignatureScheme signatureScheme;
+
+ /* The following fields were added in NSS 3.60. */
+ PRBool echAccepted;
+ /* If the application configured ECH but |!echAccepted|, authCertificate
+ * should use the following hostname extracted from the ECHConfig. */
+ const char* echPublicName;
+
+ /* The following field was added in NSS 3.85. */
+ PRBool ticketSupportsEarlyData;
+
+ /* When adding new fields to this structure, please document the
+ * NSS version in which they were added. */
+} SSLPreliminaryChannelInfo;
+
+typedef struct SSLCipherSuiteInfoStr {
+ /* On return, SSL_GetCipherSuitelInfo sets |length| to the smaller of
+ * the |len| argument and the length of the struct used by NSS.
+ * Callers must ensure the application uses a version of NSS that
+ * isn't older than the version used at compile time. */
+ PRUint16 length;
+ PRUint16 cipherSuite;
+
+ /* Cipher Suite Name */
+ const char* cipherSuiteName;
+
+ /* server authentication info */
+ const char* authAlgorithmName;
+ SSLAuthType authAlgorithm; /* deprecated, use |authType| */
+
+ /* key exchange algorithm info */
+ const char* keaTypeName;
+ SSLKEAType keaType;
+
+ /* symmetric encryption info */
+ const char* symCipherName;
+ SSLCipherAlgorithm symCipher;
+ PRUint16 symKeyBits;
+ PRUint16 symKeySpace;
+ PRUint16 effectiveKeyBits;
+
+ /* MAC info */
+ /* AEAD ciphers don't have a MAC. For an AEAD cipher, macAlgorithmName
+ * is "AEAD", macAlgorithm is ssl_mac_aead, and macBits is the length in
+ * bits of the authentication tag. */
+ const char* macAlgorithmName;
+ SSLMACAlgorithm macAlgorithm;
+ PRUint16 macBits;
+
+ PRUintn isFIPS : 1;
+ PRUintn isExportable : 1; /* deprecated, don't use */
+ PRUintn nonStandard : 1;
+ PRUintn reservedBits : 29;
+
+ /* The following fields were added in NSS 3.24. */
+ /* This reports the correct authentication type for the cipher suite, use
+ * this instead of |authAlgorithm|. */
+ SSLAuthType authType;
+
+ /* The following fields were added in NSS 3.43. */
+ /* This reports the hash function used in the TLS KDF, or HKDF for TLS 1.3.
+ * For suites defined for versions of TLS earlier than TLS 1.2, this reports
+ * ssl_hash_none. */
+ SSLHashType kdfHash;
+
+ /* When adding new fields to this structure, please document the
+ * NSS version in which they were added. */
+} SSLCipherSuiteInfo;
+
+typedef enum {
+ ssl_variant_stream = 0,
+ ssl_variant_datagram = 1
+} SSLProtocolVariant;
+
+typedef struct SSLVersionRangeStr {
+ PRUint16 min;
+ PRUint16 max;
+} SSLVersionRange;
+
+typedef enum {
+ SSL_sni_host_name = 0,
+ SSL_sni_type_total
+} SSLSniNameType;
+
+/* Supported extensions. */
+/* Update SSL_MAX_EXTENSIONS whenever a new extension type is added. */
+typedef enum {
+ ssl_server_name_xtn = 0,
+ ssl_cert_status_xtn = 5,
+ ssl_supported_groups_xtn = 10,
+ ssl_ec_point_formats_xtn = 11,
+ ssl_signature_algorithms_xtn = 13,
+ ssl_use_srtp_xtn = 14,
+ ssl_app_layer_protocol_xtn = 16,
+ /* signed_certificate_timestamp extension, RFC 6962 */
+ ssl_signed_cert_timestamp_xtn = 18,
+ ssl_padding_xtn = 21,
+ ssl_extended_master_secret_xtn = 23,
+ ssl_record_size_limit_xtn = 28,
+ ssl_delegated_credentials_xtn = 34,
+ ssl_session_ticket_xtn = 35,
+ /* 40 was used in draft versions of TLS 1.3; it is now reserved. */
+ ssl_tls13_pre_shared_key_xtn = 41,
+ ssl_tls13_early_data_xtn = 42,
+ ssl_tls13_supported_versions_xtn = 43,
+ ssl_tls13_cookie_xtn = 44,
+ ssl_tls13_psk_key_exchange_modes_xtn = 45,
+ ssl_tls13_ticket_early_data_info_xtn = 46, /* Deprecated. */
+ ssl_tls13_certificate_authorities_xtn = 47,
+ ssl_tls13_post_handshake_auth_xtn = 49,
+ ssl_signature_algorithms_cert_xtn = 50,
+ ssl_tls13_key_share_xtn = 51,
+ /* TLS 1.3 GREASE extension dummy type for builders. */
+ ssl_tls13_grease_xtn = 0x0a0a,
+ ssl_next_proto_nego_xtn = 13172, /* Deprecated. */
+ ssl_renegotiation_info_xtn = 0xff01,
+ ssl_tls13_short_header_xtn = 0xff03, /* Deprecated. */
+ ssl_tls13_outer_extensions_xtn = 0xfd00,
+ ssl_tls13_encrypted_client_hello_xtn = 0xfe0d,
+ ssl_tls13_encrypted_sni_xtn = 0xffce, /* Deprecated. */
+} SSLExtensionType;
+
+/* This is the old name for the supported_groups extensions. */
+#define ssl_elliptic_curves_xtn ssl_supported_groups_xtn
+
+/* SSL_MAX_EXTENSIONS includes the maximum number of extensions that are
+ * supported for any single message type. That is, a ClientHello; ServerHello
+ * and TLS 1.3 NewSessionTicket and HelloRetryRequest extensions have fewer. */
+#define SSL_MAX_EXTENSIONS 21
+
+/* Deprecated */
+typedef enum {
+ ssl_dhe_group_none = 0,
+ ssl_ff_dhe_2048_group = 1,
+ ssl_ff_dhe_3072_group = 2,
+ ssl_ff_dhe_4096_group = 3,
+ ssl_ff_dhe_6144_group = 4,
+ ssl_ff_dhe_8192_group = 5,
+ ssl_dhe_group_max
+} SSLDHEGroupType;
+
+#endif /* __sslt_h_ */
diff --git a/security/nss/lib/ssl/ssltrace.c b/security/nss/lib/ssl/ssltrace.c
new file mode 100644
index 0000000000..b1fdde7902
--- /dev/null
+++ b/security/nss/lib/ssl/ssltrace.c
@@ -0,0 +1,114 @@
+/*
+ * Functions to trace SSL protocol behavior in DEBUG builds.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include <stdarg.h>
+#include "cert.h"
+#include "pk11func.h"
+#include "ssl.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "prprf.h"
+
+#if defined(DEBUG) || defined(TRACE)
+static const char *hex = "0123456789abcdef";
+
+static const char printable[257] = {
+ "................" /* 0x */
+ "................" /* 1x */
+ " !\"#$%&'()*+,-./" /* 2x */
+ "0123456789:;<=>?" /* 3x */
+ "@ABCDEFGHIJKLMNO" /* 4x */
+ "PQRSTUVWXYZ[\\]^_" /* 5x */
+ "`abcdefghijklmno" /* 6x */
+ "pqrstuvwxyz{|}~." /* 7x */
+ "................" /* 8x */
+ "................" /* 9x */
+ "................" /* ax */
+ "................" /* bx */
+ "................" /* cx */
+ "................" /* dx */
+ "................" /* ex */
+ "................" /* fx */
+};
+
+void
+ssl_PrintBuf(const sslSocket *ss, const char *msg, const void *vp, int len)
+{
+ const unsigned char *cp = (const unsigned char *)vp;
+ char buf[80];
+ char *bp;
+ char *ap;
+
+ if (ss) {
+ SSL_TRACE(("%d: SSL[%d]: %s [Len: %d]", SSL_GETPID(), ss->fd,
+ msg, len));
+ } else {
+ SSL_TRACE(("%d: SSL: %s [Len: %d]", SSL_GETPID(), msg, len));
+ }
+
+ if (!cp) {
+ SSL_TRACE((" <NULL>"));
+ return;
+ }
+
+ memset(buf, ' ', sizeof buf);
+ bp = buf;
+ ap = buf + 50;
+ while (--len >= 0) {
+ unsigned char ch = *cp++;
+ *bp++ = hex[(ch >> 4) & 0xf];
+ *bp++ = hex[ch & 0xf];
+ *bp++ = ' ';
+ *ap++ = printable[ch];
+ if (ap - buf >= 66) {
+ *ap = 0;
+ SSL_TRACE((" %s", buf));
+ memset(buf, ' ', sizeof buf);
+ bp = buf;
+ ap = buf + 50;
+ }
+ }
+ if (bp > buf) {
+ *ap = 0;
+ SSL_TRACE((" %s", buf));
+ }
+}
+
+void
+ssl_Trace(const char *format, ...)
+{
+ char buf[2000];
+ va_list args;
+
+ if (ssl_trace_iob) {
+ va_start(args, format);
+ PR_vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+
+ fputs(buf, ssl_trace_iob);
+ fputs("\n", ssl_trace_iob);
+ }
+}
+
+void
+ssl_PrintKey(const sslSocket *ss, const char *msg, PK11SymKey *key)
+{
+ SECStatus rv;
+ SECItem *rawkey;
+
+ rv = PK11_ExtractKeyValue(key);
+ if (rv != SECSuccess) {
+ ssl_Trace("Could not extract key for %s", msg);
+ return;
+ }
+ rawkey = PK11_GetKeyData(key);
+ if (!rawkey) {
+ ssl_Trace("Could not extract key for %s", msg);
+ return;
+ }
+ ssl_PrintBuf(ss, msg, rawkey->data, rawkey->len);
+}
+#endif
diff --git a/security/nss/lib/ssl/sslver.c b/security/nss/lib/ssl/sslver.c
new file mode 100644
index 0000000000..666e259224
--- /dev/null
+++ b/security/nss/lib/ssl/sslver.c
@@ -0,0 +1,18 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Library identity and versioning */
+
+#include "nss.h"
+
+#if defined(DEBUG)
+#define _DEBUG_STRING " (debug)"
+#else
+#define _DEBUG_STRING ""
+#endif
+
+/*
+ * Version information
+ */
+const char __nss_ssl_version[] = "Version: NSS " NSS_VERSION _DEBUG_STRING;
diff --git a/security/nss/lib/ssl/tls13con.c b/security/nss/lib/ssl/tls13con.c
new file mode 100644
index 0000000000..fbbc510f15
--- /dev/null
+++ b/security/nss/lib/ssl/tls13con.c
@@ -0,0 +1,6568 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * TLS 1.3 Protocol
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "stdarg.h"
+#include "cert.h"
+#include "ssl.h"
+#include "keyhi.h"
+#include "pk11func.h"
+#include "prerr.h"
+#include "secitem.h"
+#include "secmod.h"
+#include "sslimpl.h"
+#include "sslproto.h"
+#include "sslerr.h"
+#include "ssl3exthandle.h"
+#include "tls13hkdf.h"
+#include "tls13con.h"
+#include "tls13err.h"
+#include "tls13ech.h"
+#include "tls13exthandle.h"
+#include "tls13hashstate.h"
+#include "tls13subcerts.h"
+#include "tls13psk.h"
+
+static SECStatus tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
+ SSLSecretDirection install,
+ PRBool deleteSecret);
+static SECStatus tls13_SendServerHelloSequence(sslSocket *ss);
+static SECStatus tls13_SendEncryptedExtensions(sslSocket *ss);
+static void tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group);
+static SECStatus tls13_HandleClientKeyShare(sslSocket *ss,
+ TLS13KeyShareEntry *peerShare);
+static SECStatus tls13_SendHelloRetryRequest(
+ sslSocket *ss, const sslNamedGroupDef *selectedGroup,
+ const PRUint8 *token, unsigned int tokenLen);
+
+static SECStatus tls13_HandleServerKeyShare(sslSocket *ss);
+static SECStatus tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b,
+ PRUint32 length);
+static SECStatus tls13_SendCertificate(sslSocket *ss);
+static SECStatus tls13_HandleCertificate(
+ sslSocket *ss, PRUint8 *b, PRUint32 length);
+static SECStatus tls13_ReinjectHandshakeTranscript(sslSocket *ss);
+static SECStatus tls13_SendCertificateRequest(sslSocket *ss);
+static SECStatus tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b,
+ PRUint32 length);
+static SECStatus
+tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey);
+static SECStatus tls13_HandleCertificateVerify(
+ sslSocket *ss, PRUint8 *b, PRUint32 length);
+static SECStatus tls13_RecoverWrappedSharedSecret(sslSocket *ss,
+ sslSessionID *sid);
+static SECStatus
+tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
+ const char *prefix,
+ const char *suffix,
+ const char *keylogLabel,
+ PK11SymKey **dest);
+SECStatus
+tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
+ const char *label,
+ unsigned int labelLen,
+ const SSL3Hashes *hashes,
+ PK11SymKey **dest,
+ SSLHashType hash);
+static SECStatus tls13_SendEndOfEarlyData(sslSocket *ss);
+static SECStatus tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b,
+ PRUint32 length);
+static SECStatus tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss);
+static SECStatus tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey);
+static SECStatus tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
+ SSL3Hashes *hashes, SSLHashType type);
+static SECStatus tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
+ PK11SymKey *secret,
+ PRUint8 *b, PRUint32 length,
+ const SSL3Hashes *hashes);
+static SECStatus tls13_ClientHandleFinished(sslSocket *ss,
+ PRUint8 *b, PRUint32 length);
+static SECStatus tls13_ServerHandleFinished(sslSocket *ss,
+ PRUint8 *b, PRUint32 length);
+static SECStatus tls13_SendNewSessionTicket(sslSocket *ss,
+ const PRUint8 *appToken,
+ unsigned int appTokenLen);
+static SECStatus tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b,
+ PRUint32 length);
+static SECStatus tls13_ComputeEarlySecretsWithPsk(sslSocket *ss);
+static SECStatus tls13_ComputeHandshakeSecrets(sslSocket *ss);
+static SECStatus tls13_ComputeApplicationSecrets(sslSocket *ss);
+static SECStatus tls13_ComputeFinalSecrets(sslSocket *ss);
+static SECStatus tls13_ComputeFinished(
+ sslSocket *ss, PK11SymKey *baseKey, SSLHashType hashType,
+ const SSL3Hashes *hashes, PRBool sending, PRUint8 *output,
+ unsigned int *outputLen, unsigned int maxOutputLen);
+static SECStatus tls13_SendClientSecondRound(sslSocket *ss);
+static SECStatus tls13_SendClientSecondFlight(sslSocket *ss);
+static SECStatus tls13_FinishHandshake(sslSocket *ss);
+
+const char kHkdfLabelClient[] = "c";
+const char kHkdfLabelServer[] = "s";
+const char kHkdfLabelDerivedSecret[] = "derived";
+const char kHkdfLabelResPskBinderKey[] = "res binder";
+const char kHkdfLabelExtPskBinderKey[] = "ext binder";
+const char kHkdfLabelEarlyTrafficSecret[] = "e traffic";
+const char kHkdfLabelEarlyExporterSecret[] = "e exp master";
+const char kHkdfLabelHandshakeTrafficSecret[] = "hs traffic";
+const char kHkdfLabelApplicationTrafficSecret[] = "ap traffic";
+const char kHkdfLabelFinishedSecret[] = "finished";
+const char kHkdfLabelResumptionMasterSecret[] = "res master";
+const char kHkdfLabelExporterMasterSecret[] = "exp master";
+const char kHkdfLabelResumption[] = "resumption";
+const char kHkdfLabelTrafficUpdate[] = "traffic upd";
+const char kHkdfPurposeKey[] = "key";
+const char kHkdfPurposeSn[] = "sn";
+const char kHkdfPurposeIv[] = "iv";
+
+const char keylogLabelClientEarlyTrafficSecret[] = "CLIENT_EARLY_TRAFFIC_SECRET";
+const char keylogLabelClientHsTrafficSecret[] = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
+const char keylogLabelServerHsTrafficSecret[] = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
+const char keylogLabelClientTrafficSecret[] = "CLIENT_TRAFFIC_SECRET_0";
+const char keylogLabelServerTrafficSecret[] = "SERVER_TRAFFIC_SECRET_0";
+const char keylogLabelEarlyExporterSecret[] = "EARLY_EXPORTER_SECRET";
+const char keylogLabelExporterSecret[] = "EXPORTER_SECRET";
+
+/* Belt and suspenders in case we ever add a TLS 1.4. */
+PR_STATIC_ASSERT(SSL_LIBRARY_VERSION_MAX_SUPPORTED <=
+ SSL_LIBRARY_VERSION_TLS_1_3);
+
+void
+tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc)
+{
+ PORT_Assert(desc != internal_error); /* These should never happen */
+ (void)SSL3_SendAlert(ss, alert_fatal, desc);
+ PORT_SetError(prError);
+}
+
+#ifdef TRACE
+#define STATE_CASE(a) \
+ case a: \
+ return #a
+static char *
+tls13_HandshakeState(SSL3WaitState st)
+{
+ switch (st) {
+ STATE_CASE(idle_handshake);
+ STATE_CASE(wait_client_hello);
+ STATE_CASE(wait_end_of_early_data);
+ STATE_CASE(wait_client_cert);
+ STATE_CASE(wait_client_key);
+ STATE_CASE(wait_cert_verify);
+ STATE_CASE(wait_change_cipher);
+ STATE_CASE(wait_finished);
+ STATE_CASE(wait_server_hello);
+ STATE_CASE(wait_certificate_status);
+ STATE_CASE(wait_server_cert);
+ STATE_CASE(wait_server_key);
+ STATE_CASE(wait_cert_request);
+ STATE_CASE(wait_hello_done);
+ STATE_CASE(wait_new_session_ticket);
+ STATE_CASE(wait_encrypted_extensions);
+ default:
+ break;
+ }
+ PORT_Assert(0);
+ return "unknown";
+}
+#endif
+
+#define TLS13_WAIT_STATE_MASK 0x80
+
+#define TLS13_BASE_WAIT_STATE(ws) (ws & ~TLS13_WAIT_STATE_MASK)
+/* We don't mask idle_handshake because other parts of the code use it*/
+#define TLS13_WAIT_STATE(ws) (((ws == idle_handshake) || (ws == wait_server_hello)) ? ws : ws | TLS13_WAIT_STATE_MASK)
+#define TLS13_CHECK_HS_STATE(ss, err, ...) \
+ tls13_CheckHsState(ss, err, #err, __func__, __FILE__, __LINE__, \
+ __VA_ARGS__, \
+ wait_invalid)
+void
+tls13_SetHsState(sslSocket *ss, SSL3WaitState ws,
+ const char *func, const char *file, int line)
+{
+#ifdef TRACE
+ const char *new_state_name =
+ tls13_HandshakeState(ws);
+
+ SSL_TRC(3, ("%d: TLS13[%d]: %s state change from %s->%s in %s (%s:%d)",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss),
+ tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),
+ new_state_name,
+ func, file, line));
+#endif
+
+ ss->ssl3.hs.ws = TLS13_WAIT_STATE(ws);
+}
+
+static PRBool
+tls13_InHsStateV(sslSocket *ss, va_list ap)
+{
+ SSL3WaitState ws;
+
+ while ((ws = va_arg(ap, SSL3WaitState)) != wait_invalid) {
+ if (TLS13_WAIT_STATE(ws) == ss->ssl3.hs.ws) {
+ return PR_TRUE;
+ }
+ }
+ return PR_FALSE;
+}
+
+PRBool
+tls13_InHsState(sslSocket *ss, ...)
+{
+ PRBool found;
+ va_list ap;
+
+ va_start(ap, ss);
+ found = tls13_InHsStateV(ss, ap);
+ va_end(ap);
+
+ return found;
+}
+
+static SECStatus
+tls13_CheckHsState(sslSocket *ss, int err, const char *error_name,
+ const char *func, const char *file, int line,
+ ...)
+{
+ va_list ap;
+ va_start(ap, line);
+ if (tls13_InHsStateV(ss, ap)) {
+ va_end(ap);
+ return SECSuccess;
+ }
+ va_end(ap);
+
+ SSL_TRC(3, ("%d: TLS13[%d]: error %s state is (%s) at %s (%s:%d)",
+ SSL_GETPID(), ss->fd,
+ error_name,
+ tls13_HandshakeState(TLS13_BASE_WAIT_STATE(ss->ssl3.hs.ws)),
+ func, file, line));
+ tls13_FatalError(ss, err, unexpected_message);
+ return SECFailure;
+}
+
+PRBool
+tls13_IsPostHandshake(const sslSocket *ss)
+{
+ return ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && ss->firstHsDone;
+}
+
+SSLHashType
+tls13_GetHashForCipherSuite(ssl3CipherSuite suite)
+{
+ const ssl3CipherSuiteDef *cipherDef =
+ ssl_LookupCipherSuiteDef(suite);
+ PORT_Assert(cipherDef);
+ if (!cipherDef) {
+ return ssl_hash_none;
+ }
+ return cipherDef->prf_hash;
+}
+
+SSLHashType
+tls13_GetHash(const sslSocket *ss)
+{
+ /* suite_def may not be set yet when doing EPSK 0-Rtt. */
+ if (!ss->ssl3.hs.suite_def) {
+ if (ss->xtnData.selectedPsk) {
+ return ss->xtnData.selectedPsk->hash;
+ }
+ /* This should never happen. */
+ PORT_Assert(0);
+ return ssl_hash_none;
+ }
+
+ /* All TLS 1.3 cipher suites must have an explict PRF hash. */
+ PORT_Assert(ss->ssl3.hs.suite_def->prf_hash != ssl_hash_none);
+ return ss->ssl3.hs.suite_def->prf_hash;
+}
+
+SECStatus
+tls13_GetHashAndCipher(PRUint16 version, PRUint16 cipherSuite,
+ SSLHashType *hash, const ssl3BulkCipherDef **cipher)
+{
+ if (version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ // Lookup and check the suite.
+ SSLVersionRange vrange = { version, version };
+ if (!ssl3_CipherSuiteAllowedForVersionRange(cipherSuite, &vrange)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ const ssl3CipherSuiteDef *suiteDef = ssl_LookupCipherSuiteDef(cipherSuite);
+ const ssl3BulkCipherDef *cipherDef = ssl_GetBulkCipherDef(suiteDef);
+ if (cipherDef->type != type_aead) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ *hash = suiteDef->prf_hash;
+ if (cipher != NULL) {
+ *cipher = cipherDef;
+ }
+ return SECSuccess;
+}
+
+unsigned int
+tls13_GetHashSizeForHash(SSLHashType hash)
+{
+ switch (hash) {
+ case ssl_hash_sha256:
+ return 32;
+ case ssl_hash_sha384:
+ return 48;
+ default:
+ PORT_Assert(0);
+ }
+ return 32;
+}
+
+unsigned int
+tls13_GetHashSize(const sslSocket *ss)
+{
+ return tls13_GetHashSizeForHash(tls13_GetHash(ss));
+}
+
+static CK_MECHANISM_TYPE
+tls13_GetHmacMechanismFromHash(SSLHashType hashType)
+{
+ switch (hashType) {
+ case ssl_hash_sha256:
+ return CKM_SHA256_HMAC;
+ case ssl_hash_sha384:
+ return CKM_SHA384_HMAC;
+ default:
+ PORT_Assert(0);
+ }
+ return CKM_SHA256_HMAC;
+}
+
+static CK_MECHANISM_TYPE
+tls13_GetHmacMechanism(const sslSocket *ss)
+{
+ return tls13_GetHmacMechanismFromHash(tls13_GetHash(ss));
+}
+
+SECStatus
+tls13_ComputeHash(sslSocket *ss, SSL3Hashes *hashes,
+ const PRUint8 *buf, unsigned int len,
+ SSLHashType hash)
+{
+ SECStatus rv;
+
+ rv = PK11_HashBuf(ssl3_HashTypeToOID(hash), hashes->u.raw, buf, len);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ hashes->len = tls13_GetHashSizeForHash(hash);
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef,
+ sslEphemeralKeyPair **keyPair)
+{
+ SECStatus rv;
+ const ssl3DHParams *params;
+
+ PORT_Assert(groupDef);
+ switch (groupDef->keaType) {
+ case ssl_kea_ecdh:
+ rv = ssl_CreateECDHEphemeralKeyPair(ss, groupDef, keyPair);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ break;
+ case ssl_kea_dh:
+ params = ssl_GetDHEParams(groupDef);
+ PORT_Assert(params->name != ssl_grp_ffdhe_custom);
+ rv = ssl_CreateDHEKeyPair(groupDef, params, keyPair);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ break;
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ return rv;
+}
+
+SECStatus
+tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef)
+{
+ sslEphemeralKeyPair *keyPair = NULL;
+ SECStatus rv;
+
+ rv = tls13_CreateKeyShare(ss, groupDef, &keyPair);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs);
+ return SECSuccess;
+}
+
+SECStatus
+SSL_SendAdditionalKeyShares(PRFileDesc *fd, unsigned int count)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss->additionalShares = count;
+ return SECSuccess;
+}
+
+/*
+ * Generate shares for ECDHE and FFDHE. This picks the first enabled group of
+ * the requisite type and creates a share for that.
+ *
+ * Called from ssl3_SendClientHello.
+ */
+SECStatus
+tls13_SetupClientHello(sslSocket *ss, sslClientHelloType chType)
+{
+ unsigned int i;
+ SSL3Statistics *ssl3stats = SSL_GetStatistics();
+ NewSessionTicket *session_ticket = NULL;
+ sslSessionID *sid = ss->sec.ci.sid;
+ unsigned int numShares = 0;
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ rv = tls13_ClientSetupEch(ss, chType);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Everything below here is only run on the first CH. */
+ if (chType != client_hello_initial) {
+ return SECSuccess;
+ }
+
+ rv = tls13_ClientGreaseSetup(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Select the first enabled group.
+ * TODO(ekr@rtfm.com): be smarter about offering the group
+ * that the other side negotiated if we are resuming. */
+ PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
+ for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
+ if (!ss->namedGroupPreferences[i]) {
+ continue;
+ }
+ rv = tls13_AddKeyShare(ss, ss->namedGroupPreferences[i]);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (++numShares > ss->additionalShares) {
+ break;
+ }
+ }
+
+ if (PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)) {
+ PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
+ return SECFailure;
+ }
+
+ /* Try to do stateless resumption, if we can. */
+ if (sid->cached != never_cached &&
+ sid->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ /* The caller must be holding sid->u.ssl3.lock for reading. */
+ session_ticket = &sid->u.ssl3.locked.sessionTicket;
+ PORT_Assert(session_ticket && session_ticket->ticket.data);
+
+ if (ssl_TicketTimeValid(ss, session_ticket)) {
+ ss->statelessResume = PR_TRUE;
+ }
+
+ if (ss->statelessResume) {
+ PORT_Assert(ss->sec.ci.sid);
+ rv = tls13_RecoverWrappedSharedSecret(ss, ss->sec.ci.sid);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ SSL_AtomicIncrementLong(&ssl3stats->sch_sid_cache_not_ok);
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(ss->sec.ci.sid);
+ ss->sec.ci.sid = NULL;
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.cipher_suite = ss->sec.ci.sid->u.ssl3.cipherSuite;
+ rv = ssl3_SetupCipherSuite(ss, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
+ }
+ }
+
+ /* Derive the binder keys if any PSKs. */
+ if (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
+ /* If an External PSK specified a suite, use that. */
+ sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+ if (!ss->statelessResume &&
+ psk->type == ssl_psk_external &&
+ psk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
+ ss->ssl3.hs.cipher_suite = psk->zeroRttSuite;
+ }
+
+ rv = tls13_ComputeEarlySecretsWithPsk(ss);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_ImportDHEKeyShare(SECKEYPublicKey *peerKey,
+ PRUint8 *b, PRUint32 length,
+ SECKEYPublicKey *pubKey)
+{
+ SECStatus rv;
+ SECItem publicValue = { siBuffer, NULL, 0 };
+
+ publicValue.data = b;
+ publicValue.len = length;
+ if (!ssl_IsValidDHEShare(&pubKey->u.dh.prime, &publicValue)) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_DHE_KEY_SHARE);
+ return SECFailure;
+ }
+
+ peerKey->keyType = dhKey;
+ rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.prime,
+ &pubKey->u.dh.prime);
+ if (rv != SECSuccess)
+ return SECFailure;
+ rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.base,
+ &pubKey->u.dh.base);
+ if (rv != SECSuccess)
+ return SECFailure;
+ rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.dh.publicValue,
+ &publicValue);
+ if (rv != SECSuccess)
+ return SECFailure;
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_HandleKeyShare(sslSocket *ss,
+ TLS13KeyShareEntry *entry,
+ sslKeyPair *keyPair,
+ SSLHashType hash,
+ PK11SymKey **out)
+{
+ PORTCheapArenaPool arena;
+ SECKEYPublicKey *peerKey;
+ CK_MECHANISM_TYPE mechanism;
+ PRErrorCode errorCode;
+ PK11SymKey *key;
+ SECStatus rv;
+ int keySize = 0;
+
+ PORT_InitCheapArena(&arena, DER_DEFAULT_CHUNKSIZE);
+ peerKey = PORT_ArenaZNew(&arena.arena, SECKEYPublicKey);
+ if (peerKey == NULL) {
+ goto loser;
+ }
+ peerKey->arena = &arena.arena;
+ peerKey->pkcs11Slot = NULL;
+ peerKey->pkcs11ID = CK_INVALID_HANDLE;
+
+ switch (entry->group->keaType) {
+ case ssl_kea_ecdh:
+ rv = ssl_ImportECDHKeyShare(peerKey,
+ entry->key_exchange.data,
+ entry->key_exchange.len,
+ entry->group);
+ mechanism = CKM_ECDH1_DERIVE;
+ break;
+ case ssl_kea_dh:
+ rv = tls13_ImportDHEKeyShare(peerKey,
+ entry->key_exchange.data,
+ entry->key_exchange.len,
+ keyPair->pubKey);
+ mechanism = CKM_DH_PKCS_DERIVE;
+ keySize = peerKey->u.dh.publicValue.len;
+ break;
+ default:
+ PORT_Assert(0);
+ goto loser;
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ key = PK11_PubDeriveWithKDF(
+ keyPair->privKey, peerKey, PR_FALSE, NULL, NULL, mechanism,
+ CKM_HKDF_DERIVE, CKA_DERIVE, keySize, CKD_NULL, NULL, NULL);
+ if (!key) {
+ ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE);
+ goto loser;
+ }
+ *out = key;
+ PORT_DestroyCheapArena(&arena);
+ return SECSuccess;
+
+loser:
+ PORT_DestroyCheapArena(&arena);
+ errorCode = PORT_GetError(); /* don't overwrite the error code */
+ tls13_FatalError(ss, errorCode, illegal_parameter);
+ return SECFailure;
+}
+
+static PRBool
+tls13_UseServerSecret(sslSocket *ss, SSLSecretDirection direction)
+{
+ return ss->sec.isServer == (direction == ssl_secret_write);
+}
+
+static PK11SymKey **
+tls13_TrafficSecretRef(sslSocket *ss, SSLSecretDirection direction)
+{
+ if (tls13_UseServerSecret(ss, direction)) {
+ return &ss->ssl3.hs.serverTrafficSecret;
+ }
+ return &ss->ssl3.hs.clientTrafficSecret;
+}
+
+SECStatus
+tls13_UpdateTrafficKeys(sslSocket *ss, SSLSecretDirection direction)
+{
+ PK11SymKey **secret;
+ PK11SymKey *updatedSecret;
+ PRUint16 epoch;
+ SECStatus rv;
+
+ secret = tls13_TrafficSecretRef(ss, direction);
+ rv = tls13_HkdfExpandLabel(*secret, tls13_GetHash(ss),
+ NULL, 0,
+ kHkdfLabelTrafficUpdate,
+ strlen(kHkdfLabelTrafficUpdate),
+ tls13_GetHmacMechanism(ss),
+ tls13_GetHashSize(ss),
+ ss->protocolVariant,
+ &updatedSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ PK11_FreeSymKey(*secret);
+ *secret = updatedSecret;
+
+ ssl_GetSpecReadLock(ss);
+ if (direction == ssl_secret_read) {
+ epoch = ss->ssl3.crSpec->epoch;
+ } else {
+ epoch = ss->ssl3.cwSpec->epoch;
+ }
+ ssl_ReleaseSpecReadLock(ss);
+
+ if (epoch == PR_UINT16_MAX) {
+ /* Good chance that this is an overflow from too many updates. */
+ FATAL_ERROR(ss, SSL_ERROR_TOO_MANY_KEY_UPDATES, internal_error);
+ return SECFailure;
+ }
+ ++epoch;
+
+ if (ss->secretCallback) {
+ ss->secretCallback(ss->fd, epoch, direction, updatedSecret,
+ ss->secretCallbackArg);
+ }
+
+ rv = tls13_SetCipherSpec(ss, epoch, direction, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_SendKeyUpdate(sslSocket *ss, tls13KeyUpdateRequest request, PRBool buffer)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: %s send key update, response %s",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss),
+ (request == update_requested) ? "requested"
+ : "not requested"));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(!ss->sec.isServer || !ss->ssl3.clientCertRequested);
+
+ if (!tls13_IsPostHandshake(ss)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_LIBRARY_FAILURE,
+ idle_handshake);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Not supported. */
+ if (IS_DTLS(ss)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_key_update, 1);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+ rv = ssl3_AppendHandshakeNumber(ss, request, 1);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+
+ /* If we have been asked to buffer, then do so. This allows us to coalesce
+ * a KeyUpdate with a pending write. */
+ rv = ssl3_FlushHandshake(ss, buffer ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
+ if (rv != SECSuccess) {
+ goto loser; /* error code set by ssl3_FlushHandshake */
+ }
+ ssl_ReleaseXmitBufLock(ss);
+
+ rv = tls13_UpdateTrafficKeys(ss, ssl_secret_write);
+ if (rv != SECSuccess) {
+ goto loser; /* error code set by tls13_UpdateTrafficKeys */
+ }
+
+ return SECSuccess;
+
+loser:
+ ssl_ReleaseXmitBufLock(ss);
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_KeyUpdate(PRFileDesc *fd, PRBool requestUpdate)
+{
+ SECStatus rv;
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ if (!tls13_IsPostHandshake(ss)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ss->ssl3.clientCertRequested) {
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+
+ rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,
+ idle_handshake);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ ssl_GetSSL3HandshakeLock(ss);
+ rv = tls13_SendKeyUpdate(ss, requestUpdate ? update_requested : update_not_requested,
+ PR_FALSE /* don't buffer */);
+
+ /* Remember that we are the ones that initiated this KeyUpdate. */
+ if (rv == SECSuccess) {
+ ss->ssl3.peerRequestedKeyUpdate = PR_FALSE;
+ }
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ return rv;
+}
+
+/*
+ * enum {
+ * update_not_requested(0), update_requested(1), (255)
+ * } KeyUpdateRequest;
+ *
+ * struct {
+ * KeyUpdateRequest request_update;
+ * } KeyUpdate;
+ */
+static SECStatus
+tls13_HandleKeyUpdate(sslSocket *ss, PRUint8 *b, unsigned int length)
+{
+ SECStatus rv;
+ PRUint32 update;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: %s handle key update",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (!tls13_IsPostHandshake(ss)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE, unexpected_message);
+ return SECFailure;
+ }
+
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_KEY_UPDATE,
+ idle_handshake);
+ if (rv != SECSuccess) {
+ /* We should never be idle_handshake prior to firstHsDone. */
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &update, 1, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set already. */
+ }
+ if (length != 0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error);
+ return SECFailure;
+ }
+ if (!(update == update_requested ||
+ update == update_not_requested)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_UPDATE, decode_error);
+ return SECFailure;
+ }
+
+ rv = tls13_UpdateTrafficKeys(ss, ssl_secret_read);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set by tls13_UpdateTrafficKeys. */
+ }
+
+ if (update == update_requested) {
+ PRBool sendUpdate;
+ if (ss->ssl3.clientCertRequested) {
+ /* Post-handshake auth is in progress; defer sending a key update. */
+ ss->ssl3.keyUpdateDeferred = PR_TRUE;
+ ss->ssl3.deferredKeyUpdateRequest = update_not_requested;
+ sendUpdate = PR_FALSE;
+ } else if (ss->ssl3.peerRequestedKeyUpdate) {
+ /* Only send an update if we have sent with the current spec. This
+ * prevents us from being forced to crank forward pointlessly. */
+ ssl_GetSpecReadLock(ss);
+ sendUpdate = ss->ssl3.cwSpec->nextSeqNum > 0;
+ ssl_ReleaseSpecReadLock(ss);
+ } else {
+ sendUpdate = PR_TRUE;
+ }
+ if (sendUpdate) {
+ /* Respond immediately (don't buffer). */
+ rv = tls13_SendKeyUpdate(ss, update_not_requested, PR_FALSE);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error already set. */
+ }
+ }
+ ss->ssl3.peerRequestedKeyUpdate = PR_TRUE;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SendCertificateRequest(PRFileDesc *fd)
+{
+ SECStatus rv;
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ /* Not supported. */
+ if (IS_DTLS(ss)) {
+ PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
+ return SECFailure;
+ }
+
+ if (!tls13_IsPostHandshake(ss)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ if (ss->ssl3.clientCertRequested) {
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+
+ /* Disallow a CertificateRequest if this connection uses an external PSK. */
+ if (ss->sec.authType == ssl_auth_psk) {
+ PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
+ return SECFailure;
+ }
+
+ rv = TLS13_CHECK_HS_STATE(ss, SEC_ERROR_INVALID_ARGS,
+ idle_handshake);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_post_handshake_auth_xtn)) {
+ PORT_SetError(SSL_ERROR_MISSING_POST_HANDSHAKE_AUTH_EXTENSION);
+ return SECFailure;
+ }
+
+ ssl_GetSSL3HandshakeLock(ss);
+
+ rv = tls13_SendCertificateRequest(ss);
+ if (rv == SECSuccess) {
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_FlushHandshake(ss, 0);
+ ssl_ReleaseXmitBufLock(ss);
+ ss->ssl3.clientCertRequested = PR_TRUE;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ return rv;
+}
+
+SECStatus
+tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ if (ss->sec.isServer && ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) {
+ SSL_TRC(3, ("%d: TLS13[%d]: successfully decrypted handshake after "
+ "failed 0-RTT",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
+ }
+
+ /* TODO(ekr@rtfm.com): Would it be better to check all the states here? */
+ switch (ss->ssl3.hs.msg_type) {
+ case ssl_hs_certificate:
+ return tls13_HandleCertificate(ss, b, length);
+
+ case ssl_hs_certificate_request:
+ return tls13_HandleCertificateRequest(ss, b, length);
+
+ case ssl_hs_certificate_verify:
+ return tls13_HandleCertificateVerify(ss, b, length);
+
+ case ssl_hs_encrypted_extensions:
+ return tls13_HandleEncryptedExtensions(ss, b, length);
+
+ case ssl_hs_new_session_ticket:
+ return tls13_HandleNewSessionTicket(ss, b, length);
+
+ case ssl_hs_finished:
+ if (ss->sec.isServer) {
+ return tls13_ServerHandleFinished(ss, b, length);
+ } else {
+ return tls13_ClientHandleFinished(ss, b, length);
+ }
+
+ case ssl_hs_end_of_early_data:
+ return tls13_HandleEndOfEarlyData(ss, b, length);
+
+ case ssl_hs_key_update:
+ return tls13_HandleKeyUpdate(ss, b, length);
+
+ default:
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNKNOWN_HANDSHAKE, unexpected_message);
+ return SECFailure;
+ }
+
+ PORT_Assert(0); /* Unreached */
+ return SECFailure;
+}
+
+static SECStatus
+tls13_RecoverWrappedSharedSecret(sslSocket *ss, sslSessionID *sid)
+{
+ PK11SymKey *wrapKey; /* wrapping key */
+ SECItem wrappedMS = { siBuffer, NULL, 0 };
+ SSLHashType hashType;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: recovering static secret (%s)",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+
+ /* Now find the hash used as the PRF for the previous handshake. */
+ hashType = tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite);
+
+ /* If we are the server, we compute the wrapping key, but if we
+ * are the client, its coordinates are stored with the ticket. */
+ if (ss->sec.isServer) {
+ wrapKey = ssl3_GetWrappingKey(ss, NULL,
+ sid->u.ssl3.masterWrapMech,
+ ss->pkcs11PinArg);
+ } else {
+ PK11SlotInfo *slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
+ sid->u.ssl3.masterSlotID);
+ if (!slot)
+ return SECFailure;
+
+ wrapKey = PK11_GetWrapKey(slot,
+ sid->u.ssl3.masterWrapIndex,
+ sid->u.ssl3.masterWrapMech,
+ sid->u.ssl3.masterWrapSeries,
+ ss->pkcs11PinArg);
+ PK11_FreeSlot(slot);
+ }
+ if (!wrapKey) {
+ return SECFailure;
+ }
+
+ wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
+ wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len;
+
+ PK11SymKey *unwrappedPsk = ssl_unwrapSymKey(wrapKey, sid->u.ssl3.masterWrapMech,
+ NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
+ CKA_DERIVE, tls13_GetHashSizeForHash(hashType),
+ CKF_SIGN | CKF_VERIFY, ss->pkcs11PinArg);
+ PK11_FreeSymKey(wrapKey);
+ if (!unwrappedPsk) {
+ return SECFailure;
+ }
+ sslPsk *rpsk = tls13_MakePsk(unwrappedPsk, ssl_psk_resume, hashType, NULL);
+ if (!rpsk) {
+ PK11_FreeSymKey(unwrappedPsk);
+ return SECFailure;
+ }
+ if (sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) {
+ rpsk->maxEarlyData = sid->u.ssl3.locked.sessionTicket.max_early_data_size;
+ rpsk->zeroRttSuite = sid->u.ssl3.cipherSuite;
+ }
+ PRINT_KEY(50, (ss, "Recovered RMS", rpsk->key));
+ PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) ||
+ ((sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks))->type != ssl_psk_resume);
+
+ if (ss->sec.isServer) {
+ /* In server, we couldn't select the RPSK in the extension handler
+ * since it was not unwrapped yet. We're committed now, so select
+ * it and add it to the list (to ensure it is freed). */
+ ss->xtnData.selectedPsk = rpsk;
+ }
+ PR_APPEND_LINK(&rpsk->link, &ss->ssl3.hs.psks);
+
+ return SECSuccess;
+}
+
+/* Key Derivation Functions.
+ *
+ * 0
+ * |
+ * v
+ * PSK -> HKDF-Extract = Early Secret
+ * |
+ * +-----> Derive-Secret(., "ext binder" | "res binder", "")
+ * | = binder_key
+ * |
+ * +-----> Derive-Secret(., "c e traffic",
+ * | ClientHello)
+ * | = client_early_traffic_secret
+ * |
+ * +-----> Derive-Secret(., "e exp master",
+ * | ClientHello)
+ * | = early_exporter_secret
+ * v
+ * Derive-Secret(., "derived", "")
+ * |
+ * v
+ *(EC)DHE -> HKDF-Extract = Handshake Secret
+ * |
+ * +-----> Derive-Secret(., "c hs traffic",
+ * | ClientHello...ServerHello)
+ * | = client_handshake_traffic_secret
+ * |
+ * +-----> Derive-Secret(., "s hs traffic",
+ * | ClientHello...ServerHello)
+ * | = server_handshake_traffic_secret
+ * v
+ * Derive-Secret(., "derived", "")
+ * |
+ * v
+ * 0 -> HKDF-Extract = Master Secret
+ * |
+ * +-----> Derive-Secret(., "c ap traffic",
+ * | ClientHello...Server Finished)
+ * | = client_traffic_secret_0
+ * |
+ * +-----> Derive-Secret(., "s ap traffic",
+ * | ClientHello...Server Finished)
+ * | = server_traffic_secret_0
+ * |
+ * +-----> Derive-Secret(., "exp master",
+ * | ClientHello...Server Finished)
+ * | = exporter_secret
+ * |
+ * +-----> Derive-Secret(., "res master",
+ * ClientHello...Client Finished)
+ * = resumption_master_secret
+ *
+ */
+static SECStatus
+tls13_ComputeEarlySecretsWithPsk(sslSocket *ss)
+{
+ SECStatus rv;
+
+ SSL_TRC(5, ("%d: TLS13[%d]: compute early secrets (%s)",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+
+ PORT_Assert(!ss->ssl3.hs.currentSecret);
+ sslPsk *psk = NULL;
+
+ if (ss->sec.isServer) {
+ psk = ss->xtnData.selectedPsk;
+ } else {
+ /* Client to use the first PSK for early secrets. */
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
+ psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+ }
+ PORT_Assert(psk && psk->key);
+ PORT_Assert(psk->hash != ssl_hash_none);
+
+ PK11SymKey *earlySecret = NULL;
+ rv = tls13_HkdfExtract(NULL, psk->key, psk->hash, &earlySecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* No longer need the raw input key */
+ PK11_FreeSymKey(psk->key);
+ psk->key = NULL;
+ const char *label = (psk->type == ssl_psk_resume) ? kHkdfLabelResPskBinderKey : kHkdfLabelExtPskBinderKey;
+ rv = tls13_DeriveSecretNullHash(ss, earlySecret,
+ label, strlen(label),
+ &psk->binderKey, psk->hash);
+ if (rv != SECSuccess) {
+ PK11_FreeSymKey(earlySecret);
+ return SECFailure;
+ }
+ ss->ssl3.hs.currentSecret = earlySecret;
+
+ return SECSuccess;
+}
+
+/* This derives the early traffic and early exporter secrets. */
+static SECStatus
+tls13_DeriveEarlySecrets(sslSocket *ss)
+{
+ SECStatus rv;
+ PORT_Assert(ss->ssl3.hs.currentSecret);
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelClient,
+ kHkdfLabelEarlyTrafficSecret,
+ keylogLabelClientEarlyTrafficSecret,
+ &ss->ssl3.hs.clientEarlyTrafficSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->secretCallback) {
+ ss->secretCallback(ss->fd, (PRUint16)TrafficKeyEarlyApplicationData,
+ ss->sec.isServer ? ssl_secret_read : ssl_secret_write,
+ ss->ssl3.hs.clientEarlyTrafficSecret,
+ ss->secretCallbackArg);
+ }
+
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ NULL, kHkdfLabelEarlyExporterSecret,
+ keylogLabelEarlyExporterSecret,
+ &ss->ssl3.hs.earlyExporterSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_ComputeHandshakeSecret(sslSocket *ss)
+{
+ SECStatus rv;
+ PK11SymKey *derivedSecret = NULL;
+ PK11SymKey *newSecret = NULL;
+ SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secret (%s)",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+
+ /* If no PSK, generate the default early secret. */
+ if (!ss->ssl3.hs.currentSecret) {
+ PORT_Assert(!ss->xtnData.selectedPsk);
+ rv = tls13_HkdfExtract(NULL, NULL,
+ tls13_GetHash(ss), &ss->ssl3.hs.currentSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ PORT_Assert(ss->ssl3.hs.currentSecret);
+ PORT_Assert(ss->ssl3.hs.dheSecret);
+
+ /* Derive-Secret(., "derived", "") */
+ rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelDerivedSecret,
+ strlen(kHkdfLabelDerivedSecret),
+ &derivedSecret, tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+
+ /* HKDF-Extract(ECDHE, .) = Handshake Secret */
+ rv = tls13_HkdfExtract(derivedSecret, ss->ssl3.hs.dheSecret,
+ tls13_GetHash(ss), &newSecret);
+ PK11_FreeSymKey(derivedSecret);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+
+ PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
+ ss->ssl3.hs.currentSecret = newSecret;
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_ComputeHandshakeSecrets(sslSocket *ss)
+{
+ SECStatus rv;
+ PK11SymKey *derivedSecret = NULL;
+ PK11SymKey *newSecret = NULL;
+
+ PK11_FreeSymKey(ss->ssl3.hs.dheSecret);
+ ss->ssl3.hs.dheSecret = NULL;
+
+ SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secrets (%s)",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+
+ /* Now compute |*HsTrafficSecret| */
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelClient,
+ kHkdfLabelHandshakeTrafficSecret,
+ keylogLabelClientHsTrafficSecret,
+ &ss->ssl3.hs.clientHsTrafficSecret);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelServer,
+ kHkdfLabelHandshakeTrafficSecret,
+ keylogLabelServerHsTrafficSecret,
+ &ss->ssl3.hs.serverHsTrafficSecret);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+
+ if (ss->secretCallback) {
+ SSLSecretDirection dir =
+ ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
+ ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
+ ss->ssl3.hs.clientHsTrafficSecret,
+ ss->secretCallbackArg);
+ dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
+ ss->secretCallback(ss->fd, (PRUint16)TrafficKeyHandshake, dir,
+ ss->ssl3.hs.serverHsTrafficSecret,
+ ss->secretCallbackArg);
+ }
+
+ SSL_TRC(5, ("%d: TLS13[%d]: compute master secret (%s)",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+
+ /* Crank HKDF forward to make master secret, which we
+ * stuff in current secret. */
+ rv = tls13_DeriveSecretNullHash(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelDerivedSecret,
+ strlen(kHkdfLabelDerivedSecret),
+ &derivedSecret, tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return rv;
+ }
+ rv = tls13_HkdfExtract(derivedSecret,
+ NULL,
+ tls13_GetHash(ss),
+ &newSecret);
+ PK11_FreeSymKey(derivedSecret);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
+ ss->ssl3.hs.currentSecret = newSecret;
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_ComputeApplicationSecrets(sslSocket *ss)
+{
+ SECStatus rv;
+
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelClient,
+ kHkdfLabelApplicationTrafficSecret,
+ keylogLabelClientTrafficSecret,
+ &ss->ssl3.hs.clientTrafficSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ kHkdfLabelServer,
+ kHkdfLabelApplicationTrafficSecret,
+ keylogLabelServerTrafficSecret,
+ &ss->ssl3.hs.serverTrafficSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->secretCallback) {
+ SSLSecretDirection dir =
+ ss->sec.isServer ? ssl_secret_read : ssl_secret_write;
+ ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
+ dir, ss->ssl3.hs.clientTrafficSecret,
+ ss->secretCallbackArg);
+ dir = ss->sec.isServer ? ssl_secret_write : ssl_secret_read;
+ ss->secretCallback(ss->fd, (PRUint16)TrafficKeyApplicationData,
+ dir, ss->ssl3.hs.serverTrafficSecret,
+ ss->secretCallbackArg);
+ }
+
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ NULL, kHkdfLabelExporterMasterSecret,
+ keylogLabelExporterSecret,
+ &ss->ssl3.hs.exporterSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_ComputeFinalSecrets(sslSocket *ss)
+{
+ SECStatus rv;
+
+ PORT_Assert(!ss->ssl3.crSpec->masterSecret);
+ PORT_Assert(!ss->ssl3.cwSpec->masterSecret);
+ PORT_Assert(ss->ssl3.hs.currentSecret);
+ rv = tls13_DeriveSecretWrap(ss, ss->ssl3.hs.currentSecret,
+ NULL, kHkdfLabelResumptionMasterSecret,
+ NULL,
+ &ss->ssl3.hs.resumptionMasterSecret);
+ PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
+ ss->ssl3.hs.currentSecret = NULL;
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+static void
+tls13_RestoreCipherInfo(sslSocket *ss, sslSessionID *sid)
+{
+ /* Set these to match the cached value.
+ * TODO(ekr@rtfm.com): Make a version with the "true" values.
+ * Bug 1256137.
+ */
+ ss->sec.authType = sid->authType;
+ ss->sec.authKeyBits = sid->authKeyBits;
+ ss->sec.originalKeaGroup = ssl_LookupNamedGroup(sid->keaGroup);
+ ss->sec.signatureScheme = sid->sigScheme;
+}
+
+/* Check whether resumption-PSK is allowed. */
+static PRBool
+tls13_CanResume(sslSocket *ss, const sslSessionID *sid)
+{
+ const sslServerCert *sc;
+
+ if (!sid) {
+ return PR_FALSE;
+ }
+
+ if (sid->version != ss->version) {
+ return PR_FALSE;
+ }
+
+#ifdef UNSAFE_FUZZER_MODE
+ /* When fuzzing, sid could contain garbage that will crash tls13_GetHashForCipherSuite.
+ * Do a direct comparison of cipher suites. This makes us refuse to resume when the
+ * protocol allows it, but resumption is discretionary anyway. */
+ if (sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite) {
+#else
+ if (tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite) != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
+#endif
+ return PR_FALSE;
+ }
+
+ /* Server sids don't remember the server cert we previously sent, but they
+ * do remember the type of certificate we originally used, so we can locate
+ * it again, provided that the current ssl socket has had its server certs
+ * configured the same as the previous one. */
+ sc = ssl_FindServerCert(ss, sid->authType, sid->namedCurve);
+ if (!sc || !sc->serverCert) {
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+static PRBool
+tls13_CanNegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
+{
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
+ sslPsk *psk = ss->xtnData.selectedPsk;
+
+ if (!ss->opt.enable0RttData) {
+ return PR_FALSE;
+ }
+ if (!psk) {
+ return PR_FALSE;
+ }
+ if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
+ return PR_FALSE;
+ }
+ if (!psk->maxEarlyData) {
+ return PR_FALSE;
+ }
+ if (ss->ssl3.hs.cipher_suite != psk->zeroRttSuite) {
+ return PR_FALSE;
+ }
+ if (psk->type == ssl_psk_resume) {
+ if (!sid) {
+ return PR_FALSE;
+ }
+ PORT_Assert(sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data);
+ PORT_Assert(ss->statelessResume);
+ if (!ss->statelessResume) {
+ return PR_FALSE;
+ }
+ if (SECITEM_CompareItem(&ss->xtnData.nextProto,
+ &sid->u.ssl3.alpnSelection) != 0) {
+ return PR_FALSE;
+ }
+ } else if (psk->type != ssl_psk_external) {
+ PORT_Assert(0);
+ return PR_FALSE;
+ }
+
+ if (tls13_IsReplay(ss, sid)) {
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+/* Called from tls13_HandleClientHelloPart2 to update the state of 0-RTT handling.
+ *
+ * 0-RTT is only permitted if:
+ * 1. The early data extension was present.
+ * 2. We are resuming a session.
+ * 3. The 0-RTT option is set.
+ * 4. The ticket allowed 0-RTT.
+ * 5. We negotiated the same ALPN value as in the ticket.
+ */
+static void
+tls13_NegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid)
+{
+ SSL_TRC(3, ("%d: TLS13[%d]: negotiate 0-RTT %p",
+ SSL_GETPID(), ss->fd, sid));
+
+ /* tls13_ServerHandleEarlyDataXtn sets this to ssl_0rtt_sent, so this will
+ * be ssl_0rtt_none unless early_data is present. */
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
+ return;
+ }
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored) {
+ /* HelloRetryRequest causes 0-RTT to be ignored. On the second
+ * ClientHello, reset the ignore state so that decryption failure is
+ * handled normally. */
+ if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr) {
+ PORT_Assert(ss->ssl3.hs.helloRetry);
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_none;
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
+ } else {
+ SSL_TRC(3, ("%d: TLS13[%d]: application ignored 0-RTT",
+ SSL_GETPID(), ss->fd));
+ }
+ return;
+ }
+
+ if (!tls13_CanNegotiateZeroRtt(ss, sid)) {
+ SSL_TRC(3, ("%d: TLS13[%d]: ignore 0-RTT", SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
+ return;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: enable 0-RTT", SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->xtnData.selectedPsk);
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none;
+ ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_0rtt_cipher_suite;
+}
+
+/* Check if the offered group is acceptable. */
+static PRBool
+tls13_isGroupAcceptable(const sslNamedGroupDef *offered,
+ const sslNamedGroupDef *preferredGroup)
+{
+ /* We accept epsilon (e) bits around the offered group size. */
+ const unsigned int e = 2;
+
+ PORT_Assert(offered);
+ PORT_Assert(preferredGroup);
+
+ if (offered->bits >= preferredGroup->bits - e &&
+ offered->bits <= preferredGroup->bits + e) {
+ return PR_TRUE;
+ }
+
+ return PR_FALSE;
+}
+
+/* Find remote key share for given group and return it.
+ * Returns NULL if no key share is found. */
+static TLS13KeyShareEntry *
+tls13_FindKeyShareEntry(sslSocket *ss, const sslNamedGroupDef *group)
+{
+ PRCList *cur_p = PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
+ while (cur_p != &ss->xtnData.remoteKeyShares) {
+ TLS13KeyShareEntry *offer = (TLS13KeyShareEntry *)cur_p;
+ if (offer->group == group) {
+ return offer;
+ }
+ cur_p = PR_NEXT_LINK(cur_p);
+ }
+ return NULL;
+}
+
+static SECStatus
+tls13_NegotiateKeyExchange(sslSocket *ss,
+ const sslNamedGroupDef **requestedGroup,
+ TLS13KeyShareEntry **clientShare)
+{
+ unsigned int index;
+ TLS13KeyShareEntry *entry = NULL;
+ const sslNamedGroupDef *preferredGroup = NULL;
+
+ /* We insist on DHE. */
+ if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
+ if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_psk_key_exchange_modes_xtn)) {
+ FATAL_ERROR(ss, SSL_ERROR_MISSING_PSK_KEY_EXCHANGE_MODES,
+ missing_extension);
+ return SECFailure;
+ }
+ /* Since the server insists on DHE to provide forward secracy, for
+ * every other PskKem value but DHE stateless resumption is disabled,
+ * this includes other specified and GREASE values. */
+ if (!memchr(ss->xtnData.psk_ke_modes.data, tls13_psk_dh_ke,
+ ss->xtnData.psk_ke_modes.len)) {
+ SSL_TRC(3, ("%d: TLS13[%d]: client offered PSK without DH",
+ SSL_GETPID(), ss->fd));
+ ss->statelessResume = PR_FALSE;
+ }
+ }
+
+ /* Now figure out which key share we like the best out of the
+ * mutually supported groups, regardless of what the client offered
+ * for key shares.
+ */
+ if (!ssl3_ExtensionNegotiated(ss, ssl_supported_groups_xtn)) {
+ FATAL_ERROR(ss, SSL_ERROR_MISSING_SUPPORTED_GROUPS_EXTENSION,
+ missing_extension);
+ return SECFailure;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: selected KE = %s", SSL_GETPID(),
+ ss->fd, ss->statelessResume || ss->xtnData.selectedPsk ? "PSK + (EC)DHE" : "(EC)DHE"));
+
+ /* Find the preferred group and an according client key share available. */
+ for (index = 0; index < SSL_NAMED_GROUP_COUNT; ++index) {
+ /* Continue to the next group if this one is not enabled. */
+ if (!ss->namedGroupPreferences[index]) {
+ /* There's a gap in the preferred groups list. Assume this is a group
+ * that's not supported by the client but preferred by the server. */
+ if (preferredGroup) {
+ entry = NULL;
+ break;
+ }
+ continue;
+ }
+
+ /* Check if the client sent a key share for this group. */
+ entry = tls13_FindKeyShareEntry(ss, ss->namedGroupPreferences[index]);
+
+ if (preferredGroup) {
+ /* We already found our preferred group but the group didn't have a share. */
+ if (entry) {
+ /* The client sent a key share with group ss->namedGroupPreferences[index] */
+ if (tls13_isGroupAcceptable(ss->namedGroupPreferences[index],
+ preferredGroup)) {
+ /* This is not the preferred group, but it's acceptable */
+ preferredGroup = ss->namedGroupPreferences[index];
+ } else {
+ /* The proposed group is not acceptable. */
+ entry = NULL;
+ }
+ }
+ break;
+ } else {
+ /* The first enabled group is the preferred group. */
+ preferredGroup = ss->namedGroupPreferences[index];
+ if (entry) {
+ break;
+ }
+ }
+ }
+
+ if (!preferredGroup) {
+ FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, handshake_failure);
+ return SECFailure;
+ }
+ SSL_TRC(3, ("%d: TLS13[%d]: group = %d", SSL_GETPID(), ss->fd,
+ preferredGroup->name));
+
+ /* Either provide a share, or provide a group that should be requested in a
+ * HelloRetryRequest, but not both. */
+ if (entry) {
+ PORT_Assert(preferredGroup == entry->group);
+ *clientShare = entry;
+ *requestedGroup = NULL;
+ } else {
+ *clientShare = NULL;
+ *requestedGroup = preferredGroup;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+tls13_SelectServerCert(sslSocket *ss)
+{
+ PRCList *cursor;
+ SECStatus rv;
+
+ if (!ssl3_ExtensionNegotiated(ss, ssl_signature_algorithms_xtn)) {
+ FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
+ missing_extension);
+ return SECFailure;
+ }
+
+ /* This picks the first certificate that has:
+ * a) the right authentication method, and
+ * b) the right named curve (EC only)
+ *
+ * We might want to do some sort of ranking here later. For now, it's all
+ * based on what order they are configured in. */
+ for (cursor = PR_NEXT_LINK(&ss->serverCerts);
+ cursor != &ss->serverCerts;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslServerCert *cert = (sslServerCert *)cursor;
+
+ if (SSL_CERT_IS_ONLY(cert, ssl_auth_rsa_decrypt)) {
+ continue;
+ }
+
+ rv = ssl_PickSignatureScheme(ss,
+ cert->serverCert,
+ cert->serverKeyPair->pubKey,
+ cert->serverKeyPair->privKey,
+ ss->xtnData.sigSchemes,
+ ss->xtnData.numSigSchemes,
+ PR_FALSE,
+ &ss->ssl3.hs.signatureScheme);
+ if (rv == SECSuccess) {
+ /* Found one. */
+ ss->sec.serverCert = cert;
+
+ /* If we can use a delegated credential (DC) for authentication in
+ * the current handshake, then commit to using it now. We'll send a
+ * DC as an extension and use the DC private key to sign the
+ * handshake.
+ *
+ * This sets the signature scheme to be the signature scheme
+ * indicated by the DC.
+ */
+ rv = tls13_MaybeSetDelegatedCredential(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Failure indicates an internal error. */
+ }
+
+ ss->sec.authType = ss->ssl3.hs.kea_def_mutable.authKeyType =
+ ssl_SignatureSchemeToAuthType(ss->ssl3.hs.signatureScheme);
+ ss->sec.authKeyBits = cert->serverKeyBits;
+ return SECSuccess;
+ }
+ }
+
+ FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM,
+ handshake_failure);
+ return SECFailure;
+}
+
+/* Note: |requestedGroup| is non-NULL when we send a key_share extension. */
+static SECStatus
+tls13_MaybeSendHelloRetry(sslSocket *ss, const sslNamedGroupDef *requestedGroup,
+ PRBool *hrrSent)
+{
+ SSLHelloRetryRequestAction action = ssl_hello_retry_accept;
+ PRUint8 token[256] = { 0 };
+ unsigned int tokenLen = 0;
+ SECStatus rv;
+
+ if (ss->hrrCallback) {
+ action = ss->hrrCallback(!ss->ssl3.hs.helloRetry,
+ ss->xtnData.applicationToken.data,
+ ss->xtnData.applicationToken.len,
+ token, &tokenLen, sizeof(token),
+ ss->hrrCallbackArg);
+ }
+
+ /* These use SSL3_SendAlert directly to avoid an assertion in
+ * tls13_FatalError(), which is ordinarily OK. */
+ if (action == ssl_hello_retry_request && ss->ssl3.hs.helloRetry) {
+ (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
+ PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
+ return SECFailure;
+ }
+
+ if (action != ssl_hello_retry_request && tokenLen) {
+ (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
+ PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
+ return SECFailure;
+ }
+
+ if (tokenLen > sizeof(token)) {
+ (void)SSL3_SendAlert(ss, alert_fatal, internal_error);
+ PORT_SetError(SSL_ERROR_APP_CALLBACK_ERROR);
+ return SECFailure;
+ }
+
+ if (action == ssl_hello_retry_fail) {
+ FATAL_ERROR(ss, SSL_ERROR_APPLICATION_ABORT, handshake_failure);
+ return SECFailure;
+ }
+
+ if (action == ssl_hello_retry_reject_0rtt) {
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
+ }
+
+ if (!requestedGroup && action != ssl_hello_retry_request) {
+ return SECSuccess;
+ }
+
+ rv = tls13_SendHelloRetryRequest(ss, requestedGroup, token, tokenLen);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+
+ /* We may have received ECH, but have to start over with CH2. */
+ ss->ssl3.hs.echAccepted = PR_FALSE;
+ PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
+ ss->ssl3.hs.echHpkeCtx = NULL;
+
+ *hrrSent = PR_TRUE;
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_NegotiateAuthentication(sslSocket *ss)
+{
+ if (ss->statelessResume) {
+ SSL_TRC(3, ("%d: TLS13[%d]: selected resumption PSK authentication",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.signatureScheme = ssl_sig_none;
+ ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
+ /* Overwritten by tls13_RestoreCipherInfo. */
+ ss->sec.authType = ssl_auth_psk;
+ return SECSuccess;
+ } else if (ss->xtnData.selectedPsk) {
+ /* If the EPSK doesn't specify a suite, use what was negotiated.
+ * Else, only use the EPSK if we negotiated that suite. */
+ if (ss->xtnData.selectedPsk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL ||
+ ss->ssl3.hs.cipher_suite == ss->xtnData.selectedPsk->zeroRttSuite) {
+ SSL_TRC(3, ("%d: TLS13[%d]: selected external PSK authentication",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.signatureScheme = ssl_sig_none;
+ ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
+ ss->sec.authType = ssl_auth_psk;
+ return SECSuccess;
+ }
+ }
+
+ /* If there were PSKs, they are no longer needed. */
+ if (ss->xtnData.selectedPsk) {
+ tls13_DestroyPskList(&ss->ssl3.hs.psks);
+ ss->xtnData.selectedPsk = NULL;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: selected certificate authentication",
+ SSL_GETPID(), ss->fd));
+ SECStatus rv = tls13_SelectServerCert(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+/* Called from ssl3_HandleClientHello after we have parsed the
+ * ClientHello and are sure that we are going to do TLS 1.3
+ * or fail. */
+SECStatus
+tls13_HandleClientHelloPart2(sslSocket *ss,
+ const SECItem *suites,
+ sslSessionID *sid,
+ const PRUint8 *msg,
+ unsigned int len)
+{
+ SECStatus rv;
+ SSL3Statistics *ssl3stats = SSL_GetStatistics();
+ const sslNamedGroupDef *requestedGroup = NULL;
+ TLS13KeyShareEntry *clientShare = NULL;
+ ssl3CipherSuite previousCipherSuite = 0;
+ const sslNamedGroupDef *previousGroup = NULL;
+ PRBool hrr = PR_FALSE;
+ PRBool previousOfferedEch;
+
+ /* If the legacy_version field is set to 0x300 or smaller,
+ * reject the connection with protocol_version alert. */
+ if (ss->clientHelloVersion <= SSL_LIBRARY_VERSION_3_0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, protocol_version);
+ goto loser;
+ }
+
+ ss->ssl3.hs.endOfFlight = PR_TRUE;
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
+ }
+
+ /* Negotiate cipher suite. */
+ rv = ssl3_NegotiateCipherSuite(ss, suites, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
+ goto loser;
+ }
+
+ /* If we are going around again, then we should make sure that the cipher
+ * suite selection doesn't change. That's a sign of client shennanigans. */
+ if (ss->ssl3.hs.helloRetry) {
+
+ /* Update sequence numbers before checking the cookie so that any alerts
+ * we generate are sent with the right sequence numbers. */
+ if (IS_DTLS(ss)) {
+ /* Count the first ClientHello and the HelloRetryRequest. */
+ ss->ssl3.hs.sendMessageSeq = 1;
+ ss->ssl3.hs.recvMessageSeq = 1;
+ ssl_GetSpecWriteLock(ss);
+ /* Increase the write sequence number. The read sequence number
+ * will be reset after this to early data or handshake. */
+ ss->ssl3.cwSpec->nextSeqNum = 1;
+ ssl_ReleaseSpecWriteLock(ss);
+ }
+
+ if (!ssl3_ExtensionNegotiated(ss, ssl_tls13_cookie_xtn) ||
+ !ss->xtnData.cookie.len) {
+ FATAL_ERROR(ss, SSL_ERROR_MISSING_COOKIE_EXTENSION,
+ missing_extension);
+ goto loser;
+ }
+ PRINT_BUF(50, (ss, "Client sent cookie",
+ ss->xtnData.cookie.data, ss->xtnData.cookie.len));
+
+ rv = tls13_HandleHrrCookie(ss, ss->xtnData.cookie.data,
+ ss->xtnData.cookie.len,
+ &previousCipherSuite,
+ &previousGroup,
+ &previousOfferedEch, NULL, PR_TRUE);
+
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO, illegal_parameter);
+ goto loser;
+ }
+ }
+
+ /* Now merge the ClientHello into the hash state. */
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_client_hello, msg, len);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+
+ /* Now create a synthetic kea_def that we can tweak. */
+ ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
+ ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
+
+ /* Note: We call this quite a bit earlier than with TLS 1.2 and
+ * before. */
+ rv = ssl3_ServerCallSNICallback(ss);
+ if (rv != SECSuccess) {
+ goto loser; /* An alert has already been sent. */
+ }
+
+ /* Check if we could in principle resume. */
+ if (ss->statelessResume) {
+ PORT_Assert(sid);
+ if (!sid) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ if (!tls13_CanResume(ss, sid)) {
+ ss->statelessResume = PR_FALSE;
+ }
+ }
+
+ /* Select key exchange. */
+ rv = tls13_NegotiateKeyExchange(ss, &requestedGroup, &clientShare);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* We should get either one of these, but not both. */
+ PORT_Assert((requestedGroup && !clientShare) ||
+ (!requestedGroup && clientShare));
+
+ /* After HelloRetryRequest, check consistency of cipher and group. */
+ if (ss->ssl3.hs.helloRetry) {
+ PORT_Assert(previousCipherSuite);
+ if (ss->ssl3.hs.cipher_suite != previousCipherSuite) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
+ illegal_parameter);
+ goto loser;
+ }
+ if (!clientShare) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
+ illegal_parameter);
+ goto loser;
+ }
+
+ /* CH1/CH2 must either both include ECH, or both exclude it. */
+ if (previousOfferedEch != (ss->xtnData.ech != NULL)) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
+ previousOfferedEch ? missing_extension : illegal_parameter);
+ goto loser;
+ }
+
+ /* If we requested a new key share, check that the client provided just
+ * one of the right type. */
+ if (previousGroup) {
+ if (PR_PREV_LINK(&ss->xtnData.remoteKeyShares) !=
+ PR_NEXT_LINK(&ss->xtnData.remoteKeyShares)) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
+ illegal_parameter);
+ goto loser;
+ }
+ if (clientShare->group != previousGroup) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
+ illegal_parameter);
+ goto loser;
+ }
+ }
+ }
+
+ rv = tls13_MaybeSendHelloRetry(ss, requestedGroup, &hrr);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (hrr) {
+ if (sid) { /* Free the sid. */
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ }
+ PORT_Assert(ss->ssl3.hs.helloRetry);
+ return SECSuccess;
+ }
+
+ /* Select the authentication (this is also handshake shape). */
+ rv = tls13_NegotiateAuthentication(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (ss->sec.authType == ssl_auth_psk) {
+ if (ss->statelessResume) {
+ /* We are now committed to trying to resume. */
+ PORT_Assert(sid);
+ /* Check that the negotiated SNI and the cached SNI match. */
+ if (SECITEM_CompareItem(&sid->u.ssl3.srvName,
+ &ss->ssl3.hs.srvVirtName) != SECEqual) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO,
+ handshake_failure);
+ goto loser;
+ }
+
+ ss->sec.serverCert = ssl_FindServerCert(ss, sid->authType,
+ sid->namedCurve);
+ PORT_Assert(ss->sec.serverCert);
+
+ rv = tls13_RecoverWrappedSharedSecret(ss, sid);
+ if (rv != SECSuccess) {
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+ tls13_RestoreCipherInfo(ss, sid);
+
+ ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
+ if (sid->peerCert != NULL) {
+ ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
+ }
+ } else if (sid) {
+ /* We should never have a SID in the non-resumption case. */
+ PORT_Assert(0);
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ sid = NULL;
+ }
+ ssl3_RegisterExtensionSender(
+ ss, &ss->xtnData,
+ ssl_tls13_pre_shared_key_xtn, tls13_ServerSendPreSharedKeyXtn);
+ tls13_NegotiateZeroRtt(ss, sid);
+
+ rv = tls13_ComputeEarlySecretsWithPsk(ss);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ } else {
+ if (sid) { /* we had a sid, but it's no longer valid, free it */
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ sid = NULL;
+ }
+ tls13_NegotiateZeroRtt(ss, NULL);
+ }
+
+ if (ss->statelessResume) {
+ PORT_Assert(ss->xtnData.selectedPsk);
+ PORT_Assert(ss->ssl3.hs.kea_def_mutable.authKeyType == ssl_auth_psk);
+ }
+
+ /* Now that we have the binder key, check the binder. */
+ if (ss->xtnData.selectedPsk) {
+ SSL3Hashes hashes;
+ PORT_Assert(ss->ssl3.hs.messages.len > ss->xtnData.pskBindersLen);
+ rv = tls13_ComputePskBinderHash(
+ ss,
+ ss->ssl3.hs.messages.buf,
+ ss->ssl3.hs.messages.len - ss->xtnData.pskBindersLen,
+ &hashes, tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+
+ PORT_Assert(ss->xtnData.selectedPsk->hash == tls13_GetHash(ss));
+ PORT_Assert(ss->ssl3.hs.suite_def);
+ rv = tls13_VerifyFinished(ss, ssl_hs_client_hello,
+ ss->xtnData.selectedPsk->binderKey,
+ ss->xtnData.pskBinder.data,
+ ss->xtnData.pskBinder.len,
+ &hashes);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* This needs to go after we verify the psk binder. */
+ rv = ssl3_InitHandshakeHashes(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* If this is TLS 1.3 we are expecting a ClientKeyShare
+ * extension. Missing/absent extension cause failure
+ * below. */
+ rv = tls13_HandleClientKeyShare(ss, clientShare);
+ if (rv != SECSuccess) {
+ goto loser; /* An alert was sent already. */
+ }
+
+ /* From this point we are either committed to resumption, or not. */
+ if (ss->statelessResume) {
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_hits);
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_stateless_resumes);
+ } else {
+ if (sid) {
+ /* We had a sid, but it's no longer valid, free it. */
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok);
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ } else if (!ss->xtnData.selectedPsk) {
+ SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_misses);
+ }
+
+ sid = ssl3_NewSessionID(ss, PR_TRUE);
+ if (!sid) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+ }
+ /* Take ownership of the session. */
+ ss->sec.ci.sid = sid;
+ sid = NULL;
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ rv = tls13_DeriveEarlySecrets(ss);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = tls13_SendServerHelloSequence(ss);
+ ssl_ReleaseXmitBufLock(ss);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), handshake_failure);
+ return SECFailure;
+ }
+
+ /* We're done with PSKs */
+ tls13_DestroyPskList(&ss->ssl3.hs.psks);
+ ss->xtnData.selectedPsk = NULL;
+
+ return SECSuccess;
+
+loser:
+ if (sid) {
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(sid);
+ }
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_HelloRetryRequestCallback(PRFileDesc *fd,
+ SSLHelloRetryRequestCallback cb, void *arg)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure; /* Code already set. */
+ }
+
+ ss->hrrCallback = cb;
+ ss->hrrCallbackArg = arg;
+ return SECSuccess;
+}
+
+/*
+ * struct {
+ * ProtocolVersion server_version;
+ * CipherSuite cipher_suite;
+ * Extension extensions<2..2^16-1>;
+ * } HelloRetryRequest;
+ *
+ * Note: this function takes an empty buffer and returns
+ * a non-empty one on success, in which case the caller must
+ * eventually clean up.
+ */
+SECStatus
+tls13_ConstructHelloRetryRequest(sslSocket *ss,
+ ssl3CipherSuite cipherSuite,
+ const sslNamedGroupDef *selectedGroup,
+ PRUint8 *cookie, unsigned int cookieLen,
+ const PRUint8 *cookieGreaseEchSignal,
+ sslBuffer *buffer)
+{
+ SECStatus rv;
+ sslBuffer extensionsBuf = SSL_BUFFER_EMPTY;
+ PORT_Assert(buffer->len == 0);
+
+ /* Note: cookie is pointing to a stack variable, so is only valid
+ * now. */
+ ss->xtnData.selectedGroup = selectedGroup;
+ ss->xtnData.cookie.data = cookie;
+ ss->xtnData.cookie.len = cookieLen;
+
+ /* Set restored ss->ssl3.hs.greaseEchBuf value for ECH HRR extension
+ * reconstruction. */
+ if (cookieGreaseEchSignal) {
+ PORT_Assert(!ss->ssl3.hs.greaseEchBuf.len);
+ rv = sslBuffer_Append(&ss->ssl3.hs.greaseEchBuf,
+ cookieGreaseEchSignal,
+ TLS13_ECH_SIGNAL_LEN);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ rv = ssl_ConstructExtensions(ss, &extensionsBuf,
+ ssl_hs_hello_retry_request);
+ /* Reset ss->ssl3.hs.greaseEchBuf if it was changed. */
+ if (cookieGreaseEchSignal) {
+ sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* These extensions can't be empty. */
+ PORT_Assert(SSL_BUFFER_LEN(&extensionsBuf) > 0);
+
+ /* Clean up cookie so we're not pointing at random memory. */
+ ss->xtnData.cookie.data = NULL;
+ ss->xtnData.cookie.len = 0;
+
+ rv = ssl_ConstructServerHello(ss, PR_TRUE, &extensionsBuf, buffer);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ sslBuffer_Clear(&extensionsBuf);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&extensionsBuf);
+ sslBuffer_Clear(buffer);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_SendHelloRetryRequest(sslSocket *ss,
+ const sslNamedGroupDef *requestedGroup,
+ const PRUint8 *appToken, unsigned int appTokenLen)
+{
+ SECStatus rv;
+ unsigned int cookieLen;
+ PRUint8 cookie[1024];
+ sslBuffer messageBuf = SSL_BUFFER_EMPTY;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send hello retry request handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ /* If an ECH backend or shared-mode server accepted ECH when offered,
+ * the HRR extension's payload must be set to 8 zero bytes, these are
+ * overwritten with the accept_confirmation value after the handshake
+ * transcript calculation.
+ * If a client-facing or shared-mode server did not accept ECH when offered
+ * OR if ECH GREASE is enabled on the server and a ECH extension was
+ * received, a 8 byte random value is set as the extension's payload
+ * [draft-ietf-tls-esni-14, Section 7].
+ *
+ * The (temporary) payload is written to the extension in tls13exthandle.c/
+ * tls13_ServerSendHrrEchXtn(). */
+ if (ss->xtnData.ech) {
+ PRUint8 echGreaseRaw[TLS13_ECH_SIGNAL_LEN] = { 0 };
+ if (!(ss->ssl3.hs.echAccepted ||
+ (ss->opt.enableTls13BackendEch &&
+ ss->xtnData.ech &&
+ ss->xtnData.ech->receivedInnerXtn))) {
+ rv = PK11_GenerateRandom(echGreaseRaw, TLS13_ECH_SIGNAL_LEN);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ SSL_TRC(100, ("Generated random value for ECH HRR GREASE."));
+ }
+ sslBuffer echGreaseBuffer = SSL_BUFFER_EMPTY;
+ rv = sslBuffer_Append(&echGreaseBuffer, echGreaseRaw, sizeof(echGreaseRaw));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* HRR GREASE/accept_confirmation zero bytes placeholder buffer. */
+ ss->ssl3.hs.greaseEchBuf = echGreaseBuffer;
+ }
+
+ /* Compute the cookie we are going to need. */
+ rv = tls13_MakeHrrCookie(ss, requestedGroup,
+ appToken, appTokenLen,
+ cookie, &cookieLen, sizeof(cookie));
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ /* Now build the body of the message. */
+ rv = tls13_ConstructHelloRetryRequest(ss, ss->ssl3.hs.cipher_suite,
+ requestedGroup,
+ cookie, cookieLen,
+ NULL, &messageBuf);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ /* And send it. */
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_server_hello,
+ SSL_BUFFER_LEN(&messageBuf));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = ssl3_AppendBufferToHandshake(ss, &messageBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ sslBuffer_Clear(&messageBuf); /* Done with messageBuf */
+
+ if (ss->ssl3.hs.fakeSid.len) {
+ PRInt32 sent;
+
+ PORT_Assert(!IS_DTLS(ss));
+ rv = ssl3_SendChangeCipherSpecsInt(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* ssl3_SendChangeCipherSpecsInt() only flushes to the output buffer, so we
+ * have to force a send. */
+ sent = ssl_SendSavedWriteData(ss);
+ if (sent < 0 && PORT_GetError() != PR_WOULD_BLOCK_ERROR) {
+ PORT_SetError(SSL_ERROR_SOCKET_WRITE_FAILURE);
+ goto loser;
+ }
+ } else {
+ rv = ssl3_FlushHandshake(ss, 0);
+ if (rv != SECSuccess) {
+ goto loser; /* error code set by ssl3_FlushHandshake */
+ }
+ }
+
+ /* We depend on this being exactly one record and one message. */
+ PORT_Assert(!IS_DTLS(ss) || (ss->ssl3.hs.sendMessageSeq == 1 &&
+ ss->ssl3.cwSpec->nextSeqNum == 1));
+ ssl_ReleaseXmitBufLock(ss);
+
+ ss->ssl3.hs.helloRetry = PR_TRUE;
+
+ /* We received early data but have to ignore it because we sent a retry. */
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_hrr;
+ }
+
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&messageBuf);
+ ssl_ReleaseXmitBufLock(ss);
+ return SECFailure;
+}
+
+/* Called from tls13_HandleClientHello.
+ *
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+
+static SECStatus
+tls13_HandleClientKeyShare(sslSocket *ss, TLS13KeyShareEntry *peerShare)
+{
+ SECStatus rv;
+ sslEphemeralKeyPair *keyPair; /* ours */
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle client_key_share handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(peerShare);
+
+ tls13_SetKeyExchangeType(ss, peerShare->group);
+
+ /* Generate our key */
+ rv = tls13_AddKeyShare(ss, peerShare->group);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ /* We should have exactly one key share. */
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
+ PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
+ PR_NEXT_LINK(&ss->ephemeralKeyPairs));
+
+ keyPair = ((sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs));
+ ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
+
+ /* Register the sender */
+ rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_tls13_key_share_xtn,
+ tls13_ServerSendKeyShareXtn);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set already. */
+ }
+
+ rv = tls13_HandleKeyShare(ss, peerShare, keyPair->keys,
+ tls13_GetHash(ss),
+ &ss->ssl3.hs.dheSecret);
+ return rv; /* Error code set already. */
+}
+
+/*
+ * [draft-ietf-tls-tls13-11] Section 6.3.3.2
+ *
+ * opaque DistinguishedName<1..2^16-1>;
+ *
+ * struct {
+ * opaque certificate_extension_oid<1..2^8-1>;
+ * opaque certificate_extension_values<0..2^16-1>;
+ * } CertificateExtension;
+ *
+ * struct {
+ * opaque certificate_request_context<0..2^8-1>;
+ * SignatureAndHashAlgorithm
+ * supported_signature_algorithms<2..2^16-2>;
+ * DistinguishedName certificate_authorities<0..2^16-1>;
+ * CertificateExtension certificate_extensions<0..2^16-1>;
+ * } CertificateRequest;
+ */
+static SECStatus
+tls13_SendCertificateRequest(sslSocket *ss)
+{
+ SECStatus rv;
+ sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
+ unsigned int offset = 0;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request",
+ SSL_GETPID(), ss->fd));
+
+ if (ss->firstHsDone) {
+ PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
+ ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
+ if (ss->ssl3.hs.shaPostHandshake == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate_request);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+ /* We should always have at least one of these. */
+ PORT_Assert(SSL_BUFFER_LEN(&extensionBuf) > 0);
+
+ /* Create a new request context for post-handshake authentication */
+ if (ss->firstHsDone) {
+ PRUint8 context[16];
+ SECItem contextItem = { siBuffer, context, sizeof(context) };
+
+ rv = PK11_GenerateRandom(context, sizeof(context));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
+ rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &contextItem);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ goto loser;
+ }
+
+ offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_request,
+ 1 + /* request context length */
+ ss->xtnData.certReqContext.len +
+ 2 + /* extension length */
+ SSL_BUFFER_LEN(&extensionBuf));
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ /* Context. */
+ rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.certReqContext.data,
+ ss->xtnData.certReqContext.len, 1);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+ /* Extensions. */
+ rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ if (ss->firstHsDone) {
+ rv = ssl3_UpdatePostHandshakeHashes(ss,
+ SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
+ SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ sslBuffer_Clear(&extensionBuf);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&extensionBuf);
+ return SECFailure;
+}
+
+/* [draft-ietf-tls-tls13; S 4.4.1] says:
+ *
+ * Transcript-Hash(ClientHello1, HelloRetryRequest, ... MN) =
+ * Hash(message_hash || // Handshake type
+ * 00 00 Hash.length || // Handshake message length
+ * Hash(ClientHello1) || // Hash of ClientHello1
+ * HelloRetryRequest ... MN)
+ *
+ * For an ECH handshake, the process occurs for the outer
+ * transcript in |ss->ssl3.hs.messages| and the inner
+ * transcript in |ss->ssl3.hs.echInnerMessages|.
+ */
+static SECStatus
+tls13_ReinjectHandshakeTranscript(sslSocket *ss)
+{
+ SSL3Hashes hashes;
+ SSL3Hashes echInnerHashes;
+ SECStatus rv;
+
+ /* First compute the hash. */
+ rv = tls13_ComputeHash(ss, &hashes,
+ ss->ssl3.hs.messages.buf,
+ ss->ssl3.hs.messages.len,
+ tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->ssl3.hs.echHpkeCtx) {
+ rv = tls13_ComputeHash(ss, &echInnerHashes,
+ ss->ssl3.hs.echInnerMessages.buf,
+ ss->ssl3.hs.echInnerMessages.len,
+ tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ ssl3_RestartHandshakeHashes(ss);
+
+ /* Reinject the message. The Default context variant updates
+ * the default hash state. Use it for both non-ECH and ECH Outer. */
+ rv = ssl_HashHandshakeMessageDefault(ss, ssl_hs_message_hash,
+ hashes.u.raw, hashes.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->ssl3.hs.echHpkeCtx) {
+ rv = ssl_HashHandshakeMessageEchInner(ss, ssl_hs_message_hash,
+ echInnerHashes.u.raw,
+ echInnerHashes.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ return SECSuccess;
+}
+static unsigned int
+ssl_ListCount(PRCList *list)
+{
+ unsigned int c = 0;
+ PRCList *cur;
+ for (cur = PR_NEXT_LINK(list); cur != list; cur = PR_NEXT_LINK(cur)) {
+ ++c;
+ }
+ return c;
+}
+
+/*
+ * savedMsg contains the HelloRetryRequest message. When its extensions are parsed
+ * in ssl3_HandleParsedExtensions, the handler for ECH HRR extensions (tls13_ClientHandleHrrEchXtn)
+ * will take a reference into the message buffer.
+ *
+ * This reference is then used in tls13_MaybeHandleEchSignal in order to compute
+ * the transcript for the ECH signal calculation. This was felt to be preferable
+ * to re-parsing the HelloRetryRequest message in order to create the transcript.
+ *
+ * Consequently, savedMsg should not be moved or mutated between these
+ * function calls.
+ */
+SECStatus
+tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *savedMsg,
+ PRUint32 savedLength)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle hello retry request",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST,
+ unexpected_message);
+ return SECFailure;
+ }
+ PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+ /* Restore the null cipher spec for writing. */
+ ssl_GetSpecWriteLock(ss);
+ ssl_CipherSpecRelease(ss->ssl3.cwSpec);
+ ss->ssl3.cwSpec = ssl_FindCipherSpecByEpoch(ss, ssl_secret_write,
+ TrafficKeyClearText);
+ PORT_Assert(ss->ssl3.cwSpec);
+ ssl_ReleaseSpecWriteLock(ss);
+ } else {
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none);
+ }
+ /* Set the spec version, because we want to send CH now with 0303 */
+ tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
+
+ /* Extensions must contain more than just supported_versions. This will
+ * ensure that a HelloRetryRequest isn't a no-op: we must have at least two
+ * extensions, supported_versions plus one other. That other must be one
+ * that we understand and recognize as being valid for HelloRetryRequest,
+ * and should alter our next Client Hello. */
+ unsigned int requiredExtensions = 1;
+ /* The ECH HRR extension is a no-op from the client's perspective. */
+ if (ss->xtnData.ech) {
+ requiredExtensions++;
+ }
+ if (ssl_ListCount(&ss->ssl3.hs.remoteExtensions) <= requiredExtensions) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST,
+ decode_error);
+ return SECFailure;
+ }
+
+ rv = ssl3_HandleParsedExtensions(ss, ssl_hs_hello_retry_request);
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set below */
+ }
+ rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_TRUE);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ ss->ssl3.hs.helloRetry = PR_TRUE;
+ rv = tls13_ReinjectHandshakeTranscript(ss);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_server_hello,
+ savedMsg, savedLength);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_none) {
+ rv = ssl3_SendChangeCipherSpecsInt(ss);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ rv = ssl3_SendClientHello(ss, client_hello_retry);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ ssl_ReleaseXmitBufLock(ss);
+ return SECSuccess;
+
+loser:
+ ssl_ReleaseXmitBufLock(ss);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_SendPostHandshakeCertificate(sslSocket *ss)
+{
+ SECStatus rv;
+ if (ss->ssl3.hs.restartTarget) {
+ PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (ss->ssl3.hs.clientCertificatePending) {
+ SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondFlight because"
+ " certificate authentication is still pending.",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.restartTarget = tls13_SendPostHandshakeCertificate;
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ rv = tls13_SendClientSecondFlight(ss);
+ ssl_ReleaseXmitBufLock(ss);
+ PORT_Assert(ss->ssl3.hs.ws == idle_handshake);
+ PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
+ PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
+ ss->ssl3.hs.shaPostHandshake = NULL;
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ return rv;
+}
+
+static SECStatus
+tls13_HandleCertificateRequest(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ SECItem context = { siBuffer, NULL, 0 };
+ SECItem extensionsData = { siBuffer, NULL, 0 };
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_request sequence",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ /* Client */
+ if (ss->opt.enablePostHandshakeAuth) {
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
+ wait_cert_request, idle_handshake);
+ } else {
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST,
+ wait_cert_request);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* MUST NOT combine external PSKs with certificate authentication. */
+ if (ss->sec.authType == ssl_auth_psk) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, unexpected_message);
+ return SECFailure;
+ }
+
+ if (tls13_IsPostHandshake(ss)) {
+ PORT_Assert(ss->ssl3.hs.shaPostHandshake == NULL);
+ ss->ssl3.hs.shaPostHandshake = PK11_CloneContext(ss->ssl3.hs.sha);
+ if (ss->ssl3.hs.shaPostHandshake == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_request, b, length);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ /* clean up anything left from previous handshake. */
+ if (ss->ssl3.clientCertChain != NULL) {
+ CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
+ ss->ssl3.clientCertChain = NULL;
+ }
+ if (ss->ssl3.clientCertificate != NULL) {
+ CERT_DestroyCertificate(ss->ssl3.clientCertificate);
+ ss->ssl3.clientCertificate = NULL;
+ }
+ if (ss->ssl3.clientPrivateKey != NULL) {
+ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
+ ss->ssl3.clientPrivateKey = NULL;
+ }
+ if (ss->ssl3.hs.clientAuthSignatureSchemes != NULL) {
+ PORT_Free(ss->ssl3.hs.clientAuthSignatureSchemes);
+ ss->ssl3.hs.clientAuthSignatureSchemes = NULL;
+ ss->ssl3.hs.clientAuthSignatureSchemesLen = 0;
+ }
+ SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
+ ss->xtnData.certReqContext.data = NULL;
+ } else {
+ PORT_Assert(ss->ssl3.clientCertChain == NULL);
+ PORT_Assert(ss->ssl3.clientCertificate == NULL);
+ PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
+ PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemes == NULL);
+ PORT_Assert(ss->ssl3.hs.clientAuthSignatureSchemesLen == 0);
+ PORT_Assert(!ss->ssl3.hs.clientCertRequested);
+ PORT_Assert(ss->xtnData.certReqContext.data == NULL);
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Unless it is a post-handshake client auth, the certificate
+ * request context must be empty. */
+ if (!tls13_IsPostHandshake(ss) && context.len > 0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, illegal_parameter);
+ return SECFailure;
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData, 2, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (length) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, decode_error);
+ return SECFailure;
+ }
+
+ /* Process all the extensions. */
+ rv = ssl3_HandleExtensions(ss, &extensionsData.data, &extensionsData.len,
+ ssl_hs_certificate_request);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (!ss->xtnData.numSigSchemes) {
+ FATAL_ERROR(ss, SSL_ERROR_MISSING_SIGNATURE_ALGORITHMS_EXTENSION,
+ missing_extension);
+ return SECFailure;
+ }
+
+ rv = SECITEM_CopyItem(NULL, &ss->xtnData.certReqContext, &context);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.clientCertRequested = PR_TRUE;
+
+ if (ss->firstHsDone) {
+
+ /* Request a client certificate. */
+ rv = ssl3_BeginHandleCertificateRequest(
+ ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
+ &ss->xtnData.certReqAuthorities);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return rv;
+ }
+ rv = tls13_SendPostHandshakeCertificate(ss);
+ } else {
+ TLS13_SET_HS_STATE(ss, wait_server_cert);
+ }
+ return SECSuccess;
+}
+
+PRBool
+tls13_ShouldRequestClientAuth(sslSocket *ss)
+{
+ /* Even if we are configured to request a certificate, we can't
+ * if this handshake used a PSK, even when we are resuming. */
+ return ss->opt.requestCertificate &&
+ ss->ssl3.hs.kea_def->authKeyType != ssl_auth_psk;
+}
+
+static SECStatus
+tls13_SendEncryptedServerSequence(sslSocket *ss)
+{
+ SECStatus rv;
+
+ rv = tls13_ComputeHandshakeSecrets(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
+ ssl_secret_write, PR_FALSE);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
+ ssl_tls13_early_data_xtn,
+ ssl_SendEmptyExtension);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set already. */
+ }
+ }
+
+ rv = tls13_SendEncryptedExtensions(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ if (tls13_ShouldRequestClientAuth(ss)) {
+ rv = tls13_SendCertificateRequest(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+ }
+ if (ss->ssl3.hs.signatureScheme != ssl_sig_none) {
+ SECKEYPrivateKey *svrPrivKey;
+
+ rv = tls13_SendCertificate(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ if (tls13_IsSigningWithDelegatedCredential(ss)) {
+ SSL_TRC(3, ("%d: TLS13[%d]: Signing with delegated credential",
+ SSL_GETPID(), ss->fd));
+ svrPrivKey = ss->sec.serverCert->delegCredKeyPair->privKey;
+ } else {
+ svrPrivKey = ss->sec.serverCert->serverKeyPair->privKey;
+ }
+
+ rv = tls13_SendCertificateVerify(ss, svrPrivKey);
+ if (rv != SECSuccess) {
+ return SECFailure; /* err code is set. */
+ }
+ }
+
+ rv = tls13_SendFinished(ss, ss->ssl3.hs.serverHsTrafficSecret);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ return SECSuccess;
+}
+
+/* Called from: ssl3_HandleClientHello */
+static SECStatus
+tls13_SendServerHelloSequence(sslSocket *ss)
+{
+ SECStatus rv;
+ PRErrorCode err = 0;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: begin send server_hello sequence",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData,
+ ssl_tls13_supported_versions_xtn,
+ tls13_ServerSendSupportedVersionsXtn);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = tls13_ComputeHandshakeSecret(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ rv = ssl3_SendServerHello(ss);
+ if (rv != SECSuccess) {
+ return rv; /* err code is set. */
+ }
+
+ if (ss->ssl3.hs.fakeSid.len) {
+ PORT_Assert(!IS_DTLS(ss));
+ SECITEM_FreeItem(&ss->ssl3.hs.fakeSid, PR_FALSE);
+ if (!ss->ssl3.hs.helloRetry) {
+ rv = ssl3_SendChangeCipherSpecsInt(ss);
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+ }
+
+ rv = tls13_SendEncryptedServerSequence(ss);
+ if (rv != SECSuccess) {
+ err = PORT_GetError();
+ }
+ /* Even if we get an error, since the ServerHello was successfully
+ * serialized, we should give it a chance to reach the network. This gives
+ * the client a chance to perform the key exchange and decrypt the alert
+ * we're about to send. */
+ rv |= ssl3_FlushHandshake(ss, 0);
+ if (rv != SECSuccess) {
+ if (err) {
+ PORT_SetError(err);
+ }
+ return SECFailure;
+ }
+
+ /* Compute the rest of the secrets except for the resumption
+ * and exporter secret. */
+ rv = tls13_ComputeApplicationSecrets(ss);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, PORT_GetError());
+ return SECFailure;
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
+ ssl_secret_write, PR_FALSE);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (IS_DTLS(ss)) {
+ /* We need this for reading ACKs. */
+ ssl_CipherSpecAddRef(ss->ssl3.crSpec);
+ }
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
+ ssl_secret_read, PR_TRUE);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ TLS13_SET_HS_STATE(ss, wait_end_of_early_data);
+ } else {
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored);
+
+ rv = tls13_SetCipherSpec(ss,
+ TrafficKeyHandshake,
+ ssl_secret_read, PR_FALSE);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ if (tls13_ShouldRequestClientAuth(ss)) {
+ TLS13_SET_HS_STATE(ss, wait_client_cert);
+ } else {
+ TLS13_SET_HS_STATE(ss, wait_finished);
+ }
+ }
+
+ /* Here we set a baseline value for our RTT estimation.
+ * This value is updated when we get a response from the client. */
+ ss->ssl3.hs.rttEstimate = ssl_Time(ss);
+ return SECSuccess;
+}
+
+SECStatus
+tls13_HandleServerHelloPart2(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength)
+{
+ SECStatus rv;
+ sslSessionID *sid = ss->sec.ci.sid;
+ SSL3Statistics *ssl3stats = SSL_GetStatistics();
+
+ if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) {
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
+ PORT_Assert(ss->xtnData.selectedPsk);
+
+ if (ss->xtnData.selectedPsk->type != ssl_psk_resume) {
+ ss->statelessResume = PR_FALSE;
+ }
+ } else {
+ /* We may have offered a PSK. If the server didn't negotiate
+ * it, clear this state to re-extract the Early Secret. */
+ if (ss->ssl3.hs.currentSecret) {
+ /* We might have dropped incompatible PSKs on HRR
+ * (see RFC8466, Section 4.1.4). */
+ PORT_Assert(ss->ssl3.hs.helloRetry ||
+ ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
+ PK11_FreeSymKey(ss->ssl3.hs.currentSecret);
+ ss->ssl3.hs.currentSecret = NULL;
+ }
+ ss->statelessResume = PR_FALSE;
+ ss->xtnData.selectedPsk = NULL;
+ }
+
+ if (ss->statelessResume) {
+ PORT_Assert(sid->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ if (tls13_GetHash(ss) !=
+ tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO,
+ illegal_parameter);
+ return SECFailure;
+ }
+ }
+
+ /* Now create a synthetic kea_def that we can tweak. */
+ ss->ssl3.hs.kea_def_mutable = *ss->ssl3.hs.kea_def;
+ ss->ssl3.hs.kea_def = &ss->ssl3.hs.kea_def_mutable;
+
+ if (ss->xtnData.selectedPsk) {
+ ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk;
+ if (ss->statelessResume) {
+ tls13_RestoreCipherInfo(ss, sid);
+ if (sid->peerCert) {
+ ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
+ }
+
+ SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_hits);
+ SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_stateless_resumes);
+ } else {
+ ss->sec.authType = ssl_auth_psk;
+ }
+ } else {
+ if (ss->statelessResume &&
+ ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn)) {
+ SSL_AtomicIncrementLong(&ssl3stats->hsh_sid_cache_misses);
+ }
+ if (sid->cached == in_client_cache) {
+ /* If we tried to resume and failed, let's not try again. */
+ ssl_UncacheSessionID(ss);
+ }
+ }
+
+ /* Discard current SID and make a new one, though it may eventually
+ * end up looking a lot like the old one.
+ */
+ ssl_FreeSID(sid);
+ ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
+ if (sid == NULL) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+ if (ss->statelessResume) {
+ PORT_Assert(ss->sec.peerCert);
+ sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
+ }
+ sid->version = ss->version;
+
+ rv = tls13_HandleServerKeyShare(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = tls13_ComputeHandshakeSecret(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ rv = tls13_MaybeHandleEchSignal(ss, savedMsg, savedLength, PR_FALSE);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ rv = tls13_ComputeHandshakeSecrets(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code is set. */
+ }
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+ /* When we send 0-RTT, we saved the null spec in case we needed it to
+ * send another ClientHello in response to a HelloRetryRequest. Now
+ * that we won't be receiving a HelloRetryRequest, release the spec. */
+ ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_write, TrafficKeyClearText);
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
+ ssl_secret_read, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
+ return SECFailure;
+ }
+ TLS13_SET_HS_STATE(ss, wait_encrypted_extensions);
+
+ return SECSuccess;
+}
+
+static void
+tls13_SetKeyExchangeType(sslSocket *ss, const sslNamedGroupDef *group)
+{
+ ss->sec.keaGroup = group;
+ switch (group->keaType) {
+ /* Note: These overwrite on resumption.... so if you start with ECDH
+ * and resume with DH, we report DH. That's fine, since no answer
+ * is really right. */
+ case ssl_kea_ecdh:
+ ss->ssl3.hs.kea_def_mutable.exchKeyType =
+ ss->statelessResume ? ssl_kea_ecdh_psk : ssl_kea_ecdh;
+ ss->sec.keaType = ssl_kea_ecdh;
+ break;
+ case ssl_kea_dh:
+ ss->ssl3.hs.kea_def_mutable.exchKeyType =
+ ss->statelessResume ? ssl_kea_dh_psk : ssl_kea_dh;
+ ss->sec.keaType = ssl_kea_dh;
+ break;
+ default:
+ PORT_Assert(0);
+ }
+}
+
+/*
+ * Called from ssl3_HandleServerHello.
+ *
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+tls13_HandleServerKeyShare(sslSocket *ss)
+{
+ SECStatus rv;
+ TLS13KeyShareEntry *entry;
+ sslEphemeralKeyPair *keyPair;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle server_key_share handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ /* This list should have one entry. */
+ if (PR_CLIST_IS_EMPTY(&ss->xtnData.remoteKeyShares)) {
+ FATAL_ERROR(ss, SSL_ERROR_MISSING_KEY_SHARE, missing_extension);
+ return SECFailure;
+ }
+
+ entry = (TLS13KeyShareEntry *)PR_NEXT_LINK(&ss->xtnData.remoteKeyShares);
+ PORT_Assert(PR_NEXT_LINK(&entry->link) == &ss->xtnData.remoteKeyShares);
+
+ /* Now get our matching key. */
+ keyPair = ssl_LookupEphemeralKeyPair(ss, entry->group);
+ if (!keyPair) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_KEY_SHARE, illegal_parameter);
+ return SECFailure;
+ }
+
+ PORT_Assert(ssl_NamedGroupEnabled(ss, entry->group));
+
+ rv = tls13_HandleKeyShare(ss, entry, keyPair->keys,
+ tls13_GetHash(ss),
+ &ss->ssl3.hs.dheSecret);
+ if (rv != SECSuccess)
+ return SECFailure; /* Error code set by caller. */
+
+ tls13_SetKeyExchangeType(ss, entry->group);
+ ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->keys->pubKey);
+
+ return SECSuccess;
+}
+
+/*
+ * opaque ASN1Cert<1..2^24-1>;
+ *
+ * struct {
+ * ASN1Cert cert_data;
+ * Extension extensions<0..2^16-1>;
+ * } CertificateEntry;
+ *
+ * struct {
+ * opaque certificate_request_context<0..2^8-1>;
+ * CertificateEntry certificate_list<0..2^24-1>;
+ * } Certificate;
+ */
+static SECStatus
+tls13_SendCertificate(sslSocket *ss)
+{
+ SECStatus rv;
+ CERTCertificateList *certChain;
+ int certChainLen = 0;
+ int i;
+ SECItem context = { siBuffer, NULL, 0 };
+ sslBuffer extensionBuf = SSL_BUFFER_EMPTY;
+
+ SSL_TRC(3, ("%d: TLS1.3[%d]: send certificate handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->sec.isServer) {
+ PORT_Assert(!ss->sec.localCert);
+ /* A server certificate is selected in tls13_SelectServerCert(). */
+ PORT_Assert(ss->sec.serverCert);
+
+ certChain = ss->sec.serverCert->serverCertChain;
+ ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert);
+ } else {
+ if (ss->sec.localCert)
+ CERT_DestroyCertificate(ss->sec.localCert);
+
+ certChain = ss->ssl3.clientCertChain;
+ ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
+ }
+
+ if (!ss->sec.isServer) {
+ PORT_Assert(ss->ssl3.hs.clientCertRequested);
+ context = ss->xtnData.certReqContext;
+ }
+ if (certChain) {
+ for (i = 0; i < certChain->len; i++) {
+ /* Each cert is 3 octet length, cert, and extensions */
+ certChainLen += 3 + certChain->certs[i].len + 2;
+ }
+
+ /* Build the extensions. This only applies to the leaf cert, because we
+ * don't yet send extensions for non-leaf certs. */
+ rv = ssl_ConstructExtensions(ss, &extensionBuf, ssl_hs_certificate);
+ if (rv != SECSuccess) {
+ return SECFailure; /* code already set */
+ }
+ /* extensionBuf.len is only added once, for the leaf cert. */
+ certChainLen += SSL_BUFFER_LEN(&extensionBuf);
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate,
+ 1 + context.len + 3 + certChainLen);
+ if (rv != SECSuccess) {
+ return SECFailure; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, context.data,
+ context.len, 1);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+ if (certChain) {
+ for (i = 0; i < certChain->len; i++) {
+ rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
+ certChain->certs[i].len, 3);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+
+ if (i) {
+ /* Not end-entity. */
+ rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+ continue;
+ }
+
+ /* End-entity, send extensions. */
+ rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensionBuf, 2);
+ if (rv != SECSuccess) {
+ goto loser; /* err set by AppendHandshake. */
+ }
+ }
+ }
+
+ sslBuffer_Clear(&extensionBuf);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&extensionBuf);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_HandleCertificateEntry(sslSocket *ss, SECItem *data, PRBool first,
+ CERTCertificate **certp)
+{
+ SECStatus rv;
+ SECItem certData;
+ SECItem extensionsData;
+ CERTCertificate *cert = NULL;
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &certData,
+ 3, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &extensionsData,
+ 2, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Parse all the extensions. */
+ if (first && !ss->sec.isServer) {
+ rv = ssl3_HandleExtensions(ss, &extensionsData.data,
+ &extensionsData.len,
+ ssl_hs_certificate);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* TODO(ekr@rtfm.com): Copy out SCTs. Bug 1315727. */
+ }
+
+ cert = CERT_NewTempCertificate(ss->dbHandle, &certData, NULL,
+ PR_FALSE, PR_TRUE);
+
+ if (!cert) {
+ PRErrorCode errCode = PORT_GetError();
+ switch (errCode) {
+ case PR_OUT_OF_MEMORY_ERROR:
+ case SEC_ERROR_BAD_DATABASE:
+ case SEC_ERROR_NO_MEMORY:
+ FATAL_ERROR(ss, errCode, internal_error);
+ return SECFailure;
+ default:
+ ssl3_SendAlertForCertError(ss, errCode);
+ return SECFailure;
+ }
+ }
+
+ *certp = cert;
+
+ return SECSuccess;
+}
+
+/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
+ * tls13 Certificate message.
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+static SECStatus
+tls13_HandleCertificate(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ SECItem context = { siBuffer, NULL, 0 };
+ SECItem certList;
+ PRBool first = PR_TRUE;
+ ssl3CertNode *lastCert = NULL;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle certificate handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ if (ss->sec.isServer) {
+ /* Receiving this message might be the first sign we have that
+ * early data is over, so pretend we received EOED. */
+ rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+
+ if (ss->ssl3.clientCertRequested) {
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
+ idle_handshake);
+ } else {
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
+ wait_client_cert);
+ }
+ } else {
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERTIFICATE,
+ wait_cert_request, wait_server_cert);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* We can ignore any other cleartext from the client. */
+ if (ss->sec.isServer && IS_DTLS(ss)) {
+ ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
+ dtls_ReceivedFirstMessageInFlight(ss);
+ }
+
+ if (ss->firstHsDone) {
+ rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate, b, length);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ } else if (ss->sec.isServer) {
+ /* Our first shot an getting an RTT estimate. If the client took extra
+ * time to fetch a certificate, this will be bad, but we can't do much
+ * about that. */
+ ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
+ }
+
+ /* Process the context string */
+ rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length);
+ if (rv != SECSuccess)
+ return SECFailure;
+
+ if (ss->ssl3.clientCertRequested) {
+ PORT_Assert(ss->sec.isServer);
+ if (SECITEM_CompareItem(&context, &ss->xtnData.certReqContext) != 0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
+ return SECFailure;
+ }
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &certList, 3, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (length) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, illegal_parameter);
+ return SECFailure;
+ }
+
+ if (!certList.len) {
+ if (!ss->sec.isServer) {
+ /* Servers always need to send some cert. */
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERTIFICATE, bad_certificate);
+ return SECFailure;
+ } else {
+ /* This is TLS's version of a no_certificate alert. */
+ /* I'm a server. I've requested a client cert. He hasn't got one. */
+ rv = ssl3_HandleNoCertificate(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ TLS13_SET_HS_STATE(ss, wait_finished);
+ return SECSuccess;
+ }
+ }
+
+ /* Now clean up. */
+ ssl3_CleanupPeerCerts(ss);
+ ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (ss->ssl3.peerCertArena == NULL) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ return SECFailure;
+ }
+
+ while (certList.len) {
+ CERTCertificate *cert;
+
+ rv = tls13_HandleCertificateEntry(ss, &certList, first,
+ &cert);
+ if (rv != SECSuccess) {
+ ss->xtnData.signedCertTimestamps.len = 0;
+ return SECFailure;
+ }
+
+ if (first) {
+ ss->sec.peerCert = cert;
+
+ if (ss->xtnData.signedCertTimestamps.len) {
+ sslSessionID *sid = ss->sec.ci.sid;
+ rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
+ &ss->xtnData.signedCertTimestamps);
+ ss->xtnData.signedCertTimestamps.len = 0;
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ return SECFailure;
+ }
+ }
+ } else {
+ ssl3CertNode *c = PORT_ArenaNew(ss->ssl3.peerCertArena,
+ ssl3CertNode);
+ if (!c) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ return SECFailure;
+ }
+ c->cert = cert;
+ c->next = NULL;
+
+ if (lastCert) {
+ lastCert->next = c;
+ } else {
+ ss->ssl3.peerCertChain = c;
+ }
+ lastCert = c;
+ }
+
+ first = PR_FALSE;
+ }
+ SECKEY_UpdateCertPQG(ss->sec.peerCert);
+
+ return ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
+}
+
+/* Add context to the hash functions as described in
+ [draft-ietf-tls-tls13; Section 4.9.1] */
+SECStatus
+tls13_AddContextToHashes(sslSocket *ss, const SSL3Hashes *hashes,
+ SSLHashType algorithm, PRBool sending,
+ SSL3Hashes *tbsHash)
+{
+ SECStatus rv = SECSuccess;
+ PK11Context *ctx;
+ const unsigned char context_padding[] = {
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
+ };
+
+ const char *client_cert_verify_string = "TLS 1.3, client CertificateVerify";
+ const char *server_cert_verify_string = "TLS 1.3, server CertificateVerify";
+ const char *context_string = (sending ^ ss->sec.isServer) ? client_cert_verify_string
+ : server_cert_verify_string;
+ unsigned int hashlength;
+
+ /* Double check that we are doing the same hash.*/
+ PORT_Assert(hashes->len == tls13_GetHashSize(ss));
+
+ ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(algorithm));
+ if (!ctx) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ goto loser;
+ }
+
+ PORT_Assert(SECFailure);
+ PORT_Assert(!SECSuccess);
+
+ PRINT_BUF(50, (ss, "TLS 1.3 hash without context", hashes->u.raw, hashes->len));
+ PRINT_BUF(50, (ss, "Context string", context_string, strlen(context_string)));
+ rv |= PK11_DigestBegin(ctx);
+ rv |= PK11_DigestOp(ctx, context_padding, sizeof(context_padding));
+ rv |= PK11_DigestOp(ctx, (unsigned char *)context_string,
+ strlen(context_string) + 1); /* +1 includes the terminating 0 */
+ rv |= PK11_DigestOp(ctx, hashes->u.raw, hashes->len);
+ /* Update the hash in-place */
+ rv |= PK11_DigestFinal(ctx, tbsHash->u.raw, &hashlength, sizeof(tbsHash->u.raw));
+ PK11_DestroyContext(ctx, PR_TRUE);
+ PRINT_BUF(50, (ss, "TLS 1.3 hash with context", tbsHash->u.raw, hashlength));
+
+ tbsHash->len = hashlength;
+ tbsHash->hashAlg = algorithm;
+
+ if (rv) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+ return SECSuccess;
+
+loser:
+ return SECFailure;
+}
+
+/*
+ * Derive-Secret(Secret, Label, Messages) =
+ * HKDF-Expand-Label(Secret, Label,
+ * Hash(Messages) + Hash(resumption_context), L))
+ */
+SECStatus
+tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
+ const char *label,
+ unsigned int labelLen,
+ const SSL3Hashes *hashes,
+ PK11SymKey **dest,
+ SSLHashType hash)
+{
+ SECStatus rv;
+
+ rv = tls13_HkdfExpandLabel(key, hash, hashes->u.raw, hashes->len,
+ label, labelLen, CKM_HKDF_DERIVE,
+ tls13_GetHashSizeForHash(hash),
+ ss->protocolVariant, dest);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/* Convenience wrapper for the empty hash. */
+SECStatus
+tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
+ const char *label,
+ unsigned int labelLen,
+ PK11SymKey **dest,
+ SSLHashType hash)
+{
+ SSL3Hashes hashes;
+ SECStatus rv;
+ PRUint8 buf[] = { 0 };
+
+ rv = tls13_ComputeHash(ss, &hashes, buf, 0, hash);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return tls13_DeriveSecret(ss, key, label, labelLen, &hashes, dest, hash);
+}
+
+/* Convenience wrapper that lets us supply a separate prefix and suffix. */
+static SECStatus
+tls13_DeriveSecretWrap(sslSocket *ss, PK11SymKey *key,
+ const char *prefix,
+ const char *suffix,
+ const char *keylogLabel,
+ PK11SymKey **dest)
+{
+ SECStatus rv;
+ SSL3Hashes hashes;
+ char buf[100];
+ const char *label;
+
+ if (prefix) {
+ if ((strlen(prefix) + strlen(suffix) + 2) > sizeof(buf)) {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ (void)PR_snprintf(buf, sizeof(buf), "%s %s",
+ prefix, suffix);
+ label = buf;
+ } else {
+ label = suffix;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: deriving secret '%s'",
+ SSL_GETPID(), ss->fd, label));
+ rv = tls13_ComputeHandshakeHashes(ss, &hashes);
+ if (rv != SECSuccess) {
+ PORT_Assert(0); /* Should never fail */
+ ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = tls13_DeriveSecret(ss, key, label, strlen(label),
+ &hashes, dest, tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (keylogLabel) {
+ ssl3_RecordKeyLog(ss, keylogLabel, *dest);
+ }
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb, void *arg)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SecretCallback",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+ ss->secretCallback = cb;
+ ss->secretCallbackArg = arg;
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+ return SECSuccess;
+}
+
+/* Derive traffic keys for the next cipher spec in the queue. */
+static SECStatus
+tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec,
+ TrafficKeyType type,
+ PRBool deleteSecret)
+{
+ size_t keySize = spec->cipherDef->key_size;
+ size_t ivSize = spec->cipherDef->iv_size +
+ spec->cipherDef->explicit_nonce_size; /* This isn't always going to
+ * work, but it does for
+ * AES-GCM */
+ CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipherDef->calg);
+ PK11SymKey **prkp = NULL;
+ PK11SymKey *prk = NULL;
+ PRBool clientSecret;
+ SECStatus rv;
+ /* These labels are just used for debugging. */
+ static const char kHkdfPhaseEarlyApplicationDataKeys[] = "early application data";
+ static const char kHkdfPhaseHandshakeKeys[] = "handshake data";
+ static const char kHkdfPhaseApplicationDataKeys[] = "application data";
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ clientSecret = !tls13_UseServerSecret(ss, spec->direction);
+ switch (type) {
+ case TrafficKeyEarlyApplicationData:
+ PORT_Assert(clientSecret);
+ prkp = &ss->ssl3.hs.clientEarlyTrafficSecret;
+ spec->phase = kHkdfPhaseEarlyApplicationDataKeys;
+ break;
+ case TrafficKeyHandshake:
+ prkp = clientSecret ? &ss->ssl3.hs.clientHsTrafficSecret
+ : &ss->ssl3.hs.serverHsTrafficSecret;
+ spec->phase = kHkdfPhaseHandshakeKeys;
+ break;
+ case TrafficKeyApplicationData:
+ prkp = clientSecret ? &ss->ssl3.hs.clientTrafficSecret
+ : &ss->ssl3.hs.serverTrafficSecret;
+ spec->phase = kHkdfPhaseApplicationDataKeys;
+ break;
+ default:
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ PORT_Assert(0);
+ return SECFailure;
+ }
+ PORT_Assert(prkp != NULL);
+ prk = *prkp;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: deriving %s traffic keys epoch=%d (%s)",
+ SSL_GETPID(), ss->fd, SPEC_DIR(spec),
+ spec->epoch, spec->phase));
+
+ rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss),
+ NULL, 0,
+ kHkdfPurposeKey, strlen(kHkdfPurposeKey),
+ bulkAlgorithm, keySize,
+ ss->protocolVariant,
+ &spec->keyMaterial.key);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ PORT_Assert(0);
+ goto loser;
+ }
+
+ if (IS_DTLS(ss) && spec->epoch > 0) {
+ rv = ssl_CreateMaskingContextInner(spec->version, ss->ssl3.hs.cipher_suite,
+ ss->protocolVariant, prk, kHkdfPurposeSn,
+ strlen(kHkdfPurposeSn), &spec->maskContext);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ PORT_Assert(0);
+ goto loser;
+ }
+ }
+
+ rv = tls13_HkdfExpandLabelRaw(prk, tls13_GetHash(ss),
+ NULL, 0,
+ kHkdfPurposeIv, strlen(kHkdfPurposeIv),
+ ss->protocolVariant,
+ spec->keyMaterial.iv, ivSize);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ PORT_Assert(0);
+ goto loser;
+ }
+
+ if (deleteSecret) {
+ PK11_FreeSymKey(prk);
+ *prkp = NULL;
+ }
+ return SECSuccess;
+
+loser:
+ return SECFailure;
+}
+
+void
+tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ /* Set the record version to pretend to be (D)TLS 1.2. */
+ if (IS_DTLS(ss)) {
+ spec->recordVersion = SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
+ } else {
+ spec->recordVersion = SSL_LIBRARY_VERSION_TLS_1_2;
+ }
+ SSL_TRC(10, ("%d: TLS13[%d]: set spec=%d record version to 0x%04x",
+ SSL_GETPID(), ss->fd, spec, spec->recordVersion));
+}
+
+static SECStatus
+tls13_SetupPendingCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(spec->epoch);
+
+ /* Version isn't set when we send 0-RTT data. */
+ spec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version);
+
+ ssl_SaveCipherSpec(ss, spec);
+ /* We want to keep read cipher specs around longer because
+ * there are cases where we might get either epoch N or
+ * epoch N+1. */
+ if (IS_DTLS(ss) && spec->direction == ssl_secret_read) {
+ ssl_CipherSpecAddRef(spec);
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x",
+ SSL_GETPID(), ss->fd, suite));
+
+ spec->cipherDef = ssl_GetBulkCipherDef(ssl_LookupCipherSuiteDef(suite));
+
+ if (spec->epoch == TrafficKeyEarlyApplicationData) {
+ if (ss->xtnData.selectedPsk &&
+ ss->xtnData.selectedPsk->zeroRttSuite != TLS_NULL_WITH_NULL_NULL) {
+ spec->earlyDataRemaining = ss->xtnData.selectedPsk->maxEarlyData;
+ }
+ }
+
+ tls13_SetSpecRecordVersion(ss, spec);
+
+ /* The record size limit is reduced by one so that the remainder of the
+ * record handling code can use the same checks for all versions. */
+ if (ssl3_ExtensionNegotiated(ss, ssl_record_size_limit_xtn)) {
+ spec->recordSizeLimit = ((spec->direction == ssl_secret_read)
+ ? ss->opt.recordSizeLimit
+ : ss->xtnData.recordSizeLimit) -
+ 1;
+ } else {
+ spec->recordSizeLimit = MAX_FRAGMENT_LENGTH;
+ }
+ return SECSuccess;
+}
+
+/*
+ * Initialize the cipher context. All TLS 1.3 operations are AEAD,
+ * so they are all message contexts.
+ */
+static SECStatus
+tls13_InitPendingContext(sslSocket *ss, ssl3CipherSpec *spec)
+{
+ CK_MECHANISM_TYPE encMechanism;
+ CK_ATTRIBUTE_TYPE encMode;
+ SECItem iv;
+ SSLCipherAlgorithm calg;
+
+ calg = spec->cipherDef->calg;
+
+ encMechanism = ssl3_Alg2Mech(calg);
+ encMode = CKA_NSS_MESSAGE | ((spec->direction == ssl_secret_write) ? CKA_ENCRYPT : CKA_DECRYPT);
+ iv.data = NULL;
+ iv.len = 0;
+
+ /*
+ * build the context
+ */
+ spec->cipherContext = PK11_CreateContextBySymKey(encMechanism, encMode,
+ spec->keyMaterial.key,
+ &iv);
+ if (!spec->cipherContext) {
+ ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/*
+ * Called before sending alerts to set up the right key on the client.
+ * We might encounter errors during the handshake where the current
+ * key is ClearText or EarlyApplicationData. This
+ * function switches to the Handshake key if possible.
+ */
+SECStatus
+tls13_SetAlertCipherSpec(sslSocket *ss)
+{
+ SECStatus rv;
+
+ if (ss->sec.isServer) {
+ return SECSuccess;
+ }
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+ if (TLS13_IN_HS_STATE(ss, wait_server_hello)) {
+ return SECSuccess;
+ }
+ if ((ss->ssl3.cwSpec->epoch != TrafficKeyClearText) &&
+ (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData)) {
+ return SECSuccess;
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
+ ssl_secret_write, PR_FALSE);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/* Install a new cipher spec for this direction.
+ *
+ * During the handshake, the values for |epoch| take values from the
+ * TrafficKeyType enum. Afterwards, key update increments them.
+ */
+static SECStatus
+tls13_SetCipherSpec(sslSocket *ss, PRUint16 epoch,
+ SSLSecretDirection direction, PRBool deleteSecret)
+{
+ TrafficKeyType type;
+ SECStatus rv;
+ ssl3CipherSpec *spec = NULL;
+ ssl3CipherSpec **specp;
+
+ /* Flush out old handshake data. */
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
+ ssl_ReleaseXmitBufLock(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Create the new spec. */
+ spec = ssl_CreateCipherSpec(ss, direction);
+ if (!spec) {
+ return SECFailure;
+ }
+ spec->epoch = epoch;
+ spec->nextSeqNum = 0;
+ if (IS_DTLS(ss)) {
+ dtls_InitRecvdRecords(&spec->recvdRecords);
+ }
+
+ /* This depends on spec having a valid direction and epoch. */
+ rv = tls13_SetupPendingCipherSpec(ss, spec);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ type = (TrafficKeyType)PR_MIN(TrafficKeyApplicationData, epoch);
+ rv = tls13_DeriveTrafficKeys(ss, spec, type, deleteSecret);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = tls13_InitPendingContext(ss, spec);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Now that we've set almost everything up, finally cut over. */
+ specp = (direction == ssl_secret_read) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec;
+ ssl_GetSpecWriteLock(ss);
+ ssl_CipherSpecRelease(*specp); /* May delete old cipher. */
+ *specp = spec; /* Overwrite. */
+ ssl_ReleaseSpecWriteLock(ss);
+
+ SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for epoch=%d (%s) dir=%s",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss), spec->epoch,
+ spec->phase, SPEC_DIR(spec)));
+ return SECSuccess;
+
+loser:
+ ssl_CipherSpecRelease(spec);
+ return SECFailure;
+}
+
+SECStatus
+tls13_ComputeHandshakeHashes(sslSocket *ss, SSL3Hashes *hashes)
+{
+ SECStatus rv;
+ PK11Context *ctx = NULL;
+ PRBool useEchInner;
+ sslBuffer *transcript;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
+ /* Backup: if we haven't done any hashing, then hash now.
+ * This happens when we are doing 0-RTT on the client. */
+ ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(tls13_GetHash(ss)));
+ if (!ctx) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+
+ if (PK11_DigestBegin(ctx) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+
+ /* One might expect this to use ss->ssl3.hs.echAccepted,
+ * but with 0-RTT we don't know that yet. */
+ useEchInner = ss->sec.isServer ? PR_FALSE : !!ss->ssl3.hs.echHpkeCtx;
+ transcript = useEchInner ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
+
+ PRINT_BUF(10, (ss, "Handshake hash computed over saved messages",
+ transcript->buf,
+ transcript->len));
+
+ if (PK11_DigestOp(ctx,
+ transcript->buf,
+ transcript->len) != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+ } else {
+ if (ss->firstHsDone) {
+ ctx = PK11_CloneContext(ss->ssl3.hs.shaPostHandshake);
+ } else {
+ ctx = PK11_CloneContext(ss->ssl3.hs.sha);
+ }
+ if (!ctx) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ return SECFailure;
+ }
+ }
+
+ rv = PK11_DigestFinal(ctx, hashes->u.raw,
+ &hashes->len,
+ sizeof(hashes->u.raw));
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
+ goto loser;
+ }
+
+ PRINT_BUF(10, (ss, "Handshake hash", hashes->u.raw, hashes->len));
+ PORT_Assert(hashes->len == tls13_GetHashSize(ss));
+ PK11_DestroyContext(ctx, PR_TRUE);
+
+ return SECSuccess;
+
+loser:
+ PK11_DestroyContext(ctx, PR_TRUE);
+ return SECFailure;
+}
+
+TLS13KeyShareEntry *
+tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o)
+{
+ TLS13KeyShareEntry *n;
+
+ PORT_Assert(o);
+ n = PORT_ZNew(TLS13KeyShareEntry);
+ if (!n) {
+ return NULL;
+ }
+
+ if (SECSuccess != SECITEM_CopyItem(NULL, &n->key_exchange, &o->key_exchange)) {
+ PORT_Free(n);
+ return NULL;
+ }
+ n->group = o->group;
+ return n;
+}
+
+void
+tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer)
+{
+ if (!offer) {
+ return;
+ }
+ SECITEM_ZfreeItem(&offer->key_exchange, PR_FALSE);
+ PORT_ZFree(offer, sizeof(*offer));
+}
+
+void
+tls13_DestroyKeyShares(PRCList *list)
+{
+ PRCList *cur_p;
+
+ /* The list must be initialized. */
+ PORT_Assert(PR_LIST_HEAD(list));
+
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ cur_p = PR_LIST_TAIL(list);
+ PR_REMOVE_LINK(cur_p);
+ tls13_DestroyKeyShareEntry((TLS13KeyShareEntry *)cur_p);
+ }
+}
+
+void
+tls13_DestroyEarlyData(PRCList *list)
+{
+ PRCList *cur_p;
+
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ TLS13EarlyData *msg;
+
+ cur_p = PR_LIST_TAIL(list);
+ msg = (TLS13EarlyData *)cur_p;
+
+ PR_REMOVE_LINK(cur_p);
+ SECITEM_ZfreeItem(&msg->data, PR_FALSE);
+ PORT_ZFree(msg, sizeof(*msg));
+ }
+}
+
+/* draft-ietf-tls-tls13 Section 5.2.2 specifies the following
+ * nonce algorithm:
+ *
+ * The length of the per-record nonce (iv_length) is set to max(8 bytes,
+ * N_MIN) for the AEAD algorithm (see [RFC5116] Section 4). An AEAD
+ * algorithm where N_MAX is less than 8 bytes MUST NOT be used with TLS.
+ * The per-record nonce for the AEAD construction is formed as follows:
+ *
+ * 1. The 64-bit record sequence number is padded to the left with
+ * zeroes to iv_length.
+ *
+ * 2. The padded sequence number is XORed with the static
+ * client_write_iv or server_write_iv, depending on the role.
+ *
+ * The resulting quantity (of length iv_length) is used as the per-
+ * record nonce.
+ *
+ * Existing suites have the same nonce size: N_MIN = N_MAX = 12 bytes
+ *
+ * See RFC 5288 and https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2
+ */
+static void
+tls13_WriteNonce(const unsigned char *ivIn, unsigned int ivInLen,
+ const unsigned char *nonce, unsigned int nonceLen,
+ unsigned char *ivOut, unsigned int ivOutLen)
+{
+ size_t i;
+ unsigned int offset = ivOutLen - nonceLen;
+
+ PORT_Assert(ivInLen <= ivOutLen);
+ PORT_Assert(nonceLen <= ivOutLen);
+ PORT_Memset(ivOut, 0, ivOutLen);
+ PORT_Memcpy(ivOut, ivIn, ivInLen);
+
+ /* XOR the last n bytes of the IV with the nonce (should be a counter). */
+ for (i = 0; i < nonceLen; ++i) {
+ ivOut[offset + i] ^= nonce[i];
+ }
+ PRINT_BUF(50, (NULL, "Nonce", ivOut, ivOutLen));
+}
+
+/* Setup the IV for AEAD encrypt. The PKCS #11 module will add the
+ * counter, but it doesn't know about the DTLS epic, so we add it here.
+ */
+unsigned int
+tls13_SetupAeadIv(PRBool isDTLS, unsigned char *ivOut, unsigned char *ivIn,
+ unsigned int offset, unsigned int ivLen, DTLSEpoch epoch)
+{
+ PORT_Memcpy(ivOut, ivIn, ivLen);
+ if (isDTLS) {
+ /* handle the tls 1.2 counter mode case, the epoc is copied
+ * instead of xored. We accomplish this by clearing ivOut
+ * before running xor. */
+ if (offset >= ivLen) {
+ ivOut[offset] = ivOut[offset + 1] = 0;
+ }
+ ivOut[offset] ^= (unsigned char)(epoch >> BPB) & 0xff;
+ ivOut[offset + 1] ^= (unsigned char)(epoch)&0xff;
+ offset += 2;
+ }
+ return offset;
+}
+
+/*
+ * Do a single AEAD for TLS. This differs from PK11_AEADOp in the following
+ * ways.
+ * 1) If context is not supplied, it treats the operation as a single shot
+ * and creates a context from symKey and mech.
+ * 2) It always assumes the tag will be at the end of the buffer
+ * (in on decrypt, out on encrypt) just like the old single shot.
+ * 3) If we aren't generating an IV, it uses tls13_WriteNonce to create the
+ * nonce.
+ * NOTE is context is supplied, symKey and mech are ignored
+ */
+SECStatus
+tls13_AEAD(PK11Context *context, PRBool decrypt,
+ CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
+ const unsigned char *ivIn, unsigned char *ivOut, unsigned int ivLen,
+ const unsigned char *nonceIn, unsigned int nonceLen,
+ const unsigned char *aad, unsigned int aadLen,
+ unsigned char *out, unsigned int *outLen, unsigned int maxout,
+ unsigned int tagLen, const unsigned char *in, unsigned int inLen)
+{
+ unsigned char *tag;
+ unsigned char iv[MAX_IV_LENGTH];
+ unsigned char tagbuf[HASH_LENGTH_MAX];
+ SECStatus rv;
+
+ /* must have either context or the symKey set */
+ if (!context) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ PORT_Assert(ivLen <= MAX_IV_LENGTH);
+ PORT_Assert(tagLen <= HASH_LENGTH_MAX);
+ if (!ivOut) {
+ ivOut = iv; /* caller doesn't need a returned, iv */
+ }
+
+ if (ivGen == CKG_NO_GENERATE) {
+ tls13_WriteNonce(ivIn, ivLen, nonceIn, nonceLen, ivOut, ivLen);
+ } else if (ivIn != ivOut) {
+ PORT_Memcpy(ivOut, ivIn, ivLen);
+ }
+ if (decrypt) {
+ inLen = inLen - tagLen;
+ tag = (unsigned char *)in + inLen;
+ /* tag is const on decrypt, but returned on encrypt */
+ } else {
+ /* tag is written to a separate buffer, then added to the end
+ * of the actual output buffer. This allows output buffer to be larger
+ * than the input buffer and everything still work */
+ tag = tagbuf;
+ }
+ rv = PK11_AEADOp(context, ivGen, fixedbits, ivOut, ivLen, aad, aadLen,
+ out, (int *)outLen, maxout, tag, tagLen, in, inLen);
+ /* on encrypt SSL always puts the tag at the end of the buffer */
+ if ((rv == SECSuccess) && !(decrypt)) {
+ unsigned int len = *outLen;
+ /* make sure there is still space */
+ if (len + tagLen > maxout) {
+ PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+ return SECFailure;
+ }
+ PORT_Memcpy(out + len, tag, tagLen);
+ *outLen += tagLen;
+ }
+ return rv;
+}
+
+static SECStatus
+tls13_HandleEncryptedExtensions(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ PRUint32 innerLength;
+ SECItem oldAlpn = { siBuffer, NULL, 0 };
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle encrypted extensions",
+ SSL_GETPID(), ss->fd));
+
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_ENCRYPTED_EXTENSIONS,
+ wait_encrypted_extensions);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &innerLength, 2, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Alert already sent. */
+ }
+ if (innerLength != length) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
+ illegal_parameter);
+ return SECFailure;
+ }
+
+ /* If we are doing 0-RTT, then we already have an ALPN value. Stash
+ * it for comparison. */
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent &&
+ ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) {
+ oldAlpn = ss->xtnData.nextProto;
+ ss->xtnData.nextProto.data = NULL;
+ ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT;
+ }
+
+ rv = ssl3_ParseExtensions(ss, &b, &length);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set below */
+ }
+
+ /* Handle the rest of the extensions. */
+ rv = ssl3_HandleParsedExtensions(ss, ssl_hs_encrypted_extensions);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code set below */
+ }
+
+ /* We can only get here if we offered 0-RTT. */
+ if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) {
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent);
+ if (!ss->xtnData.selectedPsk) {
+ /* Illegal to accept 0-RTT without also accepting PSK. */
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
+ illegal_parameter);
+ }
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted;
+
+ /* Check that the server negotiated the same ALPN (if any). */
+ if (SECITEM_CompareItem(&oldAlpn, &ss->xtnData.nextProto)) {
+ SECITEM_FreeItem(&oldAlpn, PR_FALSE);
+ FATAL_ERROR(ss, SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID,
+ illegal_parameter);
+ return SECFailure;
+ }
+ /* Check that the server negotiated the same cipher suite. */
+ if (ss->ssl3.hs.cipher_suite != ss->ssl3.hs.zeroRttSuite) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ENCRYPTED_EXTENSIONS,
+ illegal_parameter);
+ return SECFailure;
+ }
+ } else if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) {
+ /* Though we sent 0-RTT, the early_data extension wasn't present so the
+ * state is unmodified; the server must have rejected 0-RTT. */
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored;
+ ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_trial;
+ } else {
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none ||
+ (ss->ssl3.hs.helloRetry &&
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored));
+ }
+
+ SECITEM_FreeItem(&oldAlpn, PR_FALSE);
+ if (ss->ssl3.hs.kea_def->authKeyType == ssl_auth_psk) {
+ TLS13_SET_HS_STATE(ss, wait_finished);
+ } else {
+ TLS13_SET_HS_STATE(ss, wait_cert_request);
+ }
+
+ /* Client is done with any PSKs */
+ tls13_DestroyPskList(&ss->ssl3.hs.psks);
+ ss->xtnData.selectedPsk = NULL;
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_SendEncryptedExtensions(sslSocket *ss)
+{
+ sslBuffer extensions = SSL_BUFFER_EMPTY;
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send encrypted extensions handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ rv = ssl_ConstructExtensions(ss, &extensions, ssl_hs_encrypted_extensions);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_encrypted_extensions,
+ SSL_BUFFER_LEN(&extensions) + 2);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+ rv = ssl3_AppendBufferToHandshakeVariable(ss, &extensions, 2);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+ sslBuffer_Clear(&extensions);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&extensions);
+ return SECFailure;
+}
+
+SECStatus
+tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey)
+{
+ SECStatus rv = SECFailure;
+ SECItem buf = { siBuffer, NULL, 0 };
+ unsigned int len;
+ SSLHashType hashAlg;
+ SSL3Hashes hash;
+ SSL3Hashes tbsHash; /* The hash "to be signed". */
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send certificate_verify handshake",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_single);
+ rv = tls13_ComputeHandshakeHashes(ss, &hash);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* We should have picked a signature scheme when we received a
+ * CertificateRequest, or when we picked a server certificate. */
+ PORT_Assert(ss->ssl3.hs.signatureScheme != ssl_sig_none);
+ if (ss->ssl3.hs.signatureScheme == ssl_sig_none) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme);
+ rv = tls13_AddContextToHashes(ss, &hash, hashAlg,
+ PR_TRUE, &tbsHash);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = ssl3_SignHashes(ss, &tbsHash, privKey, &buf);
+ if (rv == SECSuccess && !ss->sec.isServer) {
+ /* Remember the info about the slot that did the signing.
+ * Later, when doing an SSL restart handshake, verify this.
+ * These calls are mere accessors, and can't fail.
+ */
+ PK11SlotInfo *slot;
+ sslSessionID *sid = ss->sec.ci.sid;
+
+ slot = PK11_GetSlotFromPrivateKey(privKey);
+ sid->u.ssl3.clAuthSeries = PK11_GetSlotSeries(slot);
+ sid->u.ssl3.clAuthSlotID = PK11_GetSlotID(slot);
+ sid->u.ssl3.clAuthModuleID = PK11_GetModuleID(slot);
+ sid->u.ssl3.clAuthValid = PR_TRUE;
+ PK11_FreeSlot(slot);
+ }
+ if (rv != SECSuccess) {
+ goto done; /* err code was set by ssl3_SignHashes */
+ }
+
+ len = buf.len + 2 + 2;
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_certificate_verify, len);
+ if (rv != SECSuccess) {
+ goto done; /* error code set by AppendHandshake */
+ }
+
+ rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2);
+ if (rv != SECSuccess) {
+ goto done; /* err set by AppendHandshakeNumber */
+ }
+
+ rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
+ if (rv != SECSuccess) {
+ goto done; /* error code set by AppendHandshake */
+ }
+
+done:
+ /* For parity with the allocation functions, which don't use
+ * SECITEM_AllocItem(). */
+ if (buf.data)
+ PORT_Free(buf.data);
+ return rv;
+}
+
+/* Called from tls13_CompleteHandleHandshakeMessage() when it has deciphered a complete
+ * tls13 CertificateVerify message
+ * Caller must hold Handshake and RecvBuf locks.
+ */
+SECStatus
+tls13_HandleCertificateVerify(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ sslDelegatedCredential *dc = ss->xtnData.peerDelegCred;
+ CERTSubjectPublicKeyInfo *spki;
+ SECKEYPublicKey *pubKey = NULL;
+ SECItem signed_hash = { siBuffer, NULL, 0 };
+ SECStatus rv;
+ SSLSignatureScheme sigScheme;
+ SSLHashType hashAlg;
+ SSL3Hashes tbsHash;
+ SSL3Hashes hashes;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle certificate_verify handshake",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY,
+ wait_cert_verify);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = tls13_ComputeHandshakeHashes(ss, &hashes);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->firstHsDone) {
+ rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
+ } else {
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_certificate_verify, b, length);
+ }
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* Set the |spki| used to verify the handshake. When verifying with a
+ * delegated credential (DC), this corresponds to the DC public key;
+ * otherwise it correspond to the public key of the peer's end-entity
+ * certificate.
+ */
+ if (tls13_IsVerifyingWithDelegatedCredential(ss)) {
+ /* DelegatedCredential.cred.expected_cert_verify_algorithm is expected
+ * to match CertificateVerify.scheme.
+ * DelegatedCredential.cred.expected_cert_verify_algorithm must also be
+ * the same as was reported in ssl3_AuthCertificate.
+ */
+ if (sigScheme != dc->expectedCertVerifyAlg || sigScheme != ss->sec.signatureScheme) {
+ FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* Verify the DC has three steps: (1) use the peer's end-entity
+ * certificate to verify DelegatedCredential.signature, (2) check that
+ * the certificate has the correct key usage, and (3) check that the DC
+ * hasn't expired.
+ */
+ rv = tls13_VerifyDelegatedCredential(ss, dc);
+ if (rv != SECSuccess) { /* Calls FATAL_ERROR() */
+ return SECFailure;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: Verifying with delegated credential",
+ SSL_GETPID(), ss->fd));
+ spki = dc->spki;
+ } else {
+ spki = &ss->sec.peerCert->subjectPublicKeyInfo;
+ }
+
+ rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, spki);
+ if (rv != SECSuccess) {
+ /* Error set already */
+ FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
+ return SECFailure;
+ }
+ hashAlg = ssl_SignatureSchemeToHashType(sigScheme);
+
+ rv = tls13_AddContextToHashes(ss, &hashes, hashAlg, PR_FALSE, &tbsHash);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_DIGEST_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_VERIFY);
+ return SECFailure;
+ }
+
+ if (length != 0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_VERIFY, decode_error);
+ return SECFailure;
+ }
+
+ pubKey = SECKEY_ExtractPublicKey(spki);
+ if (pubKey == NULL) {
+ ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, sigScheme,
+ &tbsHash, &signed_hash);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), decrypt_error);
+ goto loser;
+ }
+
+ /* Set the auth type and verify it is what we captured in ssl3_AuthCertificate */
+ if (!ss->sec.isServer) {
+ ss->sec.authType = ssl_SignatureSchemeToAuthType(sigScheme);
+
+ uint32_t prelimAuthKeyBits = ss->sec.authKeyBits;
+ rv = ssl_SetAuthKeyBits(ss, pubKey);
+ if (rv != SECSuccess) {
+ goto loser; /* Alert sent and code set. */
+ }
+
+ if (prelimAuthKeyBits != ss->sec.authKeyBits) {
+ FATAL_ERROR(ss, SSL_ERROR_DC_CERT_VERIFY_ALG_MISMATCH, illegal_parameter);
+ goto loser;
+ }
+ }
+
+ /* Request a client certificate now if one was requested. */
+ if (ss->ssl3.hs.clientCertRequested) {
+ PORT_Assert(!ss->sec.isServer);
+ rv = ssl3_BeginHandleCertificateRequest(
+ ss, ss->xtnData.sigSchemes, ss->xtnData.numSigSchemes,
+ &ss->xtnData.certReqAuthorities);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+ }
+
+ SECKEY_DestroyPublicKey(pubKey);
+ TLS13_SET_HS_STATE(ss, wait_finished);
+ return SECSuccess;
+
+loser:
+ SECKEY_DestroyPublicKey(pubKey);
+ return SECFailure;
+}
+
+/* Compute the PSK binder hash over:
+ * Client HRR prefix, if present in ss->ssl3.hs.messages or ss->ssl3.hs.echInnerMessages,
+ * |len| bytes of |buf| */
+static SECStatus
+tls13_ComputePskBinderHash(sslSocket *ss, PRUint8 *b, size_t length,
+ SSL3Hashes *hashes, SSLHashType hashType)
+{
+ SECStatus rv;
+ PK11Context *ctx = NULL;
+ sslBuffer *clientResidual = NULL;
+ if (!ss->sec.isServer) {
+ /* On the server, HRR residual is already buffered. */
+ clientResidual = ss->ssl3.hs.echHpkeCtx ? &ss->ssl3.hs.echInnerMessages : &ss->ssl3.hs.messages;
+ }
+ PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ PRINT_BUF(10, (NULL, "Binder computed over ClientHello",
+ b, length));
+
+ ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hashType));
+ if (!ctx) {
+ goto loser;
+ }
+ rv = PK11_DigestBegin(ctx);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+
+ if (clientResidual && clientResidual->len) {
+ PRINT_BUF(10, (NULL, " with HRR prefix", clientResidual->buf,
+ clientResidual->len));
+ rv = PK11_DigestOp(ctx, clientResidual->buf, clientResidual->len);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+ }
+
+ rv = PK11_DigestOp(ctx, b, length);
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+ rv = PK11_DigestFinal(ctx, hashes->u.raw, &hashes->len, sizeof(hashes->u.raw));
+ if (rv != SECSuccess) {
+ ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+
+ PK11_DestroyContext(ctx, PR_TRUE);
+ PRINT_BUF(10, (NULL, "PSK Binder hash", hashes->u.raw, hashes->len));
+ return SECSuccess;
+
+loser:
+ if (ctx) {
+ PK11_DestroyContext(ctx, PR_TRUE);
+ }
+ return SECFailure;
+}
+
+/* Compute and inject the PSK Binder for sending.
+ *
+ * When sending a ClientHello, we construct all the extensions with a dummy
+ * value for the binder. To construct the binder, we commit the entire message
+ * up to the point where the binders start. Then we calculate the hash using
+ * the saved message (in ss->ssl3.hs.messages). This is written over the dummy
+ * binder, after which we write the remainder of the binder extension. */
+SECStatus
+tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions, sslBuffer *chBuf)
+{
+ SSL3Hashes hashes;
+ SECStatus rv;
+
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
+ sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+ unsigned int size = tls13_GetHashSizeForHash(psk->hash);
+ unsigned int prefixLen = extensions->len - size - 3;
+ unsigned int finishedLen;
+
+ PORT_Assert(extensions->len >= size + 3);
+
+ rv = sslBuffer_AppendNumber(chBuf, extensions->len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Only write the extension up to the point before the binders. Assume that
+ * the pre_shared_key extension is at the end of the buffer. Don't write
+ * the binder, or the lengths that precede it (a 2 octet length for the list
+ * of all binders, plus a 1 octet length for the binder length). */
+ rv = sslBuffer_Append(chBuf, extensions->buf, prefixLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Calculate the binder based on what has been written out. */
+ rv = tls13_ComputePskBinderHash(ss, chBuf->buf, chBuf->len, &hashes, psk->hash);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Write the binder into the extensions buffer, over the zeros we reserved
+ * previously. This avoids an allocation and means that we don't need a
+ * separate write for the extra bits that precede the binder. */
+ PORT_Assert(psk->binderKey);
+ rv = tls13_ComputeFinished(ss, psk->binderKey,
+ psk->hash, &hashes, PR_TRUE,
+ extensions->buf + extensions->len - size,
+ &finishedLen, size);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PORT_Assert(finishedLen == size);
+
+ /* Write out the remainder of the extension. */
+ rv = sslBuffer_Append(chBuf, extensions->buf + prefixLen,
+ extensions->len - prefixLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey,
+ SSLHashType hashType, const SSL3Hashes *hashes,
+ PRBool sending, PRUint8 *output, unsigned int *outputLen,
+ unsigned int maxOutputLen)
+{
+ SECStatus rv;
+ PK11Context *hmacCtx = NULL;
+ CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanismFromHash(hashType);
+ SECItem param = { siBuffer, NULL, 0 };
+ unsigned int outputLenUint;
+ const char *label = kHkdfLabelFinishedSecret;
+ PK11SymKey *secret = NULL;
+
+ PORT_Assert(baseKey);
+ SSL_TRC(3, ("%d: TLS13[%d]: %s calculate finished",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+ PRINT_BUF(50, (ss, "Handshake hash", hashes->u.raw, hashes->len));
+
+ /* Now derive the appropriate finished secret from the base secret. */
+ rv = tls13_HkdfExpandLabel(baseKey, hashType,
+ NULL, 0, label, strlen(label),
+ tls13_GetHmacMechanismFromHash(hashType),
+ tls13_GetHashSizeForHash(hashType),
+ ss->protocolVariant, &secret);
+ if (rv != SECSuccess) {
+ goto abort;
+ }
+
+ PORT_Assert(hashes->len == tls13_GetHashSizeForHash(hashType));
+ hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN,
+ secret, &param);
+ if (!hmacCtx) {
+ goto abort;
+ }
+
+ rv = PK11_DigestBegin(hmacCtx);
+ if (rv != SECSuccess)
+ goto abort;
+
+ rv = PK11_DigestOp(hmacCtx, hashes->u.raw, hashes->len);
+ if (rv != SECSuccess)
+ goto abort;
+
+ PORT_Assert(maxOutputLen >= tls13_GetHashSizeForHash(hashType));
+ rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen);
+ if (rv != SECSuccess)
+ goto abort;
+ *outputLen = outputLenUint;
+
+ PK11_FreeSymKey(secret);
+ PK11_DestroyContext(hmacCtx, PR_TRUE);
+ PRINT_BUF(50, (ss, "finished value", output, outputLenUint));
+ return SECSuccess;
+
+abort:
+ if (secret) {
+ PK11_FreeSymKey(secret);
+ }
+
+ if (hmacCtx) {
+ PK11_DestroyContext(hmacCtx, PR_TRUE);
+ }
+
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey)
+{
+ SECStatus rv;
+ PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
+ unsigned int finishedLen;
+ SSL3Hashes hashes;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send finished handshake", SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ rv = tls13_ComputeHandshakeHashes(ss, &hashes);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ssl_GetSpecReadLock(ss);
+ rv = tls13_ComputeFinished(ss, baseKey, tls13_GetHash(ss), &hashes, PR_TRUE,
+ finishedBuf, &finishedLen, sizeof(finishedBuf));
+ ssl_ReleaseSpecReadLock(ss);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_finished, finishedLen);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code already set. */
+ }
+
+ rv = ssl3_AppendHandshake(ss, finishedBuf, finishedLen);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code already set. */
+ }
+
+ /* TODO(ekr@rtfm.com): Record key log */
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_VerifyFinished(sslSocket *ss, SSLHandshakeType message,
+ PK11SymKey *secret,
+ PRUint8 *b, PRUint32 length,
+ const SSL3Hashes *hashes)
+{
+ SECStatus rv;
+ PRUint8 finishedBuf[TLS13_MAX_FINISHED_SIZE];
+ unsigned int finishedLen;
+
+ if (!hashes) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ rv = tls13_ComputeFinished(ss, secret, tls13_GetHash(ss), hashes, PR_FALSE,
+ finishedBuf, &finishedLen, sizeof(finishedBuf));
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ if (length != finishedLen) {
+#ifndef UNSAFE_FUZZER_MODE
+ FATAL_ERROR(ss, message == ssl_hs_finished ? SSL_ERROR_RX_MALFORMED_FINISHED : SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+#endif
+ }
+
+ if (NSS_SecureMemcmp(b, finishedBuf, finishedLen) != 0) {
+#ifndef UNSAFE_FUZZER_MODE
+ FATAL_ERROR(ss, SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE,
+ decrypt_error);
+ return SECFailure;
+#endif
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_CommonHandleFinished(sslSocket *ss, PK11SymKey *key,
+ PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ SSL3Hashes hashes;
+
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED,
+ wait_finished);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ ss->ssl3.hs.endOfFlight = PR_TRUE;
+
+ rv = tls13_ComputeHandshakeHashes(ss, &hashes);
+ if (rv != SECSuccess) {
+ LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ if (ss->firstHsDone) {
+ rv = ssl_HashPostHandshakeMessage(ss, ssl_hs_finished, b, length);
+ } else {
+ rv = ssl_HashHandshakeMessage(ss, ssl_hs_finished, b, length);
+ }
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ return tls13_VerifyFinished(ss, ssl_hs_finished,
+ key, b, length, &hashes);
+}
+
+static SECStatus
+tls13_ClientHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: TLS13[%d]: client handle finished handshake",
+ SSL_GETPID(), ss->fd));
+
+ rv = tls13_CommonHandleFinished(ss, ss->ssl3.hs.serverHsTrafficSecret,
+ b, length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return tls13_SendClientSecondRound(ss);
+}
+
+static SECStatus
+tls13_ServerHandleFinished(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ SSL_TRC(3, ("%d: TLS13[%d]: server handle finished handshake",
+ SSL_GETPID(), ss->fd));
+
+ if (!tls13_ShouldRequestClientAuth(ss)) {
+ /* Receiving this message might be the first sign we have that
+ * early data is over, so pretend we received EOED. */
+ rv = tls13_MaybeHandleSuppressedEndOfEarlyData(ss);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Code already set. */
+ }
+
+ if (!tls13_IsPostHandshake(ss)) {
+ /* Finalize the RTT estimate. */
+ ss->ssl3.hs.rttEstimate = ssl_Time(ss) - ss->ssl3.hs.rttEstimate;
+ }
+ }
+
+ rv = tls13_CommonHandleFinished(ss,
+ ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret,
+ b, length);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->firstHsDone) {
+ TLS13_SET_HS_STATE(ss, idle_handshake);
+
+ PORT_Assert(ss->ssl3.hs.shaPostHandshake != NULL);
+ PK11_DestroyContext(ss->ssl3.hs.shaPostHandshake, PR_TRUE);
+ ss->ssl3.hs.shaPostHandshake = NULL;
+
+ ss->ssl3.clientCertRequested = PR_FALSE;
+
+ if (ss->ssl3.keyUpdateDeferred) {
+ rv = tls13_SendKeyUpdate(ss, ss->ssl3.deferredKeyUpdateRequest,
+ PR_FALSE);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error is set. */
+ }
+ ss->ssl3.keyUpdateDeferred = PR_FALSE;
+ }
+
+ return SECSuccess;
+ }
+
+ if (!tls13_ShouldRequestClientAuth(ss) &&
+ (ss->ssl3.hs.zeroRttState != ssl_0rtt_done)) {
+ dtls_ReceivedFirstMessageInFlight(ss);
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
+ ssl_secret_read, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ if (IS_DTLS(ss)) {
+ ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read, TrafficKeyClearText);
+ /* We need to keep the handshake cipher spec so we can
+ * read re-transmitted client Finished. */
+ rv = dtls_StartTimer(ss, ss->ssl3.hs.hdTimer,
+ DTLS_RETRANSMIT_FINISHED_MS,
+ dtls13_HolddownTimerCb);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ rv = tls13_ComputeFinalSecrets(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = tls13_FinishHandshake(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ ssl_GetXmitBufLock(ss);
+ /* If resumption, authType is the original value and not ssl_auth_psk. */
+ if (ss->opt.enableSessionTickets && ss->sec.authType != ssl_auth_psk) {
+ rv = tls13_SendNewSessionTicket(ss, NULL, 0);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = ssl3_FlushHandshake(ss, 0);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ ssl_ReleaseXmitBufLock(ss);
+ return SECSuccess;
+
+loser:
+ ssl_ReleaseXmitBufLock(ss);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_FinishHandshake(sslSocket *ss)
+{
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+ PORT_Assert(ss->ssl3.hs.restartTarget == NULL);
+
+ /* The first handshake is now completed. */
+ ss->handshake = NULL;
+
+ /* Don't need this. */
+ PK11_FreeSymKey(ss->ssl3.hs.clientHsTrafficSecret);
+ ss->ssl3.hs.clientHsTrafficSecret = NULL;
+ PK11_FreeSymKey(ss->ssl3.hs.serverHsTrafficSecret);
+ ss->ssl3.hs.serverHsTrafficSecret = NULL;
+
+ TLS13_SET_HS_STATE(ss, idle_handshake);
+
+ return ssl_FinishHandshake(ss);
+}
+
+/* Do the parts of sending the client's second round that require
+ * the XmitBuf lock. */
+static SECStatus
+tls13_SendClientSecondFlight(sslSocket *ss)
+{
+ SECStatus rv;
+ unsigned int offset = 0;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+ PORT_Assert(!ss->ssl3.hs.clientCertificatePending);
+
+ PRBool sendClientCert = !ss->ssl3.sendEmptyCert &&
+ ss->ssl3.clientCertChain != NULL &&
+ ss->ssl3.clientPrivateKey != NULL;
+
+ if (ss->firstHsDone) {
+ offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
+ }
+
+ if (ss->ssl3.sendEmptyCert) {
+ ss->ssl3.sendEmptyCert = PR_FALSE;
+ rv = ssl3_SendEmptyCertificate(ss);
+ /* Don't send verify */
+ if (rv != SECSuccess) {
+ goto alert_error; /* error code is set. */
+ }
+ } else if (sendClientCert) {
+ rv = tls13_SendCertificate(ss);
+ if (rv != SECSuccess) {
+ goto alert_error; /* err code was set. */
+ }
+ }
+
+ if (ss->firstHsDone) {
+ rv = ssl3_UpdatePostHandshakeHashes(ss,
+ SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
+ SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
+ if (rv != SECSuccess) {
+ goto alert_error; /* err code was set. */
+ }
+ }
+
+ if (ss->ssl3.hs.clientCertRequested) {
+ SECITEM_FreeItem(&ss->xtnData.certReqContext, PR_FALSE);
+ if (ss->xtnData.certReqAuthorities.arena) {
+ PORT_FreeArena(ss->xtnData.certReqAuthorities.arena, PR_FALSE);
+ ss->xtnData.certReqAuthorities.arena = NULL;
+ }
+ PORT_Memset(&ss->xtnData.certReqAuthorities, 0,
+ sizeof(ss->xtnData.certReqAuthorities));
+ ss->ssl3.hs.clientCertRequested = PR_FALSE;
+ }
+
+ if (sendClientCert) {
+ if (ss->firstHsDone) {
+ offset = SSL_BUFFER_LEN(&ss->sec.ci.sendBuf);
+ }
+
+ rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey);
+ SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
+ ss->ssl3.clientPrivateKey = NULL;
+ if (rv != SECSuccess) {
+ goto alert_error; /* err code was set. */
+ }
+
+ if (ss->firstHsDone) {
+ rv = ssl3_UpdatePostHandshakeHashes(ss,
+ SSL_BUFFER_BASE(&ss->sec.ci.sendBuf) + offset,
+ SSL_BUFFER_LEN(&ss->sec.ci.sendBuf) - offset);
+ if (rv != SECSuccess) {
+ goto alert_error; /* err code was set. */
+ }
+ }
+ }
+
+ rv = tls13_SendFinished(ss, ss->firstHsDone ? ss->ssl3.hs.clientTrafficSecret : ss->ssl3.hs.clientHsTrafficSecret);
+ if (rv != SECSuccess) {
+ goto alert_error; /* err code was set. */
+ }
+ rv = ssl3_FlushHandshake(ss, 0);
+ if (rv != SECSuccess) {
+ /* No point in sending an alert here because we're not going to
+ * be able to send it if we couldn't flush the handshake. */
+ goto error;
+ }
+
+ return SECSuccess;
+
+alert_error:
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+error:
+ LOG_ERROR(ss, PORT_GetError());
+ return SECFailure;
+}
+
+static SECStatus
+tls13_SendClientSecondRound(sslSocket *ss)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss));
+ PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
+
+ /* Defer client authentication sending if we are still waiting for server
+ * authentication. This avoids unnecessary disclosure of client credentials
+ * to an unauthenticated server.
+ */
+ if (ss->ssl3.hs.restartTarget) {
+ PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+ if (ss->ssl3.hs.authCertificatePending || ss->ssl3.hs.clientCertificatePending) {
+ SSL_TRC(3, ("%d: TLS13[%d]: deferring tls13_SendClientSecondRound because"
+ " certificate authentication is still pending.",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound;
+ PORT_SetError(PR_WOULD_BLOCK_ERROR);
+ return SECFailure;
+ }
+
+ rv = tls13_ComputeApplicationSecrets(ss);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) {
+ ssl_GetXmitBufLock(ss); /*******************************/
+ rv = tls13_SendEndOfEarlyData(ss);
+ ssl_ReleaseXmitBufLock(ss); /*******************************/
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error code already set. */
+ }
+ } else if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss) &&
+ ss->ssl3.hs.zeroRttState == ssl_0rtt_none &&
+ !ss->ssl3.hs.helloRetry) {
+ ssl_GetXmitBufLock(ss); /*******************************/
+ rv = ssl3_SendChangeCipherSpecsInt(ss);
+ ssl_ReleaseXmitBufLock(ss); /*******************************/
+ if (rv != SECSuccess) {
+ return rv;
+ }
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
+ ssl_secret_write, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
+ ssl_secret_read, PR_FALSE);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ ssl_GetXmitBufLock(ss); /*******************************/
+ /* This call can't block, as clientAuthCertificatePending is checked above */
+ rv = tls13_SendClientSecondFlight(ss);
+ ssl_ReleaseXmitBufLock(ss); /*******************************/
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData,
+ ssl_secret_write, PR_FALSE);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ rv = tls13_ComputeFinalSecrets(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* The handshake is now finished */
+ return tls13_FinishHandshake(ss);
+}
+
+/*
+ * enum { (65535) } TicketExtensionType;
+ *
+ * struct {
+ * TicketExtensionType extension_type;
+ * opaque extension_data<0..2^16-1>;
+ * } TicketExtension;
+ *
+ * struct {
+ * uint32 ticket_lifetime;
+ * uint32 ticket_age_add;
+ * opaque ticket_nonce<1..255>;
+ * opaque ticket<1..2^16-1>;
+ * TicketExtension extensions<0..2^16-2>;
+ * } NewSessionTicket;
+ */
+
+static SECStatus
+tls13_SendNewSessionTicket(sslSocket *ss, const PRUint8 *appToken,
+ unsigned int appTokenLen)
+{
+ PRUint16 message_length;
+ PK11SymKey *secret;
+ SECItem ticket_data = { 0, NULL, 0 };
+ SECStatus rv;
+ NewSessionTicket ticket = { 0 };
+ PRUint32 max_early_data_size_len = 0;
+ PRUint32 greaseLen = 0;
+ PRUint8 ticketNonce[sizeof(ss->ssl3.hs.ticketNonce)];
+ sslBuffer ticketNonceBuf = SSL_BUFFER(ticketNonce);
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send new session ticket message %d",
+ SSL_GETPID(), ss->fd, ss->ssl3.hs.ticketNonce));
+
+ ticket.flags = 0;
+ if (ss->opt.enable0RttData) {
+ ticket.flags |= ticket_allow_early_data;
+ max_early_data_size_len = 8; /* type + len + value. */
+ }
+ ticket.ticket_lifetime_hint = ssl_ticket_lifetime;
+
+ if (ss->opt.enableGrease) {
+ greaseLen = 4; /* type + len + 0 (empty) */
+ }
+
+ /* The ticket age obfuscator. */
+ rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add,
+ sizeof(ticket.ticket_age_add));
+ if (rv != SECSuccess)
+ goto loser;
+
+ rv = sslBuffer_AppendNumber(&ticketNonceBuf, ss->ssl3.hs.ticketNonce,
+ sizeof(ticketNonce));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ ++ss->ssl3.hs.ticketNonce;
+ rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
+ tls13_GetHash(ss),
+ ticketNonce, sizeof(ticketNonce),
+ kHkdfLabelResumption,
+ strlen(kHkdfLabelResumption),
+ CKM_HKDF_DERIVE,
+ tls13_GetHashSize(ss),
+ ss->protocolVariant, &secret);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl3_EncodeSessionTicket(ss, &ticket, appToken, appTokenLen,
+ secret, &ticket_data);
+ PK11_FreeSymKey(secret);
+ if (rv != SECSuccess)
+ goto loser;
+
+ message_length =
+ 4 + /* lifetime */
+ 4 + /* ticket_age_add */
+ 1 + sizeof(ticketNonce) + /* ticket_nonce */
+ 2 + /* extensions lentgh */
+ max_early_data_size_len + /* max_early_data_size extension length */
+ greaseLen + /* GREASE extension length */
+ 2 + /* ticket length */
+ ticket_data.len;
+
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_new_session_ticket,
+ message_length);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* This is a fixed value. */
+ rv = ssl3_AppendHandshakeNumber(ss, ssl_ticket_lifetime, 4);
+ if (rv != SECSuccess)
+ goto loser;
+
+ rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* The ticket nonce. */
+ rv = ssl3_AppendHandshakeVariable(ss, ticketNonce, sizeof(ticketNonce), 1);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Encode the ticket. */
+ rv = ssl3_AppendHandshakeVariable(
+ ss, ticket_data.data, ticket_data.len, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Extensions */
+ rv = ssl3_AppendHandshakeNumber(ss, max_early_data_size_len + greaseLen, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* GREASE NewSessionTicket:
+ * When sending a NewSessionTicket message in TLS 1.3, a server MAY select
+ * one or more GREASE extension values and advertise them as extensions
+ * with varying length and contents [RFC8701, SEction 4.1]. */
+ if (ss->opt.enableGrease) {
+ PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ PRUint16 grease;
+ rv = tls13_RandomGreaseValue(&grease);
+ if (rv != SECSuccess)
+ goto loser;
+ /* Extension type */
+ rv = ssl3_AppendHandshakeNumber(ss, grease, 2);
+ if (rv != SECSuccess)
+ goto loser;
+ /* Extension length */
+ rv = ssl3_AppendHandshakeNumber(ss, 0, 2);
+ if (rv != SECSuccess)
+ goto loser;
+ }
+
+ /* Max early data size extension. */
+ if (max_early_data_size_len) {
+ rv = ssl3_AppendHandshakeNumber(
+ ss, ssl_tls13_early_data_xtn, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ /* Length */
+ rv = ssl3_AppendHandshakeNumber(ss, 4, 2);
+ if (rv != SECSuccess)
+ goto loser;
+
+ rv = ssl3_AppendHandshakeNumber(ss, ss->opt.maxEarlyDataSize, 4);
+ if (rv != SECSuccess)
+ goto loser;
+ }
+
+ SECITEM_FreeItem(&ticket_data, PR_FALSE);
+ return SECSuccess;
+
+loser:
+ if (ticket_data.data) {
+ SECITEM_FreeItem(&ticket_data, PR_FALSE);
+ }
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
+ unsigned int tokenLen)
+{
+ sslSocket *ss;
+ SECStatus rv;
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure;
+ }
+
+ if (IS_DTLS(ss)) {
+ PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION);
+ return SECFailure;
+ }
+
+ if (!ss->sec.isServer || !tls13_IsPostHandshake(ss) ||
+ tokenLen > 0xffff) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* Disable tickets if we can trace this connection back to a PSK.
+ * We aren't able to issue tickets (currently) without a certificate.
+ * As PSK =~ resumption, there is no reason to do this. */
+ if (ss->sec.authType == ssl_auth_psk) {
+ PORT_SetError(SSL_ERROR_FEATURE_DISABLED);
+ return SECFailure;
+ }
+
+ ssl_GetSSL3HandshakeLock(ss);
+ ssl_GetXmitBufLock(ss);
+ rv = tls13_SendNewSessionTicket(ss, token, tokenLen);
+ if (rv == SECSuccess) {
+ rv = ssl3_FlushHandshake(ss, 0);
+ }
+ ssl_ReleaseXmitBufLock(ss);
+ ssl_ReleaseSSL3HandshakeLock(ss);
+
+ return rv;
+}
+
+static SECStatus
+tls13_HandleNewSessionTicket(sslSocket *ss, PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+ PRUint32 utmp;
+ NewSessionTicket ticket = { 0 };
+ SECItem data;
+ SECItem ticket_nonce;
+ SECItem ticket_data;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle new session ticket message",
+ SSL_GETPID(), ss->fd));
+
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
+ idle_handshake);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (!tls13_IsPostHandshake(ss) || ss->sec.isServer) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET,
+ unexpected_message);
+ return SECFailure;
+ }
+
+ ticket.received_timestamp = ssl_Time(ss);
+ rv = ssl3_ConsumeHandshakeNumber(ss, &ticket.ticket_lifetime_hint, 4, &b,
+ &length);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
+ decode_error);
+ return SECFailure;
+ }
+ ticket.ticket.type = siBuffer;
+
+ rv = ssl3_ConsumeHandshake(ss, &utmp, sizeof(utmp),
+ &b, &length);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+ ticket.ticket_age_add = PR_ntohl(utmp);
+
+ /* The nonce. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_nonce, 1, &b, &length);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
+ decode_error);
+ return SECFailure;
+ }
+
+ /* Get the ticket value. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, &ticket_data, 2, &b, &length);
+ if (rv != SECSuccess || !ticket_data.len) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
+ decode_error);
+ return SECFailure;
+ }
+
+ /* Parse extensions. */
+ rv = ssl3_ConsumeHandshakeVariable(ss, &data, 2, &b, &length);
+ if (rv != SECSuccess || length) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
+ decode_error);
+ return SECFailure;
+ }
+
+ rv = ssl3_HandleExtensions(ss, &data.data,
+ &data.len, ssl_hs_new_session_ticket);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET,
+ decode_error);
+ return SECFailure;
+ }
+ if (ss->xtnData.max_early_data_size) {
+ ticket.flags |= ticket_allow_early_data;
+ ticket.max_early_data_size = ss->xtnData.max_early_data_size;
+ }
+
+ if (!ss->opt.noCache) {
+ PK11SymKey *secret;
+
+ PORT_Assert(ss->sec.ci.sid);
+ rv = SECITEM_CopyItem(NULL, &ticket.ticket, &ticket_data);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ return SECFailure;
+ }
+ PRINT_BUF(50, (ss, "Caching session ticket",
+ ticket.ticket.data,
+ ticket.ticket.len));
+
+ /* Replace a previous session ticket when
+ * we receive a second NewSessionTicket message. */
+ if (ss->sec.ci.sid->cached == in_client_cache ||
+ ss->sec.ci.sid->cached == in_external_cache) {
+ /* Create a new session ID. */
+ sslSessionID *sid = ssl3_NewSessionID(ss, PR_FALSE);
+ if (!sid) {
+ return SECFailure;
+ }
+
+ /* Copy over the peerCert. */
+ PORT_Assert(ss->sec.ci.sid->peerCert);
+ sid->peerCert = CERT_DupCertificate(ss->sec.ci.sid->peerCert);
+ if (!sid->peerCert) {
+ ssl_FreeSID(sid);
+ return SECFailure;
+ }
+
+ /* Destroy the old SID. */
+ ssl_UncacheSessionID(ss);
+ ssl_FreeSID(ss->sec.ci.sid);
+ ss->sec.ci.sid = sid;
+ }
+
+ ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket);
+ PORT_Assert(!ticket.ticket.data);
+
+ rv = tls13_HkdfExpandLabel(ss->ssl3.hs.resumptionMasterSecret,
+ tls13_GetHash(ss),
+ ticket_nonce.data, ticket_nonce.len,
+ kHkdfLabelResumption,
+ strlen(kHkdfLabelResumption),
+ CKM_HKDF_DERIVE,
+ tls13_GetHashSize(ss),
+ ss->protocolVariant, &secret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid, secret);
+ PK11_FreeSymKey(secret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Cache the session. */
+ ssl_CacheSessionID(ss);
+ }
+
+ return SECSuccess;
+}
+
+#define _M_NONE 0
+#define _M(a) (1 << PR_MIN(a, 31))
+#define _M1(a) (_M(ssl_hs_##a))
+#define _M2(a, b) (_M1(a) | _M1(b))
+#define _M3(a, b, c) (_M1(a) | _M2(b, c))
+
+static const struct {
+ PRUint16 ex_value;
+ PRUint32 messages;
+} KnownExtensions[] = {
+ { ssl_server_name_xtn, _M2(client_hello, encrypted_extensions) },
+ { ssl_supported_groups_xtn, _M2(client_hello, encrypted_extensions) },
+ { ssl_signature_algorithms_xtn, _M2(client_hello, certificate_request) },
+ { ssl_signature_algorithms_cert_xtn, _M2(client_hello,
+ certificate_request) },
+ { ssl_use_srtp_xtn, _M2(client_hello, encrypted_extensions) },
+ { ssl_app_layer_protocol_xtn, _M2(client_hello, encrypted_extensions) },
+ { ssl_padding_xtn, _M1(client_hello) },
+ { ssl_tls13_key_share_xtn, _M3(client_hello, server_hello,
+ hello_retry_request) },
+ { ssl_tls13_pre_shared_key_xtn, _M2(client_hello, server_hello) },
+ { ssl_tls13_psk_key_exchange_modes_xtn, _M1(client_hello) },
+ { ssl_tls13_early_data_xtn, _M3(client_hello, encrypted_extensions,
+ new_session_ticket) },
+ { ssl_signed_cert_timestamp_xtn, _M3(client_hello, certificate_request,
+ certificate) },
+ { ssl_cert_status_xtn, _M3(client_hello, certificate_request,
+ certificate) },
+ { ssl_delegated_credentials_xtn, _M2(client_hello, certificate) },
+ { ssl_tls13_cookie_xtn, _M2(client_hello, hello_retry_request) },
+ { ssl_tls13_certificate_authorities_xtn, _M2(client_hello, certificate_request) },
+ { ssl_tls13_supported_versions_xtn, _M3(client_hello, server_hello,
+ hello_retry_request) },
+ { ssl_record_size_limit_xtn, _M2(client_hello, encrypted_extensions) },
+ { ssl_tls13_encrypted_client_hello_xtn, _M3(client_hello, encrypted_extensions, hello_retry_request) },
+ { ssl_tls13_outer_extensions_xtn, _M_NONE /* Encoding/decoding only */ },
+ { ssl_tls13_post_handshake_auth_xtn, _M1(client_hello) }
+};
+
+tls13ExtensionStatus
+tls13_ExtensionStatus(PRUint16 extension, SSLHandshakeType message)
+{
+ unsigned int i;
+
+ PORT_Assert((message == ssl_hs_client_hello) ||
+ (message == ssl_hs_server_hello) ||
+ (message == ssl_hs_hello_retry_request) ||
+ (message == ssl_hs_encrypted_extensions) ||
+ (message == ssl_hs_new_session_ticket) ||
+ (message == ssl_hs_certificate) ||
+ (message == ssl_hs_certificate_request));
+
+ for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions); i++) {
+ /* Hacky check for message numbers > 30. */
+ PORT_Assert(!(KnownExtensions[i].messages & (1U << 31)));
+ if (KnownExtensions[i].ex_value == extension) {
+ break;
+ }
+ }
+ if (i >= PR_ARRAY_SIZE(KnownExtensions)) {
+ return tls13_extension_unknown;
+ }
+
+ /* Return "disallowed" if the message mask bit isn't set. */
+ if (!(_M(message) & KnownExtensions[i].messages)) {
+ return tls13_extension_disallowed;
+ }
+
+ return tls13_extension_allowed;
+}
+
+#undef _M
+#undef _M1
+#undef _M2
+#undef _M3
+
+/* We cheat a bit on additional data because the AEAD interface
+ * which doesn't have room for the record number. The AAD we
+ * format is serialized record number followed by the true AD
+ * (i.e., the record header) plus the serialized record number. */
+static SECStatus
+tls13_FormatAdditionalData(
+ sslSocket *ss,
+ const PRUint8 *header, unsigned int headerLen,
+ DTLSEpoch epoch, sslSequenceNumber seqNum,
+ PRUint8 *aad, unsigned int *aadLength, unsigned int maxLength)
+{
+ SECStatus rv;
+ sslBuffer buf = SSL_BUFFER_FIXED(aad, maxLength);
+
+ if (IS_DTLS(ss)) {
+ rv = sslBuffer_AppendNumber(&buf, epoch, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ rv = sslBuffer_AppendNumber(&buf, seqNum, IS_DTLS(ss) ? 6 : 8);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_Append(&buf, header, headerLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *aadLength = buf.len;
+
+ return SECSuccess;
+}
+
+PRInt32
+tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend)
+{
+ PRInt32 reduced;
+
+ PORT_Assert(type == ssl_ct_application_data);
+ PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
+ PORT_Assert(!ss->firstHsDone);
+ if (ss->ssl3.cwSpec->epoch != TrafficKeyEarlyApplicationData) {
+ return toSend;
+ }
+
+ if (IS_DTLS(ss) && toSend > ss->ssl3.cwSpec->earlyDataRemaining) {
+ /* Don't split application data records in DTLS. */
+ return 0;
+ }
+
+ reduced = PR_MIN(toSend, ss->ssl3.cwSpec->earlyDataRemaining);
+ ss->ssl3.cwSpec->earlyDataRemaining -= reduced;
+ return reduced;
+}
+
+SECStatus
+tls13_ProtectRecord(sslSocket *ss,
+ ssl3CipherSpec *cwSpec,
+ SSLContentType type,
+ const PRUint8 *pIn,
+ PRUint32 contentLen,
+ sslBuffer *wrBuf)
+{
+ const ssl3BulkCipherDef *cipher_def = cwSpec->cipherDef;
+ const int tagLen = cipher_def->tag_size;
+ SECStatus rv;
+
+ PORT_Assert(cwSpec->direction == ssl_secret_write);
+ SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) protect 0x%0llx len=%u",
+ SSL_GETPID(), ss->fd, cwSpec, cwSpec->epoch, cwSpec->phase,
+ cwSpec->nextSeqNum, contentLen));
+
+ if (contentLen + 1 + tagLen > SSL_BUFFER_SPACE(wrBuf)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Copy the data into the wrBuf. We're going to encrypt in-place
+ * in the AEAD branch anyway */
+ PORT_Memcpy(SSL_BUFFER_NEXT(wrBuf), pIn, contentLen);
+
+ if (cipher_def->calg == ssl_calg_null) {
+ /* Shortcut for plaintext */
+ rv = sslBuffer_Skip(wrBuf, contentLen, NULL);
+ PORT_Assert(rv == SECSuccess);
+ } else {
+ PRUint8 hdr[13];
+ sslBuffer buf = SSL_BUFFER_FIXED(hdr, sizeof(hdr));
+ PRBool needsLength;
+ PRUint8 aad[21];
+ const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
+ unsigned int ivOffset = ivLen - sizeof(sslSequenceNumber);
+ unsigned char ivOut[MAX_IV_LENGTH];
+
+ unsigned int aadLen;
+ unsigned int len;
+
+ PORT_Assert(cipher_def->type == type_aead);
+
+ /* If the following condition holds, we can skip the padding logic for
+ * DTLS 1.3 (4.2.3). This will be the case until we support a cipher
+ * with tag length < 15B. */
+ PORT_Assert(tagLen + 1 /* cType */ >= 16);
+
+ /* Add the content type at the end. */
+ *(SSL_BUFFER_NEXT(wrBuf) + contentLen) = type;
+
+ /* Create the header (ugly that we have to do it twice). */
+ rv = ssl_InsertRecordHeader(ss, cwSpec, ssl_ct_application_data,
+ &buf, &needsLength);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (needsLength) {
+ rv = sslBuffer_AppendNumber(&buf, contentLen + 1 + tagLen, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ rv = tls13_FormatAdditionalData(ss, SSL_BUFFER_BASE(&buf), SSL_BUFFER_LEN(&buf),
+ cwSpec->epoch, cwSpec->nextSeqNum,
+ aad, &aadLen, sizeof(aad));
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* set up initial IV value */
+ ivOffset = tls13_SetupAeadIv(IS_DTLS(ss), ivOut, cwSpec->keyMaterial.iv,
+ ivOffset, ivLen, cwSpec->epoch);
+
+ rv = tls13_AEAD(cwSpec->cipherContext, PR_FALSE,
+ CKG_GENERATE_COUNTER_XOR, ivOffset * BPB,
+ ivOut, ivOut, ivLen, /* iv */
+ NULL, 0, /* nonce */
+ aad + sizeof(sslSequenceNumber), /* aad */
+ aadLen - sizeof(sslSequenceNumber),
+ SSL_BUFFER_NEXT(wrBuf), /* output */
+ &len, /* out len */
+ SSL_BUFFER_SPACE(wrBuf), /* max out */
+ tagLen,
+ SSL_BUFFER_NEXT(wrBuf), /* input */
+ contentLen + 1); /* input len */
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
+ return SECFailure;
+ }
+ rv = sslBuffer_Skip(wrBuf, len, NULL);
+ PORT_Assert(rv == SECSuccess);
+ }
+
+ return SECSuccess;
+}
+
+/* Unprotect a TLS 1.3 record and leave the result in plaintext.
+ *
+ * Called by ssl3_HandleRecord. Caller must hold the spec read lock.
+ * Therefore, we MUST not call SSL3_SendAlert().
+ *
+ * If SECFailure is returned, we:
+ * 1. Set |*alert| to the alert to be sent.
+ * 2. Call PORT_SetError() with an appropriate code.
+ */
+SECStatus
+tls13_UnprotectRecord(sslSocket *ss,
+ ssl3CipherSpec *spec,
+ SSL3Ciphertext *cText,
+ sslBuffer *plaintext,
+ SSLContentType *innerType,
+ SSL3AlertDescription *alert)
+{
+ const ssl3BulkCipherDef *cipher_def = spec->cipherDef;
+ const int ivLen = cipher_def->iv_size + cipher_def->explicit_nonce_size;
+ const int tagLen = cipher_def->tag_size;
+ const int innerTypeLen = 1;
+
+ PRUint8 aad[21];
+ unsigned int aadLen;
+ SECStatus rv;
+
+ *alert = bad_record_mac; /* Default alert for most issues. */
+
+ PORT_Assert(spec->direction == ssl_secret_read);
+ SSL_TRC(3, ("%d: TLS13[%d]: spec=%d epoch=%d (%s) unprotect 0x%0llx len=%u",
+ SSL_GETPID(), ss->fd, spec, spec->epoch, spec->phase,
+ cText->seqNum, cText->buf->len));
+
+ /* Verify that the outer content type is right.
+ *
+ * For the inner content type as well as lower TLS versions this is checked
+ * in ssl3con.c/ssl3_HandleNonApllicationData().
+ *
+ * For DTLS 1.3 this is checked in ssl3gthr.c/dtls_GatherData(). DTLS drops
+ * invalid records silently [RFC6347, Section 4.1.2.7].
+ *
+ * Also allow the DTLS short header in TLS 1.3. */
+ if (!(cText->hdr[0] == ssl_ct_application_data ||
+ (IS_DTLS(ss) &&
+ ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 &&
+ (cText->hdr[0] & 0xe0) == 0x20))) {
+ SSL_TRC(3,
+ ("%d: TLS13[%d]: record has invalid exterior type=%2.2x",
+ SSL_GETPID(), ss->fd, cText->hdr[0]));
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_RECORD_TYPE);
+ *alert = unexpected_message;
+ return SECFailure;
+ }
+
+ /* We can perform this test in variable time because the record's total
+ * length and the ciphersuite are both public knowledge. */
+ if (cText->buf->len < tagLen) {
+ SSL_TRC(3,
+ ("%d: TLS13[%d]: record too short to contain valid AEAD data",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+ return SECFailure;
+ }
+
+ /* Check if the ciphertext can be valid if we assume maximum plaintext and
+ * add the specific ciphersuite expansion.
+ * This way we detect overlong plaintexts/padding before decryption.
+ * This check enforces size limitations more strict than the RFC.
+ * (see RFC8446, Section 5.2) */
+ if (cText->buf->len > (spec->recordSizeLimit + innerTypeLen + tagLen)) {
+ *alert = record_overflow;
+ PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+ return SECFailure;
+ }
+
+ /* Check the version number in the record. Stream only. */
+ if (!IS_DTLS(ss)) {
+ SSL3ProtocolVersion version =
+ ((SSL3ProtocolVersion)cText->hdr[1] << 8) |
+ (SSL3ProtocolVersion)cText->hdr[2];
+ if (version != spec->recordVersion) {
+ /* Do we need a better error here? */
+ SSL_TRC(3, ("%d: TLS13[%d]: record has bogus version",
+ SSL_GETPID(), ss->fd));
+ return SECFailure;
+ }
+ }
+
+ /* Decrypt */
+ PORT_Assert(cipher_def->type == type_aead);
+ rv = tls13_FormatAdditionalData(ss, cText->hdr, cText->hdrLen,
+ spec->epoch, cText->seqNum,
+ aad, &aadLen, sizeof(aad));
+ if (rv != SECSuccess) {
+
+ return SECFailure;
+ }
+ rv = tls13_AEAD(spec->cipherContext, PR_TRUE,
+ CKG_NO_GENERATE, 0, /* ignored for decrypt */
+ spec->keyMaterial.iv, NULL, ivLen, /* iv */
+ aad, sizeof(sslSequenceNumber), /* nonce */
+ aad + sizeof(sslSequenceNumber), /* aad */
+ aadLen - sizeof(sslSequenceNumber),
+ plaintext->buf, /* output */
+ &plaintext->len, /* outlen */
+ plaintext->space, /* maxout */
+ tagLen,
+ cText->buf->buf, /* in */
+ cText->buf->len); /* inlen */
+ if (rv != SECSuccess) {
+ if (IS_DTLS(ss)) {
+ spec->deprotectionFailures++;
+ }
+
+ SSL_TRC(3,
+ ("%d: TLS13[%d]: record has bogus MAC",
+ SSL_GETPID(), ss->fd));
+ PORT_SetError(SSL_ERROR_BAD_MAC_READ);
+ return SECFailure;
+ }
+
+ /* There is a similar test in ssl3_HandleRecord, but this test is needed to
+ * account for padding. */
+ if (plaintext->len > spec->recordSizeLimit + innerTypeLen) {
+ *alert = record_overflow;
+ PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
+ return SECFailure;
+ }
+
+ /* The record is right-padded with 0s, followed by the true
+ * content type, so read from the right until we receive a
+ * nonzero byte. */
+ while (plaintext->len > 0 && !(plaintext->buf[plaintext->len - 1])) {
+ --plaintext->len;
+ }
+
+ /* Bogus padding. */
+ if (plaintext->len < 1) {
+ SSL_TRC(3, ("%d: TLS13[%d]: empty record", SSL_GETPID(), ss->fd));
+ /* It's safe to report this specifically because it happened
+ * after the MAC has been verified. */
+ *alert = unexpected_message;
+ PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING);
+ return SECFailure;
+ }
+
+ /* Record the type. */
+ *innerType = (SSLContentType)plaintext->buf[plaintext->len - 1];
+ --plaintext->len;
+
+ /* Check for zero-length encrypted Alert and Handshake fragments
+ * (zero-length + inner content type byte).
+ *
+ * Implementations MUST NOT send Handshake and Alert records that have a
+ * zero-length TLSInnerPlaintext.content; if such a message is received,
+ * the receiving implementation MUST terminate the connection with an
+ * "unexpected_message" alert [RFC8446, Section 5.4]. */
+ if (!plaintext->len && ((!IS_DTLS(ss) && cText->hdr[0] == ssl_ct_application_data) ||
+ (IS_DTLS(ss) && dtls_IsDtls13Ciphertext(spec->version, cText->hdr[0])))) {
+ switch (*innerType) {
+ case ssl_ct_alert:
+ *alert = unexpected_message;
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
+ return SECFailure;
+ case ssl_ct_handshake:
+ *alert = unexpected_message;
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE);
+ return SECFailure;
+ default:
+ break;
+ }
+ }
+
+ /* Check that we haven't received too much 0-RTT data. */
+ if (spec->epoch == TrafficKeyEarlyApplicationData &&
+ *innerType == ssl_ct_application_data) {
+ if (plaintext->len > spec->earlyDataRemaining) {
+ *alert = unexpected_message;
+ PORT_SetError(SSL_ERROR_TOO_MUCH_EARLY_DATA);
+ return SECFailure;
+ }
+ spec->earlyDataRemaining -= plaintext->len;
+ }
+
+ SSL_TRC(10,
+ ("%d: TLS13[%d]: %s received record of length=%d, type=%d",
+ SSL_GETPID(), ss->fd, SSL_ROLE(ss), plaintext->len, *innerType));
+
+ return SECSuccess;
+}
+
+/* 0-RTT is only permitted if:
+ *
+ * 1. We are doing TLS 1.3
+ * 2. This isn't a second ClientHello (in response to HelloRetryRequest)
+ * 3. The 0-RTT option is set.
+ * 4. We have a valid ticket or an External PSK.
+ * 5. If resuming:
+ * 5a. The server is willing to accept 0-RTT.
+ * 5b. We have not changed our ALPN settings to disallow the ALPN tag
+ * in the ticket.
+ *
+ * Called from tls13_ClientSendEarlyDataXtn().
+ */
+PRBool
+tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid)
+{
+ /* We checked that the cipher suite was still allowed back in
+ * ssl3_SendClientHello. */
+ if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return PR_FALSE;
+ }
+ if (ss->ssl3.hs.helloRetry) {
+ return PR_FALSE;
+ }
+ if (!ss->opt.enable0RttData) {
+ return PR_FALSE;
+ }
+ if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks)) {
+ return PR_FALSE;
+ }
+ sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+
+ if (psk->zeroRttSuite == TLS_NULL_WITH_NULL_NULL) {
+ return PR_FALSE;
+ }
+ if (!psk->maxEarlyData) {
+ return PR_FALSE;
+ }
+
+ if (psk->type == ssl_psk_external) {
+ return psk->hash == tls13_GetHashForCipherSuite(psk->zeroRttSuite);
+ }
+ if (psk->type == ssl_psk_resume) {
+ if (!ss->statelessResume)
+ return PR_FALSE;
+ if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0)
+ return PR_FALSE;
+ return ssl_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection);
+ }
+ PORT_Assert(0);
+ return PR_FALSE;
+}
+
+SECStatus
+tls13_MaybeDo0RTTHandshake(sslSocket *ss)
+{
+ SECStatus rv;
+
+ /* Don't do anything if there is no early_data xtn, which means we're
+ * not doing early data. */
+ if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) {
+ return SECSuccess;
+ }
+
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_sent;
+ ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.cipher_suite;
+ /* Note: Reset the preliminary info here rather than just add 0-RTT. We are
+ * only guessing what might happen at this point.*/
+ ss->ssl3.hs.preliminaryInfo = ssl_preinfo_0rtt_cipher_suite;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: in 0-RTT mode", SSL_GETPID(), ss->fd));
+
+ /* Set the ALPN data as if it was negotiated. We check in the ServerHello
+ * handler that the server negotiates the same value. */
+ if (ss->sec.ci.sid->u.ssl3.alpnSelection.len) {
+ ss->xtnData.nextProtoState = SSL_NEXT_PROTO_EARLY_VALUE;
+ rv = SECITEM_CopyItem(NULL, &ss->xtnData.nextProto,
+ &ss->sec.ci.sid->u.ssl3.alpnSelection);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ if (ss->opt.enableTls13CompatMode && !IS_DTLS(ss)) {
+ /* Pretend that this is a proper ChangeCipherSpec even though it is sent
+ * before receiving the ServerHello. */
+ ssl_GetSpecWriteLock(ss);
+ tls13_SetSpecRecordVersion(ss, ss->ssl3.cwSpec);
+ ssl_ReleaseSpecWriteLock(ss);
+ ssl_GetXmitBufLock(ss);
+ rv = ssl3_SendChangeCipherSpecsInt(ss);
+ ssl_ReleaseXmitBufLock(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ /* If we're trying 0-RTT, derive from the first PSK */
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) && !ss->xtnData.selectedPsk);
+ ss->xtnData.selectedPsk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+ rv = tls13_DeriveEarlySecrets(ss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Save cwSpec in case we get a HelloRetryRequest and have to send another
+ * ClientHello. */
+ ssl_CipherSpecAddRef(ss->ssl3.cwSpec);
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData,
+ ssl_secret_write, PR_TRUE);
+ ss->xtnData.selectedPsk = NULL;
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+PRInt32
+tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len)
+{
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData));
+ PRInt32 offset = 0;
+ while (!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)) {
+ TLS13EarlyData *msg =
+ (TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData);
+ unsigned int tocpy = msg->data.len - msg->consumed;
+
+ if (tocpy > (len - offset)) {
+ if (IS_DTLS(ss)) {
+ /* In DTLS, we only return entire records.
+ * So offset and consumed are always zero. */
+ PORT_Assert(offset == 0);
+ PORT_Assert(msg->consumed == 0);
+ PORT_SetError(SSL_ERROR_RX_SHORT_DTLS_READ);
+ return -1;
+ }
+
+ tocpy = len - offset;
+ }
+
+ PORT_Memcpy(buf + offset, msg->data.data + msg->consumed, tocpy);
+ offset += tocpy;
+ msg->consumed += tocpy;
+
+ if (msg->consumed == msg->data.len) {
+ PR_REMOVE_LINK(&msg->link);
+ SECITEM_ZfreeItem(&msg->data, PR_FALSE);
+ PORT_ZFree(msg, sizeof(*msg));
+ }
+
+ /* We are done after one record for DTLS; otherwise, when the buffer fills up. */
+ if (IS_DTLS(ss) || offset == len) {
+ break;
+ }
+ }
+
+ return offset;
+}
+
+static SECStatus
+tls13_SendEndOfEarlyData(sslSocket *ss)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
+
+ if (!ss->opt.suppressEndOfEarlyData) {
+ SSL_TRC(3, ("%d: TLS13[%d]: send EndOfEarlyData", SSL_GETPID(), ss->fd));
+ rv = ssl3_AppendHandshakeHeader(ss, ssl_hs_end_of_early_data, 0);
+ if (rv != SECSuccess) {
+ return rv; /* err set by AppendHandshake. */
+ }
+ }
+
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_HandleEndOfEarlyData(sslSocket *ss, const PRUint8 *b, PRUint32 length)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_END_OF_EARLY_DATA,
+ wait_end_of_early_data);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* We shouldn't be getting any more early data, and if we do,
+ * it is because of reordering and we drop it. */
+ if (IS_DTLS(ss)) {
+ ssl_CipherSpecReleaseByEpoch(ss, ssl_secret_read,
+ TrafficKeyEarlyApplicationData);
+ dtls_ReceivedFirstMessageInFlight(ss);
+ }
+
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
+
+ if (length) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_END_OF_EARLY_DATA, decode_error);
+ return SECFailure;
+ }
+
+ rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake,
+ ssl_secret_read, PR_FALSE);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ss->ssl3.hs.zeroRttState = ssl_0rtt_done;
+ if (tls13_ShouldRequestClientAuth(ss)) {
+ TLS13_SET_HS_STATE(ss, wait_client_cert);
+ } else {
+ TLS13_SET_HS_STATE(ss, wait_finished);
+ }
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_MaybeHandleSuppressedEndOfEarlyData(sslSocket *ss)
+{
+ PORT_Assert(ss->sec.isServer);
+ if (!ss->opt.suppressEndOfEarlyData ||
+ ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
+ return SECSuccess;
+ }
+
+ return tls13_HandleEndOfEarlyData(ss, NULL, 0);
+}
+
+SECStatus
+tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf)
+{
+ TLS13EarlyData *ed;
+ SECItem it = { siBuffer, NULL, 0 };
+
+ PORT_Assert(ss->sec.isServer);
+ PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted);
+ if (ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) {
+ /* Belt and suspenders. */
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ PRINT_BUF(3, (NULL, "Received early application data",
+ origBuf->buf, origBuf->len));
+ ed = PORT_ZNew(TLS13EarlyData);
+ if (!ed) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ return SECFailure;
+ }
+ it.data = origBuf->buf;
+ it.len = origBuf->len;
+ if (SECITEM_CopyItem(NULL, &ed->data, &it) != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_NO_MEMORY, internal_error);
+ return SECFailure;
+ }
+ PR_APPEND_LINK(&ed->link, &ss->ssl3.hs.bufferedEarlyData);
+
+ origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */
+
+ return SECSuccess;
+}
+
+PRUint16
+tls13_EncodeVersion(SSL3ProtocolVersion version, SSLProtocolVariant variant)
+{
+ if (variant == ssl_variant_datagram) {
+#ifdef DTLS_1_3_DRAFT_VERSION
+ switch (version) {
+ case SSL_LIBRARY_VERSION_TLS_1_3:
+ return 0x7f00 | DTLS_1_3_DRAFT_VERSION;
+ case SSL_LIBRARY_VERSION_TLS_1_2:
+ return SSL_LIBRARY_VERSION_DTLS_1_2_WIRE;
+ case SSL_LIBRARY_VERSION_TLS_1_1:
+ /* TLS_1_1 maps to DTLS_1_0, see sslproto.h. */
+ return SSL_LIBRARY_VERSION_DTLS_1_0_WIRE;
+ default:
+ PORT_Assert(0);
+ }
+#else
+ return dtls_TLSVersionToDTLSVersion();
+#endif
+ }
+ /* Stream-variant encodings do not change. */
+ return (PRUint16)version;
+}
+
+SECStatus
+tls13_ClientReadSupportedVersion(sslSocket *ss)
+{
+ PRUint32 temp;
+ TLSExtension *versionExtension;
+ SECItem it;
+ SECStatus rv;
+
+ /* Update the version based on the extension, as necessary. */
+ versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
+ if (!versionExtension) {
+ return SECSuccess;
+ }
+
+ /* Struct copy so we don't damage the extension. */
+ it = versionExtension->data;
+
+ rv = ssl3_ConsumeHandshakeNumber(ss, &temp, 2, &it.data, &it.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (it.len) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+
+ if (temp != tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_3,
+ ss->protocolVariant)) {
+ /* You cannot negotiate < TLS 1.3 with supported_versions. */
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* Any endpoint receiving a Hello message with...ServerHello.legacy_version
+ * set to 0x0300 (SSL3) MUST abort the handshake with a "protocol_version"
+ * alert. [RFC8446, Section D.5]
+ *
+ * The ServerHello.legacy_version is read into the ss->version field by
+ * ssl_ClientReadVersion(). */
+ if (ss->version == SSL_LIBRARY_VERSION_3_0) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, protocol_version);
+ return SECFailure;
+ }
+
+ ss->version = SSL_LIBRARY_VERSION_TLS_1_3;
+ return SECSuccess;
+}
+
+/* Pick the highest version we support that is also advertised. */
+SECStatus
+tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supportedVersions)
+{
+ PRUint16 version;
+ /* Make a copy so we're nondestructive. */
+ SECItem data = supportedVersions->data;
+ SECItem versions;
+ SECStatus rv;
+
+ rv = ssl3_ConsumeHandshakeVariable(ss, &versions, 1,
+ &data.data, &data.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (data.len || !versions.len || (versions.len & 1)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
+ if (version < SSL_LIBRARY_VERSION_TLS_1_3 &&
+ (ss->ssl3.hs.helloRetry || ss->ssl3.hs.echAccepted)) {
+ /* Prevent negotiating to a lower version after 1.3 HRR or ECH
+ * When accepting ECH, a different alert is generated.
+ */
+ SSL3AlertDescription alert = ss->ssl3.hs.echAccepted ? illegal_parameter : protocol_version;
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION);
+ FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, alert);
+ return SECFailure;
+ }
+
+ PRUint16 wire = tls13_EncodeVersion(version, ss->protocolVariant);
+ unsigned long offset;
+
+ for (offset = 0; offset < versions.len; offset += 2) {
+ PRUint16 supported =
+ (versions.data[offset] << 8) | versions.data[offset + 1];
+ if (supported == wire) {
+ ss->version = version;
+ return SECSuccess;
+ }
+ }
+ }
+
+ FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, protocol_version);
+ return SECFailure;
+}
+
+/* This is TLS 1.3 or might negotiate to it. */
+PRBool
+tls13_MaybeTls13(sslSocket *ss)
+{
+ if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) {
+ return PR_TRUE;
+ }
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return PR_FALSE;
+ }
+
+ if (!(ss->ssl3.hs.preliminaryInfo & ssl_preinfo_version)) {
+ return PR_TRUE;
+ }
+
+ return PR_FALSE;
+}
+
+/* Setup random client GREASE values according to RFC8701. State must be kept
+ * so an equal ClientHello might be send on HelloRetryRequest. */
+SECStatus
+tls13_ClientGreaseSetup(sslSocket *ss)
+{
+ if (!ss->opt.enableGrease) {
+ return SECSuccess;
+ }
+
+ PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (ss->ssl3.hs.grease) {
+ return SECFailure;
+ }
+ ss->ssl3.hs.grease = PORT_Alloc(sizeof(tls13ClientGrease));
+ if (!ss->ssl3.hs.grease) {
+ return SECFailure;
+ }
+
+ tls13ClientGrease *grease = ss->ssl3.hs.grease;
+ /* We require eight GREASE values and randoms. */
+ PRUint8 random[8];
+
+ /* Generate random GREASE values. */
+ if (PK11_GenerateRandom(random, sizeof(random)) != SECSuccess) {
+ return SECFailure;
+ }
+ for (size_t i = 0; i < PR_ARRAY_SIZE(grease->idx); i++) {
+ random[i] = ((random[i] & 0xf0) | 0x0a);
+ grease->idx[i] = ((random[i] << 8) | random[i]);
+ }
+ /* Specific PskKeyExchangeMode GREASE value. */
+ grease->pskKem = 0x0b + ((random[8 - 1] >> 5) * 0x1f);
+
+ /* Duplicate extensions are not allowed. */
+ if (grease->idx[grease_extension1] == grease->idx[grease_extension2]) {
+ grease->idx[grease_extension2] ^= 0x1010;
+ }
+
+ return SECSuccess;
+}
+
+/* Destroy client GREASE state. */
+void
+tls13_ClientGreaseDestroy(sslSocket *ss)
+{
+ if (ss->ssl3.hs.grease) {
+ PORT_Free(ss->ssl3.hs.grease);
+ ss->ssl3.hs.grease = NULL;
+ }
+}
+
+/* Generate a random GREASE value according to RFC8701.
+ * This function does not provide valid PskKeyExchangeMode GREASE values! */
+SECStatus
+tls13_RandomGreaseValue(PRUint16 *out)
+{
+ PRUint8 random;
+
+ if (PK11_GenerateRandom(&random, sizeof(random)) != SECSuccess) {
+ return SECFailure;
+ }
+
+ random = ((random & 0xf0) | 0x0a);
+ *out = ((random << 8) | random);
+
+ return SECSuccess;
+}
+
+/* Set TLS 1.3 GREASE Extension random GREASE type. */
+SECStatus
+tls13_MaybeGreaseExtensionType(const sslSocket *ss,
+ const SSLHandshakeType message,
+ PRUint16 *exType)
+{
+ if (*exType != ssl_tls13_grease_xtn) {
+ return SECSuccess;
+ }
+
+ PR_ASSERT(ss->opt.enableGrease);
+ PR_ASSERT(message == ssl_hs_client_hello ||
+ message == ssl_hs_certificate_request);
+
+ /* GREASE ClientHello:
+ * A client MAY select one or more GREASE extension values and
+ * advertise them as extensions with varying length and contents
+ * [RFC8701, Section 3.1]. */
+ if (message == ssl_hs_client_hello) {
+ PR_ASSERT(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
+ /* Check if the first GREASE extension was already added. */
+ if (!ssl3_ExtensionAdvertised(ss, ss->ssl3.hs.grease->idx[grease_extension1])) {
+ *exType = ss->ssl3.hs.grease->idx[grease_extension1];
+ } else {
+ *exType = ss->ssl3.hs.grease->idx[grease_extension2];
+ }
+ }
+ /* GREASE CertificateRequest:
+ * When sending a CertificateRequest in TLS 1.3, a server MAY behave as
+ * follows: A server MAY select one or more GREASE extension values and
+ * advertise them as extensions with varying length and contents
+ * [RFC8701, Section 4.1]. */
+ else if (message == ssl_hs_certificate_request) {
+ PR_ASSERT(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ /* Get random grease extension type. */
+ SECStatus rv = tls13_RandomGreaseValue(exType);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/tls13con.h b/security/nss/lib/ssl/tls13con.h
new file mode 100644
index 0000000000..1e082d639a
--- /dev/null
+++ b/security/nss/lib/ssl/tls13con.h
@@ -0,0 +1,177 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13con_h_
+#define __tls13con_h_
+
+#include "sslexp.h"
+#include "sslspec.h"
+
+typedef enum {
+ tls13_extension_allowed,
+ tls13_extension_disallowed,
+ tls13_extension_unknown
+} tls13ExtensionStatus;
+
+#define TLS13_MAX_FINISHED_SIZE 64
+#define TLS13_COOKIE_SENTINEL 0xff
+
+SECStatus tls13_UnprotectRecord(
+ sslSocket *ss, ssl3CipherSpec *spec,
+ SSL3Ciphertext *cText, sslBuffer *plaintext,
+ SSLContentType *innerType,
+ SSL3AlertDescription *alert);
+
+#if defined(WIN32)
+#define __func__ __FUNCTION__
+#endif
+
+void tls13_SetHsState(sslSocket *ss, SSL3WaitState ws,
+ const char *func, const char *file, int line);
+#define TLS13_SET_HS_STATE(ss, ws) \
+ tls13_SetHsState(ss, ws, __func__, __FILE__, __LINE__)
+
+/* Return PR_TRUE if the socket is in one of the given states, else return
+ * PR_FALSE. Only call the macro not the function, because the trailing
+ * wait_invalid is needed to terminate the argument list. */
+PRBool tls13_InHsState(sslSocket *ss, ...);
+#define TLS13_IN_HS_STATE(ss, ...) \
+ tls13_InHsState(ss, __VA_ARGS__, wait_invalid)
+
+PRBool tls13_IsPostHandshake(const sslSocket *ss);
+
+SSLHashType tls13_GetHash(const sslSocket *ss);
+SECStatus tls13_GetHashAndCipher(PRUint16 version, PRUint16 cipherSuite,
+ SSLHashType *hash, const ssl3BulkCipherDef **cipher);
+SSLHashType tls13_GetHashForCipherSuite(ssl3CipherSuite suite);
+unsigned int tls13_GetHashSize(const sslSocket *ss);
+unsigned int tls13_GetHashSizeForHash(SSLHashType hash);
+SECStatus tls13_ComputeHash(sslSocket *ss, SSL3Hashes *hashes,
+ const PRUint8 *buf, unsigned int len,
+ SSLHashType hash);
+SECStatus tls13_ComputeHandshakeHashes(sslSocket *ss,
+ SSL3Hashes *hashes);
+SECStatus tls13_DeriveSecretNullHash(sslSocket *ss, PK11SymKey *key,
+ const char *label,
+ unsigned int labelLen,
+ PK11SymKey **dest,
+ SSLHashType hash);
+void tls13_FatalError(sslSocket *ss, PRErrorCode prError,
+ SSL3AlertDescription desc);
+SECStatus tls13_SetupClientHello(sslSocket *ss, sslClientHelloType chType);
+SECStatus tls13_MaybeDo0RTTHandshake(sslSocket *ss);
+PRInt32 tls13_LimitEarlyData(sslSocket *ss, SSLContentType type, PRInt32 toSend);
+PRBool tls13_AllowPskCipher(const sslSocket *ss,
+ const ssl3CipherSuiteDef *cipher_def);
+PRBool tls13_PskSuiteEnabled(sslSocket *ss);
+SECStatus tls13_WriteExtensionsWithBinder(sslSocket *ss, sslBuffer *extensions,
+ sslBuffer *chBuf);
+SECStatus tls13_HandleClientHelloPart2(sslSocket *ss,
+ const SECItem *suites,
+ sslSessionID *sid,
+ const PRUint8 *msg,
+ unsigned int len);
+SECStatus tls13_HandleServerHelloPart2(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength);
+SECStatus tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, PRUint8 *b,
+ PRUint32 length);
+SECStatus tls13_ConstructHelloRetryRequest(sslSocket *ss,
+ ssl3CipherSuite cipherSuite,
+ const sslNamedGroupDef *selectedGroup,
+ PRUint8 *cookie,
+ unsigned int cookieLen,
+ const PRUint8 *cookieGreaseEchSignal,
+ sslBuffer *buffer);
+SECStatus tls13_HandleHelloRetryRequest(sslSocket *ss, const PRUint8 *b,
+ PRUint32 length);
+SECStatus tls13_HandleKeyShare(sslSocket *ss,
+ TLS13KeyShareEntry *entry,
+ sslKeyPair *keyPair,
+ SSLHashType hash,
+ PK11SymKey **out);
+TLS13KeyShareEntry *tls13_CopyKeyShareEntry(TLS13KeyShareEntry *o);
+void tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *entry);
+void tls13_DestroyKeyShares(PRCList *list);
+SECStatus tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef,
+ sslEphemeralKeyPair **keyPair);
+SECStatus tls13_AddKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef);
+void tls13_DestroyEarlyData(PRCList *list);
+SECStatus tls13_SetAlertCipherSpec(sslSocket *ss);
+tls13ExtensionStatus tls13_ExtensionStatus(PRUint16 extension,
+ SSLHandshakeType message);
+SECStatus tls13_ProtectRecord(sslSocket *ss,
+ ssl3CipherSpec *cwSpec,
+ SSLContentType type,
+ const PRUint8 *pIn,
+ PRUint32 contentLen,
+ sslBuffer *wrBuf);
+PRInt32 tls13_Read0RttData(sslSocket *ss, PRUint8 *buf, PRInt32 len);
+SECStatus tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf);
+PRBool tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid);
+PRUint16 tls13_EncodeVersion(SSL3ProtocolVersion version,
+ SSLProtocolVariant variant);
+SECStatus tls13_ClientReadSupportedVersion(sslSocket *ss);
+SECStatus tls13_NegotiateVersion(sslSocket *ss,
+ const TLSExtension *supported_versions);
+PRBool tls13_ShouldRequestClientAuth(sslSocket *ss);
+
+PRBool tls13_IsReplay(const sslSocket *ss, const sslSessionID *sid);
+void tls13_AntiReplayRollover(SSLAntiReplayContext *ctx, PRTime now);
+SSLAntiReplayContext *tls13_RefAntiReplayContext(SSLAntiReplayContext *ctx);
+void tls13_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx);
+
+SECStatus SSLExp_CreateAntiReplayContext(
+ PRTime now, PRTime window, unsigned int k, unsigned int bits,
+ SSLAntiReplayContext **ctx);
+SECStatus SSLExp_SetAntiReplayContext(PRFileDesc *fd,
+ SSLAntiReplayContext *ctx);
+SECStatus SSLExp_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx);
+
+SECStatus SSLExp_HelloRetryRequestCallback(PRFileDesc *fd,
+ SSLHelloRetryRequestCallback cb,
+ void *arg);
+SECStatus tls13_SendKeyUpdate(sslSocket *ss, tls13KeyUpdateRequest request,
+ PRBool buffer);
+SECStatus SSLExp_KeyUpdate(PRFileDesc *fd, PRBool requestUpdate);
+PRBool tls13_MaybeTls13(sslSocket *ss);
+unsigned int tls13_SetupAeadIv(PRBool isDTLS, unsigned char *ivOut,
+ unsigned char *ivIn, unsigned int offset,
+ unsigned int ivLen, DTLSEpoch epoch);
+SECStatus tls13_AEAD(PK11Context *context, PRBool decrypt,
+ CK_GENERATOR_FUNCTION ivGen, unsigned int fixedbits,
+ const unsigned char *ivIn, unsigned char *ivOut,
+ unsigned int ivLen,
+ const unsigned char *nonceIn, unsigned int nonceLen,
+ const unsigned char *aad, unsigned int aadLen,
+ unsigned char *out, unsigned int *outLen,
+ unsigned int maxout, unsigned int tagLen,
+ const unsigned char *in, unsigned int inLen);
+void tls13_SetSpecRecordVersion(sslSocket *ss, ssl3CipherSpec *spec);
+SECStatus SSLExp_SendCertificateRequest(PRFileDesc *fd);
+SECStatus tls13_ClientGreaseSetup(sslSocket *ss);
+void tls13_ClientGreaseDestroy(sslSocket *ss);
+SECStatus tls13_RandomGreaseValue(PRUint16 *out);
+SECStatus tls13_MaybeGreaseExtensionType(const sslSocket *ss,
+ const SSLHandshakeType message,
+ PRUint16 *exType);
+
+/* Use this instead of FATAL_ERROR when no alert shall be sent. */
+#define LOG_ERROR(ss, prError) \
+ do { \
+ SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \
+ SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \
+ PORT_SetError(prError); \
+ } while (0)
+
+/* Log an error and generate an alert because something is irreparably wrong. */
+#define FATAL_ERROR(ss, prError, desc) \
+ do { \
+ LOG_ERROR(ss, prError); \
+ tls13_FatalError(ss, prError, desc); \
+ } while (0)
+
+#endif /* __tls13con_h_ */
diff --git a/security/nss/lib/ssl/tls13ech.c b/security/nss/lib/ssl/tls13ech.c
new file mode 100644
index 0000000000..9808a9fe2d
--- /dev/null
+++ b/security/nss/lib/ssl/tls13ech.c
@@ -0,0 +1,2818 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "pk11func.h"
+#include "pk11hpke.h"
+#include "ssl.h"
+#include "sslproto.h"
+#include "sslimpl.h"
+#include "selfencrypt.h"
+#include "ssl3exthandle.h"
+#include "tls13ech.h"
+#include "tls13exthandle.h"
+#include "tls13hashstate.h"
+#include "tls13hkdf.h"
+
+extern SECStatus
+ssl3_UpdateHandshakeHashesInt(sslSocket *ss, const unsigned char *b,
+ unsigned int l, sslBuffer *transcriptBuf);
+extern SECStatus
+ssl3_HandleClientHelloPreamble(sslSocket *ss, PRUint8 **b, PRUint32 *length, SECItem *sidBytes,
+ SECItem *cookieBytes, SECItem *suites, SECItem *comps);
+extern SECStatus
+tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key,
+ const char *label,
+ unsigned int labelLen,
+ const SSL3Hashes *hashes,
+ PK11SymKey **dest,
+ SSLHashType hash);
+
+PRBool
+tls13_Debug_CheckXtnBegins(const PRUint8 *start, const PRUint16 xtnType)
+{
+#ifdef DEBUG
+ SECStatus rv;
+ sslReader ext_reader = SSL_READER(start, 2);
+ PRUint64 extension_number;
+ rv = sslRead_ReadNumber(&ext_reader, 2, &extension_number);
+ return ((rv == SECSuccess) && (extension_number == xtnType));
+#else
+ return PR_TRUE;
+#endif
+}
+
+void
+tls13_DestroyEchConfig(sslEchConfig *config)
+{
+ if (!config) {
+ return;
+ }
+ SECITEM_FreeItem(&config->contents.publicKey, PR_FALSE);
+ SECITEM_FreeItem(&config->contents.suites, PR_FALSE);
+ SECITEM_FreeItem(&config->raw, PR_FALSE);
+ PORT_Free(config->contents.publicName);
+ config->contents.publicName = NULL;
+ PORT_ZFree(config, sizeof(*config));
+}
+
+void
+tls13_DestroyEchConfigs(PRCList *list)
+{
+ PRCList *cur_p;
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ cur_p = PR_LIST_TAIL(list);
+ PR_REMOVE_LINK(cur_p);
+ tls13_DestroyEchConfig((sslEchConfig *)cur_p);
+ }
+}
+
+void
+tls13_DestroyEchXtnState(sslEchXtnState *state)
+{
+ if (!state) {
+ return;
+ }
+ SECITEM_FreeItem(&state->innerCh, PR_FALSE);
+ SECITEM_FreeItem(&state->senderPubKey, PR_FALSE);
+ SECITEM_FreeItem(&state->retryConfigs, PR_FALSE);
+ PORT_ZFree(state, sizeof(*state));
+}
+
+SECStatus
+tls13_CopyEchConfigs(PRCList *oConfigs, PRCList *configs)
+{
+ SECStatus rv;
+ sslEchConfig *config;
+ sslEchConfig *newConfig = NULL;
+
+ for (PRCList *cur_p = PR_LIST_HEAD(oConfigs);
+ cur_p != oConfigs;
+ cur_p = PR_NEXT_LINK(cur_p)) {
+ config = (sslEchConfig *)PR_LIST_TAIL(oConfigs);
+ newConfig = PORT_ZNew(sslEchConfig);
+ if (!newConfig) {
+ goto loser;
+ }
+
+ rv = SECITEM_CopyItem(NULL, &newConfig->raw, &config->raw);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ newConfig->contents.publicName = PORT_Strdup(config->contents.publicName);
+ if (!newConfig->contents.publicName) {
+ goto loser;
+ }
+ rv = SECITEM_CopyItem(NULL, &newConfig->contents.publicKey,
+ &config->contents.publicKey);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = SECITEM_CopyItem(NULL, &newConfig->contents.suites,
+ &config->contents.suites);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ newConfig->contents.configId = config->contents.configId;
+ newConfig->contents.kemId = config->contents.kemId;
+ newConfig->contents.kdfId = config->contents.kdfId;
+ newConfig->contents.aeadId = config->contents.aeadId;
+ newConfig->contents.maxNameLen = config->contents.maxNameLen;
+ newConfig->version = config->version;
+ PR_APPEND_LINK(&newConfig->link, configs);
+ }
+ return SECSuccess;
+
+loser:
+ tls13_DestroyEchConfig(newConfig);
+ tls13_DestroyEchConfigs(configs);
+ return SECFailure;
+}
+
+/*
+ * struct {
+ * HpkeKdfId kdf_id;
+ * HpkeAeadId aead_id;
+ * } HpkeSymmetricCipherSuite;
+ *
+ * struct {
+ * uint8 config_id;
+ * HpkeKemId kem_id;
+ * HpkePublicKey public_key;
+ * HpkeSymmetricCipherSuite cipher_suites<4..2^16-4>;
+ * } HpkeKeyConfig;
+ *
+ * struct {
+ * HpkeKeyConfig key_config;
+ * uint16 maximum_name_length;
+ * opaque public_name<1..2^16-1>;
+ * Extension extensions<0..2^16-1>;
+ * } ECHConfigContents;
+ *
+ * struct {
+ * uint16 version;
+ * uint16 length;
+ * select (ECHConfig.version) {
+ * case 0xfe0d: ECHConfigContents contents;
+ * }
+ * } ECHConfig;
+ */
+static SECStatus
+tls13_DecodeEchConfigContents(const sslReadBuffer *rawConfig,
+ sslEchConfig **outConfig)
+{
+ SECStatus rv;
+ sslEchConfigContents contents = { 0 };
+ sslEchConfig *decodedConfig;
+ PRUint64 tmpn;
+ PRUint64 tmpn2;
+ sslReadBuffer tmpBuf;
+ PRUint16 *extensionTypes = NULL;
+ unsigned int extensionIndex = 0;
+ sslReader configReader = SSL_READER(rawConfig->buf, rawConfig->len);
+ sslReader suiteReader;
+ sslReader extensionReader;
+ PRBool hasValidSuite = PR_FALSE;
+ PRBool unsupportedMandatoryXtn = PR_FALSE;
+
+ /* HpkeKeyConfig key_config */
+ /* uint8 config_id */
+ rv = sslRead_ReadNumber(&configReader, 1, &tmpn);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ contents.configId = tmpn;
+
+ /* HpkeKemId kem_id */
+ rv = sslRead_ReadNumber(&configReader, 2, &tmpn);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ contents.kemId = tmpn;
+
+ /* HpkePublicKey public_key */
+ rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = SECITEM_MakeItem(NULL, &contents.publicKey, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* HpkeSymmetricCipherSuite cipher_suites<4..2^16-4> */
+ rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (tmpBuf.len & 1) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
+ goto loser;
+ }
+ suiteReader = (sslReader)SSL_READER(tmpBuf.buf, tmpBuf.len);
+ while (SSL_READER_REMAINING(&suiteReader)) {
+ /* HpkeKdfId kdf_id */
+ rv = sslRead_ReadNumber(&suiteReader, 2, &tmpn);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* HpkeAeadId aead_id */
+ rv = sslRead_ReadNumber(&suiteReader, 2, &tmpn2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (!hasValidSuite) {
+ /* Use the first compatible ciphersuite. */
+ rv = PK11_HPKE_ValidateParameters(contents.kemId, tmpn, tmpn2);
+ if (rv == SECSuccess) {
+ hasValidSuite = PR_TRUE;
+ contents.kdfId = tmpn;
+ contents.aeadId = tmpn2;
+ break;
+ }
+ }
+ }
+
+ rv = SECITEM_MakeItem(NULL, &contents.suites, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* uint8 maximum_name_length */
+ rv = sslRead_ReadNumber(&configReader, 1, &tmpn);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ contents.maxNameLen = (PRUint8)tmpn;
+
+ /* opaque public_name<1..2^16-1> */
+ rv = sslRead_ReadVariable(&configReader, 1, &tmpBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (tmpBuf.len == 0) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
+ goto loser;
+ }
+ if (!tls13_IsLDH(tmpBuf.buf, tmpBuf.len) ||
+ tls13_IsIp(tmpBuf.buf, tmpBuf.len)) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
+ goto loser;
+ }
+
+ contents.publicName = PORT_ZAlloc(tmpBuf.len + 1);
+ if (!contents.publicName) {
+ goto loser;
+ }
+ PORT_Memcpy(contents.publicName, (PRUint8 *)tmpBuf.buf, tmpBuf.len);
+
+ /* Extensions. We don't support any, but must
+ * check for any that are marked critical. */
+ rv = sslRead_ReadVariable(&configReader, 2, &tmpBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ extensionReader = (sslReader)SSL_READER(tmpBuf.buf, tmpBuf.len);
+ extensionTypes = PORT_NewArray(PRUint16, tmpBuf.len / 2 * sizeof(PRUint16));
+ if (!extensionTypes) {
+ goto loser;
+ }
+
+ while (SSL_READER_REMAINING(&extensionReader)) {
+ /* Get the extension's type field */
+ rv = sslRead_ReadNumber(&extensionReader, 2, &tmpn);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ for (unsigned int i = 0; i < extensionIndex; i++) {
+ if (extensionTypes[i] == tmpn) {
+ PORT_SetError(SEC_ERROR_EXTENSION_VALUE_INVALID);
+ goto loser;
+ }
+ }
+ extensionTypes[extensionIndex++] = (PRUint16)tmpn;
+
+ /* Clients MUST parse the extension list and check for unsupported
+ * mandatory extensions. If an unsupported mandatory extension is
+ * present, clients MUST ignore the ECHConfig
+ * [draft-ietf-tls-esni, Section 4.2]. */
+ if (tmpn & (1 << 15)) {
+ unsupportedMandatoryXtn = PR_TRUE;
+ }
+
+ /* Skip. */
+ rv = sslRead_ReadVariable(&extensionReader, 2, &tmpBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ /* Check that we consumed the entire ECHConfig */
+ if (SSL_READER_REMAINING(&configReader)) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
+ goto loser;
+ }
+
+ /* If the ciphersuites were compatible AND if NO unsupported mandatory
+ * extensions were found set the outparam. Return success either way if the
+ * config was well-formed. */
+ if (hasValidSuite && !unsupportedMandatoryXtn) {
+ decodedConfig = PORT_ZNew(sslEchConfig);
+ if (!decodedConfig) {
+ goto loser;
+ }
+ decodedConfig->contents = contents;
+ *outConfig = decodedConfig;
+ } else {
+ PORT_Free(contents.publicName);
+ SECITEM_FreeItem(&contents.publicKey, PR_FALSE);
+ SECITEM_FreeItem(&contents.suites, PR_FALSE);
+ }
+ PORT_Free(extensionTypes);
+ return SECSuccess;
+
+loser:
+ PORT_Free(extensionTypes);
+ PORT_Free(contents.publicName);
+ SECITEM_FreeItem(&contents.publicKey, PR_FALSE);
+ SECITEM_FreeItem(&contents.suites, PR_FALSE);
+ return SECFailure;
+}
+
+/* Decode an ECHConfigList struct and store each ECHConfig
+ * into |configs|. */
+SECStatus
+tls13_DecodeEchConfigs(const SECItem *data, PRCList *configs)
+{
+ SECStatus rv;
+ sslEchConfig *decodedConfig = NULL;
+ sslReader rdr = SSL_READER(data->data, data->len);
+ sslReadBuffer tmp;
+ sslReadBuffer singleConfig;
+ PRUint64 version;
+ PRUint64 length;
+ PORT_Assert(PR_CLIST_IS_EMPTY(configs));
+
+ rv = sslRead_ReadVariable(&rdr, 2, &tmp);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ SSL_TRC(100, ("Read EchConfig list of size %u", SSL_READER_REMAINING(&rdr)));
+ if (SSL_READER_REMAINING(&rdr)) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+
+ sslReader configsReader = SSL_READER(tmp.buf, tmp.len);
+
+ if (!SSL_READER_REMAINING(&configsReader)) {
+ PORT_SetError(SEC_ERROR_BAD_DATA);
+ return SECFailure;
+ }
+
+ /* Handle each ECHConfig. */
+ while (SSL_READER_REMAINING(&configsReader)) {
+ singleConfig.buf = SSL_READER_CURRENT(&configsReader);
+ /* uint16 version */
+ rv = sslRead_ReadNumber(&configsReader, 2, &version);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* uint16 length */
+ rv = sslRead_ReadNumber(&configsReader, 2, &length);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ singleConfig.len = 4 + length;
+
+ rv = sslRead_Read(&configsReader, length, &tmp);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (version == TLS13_ECH_VERSION) {
+ rv = tls13_DecodeEchConfigContents(&tmp, &decodedConfig);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+
+ if (decodedConfig) {
+ decodedConfig->version = version;
+ rv = SECITEM_MakeItem(NULL, &decodedConfig->raw, singleConfig.buf,
+ singleConfig.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ PR_APPEND_LINK(&decodedConfig->link, configs);
+ decodedConfig = NULL;
+ }
+ }
+ }
+ return SECSuccess;
+
+loser:
+ tls13_DestroyEchConfigs(configs);
+ return SECFailure;
+}
+
+/* Encode an ECHConfigList structure. We only create one config, and as the
+ * primary use for this function is to generate test inputs, we don't
+ * validate against what HPKE and libssl can actually support. */
+SECStatus
+SSLExp_EncodeEchConfigId(PRUint8 configId, const char *publicName, unsigned int maxNameLen,
+ HpkeKemId kemId, const SECKEYPublicKey *pubKey,
+ const HpkeSymmetricSuite *hpkeSuites, unsigned int hpkeSuiteCount,
+ PRUint8 *out, unsigned int *outlen, unsigned int maxlen)
+{
+ SECStatus rv;
+ unsigned int savedOffset;
+ unsigned int len;
+ sslBuffer b = SSL_BUFFER_EMPTY;
+ PRUint8 tmpBuf[66]; // Large enough for an EC public key, currently only X25519.
+ unsigned int tmpLen;
+
+ if (!publicName || !hpkeSuites || hpkeSuiteCount == 0 ||
+ !pubKey || maxNameLen == 0 || !out || !outlen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* ECHConfig ECHConfigList<1..2^16-1>; */
+ rv = sslBuffer_Skip(&b, 2, NULL);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /*
+ * struct {
+ * uint16 version;
+ * uint16 length;
+ * select (ECHConfig.version) {
+ * case 0xfe0d: ECHConfigContents contents;
+ * }
+ * } ECHConfig;
+ */
+ rv = sslBuffer_AppendNumber(&b, TLS13_ECH_VERSION, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_Skip(&b, 2, &savedOffset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /*
+ * struct {
+ * uint8 config_id;
+ * HpkeKemId kem_id;
+ * HpkePublicKey public_key;
+ * HpkeSymmetricCipherSuite cipher_suites<4..2^16-4>;
+ * } HpkeKeyConfig;
+ */
+ rv = sslBuffer_AppendNumber(&b, configId, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendNumber(&b, kemId, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = PK11_HPKE_Serialize(pubKey, tmpBuf, &tmpLen, sizeof(tmpBuf));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(&b, tmpBuf, tmpLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendNumber(&b, hpkeSuiteCount * 4, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ for (unsigned int i = 0; i < hpkeSuiteCount; i++) {
+ rv = sslBuffer_AppendNumber(&b, hpkeSuites[i].kdfId, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(&b, hpkeSuites[i].aeadId, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ /*
+ * struct {
+ * HpkeKeyConfig key_config;
+ * uint8 maximum_name_length;
+ * opaque public_name<1..255>;
+ * Extension extensions<0..2^16-1>;
+ * } ECHConfigContents;
+ */
+ rv = sslBuffer_AppendNumber(&b, maxNameLen, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ len = PORT_Strlen(publicName);
+ if (len > 0xff) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(&b, (const PRUint8 *)publicName, len, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* extensions */
+ rv = sslBuffer_AppendNumber(&b, 0, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Write the length now that we know it. */
+ rv = sslBuffer_InsertLength(&b, 0, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_InsertLength(&b, savedOffset, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (SSL_BUFFER_LEN(&b) > maxlen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+ PORT_Memcpy(out, SSL_BUFFER_BASE(&b), SSL_BUFFER_LEN(&b));
+ *outlen = SSL_BUFFER_LEN(&b);
+ sslBuffer_Clear(&b);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&b);
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_GetEchRetryConfigs(PRFileDesc *fd, SECItem *retryConfigs)
+{
+ SECStatus rv;
+ sslSocket *ss;
+ SECItem out = { siBuffer, NULL, 0 };
+
+ if (!fd || !retryConfigs) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in %s",
+ SSL_GETPID(), fd, __FUNCTION__));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* We don't distinguish between "handshake completed
+ * without retry configs", and "handshake not completed".
+ * An application should only call this after receiving a
+ * RETRY_WITH_ECH error code, which implies retry_configs. */
+ if (!ss->xtnData.ech || !ss->xtnData.ech->retryConfigsValid) {
+ PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
+ return SECFailure;
+ }
+
+ /* May be empty. */
+ rv = SECITEM_CopyItem(NULL, &out, &ss->xtnData.ech->retryConfigs);
+ if (rv == SECFailure) {
+ return SECFailure;
+ }
+ *retryConfigs = out;
+ return SECSuccess;
+}
+
+SECStatus
+SSLExp_RemoveEchConfigs(PRFileDesc *fd)
+{
+ sslSocket *ss;
+
+ if (!fd) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in %s",
+ SSL_GETPID(), fd, __FUNCTION__));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SECKEY_DestroyPrivateKey(ss->echPrivKey);
+ ss->echPrivKey = NULL;
+ SECKEY_DestroyPublicKey(ss->echPubKey);
+ ss->echPubKey = NULL;
+ tls13_DestroyEchConfigs(&ss->echConfigs);
+
+ /* Also remove any retry_configs and handshake context. */
+ if (ss->xtnData.ech && ss->xtnData.ech->retryConfigs.len) {
+ SECITEM_FreeItem(&ss->xtnData.ech->retryConfigs, PR_FALSE);
+ }
+
+ if (ss->ssl3.hs.echHpkeCtx) {
+ PK11_HPKE_DestroyContext(ss->ssl3.hs.echHpkeCtx, PR_TRUE);
+ ss->ssl3.hs.echHpkeCtx = NULL;
+ }
+ PORT_Free(CONST_CAST(char, ss->ssl3.hs.echPublicName));
+ ss->ssl3.hs.echPublicName = NULL;
+
+ return SECSuccess;
+}
+
+/* Import one or more ECHConfigs for the given keypair. The AEAD/KDF
+ * may differ , but only X25519 is supported for the KEM.*/
+SECStatus
+SSLExp_SetServerEchConfigs(PRFileDesc *fd,
+ const SECKEYPublicKey *pubKey, const SECKEYPrivateKey *privKey,
+ const PRUint8 *echConfigs, unsigned int echConfigsLen)
+{
+ sslSocket *ss;
+ SECStatus rv;
+ SECItem data = { siBuffer, CONST_CAST(PRUint8, echConfigs), echConfigsLen };
+
+ if (!fd || !pubKey || !privKey || !echConfigs || echConfigsLen == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in %s",
+ SSL_GETPID(), fd, __FUNCTION__));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* Overwrite if we're already configured. */
+ rv = SSLExp_RemoveEchConfigs(fd);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = tls13_DecodeEchConfigs(&data, &ss->echConfigs);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ goto loser;
+ }
+
+ ss->echPubKey = SECKEY_CopyPublicKey(pubKey);
+ if (!ss->echPubKey) {
+ goto loser;
+ }
+ ss->echPrivKey = SECKEY_CopyPrivateKey(privKey);
+ if (!ss->echPrivKey) {
+ goto loser;
+ }
+ return SECSuccess;
+
+loser:
+ tls13_DestroyEchConfigs(&ss->echConfigs);
+ SECKEY_DestroyPrivateKey(ss->echPrivKey);
+ SECKEY_DestroyPublicKey(ss->echPubKey);
+ ss->echPubKey = NULL;
+ ss->echPrivKey = NULL;
+ return SECFailure;
+}
+
+/* Client enable. For now, we'll use the first
+ * compatible config (server preference). */
+SECStatus
+SSLExp_SetClientEchConfigs(PRFileDesc *fd,
+ const PRUint8 *echConfigs,
+ unsigned int echConfigsLen)
+{
+ SECStatus rv;
+ sslSocket *ss;
+ SECItem data = { siBuffer, CONST_CAST(PRUint8, echConfigs), echConfigsLen };
+
+ if (!fd || !echConfigs || echConfigsLen == 0) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in %s",
+ SSL_GETPID(), fd, __FUNCTION__));
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /* Overwrite if we're already configured. */
+ rv = SSLExp_RemoveEchConfigs(fd);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = tls13_DecodeEchConfigs(&data, &ss->echConfigs);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Set up ECH. This generates an ephemeral sender
+ * keypair and the HPKE context */
+SECStatus
+tls13_ClientSetupEch(sslSocket *ss, sslClientHelloType type)
+{
+ SECStatus rv;
+ HpkeContext *cx = NULL;
+ SECKEYPublicKey *pkR = NULL;
+ SECItem hpkeInfo = { siBuffer, NULL, 0 };
+ sslEchConfig *cfg = NULL;
+
+ if (PR_CLIST_IS_EMPTY(&ss->echConfigs) ||
+ !ssl_ShouldSendSNIExtension(ss, ss->url) ||
+ IS_DTLS(ss)) {
+ return SECSuccess;
+ }
+
+ /* Maybe apply our own priority if >1. For now, we only support
+ * one version and one KEM. Each ECHConfig can specify multiple
+ * KDF/AEADs, so just use the first. */
+ cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
+
+ SSL_TRC(50, ("%d: TLS13[%d]: Setup client ECH",
+ SSL_GETPID(), ss->fd));
+
+ switch (type) {
+ case client_hello_initial:
+ PORT_Assert(!ss->ssl3.hs.echHpkeCtx && !ss->ssl3.hs.echPublicName);
+ cx = PK11_HPKE_NewContext(cfg->contents.kemId, cfg->contents.kdfId,
+ cfg->contents.aeadId, NULL, NULL);
+ break;
+ case client_hello_retry:
+ if (!ss->ssl3.hs.echHpkeCtx || !ss->ssl3.hs.echPublicName) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+ /* Nothing else to do. */
+ return SECSuccess;
+ default:
+ PORT_Assert(0);
+ goto loser;
+ }
+ if (!cx) {
+ goto loser;
+ }
+
+ rv = PK11_HPKE_Deserialize(cx, cfg->contents.publicKey.data, cfg->contents.publicKey.len, &pkR);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (!SECITEM_AllocItem(NULL, &hpkeInfo, strlen(kHpkeInfoEch) + 1 + cfg->raw.len)) {
+ goto loser;
+ }
+ PORT_Memcpy(&hpkeInfo.data[0], kHpkeInfoEch, strlen(kHpkeInfoEch));
+ PORT_Memset(&hpkeInfo.data[strlen(kHpkeInfoEch)], 0, 1);
+ PORT_Memcpy(&hpkeInfo.data[strlen(kHpkeInfoEch) + 1], cfg->raw.data, cfg->raw.len);
+
+ PRINT_BUF(50, (ss, "Info", hpkeInfo.data, hpkeInfo.len));
+
+ /* Setup with an ephemeral sender keypair. */
+ rv = PK11_HPKE_SetupS(cx, NULL, NULL, pkR, &hpkeInfo);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = ssl3_GetNewRandom(ss->ssl3.hs.client_inner_random);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+
+ /* If ECH is rejected, the application will use SSLChannelInfo
+ * to fetch this field and perform cert chain verification. */
+ ss->ssl3.hs.echPublicName = PORT_Strdup(cfg->contents.publicName);
+ if (!ss->ssl3.hs.echPublicName) {
+ goto loser;
+ }
+
+ ss->ssl3.hs.echHpkeCtx = cx;
+ SECKEY_DestroyPublicKey(pkR);
+ SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
+ return SECSuccess;
+
+loser:
+ PK11_HPKE_DestroyContext(cx, PR_TRUE);
+ SECKEY_DestroyPublicKey(pkR);
+ SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
+ PORT_Assert(PORT_GetError() != 0);
+ return SECFailure;
+}
+
+/*
+ * outerAAD - The associated data for the AEAD (the entire client hello with the ECH payload zeroed)
+ * chInner - The plaintext which will be encrypted (the ClientHelloInner plus padding)
+ * echPayload - Output location. A buffer containing all-zeroes of at least chInner->len + TLS13_ECH_AEAD_TAG_LEN bytes.
+ *
+ * echPayload may point into outerAAD to avoid the need to duplicate the ClientHelloOuter buffer.
+ */
+static SECStatus
+tls13_EncryptClientHello(sslSocket *ss, SECItem *aadItem, const sslBuffer *chInner, PRUint8 *echPayload)
+{
+ SECStatus rv;
+ SECItem chPt = { siBuffer, chInner->buf, chInner->len };
+ SECItem *chCt = NULL;
+
+ PRINT_BUF(50, (ss, "aad for ECH Encrypt", aadItem->data, aadItem->len));
+ PRINT_BUF(50, (ss, "plaintext for ECH Encrypt", chInner->buf, chInner->len));
+
+#ifndef UNSAFE_FUZZER_MODE
+ rv = PK11_HPKE_Seal(ss->ssl3.hs.echHpkeCtx, aadItem, &chPt, &chCt);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PRINT_BUF(50, (ss, "ciphertext from ECH Encrypt", chCt->data, chCt->len));
+#else
+ /* Fake a tag. */
+ SECITEM_AllocItem(NULL, chCt, chPt.len + TLS13_ECH_AEAD_TAG_LEN);
+ if (!chCt) {
+ goto loser;
+ }
+ PORT_Memcpy(chCt->data, chPt.data, chPt.len);
+#endif
+
+#ifdef DEBUG
+ /* When encrypting in-place, the payload is part of the AAD and must be zeroed. */
+ PRUint8 val = 0;
+ for (int i = 0; i < chCt->len; i++) {
+ val |= *(echPayload + i);
+ }
+ PRINT_BUF(100, (ss, "Empty Placeholder for output of ECH Encryption", echPayload, chCt->len));
+ PR_ASSERT(val == 0);
+#endif
+
+ PORT_Memcpy(echPayload, chCt->data, chCt->len);
+ SECITEM_FreeItem(chCt, PR_TRUE);
+ return SECSuccess;
+
+loser:
+ SECITEM_FreeItem(chCt, PR_TRUE);
+ return SECFailure;
+}
+
+SECStatus
+tls13_GetMatchingEchConfigs(const sslSocket *ss, HpkeKdfId kdf, HpkeAeadId aead,
+ const PRUint8 configId, const sslEchConfig *cur, sslEchConfig **next)
+{
+ SSL_TRC(50, ("%d: TLS13[%d]: GetMatchingEchConfig %d",
+ SSL_GETPID(), ss->fd, configId));
+
+ /* If |cur|, resume the search at that node, else the list head. */
+ for (PRCList *cur_p = cur ? ((PRCList *)cur)->next : PR_LIST_HEAD(&ss->echConfigs);
+ cur_p != &ss->echConfigs;
+ cur_p = PR_NEXT_LINK(cur_p)) {
+ sslEchConfig *echConfig = (sslEchConfig *)cur_p;
+ if (echConfig->contents.configId == configId &&
+ echConfig->contents.aeadId == aead &&
+ echConfig->contents.kdfId == kdf) {
+ *next = echConfig;
+ return SECSuccess;
+ }
+ }
+
+ *next = NULL;
+ return SECSuccess;
+}
+
+/* Given a CH with extensions, copy from the start up to the extensions
+ * into |writer| and return the extensions themselves in |extensions|.
+ * If |explicitSid|, place this value into |writer| as the SID. Else,
+ * the sid is copied from |reader| to |writer|. */
+static SECStatus
+tls13_CopyChPreamble(sslSocket *ss, sslReader *reader, const SECItem *explicitSid, sslBuffer *writer, sslReadBuffer *extensions)
+{
+ SECStatus rv;
+ sslReadBuffer tmpReadBuf;
+
+ /* Locate the extensions. */
+ rv = sslRead_Read(reader, 2 + SSL3_RANDOM_LENGTH, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Append(writer, tmpReadBuf.buf, tmpReadBuf.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* legacy_session_id */
+ rv = sslRead_ReadVariable(reader, 1, &tmpReadBuf);
+ if (explicitSid) {
+ /* Encoded SID should be empty when copying from CHOuter. */
+ if (tmpReadBuf.len > 0) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(writer, explicitSid->data, explicitSid->len, 1);
+ } else {
+ rv = sslBuffer_AppendVariable(writer, tmpReadBuf.buf, tmpReadBuf.len, 1);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* cipher suites */
+ rv = sslRead_ReadVariable(reader, 2, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(writer, tmpReadBuf.buf, tmpReadBuf.len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* compression */
+ rv = sslRead_ReadVariable(reader, 1, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(writer, tmpReadBuf.buf, tmpReadBuf.len, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* extensions */
+ rv = sslRead_ReadVariable(reader, 2, extensions);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* padding (optional) */
+ sslReadBuffer padding;
+ rv = sslRead_Read(reader, SSL_READER_REMAINING(reader), &padding);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PRUint8 result = 0;
+ for (int i = 0; i < padding.len; i++) {
+ result |= padding.buf[i];
+ }
+ if (result) {
+ SSL_TRC(50, ("%d: TLS13: Invalid ECH ClientHelloInner padding decoded", SSL_GETPID()));
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ECH_EXTENSION, illegal_parameter);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/*
+ * The ClientHelloOuterAAD is a serialized ClientHello structure, defined in
+ * Section 4.1.2 of [RFC8446], which matches the ClientHelloOuter except the
+ * payload field of the "encrypted_client_hello" is replaced with a byte
+ * string of the same length but whose contents are zeros. This value does
+ * not include the four-byte header from the Handshake structure.
+ */
+static SECStatus
+tls13_ServerMakeChOuterAAD(sslSocket *ss, const PRUint8 *outerCh, unsigned int outerChLen, SECItem *outerAAD)
+{
+ SECStatus rv;
+ sslBuffer aad = SSL_BUFFER_EMPTY;
+ const unsigned int echPayloadLen = ss->xtnData.ech->innerCh.len; /* Length of incoming payload */
+ const unsigned int echPayloadOffset = ss->xtnData.ech->payloadStart - outerCh; /* Offset from start of CHO */
+
+ PORT_Assert(outerChLen > echPayloadLen);
+ PORT_Assert(echPayloadOffset + echPayloadLen <= outerChLen);
+ PORT_Assert(ss->sec.isServer);
+ PORT_Assert(ss->xtnData.ech);
+
+#ifdef DEBUG
+ /* Safety check that payload length pointed to by offset matches expected length */
+ sslReader echXtnReader = SSL_READER(outerCh + echPayloadOffset - 2, 2);
+ PRUint64 parsedXtnSize;
+ rv = sslRead_ReadNumber(&echXtnReader, 2, &parsedXtnSize);
+ PR_ASSERT(rv == SECSuccess);
+ PR_ASSERT(parsedXtnSize == echPayloadLen);
+#endif
+
+ rv = sslBuffer_Append(&aad, outerCh, outerChLen);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PORT_Memset(aad.buf + echPayloadOffset, 0, echPayloadLen);
+
+ PRINT_BUF(50, (ss, "AAD for ECH Decryption", aad.buf, aad.len));
+
+ outerAAD->data = aad.buf;
+ outerAAD->len = aad.len;
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&aad);
+ return SECFailure;
+}
+
+SECStatus
+tls13_OpenClientHelloInner(sslSocket *ss, const SECItem *outer, const SECItem *outerAAD, sslEchConfig *cfg, SECItem **chInner)
+{
+ SECStatus rv;
+ HpkeContext *cx = NULL;
+ SECItem *decryptedChInner = NULL;
+ SECItem hpkeInfo = { siBuffer, NULL, 0 };
+ SSL_TRC(50, ("%d: TLS13[%d]: Server opening ECH Inner%s", SSL_GETPID(),
+ ss->fd, ss->ssl3.hs.helloRetry ? " after HRR" : ""));
+
+ if (!ss->ssl3.hs.helloRetry) {
+ PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
+ cx = PK11_HPKE_NewContext(cfg->contents.kemId, cfg->contents.kdfId,
+ cfg->contents.aeadId, NULL, NULL);
+ if (!cx) {
+ goto loser;
+ }
+
+ if (!SECITEM_AllocItem(NULL, &hpkeInfo, strlen(kHpkeInfoEch) + 1 + cfg->raw.len)) {
+ goto loser;
+ }
+ PORT_Memcpy(&hpkeInfo.data[0], kHpkeInfoEch, strlen(kHpkeInfoEch));
+ PORT_Memset(&hpkeInfo.data[strlen(kHpkeInfoEch)], 0, 1);
+ PORT_Memcpy(&hpkeInfo.data[strlen(kHpkeInfoEch) + 1], cfg->raw.data, cfg->raw.len);
+
+ rv = PK11_HPKE_SetupR(cx, ss->echPubKey, ss->echPrivKey,
+ &ss->xtnData.ech->senderPubKey, &hpkeInfo);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+ } else {
+ PORT_Assert(ss->ssl3.hs.echHpkeCtx);
+ cx = ss->ssl3.hs.echHpkeCtx;
+ }
+
+#ifndef UNSAFE_FUZZER_MODE
+ rv = PK11_HPKE_Open(cx, outerAAD, &ss->xtnData.ech->innerCh, &decryptedChInner);
+ if (rv != SECSuccess) {
+ SSL_TRC(10, ("%d: SSL3[%d]: Failed to decrypt inner CH with this candidate",
+ SSL_GETPID(), ss->fd));
+ goto loser; /* code set */
+ }
+#else
+ rv = SECITEM_CopyItem(NULL, decryptedChInner, &ss->xtnData.ech->innerCh);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ decryptedChInner->len -= TLS13_ECH_AEAD_TAG_LEN; /* Fake tag */
+#endif
+
+ /* Stash the context, we may need it for HRR. */
+ ss->ssl3.hs.echHpkeCtx = cx;
+ *chInner = decryptedChInner;
+ PRINT_BUF(100, (ss, "Decrypted ECH Inner", decryptedChInner->data, decryptedChInner->len));
+ SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
+ return SECSuccess;
+
+loser:
+ SECITEM_FreeItem(decryptedChInner, PR_TRUE);
+ SECITEM_FreeItem(&hpkeInfo, PR_FALSE);
+ if (cx != ss->ssl3.hs.echHpkeCtx) {
+ /* Don't double-free if it's already global. */
+ PK11_HPKE_DestroyContext(cx, PR_TRUE);
+ }
+ return SECFailure;
+}
+
+/* This is the maximum number of extension hooks that the following functions can handle. */
+#define MAX_EXTENSION_WRITERS 32
+
+static SECStatus
+tls13_WriteDupXtnsToChInner(PRBool compressing, sslBuffer *dupXtns, sslBuffer *chInnerXtns)
+{
+ SECStatus rv;
+ if (compressing && SSL_BUFFER_LEN(dupXtns) > 0) {
+ rv = sslBuffer_AppendNumber(chInnerXtns, ssl_tls13_outer_extensions_xtn, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(chInnerXtns, dupXtns->len + 1, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendBufferVariable(chInnerXtns, dupXtns, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ } else {
+ /* dupXtns carries whole extensions with lengths on each. */
+ rv = sslBuffer_AppendBuffer(chInnerXtns, dupXtns);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ sslBuffer_Clear(dupXtns);
+ return SECSuccess;
+}
+
+/* Add ordinary extensions to CHInner.
+ * The value of the extension from CHOuter is in |extensionData|.
+ *
+ * If the value is to be compressed, it is written to |dupXtns|.
+ * Otherwise, a full extension is written to |chInnerXtns|.
+ *
+ * This function is always called twice:
+ * once without compression and once with compression if possible.
+ *
+ * Because we want to allow extensions that did not appear in CHOuter
+ * to be included in CHInner, we also need to track which extensions
+ * have been included. This is what |called| and |nCalled| track.
+ */
+static SECStatus
+tls13_ChInnerAppendExtension(sslSocket *ss, PRUint16 extensionType,
+ const sslReadBuffer *extensionData,
+ sslBuffer *dupXtns, sslBuffer *chInnerXtns,
+ PRBool compressing,
+ PRUint16 *called, unsigned int *nCalled)
+{
+ PRUint8 buf[1024] = { 0 };
+ const PRUint8 *p;
+ unsigned int len = 0;
+ PRBool willCompress;
+
+ PORT_Assert(extensionType != ssl_tls13_encrypted_client_hello_xtn);
+ sslCustomExtensionHooks *hook = ss->opt.callExtensionWriterOnEchInner
+ ? ssl_FindCustomExtensionHooks(ss, extensionType)
+ : NULL;
+ if (hook && hook->writer) {
+ if (*nCalled >= MAX_EXTENSION_WRITERS) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); /* TODO new code? */
+ return SECFailure;
+ }
+
+ PRBool append = (*hook->writer)(ss->fd, ssl_hs_client_hello,
+ buf, &len, sizeof(buf), hook->writerArg);
+ called[(*nCalled)++] = extensionType;
+ if (!append) {
+ /* This extension is not going to appear in CHInner. */
+ /* TODO: consider removing this extension from ss->xtnData.advertised.
+ * The consequence of not removing it is that we won't complain
+ * if the server accepts ECH and then includes this extension.
+ * The cost is a complete reworking of ss->xtnData.advertised.
+ */
+ return SECSuccess;
+ }
+ /* It can be compressed if it is the same as the outer value. */
+ willCompress = (len == extensionData->len &&
+ NSS_SecureMemcmp(buf, extensionData->buf, len) == 0);
+ p = buf;
+ } else {
+ /* Non-custom extensions are duplicated when compressing. */
+ willCompress = PR_TRUE;
+ p = extensionData->buf;
+ len = extensionData->len;
+ }
+
+ /* Duplicated extensions all need to go together. */
+ sslBuffer *dst = willCompress ? dupXtns : chInnerXtns;
+ SECStatus rv = sslBuffer_AppendNumber(dst, extensionType, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ if (!willCompress || !compressing) {
+ rv = sslBuffer_AppendVariable(dst, p, len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ /* As this function is called twice, we only want to update our state the second time. */
+ if (compressing) {
+ ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
+ SSL_TRC(50, ("Appending extension=%d to the Client Hello Inner. Compressed?=%d", extensionType, willCompress));
+ }
+ return SECSuccess;
+}
+
+/* Call any custom extension handlers that didn't want to be added to CHOuter. */
+static SECStatus
+tls13_ChInnerAdditionalExtensionWriters(sslSocket *ss, const PRUint16 *called,
+ unsigned int nCalled, sslBuffer *chInnerXtns)
+{
+ if (!ss->opt.callExtensionWriterOnEchInner) {
+ return SECSuccess;
+ }
+
+ for (PRCList *cursor = PR_NEXT_LINK(&ss->extensionHooks);
+ cursor != &ss->extensionHooks;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslCustomExtensionHooks *hook = (sslCustomExtensionHooks *)cursor;
+
+ /* Skip if this hook was already called. */
+ PRBool hookCalled = PR_FALSE;
+ for (unsigned int i = 0; i < nCalled; ++i) {
+ if (called[i] == hook->type) {
+ hookCalled = PR_TRUE;
+ break;
+ }
+ }
+ if (hookCalled) {
+ continue;
+ }
+
+ /* This is a cut-down version of ssl_CallCustomExtensionSenders(). */
+ PRUint8 buf[1024];
+ unsigned int len = 0;
+ PRBool append = (*hook->writer)(ss->fd, ssl_hs_client_hello,
+ buf, &len, sizeof(buf), hook->writerArg);
+ if (!append) {
+ continue;
+ }
+
+ SECStatus rv = sslBuffer_AppendNumber(chInnerXtns, hook->type, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(chInnerXtns, buf, len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = hook->type;
+ }
+ return SECSuccess;
+}
+
+/* Take the PSK extension CHOuter and fill it with junk. */
+static SECStatus
+tls13_RandomizePsk(PRUint8 *buf, unsigned int len)
+{
+ sslReader rdr = SSL_READER(buf, len);
+
+ /* Read the length of identities. */
+ PRUint64 outerLen = 0;
+ SECStatus rv = sslRead_ReadNumber(&rdr, 2, &outerLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PORT_Assert(outerLen < len + 2);
+
+ /* Read the length of PskIdentity.identity */
+ PRUint64 innerLen = 0;
+ rv = sslRead_ReadNumber(&rdr, 2, &innerLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* identities should contain just one identity. */
+ PORT_Assert(outerLen == innerLen + 6);
+
+ /* Randomize PskIdentity.{identity,obfuscated_ticket_age}. */
+ rv = PK11_GenerateRandom(buf + rdr.offset, innerLen + 4);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rdr.offset += innerLen + 4;
+
+ /* Read the length of binders. */
+ rv = sslRead_ReadNumber(&rdr, 2, &outerLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PORT_Assert(outerLen + rdr.offset == len);
+
+ /* Read the length of the binder. */
+ rv = sslRead_ReadNumber(&rdr, 1, &innerLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* binders should contain just one binder. */
+ PORT_Assert(outerLen == innerLen + 1);
+
+ /* Randomize the binder. */
+ rv = PK11_GenerateRandom(buf + rdr.offset, innerLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Given a buffer of extensions prepared for CHOuter, translate those extensions to a
+ * buffer suitable for CHInner. This is intended to be called twice: once without
+ * compression for the transcript hash and binders, and once with compression for
+ * encoding the actual CHInner value.
+ *
+ * Compressed extensions are moved in both runs. When compressing, they are moved
+ * to a single outer_extensions extension, which lists extensions from CHOuter.
+ * When not compressing, this produces the ClientHello that will be reconstructed
+ * from the compressed ClientHello (that is, what goes into the handshake transcript),
+ * so all the compressed extensions need to appear in the same place that the
+ * outer_extensions extension appears.
+ *
+ * On the first run, if |inOutPskXtn| and OuterXtnsBuf contains a PSK extension,
+ * remove it and return in the outparam.he caller will compute the binder value
+ * based on the uncompressed output. Next, if |compress|, consolidate duplicated
+ * extensions (that would otherwise be copied) into a single outer_extensions
+ * extension. If |inOutPskXtn|, the extension contains a binder, it is appended
+ * after the deduplicated outer_extensions. In the case of GREASE ECH, one call
+ * is made to estimate size (wiith compression, null inOutPskXtn).
+ */
+SECStatus
+tls13_ConstructInnerExtensionsFromOuter(sslSocket *ss, sslBuffer *chOuterXtnsBuf,
+ sslBuffer *chInnerXtns, sslBuffer *inOutPskXtn,
+ PRBool shouldCompress)
+{
+ SECStatus rv;
+ PRUint64 extensionType;
+ sslReadBuffer extensionData;
+ sslBuffer pskXtn = SSL_BUFFER_EMPTY;
+ sslBuffer dupXtns = SSL_BUFFER_EMPTY; /* Duplicated extensions, types-only if |compress|. */
+ unsigned int tmpOffset;
+ unsigned int tmpLen;
+ unsigned int srcXtnBase; /* To truncate CHOuter and remove the PSK extension. */
+
+ PRUint16 called[MAX_EXTENSION_WRITERS] = { 0 }; /* For tracking which has been called. */
+ unsigned int nCalled = 0;
+
+ SSL_TRC(50, ("%d: TLS13[%d]: Constructing ECH inner extensions %s compression",
+ SSL_GETPID(), ss->fd, shouldCompress ? "with" : "without"));
+
+ /* When offering the "encrypted_client_hello" extension in its
+ * ClientHelloOuter, the client MUST also offer an empty
+ * "encrypted_client_hello" extension in its ClientHelloInner. */
+ rv = sslBuffer_AppendNumber(chInnerXtns, ssl_tls13_encrypted_client_hello_xtn, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(chInnerXtns, 1, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(chInnerXtns, ech_xtn_type_inner, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ sslReader rdr = SSL_READER(chOuterXtnsBuf->buf, chOuterXtnsBuf->len);
+ while (SSL_READER_REMAINING(&rdr)) {
+ srcXtnBase = rdr.offset;
+ rv = sslRead_ReadNumber(&rdr, 2, &extensionType);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Get the extension data. */
+ rv = sslRead_ReadVariable(&rdr, 2, &extensionData);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Skip extensions that are TLS < 1.3 only, since CHInner MUST
+ * negotiate TLS 1.3 or above.
+ * If the extension is supported by default (sslSupported) but unknown
+ * to TLS 1.3 it must be a TLS < 1.3 only extension. */
+ SSLExtensionSupport sslSupported;
+ (void)SSLExp_GetExtensionSupport(extensionType, &sslSupported);
+ if (sslSupported != ssl_ext_none &&
+ tls13_ExtensionStatus(extensionType, ssl_hs_client_hello) == tls13_extension_unknown) {
+ continue;
+ }
+
+ switch (extensionType) {
+ case ssl_server_name_xtn:
+ /* Write the real (private) SNI value. */
+ rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_Skip(chInnerXtns, 2, &tmpOffset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ tmpLen = SSL_BUFFER_LEN(chInnerXtns);
+ rv = ssl3_ClientFormatServerNameXtn(ss, ss->url,
+ strlen(ss->url),
+ NULL, chInnerXtns);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ tmpLen = SSL_BUFFER_LEN(chInnerXtns) - tmpLen;
+ rv = sslBuffer_InsertNumber(chInnerXtns, tmpOffset, tmpLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* Only update state on second invocation of this function */
+ if (shouldCompress) {
+ ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
+ }
+ break;
+ case ssl_tls13_supported_versions_xtn:
+ /* Only TLS 1.3 and GREASE on CHInner. */
+ rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* Extension length. */
+ tmpLen = (ss->opt.enableGrease) ? 5 : 3;
+ rv = sslBuffer_AppendNumber(chInnerXtns, tmpLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* ProtocolVersion length */
+ rv = sslBuffer_AppendNumber(chInnerXtns, tmpLen - 1, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* ProtocolVersion TLS 1.3 */
+ rv = sslBuffer_AppendNumber(chInnerXtns, SSL_LIBRARY_VERSION_TLS_1_3, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* ProtocolVersion GREASE */
+ if (ss->opt.enableGrease) {
+ rv = sslBuffer_AppendNumber(chInnerXtns, ss->ssl3.hs.grease->idx[grease_version], 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ /* Only update state on second invocation of this function */
+ if (shouldCompress) {
+ ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
+ }
+ break;
+ case ssl_tls13_pre_shared_key_xtn:
+ if (inOutPskXtn && !shouldCompress) {
+ rv = sslBuffer_AppendNumber(&pskXtn, extensionType, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(&pskXtn, extensionData.buf,
+ extensionData.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* This should be the last extension. */
+ PORT_Assert(srcXtnBase == ss->xtnData.lastXtnOffset);
+ PORT_Assert(chOuterXtnsBuf->len - srcXtnBase == extensionData.len + 4);
+ rv = tls13_RandomizePsk(chOuterXtnsBuf->buf + srcXtnBase + 4,
+ chOuterXtnsBuf->len - srcXtnBase - 4);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else if (!inOutPskXtn) {
+ /* When GREASEing, only the length is used.
+ * Order doesn't matter, so just copy the extension. */
+ rv = sslBuffer_AppendNumber(chInnerXtns, extensionType, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(chInnerXtns, extensionData.buf,
+ extensionData.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ /* Only update state on second invocation of this function */
+ if (shouldCompress) {
+ ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = extensionType;
+ }
+ break;
+ default: {
+ /* This is a regular extension. We can maybe compress these. */
+ rv = tls13_ChInnerAppendExtension(ss, extensionType,
+ &extensionData,
+ &dupXtns, chInnerXtns,
+ shouldCompress,
+ called, &nCalled);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ break;
+ }
+ }
+ }
+
+ rv = tls13_WriteDupXtnsToChInner(shouldCompress, &dupXtns, chInnerXtns);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Now call custom extension handlers that didn't choose to append anything to
+ * the outer ClientHello. */
+ rv = tls13_ChInnerAdditionalExtensionWriters(ss, called, nCalled, chInnerXtns);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (inOutPskXtn) {
+ /* On the first, non-compress run, append the (bad) PSK binder.
+ * On the second compression run, the caller is responsible for
+ * providing an extension with a valid binder, so append that. */
+ if (shouldCompress) {
+ rv = sslBuffer_AppendBuffer(chInnerXtns, inOutPskXtn);
+ } else {
+ rv = sslBuffer_AppendBuffer(chInnerXtns, &pskXtn);
+ *inOutPskXtn = pskXtn;
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&pskXtn);
+ sslBuffer_Clear(&dupXtns);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_EncodeClientHelloInner(sslSocket *ss, const sslBuffer *chInner, const sslBuffer *chInnerXtns, sslBuffer *out)
+{
+ PORT_Assert(ss && chInner && chInnerXtns && out);
+ SECStatus rv;
+ sslReadBuffer tmpReadBuf;
+ sslReader chReader = SSL_READER(chInner->buf, chInner->len);
+
+ rv = sslRead_Read(&chReader, 4, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslRead_Read(&chReader, 2 + SSL3_RANDOM_LENGTH, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_Append(out, tmpReadBuf.buf, tmpReadBuf.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Skip the legacy_session_id */
+ rv = sslRead_ReadVariable(&chReader, 1, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(out, 0, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* cipher suites */
+ rv = sslRead_ReadVariable(&chReader, 2, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(out, tmpReadBuf.buf, tmpReadBuf.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* compression methods */
+ rv = sslRead_ReadVariable(&chReader, 1, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(out, tmpReadBuf.buf, tmpReadBuf.len, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Append the extensions. */
+ rv = sslBuffer_AppendBufferVariable(out, chInnerXtns, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(out);
+ return SECFailure;
+}
+
+SECStatus
+tls13_PadChInner(sslBuffer *chInner, uint8_t maxNameLen, uint8_t serverNameLen)
+{
+ SECStatus rv;
+ PORT_Assert(chInner);
+ PORT_Assert(serverNameLen > 0);
+ static unsigned char padding[256 + 32] = { 0 };
+ int16_t name_padding = (int16_t)maxNameLen - (int16_t)serverNameLen;
+ if (name_padding < 0) {
+ name_padding = 0;
+ }
+ unsigned int rounding_padding = 31 - ((SSL_BUFFER_LEN(chInner) + name_padding) % 32);
+ unsigned int total_padding = name_padding + rounding_padding;
+ PORT_Assert(total_padding < sizeof(padding));
+ SSL_TRC(100, ("computed ECH Inner Client Hello padding of size %u", total_padding));
+ rv = sslBuffer_Append(chInner, padding, total_padding);
+ if (rv != SECSuccess) {
+ sslBuffer_Clear(chInner);
+ return SECFailure;
+ }
+ return SECSuccess;
+}
+
+/* Build an ECH Xtn body with a zeroed payload for the client hello inner
+ *
+ * enum { outer(0), inner(1) } ECHClientHelloType;
+ *
+ * struct {
+ * ECHClientHelloType type;
+ * select (ECHClientHello.type) {
+ * case outer:
+ * HpkeSymmetricCipherSuite cipher_suite;
+ * uint8 config_id;
+ * opaque enc<0..2^16-1>;
+ * opaque payload<1..2^16-1>;
+ * case inner:
+ * Empty;
+ * };
+ * } ECHClientHello;
+ *
+ * payloadLen = Size of zeroed placeholder field for payload.
+ * payloadOffset = Out parameter, start of payload field
+ * echXtn = Out parameter, constructed ECH Xtn with zeroed placeholder field.
+*/
+SECStatus
+tls13_BuildEchXtn(sslEchConfig *cfg, const SECItem *hpkeEnc, unsigned int payloadLen, PRUint16 *payloadOffset, sslBuffer *echXtn)
+{
+ SECStatus rv;
+ /* Format the encrypted_client_hello extension. */
+ rv = sslBuffer_AppendNumber(echXtn, ech_xtn_type_outer, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(echXtn, cfg->contents.kdfId, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(echXtn, cfg->contents.aeadId, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendNumber(echXtn, cfg->contents.configId, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (hpkeEnc) {
+ /* Public Key */
+ rv = sslBuffer_AppendVariable(echXtn, hpkeEnc->data, hpkeEnc->len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ /* |enc| is empty. */
+ rv = sslBuffer_AppendNumber(echXtn, 0, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ payloadLen += TLS13_ECH_AEAD_TAG_LEN;
+ rv = sslBuffer_AppendNumber(echXtn, payloadLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ *payloadOffset = echXtn->len;
+ rv = sslBuffer_Fill(echXtn, 0, payloadLen);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PRINT_BUF(100, (NULL, "ECH Xtn with Placeholder:", echXtn->buf, echXtn->len));
+ return SECSuccess;
+loser:
+ sslBuffer_Clear(echXtn);
+ return SECFailure;
+}
+
+SECStatus
+tls13_ConstructClientHelloWithEch(sslSocket *ss, const sslSessionID *sid, PRBool freshSid,
+ sslBuffer *chOuter, sslBuffer *chOuterXtnsBuf)
+{
+ SECStatus rv;
+ sslBuffer chInner = SSL_BUFFER_EMPTY;
+ sslBuffer encodedChInner = SSL_BUFFER_EMPTY;
+ sslBuffer paddingChInner = SSL_BUFFER_EMPTY;
+ sslBuffer chInnerXtns = SSL_BUFFER_EMPTY;
+ sslBuffer pskXtn = SSL_BUFFER_EMPTY;
+ unsigned int preambleLen;
+
+ SSL_TRC(50, ("%d: TLS13[%d]: Constructing ECH inner", SSL_GETPID(), ss->fd));
+
+ /* Create the full (uncompressed) inner extensions and steal any PSK extension.
+ * NB: Neither chOuterXtnsBuf nor chInnerXtns are length-prefixed. */
+ rv = tls13_ConstructInnerExtensionsFromOuter(ss, chOuterXtnsBuf, &chInnerXtns,
+ &pskXtn, PR_FALSE);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+
+ rv = ssl3_CreateClientHelloPreamble(ss, sid, PR_FALSE, SSL_LIBRARY_VERSION_TLS_1_3,
+ PR_TRUE, &chInnerXtns, &chInner);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+ preambleLen = SSL_BUFFER_LEN(&chInner);
+
+ /* Write handshake header length. tls13_EncryptClientHello will
+ * remove this upon encoding, but the transcript needs it. This assumes
+ * the 4B stream-variant header. */
+ PORT_Assert(!IS_DTLS(ss));
+ rv = sslBuffer_InsertNumber(&chInner, 1,
+ chInner.len + 2 + chInnerXtns.len - 4, 3);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (pskXtn.len) {
+ PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_pre_shared_key_xtn));
+ rv = tls13_WriteExtensionsWithBinder(ss, &chInnerXtns, &chInner);
+ /* Update the stolen PSK extension with the binder value. */
+ PORT_Memcpy(pskXtn.buf, &chInnerXtns.buf[chInnerXtns.len - pskXtn.len], pskXtn.len);
+ } else {
+ rv = sslBuffer_AppendBufferVariable(&chInner, &chInnerXtns, 2);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ PRINT_BUF(50, (ss, "Uncompressed CHInner", chInner.buf, chInner.len));
+ rv = ssl3_UpdateHandshakeHashesInt(ss, chInner.buf, chInner.len,
+ &ss->ssl3.hs.echInnerMessages);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+
+ /* Un-append the extensions, then append compressed via Encoded. */
+ SSL_BUFFER_LEN(&chInner) = preambleLen;
+ sslBuffer_Clear(&chInnerXtns);
+ rv = tls13_ConstructInnerExtensionsFromOuter(ss, chOuterXtnsBuf,
+ &chInnerXtns, &pskXtn, PR_TRUE);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = tls13_EncodeClientHelloInner(ss, &chInner, &chInnerXtns, &encodedChInner);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PRINT_BUF(50, (ss, "Compressed CHInner", encodedChInner.buf, encodedChInner.len));
+
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->echConfigs));
+ sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
+
+ /* We are using ECH so SNI must have been included */
+ rv = tls13_PadChInner(&encodedChInner, cfg->contents.maxNameLen, strlen(ss->url));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Build the ECH Xtn with placeholder and put it in chOuterXtnsBuf */
+ sslBuffer echXtn = SSL_BUFFER_EMPTY;
+ const SECItem *hpkeEnc = NULL;
+ if (!ss->ssl3.hs.helloRetry) {
+ hpkeEnc = PK11_HPKE_GetEncapPubKey(ss->ssl3.hs.echHpkeCtx);
+ if (!hpkeEnc) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ goto loser;
+ }
+ }
+ PRUint16 echXtnPayloadOffset; /* Offset from start of ECH Xtn to ECH Payload */
+ rv = tls13_BuildEchXtn(cfg, hpkeEnc, encodedChInner.len, &echXtnPayloadOffset, &echXtn);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ ss->xtnData.echAdvertised[ss->xtnData.echNumAdvertised++] = ssl_tls13_encrypted_client_hello_xtn;
+ rv = ssl3_EmplaceExtension(ss, chOuterXtnsBuf, ssl_tls13_encrypted_client_hello_xtn,
+ echXtn.buf, echXtn.len, PR_TRUE);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Add the padding */
+ rv = ssl_InsertPaddingExtension(ss, chOuter->len, chOuterXtnsBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Finish the CHO with the ECH Xtn payload zeroed */
+ rv = ssl3_InsertChHeaderSize(ss, chOuter, chOuterXtnsBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ unsigned int chOuterXtnsOffset = chOuter->len + 2; /* From Start of CHO to Extensions list */
+ rv = sslBuffer_AppendBufferVariable(chOuter, chOuterXtnsBuf, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* AAD consists of entire CHO, minus the 4 byte handshake header */
+ SECItem aadItem = { siBuffer, chOuter->buf + 4, chOuter->len - 4 };
+ /* ECH Payload begins after CHO Header, after ECH Xtn start, after ECH Xtn header */
+ PRUint8 *echPayload = chOuter->buf + chOuterXtnsOffset + ss->xtnData.echXtnOffset + 4 + echXtnPayloadOffset;
+ /* Insert the encrypted_client_hello xtn and coalesce. */
+ rv = tls13_EncryptClientHello(ss, &aadItem, &encodedChInner, echPayload);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ sslBuffer_Clear(&echXtn);
+ sslBuffer_Clear(&chInner);
+ sslBuffer_Clear(&encodedChInner);
+ sslBuffer_Clear(&paddingChInner);
+ sslBuffer_Clear(&chInnerXtns);
+ sslBuffer_Clear(&pskXtn);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&chInner);
+ sslBuffer_Clear(&encodedChInner);
+ sslBuffer_Clear(&paddingChInner);
+ sslBuffer_Clear(&chInnerXtns);
+ sslBuffer_Clear(&pskXtn);
+ PORT_Assert(PORT_GetError() != 0);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_ComputeEchHelloRetryTranscript(sslSocket *ss, const PRUint8 *sh, unsigned int shLen, sslBuffer *out)
+{
+ SECStatus rv;
+ PRUint8 zeroedEchSignal[TLS13_ECH_SIGNAL_LEN] = { 0 };
+ sslBuffer *previousTranscript;
+
+ if (ss->sec.isServer) {
+ previousTranscript = &(ss->ssl3.hs.messages);
+ } else {
+ previousTranscript = &(ss->ssl3.hs.echInnerMessages);
+ }
+ /*
+ * This segment calculates the hash of the Client Hello
+ * TODO(djackson@mozilla.com) - Replace with existing function?
+ * e.g. tls13_ReinjectHandshakeTranscript
+ * TODO(djackson@mozilla.com) - Replace with streaming version
+ */
+ if (!ss->ssl3.hs.helloRetry || !ss->sec.isServer) {
+ /*
+ * This function can be called in three situations:
+ * - By the server, prior to sending the HRR, when ECH was accepted
+ * - By the client, after receiving the HRR, but before it knows whether ECH was accepted
+ * - By the server, after accepting ECH and receiving CH2 when it needs to reconstruct the HRR
+ * In the first two situations, we need to include the message hash of inner ClientHello1 but don't
+ * want to alter the buffer containing the current transcript.
+ * In the last, the buffer already contains the message hash of inner ClientHello1.
+ */
+ SSL3Hashes hashes;
+ rv = tls13_ComputeHash(ss, &hashes, previousTranscript->buf, previousTranscript->len, tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(out, ssl_hs_message_hash, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendNumber(out, hashes.len, 3);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_Append(out, hashes.u.raw, hashes.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ } else {
+ rv = sslBuffer_AppendBuffer(out, previousTranscript);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ }
+ /* Ensure the first ClientHello has been hashed. */
+ PR_ASSERT(out->len == tls13_GetHashSize(ss) + 4);
+ PRINT_BUF(100, (ss, "ECH Client Hello Message Hash", out->buf, out->len));
+ /* Message Header */
+ rv = sslBuffer_AppendNumber(out, ssl_hs_server_hello, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* Message Size */
+ rv = sslBuffer_AppendNumber(out, shLen, 3);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* Calculate where the HRR ECH Xtn Signal begins */
+ unsigned int absEchOffset;
+ if (ss->sec.isServer) {
+ /* We know the ECH HRR Xtn is last */
+ PORT_Assert(shLen >= TLS13_ECH_SIGNAL_LEN);
+ absEchOffset = shLen - TLS13_ECH_SIGNAL_LEN;
+ } else {
+ /* We parsed the offset earlier */
+ /* The result of pointer comparision is unspecified
+ * (and pointer arithemtic is undefined) if the pointers
+ * do not point to the same array or struct. That means these
+ * asserts cannot be relied on for correctness in compiled code,
+ * but may help the reader understand the requirements.
+ */
+ PORT_Assert(ss->xtnData.ech->hrrConfirmation > sh);
+ PORT_Assert(ss->xtnData.ech->hrrConfirmation < sh + shLen);
+ absEchOffset = ss->xtnData.ech->hrrConfirmation - sh;
+ }
+ PR_ASSERT(tls13_Debug_CheckXtnBegins(sh + absEchOffset - 4, ssl_tls13_encrypted_client_hello_xtn));
+ /* The HRR up to the ECH Xtn signal */
+ rv = sslBuffer_Append(out, sh, absEchOffset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_Append(out, zeroedEchSignal, sizeof(zeroedEchSignal));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PR_ASSERT(absEchOffset + TLS13_ECH_SIGNAL_LEN <= shLen);
+ /* The remainder of the HRR */
+ rv = sslBuffer_Append(out, sh + absEchOffset + TLS13_ECH_SIGNAL_LEN, shLen - absEchOffset - TLS13_ECH_SIGNAL_LEN);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PR_ASSERT(out->len == tls13_GetHashSize(ss) + 4 + shLen + 4);
+ return SECSuccess;
+loser:
+ sslBuffer_Clear(out);
+ return SECFailure;
+}
+
+static SECStatus
+tls13_ComputeEchServerHelloTranscript(sslSocket *ss, const PRUint8 *sh, unsigned int shLen, sslBuffer *out)
+{
+ SECStatus rv;
+ sslBuffer *chSource = ss->sec.isServer ? &ss->ssl3.hs.messages : &ss->ssl3.hs.echInnerMessages;
+ unsigned int offset = sizeof(SSL3ProtocolVersion) +
+ SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN;
+ PORT_Assert(sh && shLen > offset);
+ PORT_Assert(TLS13_ECH_SIGNAL_LEN <= SSL3_RANDOM_LENGTH);
+
+ /* TODO(djackson@mozilla.com) - Replace with streaming version */
+
+ rv = sslBuffer_AppendBuffer(out, chSource);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Re-create the message header. */
+ rv = sslBuffer_AppendNumber(out, ssl_hs_server_hello, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendNumber(out, shLen, 3);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Copy the version and 24B of server_random. */
+ rv = sslBuffer_Append(out, sh, offset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Zero the signal placeholder. */
+ rv = sslBuffer_AppendNumber(out, 0, TLS13_ECH_SIGNAL_LEN);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ offset += TLS13_ECH_SIGNAL_LEN;
+
+ /* Use the remainder of SH. */
+ rv = sslBuffer_Append(out, &sh[offset], shLen - offset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ sslBuffer_Clear(&ss->ssl3.hs.messages);
+ sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
+ return SECSuccess;
+loser:
+ sslBuffer_Clear(&ss->ssl3.hs.messages);
+ sslBuffer_Clear(&ss->ssl3.hs.echInnerMessages);
+ sslBuffer_Clear(out);
+ return SECFailure;
+}
+
+/* Compute the ECH signal using the transcript (up to, including)
+ * ServerHello. The server sources this transcript prefix from
+ * ss->ssl3.hs.messages, as it never uses ss->ssl3.hs.echInnerMessages.
+ * The client uses the inner transcript, echInnerMessages. */
+SECStatus
+tls13_ComputeEchSignal(sslSocket *ss, PRBool isHrr, const PRUint8 *sh, unsigned int shLen, PRUint8 *out)
+{
+ SECStatus rv;
+ sslBuffer confMsgs = SSL_BUFFER_EMPTY;
+ SSL3Hashes hashes;
+ PK11SymKey *echSecret = NULL;
+
+ const char *hkdfInfo = isHrr ? kHkdfInfoEchHrrConfirm : kHkdfInfoEchConfirm;
+ const size_t hkdfInfoLen = strlen(hkdfInfo);
+
+ PRINT_BUF(100, (ss, "ECH Server Hello", sh, shLen));
+
+ if (isHrr) {
+ rv = tls13_ComputeEchHelloRetryTranscript(ss, sh, shLen, &confMsgs);
+ } else {
+ rv = tls13_ComputeEchServerHelloTranscript(ss, sh, shLen, &confMsgs);
+ }
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PRINT_BUF(100, (ss, "ECH Transcript", confMsgs.buf, confMsgs.len));
+ rv = tls13_ComputeHash(ss, &hashes, confMsgs.buf, confMsgs.len,
+ tls13_GetHash(ss));
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ PRINT_BUF(100, (ss, "ECH Transcript Hash", &hashes.u, hashes.len));
+ rv = tls13_DeriveEchSecret(ss, &echSecret);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = tls13_HkdfExpandLabelRaw(echSecret, tls13_GetHash(ss), hashes.u.raw,
+ hashes.len, hkdfInfo, hkdfInfoLen, ss->protocolVariant,
+ out, TLS13_ECH_SIGNAL_LEN);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ SSL_TRC(50, ("%d: TLS13[%d]: %s computed ECH signal", SSL_GETPID(), ss->fd, SSL_ROLE(ss)));
+ PRINT_BUF(50, (ss, "Computed ECH Signal", out, TLS13_ECH_SIGNAL_LEN));
+ PK11_FreeSymKey(echSecret);
+ sslBuffer_Clear(&confMsgs);
+ return SECSuccess;
+
+loser:
+ PK11_FreeSymKey(echSecret);
+ sslBuffer_Clear(&confMsgs);
+ return SECFailure;
+}
+
+/* Ech Secret is HKDF-Extract(0, ClientHelloInner.random) where
+ "0" is a string of Hash.len bytes of value 0. */
+SECStatus
+tls13_DeriveEchSecret(const sslSocket *ss, PK11SymKey **output)
+{
+ SECStatus rv;
+ PK11SlotInfo *slot = NULL;
+ PK11SymKey *crKey = NULL;
+ SECItem rawKey;
+ const unsigned char *client_random = ss->sec.isServer ? ss->ssl3.hs.client_random : ss->ssl3.hs.client_inner_random;
+ PRINT_BUF(50, (ss, "Client Random for ECH", client_random, SSL3_RANDOM_LENGTH));
+ /* We need a SECItem */
+ rv = SECITEM_MakeItem(NULL, &rawKey, client_random, SSL3_RANDOM_LENGTH);
+ if (rv != SECSuccess) {
+ goto cleanup;
+ }
+ /* We need a slot*/
+ slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
+ if (!slot) {
+ rv = SECFailure;
+ goto cleanup;
+ }
+ /* We import the key */
+ crKey = PK11_ImportDataKey(slot, CKM_HKDF_DERIVE, PK11_OriginUnwrap,
+ CKA_DERIVE, &rawKey, NULL);
+ if (crKey == NULL) {
+ rv = SECFailure;
+ goto cleanup;
+ }
+ /* NULL will be expanded to 0s of hash length */
+ rv = tls13_HkdfExtract(NULL, crKey, tls13_GetHash(ss), output);
+ if (rv != SECSuccess) {
+ goto cleanup;
+ }
+ SSL_TRC(50, ("%d: TLS13[%d]: ECH Confirmation Key Derived.",
+ SSL_GETPID(), ss->fd));
+ PRINT_KEY(50, (NULL, "ECH Confirmation Key", *output));
+cleanup:
+ SECITEM_ZfreeItem(&rawKey, PR_FALSE);
+ if (slot) {
+ PK11_FreeSlot(slot);
+ }
+ if (crKey) {
+ PK11_FreeSymKey(crKey);
+ }
+ if (rv != SECSuccess && *output) {
+ PK11_FreeSymKey(*output);
+ *output = NULL;
+ }
+ return rv;
+}
+
+/* Called just prior to padding the CH. Use the size of the CH to estimate
+ * the size of a corresponding ECH extension, then add it to the buffer. */
+SECStatus
+tls13_MaybeGreaseEch(sslSocket *ss, const sslBuffer *preamble, sslBuffer *buf)
+{
+ SECStatus rv;
+ sslBuffer chInnerXtns = SSL_BUFFER_EMPTY;
+ sslBuffer encodedCh = SSL_BUFFER_EMPTY;
+ sslBuffer greaseBuf = SSL_BUFFER_EMPTY;
+ unsigned int payloadLen;
+ HpkeAeadId aead;
+ PK11SlotInfo *slot = NULL;
+ PK11SymKey *hmacPrk = NULL;
+ PK11SymKey *derivedData = NULL;
+ SECItem *rawData;
+ CK_HKDF_PARAMS params;
+ SECItem paramsi;
+ /* 1B aead determinant (don't send), 1B config_id, 32B enc, payload */
+ PR_ASSERT(!ss->sec.isServer);
+ const int kNonPayloadLen = 34;
+
+ if (!ss->opt.enableTls13GreaseEch || ss->ssl3.hs.echHpkeCtx) {
+ return SECSuccess;
+ }
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
+ IS_DTLS(ss)) {
+ return SECSuccess;
+ }
+
+ /* In draft-09, CH2 sends exactly the same GREASE ECH extension. */
+ if (ss->ssl3.hs.helloRetry) {
+ return ssl3_EmplaceExtension(ss, buf, ssl_tls13_encrypted_client_hello_xtn,
+ ss->ssl3.hs.greaseEchBuf.buf,
+ ss->ssl3.hs.greaseEchBuf.len, PR_TRUE);
+ }
+
+ /* Compress the extensions for payload length. */
+ rv = tls13_ConstructInnerExtensionsFromOuter(ss, buf, &chInnerXtns,
+ NULL, PR_TRUE);
+ if (rv != SECSuccess) {
+ goto loser; /* Code set */
+ }
+ rv = tls13_EncodeClientHelloInner(ss, preamble, &chInnerXtns, &encodedCh);
+ if (rv != SECSuccess) {
+ goto loser; /* Code set */
+ }
+ rv = tls13_PadChInner(&encodedCh, ss->ssl3.hs.greaseEchSize, strlen(ss->url));
+
+ payloadLen = encodedCh.len;
+ payloadLen += TLS13_ECH_AEAD_TAG_LEN; /* Aead tag */
+
+ /* HMAC-Expand to get something that will pass for ciphertext. */
+ slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
+ if (!slot) {
+ goto loser;
+ }
+
+ hmacPrk = PK11_KeyGen(slot, CKM_HKDF_DATA, NULL, SHA256_LENGTH, NULL);
+ if (!hmacPrk) {
+ goto loser;
+ }
+
+ params.bExtract = CK_FALSE;
+ params.bExpand = CK_TRUE;
+ params.prfHashMechanism = CKM_SHA256;
+ params.pInfo = NULL;
+ params.ulInfoLen = 0;
+ paramsi.data = (unsigned char *)&params;
+ paramsi.len = sizeof(params);
+ derivedData = PK11_DeriveWithFlags(hmacPrk, CKM_HKDF_DATA,
+ &paramsi, CKM_HKDF_DATA,
+ CKA_DERIVE, kNonPayloadLen + payloadLen,
+ CKF_VERIFY);
+ if (!derivedData) {
+ goto loser;
+ }
+
+ rv = PK11_ExtractKeyValue(derivedData);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rawData = PK11_GetKeyData(derivedData);
+ if (!rawData) {
+ goto loser;
+ }
+ PORT_Assert(rawData->len == kNonPayloadLen + payloadLen);
+
+ /* struct {
+ HpkeSymmetricCipherSuite cipher_suite; // kdf_id, aead_id
+ PRUint8 config_id;
+ opaque enc<1..2^16-1>;
+ opaque payload<1..2^16-1>;
+ } ClientECH; */
+
+ rv = sslBuffer_AppendNumber(&greaseBuf, ech_xtn_type_outer, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ /* Only support SHA256. */
+ rv = sslBuffer_AppendNumber(&greaseBuf, HpkeKdfHkdfSha256, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* HpkeAeadAes128Gcm = 1, HpkeAeadChaCha20Poly1305 = 3, */
+ aead = (rawData->data[0] & 1) ? HpkeAeadAes128Gcm : HpkeAeadChaCha20Poly1305;
+ rv = sslBuffer_AppendNumber(&greaseBuf, aead, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* config_id */
+ rv = sslBuffer_AppendNumber(&greaseBuf, rawData->data[1], 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* enc len is fixed 32B for X25519. */
+ rv = sslBuffer_AppendVariable(&greaseBuf, &rawData->data[2], 32, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendVariable(&greaseBuf, &rawData->data[kNonPayloadLen], payloadLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Mark ECH as advertised so that we can validate any response.
+ * We'll use echHpkeCtx to determine if we sent real or GREASE ECH. */
+ rv = ssl3_EmplaceExtension(ss, buf, ssl_tls13_encrypted_client_hello_xtn,
+ greaseBuf.buf, greaseBuf.len, PR_TRUE);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Stash the GREASE ECH extension - in the case of HRR, CH2 must echo it. */
+ ss->ssl3.hs.greaseEchBuf = greaseBuf;
+
+ sslBuffer_Clear(&chInnerXtns);
+ sslBuffer_Clear(&encodedCh);
+ PK11_FreeSymKey(hmacPrk);
+ PK11_FreeSymKey(derivedData);
+ PK11_FreeSlot(slot);
+ return SECSuccess;
+
+loser:
+ sslBuffer_Clear(&chInnerXtns);
+ sslBuffer_Clear(&encodedCh);
+ PK11_FreeSymKey(hmacPrk);
+ PK11_FreeSymKey(derivedData);
+ if (slot) {
+ PK11_FreeSlot(slot);
+ }
+ return SECFailure;
+}
+
+SECStatus
+tls13_MaybeHandleEch(sslSocket *ss, const PRUint8 *msg, PRUint32 msgLen, SECItem *sidBytes,
+ SECItem *comps, SECItem *cookieBytes, SECItem *suites, SECItem **echInner)
+{
+ SECStatus rv;
+ SECItem *tmpEchInner = NULL;
+ PRUint8 *b;
+ PRUint32 length;
+ TLSExtension *echExtension;
+ TLSExtension *versionExtension;
+ PORT_Assert(!ss->ssl3.hs.echAccepted);
+ SECItem tmpSid = { siBuffer, NULL, 0 };
+ SECItem tmpCookie = { siBuffer, NULL, 0 };
+ SECItem tmpSuites = { siBuffer, NULL, 0 };
+ SECItem tmpComps = { siBuffer, NULL, 0 };
+
+ echExtension = ssl3_FindExtension(ss, ssl_tls13_encrypted_client_hello_xtn);
+ if (echExtension) {
+ rv = tls13_ServerHandleOuterEchXtn(ss, &ss->xtnData, &echExtension->data);
+ if (rv != SECSuccess) {
+ goto loser; /* code set, alert sent. */
+ }
+ rv = tls13_MaybeAcceptEch(ss, sidBytes, msg, msgLen, &tmpEchInner);
+ if (rv != SECSuccess) {
+ goto loser; /* code set, alert sent. */
+ }
+ }
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
+
+ if (ss->ssl3.hs.echAccepted) {
+ PORT_Assert(tmpEchInner);
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.remoteExtensions));
+
+ /* Start over on ECHInner */
+ b = tmpEchInner->data;
+ length = tmpEchInner->len;
+ rv = ssl3_HandleClientHelloPreamble(ss, &b, &length, &tmpSid,
+ &tmpCookie, &tmpSuites, &tmpComps);
+ if (rv != SECSuccess) {
+ goto loser; /* code set, alert sent. */
+ }
+
+ versionExtension = ssl3_FindExtension(ss, ssl_tls13_supported_versions_xtn);
+ if (!versionExtension) {
+ FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_VERSION, illegal_parameter);
+ goto loser;
+ }
+ rv = tls13_NegotiateVersion(ss, versionExtension);
+ if (rv != SECSuccess) {
+ /* code and alert set by tls13_NegotiateVersion */
+ goto loser;
+ }
+
+ *comps = tmpComps;
+ *cookieBytes = tmpCookie;
+ *sidBytes = tmpSid;
+ *suites = tmpSuites;
+ *echInner = tmpEchInner;
+ }
+ return SECSuccess;
+
+loser:
+ SECITEM_FreeItem(tmpEchInner, PR_TRUE);
+ PORT_Assert(PORT_GetError() != 0);
+ return SECFailure;
+}
+
+SECStatus
+tls13_MaybeHandleEchSignal(sslSocket *ss, const PRUint8 *sh, PRUint32 shLen, PRBool isHrr)
+{
+ SECStatus rv;
+ PRUint8 computed[TLS13_ECH_SIGNAL_LEN];
+ const PRUint8 *signal;
+ PORT_Assert(!ss->sec.isServer);
+
+ /* If !echHpkeCtx, we either didn't advertise or sent GREASE ECH. */
+ if (!ss->ssl3.hs.echHpkeCtx) {
+ SSL_TRC(50, ("%d: TLS13[%d]: client only sent GREASE ECH",
+ SSL_GETPID(), ss->fd));
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
+ return SECSuccess;
+ }
+
+ if (isHrr) {
+ if (ss->xtnData.ech) {
+ signal = ss->xtnData.ech->hrrConfirmation;
+ } else {
+ SSL_TRC(50, ("%d: TLS13[%d]: client did not receive ECH Xtn from Server HRR",
+ SSL_GETPID(), ss->fd));
+ signal = NULL;
+ ss->ssl3.hs.echAccepted = PR_FALSE;
+ ss->ssl3.hs.echDecided = PR_TRUE;
+ }
+ } else {
+ signal = &ss->ssl3.hs.server_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
+ }
+
+ PORT_Assert(ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn));
+
+ /* Check ECH Confirmation for HRR ECH Xtn or ServerHello Random */
+ if (signal) {
+ rv = tls13_ComputeEchSignal(ss, isHrr, sh, shLen, computed);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PRINT_BUF(100, (ss, "Server Signal", signal, TLS13_ECH_SIGNAL_LEN));
+ PRBool new_decision = !NSS_SecureMemcmp(computed, signal, TLS13_ECH_SIGNAL_LEN);
+ /* Server can't change its mind on whether to accept ECH */
+ if (ss->ssl3.hs.echDecided && new_decision != ss->ssl3.hs.echAccepted) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ ss->ssl3.hs.echAccepted = new_decision;
+ ss->ssl3.hs.echDecided = PR_TRUE;
+ }
+
+ ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_ech;
+ if (ss->ssl3.hs.echAccepted) {
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_SERVER_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ /* Server accepted, but sent an extension which was only advertised in the ClientHelloOuter */
+ if (ss->ssl3.hs.echInvalidExtension) {
+ (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+
+ /* Swap the advertised lists as we've accepted ECH. */
+ PRUint16 *tempArray = ss->xtnData.advertised;
+ PRUint16 tempNum = ss->xtnData.numAdvertised;
+
+ ss->xtnData.advertised = ss->xtnData.echAdvertised;
+ ss->xtnData.numAdvertised = ss->xtnData.echNumAdvertised;
+
+ ss->xtnData.echAdvertised = tempArray;
+ ss->xtnData.echNumAdvertised = tempNum;
+
+ /* |enc| must not be included in CH2.ClientECH. */
+ if (ss->ssl3.hs.helloRetry && ss->sec.isServer &&
+ ss->xtnData.ech->senderPubKey.len) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_BAD_2ND_CLIENT_HELLO);
+ return SECFailure;
+ }
+ ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_tls13_encrypted_client_hello_xtn;
+
+ /* Only overwrite client_random with client_inner_random if CHInner was
+ * succesfully used for handshake (NOT if HRR is received). */
+ if (!isHrr) {
+ PORT_Memcpy(ss->ssl3.hs.client_random, ss->ssl3.hs.client_inner_random, SSL3_RANDOM_LENGTH);
+ }
+ }
+ /* If rejected, leave echHpkeCtx and echPublicName for rejection paths. */
+ ssl3_CoalesceEchHandshakeHashes(ss);
+ SSL_TRC(3, ("%d: TLS13[%d]: ECH %s accepted by server",
+ SSL_GETPID(), ss->fd, ss->ssl3.hs.echAccepted ? "is" : "is not"));
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_UnencodeChInner(sslSocket *ss, const SECItem *sidBytes, SECItem **echInner)
+{
+ SECStatus rv;
+ sslReadBuffer outerExtensionsList;
+ sslReadBuffer tmpReadBuf;
+ sslBuffer unencodedChInner = SSL_BUFFER_EMPTY;
+ PRCList *outerCursor;
+ PRCList *innerCursor;
+ PRBool outerFound;
+ PRUint32 xtnsOffset;
+ PRUint64 tmp;
+ PRUint8 *tmpB;
+ PRUint32 tmpLength;
+ sslReader chReader = SSL_READER((*echInner)->data, (*echInner)->len);
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.echOuterExtensions));
+ PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ssl3.hs.remoteExtensions));
+ TLSExtension *echExtension;
+ int error = SSL_ERROR_INTERNAL_ERROR_ALERT;
+ int errDesc = internal_error;
+
+ PRINT_BUF(100, (ss, "ECH Inner", chReader.buf.buf, chReader.buf.len));
+
+ /* unencodedChInner := preamble, tmpReadBuf := encoded extensions. */
+ rv = tls13_CopyChPreamble(ss, &chReader, sidBytes, &unencodedChInner, &tmpReadBuf);
+ if (rv != SECSuccess) {
+ goto loser; /* code set */
+ }
+
+ /* Parse inner extensions into ss->ssl3.hs.remoteExtensions. */
+ tmpB = CONST_CAST(PRUint8, tmpReadBuf.buf);
+ rv = ssl3_ParseExtensions(ss, &tmpB, &tmpReadBuf.len);
+ if (rv != SECSuccess) {
+ goto loser; /* malformed, alert sent. */
+ }
+
+ echExtension = ssl3_FindExtension(ss, ssl_tls13_encrypted_client_hello_xtn);
+ if (!echExtension) {
+ error = SSL_ERROR_MISSING_ECH_EXTENSION;
+ errDesc = illegal_parameter;
+ goto alert_loser; /* Must have an inner Extension */
+ }
+ rv = tls13_ServerHandleInnerEchXtn(ss, &ss->xtnData, &echExtension->data);
+ if (rv != SECSuccess) {
+ goto loser; /* code set, alert sent. */
+ }
+
+ /* Exit early if there are no outer_extensions to decompress. */
+ if (!ssl3_FindExtension(ss, ssl_tls13_outer_extensions_xtn)) {
+ rv = sslBuffer_AppendVariable(&unencodedChInner, tmpReadBuf.buf, tmpReadBuf.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ sslBuffer_Clear(&unencodedChInner);
+ return SECSuccess;
+ }
+
+ /* Save room for uncompressed length. */
+ rv = sslBuffer_Skip(&unencodedChInner, 2, &xtnsOffset);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* For each inner extension: If not outer_extensions, copy it to the output.
+ * Else if outer_extensions, iterate the compressed extension list and append
+ * each full extension as contained in CHOuter. Compressed extensions must be
+ * contiguous, so decompress at the point at which outer_extensions appears. */
+ for (innerCursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions);
+ innerCursor != &ss->ssl3.hs.remoteExtensions;
+ innerCursor = PR_NEXT_LINK(innerCursor)) {
+ TLSExtension *innerExtension = (TLSExtension *)innerCursor;
+ if (innerExtension->type != ssl_tls13_outer_extensions_xtn) {
+ SSL_TRC(10, ("%d: SSL3[%d]: copying inner extension of type %d and size %d directly", SSL_GETPID(),
+ ss->fd, innerExtension->type, innerExtension->data.len));
+ rv = sslBuffer_AppendNumber(&unencodedChInner,
+ innerExtension->type, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(&unencodedChInner,
+ innerExtension->data.data,
+ innerExtension->data.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ continue;
+ }
+
+ /* Decompress */
+ sslReader extensionRdr = SSL_READER(innerExtension->data.data,
+ innerExtension->data.len);
+ rv = sslRead_ReadVariable(&extensionRdr, 1, &outerExtensionsList);
+ if (rv != SECSuccess) {
+ SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid size.",
+ SSL_GETPID(), ss->fd));
+ error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
+ errDesc = illegal_parameter;
+ goto alert_loser;
+ }
+ if (SSL_READER_REMAINING(&extensionRdr) || (outerExtensionsList.len % 2) != 0 || !outerExtensionsList.len) {
+ SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid size.",
+ SSL_GETPID(), ss->fd));
+ error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
+ errDesc = illegal_parameter;
+ goto alert_loser;
+ }
+
+ outerCursor = &ss->ssl3.hs.echOuterExtensions;
+ sslReader compressedTypes = SSL_READER(outerExtensionsList.buf, outerExtensionsList.len);
+ while (SSL_READER_REMAINING(&compressedTypes)) {
+ outerFound = PR_FALSE;
+ rv = sslRead_ReadNumber(&compressedTypes, 2, &tmp);
+ if (rv != SECSuccess) {
+ SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has invalid contents.",
+ SSL_GETPID(), ss->fd));
+ error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
+ errDesc = illegal_parameter;
+ goto alert_loser;
+ }
+ if (tmp == ssl_tls13_encrypted_client_hello_xtn ||
+ tmp == ssl_tls13_outer_extensions_xtn) {
+ SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions contains an invalid reference.",
+ SSL_GETPID(), ss->fd));
+ error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
+ errDesc = illegal_parameter;
+ goto alert_loser;
+ }
+ do {
+ const TLSExtension *candidate = (TLSExtension *)outerCursor;
+ /* Advance the outerCursor, we never consider the same xtn twice. */
+ outerCursor = PR_NEXT_LINK(outerCursor);
+ if (candidate->type == tmp) {
+ outerFound = PR_TRUE;
+ SSL_TRC(100, ("%d: SSL3[%d]: Decompressing ECH Inner Extension of type %d",
+ SSL_GETPID(), ss->fd, tmp));
+ rv = sslBuffer_AppendNumber(&unencodedChInner,
+ candidate->type, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = sslBuffer_AppendVariable(&unencodedChInner,
+ candidate->data.data,
+ candidate->data.len, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ break;
+ }
+ } while (outerCursor != &ss->ssl3.hs.echOuterExtensions);
+ if (!outerFound) {
+ SSL_TRC(10, ("%d: SSL3[%d]: ECH Outer Extensions has missing,"
+ " out of order or duplicate references.",
+ SSL_GETPID(), ss->fd));
+ error = SSL_ERROR_RX_MALFORMED_ECH_EXTENSION;
+ errDesc = illegal_parameter;
+ goto alert_loser;
+ }
+ }
+ }
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.echOuterExtensions);
+ ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions);
+
+ /* Correct the message and extensions sizes. */
+ rv = sslBuffer_InsertNumber(&unencodedChInner, xtnsOffset,
+ unencodedChInner.len - xtnsOffset - 2, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ tmpB = &unencodedChInner.buf[xtnsOffset];
+ tmpLength = unencodedChInner.len - xtnsOffset;
+ rv = ssl3_ConsumeHandshakeNumber64(ss, &tmp, 2, &tmpB, &tmpLength);
+ if (rv != SECSuccess || tmpLength != tmp) {
+ error = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
+ errDesc = internal_error;
+ goto alert_loser;
+ }
+
+ rv = ssl3_ParseExtensions(ss, &tmpB, &tmpLength);
+ if (rv != SECSuccess) {
+ goto loser; /* Error set and alert already sent */
+ }
+
+ SECITEM_FreeItem(*echInner, PR_FALSE);
+ (*echInner)->data = unencodedChInner.buf;
+ (*echInner)->len = unencodedChInner.len;
+ return SECSuccess;
+alert_loser:
+ FATAL_ERROR(ss, error, errDesc);
+loser:
+ sslBuffer_Clear(&unencodedChInner);
+ return SECFailure;
+}
+
+SECStatus
+tls13_MaybeAcceptEch(sslSocket *ss, const SECItem *sidBytes, const PRUint8 *chOuter,
+ unsigned int chOuterLen, SECItem **chInner)
+{
+ SECStatus rv;
+ SECItem outer = { siBuffer, CONST_CAST(PRUint8, chOuter), chOuterLen };
+ SECItem *decryptedChInner = NULL;
+ SECItem outerAAD = { siBuffer, NULL, 0 };
+ SECItem cookieData = { siBuffer, NULL, 0 };
+ sslEchCookieData echData;
+ sslEchConfig *candidate = NULL; /* non-owning */
+ TLSExtension *hrrXtn;
+ PRBool previouslyOfferedEch;
+
+ if (!ss->xtnData.ech || ss->xtnData.ech->receivedInnerXtn) {
+ ss->ssl3.hs.echDecided = PR_TRUE;
+ return SECSuccess;
+ }
+
+ PORT_Assert(ss->xtnData.ech->innerCh.data);
+
+ if (ss->ssl3.hs.helloRetry) {
+ ss->ssl3.hs.echDecided = PR_TRUE;
+ PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
+ hrrXtn = ssl3_FindExtension(ss, ssl_tls13_cookie_xtn);
+ if (!hrrXtn) {
+ /* If the client doesn't echo cookie, we can't decrypt. */
+ return SECSuccess;
+ }
+
+ PORT_Assert(!ss->ssl3.hs.echHpkeCtx);
+
+ PRUint8 *tmp = hrrXtn->data.data;
+ PRUint32 len = hrrXtn->data.len;
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &cookieData, 2,
+ &tmp, &len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Extract ECH info without restoring hash state. If there's
+ * something wrong with the cookie, continue without ECH
+ * and let HRR code handle the problem. */
+ rv = tls13_HandleHrrCookie(ss, cookieData.data, cookieData.len,
+ NULL, NULL, &previouslyOfferedEch, &echData, PR_FALSE);
+ if (rv != SECSuccess) {
+ return SECSuccess;
+ }
+
+ ss->ssl3.hs.echHpkeCtx = echData.hpkeCtx;
+
+ const PRUint8 greaseConstant[TLS13_ECH_SIGNAL_LEN] = { 0 };
+ ss->ssl3.hs.echAccepted = previouslyOfferedEch &&
+ !NSS_SecureMemcmp(greaseConstant, echData.signal, TLS13_ECH_SIGNAL_LEN);
+
+ if (echData.configId != ss->xtnData.ech->configId ||
+ echData.kdfId != ss->xtnData.ech->kdfId ||
+ echData.aeadId != ss->xtnData.ech->aeadId) {
+ FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO,
+ illegal_parameter);
+ return SECFailure;
+ }
+
+ if (!ss->ssl3.hs.echHpkeCtx) {
+ return SECSuccess;
+ }
+ }
+
+ if (ss->ssl3.hs.echDecided && !ss->ssl3.hs.echAccepted) {
+ /* We don't change our mind */
+ return SECSuccess;
+ }
+ /* Regardless of where we return, the outcome is decided */
+ ss->ssl3.hs.echDecided = PR_TRUE;
+
+ /* Cookie data was good, proceed with ECH. */
+ rv = tls13_GetMatchingEchConfigs(ss, ss->xtnData.ech->kdfId, ss->xtnData.ech->aeadId,
+ ss->xtnData.ech->configId, candidate, &candidate);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ return SECFailure;
+ }
+
+ if (candidate) {
+ rv = tls13_ServerMakeChOuterAAD(ss, chOuter, chOuterLen, &outerAAD);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ while (candidate) {
+ rv = tls13_OpenClientHelloInner(ss, &outer, &outerAAD, candidate, &decryptedChInner);
+ if (rv != SECSuccess) {
+ /* Get the next matching config */
+ rv = tls13_GetMatchingEchConfigs(ss, ss->xtnData.ech->kdfId, ss->xtnData.ech->aeadId,
+ ss->xtnData.ech->configId, candidate, &candidate);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error);
+ SECITEM_FreeItem(&outerAAD, PR_FALSE);
+ return SECFailure;
+ }
+ continue;
+ }
+ break;
+ }
+ SECITEM_FreeItem(&outerAAD, PR_FALSE);
+
+ if (rv != SECSuccess || !decryptedChInner) {
+ if (ss->ssl3.hs.helloRetry) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_ECH_EXTENSION, decrypt_error);
+ return SECFailure;
+ } else {
+ /* Send retry_configs (if we have any) when we fail to decrypt or
+ * found no candidates. This does *not* count as negotiating ECH. */
+ return ssl3_RegisterExtensionSender(ss, &ss->xtnData,
+ ssl_tls13_encrypted_client_hello_xtn,
+ tls13_ServerSendEchXtn);
+ }
+ }
+
+ SSL_TRC(20, ("%d: TLS13[%d]: Successfully opened ECH inner CH",
+ SSL_GETPID(), ss->fd));
+ PRINT_BUF(50, (ss, "Compressed CHInner", decryptedChInner->data,
+ decryptedChInner->len));
+
+ ss->ssl3.hs.echAccepted = PR_TRUE;
+
+ /* Stash the CHOuter extensions. They're not yet handled (only parsed). If
+ * the CHInner contains outer_extensions_xtn, we'll need to reference them. */
+ ssl3_MoveRemoteExtensions(&ss->ssl3.hs.echOuterExtensions, &ss->ssl3.hs.remoteExtensions);
+
+ rv = tls13_UnencodeChInner(ss, sidBytes, &decryptedChInner);
+ if (rv != SECSuccess) {
+ SECITEM_FreeItem(decryptedChInner, PR_TRUE);
+ return SECFailure; /* code set */
+ }
+ PRINT_BUF(50, (ss, "Uncompressed CHInner", decryptedChInner->data,
+ decryptedChInner->len));
+ *chInner = decryptedChInner;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_WriteServerEchSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen)
+{
+ SECStatus rv;
+ PRUint8 signal[TLS13_ECH_SIGNAL_LEN];
+ PRUint8 *msg_random = &sh[sizeof(SSL3ProtocolVersion)];
+
+ PORT_Assert(shLen > sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH);
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ rv = tls13_ComputeEchSignal(ss, PR_FALSE, sh, shLen, signal);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PRUint8 *dest = &msg_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
+ PORT_Memcpy(dest, signal, TLS13_ECH_SIGNAL_LEN);
+
+ /* Keep the socket copy consistent. */
+ PORT_Assert(0 == memcmp(msg_random, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN));
+ dest = &ss->ssl3.hs.server_random[SSL3_RANDOM_LENGTH - TLS13_ECH_SIGNAL_LEN];
+ PORT_Memcpy(dest, signal, TLS13_ECH_SIGNAL_LEN);
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_WriteServerEchHrrSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen)
+{
+ SECStatus rv;
+ PR_ASSERT(shLen >= 4 + TLS13_ECH_SIGNAL_LEN);
+ /* We put the HRR ECH extension last. */
+ PRUint8 *placeholder_location = sh + shLen - TLS13_ECH_SIGNAL_LEN;
+ /* Defensive check that we are overwriting the contents of the right extension */
+ PR_ASSERT(tls13_Debug_CheckXtnBegins(placeholder_location - 4, ssl_tls13_encrypted_client_hello_xtn));
+ /* Calculate signal and overwrite */
+ rv = tls13_ComputeEchSignal(ss, PR_TRUE, sh, shLen, placeholder_location);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* Free HRR GREASE/accept_confirmation value, it MUST be restored from
+ * cookie when handling CH2 after HRR. */
+ sslBuffer_Clear(&ss->ssl3.hs.greaseEchBuf);
+ return SECSuccess;
+} \ No newline at end of file
diff --git a/security/nss/lib/ssl/tls13ech.h b/security/nss/lib/ssl/tls13ech.h
new file mode 100644
index 0000000000..90b674e40d
--- /dev/null
+++ b/security/nss/lib/ssl/tls13ech.h
@@ -0,0 +1,125 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13ech_h_
+#define __tls13ech_h_
+
+#include "pk11hpke.h"
+
+/* draft-09, supporting shared-mode and split-mode as a backend server only.
+ * Notes on the implementation status:
+ * - Padding (https://tools.ietf.org/html/draft-ietf-tls-esni-08#section-6.2),
+ * is not implemented (see bug 1677181).
+ * - When multiple ECHConfigs are provided by the server, the first compatible
+ * config is selected by the client. Ciphersuite choices are limited and only
+ * the AEAD may vary (AES-128-GCM or ChaCha20Poly1305).
+ * - Some of the buffering (construction/compression/decompression) could likely
+ * be optimized, but the spec is still evolving so that work is deferred.
+ */
+#define TLS13_ECH_VERSION 0xfe0d
+#define TLS13_ECH_SIGNAL_LEN 8
+#define TLS13_ECH_AEAD_TAG_LEN 16
+
+static const char kHpkeInfoEch[] = "tls ech";
+static const char hHkdfInfoEchConfigID[] = "tls ech config id";
+static const char kHkdfInfoEchConfirm[] = "ech accept confirmation";
+static const char kHkdfInfoEchHrrConfirm[] = "hrr ech accept confirmation";
+
+typedef enum {
+ ech_xtn_type_outer = 0,
+ ech_xtn_type_inner = 1,
+} EchXtnType;
+
+struct sslEchConfigContentsStr {
+ PRUint8 configId;
+ HpkeKemId kemId;
+ SECItem publicKey; /* NULL on server. Use the keypair in sslEchConfig instead. */
+ HpkeKdfId kdfId;
+ HpkeAeadId aeadId;
+ SECItem suites; /* One or more HpkeCipherSuites. The selected s
+ * suite is placed in kdfId and aeadId. */
+ PRUint8 maxNameLen;
+ char *publicName;
+ /* No supported extensions. */
+};
+
+/* ECH Information needed by a server to process a second CH after a
+ * HelloRetryRequest is sent. This data is stored in the cookie.
+ */
+struct sslEchCookieDataStr {
+ PRBool previouslyOffered;
+ PRUint8 configId;
+ HpkeKdfId kdfId;
+ HpkeAeadId aeadId;
+ HpkeContext *hpkeCtx;
+ PRUint8 signal[TLS13_ECH_SIGNAL_LEN];
+};
+
+struct sslEchConfigStr {
+ PRCList link;
+ SECItem raw;
+ PRUint16 version;
+ sslEchConfigContents contents;
+};
+
+struct sslEchXtnStateStr {
+ SECItem innerCh; /* Server: ClientECH.payload */
+ SECItem senderPubKey; /* Server: ClientECH.enc */
+ PRUint8 configId; /* Server: ClientECH.config_id */
+ HpkeKdfId kdfId; /* Server: ClientECH.cipher_suite.kdf */
+ HpkeAeadId aeadId; /* Server: ClientECH.cipher_suite.aead */
+ SECItem retryConfigs; /* Client: ServerECH.retry_configs*/
+ PRBool retryConfigsValid; /* Client: Extraction of retry_configss is allowed.
+ * This is set once the handshake completes (having
+ * verified to the ECHConfig public name). */
+ PRUint8 *hrrConfirmation; /* Client/Server: HRR Confirmation Location */
+ PRBool receivedInnerXtn; /* Server: Handled ECH Xtn with Inner Enum */
+ PRUint8 *payloadStart; /* Server: Start of ECH Payload*/
+};
+
+SEC_BEGIN_PROTOS
+
+SECStatus SSLExp_EncodeEchConfigId(PRUint8 configId, const char *publicName, unsigned int maxNameLen,
+ HpkeKemId kemId, const SECKEYPublicKey *pubKey,
+ const HpkeSymmetricSuite *hpkeSuites, unsigned int hpkeSuiteCount,
+ PRUint8 *out, unsigned int *outlen, unsigned int maxlen);
+SECStatus SSLExp_GetEchRetryConfigs(PRFileDesc *fd, SECItem *retryConfigs);
+SECStatus SSLExp_SetClientEchConfigs(PRFileDesc *fd, const PRUint8 *echConfigs,
+ unsigned int echConfigsLen);
+SECStatus SSLExp_SetServerEchConfigs(PRFileDesc *fd,
+ const SECKEYPublicKey *pubKey, const SECKEYPrivateKey *privKey,
+ const PRUint8 *echConfigs, unsigned int numEchConfigs);
+SECStatus SSLExp_RemoveEchConfigs(PRFileDesc *fd);
+
+SEC_END_PROTOS
+
+SECStatus tls13_ClientSetupEch(sslSocket *ss, sslClientHelloType type);
+SECStatus tls13_ConstructClientHelloWithEch(sslSocket *ss, const sslSessionID *sid,
+ PRBool freshSid, sslBuffer *chOuterBuf,
+ sslBuffer *chInnerXtnsBuf);
+SECStatus tls13_CopyEchConfigs(PRCList *oconfigs, PRCList *configs);
+SECStatus tls13_DecodeEchConfigs(const SECItem *data, PRCList *configs);
+void tls13_DestroyEchConfigs(PRCList *list);
+void tls13_DestroyEchXtnState(sslEchXtnState *state);
+SECStatus tls13_GetMatchingEchConfig(const sslSocket *ss, HpkeKdfId kdf, HpkeAeadId aead,
+ const SECItem *configId, sslEchConfig **cfg);
+SECStatus tls13_MaybeHandleEch(sslSocket *ss, const PRUint8 *msg, PRUint32 msgLen, SECItem *sidBytes,
+ SECItem *comps, SECItem *cookieBytes, SECItem *suites, SECItem **echInner);
+SECStatus tls13_MaybeHandleEchSignal(sslSocket *ss, const PRUint8 *savedMsg, PRUint32 savedLength, PRBool isHrr);
+SECStatus tls13_MaybeAcceptEch(sslSocket *ss, const SECItem *sidBytes, const PRUint8 *chOuter,
+ unsigned int chOuterLen, SECItem **chInner);
+SECStatus tls13_MaybeGreaseEch(sslSocket *ss, const sslBuffer *preamble, sslBuffer *buf);
+SECStatus tls13_WriteServerEchSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen);
+SECStatus tls13_WriteServerEchHrrSignal(sslSocket *ss, PRUint8 *sh, unsigned int shLen);
+SECStatus tls13_DeriveEchSecret(const sslSocket *ss, PK11SymKey **output);
+SECStatus tls13_ComputeEchSignal(sslSocket *ss, PRBool isHrr, const PRUint8 *sh, unsigned int shLen, PRUint8 *out);
+
+PRBool tls13_IsIp(const PRUint8 *str, unsigned int len);
+PRBool tls13_IsLDH(const PRUint8 *str, unsigned int len);
+
+#endif
diff --git a/security/nss/lib/ssl/tls13echv.c b/security/nss/lib/ssl/tls13echv.c
new file mode 100644
index 0000000000..ae9792a910
--- /dev/null
+++ b/security/nss/lib/ssl/tls13echv.c
@@ -0,0 +1,167 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Validation functions for ECH public names. */
+
+#include "seccomon.h"
+
+/* Convert a single character `c` into a number `*d` with the given radix.
+ * Fails if the character isn't valid for the radix.
+ */
+static SECStatus
+tls13_IpDigit(PRUint8 c, PRUint8 radix, PRUint8 *d)
+{
+ PRUint8 v = 0xff;
+ if (c >= '0' && c <= '9') {
+ v = c - '0';
+ } else if (radix > 10) {
+ if (c >= 'a' && c <= 'f') {
+ v = c - 'a';
+ } else if (c >= 'A' && c <= 'F') {
+ v = c - 'A';
+ }
+ }
+ if (v >= radix) {
+ return SECFailure;
+ }
+ *d = v;
+ return SECSuccess;
+}
+
+/* This function takes the first couple of characters from `str`, starting at offset
+ * `*i` and calculates a radix. If it starts with "0x" or "0X", then `*i` is moved up
+ * by two and `*radix` is set to 16 (hexadecimal). If it starts with "0", then `*i` is
+ * moved up by one and `*radix` is set to 8 (octal). Otherwise, `*i` is left alone and
+ * `*radix` is set to 10 (decimal).
+ * Fails if there are no characters remaining or the next character is '.', either at
+ * the start or after "0x".
+ */
+static SECStatus
+tls13_IpRadix(const PRUint8 *str, unsigned int len, unsigned int *i, PRUint8 *radix)
+{
+ if (*i == len || str[*i] == '.') {
+ return SECFailure;
+ }
+ if (str[*i] == '0') {
+ (*i)++;
+ if (*i < len && (str[*i] == 'x' || str[*i] == 'X')) {
+ (*i)++;
+ if (*i == len || str[*i] == '.') {
+ return SECFailure;
+ }
+ *radix = 16;
+ } else {
+ *radix = 8;
+ }
+ } else {
+ *radix = 10;
+ }
+ return SECSuccess;
+}
+
+/* Take a number from `str` from offset `*i` and put the value in `*v`.
+ * This calculates the radix and returns a value between 0 and 2^32-1, using all
+ * of the digits up to the end of the string (determined by `len`) or a period ('.').
+ * Fails if there is no value, if there a non-digit characters, or if the value is
+ * too large.
+ */
+static SECStatus
+tls13_IpValue(const PRUint8 *str, unsigned int len, unsigned int *i, PRUint32 *v)
+{
+ PRUint8 radix;
+ SECStatus rv = tls13_IpRadix(str, len, i, &radix);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ PRUint64 part = 0;
+ while (*i < len) {
+ PRUint8 d;
+ rv = tls13_IpDigit(str[*i], radix, &d);
+ if (rv != SECSuccess) {
+ if (str[*i] != '.') {
+ return SECFailure;
+ }
+ break;
+ }
+ part = part * radix + d;
+ if (part > PR_UINT32_MAX) {
+ return SECFailure;
+ }
+ (*i)++;
+ }
+ *v = part;
+ return SECSuccess;
+}
+
+/* Returns true if `end` is true and `v` is within the `limit`. Used to validate the
+ * last part of an IPv4 address, which can hold larger numbers if there are fewer then
+ * four parts. */
+static PRBool
+tls13_IpLastPart(PRBool end, PRUint32 v, PRUint32 limit)
+{
+ if (!end) {
+ return PR_FALSE;
+ }
+ return v <= limit;
+}
+
+/* Returns true if `str` contains an IPv4 address. */
+PRBool
+tls13_IsIp(const PRUint8 *str, unsigned int len)
+{
+ PRUint32 part;
+ PRUint32 v;
+ unsigned int i = 0;
+ for (part = 0; part < 4; part++) {
+ SECStatus rv = tls13_IpValue(str, len, &i, &v);
+ if (rv != SECSuccess) {
+ return PR_FALSE;
+ }
+ if (v > 0xff || i == len) {
+ return tls13_IpLastPart(i == len, v, PR_UINT32_MAX >> (part * 8));
+ }
+ PORT_Assert(str[i] == '.');
+ i++;
+ }
+
+ return tls13_IpLastPart(i == len, v, 0xff);
+}
+
+static PRBool
+tls13_IsLD(PRUint8 c)
+{
+ return (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') ||
+ c == '_'; /* not in spec, but in the world; bug 1136616 */
+}
+
+/* Is this a valid dotted LDH string (that is, an A-Label domain name)?
+ * This does not tolerate a trailing '.', where the DNS generally does.
+ */
+PRBool
+tls13_IsLDH(const PRUint8 *str, unsigned int len)
+{
+ unsigned int i = 0;
+ while (i < len && tls13_IsLD(str[i])) {
+ unsigned int labelEnd = PR_MIN(len, i + 63);
+ i++;
+ while (i < labelEnd && (tls13_IsLD(str[i]) || str[i] == '-')) {
+ i++;
+ }
+ if (str[i - 1] == '-') {
+ /* labels cannot end in a hyphen */
+ return PR_FALSE;
+ }
+ if (i == len) {
+ return PR_TRUE;
+ }
+ if (str[i] != '.') {
+ return PR_FALSE;
+ }
+ i++;
+ }
+ return PR_FALSE;
+}
diff --git a/security/nss/lib/ssl/tls13err.h b/security/nss/lib/ssl/tls13err.h
new file mode 100644
index 0000000000..8cdeb12eb2
--- /dev/null
+++ b/security/nss/lib/ssl/tls13err.h
@@ -0,0 +1,28 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13err_h_
+#define __tls13err_h_
+
+/* Use this instead of FATAL_ERROR when an alert isn't possible. */
+#define LOG_ERROR(ss, prError) \
+ do { \
+ SSL_TRC(3, ("%d: TLS13[%d]: fatal error %d in %s (%s:%d)", \
+ SSL_GETPID(), ss->fd, prError, __func__, __FILE__, __LINE__)); \
+ PORT_SetError(prError); \
+ } while (0)
+
+/* Log an error and generate an alert because something is irreparably wrong. */
+#define FATAL_ERROR(ss, prError, desc) \
+ do { \
+ LOG_ERROR(ss, prError); \
+ tls13_FatalError(ss, prError, desc); \
+ } while (0)
+
+void tls13_FatalError(sslSocket *ss, PRErrorCode prError, SSL3AlertDescription desc);
+#endif
diff --git a/security/nss/lib/ssl/tls13exthandle.c b/security/nss/lib/ssl/tls13exthandle.c
new file mode 100644
index 0000000000..4d8c711bd5
--- /dev/null
+++ b/security/nss/lib/ssl/tls13exthandle.c
@@ -0,0 +1,1802 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nssrenam.h"
+#include "nss.h"
+#include "ssl.h"
+#include "sslproto.h"
+#include "sslimpl.h"
+#include "pk11pub.h"
+#include "ssl3ext.h"
+#include "ssl3exthandle.h"
+#include "tls13ech.h"
+#include "tls13exthandle.h"
+#include "tls13psk.h"
+#include "tls13subcerts.h"
+
+SECStatus
+tls13_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ const sslServerCert *serverCert = ss->sec.serverCert;
+ const SECItem *item;
+ SECStatus rv;
+
+ if (!serverCert->certStatusArray ||
+ !serverCert->certStatusArray->len) {
+ return SECSuccess;
+ }
+
+ item = &serverCert->certStatusArray->items[0];
+
+ /* Only send the first entry. */
+ /* status_type == ocsp */
+ rv = sslBuffer_AppendNumber(buf, 1 /*ocsp*/, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* opaque OCSPResponse<1..2^24-1> */
+ rv = sslBuffer_AppendVariable(buf, item->data, item->len, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/*
+ * [draft-ietf-tls-tls13-11] Section 6.3.2.3.
+ *
+ * struct {
+ * NamedGroup group;
+ * opaque key_exchange<1..2^16-1>;
+ * } KeyShareEntry;
+ *
+ * struct {
+ * select (role) {
+ * case client:
+ * KeyShareEntry client_shares<4..2^16-1>;
+ *
+ * case server:
+ * KeyShareEntry server_share;
+ * }
+ * } KeyShare;
+ *
+ * DH is Section 6.3.2.3.1.
+ *
+ * opaque dh_Y<1..2^16-1>;
+ *
+ * ECDH is Section 6.3.2.3.2.
+ *
+ * opaque point <1..2^8-1>;
+ */
+PRUint32
+tls13_SizeOfKeyShareEntry(const SECKEYPublicKey *pubKey)
+{
+ /* Size = NamedGroup(2) + length(2) + opaque<?> share */
+ switch (pubKey->keyType) {
+ case ecKey:
+ return 2 + 2 + pubKey->u.ec.publicValue.len;
+ case dhKey:
+ return 2 + 2 + pubKey->u.dh.prime.len;
+ default:
+ PORT_Assert(0);
+ }
+ return 0;
+}
+
+SECStatus
+tls13_EncodeKeyShareEntry(sslBuffer *buf, SSLNamedGroup group,
+ SECKEYPublicKey *pubKey)
+{
+ SECStatus rv;
+ unsigned int size = tls13_SizeOfKeyShareEntry(pubKey);
+
+ rv = sslBuffer_AppendNumber(buf, group, 2);
+ if (rv != SECSuccess)
+ return rv;
+ rv = sslBuffer_AppendNumber(buf, size - 4, 2);
+ if (rv != SECSuccess)
+ return rv;
+
+ switch (pubKey->keyType) {
+ case ecKey:
+ rv = sslBuffer_Append(buf, pubKey->u.ec.publicValue.data,
+ pubKey->u.ec.publicValue.len);
+ break;
+ case dhKey:
+ rv = ssl_AppendPaddedDHKeyShare(buf, pubKey, PR_FALSE);
+ break;
+ default:
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ break;
+ }
+
+ return rv;
+}
+
+SECStatus
+tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+ PRCList *cursor;
+ unsigned int lengthOffset;
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ /* Optimistically try to send an ECDHE key using the
+ * preexisting key (in future will be keys) */
+ SSL_TRC(3, ("%d: TLS13[%d]: send client key share xtn",
+ SSL_GETPID(), ss->fd));
+
+ /* Save the offset to the length. */
+ rv = sslBuffer_Skip(buf, 2, &lengthOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ for (cursor = PR_NEXT_LINK(&ss->ephemeralKeyPairs);
+ cursor != &ss->ephemeralKeyPairs;
+ cursor = PR_NEXT_LINK(cursor)) {
+ sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor;
+ rv = tls13_EncodeKeyShareEntry(buf,
+ keyPair->group->name,
+ keyPair->keys->pubKey);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ /* GREASE KeyShareEntry:
+ * [The client] MAY also send KeyShareEntry values for a subset of those
+ * selected in the "key_share" extension. For each of these, the
+ * "key_exchange" field MAY be any value [RFC8701, Section 3.1].
+ *
+ * By default we do not send KeyShares for every NamedGroup so the
+ * ServerKeyShare handshake message / additional round-trip is not
+ * triggered by sending GREASE KeyShareEntries. */
+ if (ss->opt.enableGrease) {
+ rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_group], 2);
+ if (rv != SECSuccess)
+ return rv;
+ /* Entry length */
+ rv = sslBuffer_AppendNumber(buf, 2, 2);
+ if (rv != SECSuccess)
+ return rv;
+ /* Entry value */
+ rv = sslBuffer_AppendNumber(buf, 0xCD, 2);
+ if (rv != SECSuccess)
+ return rv;
+ }
+
+ rv = sslBuffer_InsertLength(buf, lengthOffset, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_DecodeKeyShareEntry(sslReader *rdr, TLS13KeyShareEntry **ksp)
+{
+ SECStatus rv;
+ PRUint64 group;
+ const sslNamedGroupDef *groupDef;
+ TLS13KeyShareEntry *ks = NULL;
+ sslReadBuffer share;
+
+ rv = sslRead_ReadNumber(rdr, 2, &group);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ groupDef = ssl_LookupNamedGroup(group);
+ rv = sslRead_ReadVariable(rdr, 2, &share);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* This has to happen here because we want to consume
+ * the entire entry even if the group is unknown
+ * or disabled. */
+ /* If the group is disabled, continue. */
+ if (!groupDef) {
+ return SECSuccess;
+ }
+
+ ks = PORT_ZNew(TLS13KeyShareEntry);
+ if (!ks) {
+ goto loser;
+ }
+ ks->group = groupDef;
+
+ rv = SECITEM_MakeItem(NULL, &ks->key_exchange,
+ share.buf, share.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ *ksp = ks;
+ return SECSuccess;
+
+loser:
+ tls13_DestroyKeyShareEntry(ks);
+
+ return SECFailure;
+}
+/* Handle an incoming KeyShare extension at the client and copy to
+ * |xtnData->remoteKeyShares| for future use. The key
+ * share is processed in tls13_HandleServerKeyShare(). */
+SECStatus
+tls13_ClientHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares));
+ TLS13KeyShareEntry *ks = NULL;
+
+ PORT_Assert(!ss->sec.isServer);
+
+ /* The server must not send this extension when negotiating < TLS 1.3. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
+ return SECFailure;
+ }
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
+ SSL_GETPID(), ss->fd));
+
+ sslReader rdr = SSL_READER(data->data, data->len);
+ rv = tls13_DecodeKeyShareEntry(&rdr, &ks);
+ if ((rv != SECSuccess) || !ks) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
+ return SECFailure;
+ }
+
+ if (SSL_READER_REMAINING(&rdr)) {
+ tls13_DestroyKeyShareEntry(ks);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
+ return SECFailure;
+ }
+ PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares);
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PRUint32 tmp;
+ const sslNamedGroupDef *group;
+
+ PORT_Assert(!ss->sec.isServer);
+ PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension in HRR",
+ SSL_GETPID(), ss->fd));
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure; /* error code already set */
+ }
+ if (data->len) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
+ return SECFailure;
+ }
+
+ group = ssl_LookupNamedGroup((SSLNamedGroup)tmp);
+ /* If the group is not enabled, or we already have a share for the
+ * requested group, abort. */
+ if (!ssl_NamedGroupEnabled(ss, group) ||
+ ssl_HaveEphemeralKeyPair(ss, group)) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
+ return SECFailure;
+ }
+
+ /* Now delete all the key shares per [draft-ietf-tls-tls13 S 4.1.2] */
+ ssl_FreeEphemeralKeyPairs(CONST_CAST(sslSocket, ss));
+
+ /* And replace with our new share. */
+ rv = tls13_AddKeyShare(CONST_CAST(sslSocket, ss), group);
+ if (rv != SECSuccess) {
+ ssl3_ExtSendAlert(ss, alert_fatal, internal_error);
+ PORT_SetError(SEC_ERROR_KEYGEN_FAIL);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Handle an incoming KeyShare extension at the server and copy to
+ * |xtnData->remoteKeyShares| for future use. The key
+ * share is processed in tls13_HandleClientKeyShare(). */
+SECStatus
+tls13_ServerHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PRUint32 length;
+
+ PORT_Assert(ss->sec.isServer);
+ PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares));
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension",
+ SSL_GETPID(), ss->fd));
+
+ /* Redundant length because of TLS encoding (this vector consumes
+ * the entire extension.) */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &length, 2, &data->data,
+ &data->len);
+ if (rv != SECSuccess)
+ goto loser;
+ if (length != data->len) {
+ /* Check for consistency */
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
+ goto loser;
+ }
+
+ sslReader rdr = SSL_READER(data->data, data->len);
+ while (SSL_READER_REMAINING(&rdr)) {
+ TLS13KeyShareEntry *ks = NULL;
+ rv = tls13_DecodeKeyShareEntry(&rdr, &ks);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE);
+ goto loser;
+ }
+ if (ks) {
+ /* |ks| == NULL if this is an unknown group. */
+ PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares);
+ }
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] =
+ ssl_tls13_key_share_xtn;
+
+ return SECSuccess;
+
+loser:
+ tls13_DestroyKeyShares(&xtnData->remoteKeyShares);
+ return SECFailure;
+}
+
+SECStatus
+tls13_ServerSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+ sslEphemeralKeyPair *keyPair;
+
+ /* There should be exactly one key share. */
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs));
+ PORT_Assert(PR_PREV_LINK(&ss->ephemeralKeyPairs) ==
+ PR_NEXT_LINK(&ss->ephemeralKeyPairs));
+
+ keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs);
+
+ rv = tls13_EncodeKeyShareEntry(buf, keyPair->group->name,
+ keyPair->keys->pubKey);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* Called by clients.
+ *
+ * struct {
+ * opaque identity<0..2^16-1>;
+ * uint32 obfuscated_ticket_age;
+ * } PskIdentity;
+ *
+ * opaque PskBinderEntry<32..255>;
+ *
+ * struct {
+ * select (Handshake.msg_type) {
+ * case client_hello:
+ * PskIdentity identities<6..2^16-1>;
+ * PskBinderEntry binders<33..2^16-1>;
+ *
+ * case server_hello:
+ * uint16 selected_identity;
+ * };
+ *
+ * } PreSharedKeyExtension;
+ */
+SECStatus
+tls13_ClientSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ const static PRUint8 binder[TLS13_MAX_FINISHED_SIZE] = { 0 };
+ unsigned int binderLen;
+ unsigned int identityLen = 0;
+ const PRUint8 *identity = NULL;
+ PRTime age;
+ SECStatus rv;
+
+ /* Exit early if no PSKs or max version < 1.3. */
+ if (PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks) ||
+ ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ /* ...or if PSK type is resumption, but we're not resuming. */
+ sslPsk *psk = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+ if (psk->type == ssl_psk_resume && !ss->statelessResume) {
+ return SECSuccess;
+ }
+
+ /* ...or if PSKs are incompatible with negotiated ciphersuites
+ * (different hash algorithms) on HRR.
+ *
+ * In addition, in its updated ClientHello, the client SHOULD NOT offer any
+ * pre-shared keys associated with a hash other than that of the selected
+ * cipher suite. This allows the client to avoid having to compute partial
+ * hash transcripts for multiple hashes in the second ClientHello
+ * [RFC8446, Section 4.1.4]. */
+ if (ss->ssl3.hs.helloRetry &&
+ (psk->hash != ss->ssl3.hs.suite_def->prf_hash)) {
+ return SECSuccess;
+ }
+
+ /* Save where this extension starts so that if we have to add padding, it
+ * can be inserted before this extension. */
+ PORT_Assert(buf->len >= 4);
+ xtnData->lastXtnOffset = buf->len - 4;
+ PORT_Assert(psk->type == ssl_psk_resume || psk->type == ssl_psk_external);
+ binderLen = tls13_GetHashSizeForHash(psk->hash);
+ if (psk->type == ssl_psk_resume) {
+ /* Send a single ticket identity. */
+ NewSessionTicket *session_ticket = &ss->sec.ci.sid->u.ssl3.locked.sessionTicket;
+ identityLen = session_ticket->ticket.len;
+ identity = session_ticket->ticket.data;
+
+ /* Obfuscated age. */
+ age = ssl_Time(ss) - session_ticket->received_timestamp;
+ age /= PR_USEC_PER_MSEC;
+ age += session_ticket->ticket_age_add;
+ PRINT_BUF(50, (ss, "Sending Resumption PSK with identity", identity, identityLen));
+ } else if (psk->type == ssl_psk_external) {
+ identityLen = psk->label.len;
+ identity = psk->label.data;
+ age = 0;
+ PRINT_BUF(50, (ss, "Sending External PSK with label", identity, identityLen));
+ } else {
+ PORT_Assert(0);
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ /* Length is len(identityLen) + identityLen + len(age) */
+ rv = sslBuffer_AppendNumber(buf, 2 + identityLen + 4, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendVariable(buf, identity,
+ identityLen, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ rv = sslBuffer_AppendNumber(buf, age, 4);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Write out the binder list length. */
+ rv = sslBuffer_AppendNumber(buf, binderLen + 1, 2);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Write zeroes for the binder for the moment. These
+ * are overwritten in tls13_WriteExtensionsWithBinder. */
+ rv = sslBuffer_AppendVariable(buf, binder, binderLen, 1);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (psk->type == ssl_psk_resume) {
+ xtnData->sentSessionTicketInClientHello = PR_TRUE;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+
+loser:
+ xtnData->ticketTimestampVerified = PR_FALSE;
+ return SECFailure;
+}
+
+/* Handle a TLS 1.3 PreSharedKey Extension. */
+SECStatus
+tls13_ServerHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECItem inner;
+ SECStatus rv;
+ unsigned int numIdentities = 0;
+ unsigned int numBinders = 0;
+ SECItem *appToken;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle pre_shared_key extension",
+ SSL_GETPID(), ss->fd));
+
+ /* If we are doing < TLS 1.3, then ignore this. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ /* The application token is set via the cookie extension if this is the
+ * second ClientHello. Don't set it twice. The cookie extension handler
+ * sets |helloRetry| and that will have been called already because this
+ * extension always comes last. */
+ if (!ss->ssl3.hs.helloRetry) {
+ appToken = &xtnData->applicationToken;
+ } else {
+ appToken = NULL;
+ }
+
+ /* Parse the identities list. */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &inner, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ while (inner.len) {
+ SECItem label;
+ PRUint32 obfuscatedAge;
+
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &label, 2,
+ &inner.data, &inner.len);
+ if (rv != SECSuccess)
+ return rv;
+ if (!label.len) {
+ goto alert_loser;
+ }
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &obfuscatedAge, 4,
+ &inner.data, &inner.len);
+ if (rv != SECSuccess)
+ return rv;
+
+ if (!numIdentities) {
+ /* Check any configured external PSK for a matching label.
+ * If none exists, try to parse it as a ticket. */
+ PORT_Assert(!xtnData->selectedPsk);
+ for (PRCList *cur_p = PR_LIST_HEAD(&ss->ssl3.hs.psks);
+ cur_p != &ss->ssl3.hs.psks;
+ cur_p = PR_NEXT_LINK(cur_p)) {
+ sslPsk *psk = (sslPsk *)cur_p;
+ if (psk->type != ssl_psk_external ||
+ SECITEM_CompareItem(&psk->label, &label) != SECEqual) {
+ continue;
+ }
+ PRINT_BUF(50, (ss, "Using External PSK with label",
+ psk->label.data, psk->label.len));
+ xtnData->selectedPsk = psk;
+ }
+
+ if (!xtnData->selectedPsk) {
+ PRINT_BUF(50, (ss, "Handling PreSharedKey value",
+ label.data, label.len));
+ rv = ssl3_ProcessSessionTicketCommon(
+ CONST_CAST(sslSocket, ss), &label, appToken);
+ /* This only happens if we have an internal error, not
+ * a malformed ticket. Bogus tickets just don't resume
+ * and return SECSuccess. */
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->sec.ci.sid) {
+ /* xtnData->ticketAge contains the baseline we use for
+ * calculating the ticket age (i.e., our RTT estimate less the
+ * value of ticket_age_add).
+ *
+ * Add that to the obfuscated ticket age to recover the client's
+ * view of the ticket age plus the estimated RTT.
+ *
+ * See ssl3_EncodeSessionTicket() for details. */
+ xtnData->ticketAge += obfuscatedAge;
+
+ /* We are not committed to resumption until after unwrapping the
+ * RMS in tls13_HandleClientHelloPart2. The RPSK will be stored
+ * in ss->xtnData.selectedPsk at that point, so continue. */
+ }
+ }
+ }
+
+ ++numIdentities;
+ }
+
+ xtnData->pskBindersLen = data->len;
+
+ /* Parse the binders list. */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss,
+ &inner, 2, &data->data, &data->len);
+ if (rv != SECSuccess)
+ return SECFailure;
+ if (data->len) {
+ goto alert_loser;
+ }
+
+ while (inner.len) {
+ SECItem binder;
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &binder, 1,
+ &inner.data, &inner.len);
+ if (rv != SECSuccess)
+ return rv;
+ if (binder.len < 32) {
+ goto alert_loser;
+ }
+
+ if (!numBinders) {
+ xtnData->pskBinder = binder;
+ }
+ ++numBinders;
+ }
+
+ if (numBinders != numIdentities)
+ goto alert_loser;
+
+ if (ss->statelessResume) {
+ PORT_Assert(!ss->xtnData.selectedPsk);
+ } else if (!xtnData->selectedPsk) {
+ /* No matching EPSK. */
+ return SECSuccess;
+ }
+
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_pre_shared_key_xtn;
+ return SECSuccess;
+
+alert_loser:
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
+ return SECFailure;
+}
+
+SECStatus
+tls13_ServerSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ /* We only process the first session ticket the client sends,
+ * so the index is always 0. */
+ rv = sslBuffer_AppendNumber(buf, 0, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* Handle a TLS 1.3 PreSharedKey Extension. */
+SECStatus
+tls13_ClientHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PRUint32 index;
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: SSL3[%d]: handle pre_shared_key extension",
+ SSL_GETPID(), ss->fd));
+
+ /* The server must not send this extension when negotiating < TLS 1.3. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
+ return SECFailure;
+ }
+
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &index, 2, &data->data, &data->len);
+ if (rv != SECSuccess)
+ return SECFailure;
+
+ /* This should be the end of the extension. */
+ if (data->len) {
+ PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
+ return SECFailure;
+ }
+
+ /* We only sent one PSK label so index must be equal to 0 */
+ if (index) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY);
+ return SECFailure;
+ }
+
+ PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.psks));
+ sslPsk *candidate = (sslPsk *)PR_LIST_HEAD(&ss->ssl3.hs.psks);
+
+ /* Check that the server-selected ciphersuite hash and PSK hash match. */
+ if (candidate->hash != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_pre_shared_key_xtn;
+ xtnData->selectedPsk = candidate;
+
+ return SECSuccess;
+}
+
+/*
+ * struct { } EarlyDataIndication;
+ */
+SECStatus
+tls13_ClientSendEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ if (!tls13_ClientAllow0Rtt(ss, ss->sec.ci.sid)) {
+ return SECSuccess;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SSL_TRC(3, ("%d: TLS13[%d]: handle early_data extension",
+ SSL_GETPID(), ss->fd));
+
+ /* If we are doing < TLS 1.3, then ignore this. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ if (ss->ssl3.hs.helloRetry) {
+ ssl3_ExtSendAlert(ss, alert_fatal, unsupported_extension);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+
+ if (data->len) {
+ PORT_SetError(SSL_ERROR_MALFORMED_EARLY_DATA);
+ return SECFailure;
+ }
+
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_early_data_xtn;
+
+ return SECSuccess;
+}
+
+/* This will only be called if we also offered the extension. */
+SECStatus
+tls13_ClientHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SSL_TRC(3, ("%d: TLS13[%d]: handle early_data extension",
+ SSL_GETPID(), ss->fd));
+
+ /* The server must not send this extension when negotiating < TLS 1.3. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
+ return SECFailure;
+ }
+
+ if (data->len) {
+ PORT_SetError(SSL_ERROR_MALFORMED_EARLY_DATA);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_early_data_xtn;
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientHandleTicketEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PRUint32 utmp;
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle ticket early_data extension",
+ SSL_GETPID(), ss->fd));
+
+ /* The server must not send this extension when negotiating < TLS 1.3. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION);
+ return SECFailure;
+ }
+
+ rv = ssl3_ExtConsumeHandshake(ss, &utmp, sizeof(utmp),
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+ if (data->len) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
+ return SECFailure;
+ }
+
+ xtnData->max_early_data_size = PR_ntohl(utmp);
+
+ return SECSuccess;
+}
+
+/*
+ * struct {
+ * select (Handshake.msg_type) {
+ * case client_hello:
+ * ProtocolVersion versions<2..254>;
+ * case server_hello:
+ * ProtocolVersion version;
+ * };
+ * } SupportedVersions;
+ */
+SECStatus
+tls13_ClientSendSupportedVersionsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ PRUint16 version;
+ unsigned int lengthOffset;
+ SECStatus rv;
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: client send supported_versions extension",
+ SSL_GETPID(), ss->fd));
+
+ rv = sslBuffer_Skip(buf, 1, &lengthOffset);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ PORT_Assert(!ss->ssl3.hs.echHpkeCtx || ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
+ for (version = ss->vrange.max; version >= ss->vrange.min; --version) {
+ PRUint16 wire = tls13_EncodeVersion(version,
+ ss->protocolVariant);
+ rv = sslBuffer_AppendNumber(buf, wire, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->opt.enableDtls13VersionCompat &&
+ ss->protocolVariant == ssl_variant_datagram) {
+ switch (version) {
+ case SSL_LIBRARY_VERSION_TLS_1_2:
+ case SSL_LIBRARY_VERSION_TLS_1_1:
+ rv = sslBuffer_AppendNumber(buf, (PRUint16)version, 2);
+ break;
+ default:
+ continue;
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+ }
+
+ /* GREASE SupportedVersions:
+ * A client MAY select one or more GREASE version values and advertise them
+ * in the "supported_versions" extension, if sent [RFC8701, Section 3.1]. */
+ if (ss->opt.enableGrease) {
+ rv = sslBuffer_AppendNumber(buf, ss->ssl3.hs.grease->idx[grease_version], 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ rv = sslBuffer_InsertLength(buf, lengthOffset, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerSendSupportedVersionsXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: server send supported_versions extension",
+ SSL_GETPID(), ss->fd));
+
+ PRUint16 ver = tls13_EncodeVersion(SSL_LIBRARY_VERSION_TLS_1_3,
+ ss->protocolVariant);
+ rv = sslBuffer_AppendNumber(buf, ver, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/*
+ * struct {
+ * opaque cookie<1..2^16-1>;
+ * } Cookie;
+ */
+SECStatus
+tls13_ClientHandleHrrCookie(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle cookie extension",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ /* IMPORTANT: this is only valid while the HelloRetryRequest is still valid. */
+ rv = ssl3_ExtConsumeHandshakeVariable(
+ ss, &CONST_CAST(sslSocket, ss)->ssl3.hs.cookie, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
+ return SECFailure;
+ }
+ if (!ss->ssl3.hs.cookie.len || data->len) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
+ !ss->ssl3.hs.cookie.len) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send cookie extension", SSL_GETPID(), ss->fd));
+ rv = sslBuffer_AppendVariable(buf, ss->ssl3.hs.cookie.data,
+ ss->ssl3.hs.cookie.len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerHandleCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle cookie extension",
+ SSL_GETPID(), ss->fd));
+
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &xtnData->cookie, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (xtnData->cookie.len == 0) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ if (data->len) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_cookie_xtn;
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientSendPostHandshakeAuthXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ /* Only one post-handshake message is supported: a single
+ * NST immediately following the client Finished. */
+ if (!IS_DTLS(ss)) {
+ SSL_TRC(3, ("%d: TLS13[%d]: send post_handshake_auth extension",
+ SSL_GETPID(), ss->fd));
+ *added = ss->opt.enablePostHandshakeAuth;
+ }
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerHandlePostHandshakeAuthXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SSL_TRC(3, ("%d: TLS13[%d]: handle post_handshake_auth extension",
+ SSL_GETPID(), ss->fd));
+
+ if (data->len) {
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ /* Only one post-handshake message is supported: a single
+ * NST immediately following the client Finished. */
+ if (!IS_DTLS(ss)) {
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_post_handshake_auth_xtn;
+ }
+
+ return SECSuccess;
+}
+
+/*
+ * enum { psk_ke(0), psk_dhe_ke(1), (255) } PskKeyExchangeMode;
+ *
+ * struct {
+ * PskKeyExchangeMode ke_modes<1..255>;
+ * } PskKeyExchangeModes;
+ */
+SECStatus
+tls13_ClientSendPskModesXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
+ ss->opt.noCache) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: send psk key exchange modes extension",
+ SSL_GETPID(), ss->fd));
+
+ /* GREASE PskKeyExchangeMode:
+ * A client MAY select one or more GREASE PskKeyExchangeMode values and
+ * advertise them in the "psk_key_exchange_modes" extension, if sent
+ * [RFC8701, Section 3.1]. */
+ if (ss->opt.enableGrease) {
+ rv = sslBuffer_AppendVariable(buf, (PRUint8[]){ tls13_psk_dh_ke, ss->ssl3.hs.grease->pskKem }, 2, 1);
+ } else {
+ rv = sslBuffer_AppendVariable(buf, (PRUint8[]){ tls13_psk_dh_ke }, 1, 1);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerHandlePskModesXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+
+ /* If we are doing < TLS 1.3, then ignore this. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ return SECSuccess;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle PSK key exchange modes extension",
+ SSL_GETPID(), ss->fd));
+
+ /* IMPORTANT: We aren't copying these values, just setting pointers.
+ * They will only be valid as long as the ClientHello is in memory. */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss,
+ &xtnData->psk_ke_modes, 1,
+ &data->data, &data->len);
+ if (rv != SECSuccess)
+ return rv;
+ if (!xtnData->psk_ke_modes.len || data->len) {
+ PORT_SetError(SSL_ERROR_MALFORMED_PSK_KEY_EXCHANGE_MODES);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->negotiated[xtnData->numNegotiated++] =
+ ssl_tls13_psk_key_exchange_modes_xtn;
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_SendCertAuthoritiesXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ unsigned int calen;
+ const SECItem *name;
+ unsigned int nnames;
+ SECStatus rv;
+
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ rv = ssl_GetCertificateRequestCAs(ss, &calen, &name, &nnames);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (!calen) {
+ return SECSuccess;
+ }
+
+ rv = sslBuffer_AppendNumber(buf, calen, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ while (nnames) {
+ rv = sslBuffer_AppendVariable(buf, name->data, name->len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ ++name;
+ --nnames;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientHandleCertAuthoritiesXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PLArenaPool *arena;
+
+ if (!data->len) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
+ return SECFailure;
+ }
+
+ arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (!arena) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ xtnData->certReqAuthorities.arena = arena;
+ rv = ssl3_ParseCertificateRequestCAs((sslSocket *)ss,
+ &data->data, &data->len,
+ &xtnData->certReqAuthorities);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ if (data->len) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_REQUEST);
+ goto loser;
+ }
+ return SECSuccess;
+
+loser:
+ PORT_FreeArena(arena, PR_FALSE);
+ xtnData->certReqAuthorities.arena = NULL;
+ return SECFailure;
+}
+
+SECStatus
+tls13_ServerHandleCertAuthoritiesXtn(const sslSocket *ss, TLSExtensionData *xtnData, SECItem *data)
+{
+ SSL_TRC(3, ("%d: TLS13[%d]: ignore certificate_authorities extension",
+ SSL_GETPID(), ss->fd));
+ /* NSS ignores certificate_authorities in the ClientHello */
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerSendHrrKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+
+ if (!xtnData->selectedGroup) {
+ return SECSuccess;
+ }
+
+ rv = sslBuffer_AppendNumber(buf, xtnData->selectedGroup->name, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ PORT_Assert(xtnData->cookie.len > 0);
+
+ rv = sslBuffer_AppendVariable(buf,
+ xtnData->cookie.data, xtnData->cookie.len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientHandleHrrEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ if (data->len != TLS13_ECH_SIGNAL_LEN) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
+ return SECFailure;
+ }
+ if (!ssl3_ExtensionAdvertised(ss, ssl_tls13_encrypted_client_hello_xtn)) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+ if (!ss->ssl3.hs.echHpkeCtx) {
+ SSL_TRC(50, ("%d: TLS13[%d]: client received GREASEd ECH confirmation",
+ SSL_GETPID(), ss->fd));
+ return SECSuccess;
+ }
+ SSL_TRC(50, ("%d: TLS13[%d]: client received HRR ECH confirmation",
+ SSL_GETPID(), ss->fd));
+ PORT_Assert(!xtnData->ech);
+ xtnData->ech = PORT_ZNew(sslEchXtnState);
+ if (!xtnData->ech) {
+ return SECFailure;
+ }
+ xtnData->ech->hrrConfirmation = data->data;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ClientHandleEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ PRCList parsedConfigs;
+ PR_INIT_CLIST(&parsedConfigs);
+
+ /* The [retry config] response is valid only when the server used the
+ * ClientHelloOuter. If the server sent this extension in response to the
+ * inner variant [ECH was accepted], then the client MUST abort with an
+ * "unsupported_extension" alert [draft-ietf-tls-esni-14, Section 5]. */
+ if (ss->ssl3.hs.echAccepted) {
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ ssl3_ExtSendAlert(ss, alert_fatal, unsupported_extension);
+ return SECFailure;
+ }
+
+ /* If the server is configured with any ECHConfigs, it MUST include the
+ * "encrypted_client_hello" extension in its EncryptedExtensions with the
+ * "retry_configs" field set to one or more ECHConfig structures with
+ * up-to-date keys [draft-ietf-tls-esni-14, Section 7.1]. */
+ if (ss->ssl3.hs.msg_type != ssl_hs_encrypted_extensions) {
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ /* For TLS < 1.3 the extension is unkown/unsupported. */
+ ssl3_ExtSendAlert(ss, alert_fatal, unsupported_extension);
+ } else {
+ /* For TLS 1.3 the extension is known but prohibited outside EE
+ * (see RFC8446, Section 4.2 for alert rationale). */
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ }
+ return SECFailure;
+ }
+
+ PORT_Assert(!xtnData->ech);
+ xtnData->ech = PORT_ZNew(sslEchXtnState);
+ if (!xtnData->ech) {
+ return SECFailure;
+ }
+
+ /* Parse the list to determine 1) That the configs are valid
+ * and properly encoded, and 2) If any are compatible. */
+ rv = tls13_DecodeEchConfigs(data, &parsedConfigs);
+ if (rv == SECFailure) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_CONFIG);
+ return SECFailure;
+ }
+ /* Don't mark ECH negotiated on rejection with retry_config.
+ * Save the the raw configs so the application can retry. If
+ * we sent GREASE ECH (no echHpkeCtx), don't apply retry_configs. */
+ if (ss->ssl3.hs.echHpkeCtx && !PR_CLIST_IS_EMPTY(&parsedConfigs)) {
+ rv = SECITEM_CopyItem(NULL, &xtnData->ech->retryConfigs, data);
+ }
+ tls13_DestroyEchConfigs(&parsedConfigs);
+
+ return rv;
+}
+
+/* Indicates support for the delegated credentials extension. This should be
+ * hooked while processing the ClientHello. */
+SECStatus
+tls13_ClientSendDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ /* Only send the extension if support is enabled and the client can
+ * negotiate TLS 1.3. */
+ if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 ||
+ !ss->opt.enableDelegatedCredentials) {
+ return SECSuccess;
+ }
+
+ /* Filter the schemes that are enabled and acceptable. Save these in
+ * the "advertised" list, then encode them to be sent. If we receive
+ * a DC in response, validate that it matches one of the advertised
+ * schemes. */
+ SSLSignatureScheme filtered[MAX_SIGNATURE_SCHEMES] = { 0 };
+ unsigned int filteredCount = 0;
+ SECStatus rv = ssl3_FilterSigAlgs(ss, ss->vrange.max,
+ PR_TRUE /* disableRsae */,
+ PR_FALSE /* forCert */,
+ MAX_SIGNATURE_SCHEMES,
+ filtered,
+ &filteredCount);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* If no schemes available for the DC extension, don't send it. */
+ if (!filteredCount) {
+ return SECSuccess;
+ }
+
+ rv = ssl3_EncodeFilteredSigAlgs(ss, filtered, filteredCount,
+ PR_FALSE /* GREASE */, buf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ SSLSignatureScheme *dcSchemesAdvertised = PORT_ZNewArray(SSLSignatureScheme,
+ filteredCount);
+ if (!dcSchemesAdvertised) {
+ return SECFailure;
+ }
+ for (unsigned int i = 0; i < filteredCount; i++) {
+ dcSchemesAdvertised[i] = filtered[i];
+ }
+
+ if (xtnData->delegCredSigSchemesAdvertised) {
+ PORT_Free(xtnData->delegCredSigSchemesAdvertised);
+ }
+ xtnData->delegCredSigSchemesAdvertised = dcSchemesAdvertised;
+ xtnData->numDelegCredSigSchemesAdvertised = filteredCount;
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* Parses the delegated credential (DC) offered by the server. This should be
+ * hooked while processing the server's CertificateVerify.
+ *
+ * Only the DC sent with the end-entity certificate is to be parsed. This is
+ * ensured by |tls13_HandleCertificateEntry|, which only processes extensions
+ * for the first certificate in the chain.
+ */
+SECStatus
+tls13_ClientHandleDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ if (!ss->opt.enableDelegatedCredentials ||
+ ss->version < SSL_LIBRARY_VERSION_TLS_1_3) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+
+ sslDelegatedCredential *dc = NULL;
+ SECStatus rv = tls13_ReadDelegatedCredential(data->data, data->len, &dc);
+ if (rv != SECSuccess) {
+ goto loser; /* code already set */
+ }
+
+ /* When using RSA, the public key MUST NOT use the rsaEncryption OID. */
+ if (dc->expectedCertVerifyAlg == ssl_sig_rsa_pss_rsae_sha256 ||
+ dc->expectedCertVerifyAlg == ssl_sig_rsa_pss_rsae_sha384 ||
+ dc->expectedCertVerifyAlg == ssl_sig_rsa_pss_rsae_sha512) {
+ goto alert_loser;
+ }
+
+ /* The algorithm and expected_cert_verify_algorithm fields MUST be of a
+ * type advertised by the client in the SignatureSchemeList and are
+ * considered invalid otherwise. Clients that receive invalid delegated
+ * credentials MUST terminate the connection with an "illegal_parameter"
+ * alert. */
+ PRBool found = PR_FALSE;
+ for (unsigned int i = 0; i < ss->xtnData.numDelegCredSigSchemesAdvertised; ++i) {
+ if (dc->expectedCertVerifyAlg == ss->xtnData.delegCredSigSchemesAdvertised[i]) {
+ found = PR_TRUE;
+ break;
+ }
+ }
+ if (found == PR_FALSE) {
+ goto alert_loser;
+ }
+
+ // Check the dc->alg, if necessary.
+ if (dc->alg != dc->expectedCertVerifyAlg) {
+ found = PR_FALSE;
+ for (unsigned int i = 0; i < ss->xtnData.numDelegCredSigSchemesAdvertised; ++i) {
+ if (dc->alg == ss->xtnData.delegCredSigSchemesAdvertised[i]) {
+ found = PR_TRUE;
+ break;
+ }
+ }
+ if (found == PR_FALSE) {
+ goto alert_loser;
+ }
+ }
+
+ xtnData->peerDelegCred = dc;
+ xtnData->negotiated[xtnData->numNegotiated++] =
+ ssl_delegated_credentials_xtn;
+ return SECSuccess;
+alert_loser:
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+loser:
+ tls13_DestroyDelegatedCredential(dc);
+ return SECFailure;
+}
+
+/* Adds the DC extension if we're committed to authenticating with a DC. */
+static SECStatus
+tls13_ServerSendDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ if (tls13_IsSigningWithDelegatedCredential(ss)) {
+ const SECItem *dc = &ss->sec.serverCert->delegCred;
+ SECStatus rv;
+ rv = sslBuffer_Append(buf, dc->data, dc->len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ *added = PR_TRUE;
+ }
+ return SECSuccess;
+}
+
+/* The client has indicated support of DCs. We can't act on this information
+ * until we've committed to signing with a DC, so just set a callback for
+ * sending the DC extension later. */
+SECStatus
+tls13_ServerHandleDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ if (xtnData->delegCredSigSchemes) {
+ PORT_Free(xtnData->delegCredSigSchemes);
+ xtnData->delegCredSigSchemes = NULL;
+ xtnData->numDelegCredSigSchemes = 0;
+ }
+ SECStatus rv = ssl_ParseSignatureSchemes(ss, NULL,
+ &xtnData->delegCredSigSchemes,
+ &xtnData->numDelegCredSigSchemes,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+ if (xtnData->numDelegCredSigSchemes == 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, handshake_failure);
+ PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM);
+ return SECFailure;
+ }
+ /* Check for trailing data. */
+ if (data->len != 0) {
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO);
+ return SECFailure;
+ }
+
+ /* Keep track of negotiated extensions. */
+ xtnData->peerRequestedDelegCred = PR_TRUE;
+ xtnData->negotiated[xtnData->numNegotiated++] =
+ ssl_delegated_credentials_xtn;
+
+ return ssl3_RegisterExtensionSender(
+ ss, xtnData, ssl_delegated_credentials_xtn,
+ tls13_ServerSendDelegatedCredentialsXtn);
+}
+
+/* Adds the ECH extension containing server retry_configs */
+SECStatus
+tls13_ServerSendEchXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ if (PR_CLIST_IS_EMPTY(&ss->echConfigs)) {
+ return SECSuccess;
+ }
+
+ const sslEchConfig *cfg = (sslEchConfig *)PR_LIST_HEAD(&ss->echConfigs);
+ rv = sslBuffer_AppendVariable(buf, cfg->raw.data, cfg->raw.len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+/* If an ECH server sends the HRR ECH extension after it accepted ECH, the
+ * extension's payload must be set to 8 zero bytes, these are overwritten with
+ * the accept_confirmation value after the required transcript calculation.
+ * If a client-facing/shared-mode server did not accept ECH when offered in CH
+ * or if ECH GREASE is enabled on the server and a ECH extension was received,
+ * a 8 byte random value is set as the extension's payload
+ * [draft-ietf-tls-esni-14, Section 7].
+ *
+ * Depending on the acceptance of ECH, zero or random bytes are written to
+ * ss->ssl3.hs.greaseEchBuf.buf in tls13con.c/tls13_SendHelloRetryRequest(). */
+SECStatus
+tls13_ServerSendHrrEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ SECStatus rv;
+ /* Do not send HRR ECH extension if TLS < 1.3 was negotiated OR no ECH
+ * extension was received OR the server is NOT in any ECH server mode AND
+ * ECH GREASE is NOT enabled. */
+ if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 ||
+ !xtnData->ech ||
+ (!ss->echPubKey && !ss->opt.enableTls13BackendEch && !ss->opt.enableTls13GreaseEch)) {
+ SSL_TRC(100, ("%d: TLS13[%d]: server not sending HRR ECH Xtn",
+ SSL_GETPID(), ss->fd));
+ return SECSuccess;
+ }
+ SSL_TRC(100, ("%d: TLS13[%d]: server sending HRR ECH Xtn",
+ SSL_GETPID(), ss->fd));
+ PR_ASSERT(SSL_BUFFER_LEN(&ss->ssl3.hs.greaseEchBuf) == TLS13_ECH_SIGNAL_LEN);
+ PRINT_BUF(100, (ss, "grease_ech_confirmation", ss->ssl3.hs.greaseEchBuf.buf, TLS13_ECH_SIGNAL_LEN));
+ rv = sslBuffer_AppendBuffer(buf, &ss->ssl3.hs.greaseEchBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_ServerHandleInnerEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ PRUint64 xtn_type;
+ sslReader xtnReader = SSL_READER(data->data, data->len);
+
+ PR_ASSERT(ss->ssl3.hs.echAccepted || ss->opt.enableTls13BackendEch);
+ PR_ASSERT(!xtnData->ech->receivedInnerXtn);
+
+ SECStatus rv = sslRead_ReadNumber(&xtnReader, 1, &xtn_type);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ if (xtn_type != ech_xtn_type_inner) {
+ goto alert_loser;
+ }
+ if (SSL_READER_REMAINING(&xtnReader)) {
+ /* Inner ECH Extension must contain only type enum */
+ goto alert_loser;
+ }
+
+ xtnData->ech->receivedInnerXtn = PR_TRUE;
+ xtnData->negotiated[xtnData->numNegotiated++] = ssl_tls13_encrypted_client_hello_xtn;
+ return SECSuccess;
+
+alert_loser:
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
+ return SECFailure;
+}
+
+SECStatus
+tls13_ServerHandleOuterEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data)
+{
+ SECStatus rv;
+ HpkeKdfId kdf;
+ HpkeAeadId aead;
+ PRUint32 tmp;
+ PRUint8 configId;
+ SECItem senderPubKey;
+ SECItem encryptedCh;
+
+ PRUint32 xtn_type;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &xtn_type, 1, &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ if (xtn_type != ech_xtn_type_outer && xtn_type != ech_xtn_type_inner) {
+ SSL_TRC(3, ("%d: TLS13[%d]: unexpected ECH extension type in client hello outer, alert",
+ SSL_GETPID(), ss->fd));
+ goto alert_loser;
+ }
+ /* If we are operating in shared mode, we can accept an inner xtn in the ClientHelloOuter */
+ if (xtn_type == ech_xtn_type_inner) {
+ if (!ss->opt.enableTls13BackendEch) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+ PORT_Assert(!xtnData->ech);
+ xtnData->ech = PORT_ZNew(sslEchXtnState);
+ if (!xtnData->ech) {
+ return SECFailure;
+ }
+ /* We have to rewind the buffer advanced by ssl3_ExtConsumeHandshakeNumber */
+ data->data--;
+ data->len++;
+ return tls13_ServerHandleInnerEchXtn(ss, xtnData, data);
+ }
+ if (ss->ssl3.hs.echAccepted) {
+ ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter);
+ PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION);
+ return SECFailure;
+ }
+
+ SSL_TRC(3, ("%d: TLS13[%d]: handle outer ECH extension",
+ SSL_GETPID(), ss->fd));
+
+ PORT_Assert(!xtnData->ech);
+ xtnData->ech = PORT_ZNew(sslEchXtnState);
+ if (!xtnData->ech) {
+ return SECFailure;
+ }
+
+ /* Parse the KDF and AEAD. */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ kdf = (HpkeKdfId)tmp;
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ aead = (HpkeAeadId)tmp;
+
+ /* config_id */
+ rv = ssl3_ExtConsumeHandshakeNumber(ss, &tmp, 1,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ configId = tmp;
+
+ /* enc */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &senderPubKey, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+
+ /* payload, which must be final and non-empty. */
+ xtnData->ech->payloadStart = data->data + 2; /* Move past length */
+ rv = ssl3_ExtConsumeHandshakeVariable(ss, &encryptedCh, 2,
+ &data->data, &data->len);
+ if (rv != SECSuccess) {
+ goto alert_loser;
+ }
+ if (data->len || !encryptedCh.len) {
+ goto alert_loser;
+ }
+
+ if (!ss->ssl3.hs.helloRetry) {
+ /* In the real ECH HRR case, config_id and enc should be empty. This
+ * is checked after acceptance, because it might be GREASE ECH. */
+ if (!senderPubKey.len) {
+ goto alert_loser;
+ }
+
+ rv = SECITEM_CopyItem(NULL, &xtnData->ech->senderPubKey, &senderPubKey);
+ if (rv == SECFailure) {
+ return SECFailure;
+ }
+ }
+
+ rv = SECITEM_CopyItem(NULL, &xtnData->ech->innerCh, &encryptedCh);
+ PRINT_BUF(100, (ss, "CT for ECH Decryption", encryptedCh.data, encryptedCh.len));
+ if (rv == SECFailure) {
+ return SECFailure;
+ }
+ xtnData->ech->configId = configId;
+ xtnData->ech->kdfId = kdf;
+ xtnData->ech->aeadId = aead;
+
+ /* Not negotiated until tls13_MaybeAcceptEch. */
+ return SECSuccess;
+
+alert_loser:
+ ssl3_ExtSendAlert(ss, alert_fatal, decode_error);
+ PORT_SetError(SSL_ERROR_RX_MALFORMED_ECH_EXTENSION);
+ return SECFailure;
+}
+
+SECStatus
+tls13_SendEmptyGreaseXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ if (!ss->opt.enableGrease ||
+ (!ss->sec.isServer && ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) ||
+ (ss->sec.isServer && ss->version < SSL_LIBRARY_VERSION_TLS_1_3)) {
+ return SECSuccess;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
+
+SECStatus
+tls13_SendGreaseXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added)
+{
+ if (!ss->opt.enableGrease ||
+ (!ss->sec.isServer && ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) ||
+ (ss->sec.isServer && ss->version < SSL_LIBRARY_VERSION_TLS_1_3)) {
+ return SECSuccess;
+ }
+
+ SECStatus rv = sslBuffer_AppendVariable(buf, (PRUint8[]){ 0x00 }, 1, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ *added = PR_TRUE;
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/tls13exthandle.h b/security/nss/lib/ssl/tls13exthandle.h
new file mode 100644
index 0000000000..e4247e295d
--- /dev/null
+++ b/security/nss/lib/ssl/tls13exthandle.h
@@ -0,0 +1,127 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13exthandle_h_
+#define __tls13exthandle_h_
+
+SECStatus tls13_ServerSendStatusRequestXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ClientSendKeyShareXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ClientHandleKeyShareXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerHandleKeyShareXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerSendKeyShareXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ClientSendPreSharedKeyXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ServerHandlePreSharedKeyXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientHandlePreSharedKeyXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerSendPreSharedKeyXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ClientSendEarlyDataXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ServerHandleEarlyDataXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientHandleEarlyDataXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientHandleTicketEarlyDataXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientSendSupportedVersionsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ServerSendSupportedVersionsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_ClientHandleHrrCookie(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientSendHrrCookieXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ClientSendPskModesXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ServerHandlePskModesXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_SendCertAuthoritiesXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *append);
+SECStatus tls13_ClientHandleCertAuthoritiesXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerHandleCertAuthoritiesXtn(const sslSocket *ss, TLSExtensionData *xtnData, SECItem *data);
+
+SECStatus tls13_ServerHandleCookieXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerSendHrrKeyShareXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_ServerSendHrrCookieXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_DecodeKeyShareEntry(sslReader *rdr, TLS13KeyShareEntry **ksp);
+PRUint32 tls13_SizeOfKeyShareEntry(const SECKEYPublicKey *pubKey);
+SECStatus tls13_EncodeKeyShareEntry(sslBuffer *buf, SSLNamedGroup group,
+ SECKEYPublicKey *pubKey);
+SECStatus tls13_ServerHandleInnerEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerHandleOuterEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ServerSendHrrEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_ServerSendEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_ClientHandleHrrEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientHandleEchXtn(const sslSocket *ss, TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientSendPostHandshakeAuthXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_ServerHandlePostHandshakeAuthXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientHandleDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_ClientSendDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_ServerHandleDelegatedCredentialsXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ SECItem *data);
+SECStatus tls13_SendEmptyGreaseXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+SECStatus tls13_SendGreaseXtn(const sslSocket *ss,
+ TLSExtensionData *xtnData,
+ sslBuffer *buf, PRBool *added);
+
+#endif
diff --git a/security/nss/lib/ssl/tls13hashstate.c b/security/nss/lib/ssl/tls13hashstate.c
new file mode 100644
index 0000000000..d14e325580
--- /dev/null
+++ b/security/nss/lib/ssl/tls13hashstate.c
@@ -0,0 +1,332 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "pk11func.h"
+#include "ssl.h"
+#include "sslt.h"
+#include "sslimpl.h"
+#include "selfencrypt.h"
+#include "tls13con.h"
+#include "tls13ech.h"
+#include "tls13err.h"
+#include "tls13hashstate.h"
+
+/*
+ * The cookie is structured as a self-encrypted structure with the
+ * inner value being.
+ *
+ * struct {
+ * uint8 indicator = 0xff; // To disambiguate from tickets.
+ * uint16 cipherSuite; // Selected cipher suite.
+ * uint16 keyShare; // Requested key share group (0=none)
+ * PRUint8 echConfigId; // ECH config_id
+ * HpkeKdfId kdfId; // ECH KDF (uint16)
+ * HpkeAeadId aeadId; // ECH AEAD (uint16)
+ * opaque echHpkeCtx<0..65535>; // ECH serialized HPKE context
+ * opaque applicationToken<0..65535>; // Application token
+ * opaque ch_hash[rest_of_buffer]; // H(ClientHello)
+ * } CookieInner;
+ *
+ * An empty echConfigId means that ECH was not offered in the first ClientHello.
+ * An empty echHrrPsk means that ECH was not accepted in CH1.
+ */
+SECStatus
+tls13_MakeHrrCookie(sslSocket *ss, const sslNamedGroupDef *selectedGroup,
+ const PRUint8 *appToken, unsigned int appTokenLen,
+ PRUint8 *buf, unsigned int *len, unsigned int maxlen)
+{
+ SECStatus rv;
+ SSL3Hashes hashes;
+ PRUint8 cookie[1024];
+ sslBuffer cookieBuf = SSL_BUFFER(cookie);
+ static const PRUint8 indicator = 0xff;
+ SECItem *echHpkeCtx = NULL;
+
+ /* Encode header. */
+ rv = sslBuffer_Append(&cookieBuf, &indicator, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(&cookieBuf, ss->ssl3.hs.cipher_suite, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(&cookieBuf,
+ selectedGroup ? selectedGroup->name : 0, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (ss->xtnData.ech) {
+ /* Record that we received ECH. See sslEchCookieData */
+ rv = sslBuffer_AppendNumber(&cookieBuf, PR_TRUE, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(&cookieBuf, ss->xtnData.ech->configId,
+ 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(&cookieBuf, ss->xtnData.ech->kdfId, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(&cookieBuf, ss->xtnData.ech->aeadId, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ /* We need to send a ECH HRR Extension containing a signal for the client,
+ * we must store the signal in the cookie so we can reconstruct the transcript
+ * later. To avoid leaking whether ECH was accepted in the length of the cookie
+ * we include the empty signal in the cookie regardless.
+ */
+ PR_ASSERT(SSL_BUFFER_LEN(&ss->ssl3.hs.greaseEchBuf) == TLS13_ECH_SIGNAL_LEN);
+ rv = sslBuffer_AppendBuffer(&cookieBuf, &ss->ssl3.hs.greaseEchBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* There might be no HPKE Context, e.g. when we lack a matching ECHConfig. */
+ if (ss->ssl3.hs.echHpkeCtx) {
+ rv = PK11_HPKE_ExportContext(ss->ssl3.hs.echHpkeCtx, NULL, &echHpkeCtx);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(&cookieBuf, echHpkeCtx->data, echHpkeCtx->len, 2);
+ SECITEM_ZfreeItem(echHpkeCtx, PR_TRUE);
+ } else {
+ /* Zero length HPKE context. */
+ rv = sslBuffer_AppendNumber(&cookieBuf, 0, 2);
+ }
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ } else {
+ rv = sslBuffer_AppendNumber(&cookieBuf, PR_FALSE, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ /* Application token. */
+ rv = sslBuffer_AppendVariable(&cookieBuf, appToken, appTokenLen, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Compute and encode hashes. */
+ rv = tls13_ComputeHandshakeHashes(ss, &hashes);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Append(&cookieBuf, hashes.u.raw, hashes.len);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* Encrypt right into the buffer. */
+ rv = ssl_SelfEncryptProtect(ss, cookieBuf.buf, cookieBuf.len,
+ buf, len, maxlen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Given a cookie and cookieLen, decrypt and parse, returning
+ * any values that were requested via the "previous_" params. If
+ * recoverState is true, the transcript state and application
+ * token are restored. Note that previousEchKdfId, previousEchAeadId,
+ * previousEchConfigId, and previousEchHpkeCtx are not modified if ECH was not
+ * previously negotiated (i.e., previousEchOffered is PR_FALSE). */
+SECStatus
+tls13_HandleHrrCookie(sslSocket *ss,
+ unsigned char *cookie, unsigned int cookieLen,
+ ssl3CipherSuite *previousCipherSuite,
+ const sslNamedGroupDef **previousGroup,
+ PRBool *previousOfferedEch,
+ sslEchCookieData *echData,
+ PRBool recoverState)
+{
+ SECStatus rv;
+ unsigned char plaintext[1024];
+ unsigned int plaintextLen = 0;
+ sslBuffer messageBuf = SSL_BUFFER_EMPTY;
+ sslReadBuffer echHpkeBuf = { 0 };
+ PRBool receivedEch;
+ PRUint64 sentinel;
+ PRUint64 cipherSuite;
+ sslEchCookieData parsedEchData = { 0 };
+ sslReadBuffer greaseReadBuf = { 0 };
+ PRUint64 group;
+ PRUint64 tmp64;
+ const sslNamedGroupDef *selectedGroup;
+ PRUint64 appTokenLen;
+
+ rv = ssl_SelfEncryptUnprotect(ss, cookie, cookieLen,
+ plaintext, &plaintextLen, sizeof(plaintext));
+ if (rv != SECSuccess) {
+ SSL_TRC(100, ("Error decrypting cookie."));
+ return SECFailure;
+ }
+
+ sslReader reader = SSL_READER(plaintext, plaintextLen);
+
+ /* Should start with the sentinel value. */
+ rv = sslRead_ReadNumber(&reader, 1, &sentinel);
+ if ((rv != SECSuccess) || (sentinel != TLS13_COOKIE_SENTINEL)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ /* The cipher suite should be the same or there are some shenanigans. */
+ rv = sslRead_ReadNumber(&reader, 2, &cipherSuite);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* The named group, if any. */
+ rv = sslRead_ReadNumber(&reader, 2, &group);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ selectedGroup = ssl_LookupNamedGroup(group);
+
+ /* Was ECH received. */
+ rv = sslRead_ReadNumber(&reader, 1, &tmp64);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ receivedEch = tmp64 == PR_TRUE;
+ *previousOfferedEch = receivedEch;
+ if (receivedEch) {
+ /* ECH config ID */
+ rv = sslRead_ReadNumber(&reader, 1, &tmp64);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ parsedEchData.configId = (PRUint8)tmp64;
+
+ /* ECH Ciphersuite */
+ rv = sslRead_ReadNumber(&reader, 2, &tmp64);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ parsedEchData.kdfId = (HpkeKdfId)tmp64;
+
+ rv = sslRead_ReadNumber(&reader, 2, &tmp64);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ parsedEchData.aeadId = (HpkeAeadId)tmp64;
+
+ /* ECH accept_confirmation signal. */
+ rv = sslRead_Read(&reader, TLS13_ECH_SIGNAL_LEN, &greaseReadBuf);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ PORT_Memcpy(parsedEchData.signal, greaseReadBuf.buf, TLS13_ECH_SIGNAL_LEN);
+
+ /* ECH HPKE context may be empty. */
+ rv = sslRead_ReadVariable(&reader, 2, &echHpkeBuf);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ if (echData && echHpkeBuf.len) {
+ const SECItem hpkeItem = { siBuffer, CONST_CAST(unsigned char, echHpkeBuf.buf),
+ echHpkeBuf.len };
+ parsedEchData.hpkeCtx = PK11_HPKE_ImportContext(&hpkeItem, NULL);
+ if (!parsedEchData.hpkeCtx) {
+ FATAL_ERROR(ss, PORT_GetError(), illegal_parameter);
+ return SECFailure;
+ }
+ }
+ }
+
+ /* Application token. */
+ rv = sslRead_ReadNumber(&reader, 2, &appTokenLen);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ sslReadBuffer appTokenReader = { 0 };
+ rv = sslRead_Read(&reader, appTokenLen, &appTokenReader);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+ PORT_Assert(appTokenReader.len == appTokenLen);
+
+ if (recoverState) {
+ PORT_Assert(ss->xtnData.applicationToken.len == 0);
+ if (SECITEM_AllocItem(NULL, &ss->xtnData.applicationToken,
+ appTokenLen) == NULL) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+ PORT_Memcpy(ss->xtnData.applicationToken.data, appTokenReader.buf, appTokenLen);
+ ss->xtnData.applicationToken.len = appTokenLen;
+
+ /* The remainder is the hash. */
+ unsigned int hashLen = SSL_READER_REMAINING(&reader);
+ if (hashLen != tls13_GetHashSize(ss)) {
+ FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* Now reinject the message. */
+ SSL_ASSERT_HASHES_EMPTY(ss);
+ rv = ssl_HashHandshakeMessageInt(ss, ssl_hs_message_hash, 0,
+ SSL_READER_CURRENT(&reader), hashLen,
+ ssl3_UpdateHandshakeHashes);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ /* And finally reinject the HRR. */
+ rv = tls13_ConstructHelloRetryRequest(ss, cipherSuite,
+ selectedGroup,
+ cookie, cookieLen,
+ parsedEchData.signal,
+ &messageBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = ssl_HashHandshakeMessageInt(ss, ssl_hs_server_hello, 0,
+ SSL_BUFFER_BASE(&messageBuf),
+ SSL_BUFFER_LEN(&messageBuf),
+ ssl3_UpdateHandshakeHashes);
+ sslBuffer_Clear(&messageBuf);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ }
+
+ if (previousCipherSuite) {
+ *previousCipherSuite = cipherSuite;
+ }
+ if (previousGroup) {
+ *previousGroup = selectedGroup;
+ }
+ if (echData) {
+ PORT_Memcpy(echData, &parsedEchData, sizeof(parsedEchData));
+ }
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/tls13hashstate.h b/security/nss/lib/ssl/tls13hashstate.h
new file mode 100644
index 0000000000..6780f4994d
--- /dev/null
+++ b/security/nss/lib/ssl/tls13hashstate.h
@@ -0,0 +1,27 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13hashstate_h_
+#define __tls13hashstate_h_
+
+#include "ssl.h"
+#include "sslt.h"
+#include "sslimpl.h"
+
+SECStatus tls13_MakeHrrCookie(sslSocket *ss, const sslNamedGroupDef *selectedGroup,
+ const PRUint8 *appToken, unsigned int appTokenLen,
+ PRUint8 *buf, unsigned int *len, unsigned int maxlen);
+SECStatus tls13_GetHrrCookieLength(sslSocket *ss, unsigned int *length);
+SECStatus tls13_HandleHrrCookie(sslSocket *ss,
+ unsigned char *cookie, unsigned int cookieLen,
+ ssl3CipherSuite *previousCipherSuite,
+ const sslNamedGroupDef **previousGroup,
+ PRBool *previousOfferedEch,
+ sslEchCookieData *echData,
+ PRBool recoverState);
+#endif
diff --git a/security/nss/lib/ssl/tls13hkdf.c b/security/nss/lib/ssl/tls13hkdf.c
new file mode 100644
index 0000000000..ed6cdd559f
--- /dev/null
+++ b/security/nss/lib/ssl/tls13hkdf.c
@@ -0,0 +1,305 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * TLS 1.3 Protocol
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "keyhi.h"
+#include "pk11func.h"
+#include "secitem.h"
+#include "ssl.h"
+#include "sslt.h"
+#include "sslerr.h"
+#include "sslimpl.h"
+
+/* This table contains the mapping between TLS hash identifiers and the
+ * PKCS#11 identifiers */
+static const struct {
+ SSLHashType hash;
+ CK_MECHANISM_TYPE pkcs11Mech;
+ unsigned int hashSize;
+} kTlsHkdfInfo[] = {
+ { ssl_hash_none, 0, 0 },
+ { ssl_hash_md5, 0, 0 },
+ { ssl_hash_sha1, 0, 0 },
+ { ssl_hash_sha224, 0 },
+ { ssl_hash_sha256, CKM_SHA256, 32 },
+ { ssl_hash_sha384, CKM_SHA384, 48 },
+ { ssl_hash_sha512, CKM_SHA512, 64 }
+};
+
+SECStatus
+tls13_HkdfExtract(PK11SymKey *ikm1, PK11SymKey *ikm2, SSLHashType baseHash,
+ PK11SymKey **prkp)
+{
+ CK_HKDF_PARAMS params;
+ SECItem paramsi;
+ PK11SymKey *prk;
+ static const PRUint8 zeroKeyBuf[HASH_LENGTH_MAX];
+ SECItem zeroKeyItem = { siBuffer, CONST_CAST(PRUint8, zeroKeyBuf), kTlsHkdfInfo[baseHash].hashSize };
+ PK11SlotInfo *slot = NULL;
+ PK11SymKey *newIkm2 = NULL;
+ PK11SymKey *newIkm1 = NULL;
+ SECStatus rv;
+
+ params.bExtract = CK_TRUE;
+ params.bExpand = CK_FALSE;
+ params.prfHashMechanism = kTlsHkdfInfo[baseHash].pkcs11Mech;
+ params.pInfo = NULL;
+ params.ulInfoLen = 0UL;
+ params.pSalt = NULL;
+ params.ulSaltLen = 0UL;
+ params.hSaltKey = CK_INVALID_HANDLE;
+
+ if (!ikm1) {
+ /* PKCS #11 v3.0 has and explict NULL value, which equates to
+ * a sequence of zeros equal in length to the HMAC. */
+ params.ulSaltType = CKF_HKDF_SALT_NULL;
+ } else {
+ /* PKCS #11 v3.0 can take the salt as a key handle */
+ params.hSaltKey = PK11_GetSymKeyHandle(ikm1);
+ params.ulSaltType = CKF_HKDF_SALT_KEY;
+
+ /* if we have both keys, make sure they are in the same slot */
+ if (ikm2) {
+ rv = PK11_SymKeysToSameSlot(CKM_HKDF_DERIVE,
+ CKA_DERIVE, CKA_DERIVE,
+ ikm2, ikm1, &newIkm2, &newIkm1);
+ if (rv != SECSuccess) {
+ SECItem *salt;
+ /* couldn't move the keys, try extracting the salt */
+ rv = PK11_ExtractKeyValue(ikm1);
+ if (rv != SECSuccess)
+ return rv;
+ salt = PK11_GetKeyData(ikm1);
+ if (!salt)
+ return SECFailure;
+ PORT_Assert(salt->len > 0);
+ /* Set up for Salt as Data instead of Salt as key */
+ params.pSalt = salt->data;
+ params.ulSaltLen = salt->len;
+ params.ulSaltType = CKF_HKDF_SALT_DATA;
+ }
+ /* use the new keys */
+ if (newIkm1) {
+ /* we've moved the key, get the handle for the new key */
+ params.hSaltKey = PK11_GetSymKeyHandle(newIkm1);
+ /* we don't use ikm1 after this, so don't bother setting it */
+ }
+ if (newIkm2) {
+ /* new ikm2 key, use the new key */
+ ikm2 = newIkm2;
+ }
+ }
+ }
+ paramsi.data = (unsigned char *)&params;
+ paramsi.len = sizeof(params);
+
+ PORT_Assert(kTlsHkdfInfo[baseHash].pkcs11Mech);
+ PORT_Assert(kTlsHkdfInfo[baseHash].hashSize);
+ PORT_Assert(kTlsHkdfInfo[baseHash].hash == baseHash);
+
+ /* A zero ikm2 is a key of hash-length 0s. */
+ if (!ikm2) {
+ /* if we have ikm1, put the zero key in the same slot */
+ slot = ikm1 ? PK11_GetSlotFromKey(ikm1) : PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
+ if (!slot) {
+ return SECFailure;
+ }
+
+ newIkm2 = PK11_ImportDataKey(slot, CKM_HKDF_DERIVE, PK11_OriginUnwrap,
+ CKA_DERIVE, &zeroKeyItem, NULL);
+ if (!newIkm2) {
+ return SECFailure;
+ }
+ ikm2 = newIkm2;
+ }
+ PORT_Assert(ikm2);
+
+ PRINT_BUF(50, (NULL, "HKDF Extract: IKM1/Salt", params.pSalt, params.ulSaltLen));
+ PRINT_KEY(50, (NULL, "HKDF Extract: IKM2", ikm2));
+
+ prk = PK11_Derive(ikm2, CKM_HKDF_DERIVE, &paramsi, CKM_HKDF_DERIVE,
+ CKA_DERIVE, 0);
+ PK11_FreeSymKey(newIkm2);
+ PK11_FreeSymKey(newIkm1);
+ if (slot)
+ PK11_FreeSlot(slot);
+ if (!prk) {
+ return SECFailure;
+ }
+
+ PRINT_KEY(50, (NULL, "HKDF Extract", prk));
+ *prkp = prk;
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_HkdfExpandLabelGeneral(CK_MECHANISM_TYPE deriveMech, PK11SymKey *prk,
+ SSLHashType baseHash,
+ const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE algorithm, unsigned int keySize,
+ SSLProtocolVariant variant, PK11SymKey **keyp)
+{
+ CK_HKDF_PARAMS params;
+ SECItem paramsi = { siBuffer, NULL, 0 };
+ /* Size of info array needs to be big enough to hold the maximum Prefix,
+ * Label, plus HandshakeHash. If it's ever to small, the code will abort.
+ */
+ PRUint8 info[256];
+ sslBuffer infoBuf = SSL_BUFFER(info);
+ PK11SymKey *derived;
+ SECStatus rv;
+ const char *kLabelPrefixTls = "tls13 ";
+ const char *kLabelPrefixDtls = "dtls13";
+ const unsigned int kLabelPrefixLen =
+ (variant == ssl_variant_stream) ? strlen(kLabelPrefixTls) : strlen(kLabelPrefixDtls);
+ const char *kLabelPrefix =
+ (variant == ssl_variant_stream) ? kLabelPrefixTls : kLabelPrefixDtls;
+
+ PORT_Assert(prk);
+ PORT_Assert(keyp);
+ if ((handshakeHashLen > 255) ||
+ (handshakeHash == NULL && handshakeHashLen > 0) ||
+ (labelLen + kLabelPrefixLen > 255)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ /*
+ * [draft-ietf-tls-tls13-11] Section 7.1:
+ *
+ * HKDF-Expand-Label(Secret, Label, HashValue, Length) =
+ * HKDF-Expand(Secret, HkdfLabel, Length)
+ *
+ * Where HkdfLabel is specified as:
+ *
+ * struct HkdfLabel {
+ * uint16 length;
+ * opaque label<9..255>;
+ * opaque hash_value<0..255>;
+ * };
+ *
+ * Where:
+ * - HkdfLabel.length is Length
+ * - HkdfLabel.hash_value is HashValue.
+ * - HkdfLabel.label is "TLS 1.3, " + Label
+ *
+ */
+ rv = sslBuffer_AppendNumber(&infoBuf, keySize, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendNumber(&infoBuf, labelLen + kLabelPrefixLen, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Append(&infoBuf, kLabelPrefix, kLabelPrefixLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_Append(&infoBuf, label, labelLen);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ rv = sslBuffer_AppendVariable(&infoBuf, handshakeHash, handshakeHashLen, 1);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ params.bExtract = CK_FALSE;
+ params.bExpand = CK_TRUE;
+ params.prfHashMechanism = kTlsHkdfInfo[baseHash].pkcs11Mech;
+ params.pInfo = SSL_BUFFER_BASE(&infoBuf);
+ params.ulInfoLen = SSL_BUFFER_LEN(&infoBuf);
+ paramsi.data = (unsigned char *)&params;
+ paramsi.len = sizeof(params);
+ derived = PK11_DeriveWithFlags(prk, deriveMech,
+ &paramsi, algorithm,
+ CKA_DERIVE, keySize,
+ CKF_SIGN | CKF_VERIFY);
+ if (!derived) {
+ return SECFailure;
+ }
+
+ *keyp = derived;
+
+#ifdef TRACE
+ if (ssl_trace >= 50) {
+ /* Make sure the label is null terminated. */
+ char labelStr[100];
+ PORT_Memcpy(labelStr, label, labelLen);
+ labelStr[labelLen] = 0;
+ SSL_TRC(50, ("HKDF Expand: label='tls13 %s',requested length=%d",
+ labelStr, keySize));
+ }
+ PRINT_KEY(50, (NULL, "PRK", prk));
+ PRINT_BUF(50, (NULL, "Hash", handshakeHash, handshakeHashLen));
+ PRINT_BUF(50, (NULL, "Info", SSL_BUFFER_BASE(&infoBuf),
+ SSL_BUFFER_LEN(&infoBuf)));
+ PRINT_KEY(50, (NULL, "Derived key", derived));
+#endif
+
+ return SECSuccess;
+}
+
+SECStatus
+tls13_HkdfExpandLabel(PK11SymKey *prk, SSLHashType baseHash,
+ const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE algorithm, unsigned int keySize,
+ SSLProtocolVariant variant, PK11SymKey **keyp)
+{
+ return tls13_HkdfExpandLabelGeneral(CKM_HKDF_DERIVE, prk, baseHash,
+ handshakeHash, handshakeHashLen,
+ label, labelLen, algorithm, keySize,
+ variant, keyp);
+}
+
+SECStatus
+tls13_HkdfExpandLabelRaw(PK11SymKey *prk, SSLHashType baseHash,
+ const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
+ const char *label, unsigned int labelLen,
+ SSLProtocolVariant variant, unsigned char *output,
+ unsigned int outputLen)
+{
+ PK11SymKey *derived = NULL;
+ SECItem *rawkey;
+ SECStatus rv;
+
+ /* the result is not really a key, it's a data object */
+ rv = tls13_HkdfExpandLabelGeneral(CKM_HKDF_DATA, prk, baseHash,
+ handshakeHash, handshakeHashLen,
+ label, labelLen, CKM_HKDF_DERIVE, outputLen,
+ variant, &derived);
+ if (rv != SECSuccess || !derived) {
+ goto abort;
+ }
+
+ rv = PK11_ExtractKeyValue(derived);
+ if (rv != SECSuccess) {
+ goto abort;
+ }
+
+ rawkey = PK11_GetKeyData(derived);
+ if (!rawkey) {
+ goto abort;
+ }
+
+ PORT_Assert(rawkey->len == outputLen);
+ memcpy(output, rawkey->data, outputLen);
+ PK11_FreeSymKey(derived);
+
+ return SECSuccess;
+
+abort:
+ if (derived) {
+ PK11_FreeSymKey(derived);
+ }
+ PORT_SetError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
+ return SECFailure;
+}
diff --git a/security/nss/lib/ssl/tls13hkdf.h b/security/nss/lib/ssl/tls13hkdf.h
new file mode 100644
index 0000000000..00e5ff1dd3
--- /dev/null
+++ b/security/nss/lib/ssl/tls13hkdf.h
@@ -0,0 +1,39 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13hkdf_h_
+#define __tls13hkdf_h_
+
+#include "keyhi.h"
+#include "sslt.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+SECStatus tls13_HkdfExtract(
+ PK11SymKey *ikm1, PK11SymKey *ikm2, SSLHashType baseHash,
+ PK11SymKey **prkp);
+SECStatus tls13_HkdfExpandLabelRaw(
+ PK11SymKey *prk, SSLHashType baseHash,
+ const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
+ const char *label, unsigned int labelLen,
+ SSLProtocolVariant variant, unsigned char *output,
+ unsigned int outputLen);
+SECStatus tls13_HkdfExpandLabel(
+ PK11SymKey *prk, SSLHashType baseHash,
+ const PRUint8 *handshakeHash, unsigned int handshakeHashLen,
+ const char *label, unsigned int labelLen,
+ CK_MECHANISM_TYPE algorithm, unsigned int keySize,
+ SSLProtocolVariant variant, PK11SymKey **keyp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/security/nss/lib/ssl/tls13psk.c b/security/nss/lib/ssl/tls13psk.c
new file mode 100644
index 0000000000..7343c5a6f1
--- /dev/null
+++ b/security/nss/lib/ssl/tls13psk.c
@@ -0,0 +1,219 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "pk11func.h"
+#include "ssl.h"
+#include "sslproto.h"
+#include "sslimpl.h"
+#include "ssl3exthandle.h"
+#include "tls13exthandle.h"
+#include "tls13hkdf.h"
+#include "tls13psk.h"
+
+SECStatus
+SSLExp_AddExternalPsk0Rtt(PRFileDesc *fd, PK11SymKey *key, const PRUint8 *identity,
+ unsigned int identityLen, SSLHashType hash,
+ PRUint16 zeroRttSuite, PRUint32 maxEarlyData)
+{
+
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSLExp_SetExternalPsk",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ if (!key || !identity || !identityLen || identityLen > 0xFFFF ||
+ (hash != ssl_hash_sha256 && hash != ssl_hash_sha384)) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SECItem label = { siBuffer, CONST_CAST(unsigned char, identity), identityLen };
+ sslPsk *psk = tls13_MakePsk(PK11_ReferenceSymKey(key), ssl_psk_external,
+ hash, &label);
+ if (!psk) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return SECFailure;
+ }
+ psk->zeroRttSuite = zeroRttSuite;
+ psk->maxEarlyData = maxEarlyData;
+ SECStatus rv = SECFailure;
+
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (ss->psk) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ tls13_DestroyPsk(psk);
+ } else {
+ ss->psk = psk;
+ rv = SECSuccess;
+ tls13_ResetHandshakePsks(ss, &ss->ssl3.hs.psks);
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+SECStatus
+SSLExp_AddExternalPsk(PRFileDesc *fd, PK11SymKey *key, const PRUint8 *identity,
+ unsigned int identityLen, SSLHashType hash)
+{
+ return SSLExp_AddExternalPsk0Rtt(fd, key, identity, identityLen,
+ hash, TLS_NULL_WITH_NULL_NULL, 0);
+}
+
+SECStatus
+SSLExp_RemoveExternalPsk(PRFileDesc *fd, const PRUint8 *identity, unsigned int identityLen)
+{
+ if (!identity || !identityLen) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetPSK",
+ SSL_GETPID(), fd));
+ return SECFailure;
+ }
+
+ SECItem removeIdentity = { siBuffer,
+ (unsigned char *)identity,
+ identityLen };
+
+ SECStatus rv;
+ ssl_Get1stHandshakeLock(ss);
+ ssl_GetSSL3HandshakeLock(ss);
+
+ if (!ss->psk || SECITEM_CompareItem(&ss->psk->label, &removeIdentity) != SECEqual) {
+ PORT_SetError(SEC_ERROR_NO_KEY);
+ rv = SECFailure;
+ } else {
+ tls13_DestroyPsk(ss->psk);
+ ss->psk = NULL;
+ tls13_ResetHandshakePsks(ss, &ss->ssl3.hs.psks);
+ rv = SECSuccess;
+ }
+
+ ssl_ReleaseSSL3HandshakeLock(ss);
+ ssl_Release1stHandshakeLock(ss);
+
+ return rv;
+}
+
+sslPsk *
+tls13_CopyPsk(sslPsk *opsk)
+{
+ if (!opsk || !opsk->key) {
+ return NULL;
+ }
+
+ sslPsk *psk = PORT_ZNew(sslPsk);
+ if (!psk) {
+ return NULL;
+ }
+
+ SECStatus rv = SECITEM_CopyItem(NULL, &psk->label, &opsk->label);
+ if (rv != SECSuccess) {
+ PORT_Free(psk);
+ return NULL;
+ }
+ /* We should only have the initial key. Binder keys
+ * are derived during the handshake. */
+ PORT_Assert(opsk->type == ssl_psk_external);
+ PORT_Assert(opsk->key);
+ PORT_Assert(!opsk->binderKey);
+ psk->hash = opsk->hash;
+ psk->type = opsk->type;
+ psk->key = opsk->key ? PK11_ReferenceSymKey(opsk->key) : NULL;
+ psk->binderKey = opsk->binderKey ? PK11_ReferenceSymKey(opsk->binderKey) : NULL;
+ return psk;
+}
+
+void
+tls13_DestroyPsk(sslPsk *psk)
+{
+ if (!psk) {
+ return;
+ }
+ if (psk->key) {
+ PK11_FreeSymKey(psk->key);
+ psk->key = NULL;
+ }
+ if (psk->binderKey) {
+ PK11_FreeSymKey(psk->binderKey);
+ psk->binderKey = NULL;
+ }
+ SECITEM_ZfreeItem(&psk->label, PR_FALSE);
+ PORT_ZFree(psk, sizeof(*psk));
+}
+
+void
+tls13_DestroyPskList(PRCList *list)
+{
+ PRCList *cur_p;
+ while (!PR_CLIST_IS_EMPTY(list)) {
+ cur_p = PR_LIST_TAIL(list);
+ PR_REMOVE_LINK(cur_p);
+ tls13_DestroyPsk((sslPsk *)cur_p);
+ }
+}
+
+sslPsk *
+tls13_MakePsk(PK11SymKey *key, SSLPskType pskType, SSLHashType hashType, const SECItem *label)
+{
+ sslPsk *psk = PORT_ZNew(sslPsk);
+ if (!psk) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ return NULL;
+ }
+ psk->type = pskType;
+ psk->hash = hashType;
+ psk->key = key;
+
+ /* Label is NULL in the resumption case. */
+ if (label) {
+ PORT_Assert(psk->type != ssl_psk_resume);
+ SECStatus rv = SECITEM_CopyItem(NULL, &psk->label, label);
+ if (rv != SECSuccess) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ tls13_DestroyPsk(psk);
+ return NULL;
+ }
+ }
+
+ return psk;
+}
+
+/* Destroy any existing PSKs in |list| then copy
+ * in the configured |ss->psk|, if any.*/
+SECStatus
+tls13_ResetHandshakePsks(sslSocket *ss, PRCList *list)
+{
+ tls13_DestroyPskList(list);
+ PORT_Assert(!ss->xtnData.selectedPsk);
+ ss->xtnData.selectedPsk = NULL;
+ if (ss->psk) {
+ PORT_Assert(ss->psk->type == ssl_psk_external);
+ PORT_Assert(ss->psk->key);
+ PORT_Assert(!ss->psk->binderKey);
+
+ sslPsk *epsk = tls13_MakePsk(PK11_ReferenceSymKey(ss->psk->key),
+ ss->psk->type, ss->psk->hash, &ss->psk->label);
+ if (!epsk) {
+ return SECFailure;
+ }
+ epsk->zeroRttSuite = ss->psk->zeroRttSuite;
+ epsk->maxEarlyData = ss->psk->maxEarlyData;
+ PR_APPEND_LINK(&epsk->link, list);
+ }
+ return SECSuccess;
+}
diff --git a/security/nss/lib/ssl/tls13psk.h b/security/nss/lib/ssl/tls13psk.h
new file mode 100644
index 0000000000..73013fb9bc
--- /dev/null
+++ b/security/nss/lib/ssl/tls13psk.h
@@ -0,0 +1,58 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13psk_h_
+#define __tls13psk_h_
+
+/*
+ * Internally, we have track sslPsk pointers in three locations:
+ * 1) An external PSK can be configured to the socket, in which case ss->psk will hold an owned reference.
+ * For now, this only holds one external PSK. The value will persist across handshake restarts.
+ * 2) When a handshake begins, the ss->psk value is deep-copied into ss->ssl3.hs.psks, which may also hold
+ * a resumption PSK. This is essentially a priority-sorted list (where a resumption PSK has higher
+ * priority than external), and we currently only send one PskIdentity and binder.
+ * 3) During negotiation, ss->xtnData.selectedPsk will either be NULL or it will hold a non-owning refernce
+ * to the PSK that has been (or is being) negotiated.
+ */
+
+/* Note: When holding a resumption PSK:
+ * 1. |hash| comes from the original connection.
+ * 2. |label| is ignored: The identity sent in the pre_shared_key_xtn
+ * comes from ss->sec.ci.sid->u.ssl3.locked.sessionTicket.
+ */
+struct sslPskStr {
+ PRCList link;
+ PK11SymKey *key; /* A raw PSK. */
+ PK11SymKey *binderKey; /* The binder key derived from |key|. |key| is NULL after derivation. */
+ SSLPskType type; /* none, resumption, or external. */
+ SECItem label; /* Label (identity) for an external PSK. */
+ SSLHashType hash; /* A hash algorithm associated with a PSK. */
+ ssl3CipherSuite zeroRttSuite; /* For EPSKs, an explicitly-configured ciphersuite for 0-Rtt. */
+ PRUint32 maxEarlyData; /* For EPSKs, a limit on early data. Must be > 0 for 0-Rtt. */
+};
+
+SECStatus SSLExp_AddExternalPsk(PRFileDesc *fd, PK11SymKey *psk, const PRUint8 *identity,
+ unsigned int identitylen, SSLHashType hash);
+
+SECStatus SSLExp_AddExternalPsk0Rtt(PRFileDesc *fd, PK11SymKey *psk, const PRUint8 *identity,
+ unsigned int identitylen, SSLHashType hash,
+ PRUint16 zeroRttSuite, PRUint32 maxEarlyData);
+
+SECStatus SSLExp_RemoveExternalPsk(PRFileDesc *fd, const PRUint8 *identity, unsigned int identitylen);
+
+sslPsk *tls13_CopyPsk(sslPsk *opsk);
+
+void tls13_DestroyPsk(sslPsk *psk);
+
+void tls13_DestroyPskList(PRCList *list);
+
+sslPsk *tls13_MakePsk(PK11SymKey *key, SSLPskType pskType, SSLHashType hashType, const SECItem *label);
+
+SECStatus tls13_ResetHandshakePsks(sslSocket *ss, PRCList *list);
+
+#endif
diff --git a/security/nss/lib/ssl/tls13replay.c b/security/nss/lib/ssl/tls13replay.c
new file mode 100644
index 0000000000..7e00785e08
--- /dev/null
+++ b/security/nss/lib/ssl/tls13replay.c
@@ -0,0 +1,285 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * Anti-replay measures for TLS 1.3.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h" /* for NSS_RegisterShutdown */
+#include "nssilock.h" /* for PZMonitor */
+#include "pk11pub.h"
+#include "prmon.h"
+#include "prtime.h"
+#include "secerr.h"
+#include "ssl.h"
+#include "sslbloom.h"
+#include "sslimpl.h"
+#include "tls13hkdf.h"
+#include "tls13psk.h"
+
+struct SSLAntiReplayContextStr {
+ /* The number of outstanding references to this context. */
+ PRInt32 refCount;
+ /* Used to serialize access. */
+ PZMonitor *lock;
+ /* The filters, use of which alternates. */
+ sslBloomFilter filters[2];
+ /* Which of the two filters is active (0 or 1). */
+ PRUint8 current;
+ /* The time that we will next update. */
+ PRTime nextUpdate;
+ /* The width of the window; i.e., the period of updates. */
+ PRTime window;
+ /* This key ensures that the bloom filter index is unpredictable. */
+ PK11SymKey *key;
+};
+
+void
+tls13_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx)
+{
+ if (!ctx) {
+ return;
+ }
+ if (PR_ATOMIC_DECREMENT(&ctx->refCount) >= 1) {
+ return;
+ }
+
+ if (ctx->lock) {
+ PZ_DestroyMonitor(ctx->lock);
+ ctx->lock = NULL;
+ }
+ PK11_FreeSymKey(ctx->key);
+ ctx->key = NULL;
+ sslBloom_Destroy(&ctx->filters[0]);
+ sslBloom_Destroy(&ctx->filters[1]);
+ PORT_Free(ctx);
+}
+
+/* Clear the current state and free any resources we allocated. */
+SECStatus
+SSLExp_ReleaseAntiReplayContext(SSLAntiReplayContext *ctx)
+{
+ tls13_ReleaseAntiReplayContext(ctx);
+ return SECSuccess;
+}
+
+SSLAntiReplayContext *
+tls13_RefAntiReplayContext(SSLAntiReplayContext *ctx)
+{
+ PORT_Assert(ctx);
+ PR_ATOMIC_INCREMENT(&ctx->refCount);
+ return ctx;
+}
+
+static SECStatus
+tls13_AntiReplayKeyGen(SSLAntiReplayContext *ctx)
+{
+ PK11SlotInfo *slot;
+
+ PORT_Assert(ctx);
+
+ slot = PK11_GetBestSlot(CKM_HKDF_DERIVE, NULL);
+ if (!slot) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ return SECFailure;
+ }
+
+ ctx->key = PK11_KeyGen(slot, CKM_HKDF_KEY_GEN, NULL, 32, NULL);
+ if (!ctx->key) {
+ goto loser;
+ }
+
+ PK11_FreeSlot(slot);
+ return SECSuccess;
+
+loser:
+ PK11_FreeSlot(slot);
+ return SECFailure;
+}
+
+/* Set a limit on the combination of number of hashes and bits in each hash. */
+#define SSL_MAX_BLOOM_FILTER_SIZE 64
+
+/*
+ * The context created by this function can be called concurrently on multiple
+ * threads if the server is multi-threaded. A monitor is used to ensure that
+ * only one thread can access the structures that change over time, but no such
+ * guarantee is provided for configuration data.
+ */
+SECStatus
+SSLExp_CreateAntiReplayContext(PRTime now, PRTime window, unsigned int k,
+ unsigned int bits, SSLAntiReplayContext **pctx)
+{
+ SECStatus rv;
+
+ if (window <= 0 || k == 0 || bits == 0 || pctx == NULL) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+ if ((k * (bits + 7) / 8) > SSL_MAX_BLOOM_FILTER_SIZE) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ SSLAntiReplayContext *ctx = PORT_ZNew(SSLAntiReplayContext);
+ if (!ctx) {
+ return SECFailure; /* Code already set. */
+ }
+
+ ctx->refCount = 1;
+ ctx->lock = PZ_NewMonitor(nssILockSSL);
+ if (!ctx->lock) {
+ goto loser; /* Code already set. */
+ }
+
+ rv = tls13_AntiReplayKeyGen(ctx);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ rv = sslBloom_Init(&ctx->filters[0], k, bits);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ rv = sslBloom_Init(&ctx->filters[1], k, bits);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ /* When starting out, ensure that 0-RTT is not accepted until the window is
+ * updated. A ClientHello might have been accepted prior to a restart. */
+ sslBloom_Fill(&ctx->filters[1]);
+
+ ctx->current = 0;
+ ctx->nextUpdate = now + window;
+ ctx->window = window;
+ *pctx = ctx;
+ return SECSuccess;
+
+loser:
+ tls13_ReleaseAntiReplayContext(ctx);
+ return SECFailure;
+}
+
+SECStatus
+SSLExp_SetAntiReplayContext(PRFileDesc *fd, SSLAntiReplayContext *ctx)
+{
+ sslSocket *ss = ssl_FindSocket(fd);
+ if (!ss) {
+ return SECFailure; /* Code already set. */
+ }
+ tls13_ReleaseAntiReplayContext(ss->antiReplay);
+ if (ctx != NULL) {
+ ss->antiReplay = tls13_RefAntiReplayContext(ctx);
+ } else {
+ ss->antiReplay = NULL;
+ }
+ return SECSuccess;
+}
+
+static void
+tls13_AntiReplayUpdate(SSLAntiReplayContext *ctx, PRTime now)
+{
+ PR_ASSERT_CURRENT_THREAD_IN_MONITOR(ctx->lock);
+ if (now >= ctx->nextUpdate) {
+ ctx->current ^= 1;
+ ctx->nextUpdate = now + ctx->window;
+ sslBloom_Zero(ctx->filters + ctx->current);
+ }
+}
+
+PRBool
+tls13_InWindow(const sslSocket *ss, const sslSessionID *sid)
+{
+ PRInt32 timeDelta;
+
+ /* Calculate the difference between the client's view of the age of the
+ * ticket (in |ss->xtnData.ticketAge|) and the server's view, which we now
+ * calculate. The result should be close to zero. timeDelta is signed to
+ * make the comparisons below easier. */
+ timeDelta = ss->xtnData.ticketAge -
+ ((ssl_Time(ss) - sid->creationTime) / PR_USEC_PER_MSEC);
+
+ /* Only allow the time delta to be at most half of our window. This is
+ * symmetrical, though it doesn't need to be; this assumes that clock errors
+ * on server and client will tend to cancel each other out.
+ *
+ * There are two anti-replay filters that roll over each window. In the
+ * worst case, immediately after a rollover of the filters, we only have a
+ * single window worth of recorded 0-RTT attempts. Thus, the period in
+ * which we can accept 0-RTT is at most one window wide. This uses PR_ABS()
+ * and half the window so that the first attempt can be up to half a window
+ * early and then replays will be caught until the attempts are half a
+ * window late.
+ *
+ * For example, a 0-RTT attempt arrives early, but near the end of window 1.
+ * The attempt is then recorded in window 1. Rollover to window 2 could
+ * occur immediately afterwards. Window 1 is still checked for new 0-RTT
+ * attempts for the remainder of window 2. Therefore, attempts to replay
+ * are detected because the value is recorded in window 1. When rollover
+ * occurs again, window 1 is erased and window 3 instated. If we allowed an
+ * attempt to be late by more than half a window, then this check would not
+ * prevent the same 0-RTT attempt from being accepted during window 1 and
+ * later window 3.
+ */
+ PRInt32 allowance = ss->antiReplay->window / (PR_USEC_PER_MSEC * 2);
+ SSL_TRC(10, ("%d: TLS13[%d]: replay check time delta=%d, allow=%d",
+ SSL_GETPID(), ss->fd, timeDelta, allowance));
+ return PR_ABS(timeDelta) < allowance;
+}
+
+/* Checks for a duplicate in the two filters we have. Performs maintenance on
+ * the filters as a side-effect. This only detects a probable replay, it's
+ * possible that this will return true when the 0-RTT attempt is not genuinely a
+ * replay. In that case, we reject 0-RTT unnecessarily, but that's OK because
+ * no client expects 0-RTT to work every time. */
+PRBool
+tls13_IsReplay(const sslSocket *ss, const sslSessionID *sid)
+{
+ PRBool replay;
+ unsigned int size;
+ PRUint8 index;
+ SECStatus rv;
+ static const char *label = "anti-replay";
+ PRUint8 buf[SSL_MAX_BLOOM_FILTER_SIZE];
+ SSLAntiReplayContext *ctx = ss->antiReplay;
+
+ /* If SSL_SetAntiReplayContext hasn't been called with a valid context, then
+ * treat all attempts at 0-RTT as a replay. */
+ if (ctx == NULL) {
+ return PR_TRUE;
+ }
+
+ if (!sid) {
+ PORT_Assert(ss->xtnData.selectedPsk->type == ssl_psk_external);
+ } else if (!tls13_InWindow(ss, sid)) {
+ return PR_TRUE;
+ }
+
+ size = ctx->filters[0].k * (ctx->filters[0].bits + 7) / 8;
+ PORT_Assert(size <= SSL_MAX_BLOOM_FILTER_SIZE);
+ rv = tls13_HkdfExpandLabelRaw(ctx->key, ssl_hash_sha256,
+ ss->xtnData.pskBinder.data,
+ ss->xtnData.pskBinder.len,
+ label, strlen(label),
+ ss->protocolVariant, buf, size);
+ if (rv != SECSuccess) {
+ return PR_TRUE;
+ }
+
+ PZ_EnterMonitor(ctx->lock);
+ tls13_AntiReplayUpdate(ctx, ssl_Time(ss));
+
+ index = ctx->current;
+ replay = sslBloom_Add(&ctx->filters[index], buf);
+ SSL_TRC(10, ("%d: TLS13[%d]: replay check current window: %s",
+ SSL_GETPID(), ss->fd, replay ? "replay" : "ok"));
+ if (!replay) {
+ replay = sslBloom_Check(&ctx->filters[index ^ 1], buf);
+ SSL_TRC(10, ("%d: TLS13[%d]: replay check previous window: %s",
+ SSL_GETPID(), ss->fd, replay ? "replay" : "ok"));
+ }
+
+ PZ_ExitMonitor(ctx->lock);
+ return replay;
+}
diff --git a/security/nss/lib/ssl/tls13subcerts.c b/security/nss/lib/ssl/tls13subcerts.c
new file mode 100644
index 0000000000..4ecc0a5816
--- /dev/null
+++ b/security/nss/lib/ssl/tls13subcerts.c
@@ -0,0 +1,801 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nss.h"
+#include "pk11func.h"
+#include "secder.h"
+#include "sechash.h"
+#include "ssl.h"
+#include "sslproto.h"
+#include "sslimpl.h"
+#include "ssl3exthandle.h"
+#include "tls13exthandle.h"
+#include "tls13hkdf.h"
+#include "tls13subcerts.h"
+
+/* Parses the delegated credential (DC) from the raw extension |b| of length
+ * |length|. Memory for the DC is allocated and set to |*dcp|.
+ *
+ * It's the caller's responsibility to invoke |tls13_DestroyDelegatedCredential|
+ * when this data is no longer needed.
+ */
+SECStatus
+tls13_ReadDelegatedCredential(PRUint8 *b, PRUint32 length,
+ sslDelegatedCredential **dcp)
+{
+ sslDelegatedCredential *dc = NULL;
+ SECStatus rv;
+ PRUint64 n;
+ sslReadBuffer tmp;
+ sslReader rdr = SSL_READER(b, length);
+
+ PORT_Assert(!*dcp);
+
+ dc = PORT_ZNew(sslDelegatedCredential);
+ if (!dc) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ goto loser;
+ }
+
+ /* Read the valid_time field of DelegatedCredential.cred. */
+ rv = sslRead_ReadNumber(&rdr, 4, &n);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ dc->validTime = n;
+
+ /* Read the expected_cert_verify_algorithm field of
+ * DelegatedCredential.cred. */
+ rv = sslRead_ReadNumber(&rdr, 2, &n);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ dc->expectedCertVerifyAlg = n;
+
+ /* Read the ASN1_subjectPublicKeyInfo field of DelegatedCredential.cred. */
+ rv = sslRead_ReadVariable(&rdr, 3, &tmp);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = SECITEM_MakeItem(NULL, &dc->derSpki, tmp.buf, tmp.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Parse the DER-encoded SubjectPublicKeyInfo. */
+ dc->spki = SECKEY_DecodeDERSubjectPublicKeyInfo(&dc->derSpki);
+ if (!dc->spki) {
+ goto loser;
+ }
+
+ /* Read the algorithm field of the DelegatedCredential. */
+ rv = sslRead_ReadNumber(&rdr, 2, &n);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ dc->alg = n;
+
+ /* Read the signature field of the DelegatedCredential. */
+ rv = sslRead_ReadVariable(&rdr, 2, &tmp);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ rv = SECITEM_MakeItem(NULL, &dc->signature, tmp.buf, tmp.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* There should be nothing left to read. */
+ if (SSL_READER_REMAINING(&rdr) > 0) {
+ goto loser;
+ }
+
+ *dcp = dc;
+ return SECSuccess;
+
+loser:
+ tls13_DestroyDelegatedCredential(dc);
+ *dcp = NULL;
+ return SECFailure;
+}
+
+/* Frees |dc| from the heap. */
+void
+tls13_DestroyDelegatedCredential(sslDelegatedCredential *dc)
+{
+ if (!dc) {
+ return;
+ }
+
+ SECKEY_DestroySubjectPublicKeyInfo(dc->spki);
+ SECITEM_FreeItem(&dc->derSpki, PR_FALSE);
+ SECITEM_FreeItem(&dc->signature, PR_FALSE);
+ PORT_ZFree(dc, sizeof(sslDelegatedCredential));
+}
+
+/* Sets |*certVerifyAlg| to the expected_cert_verify_algorithm field from the
+ * serialized DC |in|. Returns SECSuccess upon success; SECFailure indicates a
+ * decoding failure or the input wasn't long enough.
+ */
+static SECStatus
+tls13_GetExpectedCertVerifyAlg(SECItem in, SSLSignatureScheme *certVerifyAlg)
+{
+ SECStatus rv;
+ PRUint64 n;
+ sslReader rdr = SSL_READER(in.data, in.len);
+
+ if (in.len < 6) { /* Buffer too short to contain the first two params. */
+ return SECFailure;
+ }
+
+ rv = sslRead_ReadNumber(&rdr, 4, &n);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslRead_ReadNumber(&rdr, 2, &n);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+ *certVerifyAlg = n;
+
+ return SECSuccess;
+}
+
+/* Returns PR_TRUE if the host is verifying the handshake with a DC. */
+PRBool
+tls13_IsVerifyingWithDelegatedCredential(const sslSocket *ss)
+{
+ /* We currently do not support client-delegated credentials. */
+ if (ss->sec.isServer ||
+ !ss->opt.enableDelegatedCredentials ||
+ !ss->xtnData.peerDelegCred) {
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+/* Returns PR_TRUE if the host is signing the handshake with a DC. */
+PRBool
+tls13_IsSigningWithDelegatedCredential(const sslSocket *ss)
+{
+ if (!ss->sec.isServer ||
+ !ss->xtnData.sendingDelegCredToPeer ||
+ !ss->xtnData.peerRequestedDelegCred) {
+ return PR_FALSE;
+ }
+
+ return PR_TRUE;
+}
+
+/* Commits to authenticating with a DC if all of the following conditions hold:
+ * - the negotiated protocol is TLS 1.3 or newer;
+ * - the selected certificate has a DC configured;
+ * - the peer has indicated support for this extension;
+ * - the peer has indicated support for the DC signature scheme; and
+ * - the host supports the DC signature scheme.
+ *
+ * It's the caller's responsibility to ensure that the version has been
+ * negotiated and the certificate has been selected.
+ */
+SECStatus
+tls13_MaybeSetDelegatedCredential(sslSocket *ss)
+{
+ SECStatus rv;
+ PRBool doesRsaPss;
+ SECKEYPrivateKey *priv;
+ SSLSignatureScheme scheme;
+
+ /* Assert that the host is the server (we do not currently support
+ * client-delegated credentials), the certificate has been
+ * chosen, TLS 1.3 or higher has been negotiated, and that the set of
+ * signature schemes supported by the client is known.
+ */
+ PORT_Assert(ss->sec.isServer);
+ PORT_Assert(ss->sec.serverCert);
+ PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3);
+ PORT_Assert(ss->xtnData.peerRequestedDelegCred == !!ss->xtnData.delegCredSigSchemes);
+
+ /* Check that the peer has indicated support and that a DC has been
+ * configured for the selected certificate.
+ */
+ if (!ss->xtnData.peerRequestedDelegCred ||
+ !ss->xtnData.delegCredSigSchemes ||
+ !ss->sec.serverCert->delegCred.len ||
+ !ss->sec.serverCert->delegCredKeyPair) {
+ return SECSuccess;
+ }
+
+ /* Check that the host and peer both support the signing algorithm used with
+ * the DC.
+ */
+ rv = tls13_GetExpectedCertVerifyAlg(ss->sec.serverCert->delegCred,
+ &scheme);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ priv = ss->sec.serverCert->delegCredKeyPair->privKey;
+ rv = ssl_PrivateKeySupportsRsaPss(priv, NULL, NULL, &doesRsaPss);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ if (!ssl_SignatureSchemeEnabled(ss, scheme) ||
+ !ssl_CanUseSignatureScheme(scheme,
+ ss->xtnData.delegCredSigSchemes,
+ ss->xtnData.numDelegCredSigSchemes,
+ PR_FALSE /* requireSha1 */,
+ doesRsaPss)) {
+ return SECSuccess;
+ }
+
+ /* Commit to sending a DC and set the handshake signature scheme to the
+ * indicated algorithm.
+ */
+ ss->xtnData.sendingDelegCredToPeer = PR_TRUE;
+ ss->ssl3.hs.signatureScheme = scheme;
+ return SECSuccess;
+}
+
+/* Serializes the DC up to the signature. */
+static SECStatus
+tls13_AppendCredentialParams(sslBuffer *buf, sslDelegatedCredential *dc)
+{
+ SECStatus rv;
+ rv = sslBuffer_AppendNumber(buf, dc->validTime, 4);
+ if (rv != SECSuccess) {
+ return SECFailure; /* Error set by caller. */
+ }
+
+ rv = sslBuffer_AppendNumber(buf, dc->expectedCertVerifyAlg, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendVariable(buf, dc->derSpki.data, dc->derSpki.len, 3);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ rv = sslBuffer_AppendNumber(buf, dc->alg, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Serializes the DC signature. */
+static SECStatus
+tls13_AppendCredentialSignature(sslBuffer *buf, sslDelegatedCredential *dc)
+{
+ SECStatus rv;
+ rv = sslBuffer_AppendVariable(buf, dc->signature.data,
+ dc->signature.len, 2);
+ if (rv != SECSuccess) {
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Hashes the message used to sign/verify the DC. */
+static SECStatus
+tls13_HashCredentialSignatureMessage(SSL3Hashes *hash,
+ SSLSignatureScheme scheme,
+ const CERTCertificate *cert,
+ const sslBuffer *dcBuf)
+{
+ SECStatus rv;
+ PK11Context *ctx = NULL;
+ unsigned int hashLen;
+
+ /* Set up hash context. */
+ hash->hashAlg = ssl_SignatureSchemeToHashType(scheme);
+ ctx = PK11_CreateDigestContext(ssl3_HashTypeToOID(hash->hashAlg));
+ if (!ctx) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ goto loser;
+ }
+
+ static const PRUint8 kCtxStrPadding[64] = {
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
+ 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
+ };
+
+ static const PRUint8 kCtxStr[] = "TLS, server delegated credentials";
+
+ /* Hash the message signed by the peer. */
+ rv = SECSuccess;
+ rv |= PK11_DigestBegin(ctx);
+ rv |= PK11_DigestOp(ctx, kCtxStrPadding, sizeof kCtxStrPadding);
+ rv |= PK11_DigestOp(ctx, kCtxStr, 1 /* 0-byte */ + strlen((const char *)kCtxStr));
+ rv |= PK11_DigestOp(ctx, cert->derCert.data, cert->derCert.len);
+ rv |= PK11_DigestOp(ctx, dcBuf->buf, dcBuf->len);
+ rv |= PK11_DigestFinal(ctx, hash->u.raw, &hashLen, sizeof hash->u.raw);
+ if (rv != SECSuccess) {
+ PORT_SetError(SSL_ERROR_SHA_DIGEST_FAILURE);
+ goto loser;
+ }
+
+ hash->len = hashLen;
+ if (ctx) {
+ PK11_DestroyContext(ctx, PR_TRUE);
+ }
+ return SECSuccess;
+
+loser:
+ if (ctx) {
+ PK11_DestroyContext(ctx, PR_TRUE);
+ }
+ return SECFailure;
+}
+
+/* Verifies the DC signature. */
+static SECStatus
+tls13_VerifyCredentialSignature(sslSocket *ss, sslDelegatedCredential *dc)
+{
+ SECStatus rv = SECSuccess;
+ SSL3Hashes hash;
+ sslBuffer dcBuf = SSL_BUFFER_EMPTY;
+ CERTCertificate *cert = ss->sec.peerCert;
+ SECKEYPublicKey *pubKey = NULL;
+
+ /* Serialize the DC parameters. */
+ rv = tls13_AppendCredentialParams(&dcBuf, dc);
+ if (rv != SECSuccess) {
+ goto loser; /* Error set by caller. */
+ }
+
+ /* Hash the message that was signed by the delegator. */
+ rv = tls13_HashCredentialSignatureMessage(&hash, dc->alg, cert, &dcBuf);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ goto loser;
+ }
+
+ pubKey = SECKEY_ExtractPublicKey(&cert->subjectPublicKeyInfo);
+ if (pubKey == NULL) {
+ FATAL_ERROR(ss, SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE, internal_error);
+ goto loser;
+ }
+
+ /* Verify the signature of the message. */
+ rv = ssl_VerifySignedHashesWithPubKey(ss, pubKey, dc->alg,
+ &hash, &dc->signature);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, SSL_ERROR_DC_BAD_SIGNATURE, illegal_parameter);
+ goto loser;
+ }
+
+ SECOidTag spkiAlg = SECOID_GetAlgorithmTag(&(dc->spki->algorithm));
+ if (spkiAlg == SEC_OID_PKCS1_RSA_ENCRYPTION) {
+ FATAL_ERROR(ss, SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM, illegal_parameter);
+ goto loser;
+ }
+
+ SECKEY_DestroyPublicKey(pubKey);
+ sslBuffer_Clear(&dcBuf);
+ return SECSuccess;
+
+loser:
+ SECKEY_DestroyPublicKey(pubKey);
+ sslBuffer_Clear(&dcBuf);
+ return SECFailure;
+}
+
+/* Checks that the peer's end-entity certificate has the correct key usage. */
+static SECStatus
+tls13_CheckCertDelegationUsage(sslSocket *ss)
+{
+ int i;
+ PRBool found;
+ CERTCertExtension *ext;
+ SECItem delegUsageOid = { siBuffer, NULL, 0 };
+ const CERTCertificate *cert = ss->sec.peerCert;
+
+ /* 1.3.6.1.4.1.44363.44, as defined in draft-ietf-tls-subcerts. */
+ static unsigned char kDelegationUsageOid[] = {
+ 0x2b,
+ 0x06,
+ 0x01,
+ 0x04,
+ 0x01,
+ 0x82,
+ 0xda,
+ 0x4b,
+ 0x2c
+ };
+
+ delegUsageOid.data = kDelegationUsageOid;
+ delegUsageOid.len = sizeof kDelegationUsageOid;
+
+ /* The certificate must have the delegationUsage extension that authorizes
+ * it to negotiate delegated credentials.
+ */
+ found = PR_FALSE;
+ for (i = 0; cert->extensions[i] != NULL; i++) {
+ ext = cert->extensions[i];
+ if (SECITEM_CompareItem(&ext->id, &delegUsageOid) == SECEqual) {
+ found = PR_TRUE;
+ break;
+ }
+ }
+
+ /* The certificate must also have the digitalSignature keyUsage set. */
+ if (!found ||
+ !cert->keyUsagePresent ||
+ !(cert->keyUsage & KU_DIGITAL_SIGNATURE)) {
+ FATAL_ERROR(ss, SSL_ERROR_DC_INVALID_KEY_USAGE, illegal_parameter);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+static SECStatus
+tls13_CheckCredentialExpiration(sslSocket *ss, sslDelegatedCredential *dc)
+{
+ SECStatus rv;
+ CERTCertificate *cert = ss->sec.peerCert;
+ /* 7 days in microseconds */
+ static const PRTime kMaxDcValidity = ((PRTime)7 * 24 * 60 * 60 * PR_USEC_PER_SEC);
+ PRTime start, now, end; /* microseconds */
+
+ rv = DER_DecodeTimeChoice(&start, &cert->validity.notBefore);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+
+ end = start + ((PRTime)dc->validTime * PR_USEC_PER_SEC);
+ now = ssl_Time(ss);
+ if (now > end || end < 0) {
+ FATAL_ERROR(ss, SSL_ERROR_DC_EXPIRED, illegal_parameter);
+ return SECFailure;
+ }
+
+ /* Not more than 7 days remaining in the validity period. */
+ if (end - now > kMaxDcValidity) {
+ FATAL_ERROR(ss, SSL_ERROR_DC_INAPPROPRIATE_VALIDITY_PERIOD, illegal_parameter);
+ return SECFailure;
+ }
+
+ return SECSuccess;
+}
+
+/* Returns SECSucces if |dc| is a DC for the current handshake; otherwise it
+ * returns SECFailure. A valid DC meets three requirements: (1) the signature
+ * was produced by the peer's end-entity certificate, (2) the end-entity
+ * certificate must have the correct key usage, and (3) the DC must not be
+ * expired and its remaining TTL must be <= the maximum validity period (fixed
+ * as 7 days).
+ *
+ * This function calls FATAL_ERROR() when an error occurs.
+ */
+SECStatus
+tls13_VerifyDelegatedCredential(sslSocket *ss,
+ sslDelegatedCredential *dc)
+{
+ SECStatus rv;
+ PRTime start;
+ PRExplodedTime end;
+ CERTCertificate *cert = ss->sec.peerCert;
+ char endStr[256];
+
+ rv = DER_DecodeTimeChoice(&start, &cert->validity.notBefore);
+ if (rv != SECSuccess) {
+ FATAL_ERROR(ss, PORT_GetError(), internal_error);
+ return SECFailure;
+ }
+
+ PR_ExplodeTime(start + (dc->validTime * PR_USEC_PER_SEC),
+ PR_GMTParameters, &end);
+ if (PR_FormatTime(endStr, sizeof(endStr), "%a %b %d %H:%M:%S %Y", &end)) {
+ SSL_TRC(20, ("%d: TLS13[%d]: Received delegated credential (expires %s)",
+ SSL_GETPID(), ss->fd, endStr));
+ } else {
+ SSL_TRC(20, ("%d: TLS13[%d]: Received delegated credential",
+ SSL_GETPID(), ss->fd));
+ }
+
+ rv = SECSuccess;
+ rv |= tls13_VerifyCredentialSignature(ss, dc);
+ rv |= tls13_CheckCertDelegationUsage(ss);
+ rv |= tls13_CheckCredentialExpiration(ss, dc);
+ return rv;
+}
+
+static CERTSubjectPublicKeyInfo *
+tls13_MakePssSpki(const SECKEYPublicKey *pub, SECOidTag hashOid)
+{
+ SECStatus rv;
+ PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
+ if (!arena) {
+ goto loser; /* Code already set. */
+ }
+ CERTSubjectPublicKeyInfo *spki = PORT_ArenaZNew(arena, CERTSubjectPublicKeyInfo);
+ if (!spki) {
+ goto loser; /* Code already set. */
+ }
+ spki->arena = arena;
+
+ SECKEYRSAPSSParams params = { 0 };
+ params.hashAlg = PORT_ArenaZNew(arena, SECAlgorithmID);
+ rv = SECOID_SetAlgorithmID(arena, params.hashAlg, hashOid, NULL);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ /* Set the mask hash algorithm too, which is an argument to
+ * a SEC_OID_PKCS1_MGF1 value. */
+ SECAlgorithmID maskHashAlg;
+ memset(&maskHashAlg, 0, sizeof(maskHashAlg));
+ rv = SECOID_SetAlgorithmID(arena, &maskHashAlg, hashOid, NULL);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+ SECItem *maskHashAlgItem =
+ SEC_ASN1EncodeItem(arena, NULL, &maskHashAlg,
+ SEC_ASN1_GET(SECOID_AlgorithmIDTemplate));
+ if (!maskHashAlgItem) {
+ /* Probably OOM, but not certain. */
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+
+ params.maskAlg = PORT_ArenaZNew(arena, SECAlgorithmID);
+ rv = SECOID_SetAlgorithmID(arena, params.maskAlg, SEC_OID_PKCS1_MGF1,
+ maskHashAlgItem);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ /* Always include saltLength: all hashes are larger than 20. */
+ unsigned int saltLength = HASH_ResultLenByOidTag(hashOid);
+ PORT_Assert(saltLength > 20);
+ if (!SEC_ASN1EncodeInteger(arena, &params.saltLength, saltLength)) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+ /* Omit the trailerField always. */
+
+ SECItem *algorithmItem =
+ SEC_ASN1EncodeItem(arena, NULL, &params,
+ SEC_ASN1_GET(SECKEY_RSAPSSParamsTemplate));
+ if (!algorithmItem) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser; /* Code already set. */
+ }
+ rv = SECOID_SetAlgorithmID(arena, &spki->algorithm,
+ SEC_OID_PKCS1_RSA_PSS_SIGNATURE, algorithmItem);
+ if (rv != SECSuccess) {
+ goto loser; /* Code already set. */
+ }
+
+ SECItem *pubItem = SEC_ASN1EncodeItem(arena, &spki->subjectPublicKey, pub,
+ SEC_ASN1_GET(SECKEY_RSAPublicKeyTemplate));
+ if (!pubItem) {
+ PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+ goto loser;
+ }
+ spki->subjectPublicKey.len *= 8; /* Key length is in bits. */
+ return spki;
+
+loser:
+ PORT_FreeArena(arena, PR_FALSE);
+ return NULL;
+}
+
+static CERTSubjectPublicKeyInfo *
+tls13_MakeDcSpki(const SECKEYPublicKey *dcPub, SSLSignatureScheme dcCertVerifyAlg)
+{
+ switch (SECKEY_GetPublicKeyType(dcPub)) {
+ case rsaKey: {
+ SECOidTag hashOid;
+ switch (dcCertVerifyAlg) {
+ /* Note: RSAE schemes are NOT permitted within DC SPKIs. However,
+ * support for their issuance remains so as to enable negative
+ * testing of client behavior. */
+ case ssl_sig_rsa_pss_rsae_sha256:
+ case ssl_sig_rsa_pss_rsae_sha384:
+ case ssl_sig_rsa_pss_rsae_sha512:
+ return SECKEY_CreateSubjectPublicKeyInfo(dcPub);
+ case ssl_sig_rsa_pss_pss_sha256:
+ hashOid = SEC_OID_SHA256;
+ break;
+ case ssl_sig_rsa_pss_pss_sha384:
+ hashOid = SEC_OID_SHA384;
+ break;
+ case ssl_sig_rsa_pss_pss_sha512:
+ hashOid = SEC_OID_SHA512;
+ break;
+
+ default:
+ PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
+ return NULL;
+ }
+ return tls13_MakePssSpki(dcPub, hashOid);
+ }
+
+ case ecKey: {
+ const sslNamedGroupDef *group = ssl_ECPubKey2NamedGroup(dcPub);
+ if (!group) {
+ PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
+ return NULL;
+ }
+ SSLSignatureScheme keyScheme;
+ switch (group->name) {
+ case ssl_grp_ec_secp256r1:
+ keyScheme = ssl_sig_ecdsa_secp256r1_sha256;
+ break;
+ case ssl_grp_ec_secp384r1:
+ keyScheme = ssl_sig_ecdsa_secp384r1_sha384;
+ break;
+ case ssl_grp_ec_secp521r1:
+ keyScheme = ssl_sig_ecdsa_secp521r1_sha512;
+ break;
+ default:
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ return NULL;
+ }
+ if (keyScheme != dcCertVerifyAlg) {
+ PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
+ return NULL;
+ }
+ return SECKEY_CreateSubjectPublicKeyInfo(dcPub);
+ }
+
+ default:
+ break;
+ }
+
+ PORT_SetError(SEC_ERROR_INVALID_KEY);
+ return NULL;
+}
+
+/* Returns a serialized DC with the given parameters.
+ *
+ * Note that this function is meant primarily for testing. In particular, it
+ * DOES NOT verify any of the following:
+ * - |certPriv| is the private key corresponding to |cert|;
+ * - that |checkCertKeyUsage(cert) == SECSuccess|;
+ * - |dcValidFor| is less than 7 days (the maximum permitted by the spec); or
+ * - validTime doesn't overflow a PRUint32.
+ *
+ * These conditions are things we want to test for, which is why we allow them
+ * here. A real API for creating DCs would want to explicitly check ALL of these
+ * conditions are met.
+ */
+SECStatus
+SSLExp_DelegateCredential(const CERTCertificate *cert,
+ const SECKEYPrivateKey *certPriv,
+ const SECKEYPublicKey *dcPub,
+ SSLSignatureScheme dcCertVerifyAlg,
+ PRUint32 dcValidFor,
+ PRTime now,
+ SECItem *out)
+{
+ SECStatus rv;
+ SSL3Hashes hash;
+ CERTSubjectPublicKeyInfo *spki = NULL;
+ SECKEYPrivateKey *tmpPriv = NULL;
+ sslDelegatedCredential *dc = NULL;
+ sslBuffer dcBuf = SSL_BUFFER_EMPTY;
+
+ if (!cert || !certPriv || !dcPub || !out) {
+ PORT_SetError(SEC_ERROR_INVALID_ARGS);
+ return SECFailure;
+ }
+
+ dc = PORT_ZNew(sslDelegatedCredential);
+ if (!dc) {
+ PORT_SetError(SEC_ERROR_NO_MEMORY);
+ goto loser;
+ }
+
+ /* Serialize the DC parameters. */
+ PRTime start;
+ rv = DER_DecodeTimeChoice(&start, &cert->validity.notBefore);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+ dc->validTime = ((now - start) / PR_USEC_PER_SEC) + dcValidFor;
+
+ /* Building the SPKI also validates |dcCertVerifyAlg|. */
+ spki = tls13_MakeDcSpki(dcPub, dcCertVerifyAlg);
+ if (!spki) {
+ goto loser;
+ }
+ dc->expectedCertVerifyAlg = dcCertVerifyAlg;
+
+ SECItem *spkiDer =
+ SEC_ASN1EncodeItem(NULL /*arena*/, &dc->derSpki, spki,
+ SEC_ASN1_GET(CERT_SubjectPublicKeyInfoTemplate));
+ if (!spkiDer) {
+ goto loser;
+ }
+
+ rv = ssl_SignatureSchemeFromSpki(&cert->subjectPublicKeyInfo,
+ PR_TRUE /* isTls13 */, &dc->alg);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ if (dc->alg == ssl_sig_none) {
+ SECOidTag spkiOid = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm);
+ /* If the Cert SPKI contained an AlgorithmIdentifier of "rsaEncryption", set a
+ * default rsa_pss_rsae_sha256 scheme. NOTE: RSAE SPKIs are not permitted within
+ * "real" Delegated Credentials. However, since this function is primarily used for
+ * testing, we retain this support in order to verify that these DCs are rejected
+ * by tls13_VerifyDelegatedCredential. */
+ if (spkiOid == SEC_OID_PKCS1_RSA_ENCRYPTION) {
+ SSLSignatureScheme scheme = ssl_sig_rsa_pss_rsae_sha256;
+ if (ssl_SignatureSchemeValid(scheme, spkiOid, PR_TRUE /* isTls13 */)) {
+ dc->alg = scheme;
+ }
+ }
+ }
+ PORT_Assert(dc->alg != ssl_sig_none);
+
+ rv = tls13_AppendCredentialParams(&dcBuf, dc);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Hash signature message. */
+ rv = tls13_HashCredentialSignatureMessage(&hash, dc->alg, cert, &dcBuf);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Sign the hash with the delegation key.
+ *
+ * The PK11 API discards const qualifiers, so we have to make a copy of
+ * |certPriv| and pass the copy to |ssl3_SignHashesWithPrivKey|.
+ */
+ tmpPriv = SECKEY_CopyPrivateKey(certPriv);
+ rv = ssl3_SignHashesWithPrivKey(&hash, tmpPriv, dc->alg,
+ PR_TRUE /* isTls */, &dc->signature);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Serialize the DC signature. */
+ rv = tls13_AppendCredentialSignature(&dcBuf, dc);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ /* Copy the serialized DC to |out|. */
+ rv = SECITEM_MakeItem(NULL, out, dcBuf.buf, dcBuf.len);
+ if (rv != SECSuccess) {
+ goto loser;
+ }
+
+ PRINT_BUF(20, (NULL, "delegated credential", dcBuf.buf, dcBuf.len));
+
+ SECKEY_DestroySubjectPublicKeyInfo(spki);
+ SECKEY_DestroyPrivateKey(tmpPriv);
+ tls13_DestroyDelegatedCredential(dc);
+ sslBuffer_Clear(&dcBuf);
+ return SECSuccess;
+
+loser:
+ SECKEY_DestroySubjectPublicKeyInfo(spki);
+ SECKEY_DestroyPrivateKey(tmpPriv);
+ tls13_DestroyDelegatedCredential(dc);
+ sslBuffer_Clear(&dcBuf);
+ return SECFailure;
+}
diff --git a/security/nss/lib/ssl/tls13subcerts.h b/security/nss/lib/ssl/tls13subcerts.h
new file mode 100644
index 0000000000..ce9996bb80
--- /dev/null
+++ b/security/nss/lib/ssl/tls13subcerts.h
@@ -0,0 +1,56 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/*
+ * This file is PRIVATE to SSL.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __tls13subcerts_h_
+#define __tls13subcerts_h_
+
+struct sslDelegatedCredentialStr {
+ /* The number of seconds for which the delegated credential (DC) is valid
+ * following the notBefore parameter of the delegation certificate.
+ */
+ PRUint32 validTime;
+
+ /* The signature algorithm of the DC public key. This expected to the same
+ * as CertificateVerify.scheme.
+ */
+ SSLSignatureScheme expectedCertVerifyAlg;
+
+ /* The DER-encoded SubjectPublicKeyInfo, the DC public key.
+ */
+ SECItem derSpki;
+
+ /* The decoded SubjectPublicKeyInfo parsed from |derSpki|. */
+ CERTSubjectPublicKeyInfo *spki;
+
+ /* The signature algorithm used to verify the DC signature. */
+ SSLSignatureScheme alg;
+
+ /* The DC signature. */
+ SECItem signature;
+};
+
+SECStatus tls13_ReadDelegatedCredential(PRUint8 *b,
+ PRUint32 length,
+ sslDelegatedCredential **dcp);
+void tls13_DestroyDelegatedCredential(sslDelegatedCredential *dc);
+
+PRBool tls13_IsVerifyingWithDelegatedCredential(const sslSocket *ss);
+PRBool tls13_IsSigningWithDelegatedCredential(const sslSocket *ss);
+SECStatus tls13_MaybeSetDelegatedCredential(sslSocket *ss);
+SECStatus tls13_VerifyDelegatedCredential(sslSocket *ss,
+ sslDelegatedCredential *dc);
+
+SECStatus SSLExp_DelegateCredential(const CERTCertificate *cert,
+ const SECKEYPrivateKey *certPriv,
+ const SECKEYPublicKey *dcPub,
+ SSLSignatureScheme dcCertVerifyAlg,
+ PRUint32 dcValidFor,
+ PRTime now,
+ SECItem *out);
+
+#endif
diff --git a/security/nss/lib/ssl/unix_err.c b/security/nss/lib/ssl/unix_err.c
new file mode 100644
index 0000000000..6cd450f699
--- /dev/null
+++ b/security/nss/lib/ssl/unix_err.c
@@ -0,0 +1,837 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/*
+ * This file essentially replicates NSPR's source for the functions that
+ * map system-specific error codes to NSPR error codes. We would use
+ * NSPR's functions, instead of duplicating them, but they're private.
+ * As long as SSL's server session cache code must do platform native I/O
+ * to accomplish its job, and NSPR's error mapping functions remain private,
+ * this code will continue to need to be replicated.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#if 0
+#include "primpl.h"
+#else
+#define _PR_POLL_AVAILABLE 1
+#include "prerror.h"
+#endif
+
+#if defined(__bsdi__) || defined(NTO) || defined(DARWIN)
+#undef _PR_POLL_AVAILABLE
+#endif
+
+#if defined(_PR_POLL_AVAILABLE)
+#include <poll.h>
+#endif
+#include <errno.h>
+
+/* forward declarations. */
+void nss_MD_unix_map_default_error(int err);
+
+void
+nss_MD_unix_map_opendir_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_closedir_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_readdir_error(int err)
+{
+ PRErrorCode prError;
+
+ switch (err) {
+ case ENOENT:
+ prError = PR_NO_MORE_FILES_ERROR;
+ break;
+#ifdef EOVERFLOW
+ case EOVERFLOW:
+ prError = PR_IO_ERROR;
+ break;
+#endif
+ case EINVAL:
+ prError = PR_IO_ERROR;
+ break;
+ case ENXIO:
+ prError = PR_IO_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_unlink_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EPERM:
+ prError = PR_IS_DIRECTORY_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_stat_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_fstat_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_rename_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EEXIST:
+ prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_access_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_mkdir_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_rmdir_error(int err)
+{
+ PRErrorCode prError;
+
+ switch (err) {
+ case EEXIST:
+ prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
+ break;
+ case EINVAL:
+ prError = PR_DIRECTORY_NOT_EMPTY_ERROR;
+ break;
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_read_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_INVALID_METHOD_ERROR;
+ break;
+ case ENXIO:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_write_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_INVALID_METHOD_ERROR;
+ break;
+ case ENXIO:
+ prError = PR_INVALID_METHOD_ERROR;
+ break;
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_lseek_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_fsync_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ case EINVAL:
+ prError = PR_INVALID_METHOD_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_close_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_socket_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_socketavailable_error(int err)
+{
+ PR_SetError(PR_BAD_DESCRIPTOR_ERROR, err);
+}
+
+void
+nss_MD_unix_map_recv_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_recvfrom_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_send_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_sendto_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_writev_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_accept_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ENODEV:
+ prError = PR_NOT_TCP_SOCKET_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_connect_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EACCES:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+#if defined(UNIXWARE) || defined(SNI) || defined(NEC)
+ /*
+ * On some platforms, if we connect to a port on the local host
+ * (the loopback address) that no process is listening on, we get
+ * EIO instead of ECONNREFUSED.
+ */
+ case EIO:
+ prError = PR_CONNECT_REFUSED_ERROR;
+ break;
+#endif
+ case ELOOP:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case ENOENT:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case ENXIO:
+ prError = PR_IO_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_bind_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR;
+ break;
+ /*
+ * UNIX domain sockets are not supported in NSPR
+ */
+ case EIO:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case EISDIR:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case ELOOP:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case ENOENT:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case ENOTDIR:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case EROFS:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_listen_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_shutdown_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_socketpair_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_getsockname_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_getpeername_error(int err)
+{
+ PRErrorCode prError;
+
+ switch (err) {
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_getsockopt_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_BUFFER_OVERFLOW_ERROR;
+ break;
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_setsockopt_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_BUFFER_OVERFLOW_ERROR;
+ break;
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_open_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EAGAIN:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case EBUSY:
+ prError = PR_IO_ERROR;
+ break;
+ case ENODEV:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+ case ENOMEM:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case ETIMEDOUT:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_mmap_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EAGAIN:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case EMFILE:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case ENODEV:
+ prError = PR_OPERATION_NOT_SUPPORTED_ERROR;
+ break;
+ case ENXIO:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_gethostname_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+void
+nss_MD_unix_map_select_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+
+#ifdef _PR_POLL_AVAILABLE
+void
+nss_MD_unix_map_poll_error(int err)
+{
+ PRErrorCode prError;
+
+ switch (err) {
+ case EAGAIN:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_poll_revents_error(int err)
+{
+ if (err & POLLNVAL)
+ PR_SetError(PR_BAD_DESCRIPTOR_ERROR, EBADF);
+ else if (err & POLLHUP)
+ PR_SetError(PR_CONNECT_RESET_ERROR, EPIPE);
+ else if (err & POLLERR)
+ PR_SetError(PR_IO_ERROR, EIO);
+ else
+ PR_SetError(PR_UNKNOWN_ERROR, err);
+}
+#endif /* _PR_POLL_AVAILABLE */
+
+void
+nss_MD_unix_map_flock_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EINVAL:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+ case EWOULDBLOCK:
+ prError = PR_FILE_IS_LOCKED_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_unix_map_lockf_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EACCES:
+ prError = PR_FILE_IS_LOCKED_ERROR;
+ break;
+ case EDEADLK:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ default:
+ nss_MD_unix_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+#ifdef HPUX11
+void
+nss_MD_hpux_map_sendfile_error(int err)
+{
+ nss_MD_unix_map_default_error(err);
+}
+#endif /* HPUX11 */
+
+void
+nss_MD_unix_map_default_error(int err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case EACCES:
+ prError = PR_NO_ACCESS_RIGHTS_ERROR;
+ break;
+ case EADDRINUSE:
+ prError = PR_ADDRESS_IN_USE_ERROR;
+ break;
+ case EADDRNOTAVAIL:
+ prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
+ break;
+ case EAFNOSUPPORT:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case EAGAIN:
+ prError = PR_WOULD_BLOCK_ERROR;
+ break;
+/*
+ * On QNX and Neutrino, EALREADY is defined as EBUSY.
+ */
+#if EALREADY != EBUSY
+ case EALREADY:
+ prError = PR_ALREADY_INITIATED_ERROR;
+ break;
+#endif
+ case EBADF:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+#ifdef EBADMSG
+ case EBADMSG:
+ prError = PR_IO_ERROR;
+ break;
+#endif
+ case EBUSY:
+ prError = PR_FILESYSTEM_MOUNTED_ERROR;
+ break;
+ case ECONNREFUSED:
+ prError = PR_CONNECT_REFUSED_ERROR;
+ break;
+ case ECONNRESET:
+ prError = PR_CONNECT_RESET_ERROR;
+ break;
+ case EDEADLK:
+ prError = PR_DEADLOCK_ERROR;
+ break;
+#ifdef EDIRCORRUPTED
+ case EDIRCORRUPTED:
+ prError = PR_DIRECTORY_CORRUPTED_ERROR;
+ break;
+#endif
+#ifdef EDQUOT
+ case EDQUOT:
+ prError = PR_NO_DEVICE_SPACE_ERROR;
+ break;
+#endif
+ case EEXIST:
+ prError = PR_FILE_EXISTS_ERROR;
+ break;
+ case EFAULT:
+ prError = PR_ACCESS_FAULT_ERROR;
+ break;
+ case EFBIG:
+ prError = PR_FILE_TOO_BIG_ERROR;
+ break;
+ case EINPROGRESS:
+ prError = PR_IN_PROGRESS_ERROR;
+ break;
+ case EINTR:
+ prError = PR_PENDING_INTERRUPT_ERROR;
+ break;
+ case EINVAL:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case EIO:
+ prError = PR_IO_ERROR;
+ break;
+ case EISCONN:
+ prError = PR_IS_CONNECTED_ERROR;
+ break;
+ case EISDIR:
+ prError = PR_IS_DIRECTORY_ERROR;
+ break;
+ case ELOOP:
+ prError = PR_LOOP_ERROR;
+ break;
+ case EMFILE:
+ prError = PR_PROC_DESC_TABLE_FULL_ERROR;
+ break;
+ case EMLINK:
+ prError = PR_MAX_DIRECTORY_ENTRIES_ERROR;
+ break;
+ case EMSGSIZE:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+#ifdef EMULTIHOP
+ case EMULTIHOP:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+#endif
+ case ENAMETOOLONG:
+ prError = PR_NAME_TOO_LONG_ERROR;
+ break;
+ case ENETUNREACH:
+ prError = PR_NETWORK_UNREACHABLE_ERROR;
+ break;
+ case ENFILE:
+ prError = PR_SYS_DESC_TABLE_FULL_ERROR;
+ break;
+#if !defined(SCO)
+ case ENOBUFS:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+#endif
+ case ENODEV:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+ case ENOENT:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+ case ENOLCK:
+ prError = PR_FILE_IS_LOCKED_ERROR;
+ break;
+#ifdef ENOLINK
+ case ENOLINK:
+ prError = PR_REMOTE_FILE_ERROR;
+ break;
+#endif
+ case ENOMEM:
+ prError = PR_OUT_OF_MEMORY_ERROR;
+ break;
+ case ENOPROTOOPT:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case ENOSPC:
+ prError = PR_NO_DEVICE_SPACE_ERROR;
+ break;
+#ifdef ENOSR
+ case ENOSR:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+#endif
+ case ENOTCONN:
+ prError = PR_NOT_CONNECTED_ERROR;
+ break;
+ case ENOTDIR:
+ prError = PR_NOT_DIRECTORY_ERROR;
+ break;
+ case ENOTSOCK:
+ prError = PR_NOT_SOCKET_ERROR;
+ break;
+ case ENXIO:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+ case EOPNOTSUPP:
+ prError = PR_NOT_TCP_SOCKET_ERROR;
+ break;
+#ifdef EOVERFLOW
+ case EOVERFLOW:
+ prError = PR_BUFFER_OVERFLOW_ERROR;
+ break;
+#endif
+ case EPERM:
+ prError = PR_NO_ACCESS_RIGHTS_ERROR;
+ break;
+ case EPIPE:
+ prError = PR_CONNECT_RESET_ERROR;
+ break;
+#ifdef EPROTO
+ case EPROTO:
+ prError = PR_IO_ERROR;
+ break;
+#endif
+ case EPROTONOSUPPORT:
+ prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
+ break;
+ case EPROTOTYPE:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case ERANGE:
+ prError = PR_INVALID_METHOD_ERROR;
+ break;
+ case EROFS:
+ prError = PR_READ_ONLY_FILESYSTEM_ERROR;
+ break;
+ case ESPIPE:
+ prError = PR_INVALID_METHOD_ERROR;
+ break;
+ case ETIMEDOUT:
+ prError = PR_IO_TIMEOUT_ERROR;
+ break;
+#if EWOULDBLOCK != EAGAIN
+ case EWOULDBLOCK:
+ prError = PR_WOULD_BLOCK_ERROR;
+ break;
+#endif
+ case EXDEV:
+ prError = PR_NOT_SAME_DEVICE_ERROR;
+ break;
+
+ default:
+ prError = PR_UNKNOWN_ERROR;
+ break;
+ }
+ PR_SetError(prError, err);
+}
diff --git a/security/nss/lib/ssl/unix_err.h b/security/nss/lib/ssl/unix_err.h
new file mode 100644
index 0000000000..5d7d547bfb
--- /dev/null
+++ b/security/nss/lib/ssl/unix_err.h
@@ -0,0 +1,57 @@
+/*
+ * This file essentially replicates NSPR's source for the functions that
+ * map system-specific error codes to NSPR error codes. We would use
+ * NSPR's functions, instead of duplicating them, but they're private.
+ * As long as SSL's server session cache code must do platform native I/O
+ * to accomplish its job, and NSPR's error mapping functions remain private,
+ * this code will continue to need to be replicated.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* NSPR doesn't make these functions public, so we have to duplicate
+** them in NSS.
+*/
+extern void nss_MD_hpux_map_sendfile_error(int err);
+extern void nss_MD_unix_map_accept_error(int err);
+extern void nss_MD_unix_map_access_error(int err);
+extern void nss_MD_unix_map_bind_error(int err);
+extern void nss_MD_unix_map_close_error(int err);
+extern void nss_MD_unix_map_closedir_error(int err);
+extern void nss_MD_unix_map_connect_error(int err);
+extern void nss_MD_unix_map_default_error(int err);
+extern void nss_MD_unix_map_flock_error(int err);
+extern void nss_MD_unix_map_fstat_error(int err);
+extern void nss_MD_unix_map_fsync_error(int err);
+extern void nss_MD_unix_map_gethostname_error(int err);
+extern void nss_MD_unix_map_getpeername_error(int err);
+extern void nss_MD_unix_map_getsockname_error(int err);
+extern void nss_MD_unix_map_getsockopt_error(int err);
+extern void nss_MD_unix_map_listen_error(int err);
+extern void nss_MD_unix_map_lockf_error(int err);
+extern void nss_MD_unix_map_lseek_error(int err);
+extern void nss_MD_unix_map_mkdir_error(int err);
+extern void nss_MD_unix_map_mmap_error(int err);
+extern void nss_MD_unix_map_open_error(int err);
+extern void nss_MD_unix_map_opendir_error(int err);
+extern void nss_MD_unix_map_poll_error(int err);
+extern void nss_MD_unix_map_poll_revents_error(int err);
+extern void nss_MD_unix_map_read_error(int err);
+extern void nss_MD_unix_map_readdir_error(int err);
+extern void nss_MD_unix_map_recv_error(int err);
+extern void nss_MD_unix_map_recvfrom_error(int err);
+extern void nss_MD_unix_map_rename_error(int err);
+extern void nss_MD_unix_map_rmdir_error(int err);
+extern void nss_MD_unix_map_select_error(int err);
+extern void nss_MD_unix_map_send_error(int err);
+extern void nss_MD_unix_map_sendto_error(int err);
+extern void nss_MD_unix_map_setsockopt_error(int err);
+extern void nss_MD_unix_map_shutdown_error(int err);
+extern void nss_MD_unix_map_socket_error(int err);
+extern void nss_MD_unix_map_socketavailable_error(int err);
+extern void nss_MD_unix_map_socketpair_error(int err);
+extern void nss_MD_unix_map_stat_error(int err);
+extern void nss_MD_unix_map_unlink_error(int err);
+extern void nss_MD_unix_map_write_error(int err);
+extern void nss_MD_unix_map_writev_error(int err);
diff --git a/security/nss/lib/ssl/win32err.c b/security/nss/lib/ssl/win32err.c
new file mode 100644
index 0000000000..caa12b956e
--- /dev/null
+++ b/security/nss/lib/ssl/win32err.c
@@ -0,0 +1,550 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/*
+ * This file essentially replicates NSPR's source for the functions that
+ * map system-specific error codes to NSPR error codes. We would use
+ * NSPR's functions, instead of duplicating them, but they're private.
+ * As long as SSL's server session cache code must do platform native I/O
+ * to accomplish its job, and NSPR's error mapping functions remain private,
+ * this code will continue to need to be replicated.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "prerror.h"
+#include "prlog.h"
+#include <errno.h>
+#include <windows.h>
+
+/*
+ * On Win32, we map three kinds of error codes:
+ * - GetLastError(): for Win32 functions
+ * - WSAGetLastError(): for Winsock functions
+ * - errno: for standard C library functions
+ *
+ * We do not check for WSAEINPROGRESS and WSAEINTR because we do not
+ * use blocking Winsock 1.1 calls.
+ *
+ * Except for the 'socket' call, we do not check for WSAEINITIALISED.
+ * It is assumed that if Winsock is not initialized, that fact will
+ * be detected at the time we create new sockets.
+ */
+
+/* forward declaration. */
+void nss_MD_win32_map_default_error(PRInt32 err);
+
+void
+nss_MD_win32_map_opendir_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_closedir_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_readdir_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_delete_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+/* The error code for stat() is in errno. */
+void
+nss_MD_win32_map_stat_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_fstat_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_rename_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+/* The error code for access() is in errno. */
+void
+nss_MD_win32_map_access_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_mkdir_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_rmdir_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_read_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_transmitfile_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_write_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_lseek_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_fsync_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+/*
+ * For both CloseHandle() and closesocket().
+ */
+void
+nss_MD_win32_map_close_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_socket_error(PRInt32 err)
+{
+ PR_ASSERT(err != WSANOTINITIALISED);
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_recv_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_recvfrom_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_send_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEMSGSIZE:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_sendto_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEMSGSIZE:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_accept_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEOPNOTSUPP:
+ prError = PR_NOT_TCP_SOCKET_ERROR;
+ break;
+ case WSAEINVAL:
+ prError = PR_INVALID_STATE_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_acceptex_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_connect_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEWOULDBLOCK:
+ prError = PR_IN_PROGRESS_ERROR;
+ break;
+ case WSAEINVAL:
+ prError = PR_ALREADY_INITIATED_ERROR;
+ break;
+ case WSAETIMEDOUT:
+ prError = PR_IO_TIMEOUT_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_bind_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEINVAL:
+ prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_listen_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEOPNOTSUPP:
+ prError = PR_NOT_TCP_SOCKET_ERROR;
+ break;
+ case WSAEINVAL:
+ prError = PR_INVALID_STATE_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_shutdown_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_getsockname_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAEINVAL:
+ prError = PR_INVALID_STATE_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_getpeername_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_getsockopt_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_setsockopt_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_open_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_gethostname_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+/* Win32 select() only works on sockets. So in this
+** context, WSAENOTSOCK is equivalent to EBADF on Unix.
+*/
+void
+nss_MD_win32_map_select_error(PRInt32 err)
+{
+ PRErrorCode prError;
+ switch (err) {
+ case WSAENOTSOCK:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+ default:
+ nss_MD_win32_map_default_error(err);
+ return;
+ }
+ PR_SetError(prError, err);
+}
+
+void
+nss_MD_win32_map_lockf_error(PRInt32 err)
+{
+ nss_MD_win32_map_default_error(err);
+}
+
+void
+nss_MD_win32_map_default_error(PRInt32 err)
+{
+ PRErrorCode prError;
+
+ switch (err) {
+ case EACCES:
+ prError = PR_NO_ACCESS_RIGHTS_ERROR;
+ break;
+ case ENOENT:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+ case ERROR_ACCESS_DENIED:
+ prError = PR_NO_ACCESS_RIGHTS_ERROR;
+ break;
+ case ERROR_ALREADY_EXISTS:
+ prError = PR_FILE_EXISTS_ERROR;
+ break;
+ case ERROR_DISK_CORRUPT:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_DISK_FULL:
+ prError = PR_NO_DEVICE_SPACE_ERROR;
+ break;
+ case ERROR_DISK_OPERATION_FAILED:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_DRIVE_LOCKED:
+ prError = PR_FILE_IS_LOCKED_ERROR;
+ break;
+ case ERROR_FILENAME_EXCED_RANGE:
+ prError = PR_NAME_TOO_LONG_ERROR;
+ break;
+ case ERROR_FILE_CORRUPT:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_FILE_EXISTS:
+ prError = PR_FILE_EXISTS_ERROR;
+ break;
+ case ERROR_FILE_INVALID:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+#if ERROR_FILE_NOT_FOUND != ENOENT
+ case ERROR_FILE_NOT_FOUND:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+#endif
+ case ERROR_HANDLE_DISK_FULL:
+ prError = PR_NO_DEVICE_SPACE_ERROR;
+ break;
+ case ERROR_INVALID_ADDRESS:
+ prError = PR_ACCESS_FAULT_ERROR;
+ break;
+ case ERROR_INVALID_HANDLE:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+ case ERROR_INVALID_NAME:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case ERROR_INVALID_PARAMETER:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case ERROR_INVALID_USER_BUFFER:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case ERROR_LOCKED:
+ prError = PR_FILE_IS_LOCKED_ERROR;
+ break;
+ case ERROR_NETNAME_DELETED:
+ prError = PR_CONNECT_RESET_ERROR;
+ break;
+ case ERROR_NOACCESS:
+ prError = PR_ACCESS_FAULT_ERROR;
+ break;
+ case ERROR_NOT_ENOUGH_MEMORY:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case ERROR_NOT_ENOUGH_QUOTA:
+ prError = PR_OUT_OF_MEMORY_ERROR;
+ break;
+ case ERROR_NOT_READY:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_NO_MORE_FILES:
+ prError = PR_NO_MORE_FILES_ERROR;
+ break;
+ case ERROR_OPEN_FAILED:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_OPEN_FILES:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_OUTOFMEMORY:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case ERROR_PATH_BUSY:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_PATH_NOT_FOUND:
+ prError = PR_FILE_NOT_FOUND_ERROR;
+ break;
+ case ERROR_SEEK_ON_DEVICE:
+ prError = PR_IO_ERROR;
+ break;
+ case ERROR_SHARING_VIOLATION:
+ prError = PR_FILE_IS_BUSY_ERROR;
+ break;
+ case ERROR_STACK_OVERFLOW:
+ prError = PR_ACCESS_FAULT_ERROR;
+ break;
+ case ERROR_TOO_MANY_OPEN_FILES:
+ prError = PR_SYS_DESC_TABLE_FULL_ERROR;
+ break;
+ case ERROR_WRITE_PROTECT:
+ prError = PR_NO_ACCESS_RIGHTS_ERROR;
+ break;
+ case WSAEACCES:
+ prError = PR_NO_ACCESS_RIGHTS_ERROR;
+ break;
+ case WSAEADDRINUSE:
+ prError = PR_ADDRESS_IN_USE_ERROR;
+ break;
+ case WSAEADDRNOTAVAIL:
+ prError = PR_ADDRESS_NOT_AVAILABLE_ERROR;
+ break;
+ case WSAEAFNOSUPPORT:
+ prError = PR_ADDRESS_NOT_SUPPORTED_ERROR;
+ break;
+ case WSAEALREADY:
+ prError = PR_ALREADY_INITIATED_ERROR;
+ break;
+ case WSAEBADF:
+ prError = PR_BAD_DESCRIPTOR_ERROR;
+ break;
+ case WSAECONNABORTED:
+ prError = PR_CONNECT_ABORTED_ERROR;
+ break;
+ case WSAECONNREFUSED:
+ prError = PR_CONNECT_REFUSED_ERROR;
+ break;
+ case WSAECONNRESET:
+ prError = PR_CONNECT_RESET_ERROR;
+ break;
+ case WSAEDESTADDRREQ:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case WSAEFAULT:
+ prError = PR_ACCESS_FAULT_ERROR;
+ break;
+ case WSAEHOSTUNREACH:
+ prError = PR_HOST_UNREACHABLE_ERROR;
+ break;
+ case WSAEINVAL:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case WSAEISCONN:
+ prError = PR_IS_CONNECTED_ERROR;
+ break;
+ case WSAEMFILE:
+ prError = PR_PROC_DESC_TABLE_FULL_ERROR;
+ break;
+ case WSAEMSGSIZE:
+ prError = PR_BUFFER_OVERFLOW_ERROR;
+ break;
+ case WSAENETDOWN:
+ prError = PR_NETWORK_DOWN_ERROR;
+ break;
+ case WSAENETRESET:
+ prError = PR_CONNECT_ABORTED_ERROR;
+ break;
+ case WSAENETUNREACH:
+ prError = PR_NETWORK_UNREACHABLE_ERROR;
+ break;
+ case WSAENOBUFS:
+ prError = PR_INSUFFICIENT_RESOURCES_ERROR;
+ break;
+ case WSAENOPROTOOPT:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case WSAENOTCONN:
+ prError = PR_NOT_CONNECTED_ERROR;
+ break;
+ case WSAENOTSOCK:
+ prError = PR_NOT_SOCKET_ERROR;
+ break;
+ case WSAEOPNOTSUPP:
+ prError = PR_OPERATION_NOT_SUPPORTED_ERROR;
+ break;
+ case WSAEPROTONOSUPPORT:
+ prError = PR_PROTOCOL_NOT_SUPPORTED_ERROR;
+ break;
+ case WSAEPROTOTYPE:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case WSAESHUTDOWN:
+ prError = PR_SOCKET_SHUTDOWN_ERROR;
+ break;
+ case WSAESOCKTNOSUPPORT:
+ prError = PR_INVALID_ARGUMENT_ERROR;
+ break;
+ case WSAETIMEDOUT:
+ prError = PR_CONNECT_ABORTED_ERROR;
+ break;
+ case WSAEWOULDBLOCK:
+ prError = PR_WOULD_BLOCK_ERROR;
+ break;
+ default:
+ prError = PR_UNKNOWN_ERROR;
+ break;
+ }
+ PR_SetError(prError, err);
+}
diff --git a/security/nss/lib/ssl/win32err.h b/security/nss/lib/ssl/win32err.h
new file mode 100644
index 0000000000..a698849061
--- /dev/null
+++ b/security/nss/lib/ssl/win32err.h
@@ -0,0 +1,51 @@
+/*
+ * This file essentially replicates NSPR's source for the functions that
+ * map system-specific error codes to NSPR error codes. We would use
+ * NSPR's functions, instead of duplicating them, but they're private.
+ * As long as SSL's server session cache code must do platform native I/O
+ * to accomplish its job, and NSPR's error mapping functions remain private,
+ * This code will continue to need to be replicated.
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* NSPR doesn't make these functions public, so we have to duplicate
+** them in NSS.
+*/
+extern void nss_MD_win32_map_accept_error(PRInt32 err);
+extern void nss_MD_win32_map_acceptex_error(PRInt32 err);
+extern void nss_MD_win32_map_access_error(PRInt32 err);
+extern void nss_MD_win32_map_bind_error(PRInt32 err);
+extern void nss_MD_win32_map_close_error(PRInt32 err);
+extern void nss_MD_win32_map_closedir_error(PRInt32 err);
+extern void nss_MD_win32_map_connect_error(PRInt32 err);
+extern void nss_MD_win32_map_default_error(PRInt32 err);
+extern void nss_MD_win32_map_delete_error(PRInt32 err);
+extern void nss_MD_win32_map_fstat_error(PRInt32 err);
+extern void nss_MD_win32_map_fsync_error(PRInt32 err);
+extern void nss_MD_win32_map_gethostname_error(PRInt32 err);
+extern void nss_MD_win32_map_getpeername_error(PRInt32 err);
+extern void nss_MD_win32_map_getsockname_error(PRInt32 err);
+extern void nss_MD_win32_map_getsockopt_error(PRInt32 err);
+extern void nss_MD_win32_map_listen_error(PRInt32 err);
+extern void nss_MD_win32_map_lockf_error(PRInt32 err);
+extern void nss_MD_win32_map_lseek_error(PRInt32 err);
+extern void nss_MD_win32_map_mkdir_error(PRInt32 err);
+extern void nss_MD_win32_map_open_error(PRInt32 err);
+extern void nss_MD_win32_map_opendir_error(PRInt32 err);
+extern void nss_MD_win32_map_read_error(PRInt32 err);
+extern void nss_MD_win32_map_readdir_error(PRInt32 err);
+extern void nss_MD_win32_map_recv_error(PRInt32 err);
+extern void nss_MD_win32_map_recvfrom_error(PRInt32 err);
+extern void nss_MD_win32_map_rename_error(PRInt32 err);
+extern void nss_MD_win32_map_rmdir_error(PRInt32 err);
+extern void nss_MD_win32_map_select_error(PRInt32 err);
+extern void nss_MD_win32_map_send_error(PRInt32 err);
+extern void nss_MD_win32_map_sendto_error(PRInt32 err);
+extern void nss_MD_win32_map_setsockopt_error(PRInt32 err);
+extern void nss_MD_win32_map_shutdown_error(PRInt32 err);
+extern void nss_MD_win32_map_socket_error(PRInt32 err);
+extern void nss_MD_win32_map_stat_error(PRInt32 err);
+extern void nss_MD_win32_map_transmitfile_error(PRInt32 err);
+extern void nss_MD_win32_map_write_error(PRInt32 err);