diff options
author | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-01-04 14:24:24 +0000 |
---|---|---|
committer | Lorry Tar Creator <lorry-tar-importer@lorry> | 2017-01-04 14:24:24 +0000 |
commit | dc1565216a5d20ae0d75872151523252309a1292 (patch) | |
tree | d57454ba9a40386552179eddf60d28bd1e8f3d54 /nss/lib/ssl | |
parent | 26c046fbc57d53136b4fb3b5e0d18298318125d4 (diff) | |
download | nss-822b884019ac3b4a984e5d3b33b2cd07bc1518c1.tar.gz |
nss-3.28.1nss-3.28.1
Diffstat (limited to 'nss/lib/ssl')
60 files changed, 28606 insertions, 24121 deletions
diff --git a/nss/lib/ssl/Makefile b/nss/lib/ssl/Makefile index d56cbf2..24fccc5 100644 --- a/nss/lib/ssl/Makefile +++ b/nss/lib/ssl/Makefile @@ -18,8 +18,8 @@ include $(CORE_DEPTH)/coreconf/config.mk ####################################################################### # (3) Include "component" configuration information. (OPTIONAL) # -####################################################################### - +###################################################################### +# ####################################################################### @@ -39,6 +39,13 @@ 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) # ####################################################################### @@ -56,8 +63,3 @@ include $(CORE_DEPTH)/coreconf/rules.mk ####################################################################### export:: private_export - -ifndef NSS_NO_PKCS11_BYPASS -# indicates dependency on freebl static lib -$(SHARED_LIBRARY): $(CRYPTOLIB) -endif diff --git a/nss/lib/ssl/SSLerrs.h b/nss/lib/ssl/SSLerrs.h index 6028396..b0319b8 100644 --- a/nss/lib/ssl/SSLerrs.h +++ b/nss/lib/ssl/SSLerrs.h @@ -2,441 +2,506 @@ * 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_EXPORT_ONLY_SERVER, SSL_ERROR_BASE + 0, + "Unable to communicate securely. Peer does not support high-grade encryption.") -ER3(SSL_ERROR_NO_CYPHER_OVERLAP, SSL_ERROR_BASE + 2, -"Cannot communicate securely with peer: no common encryption algorithm(s).") +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_CERTIFICATE, SSL_ERROR_BASE + 3, -"Unable to find the certificate or key necessary for authentication.") +ER3(SSL_ERROR_NO_CYPHER_OVERLAP, SSL_ERROR_BASE + 2, + "Cannot communicate securely with peer: no common encryption algorithm(s).") -ER3(SSL_ERROR_BAD_CERTIFICATE, SSL_ERROR_BASE + 4, -"Unable to communicate securely with peer: peers's certificate was rejected.") +ER3(SSL_ERROR_NO_CERTIFICATE, SSL_ERROR_BASE + 3, + "Unable to find the certificate or key necessary for authentication.") -ER3(SSL_ERROR_UNUSED_5, SSL_ERROR_BASE + 5, -"Unrecognized SSL error code.") +ER3(SSL_ERROR_BAD_CERTIFICATE, SSL_ERROR_BASE + 4, + "Unable to communicate securely with peer: peers's certificate was rejected.") -ER3(SSL_ERROR_BAD_CLIENT, SSL_ERROR_BASE + 6, -"The server has encountered bad data from the client.") +UNUSED_ERROR(5) -ER3(SSL_ERROR_BAD_SERVER, SSL_ERROR_BASE + 7, -"The client has encountered bad data from the server.") +ER3(SSL_ERROR_BAD_CLIENT, SSL_ERROR_BASE + 6, + "The server has encountered bad data from the client.") -ER3(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE, SSL_ERROR_BASE + 8, -"Unsupported certificate type.") +ER3(SSL_ERROR_BAD_SERVER, SSL_ERROR_BASE + 7, + "The client has encountered bad data from the server.") -ER3(SSL_ERROR_UNSUPPORTED_VERSION, SSL_ERROR_BASE + 9, -"Peer using unsupported version of security protocol.") +ER3(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE, SSL_ERROR_BASE + 8, + "Unsupported certificate type.") -ER3(SSL_ERROR_UNUSED_10, SSL_ERROR_BASE + 10, -"Unrecognized SSL error code.") +ER3(SSL_ERROR_UNSUPPORTED_VERSION, SSL_ERROR_BASE + 9, + "Peer using unsupported version of security protocol.") -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.") +UNUSED_ERROR(10) -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_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_POST_WARNING, SSL_ERROR_BASE + 13, -"Unrecognized SSL error code.") +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_SSL2_DISABLED, (SSL_ERROR_BASE + 14), -"Peer only supports SSL version 2, which is locally disabled.") +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_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_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_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_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_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_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_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_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_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_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_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.") +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_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_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_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_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_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_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_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_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_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.") +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_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_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_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.") +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_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_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_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_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_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_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_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_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_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.") +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_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_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_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.") + "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_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_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.") +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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_CERT_KEA_MISMATCH , (SSL_ERROR_BASE + 88), -"The certificate provided cannot be used with the selected key exchange algorithm.") +ER3(SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA, (SSL_ERROR_BASE + 89), + "No certificate authority is trusted for SSL client authentication.") -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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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.") + "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.") + "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_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_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_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.") + "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_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 NPN extension data.") +ER3(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID, (SSL_ERROR_BASE + 116), + "SSL received invalid NPN 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_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.") + "SSL feature not supported for servers.") ER3(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_CLIENTS, (SSL_ERROR_BASE + 119), -"SSL feature not supported for clients.") + "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_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_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.") + "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.") + "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.") + "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_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.") + "Unsupported hash algorithm used by TLS peer.") ER3(SSL_ERROR_DIGEST_FAILURE, (SSL_ERROR_BASE + 127), -"Digest function failed.") + "Digest function failed.") ER3(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM, (SSL_ERROR_BASE + 128), -"Incorrect signature algorithm specified in a digitally-signed element.") + "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.") + "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.") + "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.") + "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.") + "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.") + "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.") + "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.") + "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") + "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") + "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.") + +ER3(SSL_ERROR_END_OF_EARLY_DATA_ALERT, (SSL_ERROR_BASE + 149), + "SSL received an unexpected end of early data alert.") + +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 missing PSK key exchange modes extension.") diff --git a/nss/lib/ssl/authcert.c b/nss/lib/ssl/authcert.c index bd0f6ed..88c7c08 100644 --- a/nss/lib/ssl/authcert.c +++ b/nss/lib/ssl/authcert.c @@ -16,74 +16,74 @@ #include "key.h" #include "nss.h" #include "ssl.h" -#include "pk11func.h" /* for PK11_ function calls */ +#include "pk11func.h" /* for PK11_ function calls */ /* * This callback used by SSL to pull client sertificate upon * server request */ -SECStatus -NSS_GetClientAuthData(void * arg, - PRFileDesc * socket, - struct CERTDistNamesStr * caNames, - struct CERTCertificateStr ** pRetCert, - struct SECKEYPrivateKeyStr **pRetKey) +SECStatus +NSS_GetClientAuthData(void *arg, + PRFileDesc *socket, + struct CERTDistNamesStr *caNames, + struct CERTCertificateStr **pRetCert, + struct SECKEYPrivateKeyStr **pRetKey) { - CERTCertificate * cert = NULL; - SECKEYPrivateKey * privkey = NULL; - char * chosenNickName = (char *)arg; /* CONST */ - void * proto_win = NULL; - SECStatus rv = SECFailure; - - proto_win = SSL_RevealPinArg(socket); - - if (chosenNickName) { - cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), - chosenNickName, certUsageSSLClient, - PR_FALSE, proto_win); - if ( cert ) { - privkey = PK11_FindKeyByAnyCert(cert, proto_win); - if ( privkey ) { - rv = SECSuccess; - } else { - CERT_DestroyCertificate(cert); - } + CERTCertificate *cert = NULL; + SECKEYPrivateKey *privkey = NULL; + char *chosenNickName = (char *)arg; /* CONST */ + void *proto_win = NULL; + SECStatus rv = SECFailure; + + proto_win = SSL_RevealPinArg(socket); + + if (chosenNickName) { + cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), + chosenNickName, certUsageSSLClient, + PR_FALSE, proto_win); + if (cert) { + privkey = PK11_FindKeyByAnyCert(cert, proto_win); + if (privkey) { + rv = SECSuccess; + } else { + CERT_DestroyCertificate(cert); + } + } + } else { /* no name given, automatically find the right cert. */ + CERTCertNicknames *names; + int i; + + names = CERT_GetCertNicknames(CERT_GetDefaultCertDB(), + SEC_CERT_NICKNAMES_USER, proto_win); + if (names != NULL) { + for (i = 0; i < names->numnicknames; i++) { + cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), + names->nicknames[i], certUsageSSLClient, + PR_FALSE, proto_win); + if (!cert) + continue; + /* Only check unexpired certs */ + if (CERT_CheckCertValidTimes(cert, PR_Now(), PR_TRUE) != + secCertTimeValid) { + CERT_DestroyCertificate(cert); + continue; + } + rv = NSS_CmpCertChainWCANames(cert, caNames); + if (rv == SECSuccess) { + privkey = + PK11_FindKeyByAnyCert(cert, proto_win); + if (privkey) + break; + } + rv = SECFailure; + CERT_DestroyCertificate(cert); + } + CERT_FreeNicknames(names); + } } - } else { /* no name given, automatically find the right cert. */ - CERTCertNicknames * names; - int i; - - names = CERT_GetCertNicknames(CERT_GetDefaultCertDB(), - SEC_CERT_NICKNAMES_USER, proto_win); - if (names != NULL) { - for (i = 0; i < names->numnicknames; i++) { - cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(), - names->nicknames[i], certUsageSSLClient, - PR_FALSE, proto_win); - if ( !cert ) - continue; - /* Only check unexpired certs */ - if (CERT_CheckCertValidTimes(cert, PR_Now(), PR_TRUE) != - secCertTimeValid ) { - CERT_DestroyCertificate(cert); - continue; - } - rv = NSS_CmpCertChainWCANames(cert, caNames); - if ( rv == SECSuccess ) { - privkey = PK11_FindKeyByAnyCert(cert, proto_win); - if ( privkey ) - break; - } - rv = SECFailure; - CERT_DestroyCertificate(cert); - } - CERT_FreeNicknames(names); + if (rv == SECSuccess) { + *pRetCert = cert; + *pRetKey = privkey; } - } - if (rv == SECSuccess) { - *pRetCert = cert; - *pRetKey = privkey; - } - return rv; + return rv; } - diff --git a/nss/lib/ssl/cmpcert.c b/nss/lib/ssl/cmpcert.c index 6d84238..e6edbee 100644 --- a/nss/lib/ssl/cmpcert.c +++ b/nss/lib/ssl/cmpcert.c @@ -18,73 +18,72 @@ /* * Look to see if any of the signers in the cert chain for "cert" are found - * in the list of caNames. + * 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; - PRInt32 contentlen; - int j; - int headerlen; - int depth; - SECStatus rv; - SECItem issuerName; - SECItem compatIssuerName; + SECItem *caname; + CERTCertificate *curcert; + CERTCertificate *oldcert; + PRInt32 contentlen; + int j; + int headerlen; + int depth; + SECStatus rv; + SECItem issuerName; + SECItem compatIssuerName; - if (!cert || !caNames || !caNames->nnames || !caNames->names || - !caNames->names->data) - return SECFailure; - depth=0; - curcert = CERT_DupCertificate(cert); - - while( curcert ) { - issuerName = curcert->derIssuer; - - /* compute an alternate issuer name for compatibility with 2.0 - * enterprise server, which send the CA names without - * the outer layer of DER header - */ - rv = DER_Lengths(&issuerName, &headerlen, (PRUint32 *)&contentlen); - if ( rv == SECSuccess ) { - compatIssuerName.data = &issuerName.data[headerlen]; - compatIssuerName.len = issuerName.len - headerlen; - } else { - compatIssuerName.data = NULL; - compatIssuerName.len = 0; - } - - for (j = 0; j < caNames->nnames; j++) { - caname = &caNames->names[j]; - if (SECITEM_CompareItem(&issuerName, caname) == SECEqual) { - rv = SECSuccess; - CERT_DestroyCertificate(curcert); - goto done; - } else if (SECITEM_CompareItem(&compatIssuerName, caname) == SECEqual) { - rv = SECSuccess; - CERT_DestroyCertificate(curcert); - goto done; - } - } - 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; + if (!cert || !caNames || !caNames->nnames || !caNames->names || + !caNames->names->data) + return SECFailure; + depth = 0; + curcert = CERT_DupCertificate(cert); + + while (curcert) { + issuerName = curcert->derIssuer; + + /* compute an alternate issuer name for compatibility with 2.0 + * enterprise server, which send the CA names without + * the outer layer of DER header + */ + rv = DER_Lengths(&issuerName, &headerlen, (PRUint32 *)&contentlen); + if (rv == SECSuccess) { + compatIssuerName.data = &issuerName.data[headerlen]; + compatIssuerName.len = issuerName.len - headerlen; + } else { + compatIssuerName.data = NULL; + compatIssuerName.len = 0; + } + + for (j = 0; j < caNames->nnames; j++) { + caname = &caNames->names[j]; + if (SECITEM_CompareItem(&issuerName, caname) == SECEqual) { + rv = SECSuccess; + CERT_DestroyCertificate(curcert); + goto done; + } else if (SECITEM_CompareItem(&compatIssuerName, caname) == SECEqual) { + rv = SECSuccess; + CERT_DestroyCertificate(curcert); + goto done; + } + } + 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; + } } - } - rv = SECFailure; - + rv = SECFailure; + done: - return rv; + return rv; } - diff --git a/nss/lib/ssl/config.mk b/nss/lib/ssl/config.mk index 40b1c30..339cc80 100644 --- a/nss/lib/ssl/config.mk +++ b/nss/lib/ssl/config.mk @@ -7,21 +7,6 @@ ifdef NISCC_TEST DEFINES += -DNISCC_TEST endif -# Allow build-time configuration of TLS 1.3 (Experimental) -ifdef NSS_ENABLE_TLS_1_3 -DEFINES += -DNSS_ENABLE_TLS_1_3 -endif - -ifdef NSS_NO_PKCS11_BYPASS -DEFINES += -DNO_PKCS11_BYPASS -else -CRYPTOLIB=$(SOFTOKEN_LIB_DIR)/$(LIB_PREFIX)freebl.$(LIB_SUFFIX) - -EXTRA_LIBS += \ - $(CRYPTOLIB) \ - $(NULL) -endif - ifeq (,$(filter-out WIN%,$(OS_TARGET))) # don't want the 32 in the shared library name @@ -72,22 +57,15 @@ endif endif -# Mozilla's mozilla/modules/zlib/src/zconf.h adds the MOZ_Z_ prefix to zlib -# exported symbols, which causes problem when NSS is built as part of Mozilla. -# So we add a NSS_ENABLE_ZLIB variable to allow Mozilla to turn this off. -NSS_ENABLE_ZLIB = 1 -ifdef NSS_ENABLE_ZLIB - -DEFINES += -DNSS_ENABLE_ZLIB +ifdef NSS_SSL_ENABLE_ZLIB +DEFINES += -DNSS_SSL_ENABLE_ZLIB +include $(CORE_DEPTH)/coreconf/zlib.mk +endif -# If a platform has a system zlib, set USE_SYSTEM_ZLIB to 1 and -# ZLIB_LIBS to the linker command-line arguments for the system zlib -# (for example, -lz) in the platform's config file in coreconf. -ifdef USE_SYSTEM_ZLIB -OS_LIBS += $(ZLIB_LIBS) -else -ZLIB_LIBS = $(DIST)/lib/$(LIB_PREFIX)zlib.$(LIB_SUFFIX) -EXTRA_LIBS += $(ZLIB_LIBS) +ifndef NSS_ENABLE_TLS_1_3 +NSS_DISABLE_TLS_1_3=1 endif +ifdef NSS_DISABLE_TLS_1_3 +DEFINES += -DNSS_DISABLE_TLS_1_3 endif diff --git a/nss/lib/ssl/derive.c b/nss/lib/ssl/derive.c deleted file mode 100644 index 8b58b80..0000000 --- a/nss/lib/ssl/derive.c +++ /dev/null @@ -1,896 +0,0 @@ -/* - * Key Derivation that doesn't use PKCS11 - * - * 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" /* prereq to sslimpl.h */ -#include "certt.h" /* prereq to sslimpl.h */ -#include "keythi.h" /* prereq to sslimpl.h */ -#include "sslimpl.h" -#ifndef NO_PKCS11_BYPASS -#include "blapi.h" -#endif - -#include "keyhi.h" -#include "pk11func.h" -#include "secasn1.h" -#include "cert.h" -#include "secmodt.h" - -#include "sslproto.h" -#include "sslerr.h" - -#ifndef NO_PKCS11_BYPASS -/* make this a macro! */ -#ifdef NOT_A_MACRO -static void -buildSSLKey(unsigned char * keyBlock, unsigned int keyLen, SECItem * result, - const char * label) -{ - result->type = siBuffer; - result->data = keyBlock; - result->len = keyLen; - PRINT_BUF(100, (NULL, label, keyBlock, keyLen)); -} -#else -#define buildSSLKey(keyBlock, keyLen, result, label) \ -{ \ - (result)->type = siBuffer; \ - (result)->data = keyBlock; \ - (result)->len = keyLen; \ - PRINT_BUF(100, (NULL, label, keyBlock, keyLen)); \ -} -#endif - -/* - * SSL Key generation given pre master secret - */ -#ifndef NUM_MIXERS -#define NUM_MIXERS 9 -#endif -static const char * const mixers[NUM_MIXERS] = { - "A", - "BB", - "CCC", - "DDDD", - "EEEEE", - "FFFFFF", - "GGGGGGG", - "HHHHHHHH", - "IIIIIIIII" -}; - - -SECStatus -ssl3_KeyAndMacDeriveBypass( - ssl3CipherSpec * pwSpec, - const unsigned char * cr, - const unsigned char * sr, - PRBool isTLS, - PRBool isExport) -{ - const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; - unsigned char * key_block = pwSpec->key_block; - unsigned char * key_block2 = NULL; - unsigned int block_bytes = 0; - unsigned int block_needed = 0; - unsigned int i; - unsigned int keySize; /* actual size of cipher keys */ - unsigned int effKeySize; /* effective size of cipher keys */ - unsigned int macSize; /* size of MAC secret */ - unsigned int IVSize; /* size of IV */ - PRBool explicitIV = PR_FALSE; - SECStatus rv = SECFailure; - SECStatus status = SECSuccess; - PRBool isFIPS = PR_FALSE; - PRBool isTLS12 = pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2; - - SECItem srcr; - SECItem crsr; - - unsigned char srcrdata[SSL3_RANDOM_LENGTH * 2]; - unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; - PRUint64 md5buf[22]; - PRUint64 shabuf[40]; - -#define md5Ctx ((MD5Context *)md5buf) -#define shaCtx ((SHA1Context *)shabuf) - - static const SECItem zed = { siBuffer, NULL, 0 }; - - if (pwSpec->msItem.data == NULL || - pwSpec->msItem.len != SSL3_MASTER_SECRET_LENGTH) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return rv; - } - - PRINT_BUF(100, (NULL, "Master Secret", pwSpec->msItem.data, - pwSpec->msItem.len)); - - /* figure out how much is needed */ - macSize = pwSpec->mac_size; - keySize = cipher_def->key_size; - effKeySize = cipher_def->secret_key_size; - IVSize = cipher_def->iv_size; - if (keySize == 0) { - effKeySize = IVSize = 0; /* only MACing */ - } - if (cipher_def->type == type_block && - pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { - /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ - explicitIV = PR_TRUE; - } - block_needed = - 2 * (macSize + effKeySize + ((!isExport && !explicitIV) * IVSize)); - - /* - * clear out our returned keys so we can recover on failure - */ - pwSpec->client.write_key_item = zed; - pwSpec->client.write_mac_key_item = zed; - pwSpec->server.write_key_item = zed; - pwSpec->server.write_mac_key_item = zed; - - /* initialize the server random, client random block */ - srcr.type = siBuffer; - srcr.data = srcrdata; - srcr.len = sizeof srcrdata; - PORT_Memcpy(srcrdata, sr, SSL3_RANDOM_LENGTH); - PORT_Memcpy(srcrdata + SSL3_RANDOM_LENGTH, cr, SSL3_RANDOM_LENGTH); - - /* initialize the client random, server random block */ - crsr.type = siBuffer; - crsr.data = crsrdata; - crsr.len = sizeof crsrdata; - PORT_Memcpy(crsrdata, cr, SSL3_RANDOM_LENGTH); - PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, sr, SSL3_RANDOM_LENGTH); - PRINT_BUF(100, (NULL, "Key & MAC CRSR", crsr.data, crsr.len)); - - /* - * generate the key material: - */ - if (isTLS) { - SECItem keyblk; - - keyblk.type = siBuffer; - keyblk.data = key_block; - keyblk.len = block_needed; - - if (isTLS12) { - status = TLS_P_hash(HASH_AlgSHA256, &pwSpec->msItem, - "key expansion", &srcr, &keyblk, isFIPS); - } else { - status = TLS_PRF(&pwSpec->msItem, "key expansion", &srcr, &keyblk, - isFIPS); - } - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - block_bytes = keyblk.len; - } else { - /* key_block = - * MD5(master_secret + SHA('A' + master_secret + - * ServerHello.random + ClientHello.random)) + - * MD5(master_secret + SHA('BB' + master_secret + - * ServerHello.random + ClientHello.random)) + - * MD5(master_secret + SHA('CCC' + master_secret + - * ServerHello.random + ClientHello.random)) + - * [...]; - */ - unsigned int made = 0; - for (i = 0; made < block_needed && i < NUM_MIXERS; ++i) { - unsigned int outLen; - unsigned char sha_out[SHA1_LENGTH]; - - SHA1_Begin(shaCtx); - SHA1_Update(shaCtx, (unsigned char*)(mixers[i]), i+1); - SHA1_Update(shaCtx, pwSpec->msItem.data, pwSpec->msItem.len); - SHA1_Update(shaCtx, srcr.data, srcr.len); - SHA1_End(shaCtx, sha_out, &outLen, SHA1_LENGTH); - PORT_Assert(outLen == SHA1_LENGTH); - - MD5_Begin(md5Ctx); - MD5_Update(md5Ctx, pwSpec->msItem.data, pwSpec->msItem.len); - MD5_Update(md5Ctx, sha_out, outLen); - MD5_End(md5Ctx, key_block + made, &outLen, MD5_LENGTH); - PORT_Assert(outLen == MD5_LENGTH); - made += MD5_LENGTH; - } - block_bytes = made; - } - PORT_Assert(block_bytes >= block_needed); - PORT_Assert(block_bytes <= sizeof pwSpec->key_block); - PRINT_BUF(100, (NULL, "key block", key_block, block_bytes)); - - /* - * Put the key material where it goes. - */ - key_block2 = key_block + block_bytes; - i = 0; /* now shows how much consumed */ - - /* - * The key_block is partitioned as follows: - * client_write_MAC_secret[CipherSpec.hash_size] - */ - buildSSLKey(&key_block[i],macSize, &pwSpec->client.write_mac_key_item, \ - "Client Write MAC Secret"); - i += macSize; - - /* - * server_write_MAC_secret[CipherSpec.hash_size] - */ - buildSSLKey(&key_block[i],macSize, &pwSpec->server.write_mac_key_item, \ - "Server Write MAC Secret"); - i += macSize; - - if (!keySize) { - /* only MACing */ - buildSSLKey(NULL, 0, &pwSpec->client.write_key_item, \ - "Client Write Key (MAC only)"); - buildSSLKey(NULL, 0, &pwSpec->server.write_key_item, \ - "Server Write Key (MAC only)"); - buildSSLKey(NULL, 0, &pwSpec->client.write_iv_item, \ - "Client Write IV (MAC only)"); - buildSSLKey(NULL, 0, &pwSpec->server.write_iv_item, \ - "Server Write IV (MAC only)"); - } else if (!isExport) { - /* - ** Generate Domestic write keys and IVs. - ** client_write_key[CipherSpec.key_material] - */ - buildSSLKey(&key_block[i], keySize, &pwSpec->client.write_key_item, \ - "Domestic Client Write Key"); - i += keySize; - - /* - ** server_write_key[CipherSpec.key_material] - */ - buildSSLKey(&key_block[i], keySize, &pwSpec->server.write_key_item, \ - "Domestic Server Write Key"); - i += keySize; - - if (IVSize > 0) { - if (explicitIV) { - static unsigned char zero_block[32]; - PORT_Assert(IVSize <= sizeof zero_block); - buildSSLKey(&zero_block[0], IVSize, \ - &pwSpec->client.write_iv_item, \ - "Domestic Client Write IV"); - buildSSLKey(&zero_block[0], IVSize, \ - &pwSpec->server.write_iv_item, \ - "Domestic Server Write IV"); - } else { - /* - ** client_write_IV[CipherSpec.IV_size] - */ - buildSSLKey(&key_block[i], IVSize, \ - &pwSpec->client.write_iv_item, \ - "Domestic Client Write IV"); - i += IVSize; - - /* - ** server_write_IV[CipherSpec.IV_size] - */ - buildSSLKey(&key_block[i], IVSize, \ - &pwSpec->server.write_iv_item, \ - "Domestic Server Write IV"); - i += IVSize; - } - } - PORT_Assert(i <= block_bytes); - } else if (!isTLS) { - /* - ** Generate SSL3 Export write keys and IVs. - */ - unsigned int outLen; - - /* - ** client_write_key[CipherSpec.key_material] - ** final_client_write_key = MD5(client_write_key + - ** ClientHello.random + ServerHello.random); - */ - MD5_Begin(md5Ctx); - MD5_Update(md5Ctx, &key_block[i], effKeySize); - MD5_Update(md5Ctx, crsr.data, crsr.len); - MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH); - i += effKeySize; - buildSSLKey(key_block2, keySize, &pwSpec->client.write_key_item, \ - "SSL3 Export Client Write Key"); - key_block2 += keySize; - - /* - ** server_write_key[CipherSpec.key_material] - ** final_server_write_key = MD5(server_write_key + - ** ServerHello.random + ClientHello.random); - */ - MD5_Begin(md5Ctx); - MD5_Update(md5Ctx, &key_block[i], effKeySize); - MD5_Update(md5Ctx, srcr.data, srcr.len); - MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH); - i += effKeySize; - buildSSLKey(key_block2, keySize, &pwSpec->server.write_key_item, \ - "SSL3 Export Server Write Key"); - key_block2 += keySize; - PORT_Assert(i <= block_bytes); - - if (IVSize) { - /* - ** client_write_IV = - ** MD5(ClientHello.random + ServerHello.random); - */ - MD5_Begin(md5Ctx); - MD5_Update(md5Ctx, crsr.data, crsr.len); - MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH); - buildSSLKey(key_block2, IVSize, &pwSpec->client.write_iv_item, \ - "SSL3 Export Client Write IV"); - key_block2 += IVSize; - - /* - ** server_write_IV = - ** MD5(ServerHello.random + ClientHello.random); - */ - MD5_Begin(md5Ctx); - MD5_Update(md5Ctx, srcr.data, srcr.len); - MD5_End(md5Ctx, key_block2, &outLen, MD5_LENGTH); - buildSSLKey(key_block2, IVSize, &pwSpec->server.write_iv_item, \ - "SSL3 Export Server Write IV"); - key_block2 += IVSize; - } - - PORT_Assert(key_block2 - key_block <= sizeof pwSpec->key_block); - } else { - /* - ** Generate TLS Export write keys and IVs. - */ - SECItem secret ; - SECItem keyblk ; - - secret.type = siBuffer; - keyblk.type = siBuffer; - /* - ** client_write_key[CipherSpec.key_material] - ** final_client_write_key = PRF(client_write_key, - ** "client write key", - ** client_random + server_random); - */ - secret.data = &key_block[i]; - secret.len = effKeySize; - i += effKeySize; - keyblk.data = key_block2; - keyblk.len = keySize; - status = TLS_PRF(&secret, "client write key", &crsr, &keyblk, isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - buildSSLKey(key_block2, keySize, &pwSpec->client.write_key_item, \ - "TLS Export Client Write Key"); - key_block2 += keySize; - - /* - ** server_write_key[CipherSpec.key_material] - ** final_server_write_key = PRF(server_write_key, - ** "server write key", - ** client_random + server_random); - */ - secret.data = &key_block[i]; - secret.len = effKeySize; - i += effKeySize; - keyblk.data = key_block2; - keyblk.len = keySize; - status = TLS_PRF(&secret, "server write key", &crsr, &keyblk, isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - buildSSLKey(key_block2, keySize, &pwSpec->server.write_key_item, \ - "TLS Export Server Write Key"); - key_block2 += keySize; - - /* - ** iv_block = PRF("", "IV block", client_random + server_random); - ** client_write_IV[SecurityParameters.IV_size] - ** server_write_IV[SecurityParameters.IV_size] - */ - if (IVSize) { - secret.data = NULL; - secret.len = 0; - keyblk.data = key_block2; - keyblk.len = 2 * IVSize; - status = TLS_PRF(&secret, "IV block", &crsr, &keyblk, isFIPS); - if (status != SECSuccess) { - goto key_and_mac_derive_fail; - } - buildSSLKey(key_block2, IVSize, \ - &pwSpec->client.write_iv_item, \ - "TLS Export Client Write IV"); - buildSSLKey(key_block2 + IVSize, IVSize, \ - &pwSpec->server.write_iv_item, \ - "TLS Export Server Write IV"); - key_block2 += 2 * IVSize; - } - PORT_Assert(key_block2 - key_block <= sizeof pwSpec->key_block); - } - rv = SECSuccess; - -key_and_mac_derive_fail: - - MD5_DestroyContext(md5Ctx, PR_FALSE); - SHA1_DestroyContext(shaCtx, PR_FALSE); - - if (rv != SECSuccess) { - PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); - } - - return rv; -} - - -/* derive the Master Secret from the PMS */ -/* Presently, this is only done wtih RSA PMS, and only on the server side, - * so isRSA is always true. - */ -SECStatus -ssl3_MasterSecretDeriveBypass( - ssl3CipherSpec * pwSpec, - const unsigned char * cr, - const unsigned char * sr, - const SECItem * pms, - PRBool isTLS, - PRBool isRSA) -{ - unsigned char * key_block = pwSpec->key_block; - SECStatus rv = SECSuccess; - PRBool isFIPS = PR_FALSE; - PRBool isTLS12 = pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2; - - SECItem crsr; - - unsigned char crsrdata[SSL3_RANDOM_LENGTH * 2]; - PRUint64 md5buf[22]; - PRUint64 shabuf[40]; - -#define md5Ctx ((MD5Context *)md5buf) -#define shaCtx ((SHA1Context *)shabuf) - - /* first do the consistancy checks */ - if (isRSA) { - PORT_Assert(pms->len == SSL3_RSA_PMS_LENGTH); - if (pms->len != SSL3_RSA_PMS_LENGTH) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - /* caller must test PMS version for rollback */ - } - - /* initialize the client random, server random block */ - crsr.type = siBuffer; - crsr.data = crsrdata; - crsr.len = sizeof crsrdata; - PORT_Memcpy(crsrdata, cr, SSL3_RANDOM_LENGTH); - PORT_Memcpy(crsrdata + SSL3_RANDOM_LENGTH, sr, SSL3_RANDOM_LENGTH); - PRINT_BUF(100, (NULL, "Master Secret CRSR", crsr.data, crsr.len)); - - /* finally do the key gen */ - if (isTLS) { - SECItem master = { siBuffer, NULL, 0 }; - - master.data = key_block; - master.len = SSL3_MASTER_SECRET_LENGTH; - - if (isTLS12) { - rv = TLS_P_hash(HASH_AlgSHA256, pms, "master secret", &crsr, - &master, isFIPS); - } else { - rv = TLS_PRF(pms, "master secret", &crsr, &master, isFIPS); - } - if (rv != SECSuccess) { - PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); - } - } else { - int i; - unsigned int made = 0; - for (i = 0; i < 3; i++) { - unsigned int outLen; - unsigned char sha_out[SHA1_LENGTH]; - - SHA1_Begin(shaCtx); - SHA1_Update(shaCtx, (unsigned char*) mixers[i], i+1); - SHA1_Update(shaCtx, pms->data, pms->len); - SHA1_Update(shaCtx, crsr.data, crsr.len); - SHA1_End(shaCtx, sha_out, &outLen, SHA1_LENGTH); - PORT_Assert(outLen == SHA1_LENGTH); - - MD5_Begin(md5Ctx); - MD5_Update(md5Ctx, pms->data, pms->len); - MD5_Update(md5Ctx, sha_out, outLen); - MD5_End(md5Ctx, key_block + made, &outLen, MD5_LENGTH); - PORT_Assert(outLen == MD5_LENGTH); - made += outLen; - } - } - - /* store the results */ - PORT_Memcpy(pwSpec->raw_master_secret, key_block, - SSL3_MASTER_SECRET_LENGTH); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; - PRINT_BUF(100, (NULL, "Master Secret", pwSpec->msItem.data, - pwSpec->msItem.len)); - - return rv; -} - -static SECStatus -ssl_canExtractMS(PK11SymKey *pms, PRBool isTLS, PRBool isDH, PRBool *pcbp) -{ SECStatus rv; - PK11SymKey * ms = NULL; - SECItem params = {siBuffer, NULL, 0}; - CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params; - unsigned char rand[SSL3_RANDOM_LENGTH]; - CK_VERSION pms_version; - CK_MECHANISM_TYPE master_derive; - CK_MECHANISM_TYPE key_derive; - CK_FLAGS keyFlags; - - if (pms == NULL) - return(SECFailure); - - PORT_Memset(rand, 0, SSL3_RANDOM_LENGTH); - - 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; - } - - master_params.pVersion = &pms_version; - master_params.RandomInfo.pClientRandom = rand; - master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; - master_params.RandomInfo.pServerRandom = rand; - master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; - - params.data = (unsigned char *) &master_params; - params.len = sizeof master_params; - - ms = PK11_DeriveWithFlags(pms, master_derive, ¶ms, key_derive, - CKA_DERIVE, 0, keyFlags); - if (ms == NULL) - return(SECFailure); - - rv = PK11_ExtractKeyValue(ms); - *pcbp = (rv == SECSuccess); - PK11_FreeSymKey(ms); - - return(rv); - -} -#endif /* !NO_PKCS11_BYPASS */ - -/* Check the key exchange algorithm for each cipher in the list to see if - * a master secret key can be extracted. If the KEA will use keys from the - * specified cert make sure the extract operation is attempted from the slot - * where the private key resides. - * If MS can be extracted for all ciphers, (*pcanbypass) is set to TRUE and - * SECSuccess is returned. In all other cases but one (*pcanbypass) is - * set to FALSE and SECFailure is returned. - * In that last case Derive() has been called successfully but the MS is null, - * CanBypass sets (*pcanbypass) to FALSE and returns SECSuccess indicating the - * arguments were all valid but the slot cannot be bypassed. - */ - -/* XXX Add SSL_CBP_TLS1_1 and test it in protocolmask when setting isTLS. */ - -SECStatus -SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *srvPrivkey, - PRUint32 protocolmask, PRUint16 *ciphersuites, int nsuites, - PRBool *pcanbypass, void *pwArg) -{ -#ifdef NO_PKCS11_BYPASS - if (!pcanbypass) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - *pcanbypass = PR_FALSE; - return SECSuccess; -#else - SECStatus rv; - int i; - PRUint16 suite; - PK11SymKey * pms = NULL; - SECKEYPublicKey * srvPubkey = NULL; - KeyType privKeytype; - PK11SlotInfo * slot = NULL; - SECItem param; - CK_VERSION version; - CK_MECHANISM_TYPE mechanism_array[2]; - SECItem enc_pms = {siBuffer, NULL, 0}; - PRBool isTLS = PR_FALSE; - SSLCipherSuiteInfo csdef; - PRBool testrsa = PR_FALSE; - PRBool testrsa_export = PR_FALSE; - PRBool testecdh = PR_FALSE; - PRBool testecdhe = PR_FALSE; -#ifndef NSS_DISABLE_ECC - SECKEYECParams ecParams = { siBuffer, NULL, 0 }; -#endif - - if (!cert || !srvPrivkey || !ciphersuites || !pcanbypass) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - srvPubkey = CERT_ExtractPublicKey(cert); - if (!srvPubkey) - return SECFailure; - - *pcanbypass = PR_TRUE; - rv = SECFailure; - - /* determine which KEAs to test */ - /* 0 (TLS_NULL_WITH_NULL_NULL) is used as a list terminator because - * SSL3 and TLS specs forbid negotiating that cipher suite number. - */ - for (i=0; i < nsuites && (suite = *ciphersuites++) != 0; i++) { - /* skip SSL2 cipher suites and ones NSS doesn't support */ - if (SSL_GetCipherSuiteInfo(suite, &csdef, sizeof(csdef)) != SECSuccess - || SSL_IS_SSL2_CIPHER(suite) ) - continue; - switch (csdef.keaType) { - case ssl_kea_rsa: - switch (csdef.cipherSuite) { - case TLS_RSA_EXPORT1024_WITH_RC4_56_SHA: - case TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA: - case TLS_RSA_EXPORT_WITH_RC4_40_MD5: - case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: - testrsa_export = PR_TRUE; - } - if (!testrsa_export) - testrsa = PR_TRUE; - break; - case ssl_kea_ecdh: - if (strcmp(csdef.keaTypeName, "ECDHE") == 0) /* ephemeral? */ - testecdhe = PR_TRUE; - else - testecdh = PR_TRUE; - break; - case ssl_kea_dh: - /* this is actually DHE */ - default: - continue; - } - } - - /* For each protocol try to derive and extract an MS. - * Failure of function any function except MS extract means - * continue with the next cipher test. Stop testing when the list is - * exhausted or when the first MS extract--not derive--fails. - */ - privKeytype = SECKEY_GetPrivateKeyType(srvPrivkey); - protocolmask &= SSL_CBP_SSL3|SSL_CBP_TLS1_0; - while (protocolmask) { - if (protocolmask & SSL_CBP_SSL3) { - isTLS = PR_FALSE; - protocolmask ^= SSL_CBP_SSL3; - } else { - isTLS = PR_TRUE; - protocolmask ^= SSL_CBP_TLS1_0; - } - - if (privKeytype == rsaKey && testrsa_export) { - if (PK11_GetPrivateModulusLen(srvPrivkey) > EXPORT_RSA_KEY_LENGTH) { - *pcanbypass = PR_FALSE; - rv = SECSuccess; - break; - } else - testrsa = PR_TRUE; - } - for (; privKeytype == rsaKey && testrsa; ) { - /* TLS_RSA */ - unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; - unsigned int outLen = 0; - CK_MECHANISM_TYPE target; - SECStatus irv; - - mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; - mechanism_array[1] = CKM_RSA_PKCS; - - slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg); - if (slot == NULL) { - PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND); - break; - } - - /* Generate the pre-master secret ... (client side) */ - version.major = 3 /*MSB(clientHelloVersion)*/; - version.minor = 0 /*LSB(clientHelloVersion)*/; - param.data = (unsigned char *)&version; - param.len = sizeof version; - pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); - PK11_FreeSlot(slot); - if (!pms) - break; - /* now wrap it */ - enc_pms.len = SECKEY_PublicKeyStrength(srvPubkey); - enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); - if (enc_pms.data == NULL) { - PORT_SetError(PR_OUT_OF_MEMORY_ERROR); - break; - } - irv = PK11_PubWrapSymKey(CKM_RSA_PKCS, srvPubkey, pms, &enc_pms); - if (irv != SECSuccess) - break; - PK11_FreeSymKey(pms); - pms = NULL; - /* now do the server side--check the triple bypass first */ - rv = PK11_PrivDecryptPKCS1(srvPrivkey, rsaPmsBuf, &outLen, - sizeof rsaPmsBuf, - (unsigned char *)enc_pms.data, - enc_pms.len); - /* if decrypt worked we're done with the RSA test */ - if (rv == SECSuccess) { - *pcanbypass = PR_TRUE; - break; - } - /* check for fallback to double bypass */ - target = isTLS ? CKM_TLS_MASTER_KEY_DERIVE - : CKM_SSL3_MASTER_KEY_DERIVE; - pms = PK11_PubUnwrapSymKey(srvPrivkey, &enc_pms, - target, CKA_DERIVE, 0); - rv = ssl_canExtractMS(pms, isTLS, PR_FALSE, pcanbypass); - if (rv == SECSuccess && *pcanbypass == PR_FALSE) - goto done; - break; - } - - /* Check for NULL to avoid double free. - * SECItem_FreeItem sets data NULL in secitem.c#265 - */ - if (enc_pms.data != NULL) { - SECITEM_FreeItem(&enc_pms, PR_FALSE); - } -#ifndef NSS_DISABLE_ECC - for (; (privKeytype == ecKey && ( testecdh || testecdhe)) || - (privKeytype == rsaKey && testecdhe); ) { - CK_MECHANISM_TYPE target; - SECKEYPublicKey *keapub = NULL; - SECKEYPrivateKey *keapriv; - SECKEYPublicKey *cpub = NULL; /* client's ephemeral ECDH keys */ - SECKEYPrivateKey *cpriv = NULL; - SECKEYECParams *pecParams = NULL; - - if (privKeytype == ecKey && testecdhe) { - /* TLS_ECDHE_ECDSA */ - pecParams = &srvPubkey->u.ec.DEREncodedParams; - } else if (privKeytype == rsaKey && testecdhe) { - /* TLS_ECDHE_RSA */ - ECName ec_curve; - int serverKeyStrengthInBits; - int signatureKeyStrength; - int requiredECCbits; - - /* find a curve of equivalent strength to the RSA key's */ - requiredECCbits = PK11_GetPrivateModulusLen(srvPrivkey); - if (requiredECCbits < 0) - break; - requiredECCbits *= BPB; - serverKeyStrengthInBits = srvPubkey->u.rsa.modulus.len; - if (srvPubkey->u.rsa.modulus.data[0] == 0) { - serverKeyStrengthInBits--; - } - /* convert to strength in bits */ - serverKeyStrengthInBits *= BPB; - - signatureKeyStrength = - SSL_RSASTRENGTH_TO_ECSTRENGTH(serverKeyStrengthInBits); - - if ( requiredECCbits > signatureKeyStrength ) - requiredECCbits = signatureKeyStrength; - - ec_curve = - ssl3_GetCurveWithECKeyStrength( - ssl3_GetSupportedECCurveMask(NULL), - requiredECCbits); - rv = ssl3_ECName2Params(NULL, ec_curve, &ecParams); - if (rv == SECFailure) { - break; - } - pecParams = &ecParams; - } - - if (testecdhe) { - /* generate server's ephemeral keys */ - keapriv = SECKEY_CreateECPrivateKey(pecParams, &keapub, NULL); - if (!keapriv || !keapub) { - if (keapriv) - SECKEY_DestroyPrivateKey(keapriv); - if (keapub) - SECKEY_DestroyPublicKey(keapub); - PORT_SetError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - break; - } - } else { - /* TLS_ECDH_ECDSA */ - keapub = srvPubkey; - keapriv = srvPrivkey; - pecParams = &srvPubkey->u.ec.DEREncodedParams; - } - - /* perform client side ops */ - /* generate a pair of ephemeral keys using server's parms */ - cpriv = SECKEY_CreateECPrivateKey(pecParams, &cpub, NULL); - if (!cpriv || !cpub) { - if (testecdhe) { - SECKEY_DestroyPrivateKey(keapriv); - SECKEY_DestroyPublicKey(keapub); - } - PORT_SetError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - break; - } - /* now do the server side */ - /* determine the PMS using client's public value */ - target = isTLS ? CKM_TLS_MASTER_KEY_DERIVE_DH - : CKM_SSL3_MASTER_KEY_DERIVE_DH; - pms = PK11_PubDeriveWithKDF(keapriv, cpub, PR_FALSE, NULL, NULL, - CKM_ECDH1_DERIVE, - target, - CKA_DERIVE, 0, CKD_NULL, NULL, NULL); - rv = ssl_canExtractMS(pms, isTLS, PR_TRUE, pcanbypass); - SECKEY_DestroyPrivateKey(cpriv); - SECKEY_DestroyPublicKey(cpub); - if (testecdhe) { - SECKEY_DestroyPrivateKey(keapriv); - SECKEY_DestroyPublicKey(keapub); - } - if (rv == SECSuccess && *pcanbypass == PR_FALSE) - goto done; - break; - } - /* Check for NULL to avoid double free. */ - if (ecParams.data != NULL) { - PORT_Free(ecParams.data); - ecParams.data = NULL; - } -#endif /* NSS_DISABLE_ECC */ - if (pms) - PK11_FreeSymKey(pms); - } - - /* *pcanbypass has been set */ - rv = SECSuccess; - - done: - if (pms) - PK11_FreeSymKey(pms); - - /* Check for NULL to avoid double free. - * SECItem_FreeItem sets data NULL in secitem.c#265 - */ - if (enc_pms.data != NULL) { - SECITEM_FreeItem(&enc_pms, PR_FALSE); - } -#ifndef NSS_DISABLE_ECC - if (ecParams.data != NULL) { - PORT_Free(ecParams.data); - ecParams.data = NULL; - } -#endif /* NSS_DISABLE_ECC */ - - if (srvPubkey) { - SECKEY_DestroyPublicKey(srvPubkey); - srvPubkey = NULL; - } - - - return rv; -#endif /* NO_PKCS11_BYPASS */ -} - diff --git a/nss/lib/ssl/dhe-param.c b/nss/lib/ssl/dhe-param.c index ac0942e..ad87cc4 100644 --- a/nss/lib/ssl/dhe-param.c +++ b/nss/lib/ssl/dhe-param.c @@ -39,7 +39,8 @@ static const unsigned char ff_dhe_2048_p[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; -static const ssl3DHParams ff_dhe_2048 = { +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) }, }; @@ -95,7 +96,8 @@ static const unsigned char ff_dhe_3072_p[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; -static const ssl3DHParams ff_dhe_3072 = { +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) }, }; @@ -167,7 +169,8 @@ static const unsigned char ff_dhe_4096_p[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; -static const ssl3DHParams ff_dhe_4096 = { +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) }, }; @@ -271,7 +274,8 @@ static const unsigned char ff_dhe_6144_p[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; -static const ssl3DHParams ff_dhe_6144 = { +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) }, }; @@ -407,7 +411,8 @@ static const unsigned char ff_dhe_8192_p[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }; -static const ssl3DHParams ff_dhe_8192 = { +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/nss/lib/ssl/dtlscon.c b/nss/lib/ssl/dtlscon.c index 1b21107..09ceeac 100644 --- a/nss/lib/ssl/dtlscon.c +++ b/nss/lib/ssl/dtlscon.c @@ -1,3 +1,4 @@ +/* -*- 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/. */ @@ -11,38 +12,34 @@ #include "sslproto.h" #ifndef PR_ARRAY_SIZE -#define PR_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) +#define PR_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif static SECStatus dtls_TransmitMessageFlight(sslSocket *ss); +static SECStatus dtls_StartRetransmitTimer(sslSocket *ss); static void dtls_RetransmitTimerExpiredCb(sslSocket *ss); static SECStatus dtls_SendSavedWriteData(sslSocket *ss); +static void dtls_FinishedTimerCb(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 */ + 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 /* List copied from ssl3con.c:cipherSuites */ static const ssl3CipherSuite nonDTLSSuites[] = { -#ifndef NSS_DISABLE_ECC TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, -#endif /* NSS_DISABLE_ECC */ TLS_DHE_DSS_WITH_RC4_128_SHA, -#ifndef NSS_DISABLE_ECC TLS_ECDH_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, -#endif /* NSS_DISABLE_ECC */ TLS_RSA_WITH_RC4_128_MD5, TLS_RSA_WITH_RC4_128_SHA, - TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, - TLS_RSA_EXPORT_WITH_RC4_40_MD5, 0 /* End of list marker */ }; @@ -86,6 +83,11 @@ dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv) 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; } @@ -94,14 +96,14 @@ dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv) } /* Return a fictional higher version than we know of */ - return SSL_LIBRARY_VERSION_TLS_1_2 + 1; + 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) +ssl3_DisableNonDTLSSuites(sslSocket *ss) { - const ssl3CipherSuite * suite; + const ssl3CipherSuite *suite; for (suite = nonDTLSSuites; *suite; ++suite) { PORT_CheckSuccess(ssl3_CipherPrefSet(ss, *suite, PR_FALSE)); @@ -114,7 +116,7 @@ ssl3_DisableNonDTLSSuites(sslSocket * ss) * Called from dtls_QueueMessage() */ static DTLSQueuedMessage * -dtls_AllocQueuedMessage(PRUint16 epoch, SSL3ContentType type, +dtls_AllocQueuedMessage(ssl3CipherSpec *cwSpec, SSL3ContentType type, const unsigned char *data, PRUint32 len) { DTLSQueuedMessage *msg = NULL; @@ -131,8 +133,11 @@ dtls_AllocQueuedMessage(PRUint16 epoch, SSL3ContentType type, PORT_Memcpy(msg->data, data, len); msg->len = len; - msg->epoch = epoch; + msg->cwSpec = cwSpec; msg->type = type; + /* Safe if we are < 1.3, since the refct is + * already very high. */ + tls13_CipherSpecAddRef(cwSpec); return msg; } @@ -142,12 +147,15 @@ dtls_AllocQueuedMessage(PRUint16 epoch, SSL3ContentType type, * * Called from dtls_FreeHandshakeMessages() */ -static void +void dtls_FreeHandshakeMessage(DTLSQueuedMessage *msg) { if (!msg) return; + /* Safe if we are < 1.3, since the refct is + * already very high. */ + tls13_CipherSpecRelease(msg->cwSpec); PORT_ZFree(msg->data, msg->len); PORT_Free(msg); } @@ -171,6 +179,62 @@ dtls_FreeHandshakeMessages(PRCList *list) } } +/* Called by dtls_HandleHandshake() and dtls_MaybeRetransmitHandshake() if a + * handshake message retransmission is detected. */ +static SECStatus +dtls_RetransmitDetected(sslSocket *ss) +{ + SECStatus rv = SECSuccess; + + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + if (ss->ssl3.hs.rtTimerCb == 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() - ss->ssl3.hs.rtTimerStarted) > + (ss->ssl3.hs.rtTimeoutMs / 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); + 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() - ss->ssl3.hs.rtTimerStarted, + ss->ssl3.hs.rtTimeoutMs / 4)); + } + + } else if (ss->ssl3.hs.rtTimerCb == 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); + rv = dtls_TransmitMessageFlight(ss); + if (rv == SECSuccess) { + rv = dtls_StartHolddownTimer(ss); + } + + } else { + PORT_Assert(ss->ssl3.hs.rtTimerCb == NULL); + /* ... and ignore it. */ + } + return rv; +} + /* 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 @@ -185,8 +249,8 @@ dtls_FreeHandshakeMessages(PRCList *list) * 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)) +#define OFFSET_BYTE(o) (o / 8) +#define OFFSET_MASK(o) (1 << (o % 8)) SECStatus dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) @@ -224,7 +288,7 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) 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 */ +#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); @@ -258,9 +322,9 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * 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)) { + if ((message_seq == ss->ssl3.hs.recvMessageSeq) && + (fragment_offset == 0) && + (fragment_length == message_length)) { /* Complete next message. Process immediately */ ss->ssl3.hs.msg_type = (SSL3HandshakeType)type; ss->ssl3.hs.msg_len = message_length; @@ -274,10 +338,11 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) /* Reset the timer to the initial value if the retry counter * is 0, per Sec. 4.2.4.1 */ if (ss->ssl3.hs.rtRetries == 0) { - ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; + ss->ssl3.hs.rtTimeoutMs = DTLS_RETRANSMIT_INITIAL_MS; } - rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len); + rv = ssl3_HandleHandshakeMessage(ss, buf.buf, ss->ssl3.hs.msg_len, + buf.len == fragment_length); if (rv == SECFailure) { /* Do not attempt to process rest of messages in this record */ break; @@ -285,52 +350,9 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) } else { if (message_seq < ss->ssl3.hs.recvMessageSeq) { /* Case 3: we do an immediate retransmit if we're - * in a waiting state*/ - if (ss->ssl3.hs.rtTimerCb == NULL) { - /* Ignore */ - } else if (ss->ssl3.hs.rtTimerCb == - dtls_RetransmitTimerExpiredCb) { - SSL_TRC(30, ("%d: SSL3[%d]: Retransmit detected", - SSL_GETPID(), ss->fd)); - /* 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 should be - */ - if ((PR_IntervalNow() - ss->ssl3.hs.rtTimerStarted) > - (ss->ssl3.hs.rtTimeoutMs / 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); - dtls_RetransmitTimerExpiredCb(ss); - rv = SECSuccess; - break; - } else { - SSL_TRC(30, - ("%d: SSL3[%d]: We just retransmitted. Ignoring.", - SSL_GETPID(), ss->fd)); - rv = SECSuccess; - break; - } - } else if (ss->ssl3.hs.rtTimerCb == dtls_FinishedTimerCb) { - /* 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); - rv = dtls_TransmitMessageFlight(ss); - if (rv == SECSuccess) { - rv = dtls_StartTimer(ss, dtls_FinishedTimerCb); - } - if (rv != SECSuccess) - return rv; - break; - } + * in a waiting state. */ + rv = dtls_RetransmitDetected(ss); + break; } else if (message_seq > ss->ssl3.hs.recvMessageSeq) { /* Case 2 * @@ -426,9 +448,10 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) if (ss->ssl3.hs.recvdHighWater == ss->ssl3.hs.msg_len) { ss->ssl3.hs.recvdHighWater = -1; - rv = ssl3_HandleHandshakeMessage(ss, - ss->ssl3.hs.msg_body.buf, - ss->ssl3.hs.msg_len); + rv = ssl3_HandleHandshakeMessage( + ss, + ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len, + buf.len == fragment_length); if (rv == SECFailure) break; /* Skip rest of record */ @@ -440,7 +463,7 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) /* If there have been no retries this time, reset the * timer value to the default per Section 4.2.4.1 */ if (ss->ssl3.hs.rtRetries == 0) { - ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS; + ss->ssl3.hs.rtTimeoutMs = DTLS_RETRANSMIT_INITIAL_MS; } } } @@ -450,7 +473,7 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) buf.len -= fragment_length; } - origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ + origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ /* XXX OK for now. In future handle rv == SECWouldBlock safely in order * to deal with asynchronous certificate verification */ @@ -463,16 +486,19 @@ dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * dtls_StageHandshakeMessage() * ssl3_SendChangeCipherSpecs() */ -SECStatus dtls_QueueMessage(sslSocket *ss, SSL3ContentType type, - const SSL3Opaque *pIn, PRInt32 nIn) +SECStatus +dtls_QueueMessage(sslSocket *ss, SSL3ContentType type, + const SSL3Opaque *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)); - msg = dtls_AllocQueuedMessage(ss->ssl3.cwSpec->epoch, type, pIn, nIn); + spec = ss->ssl3.cwSpec; + msg = dtls_AllocQueuedMessage(spec, type, pIn, nIn); if (!msg) { PORT_SetError(SEC_ERROR_NO_MEMORY); @@ -534,12 +560,12 @@ dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { rv = dtls_TransmitMessageFlight(ss); - if (rv != SECSuccess) + if (rv != SECSuccess) { return rv; + } if (!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)) { - ss->ssl3.hs.rtRetries = 0; - rv = dtls_StartTimer(ss, dtls_RetransmitTimerExpiredCb); + rv = dtls_StartRetransmitTimer(ss); } } @@ -555,7 +581,7 @@ dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) static void dtls_RetransmitTimerExpiredCb(sslSocket *ss) { - SECStatus rv = SECFailure; + SECStatus rv; ss->ssl3.hs.rtRetries++; @@ -568,15 +594,22 @@ dtls_RetransmitTimerExpiredCb(sslSocket *ss) rv = dtls_TransmitMessageFlight(ss); if (rv == SECSuccess) { - /* Re-arm the timer */ - rv = dtls_RestartTimer(ss, PR_TRUE, dtls_RetransmitTimerExpiredCb); - } + ss->ssl3.hs.rtTimeoutMs *= 2; + if (ss->ssl3.hs.rtTimeoutMs > DTLS_RETRANSMIT_MAX_MS) { + ss->ssl3.hs.rtTimeoutMs = DTLS_RETRANSMIT_MAX_MS; + } - if (rv == SECFailure) { - /* XXX OK for now. In future maybe signal the stack that we couldn't - * transmit. For now, let the read handle any real network errors */ + ss->ssl3.hs.rtTimerStarted = PR_IntervalNow(); + ss->ssl3.hs.rtTimerCb = dtls_RetransmitTimerExpiredCb; + + SSL_TRC(30, + ("%d: SSL3[%d]: Retransmit #%d, next in %d", + SSL_GETPID(), ss->fd, + ss->ssl3.hs.rtRetries, ss->ssl3.hs.rtTimeoutMs)); } + /* 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 */ } /* Transmit a flight of handshake messages, stuffing them @@ -631,10 +664,9 @@ dtls_TransmitMessageFlight(sslSocket *ss) if ((msg->len + SSL3_BUFFER_FUDGE) <= room_left) { /* The message will fit, so encrypt and then continue with the * next packet */ - sent = ssl3_SendRecord(ss, msg->epoch, msg->type, + sent = ssl3_SendRecord(ss, msg->cwSpec, msg->type, msg->data, msg->len, - ssl_SEND_FLAG_FORCE_INTO_BUFFER | - ssl_SEND_FLAG_USE_EPOCH); + ssl_SEND_FLAG_FORCE_INTO_BUFFER); if (sent != msg->len) { rv = SECFailure; if (sent != -1) { @@ -694,12 +726,12 @@ dtls_TransmitMessageFlight(sslSocket *ss) /* Offset */ fragment[6] = (fragment_offset >> 16) & 0xff; fragment[7] = (fragment_offset >> 8) & 0xff; - fragment[8] = (fragment_offset) & 0xff; + fragment[8] = (fragment_offset)&0xff; /* Fragment length */ fragment[9] = (fragment_len >> 16) & 0xff; fragment[10] = (fragment_len >> 8) & 0xff; - fragment[11] = (fragment_len) & 0xff; + fragment[11] = (fragment_len)&0xff; PORT_Memcpy(fragment + 12, content + fragment_offset, fragment_len); @@ -708,10 +740,9 @@ dtls_TransmitMessageFlight(sslSocket *ss) * Send the record. We do this in two stages * 1. Encrypt */ - sent = ssl3_SendRecord(ss, msg->epoch, msg->type, + sent = ssl3_SendRecord(ss, msg->cwSpec, msg->type, fragment, fragment_len + 12, - ssl_SEND_FLAG_FORCE_INTO_BUFFER | - ssl_SEND_FLAG_USE_EPOCH); + ssl_SEND_FLAG_FORCE_INTO_BUFFER); if (sent != (fragment_len + 12)) { rv = SECFailure; if (sent != -1) { @@ -747,8 +778,8 @@ dtls_TransmitMessageFlight(sslSocket *ss) * * Called from dtls_TransmitMessageFlight() */ -static -SECStatus dtls_SendSavedWriteData(sslSocket *ss) +static SECStatus +dtls_SendSavedWriteData(sslSocket *ss) { PRInt32 sent; @@ -771,93 +802,32 @@ SECStatus dtls_SendSavedWriteData(sslSocket *ss) return SECSuccess; } -/* Compress, MAC, encrypt a DTLS record. Allows specification of - * the epoch using epoch value. If use_epoch is PR_TRUE then - * we use the provided epoch. If use_epoch is PR_FALSE then - * whatever the current value is in effect is used. - * - * Called from ssl3_SendRecord() - */ -SECStatus -dtls_CompressMACEncryptRecord(sslSocket * ss, - DTLSEpoch epoch, - PRBool use_epoch, - SSL3ContentType type, - const SSL3Opaque * pIn, - PRUint32 contentLen, - sslBuffer * wrBuf) -{ - SECStatus rv = SECFailure; - ssl3CipherSpec * cwSpec; - - ssl_GetSpecReadLock(ss); /********************************/ - - /* The reason for this switch-hitting code is that we might have - * a flight of records spanning an epoch boundary, e.g., - * - * ClientKeyExchange (epoch = 0) - * ChangeCipherSpec (epoch = 0) - * Finished (epoch = 1) - * - * Thus, each record needs a different cipher spec. The information - * about which epoch to use is carried with the record. - */ - if (use_epoch) { - if (ss->ssl3.cwSpec->epoch == epoch) - cwSpec = ss->ssl3.cwSpec; - else if (ss->ssl3.pwSpec->epoch == epoch) - cwSpec = ss->ssl3.pwSpec; - else - cwSpec = NULL; - } else { - cwSpec = ss->ssl3.cwSpec; - } - - if (cwSpec) { - rv = ssl3_CompressMACEncryptRecord(cwSpec, ss->sec.isServer, PR_TRUE, - PR_FALSE, type, pIn, contentLen, - wrBuf); - } else { - PR_NOT_REACHED("Couldn't find a cipher spec matching epoch"); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - } - ssl_ReleaseSpecReadLock(ss); /************************************/ - - return rv; -} - -/* Start a timer - * - * Called from: - * dtls_HandleHandshake() - * dtls_FlushHAndshake() - * dtls_RestartTimer() - */ -SECStatus -dtls_StartTimer(sslSocket *ss, DTLSTimerCb cb) +static SECStatus +dtls_StartTimer(sslSocket *ss, PRUint32 time, DTLSTimerCb cb) { PORT_Assert(ss->ssl3.hs.rtTimerCb == NULL); + ss->ssl3.hs.rtRetries = 0; ss->ssl3.hs.rtTimerStarted = PR_IntervalNow(); + ss->ssl3.hs.rtTimeoutMs = time; ss->ssl3.hs.rtTimerCb = cb; - return SECSuccess; } -/* Restart a timer with optional backoff - * - * Called from dtls_RetransmitTimerExpiredCb() - */ -SECStatus -dtls_RestartTimer(sslSocket *ss, PRBool backoff, DTLSTimerCb cb) +/* Start a timer for retransmission. */ +static SECStatus +dtls_StartRetransmitTimer(sslSocket *ss) { - if (backoff) { - ss->ssl3.hs.rtTimeoutMs *= 2; - if (ss->ssl3.hs.rtTimeoutMs > MAX_DTLS_TIMEOUT_MS) - ss->ssl3.hs.rtTimeoutMs = MAX_DTLS_TIMEOUT_MS; - } + return dtls_StartTimer(ss, DTLS_RETRANSMIT_INITIAL_MS, + dtls_RetransmitTimerExpiredCb); +} - return dtls_StartTimer(ss, cb); +/* Start a timer for holding an old cipher spec. */ +SECStatus +dtls_StartHolddownTimer(sslSocket *ss) +{ + return dtls_StartTimer(ss, DTLS_RETRANSMIT_FINISHED_MS, + dtls_FinishedTimerCb); } /* Cancel a pending timer @@ -881,8 +851,11 @@ dtls_CancelTimer(sslSocket *ss) void dtls_CheckTimer(sslSocket *ss) { - if (!ss->ssl3.hs.rtTimerCb) + ssl_GetSSL3HandshakeLock(ss); + if (!ss->ssl3.hs.rtTimerCb) { + ssl_ReleaseSSL3HandshakeLock(ss); return; + } if ((PR_IntervalNow() - ss->ssl3.hs.rtTimerStarted) > PR_MillisecondsToInterval(ss->ssl3.hs.rtTimeoutMs)) { @@ -895,6 +868,7 @@ dtls_CheckTimer(sslSocket *ss) /* Now call the CB */ cb(ss); } + ssl_ReleaseSSL3HandshakeLock(ss); } /* The callback to fire when the holddown timer for the Finished @@ -902,10 +876,13 @@ dtls_CheckTimer(sslSocket *ss) * * Called from dtls_CheckTimer() */ -void +static void dtls_FinishedTimerCb(sslSocket *ss) { - ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE); + dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE); + } } /* Cancel the Finished hold-down timer and destroy the @@ -919,6 +896,11 @@ dtls_FinishedTimerCb(sslSocket *ss) 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_CancelTimer(ss); ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE); ss->ssl3.hs.sendMessageSeq = 0; @@ -956,7 +938,7 @@ dtls_SetMTU(sslSocket *ss, PRUint16 advertised) } /* Fallback */ - ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES)-1]; + ss->ssl3.mtu = COMMON_MTU_VALUES[PR_ARRAY_SIZE(COMMON_MTU_VALUES) - 1]; SSL_TRC(30, ("Resetting MTU to %d", ss->ssl3.mtu)); } @@ -967,54 +949,58 @@ dtls_SetMTU(sslSocket *ss, PRUint16 advertised) SECStatus dtls_HandleHelloVerifyRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - int errCode = SSL_ERROR_RX_MALFORMED_HELLO_VERIFY_REQUEST; - SECStatus rv; - PRInt32 temp; - SECItem cookie = {siBuffer, NULL, 0}; - SSL3AlertDescription desc = illegal_parameter; + 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)); + 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; + desc = unexpected_message; goto alert_loser; } - /* The version */ - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); - if (temp < 0) { - goto loser; /* alert has been sent */ - } - - if (temp != SSL_LIBRARY_VERSION_DTLS_1_0_WIRE && - temp != SSL_LIBRARY_VERSION_DTLS_1_2_WIRE) { - goto alert_loser; + /* 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 */ } - /* The cookie */ - rv = ssl3_ConsumeHandshakeVariable(ss, &cookie, 1, &b, &length); + /* 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 */ + goto loser; /* alert has been sent */ } - if (cookie.len > DTLS_COOKIE_BYTES) { + if (ss->ssl3.hs.cookie.len > DTLS_COOKIE_BYTES) { desc = decode_error; - goto alert_loser; /* malformed. */ + goto alert_loser; /* malformed. */ } - PORT_Memcpy(ss->ssl3.hs.cookie, cookie.data, cookie.len); - ss->ssl3.hs.cookieLen = cookie.len; - - - ssl_GetXmitBufLock(ss); /*******************************/ + ssl_GetXmitBufLock(ss); /*******************************/ /* Now re-send the client hello */ - rv = ssl3_SendClientHello(ss, PR_TRUE); + rv = ssl3_SendClientHello(ss, client_hello_retransmit); - ssl_ReleaseXmitBufLock(ss); /*******************************/ + ssl_ReleaseXmitBufLock(ss); /*******************************/ if (rv == SECSuccess) return rv; @@ -1023,7 +1009,7 @@ alert_loser: (void)SSL3_SendAlert(ss, alert_fatal, desc); loser: - errCode = ssl_MapLowLevelError(errCode); + ssl_MapLowLevelError(errCode); return SECFailure; } @@ -1047,10 +1033,10 @@ dtls_InitRecvdRecords(DTLSRecvdRecords *records) * 0 -- not received yet * 1 -- replay * - * Called from: dtls_HandleRecord() + * Called from: ssl3_HandleRecord() */ int -dtls_RecordGetRecvd(DTLSRecvdRecords *records, PRUint64 seq) +dtls_RecordGetRecvd(const DTLSRecvdRecords *records, sslSequenceNumber seq) { PRUint64 offset; @@ -1075,7 +1061,7 @@ dtls_RecordGetRecvd(DTLSRecvdRecords *records, PRUint64 seq) * Called from ssl3_HandleRecord() */ void -dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq) +dtls_RecordSetRecvd(DTLSRecvdRecords *records, sslSequenceNumber seq) { PRUint64 offset; @@ -1083,9 +1069,9 @@ dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq) return; if (seq > records->right) { - PRUint64 new_left; - PRUint64 new_right; - PRUint64 right; + sslSequenceNumber new_left; + sslSequenceNumber new_right; + sslSequenceNumber right; /* Slide to the right; this is the tricky part * @@ -1101,9 +1087,13 @@ dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq) new_right = seq | 0x07; new_left = (new_right - DTLS_RECVD_RECORDS_WINDOW) + 1; - for (right = records->right + 8; right <= new_right; right += 8) { - offset = right % DTLS_RECVD_RECORDS_WINDOW; - records->data[offset / 8] = 0; + 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; @@ -1118,7 +1108,7 @@ dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq) SECStatus DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout) { - sslSocket * ss = NULL; + sslSocket *ss = NULL; PRIntervalTime elapsed; PRIntervalTime desired; @@ -1144,3 +1134,81 @@ DTLS_GetHandshakeTimeout(PRFileDesc *socket, PRIntervalTime *timeout) return SECSuccess; } + +/* + * 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 |*seqNum| to the packet sequence number. + */ +PRBool +dtls_IsRelevant(sslSocket *ss, const SSL3Ciphertext *cText, + PRBool *sameEpoch, PRUint64 *seqNum) +{ + const ssl3CipherSpec *crSpec = ss->ssl3.crSpec; + DTLSEpoch epoch; + sslSequenceNumber dtls_seq_num; + + epoch = cText->seq_num >> 48; + *sameEpoch = crSpec->epoch == epoch; + if (!*sameEpoch) { + SSL_DBG(("%d: SSL3[%d]: dtls_IsRelevant, received packet " + "from irrelevant epoch %d", + SSL_GETPID(), ss->fd, epoch)); + return PR_FALSE; + } + + dtls_seq_num = cText->seq_num & RECORD_SEQ_MAX; + if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) { + SSL_DBG(("%d: SSL3[%d]: dtls_IsRelevant, rejecting " + "potentially replayed packet", + SSL_GETPID(), ss->fd)); + return PR_FALSE; + } + + *seqNum = dtls_seq_num; + return PR_TRUE; +} + +/* In TLS 1.3, a client that receives a retransmission of the server's first + * flight will reject that message and discard it (see dtls_IsRelevant() above). + * However, we need to trigger retransmission to prevent loss of the client's + * last flight from causing the connection to fail. + * + * This only triggers for a retransmitted ServerHello. Other (encrypted) + * handshake messages do not trigger retransmission, so we are a little more + * exposed to loss than is ideal. + * + * Note: This isn't an issue in earlier versions because the second-to-last + * flight (sent by the server) includes the Finished message, which is not + * dropped because it has the same epoch that the client currently expects. + */ +SECStatus +dtls_MaybeRetransmitHandshake(sslSocket *ss, const SSL3Ciphertext *cText, + PRBool sameEpoch) +{ + SECStatus rv = SECSuccess; + DTLSEpoch messageEpoch = cText->seq_num >> 48; + + /* Drop messages from other epochs if we are ignoring things. */ + if (!sameEpoch && ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) { + return SECSuccess; + } + + if (!ss->sec.isServer && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 && + messageEpoch == 0 && cText->type == content_handshake) { + ssl_GetSSL3HandshakeLock(ss); + if (ss->ssl3.hs.rtTimerCb == dtls_FinishedTimerCb && + ss->ssl3.hs.ws == idle_handshake) { + rv = dtls_RetransmitDetected(ss); + } + ssl_ReleaseSSL3HandshakeLock(ss); + } + return rv; +} diff --git a/nss/lib/ssl/exports.gyp b/nss/lib/ssl/exports.gyp new file mode 100644 index 0000000..e2123af --- /dev/null +++ b/nss/lib/ssl/exports.gyp @@ -0,0 +1,29 @@ +# 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', + 'sslproto.h', + 'sslt.h' + ], + 'destination': '<(nss_public_dist_dir)/<(module)' + } + ] + } + ], + 'variables': { + 'module': 'nss' + } +} diff --git a/nss/lib/ssl/manifest.mn b/nss/lib/ssl/manifest.mn index 4d46d46..e7564ed 100644 --- a/nss/lib/ssl/manifest.mn +++ b/nss/lib/ssl/manifest.mn @@ -1,4 +1,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/. @@ -7,44 +7,48 @@ CORE_DEPTH = ../.. # DEFINES = -DTRACE EXPORTS = \ - ssl.h \ - sslt.h \ - sslerr.h \ - sslproto.h \ - preenc.h \ - $(NULL) + ssl.h \ + sslt.h \ + sslerr.h \ + sslproto.h \ + preenc.h \ + $(NULL) MODULE = nss MAPFILE = $(OBJDIR)/ssl.def CSRCS = \ - derive.c \ - dtlscon.c \ - prelib.c \ - ssl3con.c \ - ssl3gthr.c \ - sslauth.c \ - sslcon.c \ - ssldef.c \ - sslenum.c \ - sslerr.c \ - sslerrstrs.c \ - sslinit.c \ - ssl3ext.c \ - sslgathr.c \ - sslmutex.c \ - sslnonce.c \ - sslreveal.c \ - sslsecur.c \ - sslsnce.c \ - sslsock.c \ - ssltrace.c \ - sslver.c \ - authcert.c \ - cmpcert.c \ - sslinfo.c \ - ssl3ecc.c \ - $(NULL) + dtlscon.c \ + prelib.c \ + ssl3con.c \ + ssl3gthr.c \ + sslauth.c \ + sslcon.c \ + ssldef.c \ + sslenum.c \ + sslerr.c \ + sslerrstrs.c \ + sslinit.c \ + ssl3ext.c \ + ssl3exthandle.c \ + sslmutex.c \ + sslnonce.c \ + sslreveal.c \ + sslsecur.c \ + sslsnce.c \ + sslsock.c \ + ssltrace.c \ + sslver.c \ + authcert.c \ + cmpcert.c \ + sslinfo.c \ + ssl3ecc.c \ + tls13con.c \ + tls13exthandle.c \ + tls13hkdf.c \ + sslcert.c \ + sslgrp.c \ + $(NULL) LIBRARY_NAME = ssl LIBRARY_VERSION = 3 diff --git a/nss/lib/ssl/notes.txt b/nss/lib/ssl/notes.txt index a71c08e..7a8998a 100644 --- a/nss/lib/ssl/notes.txt +++ b/nss/lib/ssl/notes.txt @@ -10,49 +10,47 @@ incoming: gs = ss->gather hs = ss->ssl3->hs -gs->inbuf SSL3 only: incoming (encrypted) ssl records are placed here, - and then decrypted (or copied) to gs->buf. +gs->inbuf incoming (encrypted) ssl records are placed here, + and then decrypted (or copied) to gs->buf. -gs->buf SSL2: incoming SSL records are put here, and then decrypted - in place. - SSL3: ssl3_HandleHandshake puts decrypted ssl records here. +gs->buf ssl3_HandleHandshake puts decrypted ssl records here. -hs.msg_body (SSL3 only) 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.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 (SSL3 only) 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. +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 = 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. +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. +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->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. +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 +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. --------------------------------------------------------------------------- @@ -65,70 +63,42 @@ sendLock ->/ crypto and hash Data that must be protected while turning plaintext into ciphertext: -SSL2: (in ssl2_Send*) - sec->hash* - sec->hashcx (ptr and data) - sec->enc - sec->writecx* (ptr and content) - sec->sendSecret*(ptr and content) - sec->sendSequence locked by xmitBufLock - sec->blockSize - sec->writeBuf* (ptr & content) locked by xmitBufLock - "in" locked by xmitBufLock - -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_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 -SSL2: (in ssl2_GatherData) - gs->* (locked by recvBufLock ) - sec->dec - sec->readcx - sec->hash* (ptr and data) - sec->hashcx (ptr and data) +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 +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) +ss->saveBuf.* (which is dead) in ssl3_sendPlainText ss->ssl3->current_write-> (spec) ss->sec->writeBuf.* -ss->sec->isServer +ss->sec->isServer in SendBlock -ss->sec->hash->length -ss->sec->blockSize ss->sec->writeBuf.* -ss->sec->sendSecret -ss->sec->sendSequence -ss->sec->writecx * ss->pendingBuf -------------------------------------------------------------------------- -Data variables (not const) protected by the "sslGlobalDataLock". +Data variables (not const) protected by the "sslGlobalDataLock". Note, this really should be a reader/writer lock. -allowedByPolicy sslcon.c -maybeAllowedByPolicy sslcon.c -chosenPreference sslcon.c -policyWasSet sslcon.c - -cipherSuites[] ssl3con.c +cipherSuites[] ssl3con.c diff --git a/nss/lib/ssl/os2_err.c b/nss/lib/ssl/os2_err.c index a69ca91..6e3d423 100644 --- a/nss/lib/ssl/os2_err.c +++ b/nss/lib/ssl/os2_err.c @@ -1,12 +1,12 @@ /* -*- 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 + * 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/. */ @@ -15,7 +15,6 @@ #include "prlog.h" #include <errno.h> - /* * Based on win32err.c * OS2TODO Stub everything for now to build. HCT @@ -24,79 +23,94 @@ /* forward declaration. */ void nss_MD_os2_map_default_error(PRInt32 err); -void nss_MD_os2_map_opendir_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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +void +nss_MD_os2_map_fsync_error(PRInt32 err) { nss_MD_os2_map_default_error(err); } @@ -104,177 +118,213 @@ void nss_MD_os2_map_fsync_error(PRInt32 err) /* * For both CloseHandle() and closesocket(). */ -void nss_MD_os2_map_close_error(PRInt32 err) +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) +void +nss_MD_os2_map_socket_error(PRInt32 err) { -// PR_ASSERT(err != WSANOTINITIALISED); + // PR_ASSERT(err != WSANOTINITIALISED); nss_MD_os2_map_default_error(err); } -void nss_MD_os2_map_recv_error(PRInt32 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) +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) +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; + // 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) +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; + // 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) +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; + // 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) +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) +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; + // 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) +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; + // 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) +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; + // 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) +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) +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; + // 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) +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) +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) +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) +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) +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. +** context, WSAENOTSOCK is equivalent to EBADF on Unix. */ -void nss_MD_os2_map_select_error(PRInt32 err) +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; + // 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) +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) +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 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_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; +// 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; +// case ERROR_FILE_NOT_FOUND: prError = PR_FILE_NOT_FOUND_ERROR; break; #endif - default: prError = PR_UNKNOWN_ERROR; break; + default: + prError = PR_UNKNOWN_ERROR; + break; } PR_SetError(prError, err); } - diff --git a/nss/lib/ssl/os2_err.h b/nss/lib/ssl/os2_err.h index 3052d54..15e4741 100644 --- a/nss/lib/ssl/os2_err.h +++ b/nss/lib/ssl/os2_err.h @@ -1,11 +1,11 @@ /* * This file essentially replicates NSPR's source for the functions that - * map system-specific error codes to NSPR error codes. We would use + * 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/. */ diff --git a/nss/lib/ssl/preenc.h b/nss/lib/ssl/preenc.h index af2475d..bebff89 100644 --- a/nss/lib/ssl/preenc.h +++ b/nss/lib/ssl/preenc.h @@ -25,89 +25,89 @@ 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]; + 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]; + 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]; + 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]; + 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 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)]) +#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]; + unsigned char magic[2]; + unsigned char len[2]; + unsigned char type[2]; + unsigned char version[2]; union { - PEFortezzaHeader fortezza; + PEFortezzaHeader fortezza; PEFortezzaGeneratedHeader g_fortezza; - PEFixedKeyHeader fixed; - PERSAKeyHeader rsa; + 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 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 +#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); + int *headerSize); PEHeader *SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *, - int *headerSize); - + int *headerSize); diff --git a/nss/lib/ssl/prelib.c b/nss/lib/ssl/prelib.c index a15174a..4db9ffe 100644 --- a/nss/lib/ssl/prelib.c +++ b/nss/lib/ssl/prelib.c @@ -17,18 +17,18 @@ #include "preenc.h" #include "pk11func.h" -PEHeader *SSL_PreencryptedStreamToFile(PRFileDesc *fd, PEHeader *inHeader, - int *headerSize) +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) +PEHeader * +SSL_PreencryptedFileToStream(PRFileDesc *fd, PEHeader *header, + int *headerSize) { PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return NULL; } - - diff --git a/nss/lib/ssl/ssl.def b/nss/lib/ssl/ssl.def index 44db4e5..6aa8b64 100644 --- a/nss/lib/ssl/ssl.def +++ b/nss/lib/ssl/ssl.def @@ -5,7 +5,7 @@ ;+# ;+# 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 +;+# 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. @@ -187,3 +187,37 @@ 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: +;+*; +;+}; diff --git a/nss/lib/ssl/ssl.gyp b/nss/lib/ssl/ssl.gyp new file mode 100644 index 0000000..0306ab6 --- /dev/null +++ b/nss/lib/ssl/ssl.gyp @@ -0,0 +1,98 @@ +# 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', + 'prelib.c', + 'ssl3con.c', + 'ssl3ecc.c', + 'ssl3ext.c', + 'ssl3exthandle.c', + 'ssl3gthr.c', + 'sslauth.c', + 'sslcert.c', + 'sslcon.c', + 'ssldef.c', + 'sslenum.c', + 'sslerr.c', + 'sslerrstrs.c', + 'sslgrp.c', + 'sslinfo.c', + 'sslinit.c', + 'sslmutex.c', + 'sslnonce.c', + 'sslreveal.c', + 'sslsecur.c', + 'sslsnce.c', + 'sslsock.c', + 'ssltrace.c', + 'sslver.c', + 'tls13con.c', + 'tls13exthandle.c', + 'tls13hkdf.c', + ], + 'conditions': [ + [ 'OS=="win"', { + 'sources': [ + 'win32err.c', + ], + 'defines': [ + 'IN_LIBSSL', + ], + }, { + # Not Windows. + 'sources': [ + 'unix_err.c' + ], + }], + [ 'ssl_enable_zlib==1', { + 'dependencies': [ + '<(DEPTH)/lib/zlib/zlib.gyp:nss_zlib' + ], + 'defines': [ + 'NSS_SSL_ENABLE_ZLIB', + ], + }], + [ 'fuzz==1', { + 'defines': [ + 'UNSAFE_FUZZER_MODE', + ], + }], + ], + 'dependencies': [ + '<(DEPTH)/exports.gyp:nss_exports', + '<(DEPTH)/lib/freebl/freebl.gyp:freebl', + ], + }, + { + 'target_name': 'ssl3', + 'type': 'shared_library', + 'dependencies': [ + 'ssl', + '<(DEPTH)/lib/nss/nss.gyp:nss3', + '<(DEPTH)/lib/util/util.gyp:nssutil3', + ], + 'variables': { + 'mapfile': 'ssl.def' + } + } + ], + 'target_defaults': { + 'defines': [ + 'NSS_ALLOW_SSLKEYLOGFILE=1' + ] + }, + 'variables': { + 'module': 'nss' + } +} diff --git a/nss/lib/ssl/ssl.h b/nss/lib/ssl/ssl.h index 2a52769..b4af0e1 100644 --- a/nss/lib/ssl/ssl.h +++ b/nss/lib/ssl/ssl.h @@ -15,7 +15,7 @@ #include "cert.h" #include "keyt.h" -#include "sslt.h" /* public ssl data types */ +#include "sslt.h" /* public ssl data types */ #if defined(_WIN32) && !defined(IN_LIBSSL) && !defined(NSS_USE_STATIC_LIBS) #define SSL_IMPORT extern __declspec(dllimport) @@ -25,7 +25,7 @@ SEC_BEGIN_PROTOS -/* constant table enumerating all implemented SSL 2 and 3 cipher suites. */ +/* constant table enumerating all implemented cipher suites. */ SSL_IMPORT const PRUint16 SSL_ImplementedCiphers[]; /* the same as the above, but is a function */ @@ -38,7 +38,7 @@ SSL_IMPORT const PRUint16 SSL_NumImplementedCiphers; 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) +#define SSL_IS_SSL2_CIPHER(which) (((which)&0xfff0) == 0xff00) /* ** Imports fd into SSL, returning a new socket. Copies SSL configuration @@ -55,72 +55,69 @@ 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_SECURITY: +** enable/disable use of SSL security protocol before connect ** -** SSL_SOCKS: -** enable/disable use of socks before connect -** (No longer supported). +** SSL_SOCKS: +** enable/disable use of socks before connect +** (No longer supported). ** -** SSL_REQUEST_CERTIFICATE: -** require a certificate during secure connect +** 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) */ +#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) */ +#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_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) */ +#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) */ +#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 /* Disable export cipher suites */ - /* if step-down keys are needed. */ - /* default: off, generate */ - /* step-down keys if needed. */ -#define SSL_BYPASS_PKCS11 16 /* use PKCS#11 for pub key only */ -#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 /* Enable TLS compression with */ - /* DEFLATE (off by default) */ -#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 */ +#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 /* Enable TLS compression with */ + /* DEFLATE (off by default) */ +#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 @@ -160,7 +157,7 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); * accept fragmented alerts). */ #define SSL_CBC_RANDOM_IV 23 -#define SSL_ENABLE_OCSP_STAPLING 24 /* Request OCSP stapling (client) */ +#define SSL_ENABLE_OCSP_STAPLING 24 /* Request OCSP stapling (client) */ /* SSL_ENABLE_NPN controls whether the NPN extension is enabled for the initial * handshake when application layer protocol negotiation is used. @@ -189,8 +186,8 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); */ #define SSL_REUSE_SERVER_ECDHE_KEY 27 -#define SSL_ENABLE_FALLBACK_SCSV 28 /* Send fallback SCSV in - * handshakes. */ +#define SSL_ENABLE_FALLBACK_SCSV 28 /* Send fallback SCSV in \ + * handshakes. */ /* SSL_ENABLE_SERVER_DHE controls whether DHE is enabled for the server socket. */ @@ -203,8 +200,46 @@ SSL_IMPORT PRFileDesc *DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd); */ #define SSL_ENABLE_EXTENDED_MASTER_SECRET 30 +/* Request Signed Certificate Timestamps via TLS extension (client) */ +#define SSL_ENABLE_SIGNED_CERT_TIMESTAMPS 31 -#ifdef SSL_DEPRECATED_FUNCTION +/* 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 [TODO(ekr@rtfm.com): This hasn't landed yet]. + * + * The transition between the 0-RTT and 1-RTT modes is marked by the + * handshake callback. + * + * WARNING: 0-RTT data has different anti-replay and PFS properties than + * the rest of the TLS data. See [draft-ietf-tls-tls13; Section 6.2.3] + * for more details. + */ +#define SSL_ENABLE_0RTT_DATA 33 + +#ifdef SSL_DEPRECATED_FUNCTION /* Old deprecated function names */ SSL_IMPORT SECStatus SSL_Enable(PRFileDesc *fd, int option, PRBool on); SSL_IMPORT SECStatus SSL_EnableDefault(int option, PRBool on); @@ -227,13 +262,13 @@ SSL_IMPORT SECStatus SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHan * * The callback must return SECFailure or SECSuccess (not SECWouldBlock). */ -typedef SECStatus (PR_CALLBACK *SSLNextProtoCallback)( +typedef SECStatus(PR_CALLBACK *SSLNextProtoCallback)( void *arg, PRFileDesc *fd, - const unsigned char* protos, + const unsigned char *protos, unsigned int protosLen, - unsigned char* protoOut, - unsigned int* protoOutLen, + unsigned char *protoOut, + unsigned int *protoOutLen, unsigned int protoMaxOut); /* SSL_SetNextProtoCallback sets a callback function to handle Next Protocol @@ -261,14 +296,15 @@ SSL_IMPORT SECStatus SSL_SetNextProtoCallback(PRFileDesc *fd, * The supported protocols are specified in |data| in wire-format (8-bit * length-prefixed). For example: "\010http/1.1\006spdy/2". */ 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) */ + 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 @@ -279,19 +315,19 @@ typedef enum SSLNextProtoState { * 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); + 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. +** 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 +#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); @@ -306,46 +342,87 @@ SSL_IMPORT SECStatus SSL_CipherPolicySet(PRInt32 cipher, PRInt32 policy); SSL_IMPORT SECStatus SSL_CipherPolicyGet(PRInt32 cipher, PRInt32 *policy); /* -** Control for TLS signature algorithms for TLS 1.2 only. +** Control for TLS signature schemes for TLS 1.2 and 1.3. ** -** This governs what signature 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 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. It also changes what the server uses to sign -** ServerKeyExchange: a server uses the first entry from this list that is -** compatible with the client's advertised signature_algorithms extension and -** the selected server certificate. +** 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. +** +** NSS uses the strict signature schemes from TLS 1.3 in TLS 1.2. That means +** that if a peer indicates support for SHA-384 and ECDSA, NSS will not +** generate a signature if it has a P-256 key, even though that is permitted in +** TLS 1.2. ** -** Omitting SHA-256 from this list might be foolish. Support is mandatory in -** TLS 1.2 and there might be interoperability issues. For a server, NSS only -** supports SHA-256 for verifying a TLS 1.2 CertificateVerify. This list needs -** to include SHA-256 if client authentication is requested or required, or -** creating a CertificateRequest will fail. +** 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 algorithms. +** Get the currently configured signature schemes. ** -** The algorithms are written to |algorithms| but not if there are more than -** |maxCount| values configured. The number of algorithms that are in use are +** 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_SignaturePrefSet or SSL_SignaturePrefGet. +** can be set or retrieved using SSL_SignatureSchemePrefSet or +** SSL_SignatureSchemePrefGet. */ SSL_IMPORT unsigned int SSL_SignatureMaxCount(); -/* SSL_DHEGroupPrefSet is used to configure the set of allowed/enabled DHE group +/* +** 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. @@ -354,7 +431,7 @@ SSL_IMPORT unsigned int SSL_SignatureMaxCount(); ** For example, a TLS extension sent by the client might indicate a preference. */ SSL_IMPORT SECStatus SSL_DHEGroupPrefSet(PRFileDesc *fd, - SSLDHEGroupType *groups, + const SSLDHEGroupType *groups, PRUint16 num_groups); /* Enable the use of a DHE group that's smaller than the library default, @@ -375,13 +452,11 @@ SSL_IMPORT SECStatus SSL_DHEGroupPrefSet(PRFileDesc *fd, ** 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_DHEGroupPrefSet 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, overriding the preference -** for the first group potentially set with a call to SSL_DHEGroupPrefSet -** (The first group set using SSL_DHEGroupPrefSet will still be enabled, but -** it's no longer the default 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); @@ -449,34 +524,46 @@ SSL_IMPORT SECStatus SSL_VersionRangeSetDefault( /* Returns, in |*vrange|, the range of enabled SSL3/TLS versions for |fd|. */ SSL_IMPORT SECStatus SSL_VersionRangeGet(PRFileDesc *fd, - SSLVersionRange *vrange); + SSLVersionRange *vrange); /* Sets the range of enabled SSL3/TLS versions for |fd| to |*vrange|. */ SSL_IMPORT SECStatus SSL_VersionRangeSet(PRFileDesc *fd, - const SSLVersionRange *vrange); - + 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. */ +#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_NEVER ((PRBool)0) +#define SSL_REQUIRE_ALWAYS ((PRBool)1) #define SSL_REQUIRE_FIRST_HANDSHAKE ((PRBool)2) -#define SSL_REQUIRE_NO_ERROR ((PRBool)3) +#define SSL_REQUIRE_NO_ERROR ((PRBool)3) /* Values for "on" with SSL_ENABLE_RENEGOTIATION */ /* Never renegotiate at all. */ -#define SSL_RENEGOTIATE_NEVER ((PRBool)0) +#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) +#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 */ @@ -514,22 +601,22 @@ SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, ** 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); + 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 */ +#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 +** "fd" the socket "file" descriptor */ SSL_IMPORT CERTCertificate *SSL_PeerCertificate(PRFileDesc *fd); @@ -538,7 +625,7 @@ SSL_IMPORT CERTCertificate *SSL_PeerCertificate(PRFileDesc *fd); ** 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 +** "fd" the socket "file" descriptor */ SSL_IMPORT CERTCertList *SSL_PeerCertificateChain(PRFileDesc *fd); @@ -558,17 +645,50 @@ SSL_IMPORT CERTCertList *SSL_PeerCertificateChain(PRFileDesc *fd); * 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_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); + 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 @@ -601,41 +721,40 @@ SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, ** 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); +typedef SECStatus(PR_CALLBACK *SSLAuthCertificate)(void *arg, PRFileDesc *fd, + PRBool checkSig, + PRBool isServer); -SSL_IMPORT SECStatus SSL_AuthCertificateHook(PRFileDesc *fd, - SSLAuthCertificate f, - void *arg); +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); +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 + * 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 */ -typedef SECStatus (PR_CALLBACK *SSLGetClientAuthData)(void *arg, - PRFileDesc *fd, - CERTDistNames *caNames, - CERTCertificate **pRetCert,/*return */ - SECKEYPrivateKey **pRetKey);/* return */ +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 + * 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); - +SSL_IMPORT SECStatus SSL_GetClientAuthDataHook(PRFileDesc *fd, + SSLGetClientAuthData f, void *a); /* ** SNI extension processing callback function. @@ -663,10 +782,10 @@ SSL_IMPORT SECStatus SSL_GetClientAuthDataHook(PRFileDesc *fd, ** 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); +typedef PRInt32(PR_CALLBACK *SSLSNISocketConfig)(PRFileDesc *fd, + const SECItem *srvNameArr, + PRUint32 srvNameArrSize, + void *arg); /* ** SSLSNISocketConfig should return an index within 0 and srvNameArrSize-1 @@ -675,13 +794,13 @@ typedef PRInt32 (PR_CALLBACK *SSLSNISocketConfig)(PRFileDesc *fd, ** 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 +#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, +SSL_IMPORT SECStatus SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig f, void *arg); @@ -694,8 +813,8 @@ 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 + * fd - the file descriptor for the connection in question + * a - pkcs11 application specific data */ SSL_IMPORT SECStatus SSL_SetPKCS11PinArg(PRFileDesc *fd, void *a); @@ -714,22 +833,80 @@ SSL_IMPORT SECStatus SSL_SetPKCS11PinArg(PRFileDesc *fd, void *a); ** 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); +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); + PRFileDesc *fd, CERTCertificate *cert, + SECKEYPrivateKey *key, SSLKEAType kea); /* -** Allows SSL socket configuration with caller-supplied certificate chain. -** If certChainOpt is NULL, tries to find one. +** 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, @@ -739,63 +916,63 @@ SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert, /* ** 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 +** 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 +** 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); +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); + 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 +** 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 +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 +** 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 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" +#define SSL_ENV_VAR_NAME "SSL_INHERITANCE" -/* called in child to inherit SID Cache variables. +/* 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 + * variable "SSL_INHERITANCE", otherwise the string value passed in will be * used. */ -SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char * envString); +SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char *envString); /* ** Set the callback that gets called when a TLS handshake is complete. The @@ -807,10 +984,10 @@ SSL_IMPORT SECStatus SSL_InheritMPServerSIDCache(const char * envString); ** 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); +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 @@ -823,7 +1000,7 @@ SSL_IMPORT SECStatus SSL_HandshakeCallback(PRFileDesc *fd, ** 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)( +typedef SECStatus(PR_CALLBACK *SSLCanFalseStartCallback)( PRFileDesc *fd, void *arg, PRBool *canFalseStart); SSL_IMPORT SECStatus SSL_SetCanFalseStartCallback( @@ -839,10 +1016,10 @@ SSL_IMPORT SECStatus SSL_RecommendedCanFalseStart(PRFileDesc *fd, /* ** 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 +** 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 +** 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); @@ -854,12 +1031,11 @@ SSL_IMPORT SECStatus SSL_ReHandshakeWithTimeout(PRFileDesc *fd, PRBool flushCache, PRIntervalTime timeout); - -#ifdef SSL_DEPRECATED_FUNCTION +#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. +** 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); @@ -909,11 +1085,11 @@ SSL_IMPORT SECStatus SSL_ShutdownServerSessionIDCache(void); SSL_IMPORT SECStatus SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID); /* -** Reveal the security information for the peer. +** 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); +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. @@ -921,14 +1097,14 @@ SSL_IMPORT char * SSL_RevealURL(PRFileDesc * socket); * (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 + * 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, +NSS_GetClientAuthData(void *arg, + PRFileDesc *socket, + struct CERTDistNamesStr *caNames, + struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey); /* @@ -942,8 +1118,8 @@ NSS_GetClientAuthData(void * arg, ** Otherwise returns SECFailure. */ SSL_IMPORT SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, - const PRUint16 *ciphers, - unsigned int numCiphers); + const PRUint16 *ciphers, + unsigned int numCiphers); /* ** Get the selected DTLS-SRTP cipher suite (if any). @@ -951,21 +1127,22 @@ SSL_IMPORT SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, ** Returns SECFailure if not negotiated. */ SSL_IMPORT SECStatus SSL_GetSRTPCipher(PRFileDesc *fd, - PRUint16 *cipher); + PRUint16 *cipher); /* * Look to see if any of the signers in the cert chain for "cert" are found - * in the list of caNames. + * 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); +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); +SSL_IMPORT SSLKEAType NSS_FindCertKEAType(CERTCertificate *cert); /* Set cipher policies to a predefined Domestic (U.S.A.) policy. * This essentially allows all supported ciphers. @@ -979,16 +1156,18 @@ SSL_IMPORT SECStatus NSS_SetDomesticPolicy(void); 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 + * 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); +SSL_IMPORT SSL3Statistics *SSL_GetStatistics(void); /* Report more information than SSL_SecurityStatus. - * Caller supplies the info struct. This function fills it in. + * 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 @@ -998,6 +1177,9 @@ SSL_IMPORT SSL3Statistics * SSL_GetStatistics(void); 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, @@ -1009,8 +1191,12 @@ SSL_IMPORT SECStatus SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, SSLPreliminaryChannelInfo *info, PRUintn len); -SSL_IMPORT SECStatus SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, - SSLCipherSuiteInfo *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); @@ -1030,48 +1216,38 @@ SSL_IMPORT SECStatus SSL_ExportKeyingMaterial(PRFileDesc *fd, 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); - -/* Test an SSL configuration to see if SSL_BYPASS_PKCS11 can be turned on. -** Check the key exchange algorithm for each cipher in the list to see if -** a master secret key can be extracted after being derived with the mechanism -** required by the protocolmask argument. If the KEA will use keys from the -** specified cert make sure the extract operation is attempted from the slot -** where the private key resides. -** If MS can be extracted for all ciphers, (*pcanbypass) is set to TRUE and -** SECSuccess is returned. In all other cases but one (*pcanbypass) is -** set to FALSE and SECFailure is returned. -** In that last case Derive() has been called successfully but the MS is null, -** CanBypass sets (*pcanbypass) to FALSE and returns SECSuccess indicating the -** arguments were all valid but the slot cannot be bypassed. -** -** Note: A TRUE return code from CanBypass means "Your configuration will perform -** NO WORSE with the bypass enabled than without"; it does NOT mean that every -** cipher suite listed will work properly with the selected protocols. -** -** Caveat: If export cipher suites are included in the argument list Canbypass -** will return FALSE. -**/ +SSL_IMPORT CERTCertificate *SSL_LocalCertificate(PRFileDesc *fd); -/* protocol mask bits */ -#define SSL_CBP_SSL3 0x0001 /* test SSL v3 mechanisms */ -#define SSL_CBP_TLS1_0 0x0002 /* test TLS v1.0 mechanisms */ +#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, + 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, +SSL_IMPORT SECStatus SSL_HandshakeNegotiatedExtension(PRFileDesc *socket, SSLExtensionType extId, PRBool *yes); @@ -1161,7 +1337,7 @@ extern const char *NSSSSL_GetVersion(void); * connection. */ SSL_IMPORT SECStatus SSL_AuthCertificateComplete(PRFileDesc *fd, - PRErrorCode error); + PRErrorCode error); SEC_END_PROTOS #endif /* __ssl_h_ */ diff --git a/nss/lib/ssl/ssl3con.c b/nss/lib/ssl/ssl3con.c index 8f1c547..154d22a 100644 --- a/nss/lib/ssl/ssl3con.c +++ b/nss/lib/ssl/ssl3con.c @@ -10,7 +10,7 @@ #include "cert.h" #include "ssl.h" -#include "cryptohi.h" /* for DSAU_ stuff */ +#include "cryptohi.h" /* for DSAU_ stuff */ #include "keyhi.h" #include "secder.h" #include "secitem.h" @@ -19,6 +19,8 @@ #include "sslimpl.h" #include "sslproto.h" #include "sslerr.h" +#include "ssl3ext.h" +#include "ssl3exthandle.h" #include "prtime.h" #include "prinrval.h" #include "prerror.h" @@ -29,59 +31,54 @@ #include "pk11func.h" #include "secmod.h" -#ifndef NO_PKCS11_BYPASS #include "blapi.h" -#endif #include <stdio.h> -#ifdef NSS_ENABLE_ZLIB +#ifdef NSS_SSL_ENABLE_ZLIB #include "zlib.h" #endif #ifndef PK11_SETATTRS -#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ - (x)->pValue=(v); (x)->ulValueLen = (l); +#define PK11_SETATTRS(x, id, v, l) \ + (x)->type = (id); \ + (x)->pValue = (v); \ + (x)->ulValueLen = (l); #endif -static SECStatus ssl3_AuthCertificate(sslSocket *ss); -static void ssl3_CleanupPeerCerts(sslSocket *ss); static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, - PK11SlotInfo * serverKeySlot); + PK11SlotInfo *serverKeySlot); static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms); -static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss); -static SECStatus ssl3_HandshakeFailure( sslSocket *ss); -static SECStatus ssl3_InitState( sslSocket *ss); -static SECStatus ssl3_SendCertificate( sslSocket *ss); -static SECStatus ssl3_SendCertificateStatus( sslSocket *ss); -static SECStatus ssl3_SendEmptyCertificate( sslSocket *ss); +static SECStatus ssl3_DeriveConnectionKeys(sslSocket *ss); +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_SendServerHello( sslSocket *ss); -static SECStatus ssl3_SendServerHelloDone( sslSocket *ss); -static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss); -static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss, - const unsigned char *b, - unsigned int l); -static SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss, - ssl3CipherSpec *spec, - SSL3Hashes *hashes, - PRUint32 sender); +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, + SECItem *comps, + sslSessionID *sid); +static SECStatus ssl3_HandleServerHelloPart2(sslSocket *ss, + const SECItem *sidBytes, + int *retErrCode); +static SECStatus ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, + SSL3Opaque *b, + PRUint32 length, + SSL3Hashes *hashesPtr); static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, - int maxOutputLen, const unsigned char *input, - int inputLen); -#ifndef NO_PKCS11_BYPASS -static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, - unsigned char *out, int *outlen, int maxout, - const unsigned char *in, int inlen, - const unsigned char *additionalData, - int additionalDataLen); -#endif + int maxOutputLen, const unsigned char *input, + int inputLen); + +static CK_MECHANISM_TYPE ssl3_GetHashMechanismByHashType(SSLHashType hashType); +static CK_MECHANISM_TYPE ssl3_GetMgfMechanismByHashType(SSLHashType hash); +PRBool ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme); #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */ -#define MIN_SEND_BUF_LENGTH 4000 +#define MIN_SEND_BUF_LENGTH 4000 /* This list of SSL3 cipher suites is sorted in descending order of * precedence (desirability). It only includes cipher suites we implement. @@ -91,12 +88,20 @@ static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt, * 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 }, -#ifndef NSS_DISABLE_ECC { 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_FALSE, PR_FALSE}, + { TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_FALSE, PR_FALSE}, /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around * bug 946147. */ @@ -106,14 +111,18 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { { 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}, -#endif /* NSS_DISABLE_ECC */ { 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_FALSE, 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}, @@ -130,7 +139,6 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { { 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}, -#ifndef NSS_DISABLE_ECC { 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}, @@ -139,10 +147,10 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { { 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}, -#endif /* NSS_DISABLE_ECC */ /* RSA */ { TLS_RSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_TRUE, PR_FALSE}, + { TLS_RSA_WITH_AES_256_GCM_SHA384, SSL_ALLOWED, PR_FALSE, 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}, @@ -150,7 +158,6 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { { 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}, - { SSL_RSA_FIPS_WITH_3DES_EDE_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}, @@ -158,57 +165,55 @@ static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = { /* 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}, - { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, { TLS_RSA_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, - /* export ciphersuites with 1024-bit public key exchange keys */ - { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, - { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, PR_FALSE, PR_FALSE}, - - /* export ciphersuites with 512-bit public key exchange keys */ - { TLS_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, - { TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, PR_FALSE, PR_FALSE}, - /* ciphersuites with no encryption */ -#ifndef NSS_DISABLE_ECC { 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}, -#endif /* NSS_DISABLE_ECC */ { 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}, }; - -static const SSLSignatureAndHashAlg defaultSignatureAlgorithms[] = { - {ssl_hash_sha256, ssl_sign_rsa}, - {ssl_hash_sha384, ssl_sign_rsa}, - {ssl_hash_sha512, ssl_sign_rsa}, - {ssl_hash_sha1, ssl_sign_rsa}, -#ifndef NSS_DISABLE_ECC - {ssl_hash_sha256, ssl_sign_ecdsa}, - {ssl_hash_sha384, ssl_sign_ecdsa}, - {ssl_hash_sha512, ssl_sign_ecdsa}, - {ssl_hash_sha1, ssl_sign_ecdsa}, -#endif - {ssl_hash_sha256, ssl_sign_dsa}, - {ssl_hash_sha1, ssl_sign_dsa} +/* 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_sha256, + ssl_sig_rsa_pss_sha384, + ssl_sig_rsa_pss_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(defaultSignatureAlgorithms) <= - MAX_SIGNATURE_ALGORITHMS); +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() +void +ssl3_CheckCipherSuiteOrderConsistency() { unsigned int i; - /* Note that SSL_ImplementedCiphers has more elements than cipherSuites - * because it SSL_ImplementedCiphers includes SSL 2.0 cipher suites. - */ - PORT_Assert(SSL_NumImplementedCiphers >= PR_ARRAY_SIZE(cipherSuites)); + 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); @@ -220,363 +225,391 @@ void ssl3_CheckCipherSuiteOrderConsistency() * precedence (desirability). It only includes compression methods we * implement. */ -static const /*SSLCompressionMethod*/ PRUint8 compressions [] = { -#ifdef NSS_ENABLE_ZLIB +static const SSLCompressionMethod ssl_compression_methods[] = { +#ifdef NSS_SSL_ENABLE_ZLIB ssl_compression_deflate, #endif ssl_compression_null }; -static const int compressionMethodsCount = - sizeof(compressions) / sizeof(compressions[0]); +static const unsigned int ssl_compression_method_count = + PR_ARRAY_SIZE(ssl_compression_methods); /* compressionEnabled returns true iff the compression algorithm is enabled * for the given SSL socket. */ static PRBool -compressionEnabled(sslSocket *ss, SSLCompressionMethod compression) +ssl_CompressionEnabled(sslSocket *ss, SSLCompressionMethod compression) { - switch (compression) { - case ssl_compression_null: - return PR_TRUE; /* Always enabled */ -#ifdef NSS_ENABLE_ZLIB - case ssl_compression_deflate: - if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { - return ss->opt.enableDeflate; - } + SSL3ProtocolVersion version; + + if (compression == ssl_compression_null) { + return PR_TRUE; /* Always enabled */ + } + if (ss->sec.isServer) { + /* We can't easily check that the client didn't attempt TLS 1.3, + * so this will have to do. */ + PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); + version = ss->version; + } else { + version = ss->vrange.max; + } + if (version >= SSL_LIBRARY_VERSION_TLS_1_3) { return PR_FALSE; -#endif - default: - return PR_FALSE; } +#ifdef NSS_SSL_ENABLE_ZLIB + if (compression == ssl_compression_deflate) { + if (IS_DTLS(ss)) { + return PR_FALSE; + } + return ss->opt.enableDeflate; + } +#endif + return PR_FALSE; } -static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = { +static const /*SSL3ClientCertificateType */ PRUint8 certificate_types[] = { ct_RSA_sign, -#ifndef NSS_DISABLE_ECC ct_ECDSA_sign, -#endif /* NSS_DISABLE_ECC */ ct_DSS_sign, }; -#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ - - /* This global item is used only in servers. It is is initialized by ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest(). */ CERTDistNames *ssl3_server_ca_list = NULL; static SSL3Statistics ssl3stats; -/* indexed by SSL3BulkCipher */ +/* 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 bulk_cipher_defs[] = { - /* |--------- Lengths --------| */ - /* cipher calg k s type i b t n */ - /* e e v l a o */ - /* y c | o g n */ - /* | r | c | c */ - /* | e | k | e */ - /* | t | | | | */ - {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, - {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0}, - {cipher_rc4_40, calg_rc4, 16, 5, type_stream, 0, 0, 0, 0}, - {cipher_rc4_56, calg_rc4, 16, 7, type_stream, 0, 0, 0, 0}, - {cipher_rc2, calg_rc2, 16,16, type_block, 8, 8, 0, 0}, - {cipher_rc2_40, calg_rc2, 16, 5, type_block, 8, 8, 0, 0}, - {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0}, - {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0}, - {cipher_des40, calg_des, 8, 5, type_block, 8, 8, 0, 0}, - {cipher_idea, calg_idea, 16,16, type_block, 8, 8, 0, 0}, - {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0}, - {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0}, - {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0}, - {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0}, - {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0}, - {cipher_aes_128_gcm, calg_aes_gcm, 16,16, type_aead, 4, 0,16, 8}, - {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0}, + /* |--------- Lengths ---------| */ + /* cipher calg : s : */ + /* : e b n */ + /* oid short_name mr : l o */ + /* k r o t n */ + /* e e i c a c */ + /* y t type v k g e */ + {cipher_null, calg_null, 0, 0, type_stream, 0, 0, 0, 0, + SEC_OID_NULL_CIPHER, "NULL", MR_MAX}, + {cipher_rc4, calg_rc4, 16,16, type_stream, 0, 0, 0, 0, + SEC_OID_RC4, "RC4", MR_LOW}, + {cipher_des, calg_des, 8, 8, type_block, 8, 8, 0, 0, + SEC_OID_DES_CBC, "DES-CBC", MR_LOW}, + {cipher_3des, calg_3des, 24,24, type_block, 8, 8, 0, 0, + SEC_OID_DES_EDE3_CBC, "3DES-EDE-CBC", MR_LOW}, + {cipher_aes_128, calg_aes, 16,16, type_block, 16,16, 0, 0, + SEC_OID_AES_128_CBC, "AES-128", MR_128}, + {cipher_aes_256, calg_aes, 32,32, type_block, 16,16, 0, 0, + SEC_OID_AES_256_CBC, "AES-256", MR_128}, + {cipher_camellia_128, calg_camellia, 16,16, type_block, 16,16, 0, 0, + SEC_OID_CAMELLIA_128_CBC, "Camellia-128", MR_128}, + {cipher_camellia_256, calg_camellia, 32,32, type_block, 16,16, 0, 0, + SEC_OID_CAMELLIA_256_CBC, "Camellia-256", MR_128}, + {cipher_seed, calg_seed, 16,16, type_block, 16,16, 0, 0, + SEC_OID_SEED_CBC, "SEED-CBC", MR_128}, + {cipher_aes_128_gcm, 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, calg_aes_gcm, 32,32, type_aead, 4, 0,16, 8, + SEC_OID_AES_256_GCM, "AES-256-GCM", MR_128}, + {cipher_chacha20, calg_chacha20, 32,32, type_aead, 12, 0,16, 0, + SEC_OID_CHACHA20_POLY1305, "ChaCha20-Poly1305", MR_MAX}, + {cipher_missing, calg_null, 0, 0, type_stream, 0, 0, 0, 0, + SEC_OID_UNKNOWN, "missing", 0U}, }; static const ssl3KEADef kea_defs[] = { /* indexed by SSL3KeyExchangeAlgorithm */ - /* kea exchKeyType signKeyType is_limited limit tls_keygen ephemeral */ - {kea_null, kt_null, sign_null, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_rsa, kt_rsa, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_rsa_export, kt_rsa, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE}, - {kea_rsa_export_1024,kt_rsa, sign_rsa, PR_TRUE, 1024, PR_FALSE, PR_FALSE}, - {kea_dh_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_dh_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE, PR_FALSE}, - {kea_dh_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_dh_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_FALSE}, - {kea_dhe_dss, kt_dh, sign_dsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_dhe_dss_export, kt_dh, sign_dsa, PR_TRUE, 512, PR_FALSE, PR_TRUE}, - {kea_dhe_rsa, kt_dh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_dhe_rsa_export, kt_dh, sign_rsa, PR_TRUE, 512, PR_FALSE, PR_TRUE}, - {kea_dh_anon, kt_dh, sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_dh_anon_export, kt_dh, sign_null, PR_TRUE, 512, PR_FALSE, PR_TRUE}, - {kea_rsa_fips, kt_rsa, sign_rsa, PR_FALSE, 0, PR_TRUE, PR_FALSE}, -#ifndef NSS_DISABLE_ECC - {kea_ecdh_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_ecdhe_ecdsa, kt_ecdh, sign_ecdsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_ecdh_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_FALSE}, - {kea_ecdhe_rsa, kt_ecdh, sign_rsa, PR_FALSE, 0, PR_FALSE, PR_TRUE}, - {kea_ecdh_anon, kt_ecdh, sign_null, PR_FALSE, 0, PR_FALSE, PR_TRUE}, -#endif /* NSS_DISABLE_ECC */ + /* 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 */ - - {TLS_NULL_WITH_NULL_NULL, cipher_null, mac_null, kea_null}, - {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa}, - {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa}, - {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa}, - {TLS_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export}, - {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa}, - {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa}, - {TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_rc2_40, mac_md5, kea_rsa_export}, -#if 0 /* not implemented */ - {TLS_RSA_WITH_IDEA_CBC_SHA, cipher_idea, mac_sha, kea_rsa}, - {TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_des40, mac_sha, kea_rsa_export}, -#endif - {TLS_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa}, - {TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa}, - {TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss}, +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, mac_null, kea_null, ssl_hash_none}, + {TLS_RSA_WITH_NULL_MD5, cipher_null, mac_md5, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_NULL_SHA256, cipher_null, hmac_sha256, kea_rsa, ssl_hash_sha256}, + {TLS_RSA_WITH_RC4_128_MD5, cipher_rc4, mac_md5, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa, ssl_hash_none}, + {TLS_DHE_DSS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_dss, ssl_hash_none}, {TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_3des, mac_sha, kea_dhe_dss}, - {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss}, -#if 0 /* not implemented */ - {TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_des40, mac_sha, kea_dh_dss_export}, - {TLS_DH_DSS_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_dss}, - {TLS_DH_DSS_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_dss}, - {TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_des40, mac_sha, kea_dh_rsa_export}, - {TLS_DH_RSA_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_rsa}, - {TLS_DH_RSA_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_rsa}, - {TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_des40, mac_sha, kea_dh_dss_export}, - {TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_des40, mac_sha, kea_dh_rsa_export}, -#endif - {TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa}, + cipher_3des, mac_sha, kea_dhe_dss, ssl_hash_none}, + {TLS_DHE_DSS_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_dhe_dss, ssl_hash_none}, + {TLS_DHE_RSA_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dhe_rsa, ssl_hash_none}, {TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_3des, mac_sha, kea_dhe_rsa}, -#if 0 - {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export}, - {TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, - cipher_des40, mac_sha, kea_dh_anon_export}, - {TLS_DH_anon_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_dh_anon}, - {TLS_DH_anon_WITH_3DES_CBC_SHA, cipher_3des, mac_sha, kea_dh_anon}, -#endif + cipher_3des, mac_sha, kea_dhe_rsa, ssl_hash_none}, /* New TLS cipher suites */ - {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa}, - {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa}, - {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss}, - {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa}, - {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa}, - {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa}, - {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa}, - {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss}, - {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa}, - {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa}, -#if 0 - {TLS_DH_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_dss}, - {TLS_DH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_rsa}, - {TLS_DH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dh_anon}, - {TLS_DH_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_dss}, - {TLS_DH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_rsa}, - {TLS_DH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dh_anon}, -#endif - - {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa}, - - {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa}, + {TLS_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_rsa, ssl_hash_sha256}, + {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_dss, ssl_hash_none}, + {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_dhe_rsa, ssl_hash_none}, + {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa, ssl_hash_sha256}, + {TLS_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_rsa, ssl_hash_none}, + {TLS_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_rsa, ssl_hash_sha256}, + {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_dss, ssl_hash_none}, + {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_dhe_rsa, ssl_hash_none}, + {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa, ssl_hash_sha256}, + {TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, mac_aead, kea_dhe_rsa, ssl_hash_sha384}, + + {TLS_RSA_WITH_SEED_CBC_SHA, cipher_seed, mac_sha, kea_rsa, ssl_hash_none}, + + {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa, ssl_hash_none}, {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_camellia_128, mac_sha, kea_dhe_dss}, + cipher_camellia_128, mac_sha, kea_dhe_dss, ssl_hash_none}, {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_camellia_128, mac_sha, kea_dhe_rsa}, - {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa}, + cipher_camellia_128, mac_sha, kea_dhe_rsa, ssl_hash_none}, + {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, cipher_camellia_256, mac_sha, kea_rsa, ssl_hash_none}, {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_camellia_256, mac_sha, kea_dhe_dss}, + cipher_camellia_256, mac_sha, kea_dhe_dss, ssl_hash_none}, {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_camellia_256, mac_sha, kea_dhe_rsa}, - - {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, - cipher_des, mac_sha,kea_rsa_export_1024}, - {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, - cipher_rc4_56, mac_sha,kea_rsa_export_1024}, - - {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips}, - {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des, mac_sha, kea_rsa_fips}, - - {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa}, - {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa}, - {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa}, - {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa}, - - {TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_dss}, - {TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_dss}, - {TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_dss}, - -#ifndef NSS_DISABLE_ECC - {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa}, - {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa}, - {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa}, - {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa}, - {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa}, - - {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa}, - {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa}, - {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa}, - {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa}, - {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa}, - {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa}, - - {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa}, - {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa}, - {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa}, - {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa}, - {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa}, - - {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa}, - {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa}, - {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa}, - {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa}, - {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa}, - {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa}, - -#if 0 - {TLS_ECDH_anon_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_anon}, - {TLS_ECDH_anon_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_anon}, - {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_anon}, - {TLS_ECDH_anon_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_anon}, - {TLS_ECDH_anon_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_anon}, -#endif -#endif /* NSS_DISABLE_ECC */ + cipher_camellia_256, mac_sha, kea_dhe_rsa, ssl_hash_none}, + + {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa, ssl_hash_sha256}, + {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa, ssl_hash_sha256}, + + {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa, ssl_hash_sha256}, + {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256}, + {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha384}, + {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, mac_aead, kea_ecdhe_rsa, ssl_hash_sha384}, + {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, hmac_sha384, kea_ecdhe_ecdsa, ssl_hash_sha384}, + {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, cipher_aes_256, hmac_sha384, kea_ecdhe_rsa, ssl_hash_sha384}, + {TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_dss, ssl_hash_sha256}, + {TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_dss, ssl_hash_sha256}, + {TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_dss, ssl_hash_sha256}, + {TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, mac_aead, kea_dhe_dss, ssl_hash_sha384}, + {TLS_RSA_WITH_AES_256_GCM_SHA384, cipher_aes_256_gcm, mac_aead, kea_rsa, ssl_hash_sha384}, + + {TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_dhe_rsa, ssl_hash_sha256}, + + {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_ecdhe_rsa, ssl_hash_sha256}, + {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_ecdhe_ecdsa, ssl_hash_sha256}, + + {TLS_ECDH_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_ecdsa, ssl_hash_none}, + {TLS_ECDH_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_ecdsa, ssl_hash_none}, + {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa, ssl_hash_none}, + {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa, ssl_hash_none}, + {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa, ssl_hash_none}, + + {TLS_ECDHE_ECDSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_ecdsa, ssl_hash_none}, + {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_ecdsa, ssl_hash_none}, + {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa, ssl_hash_none}, + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa, ssl_hash_none}, + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa, ssl_hash_sha256}, + {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa, ssl_hash_none}, + + {TLS_ECDH_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdh_rsa, ssl_hash_none}, + {TLS_ECDH_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdh_rsa, ssl_hash_none}, + {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_rsa, ssl_hash_none}, + {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_rsa, ssl_hash_none}, + {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_rsa, ssl_hash_none}, + + {TLS_ECDHE_RSA_WITH_NULL_SHA, cipher_null, mac_sha, kea_ecdhe_rsa, ssl_hash_none}, + {TLS_ECDHE_RSA_WITH_RC4_128_SHA, cipher_rc4, mac_sha, kea_ecdhe_rsa, ssl_hash_none}, + {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_rsa, ssl_hash_none}, + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_rsa, ssl_hash_none}, + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa, ssl_hash_sha256}, + {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_rsa, ssl_hash_none}, + + {TLS_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_tls13_any, ssl_hash_sha256}, + {TLS_CHACHA20_POLY1305_SHA256, cipher_chacha20, mac_aead, kea_tls13_any, ssl_hash_sha256}, + {TLS_AES_256_GCM_SHA384, cipher_aes_256_gcm, mac_aead, kea_tls13_any, ssl_hash_sha384}, +}; +/* clang-format on */ + +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[] = { - 0x80000000L, - CKM_RSA_PKCS, - CKM_DH_PKCS_DERIVE, - CKM_KEA_KEY_DERIVE, - CKM_ECDH1_DERIVE + 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; + SSLCipherAlgorithm calg; + CK_MECHANISM_TYPE cmech; } SSLCipher2Mech; /* indexed by type SSLCipherAlgorithm */ static const SSLCipher2Mech alg2Mech[] = { /* calg, cmech */ - { calg_null , (CK_MECHANISM_TYPE)0x80000000L }, - { calg_rc4 , CKM_RC4 }, - { calg_rc2 , CKM_RC2_CBC }, - { calg_des , CKM_DES_CBC }, - { calg_3des , CKM_DES3_CBC }, - { calg_idea , CKM_IDEA_CBC }, - { calg_fortezza , CKM_SKIPJACK_CBC64 }, - { calg_aes , CKM_AES_CBC }, - { calg_camellia , CKM_CAMELLIA_CBC }, - { calg_seed , CKM_SEED_CBC }, - { calg_aes_gcm , CKM_AES_GCM }, -/* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ + { calg_null, (CK_MECHANISM_TYPE)0x80000000L }, + { calg_rc4, CKM_RC4 }, + { calg_rc2, CKM_RC2_CBC }, + { calg_des, CKM_DES_CBC }, + { calg_3des, CKM_DES3_CBC }, + { calg_idea, CKM_IDEA_CBC }, + { calg_fortezza, CKM_SKIPJACK_CBC64 }, + { calg_aes, CKM_AES_CBC }, + { calg_camellia, CKM_CAMELLIA_CBC }, + { calg_seed, CKM_SEED_CBC }, + { calg_aes_gcm, CKM_AES_GCM }, + { calg_chacha20, CKM_NSS_CHACHA20_POLY1305 }, + /* { calg_init , (CK_MECHANISM_TYPE)0x7fffffffL } */ }; -#define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L -#define mmech_md5 CKM_SSL3_MD5_MAC -#define mmech_sha CKM_SSL3_SHA1_MAC +#define mmech_invalid (CK_MECHANISM_TYPE)0x80000000L +#define mmech_md5 CKM_SSL3_MD5_MAC +#define mmech_sha CKM_SSL3_SHA1_MAC #define mmech_md5_hmac CKM_MD5_HMAC #define mmech_sha_hmac CKM_SHA_1_HMAC #define mmech_sha256_hmac CKM_SHA256_HMAC +#define mmech_sha384_hmac CKM_SHA384_HMAC +/* clang-format off */ static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */ /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */ /* mac mmech pad_size mac_size */ - { mac_null, mmech_invalid, 0, 0 }, - { mac_md5, mmech_md5, 48, MD5_LENGTH }, - { mac_sha, mmech_sha, 40, SHA1_LENGTH}, - {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH }, - {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH}, - {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH}, - { mac_aead, mmech_invalid, 0, 0 }, -}; - -/* indexed by SSL3BulkCipher */ -const char * const ssl3_cipherName[] = { - "NULL", - "RC4", - "RC4-40", - "RC4-56", - "RC2-CBC", - "RC2-CBC-40", - "DES-CBC", - "3DES-EDE-CBC", - "DES-CBC-40", - "IDEA-CBC", - "AES-128", - "AES-256", - "Camellia-128", - "Camellia-256", - "SEED-CBC", - "AES-128-GCM", - "missing" + { mac_null, mmech_invalid, 0, 0 , 0}, + { mac_md5, mmech_md5, 48, MD5_LENGTH, SEC_OID_HMAC_MD5 }, + { mac_sha, mmech_sha, 40, SHA1_LENGTH, SEC_OID_HMAC_SHA1}, + {hmac_md5, mmech_md5_hmac, 0, MD5_LENGTH, SEC_OID_HMAC_MD5}, + {hmac_sha, mmech_sha_hmac, 0, SHA1_LENGTH, SEC_OID_HMAC_SHA1}, + {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH, SEC_OID_HMAC_SHA256}, + { mac_aead, mmech_invalid, 0, 0, 0 }, + {hmac_sha384, mmech_sha384_hmac, 0, SHA384_LENGTH, SEC_OID_HMAC_SHA384} }; - -#ifndef NSS_DISABLE_ECC -/* 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 +/* clang-format on */ + +const PRUint8 tls13_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, + 0x47, 0x52, 0x44, 0x01 }; +const PRUint8 tls12_downgrade_random[] = { 0x44, 0x4F, 0x57, 0x4E, + 0x47, 0x52, 0x44, 0x00 }; +PR_STATIC_ASSERT(sizeof(tls13_downgrade_random) == + sizeof(tls13_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 + * 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 +#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 */ + 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; -#endif /* NSS_DISABLE_ECC */ + +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; + char *rv; static char line[40]; - switch(msgType) { - case hello_request: rv = "hello_request (0)"; break; - case client_hello: rv = "client_hello (1)"; break; - case server_hello: rv = "server_hello (2)"; break; - case hello_verify_request: rv = "hello_verify_request (3)"; break; - case certificate: rv = "certificate (11)"; break; - case server_key_exchange: rv = "server_key_exchange (12)"; break; - case certificate_request: rv = "certificate_request (13)"; break; - case server_hello_done: rv = "server_hello_done (14)"; break; - case certificate_verify: rv = "certificate_verify (15)"; break; - case client_key_exchange: rv = "client_key_exchange (16)"; break; - case finished: rv = "finished (20)"; break; - default: - sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); - rv = line; + switch (msgType) { + case hello_request: + rv = "hello_request (0)"; + break; + case client_hello: + rv = "client_hello (1)"; + break; + case server_hello: + rv = "server_hello (2)"; + break; + case hello_verify_request: + rv = "hello_verify_request (3)"; + break; + case new_session_ticket: + rv = "session_ticket (4)"; + break; + case hello_retry_request: + rv = "hello_retry_request (6)"; + break; + case encrypted_extensions: + rv = "encrypted_extensions (8)"; + break; + case certificate: + rv = "certificate (11)"; + break; + case server_key_exchange: + rv = "server_key_exchange (12)"; + break; + case certificate_request: + rv = "certificate_request (13)"; + break; + case server_hello_done: + rv = "server_hello_done (14)"; + break; + case certificate_verify: + rv = "certificate_verify (15)"; + break; + case client_key_exchange: + rv = "client_key_exchange (16)"; + break; + case finished: + rv = "finished (20)"; + break; + default: + sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType); + rv = line; } return rv; } @@ -584,26 +617,32 @@ ssl3_DecodeHandshakeType(int msgType) static char * ssl3_DecodeContentType(int msgType) { - char * rv; + char *rv; static char line[40]; - switch(msgType) { - case content_change_cipher_spec: - rv = "change_cipher_spec (20)"; break; - case content_alert: rv = "alert (21)"; break; - case content_handshake: rv = "handshake (22)"; break; - case content_application_data: - rv = "application_data (23)"; break; - default: - sprintf(line, "*UNKNOWN* record type! (%d)", msgType); - rv = line; + switch (msgType) { + case content_change_cipher_spec: + rv = "change_cipher_spec (20)"; + break; + case content_alert: + rv = "alert (21)"; + break; + case content_handshake: + rv = "handshake (22)"; + break; + case content_application_data: + rv = "application_data (23)"; + break; + default: + sprintf(line, "*UNKNOWN* record type! (%d)", msgType); + rv = line; } return rv; } #endif -SSL3Statistics * +SSL3Statistics * SSL_GetStatistics(void) { return &ssl3stats; @@ -619,14 +658,15 @@ typedef struct tooLongStr { #endif } tooLong; -void SSL_AtomicIncrementLong(long * x) +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); + tooLong *tl = (tooLong *)x; + if (PR_ATOMIC_INCREMENT(&tl->low) == 0) + PR_ATOMIC_INCREMENT(&tl->high); } } @@ -636,84 +676,82 @@ ssl3_CipherSuiteAllowedForVersionRange( const SSLVersionRange *vrange) { switch (cipherSuite) { - /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or - * later. This set of cipher suites is similar to, but different from, the - * set of cipher suites considered exportable by SSL_IsExportCipherSuite. - */ - case TLS_RSA_EXPORT_WITH_RC4_40_MD5: - case TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5: - /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA: never implemented - * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5: never implemented - * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA: never implemented - */ - return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0; - - 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_RSA_WITH_AES_128_CBC_SHA256: - 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_DHE_DSS_WITH_AES_128_CBC_SHA256: - case TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: - case TLS_RSA_WITH_NULL_SHA256: - return vrange->max == SSL_LIBRARY_VERSION_TLS_1_2; - - case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: - case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: - case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: - case TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: - return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2; - - /* 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; - - default: - return vrange->min < SSL_LIBRARY_VERSION_TLS_1_3; + 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. */ -static const ssl3CipherSuiteDef * +const ssl3CipherSuiteDef * ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) { int cipher_suite_def_len = - sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]); + 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]; + if (cipher_suite_defs[i].cipher_suite == suite) + return &cipher_suite_defs[i]; } - PORT_Assert(PR_FALSE); /* We should never get here. */ + PORT_Assert(PR_FALSE); /* We should never get here. */ PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); return NULL; } @@ -721,19 +759,141 @@ ssl_LookupCipherSuiteDef(ssl3CipherSuite suite) /* Find the cipher configuration struct associate with suite */ /* XXX This does a linear search. A binary search would be better. */ static ssl3CipherSuiteCfg * -ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) +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]; + 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 static 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->version < 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, 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->certType.authType != authType) { + continue; + } + if (!cert->serverKeyPair || + !cert->serverKeyPair->privKey || + !cert->serverCertChain) { + 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 ((authType == ssl_auth_ecdsa || + authType == ssl_auth_ecdh_ecdsa || + authType == ssl_auth_ecdh_rsa) && + !ssl_NamedGroupEnabled(ss, cert->certType.namedCurve)) { + continue; + } + return PR_TRUE; + } + return PR_FALSE; +} + +const ssl3BulkCipherDef * +ssl_GetBulkCipherDef(const ssl3CipherSuiteDef *cipher_def) +{ + PORT_Assert(cipher_def->bulk_cipher_alg < PR_ARRAY_SIZE(bulk_cipher_defs)); + PORT_Assert(bulk_cipher_defs[cipher_def->bulk_cipher_alg].cipher == cipher_def->bulk_cipher_alg); + return &bulk_cipher_defs[cipher_def->bulk_cipher_alg]; +} /* Initialize the suite->isPresent value for config_match * Returns count of enabled ciphers supported by extant tokens, @@ -743,148 +903,130 @@ ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites) int ssl3_config_match_init(sslSocket *ss) { - ssl3CipherSuiteCfg * suite; + ssl3CipherSuiteCfg *suite; const ssl3CipherSuiteDef *cipher_def; - SSLCipherAlgorithm cipher_alg; - CK_MECHANISM_TYPE cipher_mech; - SSL3KEAType exchKeyType; - int i; - int numPresent = 0; - int numEnabled = 0; - PRBool isServer; - sslServerCerts *svrAuth; + SSLCipherAlgorithm cipher_alg; + CK_MECHANISM_TYPE cipher_mech; + SSLAuthType authType; + SSLKEAType keaType; + int i; + int numPresent = 0; + int numEnabled = 0; PORT_Assert(ss); if (!ss) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return 0; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return 0; } - if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - return 0; + if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) { + return 0; } - isServer = (PRBool)(ss->sec.isServer != 0); 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 = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg; - PORT_Assert( alg2Mech[cipher_alg].calg == cipher_alg); - cipher_mech = alg2Mech[cipher_alg].cmech; - exchKeyType = - kea_defs[cipher_def->key_exchange_alg].exchKeyType; -#ifdef NSS_DISABLE_ECC - svrAuth = ss->serverCerts + exchKeyType; -#else - /* XXX SSLKEAType isn't really a good choice for - * indexing certificates. It doesn't work for - * (EC)DHE-* ciphers. Here we use a hack to ensure - * that the server uses an RSA cert for (EC)DHE-RSA. - */ - switch (cipher_def->key_exchange_alg) { - case kea_dhe_dss: - svrAuth = ss->serverCerts + ssl_kea_dh; - break; - case kea_ecdhe_rsa: - case kea_dhe_rsa: - svrAuth = ss->serverCerts + kt_rsa; - break; - case kea_ecdh_ecdsa: - case kea_ecdh_rsa: - /* - * XXX We ought to have different indices for - * ECDSA- and RSA-signed EC certificates so - * we could support both key exchange mechanisms - * simultaneously. For now, both of them use - * whatever is in the certificate slot for kt_ecdh - */ - case kea_dhe_dss_export: - case kea_dhe_rsa_export: - default: - svrAuth = ss->serverCerts + exchKeyType; - break; - } -#endif /* NSS_DISABLE_ECC */ - - /* Mark the suites that are backed by real tokens, certs and keys */ - suite->isPresent = (PRBool) - (((exchKeyType == kt_null) || - ((!isServer || (svrAuth->serverKeyPair && - svrAuth->SERVERKEY && - svrAuth->serverCertChain)) && - PK11_TokenExists(kea_alg_defs[exchKeyType]))) && - ((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech))); - if (suite->isPresent) - ++numPresent; - } + 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, authType)) { + suite->isPresent = PR_FALSE; + } + 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 != calg_null && + !PK11_TokenExists(cipher_mech)) { + suite->isPresent = PR_FALSE; + } + + if (suite->isPresent) { + ++numPresent; + } + } } PORT_Assert(numPresent > 0 || numEnabled == 0); if (numPresent <= 0) { - PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); + PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED); } return numPresent; } - -/* return PR_TRUE if suite matches policy, enabled state and is applicable to - * the given version range. */ -/* It would be a REALLY BAD THING (tm) if we ever permitted the use -** of a cipher that was NOT_ALLOWED. So, if this is ever called with -** policy == SSL_NOT_ALLOWED, report no match. -*/ -/* adjust suite enabled to the availability of a token that can do the - * cipher suite. */ +/* 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. */ static PRBool -config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled, - const SSLVersionRange *vrange, const sslSocket *ss) +config_match(const ssl3CipherSuiteCfg *suite, int policy, + const SSLVersionRange *vrange, const sslSocket *ss) { const ssl3CipherSuiteDef *cipher_def; + const ssl3KEADef *kea_def; + + PORT_Assert(policy != SSL_NOT_ALLOWED); + if (policy == SSL_NOT_ALLOWED) + return PR_FALSE; - PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE); - if (policy == SSL_NOT_ALLOWED || !enabled) - 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; + } - PORT_Assert(ss != NULL); - if (ss->sec.isServer && !ss->opt.enableServerDhe && - kea_defs[cipher_def->key_exchange_alg].exchKeyType == ssl_kea_dh) - return PR_FALSE; + if (ss->sec.isServer && !ssl_HasCert(ss, kea_def->authKeyType)) { + return PR_FALSE; + } - return (PRBool)(suite->enabled && - suite->isPresent && - suite->policy != SSL_NOT_ALLOWED && - suite->policy <= policy && - ssl3_CipherSuiteAllowedForVersionRange( - suite->cipher_suite, vrange)); + return ssl3_CipherSuiteAllowedForVersionRange(suite->cipher_suite, vrange); } -/* return number of cipher suites that match policy, enabled state and are - * applicable for the configured protocol version range. */ -/* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */ +/* Return the number of cipher suites that are usable. */ +/* called from ssl3_SendClientHello */ static int -count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) +count_cipher_suites(sslSocket *ss, int policy) { int i, count = 0; - if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - return 0; + if (SSL_ALL_VERSIONS_DISABLED(&ss->vrange)) { + return 0; } for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange, ss)) - count++; + if (config_match(&ss->cipherSuites[i], policy, &ss->vrange, ss)) + count++; } if (count <= 0) { - PORT_SetError(SSL_ERROR_SSL_DISABLED); + PORT_SetError(SSL_ERROR_SSL_DISABLED); } return count; } @@ -892,19 +1034,18 @@ count_cipher_suites(sslSocket *ss, int policy, PRBool enabled) /* * Null compression, mac and encryption functions */ - static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, - const unsigned char *input, int inputLen) + const unsigned char *input, int inputLen) { if (inputLen > maxOutputLen) { - *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ + *outputLen = 0; /* Match PK11_CipherOp in setting outputLen */ PORT_SetError(SEC_ERROR_OUTPUT_LEN); return SECFailure; } *outputLen = inputLen; if (input != output) - PORT_Memcpy(output, input, inputLen); + PORT_Memcpy(output, input, inputLen); return SECSuccess; } @@ -921,17 +1062,17 @@ Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen, */ SECStatus ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, - PRBool allowLargerPeerVersion) + PRBool allowLargerPeerVersion) { - if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PORT_SetError(SSL_ERROR_SSL_DISABLED); - 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; + (peerVersion > ss->vrange.max && !allowLargerPeerVersion)) { + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + return SECFailure; } ss->version = PR_MIN(peerVersion, ss->vrange.max); @@ -940,469 +1081,473 @@ ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion, 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, SSL3Opaque **b, unsigned int *len, + SSL3ProtocolVersion *version) +{ + SSL3ProtocolVersion v; + PRInt32 temp; + + temp = ssl3_ConsumeHandshakeNumber(ss, 2, b, len); + if (temp < 0) { + return SECFailure; /* alert has been sent */ + } + +#ifdef TLS_1_3_DRAFT_VERSION + if (temp == SSL_LIBRARY_VERSION_TLS_1_3) { + (void)SSL3_SendAlert(ss, alert_fatal, protocol_version); + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + return SECFailure; + } + if (temp == tls13_EncodeDraftVersion(SSL_LIBRARY_VERSION_TLS_1_3)) { + v = SSL_LIBRARY_VERSION_TLS_1_3; + } else { + v = (SSL3ProtocolVersion)temp; + } +#else + v = (SSL3ProtocolVersion)temp; +#endif + + if (IS_DTLS(ss)) { + /* If this fails, we get 0 back and the next check to fails. */ + v = dtls_DTLSVersionToTLSVersion(v); + } + + PORT_Assert(!SSL_ALL_VERSIONS_DISABLED(&ss->vrange)); + if (ss->vrange.min > v || ss->vrange.max < v) { + (void)SSL3_SendAlert(ss, alert_fatal, + (v > SSL_LIBRARY_VERSION_3_0) ? protocol_version + : handshake_failure); + PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); + return SECFailure; + } + *version = v; + return SECSuccess; +} + static SECStatus ssl3_GetNewRandom(SSL3Random *random) { SECStatus rv; - /* first 4 bytes are reserverd for time */ rv = PK11_GenerateRandom(random->rand, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); } return rv; } /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */ SECStatus -ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf, - PRBool isTLS) -{ - SECStatus rv = SECFailure; - PRBool doDerEncode = PR_FALSE; - int signatureLen; - SECItem hashItem; - - buf->data = NULL; - - switch (key->keyType) { - 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; -#ifndef NSS_DISABLE_ECC - 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; -#endif /* NSS_DISABLE_ECC */ - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - goto done; +ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, SECKEYPrivateKey *key, + SECItem *buf) +{ + SECStatus rv = SECFailure; + PRBool doDerEncode = PR_FALSE; + PRBool isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); + PRBool useRsaPss = ssl_IsRsaPssSignatureScheme(ss->ssl3.hs.signatureScheme); + 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 (hash->hashAlg == ssl_hash_none) { - signatureLen = PK11_SignatureLen(key); - if (signatureLen <= 0) { - PORT_SetError(SEC_ERROR_INVALID_KEY); - goto done; - } + 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) }; - buf->len = (unsigned)signatureLen; - buf->data = (unsigned char *)PORT_Alloc(signatureLen); - if (!buf->data) - goto done; /* error code was set. */ + 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_Sign(key, buf, &hashItem); + rv = PK11_SignWithMechanism(key, mech, params, buf, &hashItem); } else { - SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); + SECOidTag hashOID = ssl3_HashTypeToOID(hash->hashAlg); rv = SGN_Digest(key, hashOID, buf, &hashItem); } if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE); } else if (doDerEncode) { - SECItem derSig = {siBuffer, NULL, 0}; + 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); - } + /* 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)); + if (ss->sec.isServer) { + ss->sec.signatureScheme = ss->ssl3.hs.signatureScheme; + } + 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; + PORT_Free(buf->data); + buf->data = NULL; } return rv; } /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */ SECStatus -ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert, - SECItem *buf, PRBool isTLS, void *pwArg) +ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, SSL3Hashes *hash, + SECItem *buf) { - SECKEYPublicKey * key; - SECItem * signature = NULL; - SECStatus rv; - SECItem hashItem; - SECOidTag encAlg; - SECOidTag hashAlg; - + SECKEYPublicKey *key; + 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)); + buf->data, buf->len)); - key = CERT_ExtractPublicKey(cert); + key = CERT_ExtractPublicKey(ss->sec.peerCert); if (key == NULL) { - ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; - } - - hashAlg = ssl3_TLSHashAlgorithmToOID(hash->hashAlg); - switch (key->keyType) { - case rsaKey: - encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION; - hashItem.data = hash->u.raw; - hashItem.len = hash->len; - 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 (isTLS || buf->len != SECKEY_SignatureLen(key)) { - signature = DSAU_DecodeDerSigToLen(buf, SECKEY_SignatureLen(key)); - if (!signature) { - PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); - return SECFailure; - } - buf = signature; - } - break; - -#ifndef NSS_DISABLE_ECC - 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; - } - break; -#endif /* NSS_DISABLE_ECC */ - - default: - SECKEY_DestroyPublicKey(key); - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); + return SECFailure; + } + + 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 (hashAlg == SEC_OID_UNKNOWN || key->keyType == 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. - */ - rv = PK11_Verify(key, buf, &hashItem, pwArg); + 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); } - SECKEY_DestroyPublicKey(key); if (signature) { - SECITEM_FreeItem(signature, PR_TRUE); + SECITEM_FreeItem(signature, PR_TRUE); } if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); + ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); + } + if (!ss->sec.isServer) { + ss->sec.signatureScheme = scheme; } + +loser: + SECKEY_DestroyPublicKey(key); +#ifdef UNSAFE_FUZZER_MODE + rv = SECSuccess; + PORT_SetError(0); +#endif return rv; } - /* Caller must set hiLevel error code. */ -/* Called from ssl3_ComputeExportRSAKeyHash - * ssl3_ComputeDHKeyHash +/* 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, PRBool bypassPKCS11) + PRUint8 *hashBuf, unsigned int bufLen, + SSL3Hashes *hashes) { SECStatus rv; SECOidTag hashOID; -#ifndef NO_PKCS11_BYPASS - if (bypassPKCS11) { - if (hashAlg == ssl_hash_none) { - MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen); - SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen); - hashes->len = MD5_LENGTH + SHA1_LENGTH; - } else if (hashAlg == ssl_hash_sha1) { - SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen); - hashes->len = SHA1_LENGTH; - } else if (hashAlg == ssl_hash_sha256) { - SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen); - hashes->len = SHA256_LENGTH; - } else if (hashAlg == ssl_hash_sha384) { - SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen); - hashes->len = SHA384_LENGTH; - } else if (hashAlg == ssl_hash_sha512) { - SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen); - hashes->len = SHA512_LENGTH; - } else { - PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); + if (hashAlg == ssl_hash_none) { + 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); + hashes->len = HASH_ResultLenByOidTag(hashOID); + if (hashes->len == 0 || hashes->len > sizeof(hashes->u.raw)) { + ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); return SECFailure; } - } else -#endif - { - if (hashAlg == ssl_hash_none) { - 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_TLSHashAlgorithmToOID(hashAlg); - 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; - } + 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_SendServerKeyExchange and -** ssl3_HandleServerKeyExchange. -*/ -static SECStatus -ssl3_ComputeExportRSAKeyHash(SSLHashType hashAlg, - SECItem modulus, SECItem publicExponent, - SSL3Random *client_rand, SSL3Random *server_rand, - SSL3Hashes *hashes, PRBool bypassPKCS11) -{ - PRUint8 * hashBuf; - PRUint8 * pBuf; - SECStatus rv = SECSuccess; - unsigned int bufLen; - PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; - - bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.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; - pBuf[0] = (PRUint8)(modulus.len >> 8); - pBuf[1] = (PRUint8)(modulus.len); - pBuf += 2; - memcpy(pBuf, modulus.data, modulus.len); - pBuf += modulus.len; - pBuf[0] = (PRUint8)(publicExponent.len >> 8); - pBuf[1] = (PRUint8)(publicExponent.len); - pBuf += 2; - memcpy(pBuf, publicExponent.data, publicExponent.len); - pBuf += publicExponent.len; - PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); - - rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, - bypassPKCS11); - - PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen)); - if (hashAlg == ssl_hash_none) { - PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result", - hashes->u.s.md5, MD5_LENGTH)); - PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result", - hashes->u.s.sha, SHA1_LENGTH)); - } else { - PRINT_BUF(95, (NULL, "RSAkey hash: result", - hashes->u.raw, hashes->len)); - } - - if (hashBuf != buf && hashBuf != NULL) - PORT_Free(hashBuf); - return rv; -} - /* Caller must set hiLevel error code. */ /* Called from ssl3_HandleServerKeyExchange. */ static SECStatus -ssl3_ComputeDHKeyHash(SSLHashType hashAlg, - SECItem dh_p, SECItem dh_g, SECItem dh_Ys, - SSL3Random *client_rand, SSL3Random *server_rand, - SSL3Hashes *hashes, PRBool bypassPKCS11) -{ - PRUint8 * hashBuf; - PRUint8 * pBuf; - SECStatus rv = SECSuccess; - unsigned int bufLen; - PRUint8 buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8]; - - bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len; +ssl3_ComputeDHKeyHash(sslSocket *ss, SSLHashType hashAlg, SSL3Hashes *hashes, + SECItem dh_p, SECItem dh_g, SECItem dh_Ys, PRBool padY) +{ + PRUint8 *hashBuf; + PRUint8 *pBuf; + SECStatus rv = SECSuccess; + unsigned int bufLen, yLen; + PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 4096 / 8 + 2 + 4096 / 8]; + + PORT_Assert(dh_p.data); + PORT_Assert(dh_g.data); + PORT_Assert(dh_Ys.data); + + yLen = padY ? dh_p.len : dh_Ys.len; + bufLen = 2 * SSL3_RANDOM_LENGTH + + 2 + dh_p.len + + 2 + dh_g.len + + 2 + yLen; if (bufLen <= sizeof buf) { - hashBuf = 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; - pBuf[0] = (PRUint8)(dh_p.len >> 8); - pBuf[1] = (PRUint8)(dh_p.len); - pBuf += 2; + hashBuf = PORT_Alloc(bufLen); + if (!hashBuf) { + return SECFailure; + } + } + + memcpy(hashBuf, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH); + pBuf = hashBuf + SSL3_RANDOM_LENGTH; + memcpy(pBuf, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); + pBuf += SSL3_RANDOM_LENGTH; + pBuf = ssl_EncodeUintX(dh_p.len, 2, pBuf); memcpy(pBuf, dh_p.data, dh_p.len); - pBuf += dh_p.len; - pBuf[0] = (PRUint8)(dh_g.len >> 8); - pBuf[1] = (PRUint8)(dh_g.len); - pBuf += 2; + pBuf += dh_p.len; + pBuf = ssl_EncodeUintX(dh_g.len, 2, pBuf); memcpy(pBuf, dh_g.data, dh_g.len); - pBuf += dh_g.len; - pBuf[0] = (PRUint8)(dh_Ys.len >> 8); - pBuf[1] = (PRUint8)(dh_Ys.len); - pBuf += 2; + pBuf += dh_g.len; + pBuf = ssl_EncodeUintX(yLen, 2, pBuf); + if (padY && dh_p.len > dh_Ys.len) { + memset(pBuf, 0, dh_p.len - dh_Ys.len); + pBuf += dh_p.len - dh_Ys.len; + } + /* If we're padding Y, dh_Ys can't be longer than dh_p. */ + PORT_Assert(!padY || dh_p.len >= dh_Ys.len); memcpy(pBuf, dh_Ys.data, dh_Ys.len); - pBuf += dh_Ys.len; + pBuf += dh_Ys.len; PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); - rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, - bypassPKCS11); + rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes); PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen)); - 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)); + if (rv == SECSuccess) { + 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)); + } } if (hashBuf != buf && hashBuf != NULL) - PORT_Free(hashBuf); + PORT_Free(hashBuf); return rv; } -static void -ssl3_BumpSequenceNumber(SSL3SequenceNumber *num) -{ - num->low++; - if (num->low == 0) - num->high++; -} - /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */ static void ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat) { if (mat->write_key != NULL) { - PK11_FreeSymKey(mat->write_key); - mat->write_key = NULL; + PK11_FreeSymKey(mat->write_key); + mat->write_key = NULL; } if (mat->write_mac_key != NULL) { - PK11_FreeSymKey(mat->write_mac_key); - mat->write_mac_key = NULL; + PK11_FreeSymKey(mat->write_mac_key); + mat->write_mac_key = NULL; } if (mat->write_mac_context != NULL) { - PK11_DestroyContext(mat->write_mac_context, PR_TRUE); - mat->write_mac_context = NULL; + PK11_DestroyContext(mat->write_mac_context, PR_TRUE); + mat->write_mac_context = NULL; } } -/* Called from ssl3_SendChangeCipherSpecs() and -** ssl3_HandleChangeCipherSpecs() +/* Called from ssl3_SendChangeCipherSpecs() and +** ssl3_HandleChangeCipherSpecs() ** ssl3_DestroySSL3Info ** Caller must hold SpecWriteLock. */ void ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) { - PRBool freeit = (PRBool)(!spec->bypassCiphers); -/* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */ - if (spec->destroy) { - spec->destroy(spec->encodeContext, freeit); - spec->destroy(spec->decodeContext, freeit); - spec->encodeContext = NULL; /* paranoia */ - spec->decodeContext = NULL; + /* PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */ + if (spec->encodeContext) { + PK11_DestroyContext(spec->encodeContext, PR_TRUE); + spec->encodeContext = NULL; + } + if (spec->decodeContext) { + PK11_DestroyContext(spec->decodeContext, PR_TRUE); + spec->decodeContext = NULL; } if (spec->destroyCompressContext && spec->compressContext) { - spec->destroyCompressContext(spec->compressContext, 1); - spec->compressContext = NULL; + spec->destroyCompressContext(spec->compressContext, 1); + spec->compressContext = NULL; } if (spec->destroyDecompressContext && spec->decompressContext) { - spec->destroyDecompressContext(spec->decompressContext, 1); - spec->decompressContext = NULL; - } - if (freeSrvName && spec->srvVirtName.data) { - SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE); + spec->destroyDecompressContext(spec->decompressContext, 1); + spec->decompressContext = NULL; } if (spec->master_secret != NULL) { - PK11_FreeSymKey(spec->master_secret); - spec->master_secret = NULL; + PK11_FreeSymKey(spec->master_secret); + spec->master_secret = NULL; } spec->msItem.data = NULL; - spec->msItem.len = 0; + spec->msItem.len = 0; ssl3_CleanupKeyMaterial(&spec->client); ssl3_CleanupKeyMaterial(&spec->server); - spec->bypassCiphers = PR_FALSE; - spec->destroy=NULL; spec->destroyCompressContext = NULL; spec->destroyDecompressContext = NULL; } @@ -1413,21 +1558,21 @@ ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName) ** Caller must hold the ssl3 handshake lock. ** Acquires & releases SpecWriteLock. */ -static SECStatus +SECStatus ssl3_SetupPendingCipherSpec(sslSocket *ss) { - ssl3CipherSpec * pwSpec; - ssl3CipherSpec * cwSpec; - ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; - SSL3MACAlgorithm mac; - SSL3BulkCipher cipher; - SSL3KeyExchangeAlgorithm kea; + ssl3CipherSpec *pwSpec; + ssl3CipherSpec *cwSpec; + ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; + SSL3MACAlgorithm mac; + SSL3KeyExchangeAlgorithm kea; const ssl3CipherSuiteDef *suite_def; - PRBool isTLS; + PRBool isTLS; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); - ssl_GetSpecWriteLock(ss); /*******************************/ + ssl_GetSpecWriteLock(ss); /*******************************/ pwSpec = ss->ssl3.pwSpec; PORT_Assert(pwSpec == ss->ssl3.prSpec); @@ -1435,49 +1580,41 @@ ssl3_SetupPendingCipherSpec(sslSocket *ss) /* This hack provides maximal interoperability with SSL 3 servers. */ cwSpec = ss->ssl3.cwSpec; if (cwSpec->mac_def->mac == mac_null) { - /* SSL records are not being MACed. */ - cwSpec->version = ss->version; + /* SSL records are not being MACed. */ + cwSpec->version = ss->version; } - pwSpec->version = ss->version; - isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); + pwSpec->version = ss->version; + isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x", - SSL_GETPID(), ss->fd, suite)); + SSL_GETPID(), ss->fd, suite)); suite_def = ssl_LookupCipherSuiteDef(suite); if (suite_def == NULL) { - ssl_ReleaseSpecWriteLock(ss); - return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ + ssl_ReleaseSpecWriteLock(ss); + return SECFailure; /* error code set by ssl_LookupCipherSuiteDef */ } if (IS_DTLS(ss)) { - /* Double-check that we did not pick an RC4 suite */ - PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) && - (suite_def->bulk_cipher_alg != cipher_rc4_40) && - (suite_def->bulk_cipher_alg != cipher_rc4_56)); + /* Double-check that we did not pick an RC4 suite */ + PORT_Assert(suite_def->bulk_cipher_alg != cipher_rc4); } - cipher = suite_def->bulk_cipher_alg; - kea = suite_def->key_exchange_alg; - mac = suite_def->mac_alg; + kea = suite_def->key_exchange_alg; + mac = suite_def->mac_alg; if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS) - mac += 2; + mac += 2; ss->ssl3.hs.suite_def = suite_def; - ss->ssl3.hs.kea_def = &kea_defs[kea]; + ss->ssl3.hs.kea_def = &kea_defs[kea]; PORT_Assert(ss->ssl3.hs.kea_def->kea == kea); - pwSpec->cipher_def = &bulk_cipher_defs[cipher]; - PORT_Assert(pwSpec->cipher_def->cipher == cipher); + pwSpec->cipher_def = ssl_GetBulkCipherDef(suite_def); pwSpec->mac_def = &mac_defs[mac]; PORT_Assert(pwSpec->mac_def->mac == mac); - ss->sec.keyBits = pwSpec->cipher_def->key_size * BPB; - ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB; - ss->sec.cipherType = cipher; - pwSpec->encodeContext = NULL; pwSpec->decodeContext = NULL; @@ -1487,21 +1624,25 @@ ssl3_SetupPendingCipherSpec(sslSocket *ss) pwSpec->compressContext = NULL; pwSpec->decompressContext = NULL; - ssl_ReleaseSpecWriteLock(ss); /*******************************/ + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + PORT_Assert(ss->ssl3.hs.kea_def->ephemeral); + PORT_Assert(pwSpec->cipher_def->type == type_aead); + } + ssl_ReleaseSpecWriteLock(ss); /*******************************/ return SECSuccess; } -#ifdef NSS_ENABLE_ZLIB +#ifdef NSS_SSL_ENABLE_ZLIB #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream) static SECStatus ssl3_MapZlibError(int zlib_error) { switch (zlib_error) { - case Z_OK: - return SECSuccess; - default: - return SECFailure; + case Z_OK: + return SECSuccess; + default: + return SECFailure; } } @@ -1540,7 +1681,7 @@ ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len, return SECSuccess; } - context->next_in = (unsigned char*) in; + context->next_in = (unsigned char *)in; context->avail_in = inlen; context->next_out = out; context->avail_out = maxout; @@ -1569,7 +1710,7 @@ ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len, return SECSuccess; } - context->next_in = (unsigned char*) in; + context->next_in = (unsigned char *)in; context->avail_in = inlen; context->next_out = out; context->avail_out = maxout; @@ -1598,7 +1739,7 @@ ssl3_DestroyDecompressContext(void *void_context, PRBool unused) return SECSuccess; } -#endif /* NSS_ENABLE_ZLIB */ +#endif /* NSS_SSL_ENABLE_ZLIB */ /* Initialize the compression functions and contexts for the given * CipherSpec. */ @@ -1607,227 +1748,54 @@ ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec) { /* Setup the compression functions */ switch (pwSpec->compression_method) { - case ssl_compression_null: - pwSpec->compressor = NULL; - pwSpec->decompressor = NULL; - pwSpec->compressContext = NULL; - pwSpec->decompressContext = NULL; - pwSpec->destroyCompressContext = NULL; - pwSpec->destroyDecompressContext = NULL; - break; -#ifdef NSS_ENABLE_ZLIB - case ssl_compression_deflate: - pwSpec->compressor = ssl3_DeflateCompress; - pwSpec->decompressor = ssl3_DeflateDecompress; - pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); - pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); - pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; - pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; - ssl3_DeflateInit(pwSpec->compressContext); - ssl3_InflateInit(pwSpec->decompressContext); - break; -#endif /* NSS_ENABLE_ZLIB */ - default: - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - - return SECSuccess; -} - -#ifndef NO_PKCS11_BYPASS -/* Initialize encryption contexts for pending spec. - * MAC contexts are set up when computing the mac, not here. - * Master Secret already is derived in spec->msItem - * Caller holds Spec write lock. - */ -static SECStatus -ssl3_InitPendingContextsBypass(sslSocket *ss) -{ - ssl3CipherSpec * pwSpec; - const ssl3BulkCipherDef *cipher_def; - void * serverContext = NULL; - void * clientContext = NULL; - BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL; - int mode = 0; - unsigned int optArg1 = 0; - unsigned int optArg2 = 0; - PRBool server_encrypts = ss->sec.isServer; - SSLCipherAlgorithm calg; - SECStatus rv; - - PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); - PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); - - pwSpec = ss->ssl3.pwSpec; - cipher_def = pwSpec->cipher_def; - - calg = cipher_def->calg; - - if (calg == ssl_calg_aes_gcm) { - pwSpec->encode = NULL; - pwSpec->decode = NULL; - pwSpec->destroy = NULL; - pwSpec->encodeContext = NULL; - pwSpec->decodeContext = NULL; - pwSpec->aead = ssl3_AESGCMBypass; - ssl3_InitCompressionContext(pwSpec); - return SECSuccess; - } - - serverContext = pwSpec->server.cipher_context; - clientContext = pwSpec->client.cipher_context; - - switch (calg) { - case ssl_calg_null: - pwSpec->encode = Null_Cipher; - pwSpec->decode = Null_Cipher; - pwSpec->destroy = NULL; - goto success; - - case ssl_calg_rc4: - initFn = (BLapiInitContextFunc)RC4_InitContext; - pwSpec->encode = (SSLCipher) RC4_Encrypt; - pwSpec->decode = (SSLCipher) RC4_Decrypt; - pwSpec->destroy = (SSLDestroy) RC4_DestroyContext; - break; - case ssl_calg_rc2: - initFn = (BLapiInitContextFunc)RC2_InitContext; - mode = NSS_RC2_CBC; - optArg1 = cipher_def->key_size; - pwSpec->encode = (SSLCipher) RC2_Encrypt; - pwSpec->decode = (SSLCipher) RC2_Decrypt; - pwSpec->destroy = (SSLDestroy) RC2_DestroyContext; - break; - case ssl_calg_des: - initFn = (BLapiInitContextFunc)DES_InitContext; - mode = NSS_DES_CBC; - optArg1 = server_encrypts; - pwSpec->encode = (SSLCipher) DES_Encrypt; - pwSpec->decode = (SSLCipher) DES_Decrypt; - pwSpec->destroy = (SSLDestroy) DES_DestroyContext; - break; - case ssl_calg_3des: - initFn = (BLapiInitContextFunc)DES_InitContext; - mode = NSS_DES_EDE3_CBC; - optArg1 = server_encrypts; - pwSpec->encode = (SSLCipher) DES_Encrypt; - pwSpec->decode = (SSLCipher) DES_Decrypt; - pwSpec->destroy = (SSLDestroy) DES_DestroyContext; - break; - case ssl_calg_aes: - initFn = (BLapiInitContextFunc)AES_InitContext; - mode = NSS_AES_CBC; - optArg1 = server_encrypts; - optArg2 = AES_BLOCK_SIZE; - pwSpec->encode = (SSLCipher) AES_Encrypt; - pwSpec->decode = (SSLCipher) AES_Decrypt; - pwSpec->destroy = (SSLDestroy) AES_DestroyContext; - break; - - case ssl_calg_camellia: - initFn = (BLapiInitContextFunc)Camellia_InitContext; - mode = NSS_CAMELLIA_CBC; - optArg1 = server_encrypts; - optArg2 = CAMELLIA_BLOCK_SIZE; - pwSpec->encode = (SSLCipher) Camellia_Encrypt; - pwSpec->decode = (SSLCipher) Camellia_Decrypt; - pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext; - break; - - case ssl_calg_seed: - initFn = (BLapiInitContextFunc)SEED_InitContext; - mode = NSS_SEED_CBC; - optArg1 = server_encrypts; - optArg2 = SEED_BLOCK_SIZE; - pwSpec->encode = (SSLCipher) SEED_Encrypt; - pwSpec->decode = (SSLCipher) SEED_Decrypt; - pwSpec->destroy = (SSLDestroy) SEED_DestroyContext; - break; - - case ssl_calg_idea: - case ssl_calg_fortezza : - default: - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto bail_out; - } - rv = (*initFn)(serverContext, - pwSpec->server.write_key_item.data, - pwSpec->server.write_key_item.len, - pwSpec->server.write_iv_item.data, - mode, optArg1, optArg2); - if (rv != SECSuccess) { - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto bail_out; - } - - switch (calg) { - case ssl_calg_des: - case ssl_calg_3des: - case ssl_calg_aes: - case ssl_calg_camellia: - case ssl_calg_seed: - /* For block ciphers, if the server is encrypting, then the client - * is decrypting, and vice versa. - */ - optArg1 = !optArg1; - break; - /* kill warnings. */ - case ssl_calg_null: - case ssl_calg_rc4: - case ssl_calg_rc2: - case ssl_calg_idea: - case ssl_calg_fortezza: - case ssl_calg_aes_gcm: - break; - } - - rv = (*initFn)(clientContext, - pwSpec->client.write_key_item.data, - pwSpec->client.write_key_item.len, - pwSpec->client.write_iv_item.data, - mode, optArg1, optArg2); - if (rv != SECSuccess) { - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto bail_out; + case ssl_compression_null: + pwSpec->compressor = NULL; + pwSpec->decompressor = NULL; + pwSpec->compressContext = NULL; + pwSpec->decompressContext = NULL; + pwSpec->destroyCompressContext = NULL; + pwSpec->destroyDecompressContext = NULL; + break; +#ifdef NSS_SSL_ENABLE_ZLIB + case ssl_compression_deflate: + pwSpec->compressor = ssl3_DeflateCompress; + pwSpec->decompressor = ssl3_DeflateDecompress; + pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); + pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE); + pwSpec->destroyCompressContext = ssl3_DestroyCompressContext; + pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext; + ssl3_DeflateInit(pwSpec->compressContext); + ssl3_InflateInit(pwSpec->decompressContext); + break; +#endif /* NSS_SSL_ENABLE_ZLIB */ + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } - pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; - pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; - - ssl3_InitCompressionContext(pwSpec); - -success: return SECSuccess; - -bail_out: - return SECFailure; } -#endif -/* This function should probably be moved to pk11wrap and be named +/* This function should probably be moved to pk11wrap and be named * PK11_ParamFromIVAndEffectiveKeyBits */ static SECItem * ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) { - SECItem * param = PK11_ParamFromIV(mtype, iv); - if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { - switch (mtype) { - case CKM_RC2_KEY_GEN: - case CKM_RC2_ECB: - case CKM_RC2_CBC: - case CKM_RC2_MAC: - case CKM_RC2_MAC_GENERAL: - case CKM_RC2_CBC_PAD: - *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; - default: break; - } + SECItem *param = PK11_ParamFromIV(mtype, iv); + if (param && param->data && param->len >= sizeof(CK_RC2_PARAMS)) { + switch (mtype) { + case CKM_RC2_KEY_GEN: + case CKM_RC2_ECB: + case CKM_RC2_CBC: + case CKM_RC2_MAC: + case CKM_RC2_MAC_GENERAL: + case CKM_RC2_CBC_PAD: + *(CK_RC2_PARAMS *)param->data = ulEffectiveBits; + default: + break; + } } return param; } @@ -1846,40 +1814,40 @@ ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits) */ static unsigned int ssl3_BuildRecordPseudoHeader(unsigned char *out, - SSL3SequenceNumber seq_num, - SSL3ContentType type, - PRBool includesVersion, - SSL3ProtocolVersion version, - PRBool isDTLS, - int length) -{ - out[0] = (unsigned char)(seq_num.high >> 24); - out[1] = (unsigned char)(seq_num.high >> 16); - out[2] = (unsigned char)(seq_num.high >> 8); - out[3] = (unsigned char)(seq_num.high >> 0); - out[4] = (unsigned char)(seq_num.low >> 24); - out[5] = (unsigned char)(seq_num.low >> 16); - out[6] = (unsigned char)(seq_num.low >> 8); - out[7] = (unsigned char)(seq_num.low >> 0); + sslSequenceNumber seq_num, + SSL3ContentType type, + PRBool includesVersion, + SSL3ProtocolVersion version, + PRBool isDTLS, + int length) +{ + out[0] = (unsigned char)(seq_num >> 56); + out[1] = (unsigned char)(seq_num >> 48); + out[2] = (unsigned char)(seq_num >> 40); + out[3] = (unsigned char)(seq_num >> 32); + out[4] = (unsigned char)(seq_num >> 24); + out[5] = (unsigned char)(seq_num >> 16); + out[6] = (unsigned char)(seq_num >> 8); + out[7] = (unsigned char)(seq_num >> 0); out[8] = type; /* SSL3 MAC doesn't include the record's version field. */ if (!includesVersion) { - out[9] = MSB(length); - out[10] = LSB(length); - return 11; + out[9] = MSB(length); + out[10] = LSB(length); + return 11; } /* TLS MAC and AEAD additional data include version. */ if (isDTLS) { - SSL3ProtocolVersion dtls_version; + SSL3ProtocolVersion dtls_version; - dtls_version = dtls_TLSVersionToDTLSVersion(version); - out[9] = MSB(dtls_version); - out[10] = LSB(dtls_version); + dtls_version = dtls_TLSVersionToDTLSVersion(version); + out[9] = MSB(dtls_version); + out[10] = LSB(dtls_version); } else { - out[9] = MSB(version); - out[10] = LSB(version); + out[9] = MSB(version); + out[10] = LSB(version); } out[11] = MSB(length); out[12] = LSB(length); @@ -1888,265 +1856,251 @@ ssl3_BuildRecordPseudoHeader(unsigned char *out, static SECStatus ssl3_AESGCM(ssl3KeyMaterial *keys, - PRBool doDecrypt, - unsigned char *out, - int *outlen, - int maxout, - const unsigned char *in, - int inlen, - const unsigned char *additionalData, - int additionalDataLen) -{ - SECItem param; - SECStatus rv = SECFailure; - unsigned char nonce[12]; - unsigned int uOutLen; - CK_GCM_PARAMS gcmParams; - - static const int tagSize = 16; - static const int explicitNonceLen = 8; + PRBool doDecrypt, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen, + const unsigned char *additionalData, + int additionalDataLen) +{ + SECItem param; + SECStatus rv = SECFailure; + unsigned char nonce[12]; + unsigned int uOutLen; + CK_GCM_PARAMS gcmParams; + + const int tagSize = bulk_cipher_defs[cipher_aes_128_gcm].tag_size; + const int explicitNonceLen = + bulk_cipher_defs[cipher_aes_128_gcm].explicit_nonce_size; /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the * nonce is formed. */ memcpy(nonce, keys->write_iv, 4); if (doDecrypt) { - memcpy(nonce + 4, in, explicitNonceLen); - in += explicitNonceLen; - inlen -= explicitNonceLen; - *outlen = 0; + memcpy(nonce + 4, in, explicitNonceLen); + in += explicitNonceLen; + inlen -= explicitNonceLen; + *outlen = 0; } else { - if (maxout < explicitNonceLen) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return SECFailure; + if (maxout < explicitNonceLen) { + PORT_SetError(SEC_ERROR_INPUT_LEN); + return SECFailure; } - /* Use the 64-bit sequence number as the explicit nonce. */ - memcpy(nonce + 4, additionalData, explicitNonceLen); - memcpy(out, additionalData, explicitNonceLen); - out += explicitNonceLen; - maxout -= explicitNonceLen; - *outlen = explicitNonceLen; + /* Use the 64-bit sequence number as the explicit nonce. */ + memcpy(nonce + 4, additionalData, explicitNonceLen); + memcpy(out, additionalData, explicitNonceLen); + out += explicitNonceLen; + maxout -= explicitNonceLen; + *outlen = explicitNonceLen; } param.type = siBuffer; - param.data = (unsigned char *) &gcmParams; + param.data = (unsigned char *)&gcmParams; param.len = sizeof(gcmParams); gcmParams.pIv = nonce; gcmParams.ulIvLen = sizeof(nonce); - gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ + gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ gcmParams.ulAADLen = additionalDataLen; gcmParams.ulTagBits = tagSize * 8; if (doDecrypt) { - rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); + rv = PK11_Decrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, + maxout, in, inlen); } else { - rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, - maxout, in, inlen); + rv = PK11_Encrypt(keys->write_key, CKM_AES_GCM, ¶m, out, &uOutLen, + maxout, in, inlen); } - *outlen += (int) uOutLen; + *outlen += (int)uOutLen; return rv; } -#ifndef NO_PKCS11_BYPASS static SECStatus -ssl3_AESGCMBypass(ssl3KeyMaterial *keys, - PRBool doDecrypt, - unsigned char *out, - int *outlen, - int maxout, - const unsigned char *in, - int inlen, - const unsigned char *additionalData, - int additionalDataLen) -{ - SECStatus rv = SECFailure; - unsigned char nonce[12]; - unsigned int uOutLen; - AESContext *cx; - CK_GCM_PARAMS gcmParams; - - static const int tagSize = 16; - static const int explicitNonceLen = 8; +ssl3_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt, + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + const unsigned char *additionalData, + int additionalDataLen) +{ + size_t i; + SECItem param; + SECStatus rv = SECFailure; + unsigned int uOutLen; + unsigned char nonce[12]; + CK_NSS_AEAD_PARAMS aeadParams; - /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the - * nonce is formed. */ - PORT_Assert(keys->write_iv_item.len == 4); - if (keys->write_iv_item.len != 4) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - memcpy(nonce, keys->write_iv_item.data, 4); - if (doDecrypt) { - memcpy(nonce + 4, in, explicitNonceLen); - in += explicitNonceLen; - inlen -= explicitNonceLen; - *outlen = 0; - } else { - if (maxout < explicitNonceLen) { - PORT_SetError(SEC_ERROR_INPUT_LEN); - return SECFailure; - } - /* Use the 64-bit sequence number as the explicit nonce. */ - memcpy(nonce + 4, additionalData, explicitNonceLen); - memcpy(out, additionalData, explicitNonceLen); - out += explicitNonceLen; - maxout -= explicitNonceLen; - *outlen = explicitNonceLen; - } + const int tagSize = bulk_cipher_defs[cipher_chacha20].tag_size; - gcmParams.pIv = nonce; - gcmParams.ulIvLen = sizeof(nonce); - gcmParams.pAAD = (unsigned char *)additionalData; /* const cast */ - gcmParams.ulAADLen = additionalDataLen; - gcmParams.ulTagBits = tagSize * 8; + /* See + * https://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305-04#section-2 + * for details of how the nonce is formed. */ + PORT_Memcpy(nonce, keys->write_iv, 12); - cx = (AESContext *)keys->cipher_context; - rv = AES_InitContext(cx, keys->write_key_item.data, - keys->write_key_item.len, - (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt, - AES_BLOCK_SIZE); - if (rv != SECSuccess) { - return rv; + /* XOR the last 8 bytes of the IV with the sequence number. */ + PORT_Assert(additionalDataLen >= 8); + for (i = 0; i < 8; ++i) { + nonce[4 + i] ^= additionalData[i]; } + + param.type = siBuffer; + param.len = sizeof(aeadParams); + param.data = (unsigned char *)&aeadParams; + memset(&aeadParams, 0, sizeof(aeadParams)); + aeadParams.pNonce = nonce; + aeadParams.ulNonceLen = sizeof(nonce); + aeadParams.pAAD = (unsigned char *)additionalData; + aeadParams.ulAADLen = additionalDataLen; + aeadParams.ulTagLen = tagSize; + if (doDecrypt) { - rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen); + rv = PK11_Decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, + out, &uOutLen, maxout, in, inlen); } else { - rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen); + rv = PK11_Encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, ¶m, + out, &uOutLen, maxout, in, inlen); } - AES_DestroyContext(cx, PR_FALSE); - *outlen += (int) uOutLen; + *outlen = (int)uOutLen; return rv; } -#endif /* Initialize encryption and MAC contexts for pending spec. * Master Secret already is derived. * Caller holds Spec write lock. */ static SECStatus -ssl3_InitPendingContextsPKCS11(sslSocket *ss) -{ - ssl3CipherSpec * pwSpec; - const ssl3BulkCipherDef *cipher_def; - PK11Context * serverContext = NULL; - PK11Context * clientContext = NULL; - SECItem * param; - CK_MECHANISM_TYPE mechanism; - CK_MECHANISM_TYPE mac_mech; - CK_ULONG macLength; - CK_ULONG effKeyBits; - SECItem iv; - SECItem mac_param; - SSLCipherAlgorithm calg; - - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); +ssl3_InitPendingContexts(sslSocket *ss) +{ + ssl3CipherSpec *pwSpec; + const ssl3BulkCipherDef *cipher_def; + PK11Context *serverContext = NULL; + PK11Context *clientContext = NULL; + SECItem *param; + CK_MECHANISM_TYPE mechanism; + CK_MECHANISM_TYPE mac_mech; + CK_ULONG macLength; + CK_ULONG effKeyBits; + SECItem iv; + SECItem mac_param; + SSLCipherAlgorithm calg; + + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); - pwSpec = ss->ssl3.pwSpec; - cipher_def = pwSpec->cipher_def; - macLength = pwSpec->mac_size; - calg = cipher_def->calg; + pwSpec = ss->ssl3.pwSpec; + cipher_def = pwSpec->cipher_def; + macLength = pwSpec->mac_size; + calg = cipher_def->calg; PORT_Assert(alg2Mech[calg].calg == calg); pwSpec->client.write_mac_context = NULL; pwSpec->server.write_mac_context = NULL; - if (calg == calg_aes_gcm) { - pwSpec->encode = NULL; - pwSpec->decode = NULL; - pwSpec->destroy = NULL; - pwSpec->encodeContext = NULL; - pwSpec->decodeContext = NULL; - pwSpec->aead = ssl3_AESGCM; - return SECSuccess; + if (cipher_def->type == type_aead) { + pwSpec->encode = NULL; + pwSpec->decode = NULL; + pwSpec->encodeContext = NULL; + pwSpec->decodeContext = NULL; + switch (calg) { + case calg_aes_gcm: + pwSpec->aead = ssl3_AESGCM; + break; + case calg_chacha20: + pwSpec->aead = ssl3_ChaCha20Poly1305; + break; + default: + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + return SECSuccess; } - /* - ** Now setup the MAC contexts, + /* + ** Now setup the MAC contexts, ** crypto contexts are setup below. */ - mac_mech = pwSpec->mac_def->mmech; + mac_mech = pwSpec->mac_def->mmech; mac_param.data = (unsigned char *)&macLength; - mac_param.len = sizeof(macLength); + mac_param.len = sizeof(macLength); mac_param.type = 0; pwSpec->client.write_mac_context = PK11_CreateContextBySymKey( - mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); - if (pwSpec->client.write_mac_context == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param); + if (pwSpec->client.write_mac_context == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } pwSpec->server.write_mac_context = PK11_CreateContextBySymKey( - mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); + mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param); if (pwSpec->server.write_mac_context == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } - /* + /* ** Now setup the crypto contexts. */ if (calg == calg_null) { - pwSpec->encode = Null_Cipher; - pwSpec->decode = Null_Cipher; - pwSpec->destroy = NULL; - return SECSuccess; + pwSpec->encode = Null_Cipher; + pwSpec->decode = Null_Cipher; + return SECSuccess; } - mechanism = alg2Mech[calg].cmech; + mechanism = ssl3_Alg2Mech(calg); effKeyBits = cipher_def->key_size * BPB; /* * build the server context */ iv.data = pwSpec->server.write_iv; - iv.len = cipher_def->iv_size; + iv.len = cipher_def->iv_size; param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); if (param == NULL) { - ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); + goto fail; } serverContext = PK11_CreateContextBySymKey(mechanism, - (ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT), - pwSpec->server.write_key, param); + (ss->sec.isServer ? CKA_ENCRYPT + : CKA_DECRYPT), + pwSpec->server.write_key, param); iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); if (iv.data) - PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); + PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len); SECITEM_FreeItem(param, PR_TRUE); if (serverContext == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } /* * build the client context */ iv.data = pwSpec->client.write_iv; - iv.len = cipher_def->iv_size; + iv.len = cipher_def->iv_size; param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits); if (param == NULL) { - ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE); + goto fail; } clientContext = PK11_CreateContextBySymKey(mechanism, - (ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT), - pwSpec->client.write_key, param); + (ss->sec.isServer ? CKA_DECRYPT + : CKA_ENCRYPT), + pwSpec->client.write_key, param); iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len); if (iv.data) - PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); - SECITEM_FreeItem(param,PR_TRUE); + PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len); + SECITEM_FreeItem(param, PR_TRUE); if (clientContext == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); - goto fail; + ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + goto fail; } - pwSpec->encode = (SSLCipher) PK11_CipherOp; - pwSpec->decode = (SSLCipher) PK11_CipherOp; - pwSpec->destroy = (SSLDestroy) PK11_DestroyContext; + pwSpec->encode = (SSLCipher)PK11_CipherOp; + pwSpec->decode = (SSLCipher)PK11_CipherOp; pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext; pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext; @@ -2159,122 +2113,120 @@ ssl3_InitPendingContextsPKCS11(sslSocket *ss) return SECSuccess; fail: - if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE); - if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE); + if (serverContext != NULL) + PK11_DestroyContext(serverContext, PR_TRUE); if (pwSpec->client.write_mac_context != NULL) { - PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE); - pwSpec->client.write_mac_context = NULL; + PK11_DestroyContext(pwSpec->client.write_mac_context, PR_TRUE); + pwSpec->client.write_mac_context = NULL; } if (pwSpec->server.write_mac_context != NULL) { - PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE); - pwSpec->server.write_mac_context = NULL; + PK11_DestroyContext(pwSpec->server.write_mac_context, PR_TRUE); + pwSpec->server.write_mac_context = NULL; } return SECFailure; } +HASH_HashType +ssl3_GetTls12HashType(sslSocket *ss) +{ + if (ss->ssl3.pwSpec->version < SSL_LIBRARY_VERSION_TLS_1_2) { + return HASH_AlgNULL; + } + + switch (ss->ssl3.hs.suite_def->prf_hash) { + case ssl_hash_sha384: + return HASH_AlgSHA384; + case ssl_hash_sha256: + case ssl_hash_none: + /* ssl_hash_none is for pre-1.2 suites, which use SHA-256. */ + return HASH_AlgSHA256; + default: + PORT_Assert(0); + } + return HASH_AlgSHA256; +} + /* 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) + * 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. * NULL pms means re-use old master_secret. * - * This code is common to the bypass and PKCS11 execution paths. For - * the bypass case, pms is NULL. If the old master secret is reused, - * pms is NULL and the master secret is already in either - * pwSpec->msItem.len (the bypass case) or pwSpec->master_secret. - * - * For the bypass case, pms is NULL. + * If the old master secret is reused, pms is NULL and the master secret is + * already in pwSpec->master_secret. */ SECStatus ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms) { - ssl3CipherSpec * pwSpec; - ssl3CipherSpec * cwSpec; - SECStatus rv; + ssl3CipherSpec *pwSpec; + ssl3CipherSpec *cwSpec; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - ssl_GetSpecWriteLock(ss); /**************************************/ + ssl_GetSpecWriteLock(ss); /**************************************/ PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); - pwSpec = ss->ssl3.pwSpec; - cwSpec = ss->ssl3.cwSpec; + pwSpec = ss->ssl3.pwSpec; + cwSpec = ss->ssl3.cwSpec; if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) { - rv = ssl3_DeriveMasterSecret(ss, pms); - if (rv != SECSuccess) { - goto done; /* err code set by ssl3_DeriveMasterSecret */ - } - } -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) { - /* Double Bypass succeeded in extracting the master_secret */ - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - PRBool isTLS = (PRBool)(kea_def->tls_keygen || - (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); - pwSpec->bypassCiphers = PR_TRUE; - rv = ssl3_KeyAndMacDeriveBypass( pwSpec, - (const unsigned char *)&ss->ssl3.hs.client_random, - (const unsigned char *)&ss->ssl3.hs.server_random, - isTLS, - (PRBool)(kea_def->is_limited)); - if (rv == SECSuccess) { - rv = ssl3_InitPendingContextsBypass(ss); - } - } else -#endif + rv = ssl3_DeriveMasterSecret(ss, pms); + if (rv != SECSuccess) { + goto done; /* err code set by ssl3_DeriveMasterSecret */ + } + } if (pwSpec->master_secret) { - rv = ssl3_DeriveConnectionKeysPKCS11(ss); - if (rv == SECSuccess) { - rv = ssl3_InitPendingContextsPKCS11(ss); - } + rv = ssl3_DeriveConnectionKeys(ss); + if (rv == SECSuccess) { + rv = ssl3_InitPendingContexts(ss); + } } else { - PORT_Assert(pwSpec->master_secret); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; + PORT_Assert(pwSpec->master_secret); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; } if (rv != SECSuccess) { - goto done; + goto done; } /* Generic behaviors -- common to all crypto methods */ if (!IS_DTLS(ss)) { - pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0; + pwSpec->read_seq_num = pwSpec->write_seq_num = 0; } else { - if (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); - rv = SECFailure; - goto done; - } - /* The sequence number has the high 16 bits as the epoch. */ - pwSpec->epoch = cwSpec->epoch + 1; - pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = - pwSpec->epoch << 16; - - dtls_InitRecvdRecords(&pwSpec->recvdRecords); - } - pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0; + if (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); + rv = SECFailure; + goto done; + } + /* The sequence number has the high 16 bits as the epoch. */ + pwSpec->epoch = cwSpec->epoch + 1; + pwSpec->read_seq_num = pwSpec->write_seq_num = + (sslSequenceNumber)pwSpec->epoch << 48; + + dtls_InitRecvdRecords(&pwSpec->recvdRecords); + } done: - ssl_ReleaseSpecWriteLock(ss); /******************************/ + ssl_ReleaseSpecWriteLock(ss); /******************************/ if (rv != SECSuccess) - ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return rv; } /* * 60 bytes is 3 times the maximum length MAC size that is supported. */ -static const unsigned char mac_pad_1 [60] = { +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, @@ -2284,7 +2236,7 @@ static const unsigned char mac_pad_1 [60] = { 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36 }; -static const unsigned char mac_pad_2 [60] = { +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, @@ -2300,135 +2252,41 @@ static const unsigned char mac_pad_2 [60] = { */ static SECStatus ssl3_ComputeRecordMAC( - ssl3CipherSpec * spec, - PRBool useServerMacKey, + ssl3CipherSpec *spec, + PRBool useServerMacKey, const unsigned char *header, - unsigned int headerLen, - const SSL3Opaque * input, - int inputLength, - unsigned char * outbuf, - unsigned int * outLength) + unsigned int headerLen, + const SSL3Opaque *input, + int inputLength, + unsigned char *outbuf, + unsigned int *outLength) { - const ssl3MACDef * mac_def; - SECStatus rv; + const ssl3MACDef *mac_def; + SECStatus rv; PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen)); PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength)); mac_def = spec->mac_def; if (mac_def->mac == mac_null) { - *outLength = 0; - return SECSuccess; - } -#ifndef NO_PKCS11_BYPASS - if (spec->bypassCiphers) { - /* bypass version */ - const SECHashObject *hashObj = NULL; - unsigned int pad_bytes = 0; - PRUint64 write_mac_context[MAX_MAC_CONTEXT_LLONGS]; - - switch (mac_def->mac) { - case ssl_mac_null: - *outLength = 0; - return SECSuccess; - case ssl_mac_md5: - pad_bytes = 48; - hashObj = HASH_GetRawHashObject(HASH_AlgMD5); - break; - case ssl_mac_sha: - pad_bytes = 40; - hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); - break; - case ssl_hmac_md5: /* used with TLS */ - hashObj = HASH_GetRawHashObject(HASH_AlgMD5); - break; - case ssl_hmac_sha: /* used with TLS */ - hashObj = HASH_GetRawHashObject(HASH_AlgSHA1); - break; - case ssl_hmac_sha256: /* used with TLS */ - hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); - break; - default: - break; - } - if (!hashObj) { - PORT_Assert(0); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - - if (spec->version <= SSL_LIBRARY_VERSION_3_0) { - unsigned int tempLen; - unsigned char temp[MAX_MAC_LENGTH]; - - /* compute "inner" part of SSL3 MAC */ - hashObj->begin(write_mac_context); - if (useServerMacKey) - hashObj->update(write_mac_context, - spec->server.write_mac_key_item.data, - spec->server.write_mac_key_item.len); - else - hashObj->update(write_mac_context, - spec->client.write_mac_key_item.data, - spec->client.write_mac_key_item.len); - hashObj->update(write_mac_context, mac_pad_1, pad_bytes); - hashObj->update(write_mac_context, header, headerLen); - hashObj->update(write_mac_context, input, inputLength); - hashObj->end(write_mac_context, temp, &tempLen, sizeof temp); - - /* compute "outer" part of SSL3 MAC */ - hashObj->begin(write_mac_context); - if (useServerMacKey) - hashObj->update(write_mac_context, - spec->server.write_mac_key_item.data, - spec->server.write_mac_key_item.len); - else - hashObj->update(write_mac_context, - spec->client.write_mac_key_item.data, - spec->client.write_mac_key_item.len); - hashObj->update(write_mac_context, mac_pad_2, pad_bytes); - hashObj->update(write_mac_context, temp, tempLen); - hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size); - rv = SECSuccess; - } else { /* is TLS */ -#define cx ((HMACContext *)write_mac_context) - if (useServerMacKey) { - rv = HMAC_Init(cx, hashObj, - spec->server.write_mac_key_item.data, - spec->server.write_mac_key_item.len, PR_FALSE); - } else { - rv = HMAC_Init(cx, hashObj, - spec->client.write_mac_key_item.data, - spec->client.write_mac_key_item.len, PR_FALSE); - } - if (rv == SECSuccess) { - HMAC_Begin(cx); - HMAC_Update(cx, header, headerLen); - HMAC_Update(cx, input, inputLength); - rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size); - HMAC_Destroy(cx, PR_FALSE); - } -#undef cx - } - } else -#endif - { - PK11Context *mac_context = - (useServerMacKey ? spec->server.write_mac_context - : spec->client.write_mac_context); - rv = PK11_DigestBegin(mac_context); - rv |= PK11_DigestOp(mac_context, header, headerLen); - rv |= PK11_DigestOp(mac_context, input, inputLength); - rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); + *outLength = 0; + return SECSuccess; } + PK11Context *mac_context = + (useServerMacKey ? spec->server.write_mac_context + : spec->client.write_mac_context); + rv = PK11_DigestBegin(mac_context); + rv |= PK11_DigestOp(mac_context, header, headerLen); + rv |= PK11_DigestOp(mac_context, input, inputLength); + rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size); PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size); PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength)); if (rv != SECSuccess) { - rv = SECFailure; - ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + rv = SECFailure; + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); } return rv; } @@ -2441,51 +2299,45 @@ ssl3_ComputeRecordMAC( */ static SECStatus ssl3_ComputeRecordMACConstantTime( - ssl3CipherSpec * spec, - PRBool useServerMacKey, + ssl3CipherSpec *spec, + PRBool useServerMacKey, const unsigned char *header, - unsigned int headerLen, - const SSL3Opaque * input, - int inputLen, - int originalLen, - unsigned char * outbuf, - unsigned int * outLen) -{ - CK_MECHANISM_TYPE macType; + unsigned int headerLen, + const SSL3Opaque *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; - SECStatus rv; - PK11SymKey * key; + SECItem param, inputItem, outputItem; + SECStatus rv; + PK11SymKey *key; PORT_Assert(inputLen >= spec->mac_size); PORT_Assert(originalLen >= inputLen); - if (spec->bypassCiphers) { - /* This function doesn't support PKCS#11 bypass. We fallback on the - * non-constant time version. */ - goto fallback; - } - if (spec->mac_def->mac == mac_null) { - *outLen = 0; - return SECSuccess; + *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; + if (spec->version == SSL_LIBRARY_VERSION_3_0) { + macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME; } params.macAlg = spec->mac_def->mmech; params.ulBodyTotalLen = originalLen; - params.pHeader = (unsigned char *) header; /* const cast */ + params.pHeader = (unsigned char *)header; /* const cast */ params.ulHeaderLen = headerLen; - param.data = (unsigned char*) ¶ms; + param.data = (unsigned char *)¶ms; param.len = sizeof(params); param.type = 0; - inputItem.data = (unsigned char *) input; + inputItem.data = (unsigned char *)input; inputItem.len = inputLen; inputItem.type = 0; @@ -2495,279 +2347,322 @@ ssl3_ComputeRecordMACConstantTime( key = spec->server.write_mac_key; if (!useServerMacKey) { - key = spec->client.write_mac_key; + key = spec->client.write_mac_key; } rv = PK11_SignWithSymKey(key, macType, ¶m, &outputItem, &inputItem); if (rv != SECSuccess) { - if (PORT_GetError() == SEC_ERROR_INVALID_ALGORITHM) { - goto fallback; - } + 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, useServerMacKey, + header, headerLen, + input, inputLen - spec->mac_size, + outbuf, outLen); + } - *outLen = 0; - rv = SECFailure; - ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); - return rv; + *outLen = 0; + rv = SECFailure; + ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE); + return rv; } PORT_Assert(outputItem.len == (unsigned)spec->mac_size); *outLen = outputItem.len; return rv; - -fallback: - /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the - * length already. */ - inputLen -= spec->mac_size; - return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen, - input, inputLen, outbuf, outLen); } static PRBool -ssl3_ClientAuthTokenPresent(sslSessionID *sid) { +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; + return PR_TRUE; } /* get the slot */ slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID, - sid->u.ssl3.clAuthSlotID); + 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; - } + !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); + PK11_FreeSlot(slot); } return isPresent; } /* Caller must hold the spec read lock. */ SECStatus -ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, - PRBool isServer, - PRBool isDTLS, - PRBool capRecordVersion, - SSL3ContentType type, - const SSL3Opaque * pIn, - PRUint32 contentLen, - sslBuffer * wrBuf) -{ - const ssl3BulkCipherDef * cipher_def; - SECStatus rv; - PRUint32 macLen = 0; - PRUint32 fragLen; - PRUint32 p1Len, p2Len, oddLen = 0; - PRUint16 headerLen; +ssl3_CompressMACEncryptRecord(ssl3CipherSpec *cwSpec, + PRBool isServer, + PRBool isDTLS, + PRBool capRecordVersion, + SSL3ContentType type, + const SSL3Opaque *pIn, + PRUint32 contentLen, + sslBuffer *wrBuf) +{ + const ssl3BulkCipherDef *cipher_def; + SECStatus rv; + PRUint32 macLen = 0; + PRUint32 fragLen; + PRUint32 p1Len, p2Len, oddLen = 0; unsigned int ivLen = 0; - int cipherBytes = 0; - unsigned char pseudoHeader[13]; - unsigned int pseudoHeaderLen; + unsigned char pseudoHeader[13]; + unsigned int pseudoHeaderLen; cipher_def = cwSpec->cipher_def; - headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; if (cipher_def->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 = cipher_def->iv_size; - if (ivLen > wrBuf->space - headerLen) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); - return rv; - } - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen, - &cipherBytes, /* output and actual outLen */ - ivLen, /* max outlen */ - wrBuf->buf + headerLen, - ivLen); /* input and inputLen*/ - if (rv != SECSuccess || cipherBytes != ivLen) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } + 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 = cipher_def->iv_size; + if (ivLen > wrBuf->space) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + rv = PK11_GenerateRandom(wrBuf->buf, ivLen); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); + return rv; + } + rv = cwSpec->encode(cwSpec->encodeContext, + wrBuf->buf, /* output */ + (int *)&wrBuf->len, /* outlen */ + ivLen, /* max outlen */ + wrBuf->buf, /* input */ + ivLen); /* input len */ + if (rv != SECSuccess || wrBuf->len != ivLen) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } } if (cwSpec->compressor) { - int outlen; - rv = cwSpec->compressor( - cwSpec->compressContext, - wrBuf->buf + headerLen + ivLen, &outlen, - wrBuf->space - headerLen - ivLen, pIn, contentLen); - if (rv != SECSuccess) - return rv; - pIn = wrBuf->buf + headerLen + ivLen; - contentLen = outlen; + int outlen; + rv = cwSpec->compressor(cwSpec->compressContext, wrBuf->buf + ivLen, + &outlen, wrBuf->space - ivLen, pIn, contentLen); + if (rv != SECSuccess) + return rv; + pIn = wrBuf->buf + ivLen; + contentLen = outlen; } pseudoHeaderLen = ssl3_BuildRecordPseudoHeader( - pseudoHeader, cwSpec->write_seq_num, type, - cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, - isDTLS, contentLen); + pseudoHeader, cwSpec->write_seq_num, type, + cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version, + isDTLS, contentLen); PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader)); if (cipher_def->type == type_aead) { - const int nonceLen = cipher_def->explicit_nonce_size; - const int tagLen = cipher_def->tag_size; - - if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - - cipherBytes = contentLen; - rv = cwSpec->aead( - isServer ? &cwSpec->server : &cwSpec->client, - PR_FALSE, /* do encrypt */ - wrBuf->buf + headerLen, /* output */ - &cipherBytes, /* out len */ - wrBuf->space - headerLen, /* max out */ - pIn, contentLen, /* input */ - pseudoHeader, pseudoHeaderLen); - if (rv != SECSuccess) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } + const int nonceLen = cipher_def->explicit_nonce_size; + const int tagLen = cipher_def->tag_size; + + if (nonceLen + contentLen + tagLen > wrBuf->space) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + rv = cwSpec->aead( + isServer ? &cwSpec->server : &cwSpec->client, + PR_FALSE, /* do encrypt */ + wrBuf->buf, /* output */ + (int *)&wrBuf->len, /* out len */ + wrBuf->space, /* max out */ + pIn, contentLen, /* input */ + pseudoHeader, pseudoHeaderLen); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } } else { - /* - * Add the MAC - */ - rv = ssl3_ComputeRecordMAC(cwSpec, isServer, - pseudoHeader, pseudoHeaderLen, pIn, contentLen, - wrBuf->buf + headerLen + ivLen + 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 (cipher_def->type == type_block) { - unsigned char * pBuf; - int padding_length; - int i; - - oddLen = contentLen % cipher_def->block_size; - /* Assume blockSize is a power of two */ - padding_length = cipher_def->block_size - 1 - - ((fragLen) & (cipher_def->block_size - 1)); - fragLen += padding_length + 1; - PORT_Assert((fragLen % cipher_def->block_size) == 0); - - /* Pad according to TLS rules (also acceptable to SSL3). */ - pBuf = &wrBuf->buf[headerLen + ivLen + 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( (cipher_def->block_size < 2) || \ - (p2Len % cipher_def->block_size) == 0); - memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, - oddLen); - } - if (p1Len > 0) { - int cipherBytesPart1 = -1; - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen + ivLen, /* output */ - &cipherBytesPart1, /* actual outlen */ - p1Len, /* max outlen */ - pIn, p1Len); /* input, and inputlen */ - PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len); - if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - cipherBytes += cipherBytesPart1; - } - if (p2Len > 0) { - int cipherBytesPart2 = -1; - rv = cwSpec->encode( cwSpec->encodeContext, - wrBuf->buf + headerLen + ivLen + p1Len, - &cipherBytesPart2, /* output and actual outLen */ - p2Len, /* max outlen */ - wrBuf->buf + headerLen + ivLen + p1Len, - p2Len); /* input and inputLen*/ - PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len); - if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) { - PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); - return SECFailure; - } - cipherBytes += cipherBytesPart2; - } - } - - PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024); - - wrBuf->len = cipherBytes + headerLen; - wrBuf->buf[0] = type; - if (isDTLS) { - SSL3ProtocolVersion version; - - version = dtls_TLSVersionToDTLSVersion(cwSpec->version); - wrBuf->buf[1] = MSB(version); - wrBuf->buf[2] = LSB(version); - wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24); - wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16); - wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >> 8); - wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >> 0); - wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low >> 24); - wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low >> 16); - wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low >> 8); - wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >> 0); - wrBuf->buf[11] = MSB(cipherBytes); - wrBuf->buf[12] = LSB(cipherBytes); + /* + * Add the MAC + */ + rv = ssl3_ComputeRecordMAC(cwSpec, isServer, pseudoHeader, + pseudoHeaderLen, pIn, contentLen, + wrBuf->buf + ivLen + 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 (cipher_def->type == type_block) { + unsigned char *pBuf; + int padding_length; + int i; + + oddLen = contentLen % cipher_def->block_size; + /* Assume blockSize is a power of two */ + padding_length = cipher_def->block_size - 1 - ((fragLen) & (cipher_def->block_size - 1)); + fragLen += padding_length + 1; + PORT_Assert((fragLen % cipher_def->block_size) == 0); + + /* Pad according to TLS rules (also acceptable to SSL3). */ + pBuf = &wrBuf->buf[ivLen + 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((cipher_def->block_size < 2) || + (p2Len % cipher_def->block_size) == 0); + memmove(wrBuf->buf + ivLen + p1Len, pIn + p1Len, oddLen); + } + if (p1Len > 0) { + int cipherBytesPart1 = -1; + rv = cwSpec->encode(cwSpec->encodeContext, + wrBuf->buf + ivLen, /* output */ + &cipherBytesPart1, /* actual outlen */ + p1Len, /* max outlen */ + pIn, + p1Len); /* input, and inputlen */ + PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int)p1Len); + if (rv != SECSuccess || cipherBytesPart1 != (int)p1Len) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } + wrBuf->len += cipherBytesPart1; + } + if (p2Len > 0) { + int cipherBytesPart2 = -1; + rv = cwSpec->encode(cwSpec->encodeContext, + wrBuf->buf + ivLen + p1Len, + &cipherBytesPart2, /* output and actual outLen */ + p2Len, /* max outlen */ + wrBuf->buf + ivLen + p1Len, + p2Len); /* input and inputLen*/ + PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int)p2Len); + if (rv != SECSuccess || cipherBytesPart2 != (int)p2Len) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } + wrBuf->len += cipherBytesPart2; + } + } + + return SECSuccess; +} + +SECStatus +ssl_ProtectRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, + PRBool capRecordVersion, SSL3ContentType type, + const SSL3Opaque *pIn, PRUint32 contentLen, sslBuffer *wrBuf) +{ + const ssl3BulkCipherDef *cipher_def = cwSpec->cipher_def; + PRUint16 headerLen; + sslBuffer protBuf; + SSL3ProtocolVersion version = cwSpec->version; + PRBool isTLS13; + PRUint8 *ptr = wrBuf->buf; + SECStatus rv; + + if (ss->ssl3.hs.shortHeaders) { + PORT_Assert(!IS_DTLS(ss)); + PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); + headerLen = TLS13_RECORD_HEADER_LENGTH_SHORT; } else { - SSL3ProtocolVersion version = cwSpec->version; + headerLen = IS_DTLS(ss) ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH; + } + protBuf.buf = wrBuf->buf + headerLen; + protBuf.len = 0; + protBuf.space = wrBuf->space - headerLen; + + PORT_Assert(cipher_def->max_records <= RECORD_SEQ_MAX); + if ((cwSpec->write_seq_num & RECORD_SEQ_MAX) >= cipher_def->max_records) { + SSL_TRC(3, ("%d: SSL[-]: write sequence number at limit 0x%0llx", + SSL_GETPID(), cwSpec->write_seq_num)); + PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS); + return SECFailure; + } - if (capRecordVersion) { - version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); - } - wrBuf->buf[1] = MSB(version); - wrBuf->buf[2] = LSB(version); - wrBuf->buf[3] = MSB(cipherBytes); - wrBuf->buf[4] = LSB(cipherBytes); + isTLS13 = (PRBool)(cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_3); + +#ifdef UNSAFE_FUZZER_MODE + rv = Null_Cipher(NULL, protBuf.buf, (int *)&protBuf.len, protBuf.space, + pIn, contentLen); +#else + if (isTLS13) { + rv = tls13_ProtectRecord(ss, cwSpec, type, pIn, contentLen, &protBuf); + } else { + rv = ssl3_CompressMACEncryptRecord(cwSpec, ss->sec.isServer, + IS_DTLS(ss), capRecordVersion, type, + pIn, contentLen, &protBuf); + } +#endif + if (rv != SECSuccess) { + return SECFailure; /* error was set */ } - ssl3_BumpSequenceNumber(&cwSpec->write_seq_num); + PORT_Assert(protBuf.len <= MAX_FRAGMENT_LENGTH + (isTLS13 ? 256 : 1024)); + wrBuf->len = protBuf.len + headerLen; + + if (ss->ssl3.hs.shortHeaders) { + PORT_Assert(!IS_DTLS(ss)); /* Decoder not yet implemented. */ + (void)ssl_EncodeUintX(0x8000 | protBuf.len, 2, ptr); + } else { +#ifndef UNSAFE_FUZZER_MODE + if (isTLS13 && cipher_def->calg != ssl_calg_null) { + *ptr++ = content_application_data; + } else +#endif + { + *ptr++ = type; + } + + if (IS_DTLS(ss)) { + version = isTLS13 ? SSL_LIBRARY_VERSION_TLS_1_1 : version; + version = dtls_TLSVersionToDTLSVersion(version); + + ptr = ssl_EncodeUintX(version, 2, ptr); + ptr = ssl_EncodeUintX(cwSpec->write_seq_num, 8, ptr); + } else { + if (capRecordVersion || isTLS13) { + version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version); + } + ptr = ssl_EncodeUintX(version, 2, ptr); + } + (void)ssl_EncodeUintX(protBuf.len, 2, ptr); + } + ++cwSpec->write_seq_num; 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. + * plus the number of bytes of plaintext that were copied into the + * output (write) buffer. * Returns SECFailure on a hard IO error, memory error, or crypto error. * Does NOT return SECWouldBlock. * @@ -2796,24 +2691,24 @@ ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, * flag to work around such servers. */ PRInt32 -ssl3_SendRecord( sslSocket * ss, - DTLSEpoch epoch, /* DTLS only */ - SSL3ContentType type, - const SSL3Opaque * pIn, /* input buffer */ - PRInt32 nIn, /* bytes of input */ - PRInt32 flags) -{ - sslBuffer * wrBuf = &ss->sec.writeBuf; - SECStatus rv; - PRInt32 totalSent = 0; - PRBool capRecordVersion; +ssl3_SendRecord(sslSocket *ss, + ssl3CipherSpec *cwSpec, /* non-NULL for DTLS retransmits */ + SSL3ContentType type, + const SSL3Opaque *pIn, /* input buffer */ + PRInt32 nIn, /* bytes of input */ + PRInt32 flags) +{ + sslBuffer *wrBuf = &ss->sec.writeBuf; + SECStatus rv; + PRInt32 totalSent = 0; + PRBool capRecordVersion; SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d", - SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), - nIn)); + SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type), + nIn)); PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); if (ss->ssl3.fatalAlertSent) { SSL_TRC(3, ("%d: SSL3[%d] Suppress write, fatal alert already sent", @@ -2824,180 +2719,172 @@ ssl3_SendRecord( sslSocket * ss, capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0); if (capRecordVersion) { - /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the - * TLS initial ClientHello. */ - PORT_Assert(!IS_DTLS(ss)); - PORT_Assert(!ss->firstHsDone); - PORT_Assert(type == content_handshake); - PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); + /* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the + * TLS initial ClientHello. */ + PORT_Assert(!IS_DTLS(ss)); + PORT_Assert(!ss->firstHsDone); + PORT_Assert(type == content_handshake); + PORT_Assert(ss->ssl3.hs.ws == wait_server_hello); } if (ss->ssl3.initialized == PR_FALSE) { - /* This can happen on a server if the very first incoming record - ** looks like a defective ssl3 record (e.g. too long), and we're - ** trying to send an alert. - */ - PR_ASSERT(type == content_alert); - rv = ssl3_InitState(ss); - if (rv != SECSuccess) { - return SECFailure; /* ssl3_InitState has set the error code. */ - } + /* This can happen on a server if the very first incoming record + ** looks like a defective ssl3 record (e.g. too long), and we're + ** trying to send an alert. + */ + PR_ASSERT(type == content_alert); + rv = ssl3_InitState(ss); + if (rv != SECSuccess) { + return SECFailure; /* ssl3_InitState has set the error code. */ + } } /* check for Token Presence */ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; } while (nIn > 0) { - PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); - unsigned int spaceNeeded; - unsigned int numRecords; - - ssl_GetSpecReadLock(ss); /********************************/ - - if (nIn > 1 && ss->opt.cbcRandomIV && - ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && - type == content_application_data && - ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { - /* 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 - */ - numRecords = 2; - } else { - numRecords = 1; - } - - spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); - if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && - ss->ssl3.cwSpec->cipher_def->type == type_block) { - spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; - } - if (spaceNeeded > wrBuf->space) { - rv = sslBuffer_Grow(wrBuf, spaceNeeded); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", - SSL_GETPID(), ss->fd, spaceNeeded)); - goto spec_locked_loser; /* sslBuffer_Grow set error code. */ - } - } - - if (numRecords == 2) { - sslBuffer secondRecord; - - rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, - ss->sec.isServer, IS_DTLS(ss), - capRecordVersion, type, pIn, - 1, wrBuf); - if (rv != SECSuccess) - goto spec_locked_loser; - - PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", - wrBuf->buf, wrBuf->len)); - - secondRecord.buf = wrBuf->buf + wrBuf->len; - secondRecord.len = 0; - secondRecord.space = wrBuf->space - wrBuf->len; - - rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, - ss->sec.isServer, IS_DTLS(ss), - capRecordVersion, type, - pIn + 1, contentLen - 1, - &secondRecord); - if (rv == SECSuccess) { - PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", - secondRecord.buf, secondRecord.len)); - wrBuf->len += secondRecord.len; - } - } else { - if (!IS_DTLS(ss)) { - rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec, - ss->sec.isServer, - IS_DTLS(ss), - capRecordVersion, - type, pIn, - contentLen, wrBuf); - } else { - rv = dtls_CompressMACEncryptRecord(ss, epoch, - !!(flags & ssl_SEND_FLAG_USE_EPOCH), - type, pIn, - contentLen, wrBuf); - } - - if (rv == SECSuccess) { - PRINT_BUF(50, (ss, "send (encrypted) record data:", - wrBuf->buf, wrBuf->len)); - } - } - -spec_locked_loser: - ssl_ReleaseSpecReadLock(ss); /************************************/ - - if (rv != SECSuccess) - return SECFailure; - - pIn += contentLen; - nIn -= contentLen; - 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, wrBuf->buf, wrBuf->len); - if (rv != SECSuccess) { - /* presumably a memory error, SEC_ERROR_NO_MEMORY */ - return SECFailure; - } - wrBuf->len = 0; /* All cipher text is saved away. */ - - if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { - PRInt32 sent; - ss->handshakeBegun = 1; - sent = ssl_SendSavedWriteData(ss); - if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { - ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); - return SECFailure; - } - if (ss->pendingBuf.len) { - flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; - } - } - } else if (wrBuf->len > 0) { - PRInt32 sent; - ss->handshakeBegun = 1; - sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, - flags & ~ssl_SEND_FLAG_MASK); - if (sent < 0) { - if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { - ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); - return SECFailure; - } - /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ - sent = 0; - } - wrBuf->len -= sent; - if (wrBuf->len) { - if (IS_DTLS(ss)) { - /* DTLS just says no in this case. No buffering */ - PR_SetError(PR_WOULD_BLOCK_ERROR, 0); - return SECFailure; - } - /* now take all the remaining unsent new ciphertext and - * append it to the buffer of previously unsent ciphertext. - */ - rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); - if (rv != SECSuccess) { - /* presumably a memory error, SEC_ERROR_NO_MEMORY */ - return SECFailure; - } - } - } - totalSent += contentLen; + PRUint32 contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH); + unsigned int spaceNeeded; + unsigned int numRecords; + + ssl_GetSpecReadLock(ss); /********************************/ + + if (nIn > 1 && ss->opt.cbcRandomIV && + ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 && + type == content_application_data && + ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) { + /* 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 + */ + numRecords = 2; + } else { + numRecords = 1; + } + + spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE); + if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 && + ss->ssl3.cwSpec->cipher_def->type == type_block) { + spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size; + } + if (spaceNeeded > wrBuf->space) { + rv = sslBuffer_Grow(wrBuf, spaceNeeded); + if (rv != SECSuccess) { + SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes", + SSL_GETPID(), ss->fd, spaceNeeded)); + goto spec_locked_loser; /* sslBuffer_Grow set error code. */ + } + } + + if (numRecords == 2) { + sslBuffer secondRecord; + rv = ssl_ProtectRecord(ss, ss->ssl3.cwSpec, capRecordVersion, type, + pIn, 1, wrBuf); + if (rv != SECSuccess) + goto spec_locked_loser; + + PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:", + wrBuf->buf, wrBuf->len)); + + secondRecord.buf = wrBuf->buf + wrBuf->len; + secondRecord.len = 0; + secondRecord.space = wrBuf->space - wrBuf->len; + + rv = ssl_ProtectRecord(ss, ss->ssl3.cwSpec, capRecordVersion, type, + pIn + 1, contentLen - 1, &secondRecord); + if (rv == SECSuccess) { + PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:", + secondRecord.buf, secondRecord.len)); + wrBuf->len += secondRecord.len; + } + } else { + if (cwSpec) { + /* cwSpec can only be set for retransmissions of DTLS handshake + * messages. */ + PORT_Assert(IS_DTLS(ss) && + (type == content_handshake || + type == content_change_cipher_spec)); + } else { + cwSpec = ss->ssl3.cwSpec; + } + + rv = ssl_ProtectRecord(ss, cwSpec, !IS_DTLS(ss) && capRecordVersion, + type, pIn, contentLen, wrBuf); + if (rv == SECSuccess) { + PRINT_BUF(50, (ss, "send (encrypted) record data:", + wrBuf->buf, wrBuf->len)); + } + } + + spec_locked_loser: + ssl_ReleaseSpecReadLock(ss); /************************************/ + + if (rv != SECSuccess) + return SECFailure; + + pIn += contentLen; + nIn -= contentLen; + 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, wrBuf->buf, wrBuf->len); + if (rv != SECSuccess) { + /* presumably a memory error, SEC_ERROR_NO_MEMORY */ + return SECFailure; + } + wrBuf->len = 0; /* All cipher text is saved away. */ + + if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) { + PRInt32 sent; + ss->handshakeBegun = 1; + sent = ssl_SendSavedWriteData(ss); + if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) { + ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); + return SECFailure; + } + if (ss->pendingBuf.len) { + flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER; + } + } + } else if (wrBuf->len > 0) { + PRInt32 sent; + ss->handshakeBegun = 1; + sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len, + flags & ~ssl_SEND_FLAG_MASK); + if (sent < 0) { + if (PR_GetError() != PR_WOULD_BLOCK_ERROR) { + ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE); + return SECFailure; + } + /* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */ + sent = 0; + } + wrBuf->len -= sent; + if (wrBuf->len) { + if (IS_DTLS(ss)) { + /* DTLS just says no in this case. No buffering */ + PR_SetError(PR_WOULD_BLOCK_ERROR, 0); + return SECFailure; + } + /* now take all the remaining unsent new ciphertext and + * append it to the buffer of previously unsent ciphertext. + */ + rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len); + if (rv != SECSuccess) { + /* presumably a memory error, SEC_ERROR_NO_MEMORY */ + return SECFailure; + } + } + } + totalSent += contentLen; } return totalSent; } @@ -3009,87 +2896,86 @@ spec_locked_loser: */ int ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, - PRInt32 len, PRInt32 flags) + PRInt32 len, PRInt32 flags) { - PRInt32 totalSent = 0; - PRInt32 discarded = 0; + PRInt32 totalSent = 0; + PRInt32 discarded = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); /* These flags for internal use only */ - PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH | - ssl_SEND_FLAG_NO_RETRANSMIT))); + PORT_Assert(!(flags & ssl_SEND_FLAG_NO_RETRANSMIT)); if (len < 0 || !in) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER && !ssl_SocketIsBlocking(ss)) { - PORT_Assert(!ssl_SocketIsBlocking(ss)); - PORT_SetError(PR_WOULD_BLOCK_ERROR); - return SECFailure; + PORT_Assert(!ssl_SocketIsBlocking(ss)); + PORT_SetError(PR_WOULD_BLOCK_ERROR); + return SECFailure; } 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 SECFailure; - } - in++; - len--; - discarded = 1; + PORT_Assert(in[0] == (unsigned char)(ss->appDataBuffered)); + if (in[0] != (unsigned char)(ss->appDataBuffered)) { + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; + } + in++; + len--; + discarded = 1; } 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); - } - 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, 0, content_application_data, - in + totalSent, toSend, flags); - if (sent < 0) { - if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { - PORT_Assert(ss->lastWriteBlocked); - break; - } - return SECFailure; /* 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; - } + 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); + } + 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, content_application_data, + in + totalSent, toSend, flags); + if (sent < 0) { + if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) { + PORT_Assert(ss->lastWriteBlocked); + break; + } + return SECFailure; /* 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; - } + /* 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; } @@ -3108,7 +2994,7 @@ ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in, * ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(), * ssl3_SendFinished(), */ -static SECStatus +SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags) { if (IS_DTLS(ss)) { @@ -3130,37 +3016,37 @@ ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER | ssl_SEND_FLAG_CAP_RECORD_VERSION; PRInt32 count = -1; - SECStatus rv = SECSuccess; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + 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 rv; + return SECSuccess; /* only these flags are allowed */ PORT_Assert(!(flags & ~allowedFlags)); if ((flags & ~allowedFlags) != 0) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } else { - count = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf, - ss->sec.ci.sendBuf.len, flags); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } + count = ssl3_SendRecord(ss, NULL, content_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); - } + 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; + /* 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; + rv = SECSuccess; } /* Whether we succeeded or failed, toss the old handshake data. */ @@ -3174,43 +3060,34 @@ ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags) * Returns SECFailure if the application has required client auth. * SECSuccess otherwise. */ -static SECStatus +SECStatus ssl3_HandleNoCertificate(sslSocket *ss) { - if (ss->sec.peerCert != NULL) { - if (ss->sec.peerKey != NULL) { - SECKEY_DestroyPublicKey(ss->sec.peerKey); - ss->sec.peerKey = NULL; - } - CERT_DestroyCertificate(ss->sec.peerCert); - ss->sec.peerCert = NULL; - } 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 + * 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; + (!ss->firstHsDone && + (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) { + PRFileDesc *lower; - if (ss->sec.uncache) - ss->sec.uncache(ss->sec.ci.sid); - SSL3_SendAlert(ss, alert_fatal, bad_certificate); + ss->sec.uncache(ss->sec.ci.sid); + SSL3_SendAlert(ss, alert_fatal, bad_certificate); - lower = ss->fd->lower; + lower = ss->fd->lower; #ifdef _WIN32 - lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); + lower->methods->shutdown(lower, PR_SHUTDOWN_SEND); #else - lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); + lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH); #endif - PORT_SetError(SSL_ERROR_NO_CERTIFICATE); - return SECFailure; + PORT_SetError(SSL_ERROR_NO_CERTIFICATE); + return SECFailure; } return SECSuccess; } @@ -3221,59 +3098,59 @@ ssl3_HandleNoCertificate(sslSocket *ss) /* ** Acquires both handshake and XmitBuf locks. -** Called from: ssl3_IllegalParameter <- -** ssl3_HandshakeFailure <- -** ssl3_HandleAlert <- ssl3_HandleRecord. +** Called from: ssl3_IllegalParameter <- +** ssl3_HandshakeFailure <- +** ssl3_HandleAlert <- ssl3_HandleRecord. ** ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord ** ssl3_ConsumeHandshakeVariable <- -** ssl3_HandleHelloRequest <- -** ssl3_HandleServerHello <- +** ssl3_HandleHelloRequest <- +** ssl3_HandleServerHello <- ** ssl3_HandleServerKeyExchange <- ** ssl3_HandleCertificateRequest <- ** ssl3_HandleServerHelloDone <- -** ssl3_HandleClientHello <- +** ssl3_HandleClientHello <- ** ssl3_HandleV2ClientHello <- ** ssl3_HandleCertificateVerify <- ** ssl3_HandleClientKeyExchange <- -** ssl3_HandleCertificate <- -** ssl3_HandleFinished <- +** ssl3_HandleCertificate <- +** ssl3_HandleFinished <- ** ssl3_HandleHandshakeMessage <- -** ssl3_HandleRecord <- +** ssl3_HandlePostHelloHandshakeMessage <- +** ssl3_HandleRecord <- ** */ SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc) { - PRUint8 bytes[2]; - SECStatus rv; + PRUint8 bytes[2]; + SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d", - SSL_GETPID(), ss->fd, level, desc)); + SSL_GETPID(), ss->fd, level, desc)); bytes[0] = level; bytes[1] = desc; ssl_GetSSL3HandshakeLock(ss); if (level == alert_fatal) { - if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) { - ss->sec.uncache(ss->sec.ci.sid); - } + if (!ss->opt.noCache && ss->sec.ci.sid) { + ss->sec.uncache(ss->sec.ci.sid); + } } ssl_GetXmitBufLock(ss); rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); if (rv == SECSuccess) { - PRInt32 sent; - sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2, - desc == no_certificate - ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0); - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; + PRInt32 sent; + sent = ssl3_SendRecord(ss, NULL, content_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); ssl_ReleaseSSL3HandshakeLock(ss); - return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ + return rv; /* error set by ssl3_FlushHandshake or ssl3_SendRecord */ } /* @@ -3284,7 +3161,7 @@ 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 ); + : SSL_ERROR_BAD_SERVER); return SECFailure; } @@ -3295,56 +3172,67 @@ 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 ); + PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT + : SSL_ERROR_BAD_SERVER); return SECFailure; } -static void -ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode) +void +ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode) { - SSL3AlertDescription desc = bad_certificate; + 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; + 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)); + SSL_GETPID(), ss->fd, errCode)); - (void) SSL3_SendAlert(ss, alert_fatal, desc); + (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 ); + (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; } @@ -3354,102 +3242,170 @@ ssl3_DecodeError(sslSocket *ss) static SECStatus ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) { - SSL3AlertLevel level; + SSL3AlertLevel level; SSL3AlertDescription desc; - int error; + int error; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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; + (void)ssl3_DecodeError(ss); + PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT); + return SECFailure; } level = (SSL3AlertLevel)buf->buf[0]; - desc = (SSL3AlertDescription)buf->buf[1]; + 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)); + SSL_GETPID(), ss->fd, level, desc)); 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 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 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; - default: error = SSL_ERROR_RX_UNKNOWN_ALERT; break; + 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 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 end_of_early_data: + error = SSL_ERROR_END_OF_EARLY_DATA_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: + case end_of_early_data: + break; + default: + level = alert_fatal; + } } if (level == alert_fatal) { - if (!ss->opt.noCache) { - if (ss->sec.uncache) - ss->sec.uncache(ss->sec.ci.sid); - } - 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 (!ss->opt.noCache) { + ss->sec.uncache(ss->sec.ci.sid); + } + 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 == end_of_early_data) { + return tls13_HandleEndOfEarlyData(ss); } 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; + /* 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; + PORT_Assert(ss->sec.isServer); + ss->ssl3.hs.ws = wait_client_key; + rv = ssl3_HandleNoCertificate(ss); + return rv; } return SECSuccess; } @@ -3467,61 +3423,60 @@ ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf) static SECStatus ssl3_SendChangeCipherSpecs(sslSocket *ss) { - PRUint8 change = change_cipher_spec_choice; - ssl3CipherSpec * pwSpec; - SECStatus rv; - PRInt32 sent; + PRUint8 change = change_cipher_spec_choice; + ssl3CipherSpec *pwSpec; + SECStatus rv; + PRInt32 sent; SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } if (!IS_DTLS(ss)) { - sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1, - ssl_SEND_FLAG_FORCE_INTO_BUFFER); - if (sent < 0) { - return (SECStatus)sent; /* error code set by ssl3_SendRecord */ - } + sent = ssl3_SendRecord(ss, NULL, content_change_cipher_spec, &change, 1, + ssl_SEND_FLAG_FORCE_INTO_BUFFER); + if (sent < 0) { + return (SECStatus)sent; /* error code set by ssl3_SendRecord */ + } } else { - rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); - if (rv != SECSuccess) { - return rv; - } + rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1); + if (rv != SECSuccess) { + return rv; + } } /* swap the pending and current write specs. */ - ssl_GetSpecWriteLock(ss); /**************************************/ - pwSpec = ss->ssl3.pwSpec; + ssl_GetSpecWriteLock(ss); /**************************************/ + pwSpec = ss->ssl3.pwSpec; ss->ssl3.pwSpec = ss->ssl3.cwSpec; ss->ssl3.cwSpec = pwSpec; SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending", - SSL_GETPID(), ss->fd )); + SSL_GETPID(), ss->fd)); /* We need to free up the contexts, keys and certs ! */ /* If we are really through with the old cipher spec * (Both the read and write sides have changed) destroy it. */ if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { - if (!IS_DTLS(ss)) { - ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/); - } else { - /* With DTLS, we need to set a holddown timer in case the final - * message got lost */ - ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS; - dtls_StartTimer(ss, dtls_FinishedTimerCb); - } + if (!IS_DTLS(ss)) { + ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE /*freeSrvName*/); + } else { + /* With DTLS, we need to set a holddown timer in case the final + * message got lost */ + rv = dtls_StartHolddownTimer(ss); + } } ssl_ReleaseSpecWriteLock(ss); /**************************************/ - return SECSuccess; + return rv; } /* Called from ssl3_HandleRecord. @@ -3533,65 +3488,124 @@ ssl3_SendChangeCipherSpecs(sslSocket *ss) static SECStatus ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf) { - ssl3CipherSpec * prSpec; - SSL3WaitState ws = ss->ssl3.hs.ws; + ssl3CipherSpec *prSpec; + SSL3WaitState ws = ss->ssl3.hs.ws; SSL3ChangeCipherSpecChoice change; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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)); + SSL_GETPID(), ss->fd)); if (ws != wait_change_cipher) { - if (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; - } - (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; + if (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; + } + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER); + return SECFailure; + } + /* 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; + /* 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; /* Swap the pending and current read specs. */ - ssl_GetSpecWriteLock(ss); /*************************************/ - prSpec = ss->ssl3.prSpec; + ssl_GetSpecWriteLock(ss); /*************************************/ + prSpec = ss->ssl3.prSpec; - ss->ssl3.prSpec = ss->ssl3.crSpec; - ss->ssl3.crSpec = prSpec; - ss->ssl3.hs.ws = wait_finished; + ss->ssl3.prSpec = ss->ssl3.crSpec; + ss->ssl3.crSpec = prSpec; + ss->ssl3.hs.ws = wait_finished; SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending", - SSL_GETPID(), ss->fd )); + SSL_GETPID(), ss->fd)); /* If we are really through with the old cipher prSpec * (Both the read and write sides have changed) destroy it. */ if (ss->ssl3.prSpec == ss->ssl3.pwSpec) { - ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/); + ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE /*freeSrvName*/); } - ssl_ReleaseSpecWriteLock(ss); /*************************************/ + ssl_ReleaseSpecWriteLock(ss); /*************************************/ 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. @@ -3657,67 +3671,71 @@ static SECStatus ssl3_ComputeMasterSecretInt(sslSocket *ss, PK11SymKey *pms, PK11SymKey **msp) { - ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; - const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def; - unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; - unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; - PRBool isTLS = (PRBool)(kea_def->tls_keygen || - (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); - PRBool isTLS12= - (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; + unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; + PRBool isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); + PRBool isTLS12 = + (PRBool)(isTLS && pwSpec->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 == kt_dh) || - (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); + 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; + 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; + 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; + 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; + 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) + 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 = cr; + master_params.pVersion = pms_version_ptr; + master_params.RandomInfo.pClientRandom = cr; master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; - master_params.RandomInfo.pServerRandom = sr; + master_params.RandomInfo.pServerRandom = sr; master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; if (isTLS12) { - master_params.prfHashMechanism = CKM_SHA256; + 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; + params.data = (unsigned char *)&master_params; + params.len = master_params_len; return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, pms_version_ptr, ¶ms, @@ -3742,8 +3760,8 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, /* * 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 == kt_dh) || - (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh)); + 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; @@ -3754,7 +3772,7 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, rv = ssl3_ComputeHandshakeHashes(ss, pwSpec, &hashes, 0); if (rv != SECSuccess) { - PORT_Assert(0); /* Should never fail */ + PORT_Assert(0); /* Should never fail */ ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return SECFailure; } @@ -3767,20 +3785,20 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, } if (pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - /* TLS 1.2 */ - extended_master_params.prfHashMechanism = CKM_SHA256; + /* 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; + 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.data = (unsigned char *)&extended_master_params; params.len = sizeof extended_master_params; return ssl3_ComputeMasterSecretFinish(ss, master_derive, key_derive, @@ -3788,7 +3806,6 @@ tls_ComputeExtendedMasterSecretInt(sslSocket *ss, PK11SymKey *pms, keyFlags, pms, msp); } - /* Wrapper method to compute the master secret and return it in |*msp|. ** ** Called from ssl3_ComputeMasterSecret @@ -3821,11 +3838,11 @@ static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) { SECStatus rv; - PK11SymKey* ms = NULL; + PK11SymKey *ms = NULL; ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); if (pms) { @@ -3835,43 +3852,17 @@ ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) return rv; } -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - SECItem * keydata; - /* In hope of doing a "double bypass", - * need to extract the master secret's value from the key object - * and store it raw in the sslSocket struct. - */ - rv = PK11_ExtractKeyValue(pwSpec->master_secret); - if (rv != SECSuccess) { - return rv; - } - /* This returns the address of the secItem inside the key struct, - * not a copy or a reference. So, there's no need to free it. - */ - keydata = PK11_GetKeyData(pwSpec->master_secret); - if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) { - memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = keydata->len; - } else { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } - } -#endif - return SECSuccess; } -/* +/* * 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 - * sendRSAClientKeyExchange (for Full handshake) - * sendDHClientKeyExchange (for Full handshake) + * 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) @@ -3880,279 +3871,239 @@ ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms) * */ static SECStatus -ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss) -{ - ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; - unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; - PRBool isTLS = (PRBool)(kea_def->tls_keygen || - (pwSpec->version > SSL_LIBRARY_VERSION_3_0)); - PRBool isTLS12= - (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); - /* following variables used in PKCS11 path */ +ssl3_DeriveConnectionKeys(sslSocket *ss) +{ + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + unsigned char *cr = (unsigned char *)&ss->ssl3.hs.client_random; + unsigned char *sr = (unsigned char *)&ss->ssl3.hs.server_random; + PRBool isTLS = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0); + PRBool isTLS12 = + (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def; - PK11SlotInfo * slot = NULL; - PK11SymKey * symKey = NULL; - void * pwArg = ss->pkcs11PinArg; - int keySize; + PK11SlotInfo *slot = NULL; + PK11SymKey *symKey = 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 == calg_null); - - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); + * 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 == calg_null); + + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); if (!pwSpec->master_secret) { - PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); - return SECFailure; + PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); + return SECFailure; } /* * generate the key material */ - key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; - key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB; - key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; + key_material_params.ulMacSizeInBits = pwSpec->mac_size * BPB; + key_material_params.ulKeySizeInBits = cipher_def->secret_key_size * BPB; + key_material_params.ulIVSizeInBits = cipher_def->iv_size * BPB; if (cipher_def->type == type_block && - pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { - /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ - key_material_params.ulIVSizeInBits = 0; - memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); - memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); + pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) { + /* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */ + key_material_params.ulIVSizeInBits = 0; + memset(pwSpec->client.write_iv, 0, cipher_def->iv_size); + memset(pwSpec->server.write_iv, 0, cipher_def->iv_size); } - key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited); - - key_material_params.RandomInfo.pClientRandom = cr; + key_material_params.bIsExport = PR_FALSE; + key_material_params.RandomInfo.pClientRandom = cr; key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH; - key_material_params.RandomInfo.pServerRandom = sr; + key_material_params.RandomInfo.pServerRandom = sr; key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH; - key_material_params.pReturnedKeyMaterial = &returnedKeys; + key_material_params.pReturnedKeyMaterial = &returnedKeys; returnedKeys.pIVClient = pwSpec->client.write_iv; returnedKeys.pIVServer = pwSpec->server.write_iv; - keySize = cipher_def->key_size; + keySize = cipher_def->key_size; if (skipKeysAndIVs) { - keySize = 0; + keySize = 0; key_material_params.ulKeySizeInBits = 0; - key_material_params.ulIVSizeInBits = 0; - returnedKeys.pIVClient = NULL; - returnedKeys.pIVServer = NULL; + key_material_params.ulIVSizeInBits = 0; + returnedKeys.pIVClient = NULL; + returnedKeys.pIVServer = NULL; } calg = cipher_def->calg; - PORT_Assert( alg2Mech[calg].calg == calg); - bulk_mechanism = alg2Mech[calg].cmech; + bulk_mechanism = ssl3_Alg2Mech(calg); if (isTLS12) { - key_derive = CKM_TLS12_KEY_AND_MAC_DERIVE; - key_material_params.prfHashMechanism = CKM_SHA256; - key_material_params_len = sizeof(CK_TLS12_KEY_MAT_PARAMS); + 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); + 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); + 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; + params.len = key_material_params_len; /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and * DERIVE by DEFAULT */ symKey = PK11_Derive(pwSpec->master_secret, key_derive, ¶ms, bulk_mechanism, CKA_ENCRYPT, keySize); if (!symKey) { - ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); - return SECFailure; + 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(symKey); + slot = PK11_GetSlotFromKey(symKey); PK11_FreeSlot(slot); /* slot is held until the key is freed */ pwSpec->client.write_mac_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); - if (pwSpec->client.write_mac_key == NULL ) { - goto loser; /* loser sets err */ + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg); + if (pwSpec->client.write_mac_key == NULL) { + goto loser; /* loser sets err */ } pwSpec->server.write_mac_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); - if (pwSpec->server.write_mac_key == NULL ) { - goto loser; /* loser sets err */ + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg); + if (pwSpec->server.write_mac_key == NULL) { + goto loser; /* loser sets err */ } if (!skipKeysAndIVs) { - pwSpec->client.write_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); - if (pwSpec->client.write_key == NULL ) { - goto loser; /* loser sets err */ - } - pwSpec->server.write_key = - PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, - bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); - if (pwSpec->server.write_key == NULL ) { - goto loser; /* loser sets err */ - } + pwSpec->client.write_key = + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg); + if (pwSpec->client.write_key == NULL) { + goto loser; /* loser sets err */ + } + pwSpec->server.write_key = + PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive, + bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg); + if (pwSpec->server.write_key == NULL) { + goto loser; /* loser sets err */ + } } PK11_FreeSymKey(symKey); return SECSuccess; - loser: - if (symKey) PK11_FreeSymKey(symKey); + if (symKey) + PK11_FreeSymKey(symKey); ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE); return SECFailure; } /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in - * buffered messages in ss->ssl3.hs.messages. */ -static SECStatus + * 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)); + SSL_TRC(30, ("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd)); PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone); - if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256); - if (!ss->ssl3.hs.sha_obj) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - return SECFailure; - } - ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone; - ss->ssl3.hs.hashType = handshake_hash_single; - ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx); - } else { - ss->ssl3.hs.hashType = handshake_hash_combo; - MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx); - SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx); - } - } else -#endif - { - 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_2) { - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256); - 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; - } - - /* Create a backup SHA-1 hash for a potential client auth - * signature. - * - * In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the - * handshake hash function (SHA-256). If the server or the client - * does not support SHA-256 as a signature hash, we can either - * maintain a backup SHA-1 handshake hash or buffer all handshake - * messages. - */ - if (!ss->sec.isServer) { - ss->ssl3.hs.backupHash = PK11_CreateDigestContext(SEC_OID_SHA1); - if (ss->ssl3.hs.backupHash == NULL) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return SECFailure; - } - - if (PK11_DigestBegin(ss->ssl3.hs.backupHash) != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_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.messages.len > 0) { - if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, - ss->ssl3.hs.messages.len) != - SECSuccess) { - return SECFailure; - } - PORT_Free(ss->ssl3.hs.messages.buf); - ss->ssl3.hs.messages.buf = NULL; - ss->ssl3.hs.messages.len = 0; - ss->ssl3.hs.messages.space = 0; + 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; + } + } 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) { + if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf, + ss->ssl3.hs.messages.len) != SECSuccess) { + return SECFailure; + } + sslBuffer_Clear(&ss->ssl3.hs.messages); } return SECSuccess; } -static SECStatus +SECStatus ssl3_RestartHandshakeHashes(sslSocket *ss) { SECStatus rv = SECSuccess; - SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes", - SSL_GETPID(), ss->fd )); + 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; -#ifndef NO_PKCS11_BYPASS - ss->ssl3.hs.sha_obj = NULL; - ss->ssl3.hs.sha_clone = NULL; -#endif if (ss->ssl3.hs.md5) { - PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); - ss->ssl3.hs.md5 = NULL; + 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; + PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); + ss->ssl3.hs.sha = NULL; } return rv; } @@ -4160,64 +4111,56 @@ ssl3_RestartHandshakeHashes(sslSocket *ss) /* * Handshake messages */ -/* Called from ssl3_InitHandshakeHashes() -** ssl3_AppendHandshake() -** ssl3_StartHandshakeHash() -** ssl3_HandleV2ClientHello() -** ssl3_HandleHandshakeMessage() +/* Called from ssl3_InitHandshakeHashes() +** ssl3_AppendHandshake() +** ssl3_HandleV2ClientHello() +** ssl3_HandleHandshakeMessage() ** Caller must hold the ssl3Handshake lock. */ -static SECStatus -ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, - unsigned int l) +SECStatus +ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, unsigned int l) { - SECStatus rv = SECSuccess; + SECStatus rv = SECSuccess; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - /* We need to buffer the handshake messages until we have established - * which handshake hash function to use. */ - if (ss->ssl3.hs.hashType == handshake_hash_unknown) { - return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); + /* 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) { + return sslBuffer_Append(&ss->ssl3.hs.messages, b, l); } PRINT_BUF(90, (NULL, "handshake hash input:", b, l)); -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - if (ss->ssl3.hs.hashType == handshake_hash_single) { - ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l); - } else { - MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l); - SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l); - } - return rv; - } -#endif if (ss->ssl3.hs.hashType == handshake_hash_single) { - rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE); - return rv; - } - if (ss->ssl3.hs.backupHash) { - rv = PK11_DigestOp(ss->ssl3.hs.backupHash, b, l); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - return rv; - } - } - } else { - 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; - } + PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); + rv = PK11_DigestOp(ss->ssl3.hs.sha, 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; } @@ -4230,40 +4173,40 @@ ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b, SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes) { - unsigned char * src = (unsigned char *)void_src; - int room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; - SECStatus rv; + 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. */ + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* protects sendBuf. */ if (!bytes) - return SECSuccess; + 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 rv; /* sslBuffer_Grow has set a memory error code. */ - room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len; + 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 rv; /* sslBuffer_Grow has set 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)); + PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char *)void_src, bytes)); rv = ssl3_UpdateHandshakeHashes(ss, src, bytes); if (rv != SECSuccess) - return rv; /* error code set by ssl3_UpdateHandshakeHashes */ + return rv; /* 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 rv; /* error code set by ssl3_FlushHandshake */ - } - bytes -= room; - src += room; - room = ss->sec.ci.sendBuf.space; - PORT_Assert(ss->sec.ci.sendBuf.len == 0); + 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 rv; /* 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; @@ -4274,8 +4217,8 @@ SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) { SECStatus rv; - PRUint8 b[4]; - PRUint8 * p = b; + PRUint8 b[4]; + PRUint8 *p = b; PORT_Assert(lenSize <= 4 && lenSize > 0); if (lenSize < 4 && num >= (1L << (lenSize * 8))) { @@ -4284,18 +4227,18 @@ ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize) } switch (lenSize) { - case 4: - *p++ = (num >> 24) & 0xff; - case 3: - *p++ = (num >> 16) & 0xff; - case 2: - *p++ = (num >> 8) & 0xff; - case 1: - *p = num & 0xff; + case 4: + *p++ = (num >> 24) & 0xff; + case 3: + *p++ = (num >> 16) & 0xff; + case 2: + *p++ = (num >> 8) & 0xff; + case 1: + *p = num & 0xff; } SSL_TRC(60, ("%d: number:", SSL_GETPID())); rv = ssl3_AppendHandshake(ss, &b[0], lenSize); - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } SECStatus @@ -4304,18 +4247,18 @@ ssl3_AppendHandshakeVariable( { SECStatus rv; - PORT_Assert((bytes < (1<<8) && lenSize == 1) || - (bytes < (1L<<16) && lenSize == 2) || - (bytes < (1L<<24) && lenSize == 3)); + 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())); + SSL_TRC(60, ("%d: append variable:", SSL_GETPID())); rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } SSL_TRC(60, ("data:")); rv = ssl3_AppendHandshake(ss, src, bytes); - return rv; /* error code set by AppendHandshake, if applicable. */ + return rv; /* error code set by AppendHandshake, if applicable. */ } SECStatus @@ -4328,61 +4271,47 @@ ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length) * dtls_StageHandshakeMessage to mark the message boundary. */ if (IS_DTLS(ss)) { - rv = dtls_StageHandshakeMessage(ss); - if (rv != SECSuccess) { - return rv; - } + 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))); + 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. */ + 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. */ + 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++; + /* 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. */ - } + /* 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. */ - } + /* 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. */ -} - -/* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of - * |sigAndHash| to the current handshake message. */ -SECStatus -ssl3_AppendSignatureAndHashAlgorithm( - sslSocket *ss, const SSLSignatureAndHashAlg* sigAndHash) -{ - PRUint8 serialized[2]; - - serialized[0] = (PRUint8)sigAndHash->hashAlg; - serialized[1] = (PRUint8)sigAndHash->sigAlg; - - return ssl3_AppendHandshake(ss, serialized, sizeof(serialized)); + return rv; /* error code set by AppendHandshake, if applicable. */ } /************************************************************************** @@ -4402,17 +4331,17 @@ ssl3_AppendSignatureAndHashAlgorithm( */ SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, - PRUint32 *length) + PRUint32 *length) { - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if ((PRUint32)bytes > *length) { - return ssl3_DecodeError(ss); + return ssl3_DecodeError(ss); } PORT_Memcpy(v, *b, bytes); PRINT_BUF(60, (ss, "consume bytes:", *b, bytes)); - *b += bytes; + *b += bytes; *length -= bytes; return SECSuccess; } @@ -4430,24 +4359,24 @@ ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b, */ PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, - PRUint32 *length) + PRUint32 *length) { - PRUint8 *buf = *b; - int i; - PRInt32 num = 0; + PRUint8 *buf = *b; + int i; + PRInt32 num = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( bytes <= sizeof num); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(bytes <= sizeof num); if ((PRUint32)bytes > *length) { - return ssl3_DecodeError(ss); + 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; + num = (num << 8) + buf[i]; + *b += bytes; *length -= bytes; return num; } @@ -4461,134 +4390,236 @@ ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b, * 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 + * 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 + * 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, PRInt32 bytes, - SSL3Opaque **b, PRUint32 *length) + SSL3Opaque **b, PRUint32 *length) { - PRInt32 count; + PRInt32 count; PORT_Assert(bytes <= 3); - i->len = 0; + i->len = 0; i->data = NULL; i->type = siBuffer; count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length); - if (count < 0) { /* Can't test for SECSuccess here. */ - return SECFailure; + if (count < 0) { /* Can't test for SECSuccess here. */ + return SECFailure; } if (count > 0) { - if ((PRUint32)count > *length) { - return ssl3_DecodeError(ss); - } - i->data = *b; - i->len = count; - *b += count; - *length -= count; + if ((PRUint32)count > *length) { + return ssl3_DecodeError(ss); + } + i->data = *b; + i->len = count; + *b += count; + *length -= count; } return SECSuccess; } -/* tlsHashOIDMap contains the mapping between TLS hash identifiers and the - * SECOidTag used internally by NSS. */ -static const struct { - SSLHashType tlsHash; - SECOidTag oid; -} tlsHashOIDMap[] = { - { ssl_hash_sha1, SEC_OID_SHA1 }, - { ssl_hash_sha256, SEC_OID_SHA256 }, - { ssl_hash_sha384, SEC_OID_SHA384 }, - { ssl_hash_sha512, SEC_OID_SHA512 } -}; +/* Helper function to encode an unsigned integer into a buffer. */ +PRUint8 * +ssl_EncodeUintX(PRUint64 value, unsigned int bytes, PRUint8 *to) +{ + PRUint64 encoded; + + PORT_Assert(bytes > 0 && bytes <= sizeof(encoded)); + + encoded = PR_htonll(value); + memcpy(to, ((unsigned char *)(&encoded)) + (sizeof(encoded) - bytes), bytes); + return to + bytes; +} /* 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_TLSHashAlgorithmToOID(SSLHashType hashFunc) -{ - unsigned int i; - - for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) { - if (hashFunc == tlsHashOIDMap[i].tlsHash) { - return tlsHashOIDMap[i].oid; - } +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; } -/* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm - * identifier for a given KeyType. */ -static SECStatus -ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType, SSLSignType *out) -{ - switch (keyType) { - case rsaKey: - *out = ssl_sign_rsa; - return SECSuccess; - case dsaKey: - *out = ssl_sign_dsa; - return SECSuccess; - case ecKey: - *out = ssl_sign_ecdsa; - return SECSuccess; - default: - PORT_SetError(SEC_ERROR_INVALID_KEY); - return SECFailure; +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_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_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_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; +} + +KeyType +ssl_SignatureSchemeToKeyType(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: + case ssl_sig_rsa_pss_sha256: + case ssl_sig_rsa_pss_sha384: + case ssl_sig_rsa_pss_sha512: + case ssl_sig_rsa_pkcs1_sha1md5: + return rsaKey; + case ssl_sig_ecdsa_secp256r1_sha256: + case ssl_sig_ecdsa_secp384r1_sha384: + case ssl_sig_ecdsa_secp521r1_sha512: + case ssl_sig_ecdsa_sha1: + return ecKey; + case ssl_sig_dsa_sha256: + case ssl_sig_dsa_sha384: + case ssl_sig_dsa_sha512: + case ssl_sig_dsa_sha1: + return dsaKey; + case ssl_sig_none: + case ssl_sig_ed25519: + case ssl_sig_ed448: + break; + } + PORT_Assert(0); + return nullKey; } -/* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature - * algorithm identifier for the given certificate. */ -static SECStatus -ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert, - SSLSignType *out) +static SSLNamedGroup +ssl_NamedGroupForSignatureScheme(SSLSignatureScheme scheme) { - SECKEYPublicKey *key; - KeyType keyType; - - key = CERT_ExtractPublicKey(cert); - if (key == NULL) { - ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; + switch (scheme) { + case ssl_sig_ecdsa_secp256r1_sha256: + return ssl_grp_ec_secp256r1; + case ssl_sig_ecdsa_secp384r1_sha384: + return ssl_grp_ec_secp384r1; + case ssl_sig_ecdsa_secp521r1_sha512: + return ssl_grp_ec_secp521r1; + default: + break; } + PORT_Assert(0); + return 0; +} - keyType = key->keyType; - SECKEY_DestroyPublicKey(key); - return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out); +/* Validate that the signature scheme works for the given key. + * If |allowSha1| is set, we allow the use of SHA-1. + * If |matchGroup| is set, we also check that the group and hash match. */ +static PRBool +ssl_SignatureSchemeValidForKey(PRBool allowSha1, PRBool matchGroup, + KeyType keyType, + const sslNamedGroupDef *ecGroup, + SSLSignatureScheme scheme) +{ + if (!ssl_IsSupportedSignatureScheme(scheme)) { + return PR_FALSE; + } + if (keyType != ssl_SignatureSchemeToKeyType(scheme)) { + return PR_FALSE; + } + if (!allowSha1 && ssl_SignatureSchemeToHashType(scheme) == ssl_hash_sha1) { + return PR_FALSE; + } + if (keyType != ecKey) { + return PR_TRUE; + } + if (!ecGroup) { + return PR_FALSE; + } + /* If |allowSha1| is present and the scheme is ssl_sig_ecdsa_sha1, it's OK. + * This scheme isn't bound to a specific group. */ + if (allowSha1 && (scheme == ssl_sig_ecdsa_sha1)) { + return PR_TRUE; + } + if (!matchGroup) { + return PR_TRUE; + } + return ecGroup->name == ssl_NamedGroupForSignatureScheme(scheme); } -/* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature +/* ssl3_CheckSignatureSchemeConsistency checks that the signature * algorithm identifier in |sigAndHash| is consistent with the public key in * |cert|. 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 -ssl3_CheckSignatureAndHashAlgorithmConsistency( - sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash, - CERTCertificate* cert) +ssl_CheckSignatureSchemeConsistency( + sslSocket *ss, SSLSignatureScheme scheme, CERTCertificate *cert) { - SECStatus rv; - SSLSignType sigAlg; unsigned int i; + const sslNamedGroupDef *group = NULL; + SECKEYPublicKey *key; + KeyType keyType; + PRBool isTLS13 = ss->version == SSL_LIBRARY_VERSION_TLS_1_3; - rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg); - if (rv != SECSuccess) { - return rv; + key = CERT_ExtractPublicKey(cert); + if (key == NULL) { + ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); + return SECFailure; + } + + keyType = SECKEY_GetPublicKeyType(key); + if (keyType == ecKey) { + group = ssl_ECPubKey2NamedGroup(key); + } + SECKEY_DestroyPublicKey(key); + + /* If we're a client, check that the signature algorithm matches the signing + * key type of the cipher suite. */ + if (!isTLS13 && + !ss->sec.isServer && + ss->ssl3.hs.kea_def->signKeyType != keyType) { + PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); + return SECFailure; } - if (sigAlg != sigAndHash->sigAlg) { + + /* Verify that the signature scheme matches the signing key. */ + if (!ssl_SignatureSchemeValidForKey(!isTLS13 /* allowSha1 */, + isTLS13 /* matchGroup */, + keyType, group, scheme)) { PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM); return SECFailure; } - for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { - const SSLSignatureAndHashAlg *alg = &ss->ssl3.signatureAlgorithms[i]; - if (sigAndHash->sigAlg == alg->sigAlg && - sigAndHash->hashAlg == alg->hashAlg) { + for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { + if (scheme == ss->ssl3.signatureSchemes[i]) { return SECSuccess; } } @@ -4597,69 +4628,70 @@ ssl3_CheckSignatureAndHashAlgorithmConsistency( } PRBool -ssl3_IsSupportedSignatureAlgorithm(const SSLSignatureAndHashAlg *alg) -{ - static const SSLHashType supportedHashes[] = { - ssl_hash_sha1, - ssl_hash_sha256, - ssl_hash_sha384, - ssl_hash_sha512 - }; - - static const SSLSignType supportedSigAlgs[] = { - ssl_sign_rsa, -#ifndef NSS_DISABLE_ECC - ssl_sign_ecdsa, -#endif - ssl_sign_dsa - }; - - unsigned int i; - PRBool hashOK = PR_FALSE; - PRBool signOK = PR_FALSE; +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_sha256: + case ssl_sig_rsa_pss_sha384: + case ssl_sig_rsa_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 PR_TRUE; + + case ssl_sig_rsa_pkcs1_sha1md5: + case ssl_sig_none: + case ssl_sig_ed25519: + case ssl_sig_ed448: + return PR_FALSE; + } + return PR_FALSE; +} - for (i = 0; i < PR_ARRAY_SIZE(supportedHashes); ++i) { - if (alg->hashAlg == supportedHashes[i]) { - hashOK = PR_TRUE; - break; - } - } +PRBool +ssl_IsRsaPssSignatureScheme(SSLSignatureScheme scheme) +{ + switch (scheme) { + case ssl_sig_rsa_pss_sha256: + case ssl_sig_rsa_pss_sha384: + case ssl_sig_rsa_pss_sha512: + return PR_TRUE; - for (i = 0; i < PR_ARRAY_SIZE(supportedSigAlgs); ++i) { - if (alg->sigAlg == supportedSigAlgs[i]) { - signOK = PR_TRUE; - break; - } + default: + return PR_FALSE; } - - return hashOK && signOK; + return PR_FALSE; } -/* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm - * structure from |b| and puts the resulting value into |out|. |b| and |length| - * are updated accordingly. +/* 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 -ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, - SSL3Opaque **b, - PRUint32 *length, - SSLSignatureAndHashAlg *out) +ssl_ConsumeSignatureScheme(sslSocket *ss, SSL3Opaque **b, + PRUint32 *length, SSLSignatureScheme *out) { - PRUint8 bytes[2]; - SECStatus rv; + PRInt32 tmp; - rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length); - if (rv != SECSuccess) { - return rv; + tmp = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); + if (tmp < 0) { + return SECFailure; /* Error code set already. */ } - - out->hashAlg = (SSLHashType)bytes[0]; - out->sigAlg = (SSLSignType)bytes[1]; - if (!ssl3_IsSupportedSignatureAlgorithm(out)) { + if (!ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) { PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); return SECFailure; } + *out = (SSLSignatureScheme)tmp; return SECSuccess; } @@ -4667,6 +4699,32 @@ ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, * 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 @@ -4674,21 +4732,21 @@ ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss, * * 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.) + * (There is presently no way to assert on a Read lock.) */ -static 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; - SSL3Opaque md5_inner[MAX_MAC_LENGTH]; - SSL3Opaque sha_inner[MAX_MAC_LENGTH]; - - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); +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; + SSL3Opaque md5_inner[MAX_MAC_LENGTH]; + SSL3Opaque 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; @@ -4696,406 +4754,288 @@ ssl3_ComputeHandshakeHashes(sslSocket * ss, hashes->hashAlg = ssl_hash_none; -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11 && - ss->ssl3.hs.hashType == handshake_hash_single) { - /* compute them without PKCS11 */ - PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; - - ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx); - ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len, - sizeof(hashes->u.raw)); - - PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len)); + 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); + 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; + } - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - hashes->hashAlg = ssl_hash_sha256; - rv = SECSuccess; - } else if (ss->opt.bypassPKCS11) { - /* compute them without PKCS11 */ - PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; - PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; + hashes->hashAlg = ssl3_GetSuitePrfHash(ss); + rv = SECSuccess; -#define md5cx ((MD5Context *)md5_cx) -#define shacx ((SHA1Context *)sha_cx) + 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]; + + md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, + sizeof md5StackBuf, &md5StateLen); + if (md5StateBuf == NULL) { + ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); + goto loser; + } + md5 = ss->ssl3.hs.md5; - MD5_Clone (md5cx, (MD5Context *)ss->ssl3.hs.md5_cx); - SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx); + shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf, + sizeof shaStackBuf, &shaStateLen); + if (shaStateBuf == NULL) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + goto loser; + } + sha = ss->ssl3.hs.sha; - if (!isTLS) { - /* compute hashes for SSL3. */ - unsigned char s[4]; + if (!isTLS) { + /* compute hashes for SSL3. */ + unsigned char s[4]; - if (!spec->msItem.data) { + if (!spec->master_secret) { PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); - return SECFailure; + 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; + 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) { - MD5_Update(md5cx, s, 4); - PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4)); - } + 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, - mac_defs[mac_md5].pad_size)); + PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1, + mac_defs[mac_md5].pad_size)); - MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); - MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size); - MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH); + rv |= PK11_DigestKey(md5, spec->master_secret); + rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); + 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)); + PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength)); - if (sender != 0) { - SHA1_Update(shacx, s, 4); - PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4)); - } + 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, - mac_defs[mac_sha].pad_size)); + PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1, + mac_defs[mac_sha].pad_size)); - SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); - SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size); - SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH); + rv |= PK11_DigestKey(sha, spec->master_secret); + rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); + 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, - mac_defs[mac_md5].pad_size)); - PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); + PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength)); - MD5_Begin(md5cx); - MD5_Update(md5cx, spec->msItem.data, spec->msItem.len); - MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size); - MD5_Update(md5cx, md5_inner, MD5_LENGTH); - } - MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH); + PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2, + mac_defs[mac_md5].pad_size)); + PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); - PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); + rv |= PK11_DigestBegin(md5); + rv |= PK11_DigestKey(md5, spec->master_secret); + rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); + 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; + } - if (!isTLS) { - PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, - mac_defs[mac_sha].pad_size)); - PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); + PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH)); - SHA1_Begin(shacx); - SHA1_Update(shacx, spec->msItem.data, spec->msItem.len); - SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size); - SHA1_Update(shacx, sha_inner, SHA1_LENGTH); - } - SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH); + if (!isTLS) { + PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2, + mac_defs[mac_sha].pad_size)); + PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); - PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); + rv |= PK11_DigestBegin(sha); + rv |= PK11_DigestKey(sha, spec->master_secret); + rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); + 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; + } - hashes->len = MD5_LENGTH + SHA1_LENGTH; - rv = SECSuccess; -#undef md5cx -#undef shacx - } else -#endif - if (ss->ssl3.hs.hashType == handshake_hash_single) { - /* compute hashes with PKCS11 */ - 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); - 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; - } - /* If we ever support ciphersuites where the PRF hash isn't SHA-256 - * then this will need to be updated. */ - hashes->hashAlg = ssl_hash_sha256; - rv = SECSuccess; - -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 { - /* compute hashes with PKCS11 */ - 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]; - - md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf, - sizeof md5StackBuf, &md5StateLen); - if (md5StateBuf == NULL) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - 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); - goto loser; - } - sha = ss->ssl3.hs.sha; - - if (!isTLS) { - /* compute hashes for SSL3. */ - unsigned char s[4]; + PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH)); - if (!spec->master_secret) { - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE); - return SECFailure; - } - - 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, - mac_defs[mac_md5].pad_size)); - - rv |= PK11_DigestKey(md5,spec->master_secret); - rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size); - 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, - mac_defs[mac_sha].pad_size)); - - rv |= PK11_DigestKey(sha, spec->master_secret); - rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size); - 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, - mac_defs[mac_md5].pad_size)); - PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH)); - - rv |= PK11_DigestBegin(md5); - rv |= PK11_DigestKey(md5, spec->master_secret); - rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size); - 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, - mac_defs[mac_sha].pad_size)); - PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH)); - - rv |= PK11_DigestBegin(sha); - rv |= PK11_DigestKey(sha,spec->master_secret); - rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size); - 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; - rv = SECSuccess; + hashes->len = MD5_LENGTH + SHA1_LENGTH; + rv = SECSuccess; 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); - } - } + 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; } -static SECStatus -ssl3_ComputeBackupHandshakeHashes(sslSocket * ss, - SSL3Hashes * hashes) /* output goes here. */ -{ - SECStatus rv = SECSuccess; +/************************************************************************** + * end of Handshake Hash functions. + * Begin Send and Handle functions for handshakes. + **************************************************************************/ - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( !ss->sec.isServer ); - PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single ); +#ifdef TRACE +#define CHTYPE(t) \ + case client_hello_##t: \ + return #t; - rv = PK11_DigestFinal(ss->ssl3.hs.backupHash, hashes->u.raw, &hashes->len, - sizeof(hashes->u.raw)); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); - rv = SECFailure; - goto loser; +static const char * +ssl_ClientHelloTypeName(sslClientHelloType type) +{ + switch (type) { + CHTYPE(initial); + CHTYPE(retry); + CHTYPE(retransmit); /* DTLS only */ + CHTYPE(renegotiation); /* TLS <= 1.2 only */ } - hashes->hashAlg = ssl_hash_sha1; - -loser: - PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); - ss->ssl3.hs.backupHash = NULL; - return rv; + PORT_Assert(0); + return NULL; } +#undef CHTYPE +#endif -/* - * SSL 2 based implementations pass in the initial outbound buffer - * so that the handshake hash can contain the included information. +/* Called from ssl3_HandleHelloRequest(), + * ssl3_RedoHandshake() + * ssl_BeginClientHandshake (when resuming ssl3 session) + * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) * - * Called from ssl2_BeginClientHandshake() in sslcon.c + * 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_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length) +ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type) { + sslSessionID *sid; + ssl3CipherSpec *cwSpec; SECStatus rv; + int i; + int length; + int num_suites; + int actual_count = 0; + PRBool isTLS = PR_FALSE; + PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; + PRInt32 total_exten_len = 0; + unsigned paddingExtensionLen; + unsigned numCompressionMethods; + PRUint16 version; + PRInt32 flags; + + SSL_TRC(3, ("%d: SSL3[%d]: send %s ClientHello handshake", SSL_GETPID(), + ss->fd, ssl_ClientHelloTypeName(type))); - ssl_GetSSL3HandshakeLock(ss); /**************************************/ + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - rv = ssl3_InitState(ss); - if (rv != SECSuccess) { - goto done; /* ssl3_InitState has set the error code. */ - } - rv = ssl3_RestartHandshakeHashes(ss); - if (rv != SECSuccess) { - goto done; + /* 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; } - PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH); - PORT_Memcpy( - &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES], - &ss->sec.ci.clientChallenge, - SSL_CHALLENGE_BYTES); - - rv = ssl3_UpdateHandshakeHashes(ss, buf, length); - /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */ - -done: - ssl_ReleaseSSL3HandshakeLock(ss); /**************************************/ - return rv; -} - -/************************************************************************** - * end of Handshake Hash functions. - * Begin Send and Handle functions for handshakes. - **************************************************************************/ - -/* Called from ssl3_HandleHelloRequest(), - * ssl3_RedoHandshake() - * ssl2_BeginClientHandshake (when resuming ssl3 session) - * dtls_HandleHelloVerifyRequest(with resending=PR_TRUE) - */ -SECStatus -ssl3_SendClientHello(sslSocket *ss, PRBool resending) -{ - sslSessionID * sid; - ssl3CipherSpec * cwSpec; - SECStatus rv; - int i; - int length; - int num_suites; - int actual_count = 0; - PRBool isTLS = PR_FALSE; - PRBool requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE; - PRInt32 total_exten_len = 0; - unsigned paddingExtensionLen; - unsigned numCompressionMethods; - PRInt32 flags; - - SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(), - ss->fd)); - - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + /* If we are responding to a HelloRetryRequest, don't reinitialize. We need + * to maintain the handshake hashes. */ + if (ss->ssl3.hs.helloRetry) { + PORT_Assert(type == client_hello_retry); + } else { + rv = ssl3_InitState(ss); + if (rv != SECSuccess) { + return rv; /* ssl3_InitState has set the error code. */ + } - rv = ssl3_InitState(ss); - if (rv != SECSuccess) { - return rv; /* ssl3_InitState has set the error code. */ + rv = ssl3_RestartHandshakeHashes(ss); + if (rv != SECSuccess) { + return rv; + } } + /* These must be reset every handshake. */ ss->ssl3.hs.sendingSCSV = PR_FALSE; ss->ssl3.hs.preliminaryInfo = 0; - PORT_Assert(IS_DTLS(ss) || !resending); - + PORT_Assert(IS_DTLS(ss) || type != client_hello_retransmit); SECITEM_FreeItem(&ss->ssl3.hs.newSessionTicket.ticket, PR_FALSE); ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; + ssl3_ResetExtensionData(&ss->xtnData); - /* We might be starting a session renegotiation in which case we should - * clear previous state. - */ - PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); - - rv = ssl3_RestartHandshakeHashes(ss); - if (rv != SECSuccess) { - return rv; + /* How many suites does our PKCS11 support (regardless of policy)? */ + num_suites = ssl3_config_match_init(ss); + if (!num_suites) { + return SECFailure; /* ssl3_config_match_init has set error code. */ } /* @@ -5103,25 +5043,26 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) * work around a Windows SChannel bug. Ensure that it is still enabled. */ if (ss->firstHsDone) { - if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PORT_SetError(SSL_ERROR_SSL_DISABLED); - return SECFailure; - } + 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; - } + if (ss->clientHelloVersion < ss->vrange.min || + ss->clientHelloVersion > ss->vrange.max) { + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; + } } /* 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 ssl2_BeginClientHandshake, then + * XXX If we've been called from ssl_BeginClientHandshake, then * this lookup is duplicative and wasteful. */ sid = (ss->opt.noCache) ? NULL - : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url); + : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url); /* We can't resume based on a different token. If the sid exists, * make sure the token that holds the master secret still exists ... @@ -5129,161 +5070,152 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) * the private key still exists, is logged in, hasn't been removed, etc. */ if (sid) { - PRBool sidOK = PR_TRUE; - if (sid->u.ssl3.keys.msIsWrapped) { - /* Session key was wrapped, which means it was using PKCS11, */ - PK11SlotInfo *slot = NULL; - if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) { - 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 ss->version based on the session cache */ - 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) { - ss->version = ss->clientHelloVersion; - } else { - sidOK = PR_FALSE; - } - } else { + PRBool sidOK = PR_TRUE; + const ssl3CipherSuiteCfg *suite; + + /* Check that the cipher suite we need is enabled. */ + suite = ssl_LookupCipherSuiteCfg(sid->u.ssl3.cipherSuite, + ss->cipherSuites); + PORT_Assert(suite); + if (!suite || !config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { + sidOK = PR_FALSE; + } + + /* Check that we can recover the master secret. */ + if (sidOK && sid->u.ssl3.keys.msIsWrapped) { + 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 || + if (sid->version < ss->vrange.min || sid->version > ss->vrange.max) { - sidOK = PR_FALSE; - } else { - rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, - PR_TRUE); - if (rv != SECSuccess) { - return rv; /* error code was set */ - } - } - } - } + sidOK = PR_FALSE; + } else { + version = ss->vrange.max; + } + } + } - if (!sidOK) { - SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok ); - if (ss->sec.uncache) - (*ss->sec.uncache)(sid); - ssl_FreeSID(sid); - sid = NULL; - } + if (!sidOK) { + SSL_AtomicIncrementLong(&ssl3stats.sch_sid_cache_not_ok); + ss->sec.uncache(sid); + ssl_FreeSID(sid); + sid = NULL; + } } if (sid) { - requestingResume = PR_TRUE; - SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits ); + 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)); + PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID, + sid->u.ssl3.sessionIDLength)); - ss->ssl3.policy = sid->u.ssl3.policy; + 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) { - ss->version = ss->clientHelloVersion; - } else { - rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, - PR_TRUE); - if (rv != SECSuccess) - return rv; /* error code was set */ - } - - sid = ssl3_NewSessionID(ss, PR_FALSE); - if (!sid) { - return SECFailure; /* memory error is set */ + 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; + } else { + version = ss->vrange.max; + } + + 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 = (ss->version > SSL_LIBRARY_VERSION_3_0); + isTLS = (version > SSL_LIBRARY_VERSION_3_0); ssl_GetSpecWriteLock(ss); cwSpec = ss->ssl3.cwSpec; if (cwSpec->mac_def->mac == mac_null) { - /* SSL records are not being MACed. */ - cwSpec->version = ss->version; + /* SSL records are not being MACed. */ + cwSpec->version = version; } ssl_ReleaseSpecWriteLock(ss); if (ss->sec.ci.sid != NULL) { - ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ + ssl_FreeSID(ss->sec.ci.sid); /* decrement ref count, free if zero */ } ss->sec.ci.sid = sid; - ss->sec.send = ssl3_SendApplicationData; - - /* shouldn't get here if SSL3 is disabled, but ... */ - if (SSL3_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; - } - - /* how many suites does our PKCS11 support (regardless of policy)? */ - num_suites = ssl3_config_match_init(ss); - if (!num_suites) - return SECFailure; /* ssl3_config_match_init has set error code. */ - /* 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; + /* 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 @@ -5297,62 +5229,68 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) PR_RWLock_Rlock(sid->u.ssl3.lock); } + if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3 && + type == client_hello_initial) { + rv = tls13_SetupClientHello(ss); + if (rv != SECSuccess) { + return SECFailure; + } + } if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) { - PRUint32 maxBytes = 65535; /* 2^16 - 1 */ - PRInt32 extLen; + PRUint32 maxBytes = 65535; /* 2^16 - 1 */ + PRInt32 extLen; - extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); - if (extLen < 0) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; - } - total_exten_len += extLen; - - if (total_exten_len > 0) - total_exten_len += 2; - } + extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL); + if (extLen < 0) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; + } + total_exten_len += extLen; -#ifndef NSS_DISABLE_ECC - if (!total_exten_len || !isTLS) { - /* not sending the elliptic_curves and ec_point_formats extensions */ - ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ + if (total_exten_len > 0) + total_exten_len += 2; } -#endif /* NSS_DISABLE_ECC */ if (IS_DTLS(ss)) { - ssl3_DisableNonDTLSSuites(ss); + ssl3_DisableNonDTLSSuites(ss); } /* how many suites are permitted by policy and user preference? */ - num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE); + num_suites = count_cipher_suites(ss, ss->ssl3.policy); if (!num_suites) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; /* count_cipher_suites has set error code. */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; /* count_cipher_suites has set error code. */ } fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume || - ss->version < sid->version); + version < sid->version); /* make room for SCSV */ if (ss->ssl3.hs.sendingSCSV) { - ++num_suites; + ++num_suites; } if (fallbackSCSV) { - ++num_suites; + ++num_suites; } /* count compression methods */ numCompressionMethods = 0; - for (i = 0; i < compressionMethodsCount; i++) { - if (compressionEnabled(ss, compressions[i])) - numCompressionMethods++; + for (i = 0; i < ssl_compression_method_count; i++) { + if (ssl_CompressionEnabled(ss, ssl_compression_methods[i])) + numCompressionMethods++; } length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + - 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) + - 2 + num_suites*sizeof(ssl3CipherSuite) + - 1 + numCompressionMethods + total_exten_len; + 1 + (sid->version >= SSL_LIBRARY_VERSION_TLS_1_3 + ? 0 + : sid->u.ssl3.sessionIDLength) + + 2 + num_suites * sizeof(ssl3CipherSuite) + + 1 + numCompressionMethods + total_exten_len; if (IS_DTLS(ss)) { - length += 1 + ss->ssl3.hs.cookieLen; + length += 1 + ss->ssl3.hs.cookie.len; } /* A padding extension may be included to ensure that the record containing @@ -5360,8 +5298,9 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) * (inclusive). Initial, ClientHello records with such lengths trigger bugs * in F5 devices. * - * This is not done for DTLS nor for renegotiation. */ - if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) { + * This is not done for DTLS, for renegotiation, or when there are no + * extensions. */ + if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone && total_exten_len) { paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length); total_exten_len += paddingExtensionLen; length += paddingExtensionLen; @@ -5371,157 +5310,192 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) rv = ssl3_AppendHandshakeHeader(ss, client_hello, length); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (ss->firstHsDone) { - /* The client hello version must stay unchanged to work around - * the Windows SChannel bug described above. */ - PORT_Assert(ss->version == ss->clientHelloVersion); + /* The client hello version must stay unchanged to work around + * the Windows SChannel bug described above. */ + PORT_Assert(version == ss->clientHelloVersion); } - ss->clientHelloVersion = ss->version; + ss->clientHelloVersion = PR_MIN(version, SSL_LIBRARY_VERSION_TLS_1_2); if (IS_DTLS(ss)) { - PRUint16 version; + PRUint16 dtlsVersion; - version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); - rv = ssl3_AppendHandshakeNumber(ss, version, 2); + dtlsVersion = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); + rv = ssl3_AppendHandshakeNumber(ss, dtlsVersion, 2); } else { - rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); + rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2); } if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } - if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */ - rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by GetNewRandom. */ - } + /* Generate a new random if this is the first attempt. */ + if (type == client_hello_initial) { + rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by GetNewRandom. */ + } } rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } - if (sid) - rv = ssl3_AppendHandshakeVariable( - ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); + if (sid->version < SSL_LIBRARY_VERSION_TLS_1_3) + rv = ssl3_AppendHandshakeVariable( + ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); else - rv = ssl3_AppendHandshakeNumber(ss, 0, 1); + rv = ssl3_AppendHandshakeNumber(ss, 0, 1); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (IS_DTLS(ss)) { - rv = ssl3_AppendHandshakeVariable( - ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } + rv = ssl3_AppendHandshakeVariable( + ss, ss->ssl3.hs.cookie.data, ss->ssl3.hs.cookie.len, 1); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } } - rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2); + rv = ssl3_AppendHandshakeNumber(ss, num_suites * sizeof(ssl3CipherSuite), 2); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } if (ss->ssl3.hs.sendingSCSV) { - /* Add the actual SCSV */ - rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } - actual_count++; + /* Add the actual SCSV */ + rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } + actual_count++; } if (fallbackSCSV) { - rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } - actual_count++; + rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } + actual_count++; } for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange, ss)) { - actual_count++; - if (actual_count > num_suites) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - /* set error card removal/insertion error */ - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; - } - rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } - } + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; + if (config_match(suite, ss->ssl3.policy, &ss->vrange, ss)) { + actual_count++; + if (actual_count > num_suites) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + /* set error card removal/insertion error */ + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; + } + rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } + } } /* if cards were removed or inserted between count_cipher_suites and * generating our list, detect the error here rather than send it off to * the server.. */ if (actual_count != num_suites) { - /* Card removal/insertion error */ - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; + /* Card removal/insertion error */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; } rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1); if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ } - for (i = 0; i < compressionMethodsCount; i++) { - if (!compressionEnabled(ss, compressions[i])) - continue; - rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by ssl3_AppendHandshake* */ - } + for (i = 0; i < ssl_compression_method_count; i++) { + if (!ssl_CompressionEnabled(ss, ssl_compression_methods[i])) + continue; + rv = ssl3_AppendHandshakeNumber(ss, ssl_compression_methods[i], 1); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by ssl3_AppendHandshake* */ + } } if (total_exten_len) { - PRUint32 maxBytes = total_exten_len - 2; - PRInt32 extLen; - - rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); - if (rv != SECSuccess) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return rv; /* err set by AppendHandshake. */ - } - - extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); - if (extLen < 0) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; - } - maxBytes -= extLen; - - extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); - if (extLen < 0) { - if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); } - return SECFailure; - } - maxBytes -= extLen; - - PORT_Assert(!maxBytes); - } + PRUint32 maxBytes = total_exten_len - 2; + PRInt32 extLen; + + rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2); + if (rv != SECSuccess) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return rv; /* err set by AppendHandshake. */ + } + + extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes); + if (extLen < 0) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; + } + maxBytes -= extLen; + + extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL); + if (extLen < 0) { + if (sid->u.ssl3.lock) { + PR_RWLock_Unlock(sid->u.ssl3.lock); + } + return SECFailure; + } + maxBytes -= extLen; + + PORT_Assert(!maxBytes); + } if (sid->u.ssl3.lock) { PR_RWLock_Unlock(sid->u.ssl3.lock); @@ -5532,68 +5506,74 @@ ssl3_SendClientHello(sslSocket *ss, PRBool resending) } 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; + /* 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; if (!ss->firstHsDone && !IS_DTLS(ss)) { - flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; + flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION; } rv = ssl3_FlushHandshake(ss, flags); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + 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; - return rv; + return SECSuccess; } - -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 Hello Request. +/* 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; + SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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; + 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; + (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; + (void)SSL3_SendAlert(ss, alert_warning, no_renegotiation); + PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); + return SECFailure; } if (sid) { - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - ss->sec.ci.sid = NULL; + ss->sec.uncache(sid); + ssl_FreeSID(sid); + ss->sec.ci.sid = NULL; } if (IS_DTLS(ss)) { - dtls_RehandshakeCleanup(ss); + dtls_RehandshakeCleanup(ss); } ssl_GetXmitBufLock(ss); - rv = ssl3_SendClientHello(ss, PR_FALSE); + rv = ssl3_SendClientHello(ss, client_hello_renegotiation); ssl_ReleaseXmitBufLock(ss); return rv; @@ -5626,7 +5606,7 @@ ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) const CK_MECHANISM_TYPE *pMech = wrapMechanismList; while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) { - ++pMech; + ++pMech; } return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1 : (pMech - wrapMechanismList); @@ -5634,116 +5614,118 @@ ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech) static PK11SymKey * ssl_UnwrapSymWrappingKey( - SSLWrappedSymWrappingKey *pWswk, - SECKEYPrivateKey * svrPrivKey, - SSL3KEAType exchKeyType, - CK_MECHANISM_TYPE masterWrapMech, - void * pwArg) -{ - PK11SymKey * unwrappedWrappingKey = NULL; - SECItem wrappedKey; -#ifndef NSS_DISABLE_ECC - PK11SymKey * Ks; - SECKEYPublicKey pubWrapKey; - ECCWrappedKeyInfo *ecWrapped; -#endif /* NSS_DISABLE_ECC */ + SSLWrappedSymWrappingKey *pWswk, + SECKEYPrivateKey *svrPrivKey, + SSLAuthType authType, + 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->exchKeyType == exchKeyType); + PORT_Assert(pWswk->authType == authType); if (pWswk->symWrapMechanism != masterWrapMech || - pWswk->exchKeyType != exchKeyType) { - goto loser; + pWswk->authType != authType) { + goto loser; } wrappedKey.type = siBuffer; wrappedKey.data = pWswk->wrappedSymmetricWrappingkey; - wrappedKey.len = pWswk->wrappedSymKeyLen; + wrappedKey.len = pWswk->wrappedSymKeyLen; PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey); - switch (exchKeyType) { - - case kt_rsa: - unwrappedWrappingKey = - PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, - masterWrapMech, CKA_UNWRAP, 0); - break; - -#ifndef NSS_DISABLE_ECC - case kt_ecdh: - /* - * For kt_ecdh, 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; + switch (authType) { - PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen + - ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN); + case ssl_auth_rsa_decrypt: + case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */ + unwrappedWrappingKey = + PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, + masterWrapMech, CKA_UNWRAP, 0); + break; - if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen + - ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto loser; - } + 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; - } + 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; -#endif + /* Use Ks to unwrap the wrapping key */ + unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL, + &wrappedKey, masterWrapMech, + CKA_UNWRAP, 0); + PK11_FreeSymKey(Ks); - default: - /* Assert? */ - SET_ERROR_CODE - goto loser; + break; + + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + goto loser; } loser: return unwrappedWrappingKey; } -/* 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 KEA type. These Symkeys +/* 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. */ typedef struct { - PK11SymKey * symWrapKey[kt_kea_size]; + PK11SymKey *symWrapKey[ssl_auth_size]; } ssl3SymWrapKey; -static PZLock * symWrapKeysLock = NULL; -static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; +static PZLock *symWrapKeysLock = NULL; +static ssl3SymWrapKey symWrapKeys[SSL_NUM_WRAP_MECHS]; -SECStatus ssl_FreeSymWrapKeysLock(void) +SECStatus +ssl_FreeSymWrapKeysLock(void) { if (symWrapKeysLock) { PZ_DestroyLock(symWrapKeysLock); @@ -5757,21 +5739,21 @@ SECStatus ssl_FreeSymWrapKeysLock(void) SECStatus SSL3_ShutdownServerCache(void) { - int i, j; + int i, j; if (!symWrapKeysLock) - return SECSuccess; /* lock was never initialized */ + 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 < kt_kea_size; ++j) { - PK11SymKey ** pSymWrapKey; - pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; - if (*pSymWrapKey) { - PK11_FreeSymKey(*pSymWrapKey); - *pSymWrapKey = NULL; - } - } + for (j = 0; j < ssl_auth_size; ++j) { + PK11SymKey **pSymWrapKey; + pSymWrapKey = &symWrapKeys[i].symWrapKey[j]; + if (*pSymWrapKey) { + PK11_FreeSymKey(*pSymWrapKey); + *pSymWrapKey = NULL; + } + } } PZ_Unlock(symWrapKeysLock); @@ -5779,7 +5761,8 @@ SSL3_ShutdownServerCache(void) return SECSuccess; } -SECStatus ssl_InitSymWrapKeysLock(void) +SECStatus +ssl_InitSymWrapKeysLock(void) { symWrapKeysLock = PZ_NewLock(nssILockOther); return symWrapKeysLock ? SECSuccess : SECFailure; @@ -5789,43 +5772,53 @@ SECStatus ssl_InitSymWrapKeysLock(void) * 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. */ -static PK11SymKey * -getWrappingKey( sslSocket * ss, - PK11SlotInfo * masterSecretSlot, - SSL3KEAType exchKeyType, - CK_MECHANISM_TYPE masterWrapMech, - void * pwArg) -{ - SECKEYPrivateKey * svrPrivKey; - SECKEYPublicKey * svrPubKey = NULL; - PK11SymKey * unwrappedWrappingKey = NULL; - PK11SymKey ** pSymWrapKey; - CK_MECHANISM_TYPE asymWrapMechanism = CKM_INVALID_MECHANISM; - int length; - int symWrapMechIndex; - SECStatus rv; - SECItem wrappedKey; +PK11SymKey * +ssl3_GetWrappingKey(sslSocket *ss, + PK11SlotInfo *masterSecretSlot, + const sslServerCert *serverCert, + 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; + int symWrapMechIndex; + SECStatus rv; + SECItem wrappedKey; SSLWrappedSymWrappingKey wswk; -#ifndef NSS_DISABLE_ECC - PK11SymKey * Ks = NULL; - SECKEYPublicKey *pubWrapKey = NULL; - SECKEYPrivateKey *privWrapKey = NULL; + PK11SymKey *Ks = NULL; + SECKEYPublicKey *pubWrapKey = NULL; + SECKEYPrivateKey *privWrapKey = NULL; ECCWrappedKeyInfo *ecWrapped; -#endif /* NSS_DISABLE_ECC */ - svrPrivKey = ss->serverCerts[exchKeyType].SERVERKEY; - PORT_Assert(svrPrivKey != NULL); - if (!svrPrivKey) { - return NULL; /* why are we here?!? */ + 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 */ } + authType = serverCert->certType.authType; + svrPrivKey = serverCert->serverKeyPair->privKey; symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech); PORT_Assert(symWrapMechIndex >= 0); if (symWrapMechIndex < 0) - return NULL; /* invalid masterWrapMech. */ + return NULL; /* invalid masterWrapMech. */ - pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType]; + pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[authType]; ssl_InitSessionCacheLocks(PR_TRUE); @@ -5833,29 +5826,29 @@ getWrappingKey( sslSocket * ss, 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; + 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. */ - if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) { - /* found the wrapped sym wrapping key on disk. */ - unwrappedWrappingKey = - ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType, + if (ssl_GetWrappingKey(symWrapMechIndex, authType, &wswk)) { + /* found the wrapped sym wrapping key on disk. */ + unwrappedWrappingKey = + ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, authType, masterWrapMech, pwArg); - if (unwrappedWrappingKey) { - goto install; - } + if (unwrappedWrappingKey) { + goto install; + } } - if (!masterSecretSlot) /* caller doesn't want to create a new one. */ - goto loser; + 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. @@ -5864,163 +5857,163 @@ getWrappingKey( sslSocket * ss, unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL, length, pwArg); if (!unwrappedWrappingKey) { - goto loser; + 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. */ + PORT_Memset(&wswk, 0, sizeof wswk); /* eliminate UMRs. */ - if (ss->serverCerts[exchKeyType].serverKeyPair) { - svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey; - } - if (svrPubKey == NULL) { - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - goto loser; - } + svrPubKey = serverCert->serverKeyPair->pubKey; wrappedKey.type = siBuffer; - wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); + wrappedKey.len = SECKEY_PublicKeyStrength(svrPubKey); wrappedKey.data = wswk.wrappedSymmetricWrappingkey; PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey); if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey) - goto loser; + goto loser; /* wrap symmetric wrapping key in server's public key. */ - switch (exchKeyType) { - case kt_rsa: - asymWrapMechanism = CKM_RSA_PKCS; - rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey, - unwrappedWrappingKey, &wrappedKey); - break; - -#ifndef NSS_DISABLE_ECC - case kt_ecdh: - /* - * 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(svrPubKey->keyType == ecKey); - if (svrPubKey->keyType != 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; -#endif /* NSS_DISABLE_ECC */ - - default: - rv = SECFailure; - break; + switch (authType) { + case ssl_auth_rsa_decrypt: + case ssl_auth_rsa_sign: /* bad: see Bug 1248320 */ + 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; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM); - wswk.symWrapMechanism = masterWrapMech; - wswk.symWrapMechIndex = symWrapMechIndex; + wswk.symWrapMechanism = masterWrapMech; + wswk.symWrapMechIndex = symWrapMechIndex; wswk.asymWrapMechanism = asymWrapMechanism; - wswk.exchKeyType = exchKeyType; - wswk.wrappedSymKeyLen = wrappedKey.len; + wswk.authType = authType; + 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 + /* 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. */ if (ssl_SetWrappingKey(&wswk)) { - /* 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, exchKeyType, + /* 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, authType, masterWrapMech, pwArg); } install: if (unwrappedWrappingKey) { - *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); + *pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey); } loser: @@ -6029,6 +6022,7 @@ done: return unwrappedWrappingKey; } +#ifdef NSS_ALLOW_SSLKEYLOGFILE /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2| * bytes to |out|. */ static void @@ -6038,23 +6032,23 @@ hexEncode(char *out, const unsigned char *in, unsigned int length) unsigned int i; for (i = 0; i < length; i++) { - *(out++) = hextable[in[i] >> 4]; - *(out++) = hextable[in[i] & 15]; + *(out++) = hextable[in[i] >> 4]; + *(out++) = hextable[in[i] & 15]; } } +#endif /* Called from ssl3_SendClientKeyExchange(). */ -/* Presently, this always uses PKCS11. There is no bypass for this. */ static SECStatus -sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) +ssl3_SendRSAClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) { - PK11SymKey * pms = NULL; - SECStatus rv = SECFailure; - SECItem enc_pms = {siBuffer, NULL, 0}; - PRBool isTLS; + 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)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); /* Generate the pre-master secret ... */ ssl_GetSpecWriteLock(ss); @@ -6063,68 +6057,71 @@ sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL); ssl_ReleaseSpecWriteLock(ss); if (pms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } /* Get the wrapped (encrypted) pre-master secret, enc_pms */ - enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); - enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len); + enc_pms.len = SECKEY_PublicKeyStrength(svrPubKey); + enc_pms.data = (unsigned char *)PORT_Alloc(enc_pms.len); if (enc_pms.data == NULL) { - goto loser; /* err set by PORT_Alloc */ + 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; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } +#ifdef NSS_ALLOW_SSLKEYLOGFILE if (ssl_keylog_iob) { - SECStatus extractRV = PK11_ExtractKeyValue(pms); - if (extractRV == SECSuccess) { - SECItem * keyData = PK11_GetKeyData(pms); - if (keyData && keyData->data && keyData->len) { + SECStatus extractRV = PK11_ExtractKeyValue(pms); + if (extractRV == SECSuccess) { + SECItem *keyData = PK11_GetKeyData(pms); + if (keyData && keyData->data && keyData->len) { #ifdef TRACE - if (ssl_trace >= 100) { - ssl_PrintBuf(ss, "Pre-Master Secret", - keyData->data, keyData->len); - } + if (ssl_trace >= 100) { + ssl_PrintBuf(ss, "Pre-Master Secret", + keyData->data, keyData->len); + } #endif - if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { - /* 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. */ - char buf[4 + 8*2 + 1 + 48*2 + 1]; - - strcpy(buf, "RSA "); - hexEncode(buf + 4, enc_pms.data, 8); - buf[20] = ' '; - hexEncode(buf + 21, keyData->data, 48); - buf[sizeof(buf) - 1] = '\n'; - - fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); - fflush(ssl_keylog_iob); - } - } - } + if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) { + /* 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. */ + char buf[4 + 8 * 2 + 1 + 48 * 2 + 1]; + + strcpy(buf, "RSA "); + hexEncode(buf + 4, enc_pms.data, 8); + buf[20] = ' '; + hexEncode(buf + 21, keyData->data, 48); + buf[sizeof(buf) - 1] = '\n'; + + fwrite(buf, sizeof(buf), 1, ssl_keylog_iob); + fflush(ssl_keylog_iob); + } + } + } } +#endif - rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, - isTLS ? enc_pms.len + 2 : enc_pms.len); + rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, + isTLS ? enc_pms.len + 2 + : enc_pms.len); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } if (isTLS) { - rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); + rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2); } else { - rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); + rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len); } if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } rv = ssl3_InitPendingCipherSpec(ss, pms); @@ -6132,278 +6129,476 @@ sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) pms = NULL; if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } rv = SECSuccess; loser: if (enc_pms.data != NULL) { - PORT_Free(enc_pms.data); + PORT_Free(enc_pms.data); } if (pms != NULL) { - PK11_FreeSymKey(pms); + 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(const sslSocket *ss, const SECKEYPublicKey *pubKey, + PRBool appendLength) +{ + SECStatus rv; + unsigned int pad = pubKey->u.dh.prime.len - pubKey->u.dh.publicValue.len; + + if (appendLength) { + rv = ssl3_ExtAppendHandshakeNumber(ss, pubKey->u.dh.prime.len, 2); + if (rv != SECSuccess) { + return rv; + } + } + while (pad) { + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 1); + if (rv != SECSuccess) { + return rv; + } + --pad; + } + rv = ssl3_ExtAppendHandshake(ss, pubKey->u.dh.publicValue.data, + pubKey->u.dh.publicValue.len); + if (rv != SECSuccess) { + return rv; + } + return SECSuccess; +} + /* Called from ssl3_SendClientKeyExchange(). */ -/* Presently, this always uses PKCS11. There is no bypass for this. */ static SECStatus -sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) +ssl3_SendDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) { - PK11SymKey * pms = NULL; - SECStatus rv = SECFailure; - PRBool isTLS; - CK_MECHANISM_TYPE target; - - SECKEYDHParams dhParam; /* DH parameters */ - SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ - SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ + 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; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); /* Copy DH parameters from server key */ - if (svrPubKey->keyType != dhKey) { - PORT_SetError(SEC_ERROR_BAD_KEY); - goto loser; + if (SECKEY_GetPublicKeyType(svrPubKey) != dhKey) { + PORT_SetError(SEC_ERROR_BAD_KEY); + return SECFailure; } - dhParam.prime.data = svrPubKey->u.dh.prime.data; - dhParam.prime.len = svrPubKey->u.dh.prime.len; - dhParam.base.data = svrPubKey->u.dh.base.data; - dhParam.base.len = svrPubKey->u.dh.base.len; - /* Generate ephemeral DH keypair */ - privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); - if (!privKey || !pubKey) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - goto loser; + /* Work out the parameters. */ + rv = ssl_ValidateDHENamedGroup(ss, &svrPubKey->u.dh.prime, + &svrPubKey->u.dh.base, + &groupDef, ¶ms); + 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)); + 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; + if (isTLS) + target = CKM_TLS_MASTER_KEY_DERIVE_DH; + else + target = CKM_SSL3_MASTER_KEY_DERIVE_DH; /* Determine the PMS */ - - pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL, - CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL); + 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; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } - SECKEY_DestroyPrivateKey(privKey); - privKey = NULL; - - rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, - pubKey->u.dh.publicValue.len + 2); + /* Note: send the DH share padded to avoid triggering bugs. */ + rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, + params->prime.len + 2); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } - rv = ssl3_AppendHandshakeVariable(ss, - pubKey->u.dh.publicValue.data, - pubKey->u.dh.publicValue.len, 2); - SECKEY_DestroyPublicKey(pubKey); - pubKey = NULL; - + rv = ssl_AppendPaddedDHKeyShare(ss, pubKey, PR_TRUE); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl_AppendPaddedDHKeyShare */ } rv = ssl3_InitPendingCipherSpec(ss, pms); - PK11_FreeSymKey(pms); - pms = NULL; - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + goto loser; } - rv = SECSuccess; + PK11_FreeSymKey(pms); + ssl_FreeEphemeralKeyPair(keyPair); + return SECSuccess; loser: - - if(pms) PK11_FreeSymKey(pms); - if(privKey) SECKEY_DestroyPrivateKey(privKey); - if(pubKey) SECKEY_DestroyPublicKey(pubKey); - return rv; + if (pms) + PK11_FreeSymKey(pms); + if (keyPair) + ssl_FreeEphemeralKeyPair(keyPair); + return SECFailure; } - - - - /* Called from ssl3_HandleServerHelloDone(). */ static SECStatus ssl3_SendClientKeyExchange(sslSocket *ss) { - SECKEYPublicKey * serverKey = NULL; - SECStatus rv = SECFailure; - PRBool isTLS; + SECKEYPublicKey *serverKey = NULL; + SECStatus rv = SECFailure; SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + 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; - } + 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 */ + serverKey = ss->sec.peerKey; + ss->sec.peerKey = NULL; /* we're done with it now */ } - isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); - /* enforce limits on kea key sizes. */ - if (ss->ssl3.hs.kea_def->is_limited) { - unsigned int keyLen = SECKEY_PublicKeyStrengthInBits(serverKey); - - if (keyLen > ss->ssl3.hs.kea_def->key_size_limit) { - if (isTLS) - (void)SSL3_SendAlert(ss, alert_fatal, export_restriction); - else - (void)ssl3_HandshakeFailure(ss); - PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); - goto loser; - } - } - - ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); switch (ss->ssl3.hs.kea_def->exchKeyType) { - case kt_rsa: - rv = sendRSAClientKeyExchange(ss, serverKey); - break; + case ssl_kea_rsa: + rv = ssl3_SendRSAClientKeyExchange(ss, serverKey); + break; - case kt_dh: - rv = sendDHClientKeyExchange(ss, serverKey); - break; + case ssl_kea_dh: + rv = ssl3_SendDHClientKeyExchange(ss, serverKey); + break; -#ifndef NSS_DISABLE_ECC - case kt_ecdh: - rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); - break; -#endif /* NSS_DISABLE_ECC */ + case ssl_kea_ecdh: + rv = ssl3_SendECDHClientKeyExchange(ss, serverKey); + break; - default: - /* got an unknown or unsupported Key Exchange Algorithm. */ - SEND_ALERT - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - 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)); + SSL_GETPID(), ss->fd)); -loser: - if (serverKey) - SECKEY_DestroyPublicKey(serverKey); - return rv; /* err code already set. */ + SECKEY_DestroyPublicKey(serverKey); + return rv; /* err code already set. */ +} + +SECStatus +ssl_PickSignatureScheme(sslSocket *ss, + SECKEYPublicKey *pubKey, + SECKEYPrivateKey *privKey, + const SSLSignatureScheme *peerSchemes, + unsigned int peerSchemeCount, + PRBool requireSha1) +{ + unsigned int i, j; + const sslNamedGroupDef *group = NULL; + KeyType keyType; + PK11SlotInfo *slot; + PRBool slotDoesPss; + PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; + + /* We can't require SHA-1 in TLS 1.3. */ + PORT_Assert(!(requireSha1 && isTLS13)); + if (!pubKey || !privKey) { + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + slot = PK11_GetSlotFromPrivateKey(privKey); + if (!slot) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + slotDoesPss = PK11_DoesMechanism(slot, auth_alg_defs[ssl_auth_rsa_pss]); + PK11_FreeSlot(slot); + + keyType = SECKEY_GetPublicKeyType(pubKey); + if (keyType == ecKey) { + group = ssl_ECPubKey2NamedGroup(pubKey); + } + + /* Here we look for the first local preference that the client has + * indicated support for in their signature_algorithms extension. */ + for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { + SSLHashType hashType; + SECOidTag hashOID; + SSLSignatureScheme preferred = ss->ssl3.signatureSchemes[i]; + PRUint32 policy; + + if (!ssl_SignatureSchemeValidForKey(!isTLS13 /* allowSha1 */, + PR_TRUE /* matchGroup */, + keyType, group, preferred)) { + continue; + } + + /* Skip RSA-PSS schemes when the certificate's private key slot does + * not support this signature mechanism. */ + if (ssl_IsRsaPssSignatureScheme(preferred) && !slotDoesPss) { + continue; + } + + hashType = ssl_SignatureSchemeToHashType(preferred); + if (requireSha1 && (hashType != ssl_hash_sha1)) { + continue; + } + hashOID = ssl3_HashTypeToOID(hashType); + if ((NSS_GetAlgorithmPolicy(hashOID, &policy) == SECSuccess) && + !(policy & NSS_USE_ALG_IN_SSL_KX)) { + /* we ignore hashes we don't support */ + continue; + } + + for (j = 0; j < peerSchemeCount; j++) { + if (peerSchemes[j] == preferred) { + ss->ssl3.hs.signatureScheme = preferred; + return SECSuccess; + } + } + } + + PORT_SetError(SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM); + return SECFailure; +} + +/* 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) +{ + sslKeyPair *keyPair = ss->sec.serverCert->serverKeyPair; + 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. */ + switch (SECKEY_GetPublicKeyType(keyPair->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; + } + + /* Sets error code, if needed. */ + return ssl_PickSignatureScheme(ss, keyPair->pubKey, keyPair->privKey, + ss->xtnData.clientSigSchemes, + ss->xtnData.numClientSigScheme, + PR_FALSE /* requireSha1 */); +} + +static SECStatus +ssl_PickClientSignatureScheme(sslSocket *ss, const SSLSignatureScheme *schemes, + unsigned int numSchemes) +{ + SECKEYPrivateKey *privKey = ss->ssl3.clientPrivateKey; + SECKEYPublicKey *pubKey; + SECStatus rv; + + pubKey = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); + PORT_Assert(pubKey); + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 && + (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, pubKey, privKey, schemes, numSchemes, + PR_TRUE /* requireSha1 */); + 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, pubKey, privKey, schemes, numSchemes, + PR_FALSE /* requireSha1 */); + SECKEY_DestroyPublicKey(pubKey); + return rv; } /* Called from ssl3_HandleServerHelloDone(). */ static SECStatus -ssl3_SendCertificateVerify(sslSocket *ss) +ssl3_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey) { - SECStatus rv = SECFailure; - PRBool isTLS; - PRBool isTLS12; - SECItem buf = {siBuffer, NULL, 0}; - SSL3Hashes hashes; - KeyType keyType; - unsigned int len; - SSLSignatureAndHashAlg sigAndHash; + 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)); + 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_GETPID(), ss->fd)); ssl_GetSpecReadLock(ss); - if (ss->ssl3.hs.hashType == handshake_hash_single && - ss->ssl3.hs.backupHash) { - rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes); - PORT_Assert(!ss->ssl3.hs.backupHash); + + if (ss->ssl3.hs.hashType == handshake_hash_record) { + hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme); } else { - rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0); + /* 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_ComputeHandshakeHashes */ + goto done; /* err code was set by ssl3_ComputeHandshakeHash(es) */ } - isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); - isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); - keyType = ss->ssl3.clientPrivateKey->keyType; - rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS); - if (rv == SECSuccess) { - PK11SlotInfo * slot; - sslSessionID * sid = ss->sec.ci.sid; - - /* 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. - */ - slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey); - 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); - } - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); - ss->ssl3.clientPrivateKey = NULL; + 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 */ + goto done; /* err code was set by ssl3_SignHashes */ } len = buf.len + 2 + (isTLS12 ? 2 : 0); rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len); if (rv != SECSuccess) { - goto done; /* error code set by AppendHandshake */ + goto done; /* error code set by AppendHandshake */ } if (isTLS12) { - rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType, - &sigAndHash.sigAlg); - if (rv != SECSuccess) { - goto done; - } - sigAndHash.hashAlg = hashes.hashAlg; - - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); - if (rv != SECSuccess) { - goto done; /* err set by AppendHandshake. */ - } + 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 */ + goto done; /* error code set by AppendHandshake */ } done: if (buf.data) - PORT_Free(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_SetCipherSuite(sslSocket *ss, ssl3CipherSuite chosenSuite, + PRBool initHashes) +{ + ss->ssl3.hs.cipher_suite = chosenSuite; + ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef(chosenSuite); + 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've have a cipher suite, initialize the handshake hashes. */ + return ssl3_InitHandshakeHashes(ss); +} + /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete * ssl3 ServerHello message. * Caller must hold Handshake and RecvBuf locks. @@ -6411,162 +6606,190 @@ done: static SECStatus ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - sslSessionID *sid = ss->sec.ci.sid; - PRInt32 temp; /* allow for consume number failure */ - PRBool suite_found = PR_FALSE; - int i; - int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; - SECStatus rv; - SECItem sidBytes = {siBuffer, NULL, 0}; - PRBool sid_match; - PRBool isTLS = PR_FALSE; - SSL3AlertDescription desc = illegal_parameter; - SSL3ProtocolVersion version; + PRInt32 temp; /* allow for consume number failure */ + PRBool suite_found = PR_FALSE; + int i; + int errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; + SECStatus rv; + SECItem sidBytes = { siBuffer, NULL, 0 }; + PRBool isTLS = PR_FALSE; + SSL3AlertDescription desc = illegal_parameter; +#ifndef TLS_1_3_DRAFT_VERSION + SSL3ProtocolVersion downgradeCheckVersion; +#endif 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) ); - PORT_Assert( ss->ssl3.initialized ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.initialized); if (ss->ssl3.hs.ws != wait_server_hello) { errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO; - desc = unexpected_message; - goto alert_loser; + 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; + CERT_DestroyCertificateList(ss->ssl3.clientCertChain); + ss->ssl3.clientCertChain = NULL; } if (ss->ssl3.clientCertificate != NULL) { - CERT_DestroyCertificate(ss->ssl3.clientCertificate); - 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; + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + ss->ssl3.clientPrivateKey = NULL; } - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); - if (temp < 0) { - goto loser; /* alert has been sent */ + rv = ssl_ClientReadVersion(ss, &b, &length, &ss->version); + if (rv != SECSuccess) { + goto loser; /* alert has been sent */ } - version = (SSL3ProtocolVersion)temp; - if (IS_DTLS(ss)) { - /* 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 check for matching here. - */ - version = dtls_DTLSVersionToTLSVersion(version); - if (version == 0) { /* Insane version number */ - goto alert_loser; - } + /* We got a HelloRetryRequest, but the server didn't pick 1.3. Scream. */ + if (ss->ssl3.hs.helloRetry && ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + desc = illegal_parameter; + errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; + goto alert_loser; } - rv = ssl3_NegotiateVersion(ss, version, PR_FALSE); - if (rv != SECSuccess) { - desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version - : handshake_failure; - errCode = SSL_ERROR_UNSUPPORTED_VERSION; - 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 = illegal_parameter; + errCode = SSL_ERROR_UNSUPPORTED_VERSION; + goto alert_loser; } ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0); - rv = ssl3_InitHandshakeHashes(ss); - if (rv != SECSuccess) { - desc = internal_error; - errCode = PORT_GetError(); - goto alert_loser; - } - rv = ssl3_ConsumeHandshake( - ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); + ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length); if (rv != SECSuccess) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ } - rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); - if (rv != SECSuccess) { - goto loser; /* alert has been sent */ +#ifndef TLS_1_3_DRAFT_VERSION + /* Check the ServerHello.random per + * [draft-ietf-tls-tls13-11 Section 6.3.1.1]. + * + * TLS 1.3 clients receiving a TLS 1.2 or below ServerHello MUST check + * that the top eight octets are not equal to either of these values. + * TLS 1.2 clients SHOULD also perform this check if the ServerHello + * indicates TLS 1.1 or below. If a match is found the client MUST + * abort the handshake with a fatal "illegal_parameter" alert. + * + * Disable this test during the TLS 1.3 draft version period. + */ + downgradeCheckVersion = ss->ssl3.downgradeCheckVersion ? ss->ssl3.downgradeCheckVersion + : ss->vrange.max; + + if (downgradeCheckVersion >= SSL_LIBRARY_VERSION_TLS_1_2 && + downgradeCheckVersion > ss->version) { + /* Both sections use the same sentinel region. */ + unsigned char *downgrade_sentinel = + ss->ssl3.hs.server_random.rand + + SSL3_RANDOM_LENGTH - sizeof(tls13_downgrade_random); + if (!PORT_Memcmp(downgrade_sentinel, + tls13_downgrade_random, + sizeof(tls13_downgrade_random)) || + !PORT_Memcmp(downgrade_sentinel, + tls12_downgrade_random, + sizeof(tls12_downgrade_random))) { + desc = illegal_parameter; + errCode = SSL_ERROR_RX_MALFORMED_SERVER_HELLO; + goto alert_loser; + } } - if (sidBytes.len > SSL3_SESSIONID_BYTES) { - if (isTLS) - desc = decode_error; - goto alert_loser; /* malformed. */ +#endif + + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); + if (rv != SECSuccess) { + goto loser; /* alert has been sent */ + } + if (sidBytes.len > SSL3_SESSIONID_BYTES) { + if (isTLS) + desc = decode_error; + goto alert_loser; /* malformed. */ + } } /* find selected cipher suite in our list. */ temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); if (temp < 0) { - goto loser; /* alert has been sent */ + goto loser; /* alert has been sent */ + } + i = ssl3_config_match_init(ss); + PORT_Assert(i > 0); + if (i <= 0) { + errCode = PORT_GetError(); + goto loser; } - ssl3_config_match_init(ss); for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (temp == suite->cipher_suite) { - SSLVersionRange vrange = {ss->version, ss->version}; - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &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(temp, &vrange)) { - desc = handshake_failure; - errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; - goto alert_loser; - } - - break; /* failure */ - } - - suite_found = PR_TRUE; - break; /* success */ - } + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; + if (temp == suite->cipher_suite) { + SSLVersionRange vrange = { ss->version, ss->version }; + if (!config_match(suite, 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(temp, &vrange)) { + desc = handshake_failure; + errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION; + goto alert_loser; + } + + break; /* failure */ + } + + suite_found = PR_TRUE; + break; /* success */ + } } if (!suite_found) { - desc = handshake_failure; - errCode = SSL_ERROR_NO_CYPHER_OVERLAP; - goto alert_loser; - } - ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp; - ss->ssl3.hs.suite_def = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp); - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - PORT_Assert(ss->ssl3.hs.suite_def); - if (!ss->ssl3.hs.suite_def) { - PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE); - goto loser; /* we don't send alerts for our screw-ups. */ + desc = handshake_failure; + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; + goto alert_loser; } - /* find selected compression method in our list. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); - if (temp < 0) { - goto loser; /* alert has been sent */ - } - suite_found = PR_FALSE; - for (i = 0; i < compressionMethodsCount; i++) { - if (temp == compressions[i]) { - if (!compressionEnabled(ss, compressions[i])) { - break; /* failure */ - } - suite_found = PR_TRUE; - break; /* success */ - } + rv = ssl3_SetCipherSuite(ss, (ssl3CipherSuite)temp, PR_TRUE); + if (rv != SECSuccess) { + desc = internal_error; + errCode = PORT_GetError(); + goto alert_loser; } - if (!suite_found) { - desc = handshake_failure; - errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; - goto alert_loser; + + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + /* find selected compression method in our list. */ + temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); + if (temp < 0) { + goto loser; /* alert has been sent */ + } + suite_found = PR_FALSE; + for (i = 0; i < ssl_compression_method_count; i++) { + if (temp == ssl_compression_methods[i]) { + if (!ssl_CompressionEnabled(ss, ssl_compression_methods[i])) { + break; /* failure */ + } + suite_found = PR_TRUE; + break; /* success */ + } + } + if (!suite_found) { + desc = handshake_failure; + errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; + goto alert_loser; + } + ss->ssl3.hs.compression = (SSLCompressionMethod)temp; + } else { + ss->ssl3.hs.compression = ssl_compression_null; } - ss->ssl3.hs.compression = (SSLCompressionMethod)temp; /* Note that if !isTLS and the extra stuff is not extensions, we * do NOT goto alert_loser. @@ -6578,36 +6801,72 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * extension in SSL 3.0. */ if (length != 0) { - SECItem extensions; - rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); - if (rv != SECSuccess || length != 0) { - if (isTLS) - goto alert_loser; - } else { - rv = ssl3_HandleHelloExtensions(ss, &extensions.data, - &extensions.len); - if (rv != SECSuccess) - goto alert_loser; - } - } - if ((ss->opt.requireSafeNegotiation || + SECItem extensions; + rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length); + if (rv != SECSuccess || length != 0) { + if (isTLS) + goto alert_loser; + } else { + rv = ssl3_HandleExtensions(ss, &extensions.data, + &extensions.len, server_hello); + if (rv != SECSuccess) + goto alert_loser; + } + } + + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + rv = tls13_HandleServerHelloPart2(ss); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + goto loser; + } + } else { + rv = ssl3_HandleServerHelloPart2(ss, &sidBytes, &errCode); + if (rv != SECSuccess) + goto loser; + } + + 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_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; + 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; + desc = handshake_failure; /* we need to call ssl3_SetupPendingCipherSpec here so we can check the * key exchange algorithm. */ rv = ssl3_SetupPendingCipherSpec(ss); if (rv != SECSuccess) { - goto alert_loser; /* error code is set. */ + goto alert_loser; /* error code is set. */ } /* We may or may not have sent a session id, we may get one back or @@ -6615,179 +6874,174 @@ ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) * 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 && - sid->version == ss->version && - sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do { - ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; - - SECItem wrappedMS; /* wrapped master secret. */ - - /* [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; + 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 { + ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec; + + SECItem wrappedMS; /* wrapped master secret. */ + + /* [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; - } + /* + * 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.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; - - /* 3 cases here: - * a) key is wrapped (implies using PKCS11) - * b) key is unwrapped, but we're still using PKCS11 - * c) key is unwrapped, and we're bypassing PKCS11. - */ - if (sid->u.ssl3.keys.msIsWrapped) { - PK11SlotInfo *slot; - PK11SymKey * wrapKey; /* wrapping key */ - CK_FLAGS keyFlags = 0; - -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - /* we cannot restart a non-bypass session in a - ** bypass socket. - */ - break; - } -#endif - /* unwrap master secret with PKCS11 */ - slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, - sid->u.ssl3.masterSlotID); - if (slot == NULL) { - break; /* not considered an error. */ - } - if (!PK11_IsPresent(slot)) { - PK11_FreeSlot(slot); - break; /* not considered an error. */ - } - wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, - sid->u.ssl3.masterWrapMech, - sid->u.ssl3.masterWrapSeries, - ss->pkcs11PinArg); - PK11_FreeSlot(slot); - if (wrapKey == NULL) { - break; /* not considered an error. */ - } - - if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ - keyFlags = CKF_SIGN | CKF_VERIFY; - } - - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - pwSpec->master_secret = - PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, - NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, - CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); - errCode = PORT_GetError(); - PK11_FreeSymKey(wrapKey); - if (pwSpec->master_secret == NULL) { - break; /* errorCode set just after call to UnwrapSymKey. */ - } -#ifndef NO_PKCS11_BYPASS - } else if (ss->opt.bypassPKCS11) { - /* MS is not wrapped */ - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = wrappedMS.len; -#endif - } else { - /* We CAN restart a bypass session in a non-bypass socket. */ - /* need to import the raw master secret to session object */ - PK11SlotInfo *slot = PK11_GetInternalSlot(); - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - pwSpec->master_secret = - PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, - PK11_OriginUnwrap, CKA_ENCRYPT, - &wrappedMS, NULL); - PK11_FreeSlot(slot); - if (pwSpec->master_secret == NULL) { - break; - } - } - - /* 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); - } - - /* NULL value for PMS because we are reusing the old MS */ - rv = ssl3_InitPendingCipherSpec(ss, NULL); - if (rv != SECSuccess) { - goto alert_loser; /* err code was set */ - } - return SECSuccess; - } while (0); + ss->sec.authType = sid->authType; + ss->sec.authKeyBits = sid->authKeyBits; + ss->sec.keaType = sid->keaType; + ss->sec.keaKeyBits = sid->keaKeyBits; + + if (sid->u.ssl3.keys.msIsWrapped) { + PK11SlotInfo *slot; + PK11SymKey *wrapKey; /* wrapping key */ + CK_FLAGS keyFlags = 0; + + /* unwrap master secret */ + slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID, + sid->u.ssl3.masterSlotID); + if (slot == NULL) { + break; /* not considered an error. */ + } + if (!PK11_IsPresent(slot)) { + PK11_FreeSlot(slot); + break; /* not considered an error. */ + } + wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex, + sid->u.ssl3.masterWrapMech, + sid->u.ssl3.masterWrapSeries, + ss->pkcs11PinArg); + PK11_FreeSlot(slot); + if (wrapKey == NULL) { + break; /* not considered an error. */ + } + + if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ + keyFlags = + CKF_SIGN | CKF_VERIFY; + } + + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + pwSpec->master_secret = + PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, + NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, + CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); + errCode = PORT_GetError(); + PK11_FreeSymKey(wrapKey); + if (pwSpec->master_secret == NULL) { + break; /* errorCode set just after call to UnwrapSymKey. */ + } + } else { + /* need to import the raw master secret to session object */ + PK11SlotInfo *slot = PK11_GetInternalSlot(); + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + pwSpec->master_secret = + PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, + PK11_OriginUnwrap, CKA_ENCRYPT, + &wrappedMS, NULL); + PK11_FreeSlot(slot); + if (pwSpec->master_secret == NULL) { + break; + } + } + + /* 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); + } + + /* NULL value for PMS because we are reusing the old MS */ + rv = ssl3_InitPendingCipherSpec(ss, NULL); + 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 ); + SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_not_ok); else - SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses ); + SSL_AtomicIncrementLong(&ssl3stats.hsh_sid_cache_misses); /* throw the old one away */ sid->u.ssl3.keys.resumable = PR_FALSE; - if (ss->sec.uncache) - (*ss->sec.uncache)(sid); + ss->sec.uncache(sid); 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. */ + goto alert_loser; /* memory error is set. */ } sid->version = ss->version; - sid->u.ssl3.sessionIDLength = sidBytes.len; - PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len); + 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); + 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->signKeyType != sign_null) { - /* All current cipher suites other than those with sign_null (i.e., + 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 { @@ -6803,413 +7057,376 @@ alert_loser: (void)SSL3_SendAlert(ss, alert_fatal, desc); loser: - errCode = ssl_MapLowLevelError(errCode); + *retErrCode = errCode; return SECFailure; } - -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 ServerKeyExchange message. - * Caller must hold Handshake and RecvBuf locks. - */ static SECStatus -ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +ssl_HandleDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - PLArenaPool * arena = NULL; - SECKEYPublicKey *peerKey = NULL; - PRBool isTLS, isTLS12; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; - SSL3AlertDescription desc = illegal_parameter; - SSL3Hashes hashes; - SECItem signature = {siBuffer, NULL, 0}; - SSLSignatureAndHashAlg sigAndHash; + 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; - sigAndHash.hashAlg = ssl_hash_none; + SSL3Hashes hashes; + SECItem signature = { siBuffer, NULL, 0 }; + PLArenaPool *arena = NULL; + SECKEYPublicKey *peerKey = NULL; - 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) ); + rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed. */ + } - if (ss->ssl3.hs.ws != wait_server_key) { - errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH; - desc = unexpected_message; + rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH); + if (rv != SECSuccess) { + minDH = SSL_DH_MIN_P_BITS; + } + dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p); + if (dh_p_bits < minDH) { + errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; goto alert_loser; } - - isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); - isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); - - switch (ss->ssl3.hs.kea_def->exchKeyType) { - - case kt_rsa: { - SECItem modulus = {siBuffer, NULL, 0}; - SECItem exponent = {siBuffer, NULL, 0}; - - rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - /* This exchange method is only used by export cipher suites. - * Those are broken and so this code will eventually be removed. */ - if (SECKEY_BigIntegerBitLength(&modulus) < 512) { - desc = isTLS ? insufficient_security : illegal_parameter; + 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, &exponent, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ - } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, - &sigAndHash, ss->sec.peerCert); - if (rv != SECSuccess) { - goto loser; - } - } - 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. */ - } - - /* 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_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); + } + + 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) { - errCode = - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto alert_loser; - } - rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, - isTLS, ss->pkcs11PinArg); - 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) { - goto no_memory; - } - - peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); - if (peerKey == NULL) { - goto no_memory; - } - - peerKey->arena = arena; - peerKey->keyType = rsaKey; - peerKey->pkcs11Slot = NULL; - peerKey->pkcs11ID = CK_INVALID_HANDLE; - if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus, &modulus) || - SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent)) - { - goto no_memory; - } - ss->sec.peerKey = peerKey; - ss->ssl3.hs.ws = wait_cert_request; - return SECSuccess; - } - - case kt_dh: { - 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; - unsigned dh_Ys_bits; - PRInt32 minDH; - - rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - - rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH); - if (rv != SECSuccess) { - minDH = SSL_DH_MIN_P_BITS; - } - dh_p_bits = SECKEY_BigIntegerBitLength(&dh_p); - if (dh_p_bits < minDH) { - errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY; - 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; - rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed. */ - } - dh_Ys_bits = SECKEY_BigIntegerBitLength(&dh_Ys); - if (dh_Ys_bits > dh_p_bits || dh_Ys_bits <= 1) - goto alert_loser; - if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ - } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(ss, - &sigAndHash, ss->sec.peerCert); - if (rv != SECSuccess) { - goto loser; - } - } - 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(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); + goto loser; /* malformed or unsupported. */ + } + rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, + ss->sec.peerCert); if (rv != SECSuccess) { - errCode = - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto alert_loser; - } - rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, - isTLS, ss->pkcs11PinArg); - 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) { - goto no_memory; - } - - peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); - if (peerKey == NULL) { - goto no_memory; - } - - 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)) - { - goto no_memory; - } - ss->sec.peerKey = peerKey; - ss->ssl3.hs.ws = wait_cert_request; - return SECSuccess; - } - -#ifndef NSS_DISABLE_ECC - case kt_ecdh: - rv = ssl3_HandleECDHServerKeyExchange(ss, b, length); - return rv; -#endif /* NSS_DISABLE_ECC */ - - default: - desc = handshake_failure; - errCode = SEC_ERROR_UNSUPPORTED_KEYALG; - break; /* goto alert_loser; */ + goto 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( errCode ); - return SECFailure; - -no_memory: /* no-memory error has already been set. */ - if (arena) { - PORT_FreeArena(arena, PR_FALSE); - } - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + PORT_SetError(ssl_MapLowLevelError(errCode)); return SECFailure; } -/* - * Returns the TLS signature algorithm for the client authentication key and - * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes. +/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered a + * complete ssl3 ServerKeyExchange message. + * Caller must hold Handshake and RecvBuf locks. */ static SECStatus -ssl3_ExtractClientKeyInfo(sslSocket *ss, - SSLSignType *sigAlg, - PRBool *preferSha1) +ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - SECStatus rv = SECSuccess; - SECKEYPublicKey *pubk; + SECStatus rv; - pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate); - if (pubk == NULL) { - rv = SECFailure; - goto done; - } + 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)); - rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg); - if (rv != SECSuccess) { - goto done; + 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; } - /* 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. - */ - if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) { - *preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128; - } else { - *preferSha1 = PR_FALSE; + 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; } -done: - if (pubk) - SECKEY_DestroyPublicKey(pubk); + if (rv == SECSuccess) { + ss->ssl3.hs.ws = wait_cert_request; + } + /* All Handle*ServerKeyExchange functions set the error code. */ return rv; } -/* Destroys the backup handshake hash context if we don't need it. Note that - * this function selects the hash algorithm for client authentication - * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash - * to determine whether to use SHA-1 or SHA-256. */ -static void -ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss, - const SECItem *algorithms) +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, SSL3Opaque **b, PRUint32 *length, + PLArenaPool *arena, CERTDistNames *ca_list) { - SECStatus rv; - SSLSignType sigAlg; - PRBool preferSha1; - PRBool supportsSha1 = PR_FALSE; - PRBool supportsSha256 = PR_FALSE; - PRBool needBackupHash = PR_FALSE; - unsigned int i; + PRInt32 remaining; + int nnames = 0; + dnameNode *node; + int i; + + remaining = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); + if (remaining < 0) + return SECFailure; /* malformed, alert has been sent */ + + if ((PRUint32)remaining > *length) + goto alert_loser; + + ca_list->head = node = PORT_ArenaZNew(arena, dnameNode); + if (node == NULL) + goto no_mem; + + while (remaining > 0) { + PRInt32 len; + + if (remaining < 2) + goto alert_loser; /* malformed */ -#ifndef NO_PKCS11_BYPASS - /* Backup handshake hash is not supported in PKCS #11 bypass mode. */ - if (ss->opt.bypassPKCS11) { - PORT_Assert(!ss->ssl3.hs.backupHash); - return; + node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); + if (len <= 0) + return SECFailure; /* malformed, alert has been sent */ + + remaining -= 2; + if (remaining < len) + goto alert_loser; /* malformed */ + + node->name.data = *b; + *b += len; + *length -= len; + remaining -= len; + nnames++; + if (remaining <= 0) + break; /* success */ + + node->next = PORT_ArenaZNew(arena, dnameNode); + node = node->next; + if (node == NULL) + goto no_mem; } -#endif - PORT_Assert(ss->ssl3.hs.backupHash); - /* Determine the key's signature algorithm and whether it prefers SHA-1. */ - rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1); + ca_list->nnames = nnames; + ca_list->names = PORT_ArenaNewArray(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: + PORT_SetError(SEC_ERROR_NO_MEMORY); + 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; + unsigned int numSchemes = 0; + unsigned int max; + + rv = ssl3_ExtConsumeHandshakeVariable(ss, &buf, 2, b, len); if (rv != SECSuccess) { - goto done; + return SECFailure; + } + /* An empty or odd-length value is invalid. */ + if (buf.len == 0 || (buf.len & 1) != 0) { + ssl3_ExtSendAlert(ss, alert_fatal, decode_error); + return SECFailure; } - /* Determine the server's hash support for that signature algorithm. */ - for (i = 0; i < algorithms->len; i += 2) { - if (algorithms->data[i+1] == sigAlg) { - if (algorithms->data[i] == ssl_hash_sha1) { - supportsSha1 = PR_TRUE; - } else if (algorithms->data[i] == ssl_hash_sha256) { - supportsSha256 = PR_TRUE; - } - } + /* Limit the number of schemes we read. */ + max = PR_MIN(buf.len / 2, 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; } - /* If either the server does not support SHA-256 or the client key prefers - * SHA-1, leave the backup hash. */ - if (supportsSha1 && (preferSha1 || !supportsSha256)) { - needBackupHash = PR_TRUE; + for (; max; --max) { + PRInt32 tmp; + tmp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buf.data, &buf.len); + if (tmp < 0) { + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + if (ssl_IsSupportedSignatureScheme((SSLSignatureScheme)tmp)) { + schemes[numSchemes++] = (SSLSignatureScheme)tmp; + } } -done: - if (!needBackupHash) { - PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); - ss->ssl3.hs.backupHash = NULL; + if (!numSchemes) { + if (!arena) { + PORT_Free(schemes); + } + schemes = NULL; } -} -typedef struct dnameNode { - struct dnameNode *next; - SECItem name; -} dnameNode; + *schemesOut = schemes; + *numSchemesOut = numSchemes; + return SECSuccess; +} -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 Certificate Request message. +/* 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, SSL3Opaque *b, PRUint32 length) { - PLArenaPool * arena = NULL; - dnameNode * node; - PRInt32 remaining; - PRBool isTLS = PR_FALSE; - PRBool isTLS12 = PR_FALSE; - int i; - int errCode = SSL_ERROR_RX_MALFORMED_CERT_REQUEST; - int nnames = 0; - SECStatus rv; - SSL3AlertDescription desc = illegal_parameter; - SECItem cert_types = {siBuffer, NULL, 0}; - SECItem algorithms = {siBuffer, NULL, 0}; - CERTDistNames ca_list; + 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) ); + 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; @@ -7225,140 +7442,39 @@ ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 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 */ - - if (isTLS12) { - rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length); - if (rv != SECSuccess) - goto loser; /* malformed, alert has been sent */ - /* An empty or odd-length value is invalid. - * SignatureAndHashAlgorithm - * supported_signature_algorithms<2..2^16-2>; - */ - if (algorithms.len == 0 || (algorithms.len & 1) != 0) - goto alert_loser; - } + goto loser; /* malformed, alert has been sent */ arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) - goto no_mem; - - remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); - if (remaining < 0) - goto loser; /* malformed, alert has been sent */ - - if ((PRUint32)remaining > length) - goto alert_loser; - - ca_list.head = node = PORT_ArenaZNew(arena, dnameNode); - if (node == NULL) - goto no_mem; - - while (remaining > 0) { - PRInt32 len; - - if (remaining < 2) - goto alert_loser; /* malformed */ - - node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); - if (len <= 0) - goto loser; /* malformed, alert has been sent */ - - remaining -= 2; - if (remaining < len) - goto alert_loser; /* malformed */ - - node->name.data = b; - b += len; - length -= len; - remaining -= len; - nnames++; - if (remaining <= 0) - break; /* success */ - - node->next = PORT_ArenaZNew(arena, dnameNode); - node = node->next; - if (node == NULL) - goto no_mem; - } - - ca_list.nnames = nnames; - ca_list.names = PORT_ArenaNewArray(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; + 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 */ + } } + rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, arena, &ca_list); + if (rv != SECSuccess) + goto done; /* alert sent in ssl3_ParseCertificateRequestCAs */ + if (length != 0) - goto alert_loser; /* malformed */ + goto alert_loser; /* malformed */ - desc = no_certificate; ss->ssl3.hs.ws = wait_hello_done; - if (ss->getClientAuthData != NULL) { - PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == - ssl_preinfo_all); - /* XXX Should pass cert_types and algorithms in this call!! */ - 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 */ - } - switch (rv) { - case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ - ssl3_SetAlwaysBlock(ss); - break; /* not an error */ - - case SECSuccess: - /* check what the callback function returned */ - if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { - /* we are missing either the key or cert */ - if (ss->ssl3.clientCertificate) { - /* got a cert, but no key - free it */ - CERT_DestroyCertificate(ss->ssl3.clientCertificate); - ss->ssl3.clientCertificate = NULL; - } - if (ss->ssl3.clientPrivateKey) { - /* got a key, but no cert - free it */ - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); - ss->ssl3.clientPrivateKey = NULL; - } - 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) { - CERT_DestroyCertificate(ss->ssl3.clientCertificate); - ss->ssl3.clientCertificate = NULL; - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); - ss->ssl3.clientPrivateKey = NULL; - goto send_no_certificate; - } - if (ss->ssl3.hs.hashType == handshake_hash_single) { - ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms); - } - break; /* not an error */ - - case SECFailure: - default: -send_no_certificate: - if (isTLS) { - ss->ssl3.sendEmptyCert = PR_TRUE; - } else { - (void)SSL3_SendAlert(ss, alert_warning, no_certificate); - } - rv = SECSuccess; - break; + rv = ssl3_CompleteHandleCertificateRequest(ss, signatureSchemes, + signatureSchemeCount, &ca_list); + if (rv == SECFailure) { + PORT_Assert(0); + errCode = SEC_ERROR_LIBRARY_FAILURE; + desc = internal_error; + goto alert_loser; } goto done; @@ -7369,59 +7485,135 @@ no_mem: alert_loser: if (isTLS && desc == illegal_parameter) - desc = decode_error; + 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); + PORT_FreeArena(arena, PR_FALSE); + return rv; +} + +SECStatus +ssl3_CompleteHandleCertificateRequest(sslSocket *ss, + const SSLSignatureScheme *signatureSchemes, + unsigned int signatureSchemeCount, + CERTDistNames *ca_list) +{ + SECStatus rv; + + if (ss->getClientAuthData != NULL) { + PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == + ssl_preinfo_all); + /* XXX Should pass cert_types and algorithms in this call!! */ + 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 */ + } + switch (rv) { + case SECWouldBlock: /* getClientAuthData has put up a dialog box. */ + ssl3_SetAlwaysBlock(ss); + break; /* not an error */ + + case SECSuccess: + /* check what the callback function returned */ + if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) { + /* we are missing either the key or cert */ + if (ss->ssl3.clientCertificate) { + /* got a cert, but no key - free it */ + CERT_DestroyCertificate(ss->ssl3.clientCertificate); + ss->ssl3.clientCertificate = NULL; + } + if (ss->ssl3.clientPrivateKey) { + /* got a key, but no cert - free it */ + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + ss->ssl3.clientPrivateKey = NULL; + } + 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) { + CERT_DestroyCertificate(ss->ssl3.clientCertificate); + ss->ssl3.clientCertificate = NULL; + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + ss->ssl3.clientPrivateKey = NULL; + goto send_no_certificate; + } + if (ss->ssl3.hs.hashType == handshake_hash_record || + ss->ssl3.hs.hashType == handshake_hash_single) { + rv = ssl_PickClientSignatureScheme(ss, signatureSchemes, + signatureSchemeCount); + } + break; /* not an error */ + + case SECFailure: + default: + send_no_certificate: + if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { + ss->ssl3.sendEmptyCert = PR_TRUE; + } else { + (void)SSL3_SendAlert(ss, alert_warning, no_certificate); + } + rv = SECSuccess; + break; + } + return rv; } 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 ); + 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)); + SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start", + SSL_GETPID(), ss->fd)); } else { - PRBool maybeFalseStart; - SECStatus rv; + PRBool maybeFalseStart; + SECStatus rv; - /* 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. */ + /* 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); maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10; ssl_ReleaseSpecReadLock(ss); - if (!maybeFalseStart) { - SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", - SSL_GETPID(), ss->fd)); - } else { + if (!maybeFalseStart) { + SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher", + SSL_GETPID(), ss->fd)); + } else { 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; - } + 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; + } } ss->ssl3.hs.canFalseStart = PR_FALSE; @@ -7429,22 +7621,21 @@ ssl3_CheckFalseStart(sslSocket *ss) } PRBool -ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss) +ssl3_WaitingForServerSecondRound(sslSocket *ss) { PRBool result; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); switch (ss->ssl3.hs.ws) { - case wait_new_session_ticket: - result = PR_TRUE; - break; - case wait_change_cipher: - result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn); - break; - default: - result = PR_FALSE; - break; + case wait_new_session_ticket: + case wait_change_cipher: + case wait_finished: + result = PR_TRUE; + break; + default: + result = PR_FALSE; + break; } return result; @@ -7452,27 +7643,27 @@ ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss) static SECStatus ssl3_SendClientSecondRound(sslSocket *ss); -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 Server Hello Done message. +/* 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; + 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) ); + 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; + 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); @@ -7490,20 +7681,12 @@ ssl3_SendClientSecondRound(sslSocket *ss) SECStatus rv; PRBool sendClientCert; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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; - - if (!sendClientCert && - ss->ssl3.hs.hashType == handshake_hash_single && - ss->ssl3.hs.backupHash) { - /* Don't need the backup handshake hash. */ - PK11_DestroyContext(ss->ssl3.hs.backupHash, PR_TRUE); - ss->ssl3.hs.backupHash = NULL; - } + 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 @@ -7530,50 +7713,52 @@ ssl3_SendClientSecondRound(sslSocket *ss) * application data. */ if (ss->ssl3.hs.restartTarget) { - PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; + PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget"); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } if (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; - return SECWouldBlock; + (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; + return SECWouldBlock; } - ssl_GetXmitBufLock(ss); /*******************************/ + 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. */ - } + 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_SendCertificate(ss); + if (rv != SECSuccess) { + goto loser; /* error code is set. */ + } } rv = ssl3_SendClientKeyExchange(ss); if (rv != SECSuccess) { - goto loser; /* err is set. */ + goto loser; /* err is set. */ } if (sendClientCert) { - rv = ssl3_SendCertificateVerify(ss); - if (rv != SECSuccess) { - goto loser; /* err is set. */ + 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. */ + goto loser; /* err code was set. */ } /* This must be done after we've set ss->ssl3.cwSpec in @@ -7585,56 +7770,56 @@ ssl3_SendClientSecondRound(sslSocket *ss) ss->enoughFirstHsDone = PR_TRUE; if (!ss->firstHsDone) { - /* XXX: If the server's certificate hasn't been authenticated by this - * point, then we may be leaking this NPN message to an attacker. - */ - rv = ssl3_SendNextProto(ss); - if (rv != SECSuccess) { - goto loser; /* err code was set. */ - } - - 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)); - } - } + /* XXX: If the server's certificate hasn't been authenticated by this + * point, then we may be leaking this NPN message to an attacker. + */ + rv = ssl3_SendNextProto(ss); + if (rv != SECSuccess) { + goto loser; /* err code was set. */ + } + + 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. */ + goto loser; /* err code was set. */ } - ssl_ReleaseXmitBufLock(ss); /*******************************/ + ssl_ReleaseXmitBufLock(ss); /*******************************/ if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) - ss->ssl3.hs.ws = wait_new_session_ticket; + ss->ssl3.hs.ws = wait_new_session_ticket; else - ss->ssl3.hs.ws = wait_change_cipher; + ss->ssl3.hs.ws = wait_change_cipher; - PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss)); + PORT_Assert(ssl3_WaitingForServerSecondRound(ss)); return SECSuccess; @@ -7652,18 +7837,18 @@ ssl3_SendHelloRequest(sslSocket *ss) SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(), - ss->fd)); + ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake */ + return rv; /* err set by AppendHandshake */ } rv = ssl3_FlushHandshake(ss, 0); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } ss->ssl3.hs.ws = wait_client_hello; return SECSuccess; @@ -7671,7 +7856,7 @@ ssl3_SendHelloRequest(sslSocket *ss) /* * Called from: - * ssl3_HandleClientHello() + * ssl3_HandleClientHello() */ static SECComparison ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) @@ -7690,10 +7875,10 @@ ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2) /* Sets memory error when returning NULL. * Called from: - * ssl3_SendClientHello() - * ssl3_HandleServerHello() - * ssl3_HandleClientHello() - * ssl3_HandleV2ClientHello() + * ssl3_SendClientHello() + * ssl3_HandleServerHello() + * ssl3_HandleClientHello() + * ssl3_HandleV2ClientHello() */ sslSessionID * ssl3_NewSessionID(sslSocket *ss, PRBool is_server) @@ -7702,14 +7887,14 @@ ssl3_NewSessionID(sslSocket *ss, PRBool is_server) sid = PORT_ZNew(sslSessionID); if (sid == NULL) - return sid; + return sid; if (is_server) { - const SECItem * srvName; - SECStatus rv = SECSuccess; + const SECItem *srvName; + SECStatus rv = SECSuccess; - ssl_GetSpecReadLock(ss); /********************************/ - srvName = &ss->ssl3.prSpec->srvVirtName; + ssl_GetSpecReadLock(ss); /********************************/ + srvName = &ss->ssl3.hs.srvVirtName; if (srvName->len && srvName->data) { rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName); } @@ -7719,34 +7904,34 @@ ssl3_NewSessionID(sslSocket *ss, PRBool is_server) 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->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->u.ssl3.keys.resumable = PR_TRUE; - sid->u.ssl3.policy = SSL_ALLOWED; + sid->u.ssl3.policy = SSL_ALLOWED; sid->u.ssl3.clientWriteKey = NULL; sid->u.ssl3.serverWriteKey = NULL; 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; - } + 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; } @@ -7756,95 +7941,302 @@ static SECStatus ssl3_SendServerHelloSequence(sslSocket *ss) { const ssl3KEADef *kea_def; - SECStatus rv; + SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + 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. */ + return rv; /* err code is set. */ } rv = ssl3_SendCertificate(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ + return rv; /* error code is set. */ } rv = ssl3_SendCertificateStatus(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ + 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; - ss->ssl3.hs.usedStepDownKey = PR_FALSE; - - if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) { - /* see if we can legally use the key in the cert. */ - unsigned int keyLen; /* bytes */ - - keyLen = PK11_GetPrivateModulusLen( - ss->serverCerts[kea_def->exchKeyType].SERVERKEY); - - if (keyLen > 0 && - keyLen * BPB <= kea_def->key_size_limit ) { - /* XXX AND cert is not signing only!! */ - /* just fall through and use it. */ - } else if (ss->stepDownKeyPair != NULL) { - ss->ssl3.hs.usedStepDownKey = PR_TRUE; - rv = ssl3_SendServerKeyExchange(ss); - if (rv != SECSuccess) { - return rv; /* err code was set. */ - } - } else { -#ifndef HACKED_EXPORT_SERVER - PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED); - return rv; -#endif - } - } else if (kea_def->ephemeral) { + + if (kea_def->ephemeral) { rv = ssl3_SendServerKeyExchange(ss); if (rv != SECSuccess) { - return rv; /* err code was set. */ + 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_SendCertificateRequest(ss); + if (rv != SECSuccess) { + return rv; /* err code is set. */ + } } rv = ssl3_SendServerHelloDone(ss); if (rv != SECSuccess) { - return rv; /* err code is set. */ + return rv; /* err code is set. */ } ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert - : wait_client_key; + : wait_client_key; return SECSuccess; } /* An empty TLS Renegotiation Info (RI) extension */ -static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00}; +static const PRUint8 emptyRIext[5] = { 0xff, 0x01, 0x00, 0x01, 0x00 }; static PRBool -ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea) -{ - switch (kea) { - case kea_dhe_dss: - case kea_dhe_dss_export: - case kea_dh_dss_export: - case kea_dh_dss: - /* TODO: Fix session tickets for DSS. The server code rejects the - * session ticket received from the client. Bug 1174677 */ - return PR_FALSE; - default: - return PR_TRUE; - }; +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; +} + +/* 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) +{ + int j; + int i; + + for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; + SSLVersionRange vrange = { ss->version, ss->version }; + if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) { + continue; + } + 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) { + return ssl3_SetCipherSuite(ss, suite_i, initHashes); + } + } + } + return SECFailure; +} + +/* + * 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]; + int configedCiphers; + 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; + } + configedCiphers = ssl3_config_match_init(ss); + if (configedCiphers <= 0) { + /* no ciphers are working/supported */ + errCode = PORT_GetError(); + desc = handshake_failure; + 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, + ssl3_SendServerNameXtn); + } 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; + + /* 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 (cert->certType.authType != kea_def->authKeyType) { + continue; + } + if ((cert->certType.authType == ssl_auth_ecdsa || + cert->certType.authType == ssl_auth_ecdh_rsa || + cert->certType.authType == ssl_auth_ecdh_ecdsa) && + !ssl_NamedGroupEnabled(ss, cert->certType.namedCurve)) { + continue; + } + + /* Found one. */ + ss->sec.serverCert = cert; + ss->sec.authType = cert->certType.authType; + ss->sec.authKeyBits = cert->serverKeyBits; + + /* Don't pick a signature scheme if we aren't going to use it. */ + if (kea_def->signKeyType == nullKey) { + return SECSuccess; + } + return ssl3_PickServerSignatureScheme(ss); + } + + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return SECFailure; } /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete @@ -7854,29 +8246,27 @@ ssl3_KEAAllowsSessionTicket(SSL3KeyExchangeAlgorithm kea) static SECStatus ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - sslSessionID * sid = NULL; - PRInt32 tmp; - unsigned int i; - int j; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; - SSL3AlertDescription desc = illegal_parameter; - SSL3AlertLevel level = alert_fatal; + sslSessionID *sid = NULL; + PRInt32 tmp; + unsigned int i; + SECStatus rv; + int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; + SSL3AlertDescription desc = illegal_parameter; + SSL3AlertLevel level = alert_fatal; SSL3ProtocolVersion version; - SECItem sidBytes = {siBuffer, NULL, 0}; - SECItem cookieBytes = {siBuffer, NULL, 0}; - SECItem suites = {siBuffer, NULL, 0}; - SECItem comps = {siBuffer, NULL, 0}; - PRBool haveSpecWriteLock = PR_FALSE; - PRBool haveXmitBufLock = PR_FALSE; - PRBool canOfferSessionTicket = PR_FALSE; + TLSExtension *versionExtension; + SECItem sidBytes = { siBuffer, NULL, 0 }; + SECItem cookieBytes = { siBuffer, NULL, 0 }; + SECItem suites = { siBuffer, NULL, 0 }; + SECItem comps = { siBuffer, NULL, 0 }; + PRBool isTLS13; SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - PORT_Assert( ss->ssl3.initialized ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.initialized); ss->ssl3.hs.preliminaryInfo = 0; if (!ss->sec.isServer || @@ -7886,126 +8276,82 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; goto alert_loser; } - if (ss->ssl3.hs.ws == idle_handshake && - ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { - desc = no_renegotiation; - level = alert_warning; - errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; - 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; + } } /* Get peer name of client */ rv = ssl_GetPeerInfo(ss); if (rv != SECSuccess) { - return rv; /* error code is set. */ - } - - /* Clearing the handshake pointers so that ssl_Do1stHandshake won't - * call ssl2_HandleMessage. - * - * The issue here is that TLS ordinarily starts out in - * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility - * code paths. That function zeroes these next pointers. But with DTLS, - * we don't even try to do the v2 ClientHello so we skip that function - * and need to reset these values here. - */ - if (IS_DTLS(ss)) { - ss->nextHandshake = 0; - ss->securityHandshake = 0; + return rv; /* error code is set. */ } /* We might be starting session renegotiation in which case we should * clear previous state. */ - PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); + ssl3_ResetExtensionData(&ss->xtnData); ss->statelessResume = PR_FALSE; if (IS_DTLS(ss)) { - dtls_RehandshakeCleanup(ss); + dtls_RehandshakeCleanup(ss); } tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); if (tmp < 0) - goto loser; /* malformed, alert already sent */ + goto loser; /* malformed, alert already sent */ - /* Translate the version */ + /* Translate the version. */ if (IS_DTLS(ss)) { - ss->clientHelloVersion = version = - dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); + ss->clientHelloVersion = version = + dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp); } else { - ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; + ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp; } - rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); - if (rv != SECSuccess) { - desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version - : handshake_failure; - errCode = SSL_ERROR_UNSUPPORTED_VERSION; - goto alert_loser; - } - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; - - rv = ssl3_InitHandshakeHashes(ss); - if (rv != SECSuccess) { - desc = internal_error; - errCode = PORT_GetError(); - goto alert_loser; - } - - /* grab the client random data. */ + /* Grab the client random data. */ rv = ssl3_ConsumeHandshake( - ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); + ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } - /* grab the client's SID, if present. */ + /* Grab the client's SID, if present. */ rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } - /* grab the client's cookie, if present. */ + /* Grab the client's cookie, if present. */ if (IS_DTLS(ss)) { - rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed */ - } + rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length); + if (rv != SECSuccess) { + goto loser; /* malformed */ + } } - /* grab the list of cipher suites. */ + /* Grab the list of cipher suites. */ rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + 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->clientHelloVersion) { - 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; - } - } - - /* grab the list of compression methods. */ + /* Grab the list of compression methods. */ rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed */ + goto loser; /* malformed */ } - /* TLS 1.3 requires that compression be empty */ - if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { - if (comps.len != 1 || comps.data[0] != ssl_compression_null) { - goto loser; - } - } - desc = handshake_failure; - /* 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. @@ -8014,280 +8360,384 @@ ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length) */ if (length) { - /* Get length of hello extensions */ - PRInt32 extension_length; - extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); - if (extension_length < 0) { - goto loser; /* alert already sent */ - } - if (extension_length != length) { - ssl3_DecodeError(ss); /* send alert */ - goto loser; - } - rv = ssl3_HandleHelloExtensions(ss, &b, &length); - if (rv != SECSuccess) { - goto loser; /* malformed */ - } + /* Get length of hello extensions */ + PRInt32 extension_length; + extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); + if (extension_length < 0) { + goto loser; /* alert already sent */ + } + if (extension_length != length) { + ssl3_DecodeError(ss); /* send alert */ + goto 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(version, + SSL_LIBRARY_VERSION_TLS_1_2), + PR_TRUE); + if (rv != SECSuccess) { + desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version + : handshake_failure; + errCode = SSL_ERROR_UNSUPPORTED_VERSION; + goto alert_loser; + } + } + isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; + ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; + + /* You can't resume TLS 1.3 like this. */ + if (isTLS13 && sidBytes.len) { + goto alert_loser; + } + + /* Generate the Server Random now so it is available + * when we process the ClientKeyShare in TLS 1.3 */ + rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); + if (rv != SECSuccess) { + errCode = SSL_ERROR_GENERATE_RANDOM_FAILURE; + goto loser; + } + +#ifndef TLS_1_3_DRAFT_VERSION + /* + * [draft-ietf-tls-tls13-11 Section 6.3.1.1]. + * TLS 1.3 server implementations which respond to a ClientHello with a + * client_version indicating TLS 1.2 or below MUST set the last eight + * bytes of their Random value to the bytes: + * + * 44 4F 57 4E 47 52 44 01 + * + * TLS 1.2 server implementations which respond to a ClientHello with a + * client_version indicating TLS 1.1 or below SHOULD set the last eight + * bytes of their Random value to the bytes: + * + * 44 4F 57 4E 47 52 44 00 + * + * TODO(ekr@rtfm.com): Note this change was not added in the SSLv2 + * compat processing code since that will most likely be removed before + * we ship the final version of TLS 1.3. Bug 1306672. + */ + if (ss->vrange.max > ss->version) { + unsigned char *downgrade_sentinel = + ss->ssl3.hs.server_random.rand + + SSL3_RANDOM_LENGTH - sizeof(tls13_downgrade_random); + + switch (ss->vrange.max) { + case SSL_LIBRARY_VERSION_TLS_1_3: + PORT_Memcpy(downgrade_sentinel, + tls13_downgrade_random, + sizeof(tls13_downgrade_random)); + break; + case SSL_LIBRARY_VERSION_TLS_1_2: + PORT_Memcpy(downgrade_sentinel, + tls12_downgrade_random, + sizeof(tls12_downgrade_random)); + break; + default: + /* Do not change random. */ + break; + } + } +#endif + + /* Now parse the rest of the extensions. */ + rv = ssl3_HandleParsedExtensions(ss, client_hello); + if (rv != SECSuccess) { + 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->clientHelloVersion) { + 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; + } + } + + /* TLS 1.3 requires that compression only include null. */ + if (isTLS13) { + if (comps.len != 1 || comps.data[0] != ssl_compression_null) { + 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) { - SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; - PRUint32 L2 = sizeof emptyRIext; - (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); - break; - } - } + /* 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) { + SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext; + PRUint32 L2 = sizeof emptyRIext; + (void)ssl3_HandleExtensions(ss, &b2, &L2, client_hello); + break; + } + } + } + /* This is a second check for TLS 1.3 and re-handshake to stop us + * from re-handshake up to TLS 1.3, so it happens after version + * negotiation. */ + if (ss->firstHsDone && ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + desc = unexpected_message; + errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED; + goto alert_loser; } 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->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; + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { + desc = handshake_failure; + errCode = SSL_ERROR_UNSAFE_NEGOTIATION; + goto alert_loser; } - /* We do stateful resumes only if 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. + /* 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 (!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)(&ss->sec.ci.peer, sidBytes.data, - sidBytes.len, ss->dbHandle); - } else { - errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED; - goto loser; - } - } + if ((ss->version < SSL_LIBRARY_VERSION_TLS_1_3) && + (!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)(&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.) - */ - 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; + /* 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; } - /* We only send a session ticket extension if the client supports - * the extension and we are unable to do either a stateful or - * stateless 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) && sid == NULL) { - canOfferSessionTicket = PR_TRUE; + /* 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 ); - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - } - } - -#ifndef NSS_DISABLE_ECC - /* Disable any ECC cipher suites for which we have no cert. */ - ssl3_FilterECCipherSuitesByServerCerts(ss); -#endif + /* 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); + ss->sec.uncache(sid); + ssl_FreeSID(sid); + sid = NULL; + } + } if (IS_DTLS(ss)) { - ssl3_DisableNonDTLSSuites(ss); + ssl3_DisableNonDTLSSuites(ss); } #ifdef PARANOID /* Look for a matching cipher suite. */ j = ssl3_config_match_init(ss); - if (j <= 0) { /* no ciphers are working/supported by PK11 */ - errCode = PORT_GetError(); /* error code is already set. */ - goto alert_loser; + if (j <= 0) { /* no ciphers are working/supported by PK11 */ + errCode = PORT_GetError(); /* error code is already set. */ + goto alert_loser; } #endif + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + rv = tls13_HandleClientHelloPart2(ss, &suites, sid); + } else { + rv = ssl3_HandleClientHelloPart2(ss, &suites, &comps, sid); + } + if (rv != SECSuccess) { + errCode = PORT_GetError(); + goto loser; + } + return SECSuccess; + +alert_loser: + (void)SSL3_SendAlert(ss, level, desc); +/* FALLTHRU */ +loser: + PORT_SetError(errCode); + return SECFailure; +} + +static SECStatus +ssl3_HandleClientHelloPart2(sslSocket *ss, + SECItem *suites, + SECItem *comps, + sslSessionID *sid) +{ + PRBool haveSpecWriteLock = PR_FALSE; + PRBool haveXmitBufLock = PR_FALSE; + int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; + SSL3AlertDescription desc = illegal_parameter; + SECStatus rv; + unsigned int i; + int j; + /* If we already have a session for this client, be sure to pick the ** same cipher suite and compression method we picked before. ** This is not a loop, despite appearances. */ - if (sid) do { - ssl3CipherSuiteCfg *suite; + if (sid) + do { + ssl3CipherSuiteCfg *suite; #ifdef PARANOID - SSLVersionRange vrange = {ss->version, ss->version}; + SSLVersionRange vrange = { ss->version, ss->version }; #endif - /* Check that the cached compression method is still enabled. */ - if (!compressionEnabled(ss, sid->u.ssl3.compression)) - break; - - /* Check that the cached compression method is in the client's list */ - for (i = 0; i < comps.len; i++) { - if (comps.data[i] == sid->u.ssl3.compression) - break; - } - if (i == comps.len) - break; - - 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; + /* Check that the cached compression method is still enabled. */ + if (!ssl_CompressionEnabled(ss, sid->u.ssl3.compression)) + break; + + /* Check that the cached compression method is in the client's list */ + for (i = 0; i < comps->len; i++) { + if (comps->data[i] == sid->u.ssl3.compression) + break; + } + if (i == comps->len) + break; + + 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; #ifdef PARANOID - /* Double check that the cached cipher suite is still enabled, - * implemented, and allowed by policy. Might have been disabled. - * The product policy won't change during the process lifetime. - * Implemented ("isPresent") shouldn't change for servers. - */ - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) - break; + /* Double check that the cached cipher suite is still enabled, + * implemented, and allowed by policy. Might have been disabled. + * The product policy won't change during the process lifetime. + * Implemented ("isPresent") shouldn't change for servers. + */ + if (!config_match(suite, ss->ssl3.policy, &vrange, ss)) + break; #else - if (!suite->enabled) - break; + if (!suite->enabled) + break; #endif - /* Double check that the cached cipher suite is in the client's list */ - 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->cipher_suite; - ss->ssl3.hs.suite_def = - ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - - /* Use the cached compression method. */ - ss->ssl3.hs.compression = sid->u.ssl3.compression; - goto compression_found; - } - } - } while (0); - - /* START A NEW SESSION */ + /* 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) { + rv = ssl3_SetCipherSuite(ss, suite_i, PR_TRUE); + if (rv != SECSuccess) { + desc = internal_error; + errCode = PORT_GetError(); + goto alert_loser; + } + + /* Use the cached compression method. */ + ss->ssl3.hs.compression = + sid->u.ssl3.compression; + goto compression_found; + } + } + } while (0); +/* START A NEW SESSION */ #ifndef PARANOID /* Look for a matching cipher suite. */ j = ssl3_config_match_init(ss); - if (j <= 0) { /* no ciphers are working/supported by PK11 */ - errCode = PORT_GetError(); /* error code is already set. */ - goto alert_loser; + if (j <= 0) { /* no ciphers are working/supported by PK11 */ + desc = internal_error; + errCode = PORT_GetError(); /* error code is already set. */ + goto alert_loser; } #endif - /* 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. - */ - for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; - SSLVersionRange vrange = {ss->version, ss->version}; - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange, ss)) { - continue; - } - 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->cipher_suite; - ss->ssl3.hs.suite_def = - ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - goto suite_found; - } - } - } - errCode = SSL_ERROR_NO_CYPHER_OVERLAP; - goto alert_loser; - -suite_found: - if (canOfferSessionTicket) - canOfferSessionTicket = ssl3_KEAAllowsSessionTicket( - ss->ssl3.hs.suite_def->key_exchange_alg); - - if (canOfferSessionTicket) { - ssl3_RegisterServerHelloExtensionSender(ss, - ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn); + rv = ssl3_NegotiateCipherSuite(ss, suites, PR_TRUE); + if (rv != SECSuccess) { + desc = handshake_failure; + errCode = SSL_ERROR_NO_CYPHER_OVERLAP; + goto alert_loser; } /* Select a compression algorithm. */ - for (i = 0; i < comps.len; i++) { - if (!compressionEnabled(ss, comps.data[i])) - continue; - for (j = 0; j < compressionMethodsCount; j++) { - if (comps.data[i] == compressions[j]) { - ss->ssl3.hs.compression = - (SSLCompressionMethod)compressions[j]; - goto compression_found; - } - } + for (i = 0; i < comps->len; i++) { + SSLCompressionMethod method = (SSLCompressionMethod)comps->data[i]; + if (!ssl_CompressionEnabled(ss, method)) + continue; + for (j = 0; j < ssl_compression_method_count; j++) { + if (method == ssl_compression_methods[j]) { + ss->ssl3.hs.compression = ssl_compression_methods[j]; + goto compression_found; + } + } } errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP; - /* null compression must be supported */ + /* null compression must be supported */ goto alert_loser; compression_found: - suites.data = NULL; - comps.data = NULL; - - ss->sec.send = ssl3_SendApplicationData; + suites->data = NULL; + comps->data = NULL; /* If there are any failures while processing the old sid, * we don't consider them to be errors. Instead, We just behave @@ -8295,374 +8745,249 @@ compression_found: * The exception here is attempts to resume extended_master_secret * sessions without the extension, which causes an alert. */ - if (sid != NULL) do { - ssl3CipherSpec *pwSpec; - SECItem wrappedMS; /* wrapped key */ - - if (sid->version != ss->version || - sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || - sid->u.ssl3.compression != ss->ssl3.hs.compression) { - break; /* not an error */ - } - - /* [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) { - if (ss->sec.uncache) - ss->sec.uncache(ss->sec.ci.sid); - 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.... */ - - ssl_GetSpecWriteLock(ss); haveSpecWriteLock = PR_TRUE; - pwSpec = ss->ssl3.pwSpec; - if (sid->u.ssl3.keys.msIsWrapped) { - PK11SymKey * wrapKey; /* wrapping key */ - CK_FLAGS keyFlags = 0; -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - /* we cannot restart a non-bypass session in a - ** bypass socket. - */ - break; - } -#endif - - wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType, - sid->u.ssl3.masterWrapMech, - ss->pkcs11PinArg); - if (!wrapKey) { - /* we have a SID cache entry, but no wrapping key for it??? */ - break; - } - - if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ - keyFlags = CKF_SIGN | CKF_VERIFY; - } - - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - - /* unwrap the master secret. */ - pwSpec->master_secret = - PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, - NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, - CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); - PK11_FreeSymKey(wrapKey); - if (pwSpec->master_secret == NULL) { - break; /* not an error */ - } -#ifndef NO_PKCS11_BYPASS - } else if (ss->opt.bypassPKCS11) { - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len); - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = wrappedMS.len; -#endif - } else { - /* We CAN restart a bypass session in a non-bypass socket. */ - /* need to import the raw master secret to session object */ - PK11SlotInfo * slot; - wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; - wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; - slot = PK11_GetInternalSlot(); - pwSpec->master_secret = - PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, - PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, - NULL); - PK11_FreeSlot(slot); - if (pwSpec->master_secret == NULL) { - 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. - * - * XXX make sure compression still matches - */ - 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.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; - - /* server sids don't remember the server cert we previously sent, - ** but they do remember the kea type 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.localCert = - CERT_DupCertificate(ss->serverCerts[sid->keaType].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.pwSpec->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; + if (sid != NULL) + do { + ssl3CipherSpec *pwSpec; + SECItem wrappedMS; /* wrapped key */ + const sslServerCert *serverCert; + + if (sid->version != ss->version || + sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite || + sid->u.ssl3.compression != ss->ssl3.hs.compression) { + break; /* not an error */ } - } - - /* Clean up sni name array */ - if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) && - ss->xtnData.sniNameArr) { - PORT_Free(ss->xtnData.sniNameArr); - ss->xtnData.sniNameArr = NULL; - ss->xtnData.sniNameArrSize = 0; - } - - ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE; - - rv = ssl3_SendServerHello(ss); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; - } - - if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; - } - - /* NULL value for PMS because we are re-using the old MS */ - rv = ssl3_InitPendingCipherSpec(ss, NULL); - 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); - haveXmitBufLock = PR_FALSE; - } - - return SECSuccess; - } while (0); - - if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; - } - - if (sid) { /* we had a sid, but it's no longer valid, free it */ - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok ); - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - } - SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses ); - - if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) { - int ret = 0; - 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; + serverCert = ssl_FindServerCert(ss, &sid->certType); + if (!serverCert || !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; - } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) { - SECStatus rv = SECSuccess; - SECItem * cwsName, *pwsName; + } - ssl_GetSpecWriteLock(ss); /*******************************/ - pwsName = &ss->ssl3.pwSpec->srvVirtName; - cwsName = &ss->ssl3.cwSpec->srvVirtName; -#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS - /* 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; - } + /* [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 */ } -#endif - if (pwsName->data) { - SECITEM_FreeItem(pwsName, PR_FALSE); + } 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 (cwsName->data) { - rv = SECITEM_CopyItem(NULL, pwsName, cwsName); + } + + if (ss->sec.ci.sid) { + ss->sec.uncache(ss->sec.ci.sid); + PORT_Assert(ss->sec.ci.sid != sid); /* should be impossible, but ... */ + if (ss->sec.ci.sid != sid) { + ssl_FreeSID(ss->sec.ci.sid); } - ssl_ReleaseSpecWriteLock(ss); /**************************/ - if (rv != SECSuccess) { - errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; - desc = internal_error; - ret = SSL_SNI_SEND_ALERT; + ss->sec.ci.sid = NULL; + } + /* we need to resurrect the master secret.... */ + + ssl_GetSpecWriteLock(ss); + haveSpecWriteLock = PR_TRUE; + pwSpec = ss->ssl3.pwSpec; + if (sid->u.ssl3.keys.msIsWrapped) { + PK11SymKey *wrapKey; /* wrapping key */ + CK_FLAGS keyFlags = 0; + + wrapKey = ssl3_GetWrappingKey(ss, NULL, serverCert, + sid->u.ssl3.masterWrapMech, + ss->pkcs11PinArg); + if (!wrapKey) { + /* we have a SID cache entry, but no wrapping key for it??? */ 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]; - int configedCiphers; - SECItem * pwsName; - /* get rid of the old name and save the newly picked. */ - /* This code is protected by ssl3HandshakeLock. */ - ssl_GetSpecWriteLock(ss); /*******************************/ -#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS - /* not allow name change on the 2d HS */ - if (ss->firstHsDone) { - SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName; - if (ssl3_ServerNameCompare(name, cwsName)) { - ssl_ReleaseSpecWriteLock(ss); /******************/ - errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; - desc = handshake_failure; - ret = SSL_SNI_SEND_ALERT; - break; - } + if (ss->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ + keyFlags = CKF_SIGN | CKF_VERIFY; } -#endif - pwsName = &ss->ssl3.pwSpec->srvVirtName; + + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + + /* unwrap the master secret. */ + pwSpec->master_secret = + PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech, + NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE, + CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags); + PK11_FreeSymKey(wrapKey); + if (pwSpec->master_secret == NULL) { + break; /* not an error */ + } + } else { + /* need to import the raw master secret to session object */ + PK11SlotInfo *slot; + wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret; + wrappedMS.len = sid->u.ssl3.keys.wrapped_master_secret_len; + slot = PK11_GetInternalSlot(); + pwSpec->master_secret = + PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE, + PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS, + NULL); + PK11_FreeSlot(slot); + if (pwSpec->master_secret == NULL) { + 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. + * + * XXX make sure compression still matches + */ + 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; + + /* 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 = serverCert; + ss->sec.localCert = CERT_DupCertificate(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, name); - ssl_ReleaseSpecWriteLock(ss); /***************************/ + rv = SECITEM_CopyItem(NULL, pwsName, sidName); if (rv != SECSuccess) { - errCode = SSL_ERROR_INTERNAL_ERROR_ALERT; - desc = internal_error; - ret = SSL_SNI_SEND_ALERT; - break; - } - configedCiphers = ssl3_config_match_init(ss); - if (configedCiphers <= 0) { - /* no ciphers are working/supported */ errCode = PORT_GetError(); - desc = handshake_failure; - ret = SSL_SNI_SEND_ALERT; - break; + desc = internal_error; + goto alert_loser; } - /* Need to tell the client that application has picked - * the name from the offered list and reconfigured the socket. - */ - ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn, - ssl3_SendServerNameXtn); - } 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; } + + /* 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; + } + + if (haveSpecWriteLock) { + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; + } + + /* NULL value for PMS because we are re-using the old MS */ + rv = ssl3_InitPendingCipherSpec(ss, NULL); + 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); - /* Free sniNameArr. The data that each SECItem in the array - * points into is the data from the input buffer "b". It will - * not be available outside the scope of this or it's child - * functions.*/ - if (ss->xtnData.sniNameArr) { - PORT_Free(ss->xtnData.sniNameArr); - ss->xtnData.sniNameArr = NULL; - ss->xtnData.sniNameArrSize = 0; - } - if (ret <= SSL_SNI_SEND_ALERT) { - /* desc and errCode should be set. */ - goto alert_loser; - } + + if (haveSpecWriteLock) { + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; } -#ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS - else 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.cwSpec->srvVirtName.data) { - passed = PR_FALSE; - } - ssl_ReleaseSpecReadLock(ss); /***************************/ - if (!passed) { - errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT; - desc = handshake_failure; - goto alert_loser; - } + + if (sid) { /* we had a sid, but it's no longer valid, free it */ + SSL_AtomicIncrementLong(&ssl3stats.hch_sid_cache_not_ok); + ss->sec.uncache(sid); + 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, + ssl3_SendSessionTicketXtn); + } + + 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; } -#endif sid = ssl3_NewSessionID(ss, PR_TRUE); if (sid == NULL) { - errCode = PORT_GetError(); - goto loser; /* memory error is set. */ + 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); + ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn); ss->ssl3.hs.isResuming = PR_FALSE; + ssl_GetXmitBufLock(ss); rv = ssl3_SendServerHelloSequence(ss); ssl_ReleaseXmitBufLock(ss); @@ -8673,28 +8998,30 @@ compression_found: } if (haveXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); - haveXmitBufLock = PR_FALSE; + ssl_ReleaseXmitBufLock(ss); } return SECSuccess; alert_loser: if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; + ssl_ReleaseSpecWriteLock(ss); + haveSpecWriteLock = PR_FALSE; } - (void)SSL3_SendAlert(ss, level, desc); - /* FALLTHRU */ + (void)SSL3_SendAlert(ss, alert_fatal, desc); +/* FALLTHRU */ loser: + if (sid && sid != ss->sec.ci.sid) { + ss->sec.uncache(sid); + ssl_FreeSID(sid); + } + if (haveSpecWriteLock) { - ssl_ReleaseSpecWriteLock(ss); - haveSpecWriteLock = PR_FALSE; + ssl_ReleaseSpecWriteLock(ss); } if (haveXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); - haveXmitBufLock = PR_FALSE; + ssl_ReleaseXmitBufLock(ss); } PORT_SetError(errCode); @@ -8704,107 +9031,111 @@ loser: /* * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes * in asking to use the V3 handshake. - * Called from ssl2_HandleClientHelloMessage() in sslcon.c */ SECStatus -ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) +ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length, + PRUint8 padding) { - sslSessionID * sid = NULL; - unsigned char * suites; - unsigned char * random; + sslSessionID *sid = NULL; + unsigned char *suites; + unsigned char *random; SSL3ProtocolVersion version; - SECStatus rv; - int i; - int j; - int sid_length; - int suite_length; - int rand_length; - int errCode = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO; - SSL3AlertDescription desc = handshake_failure; + SECStatus rv; + int i; + int j; + int sid_length; + int suite_length; + 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) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); ssl_GetSSL3HandshakeLock(ss); - PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); + ssl3_ResetExtensionData(&ss->xtnData); + + version = (buffer[1] << 8) | buffer[2]; + if (version < SSL_LIBRARY_VERSION_3_0) { + goto loser; + } rv = ssl3_InitState(ss); if (rv != SECSuccess) { - ssl_ReleaseSSL3HandshakeLock(ss); - return rv; /* ssl3_InitState has set the error code. */ + ssl_ReleaseSSL3HandshakeLock(ss); + return rv; /* ssl3_InitState has set the error code. */ } rv = ssl3_RestartHandshakeHashes(ss); if (rv != SECSuccess) { - ssl_ReleaseSSL3HandshakeLock(ss); - return rv; + ssl_ReleaseSSL3HandshakeLock(ss); + return rv; } if (ss->ssl3.hs.ws != wait_client_hello) { - desc = unexpected_message; - errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; - goto loser; /* alert_loser */ + desc = unexpected_message; + errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO; + goto alert_loser; } - version = (buffer[1] << 8) | buffer[2]; - suite_length = (buffer[3] << 8) | buffer[4]; - sid_length = (buffer[5] << 8) | buffer[6]; - rand_length = (buffer[7] << 8) | buffer[8]; + 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; - 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; + 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; } - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; - rv = ssl3_InitHandshakeHashes(ss); + rv = ssl3_NegotiateVersion(ss, version, PR_TRUE); if (rv != SECSuccess) { - desc = internal_error; - errCode = PORT_GetError(); - goto alert_loser; + /* 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; } + ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_version; /* if we get a non-zero SID, just ignore it. */ - if (length != - SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) { - SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d", - SSL_GETPID(), ss->fd, length, - SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + - rand_length)); - goto loser; /* malformed */ /* alert_loser */ + 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) { - goto loser; /* malformed */ /* alert_loser */ + 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.rand[SSL3_RANDOM_LENGTH - rand_length], - random, rand_length); + &ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length], + random, rand_length); PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0], - SSL3_RANDOM_LENGTH)); -#ifndef NSS_DISABLE_ECC - /* Disable any ECC cipher suites for which we have no cert. */ - ssl3_FilterECCipherSuitesByServerCerts(ss); -#endif + SSL3_RANDOM_LENGTH)); i = ssl3_config_match_init(ss); if (i <= 0) { - errCode = PORT_GetError(); /* error code is already set. */ - goto alert_loser; + errCode = PORT_GetError(); /* error code is already set. */ + goto alert_loser; } /* Select a cipher suite. @@ -8815,56 +9146,77 @@ ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length) ** See the comments about export cipher suites in ssl3_HandleClientHello(). */ for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; - SSLVersionRange vrange = {ss->version, ss->version}; - if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &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->cipher_suite; - ss->ssl3.hs.suite_def = - ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite); - ss->ssl3.hs.preliminaryInfo |= ssl_preinfo_cipher_suite; - goto suite_found; - } - } + ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j]; + SSLVersionRange vrange = { ss->version, ss->version }; + if (!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) { + rv = ssl3_SetCipherSuite(ss, suite_i, 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: - /* Look for the SCSV, and if found, treat it just like an empty RI + /* 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) { - SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext; - PRUint32 L2 = sizeof emptyRIext; - (void)ssl3_HandleHelloExtensions(ss, &b2, &L2); - break; - } + 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) { + SSL3Opaque *b2 = (SSL3Opaque *)emptyRIext; + PRUint32 L2 = sizeof emptyRIext; + (void)ssl3_HandleExtensions(ss, &b2, &L2, 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; + !ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) { + desc = handshake_failure; + errCode = SSL_ERROR_UNSAFE_NEGOTIATION; + goto alert_loser; } ss->ssl3.hs.compression = ssl_compression_null; - ss->sec.send = ssl3_SendApplicationData; + + 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 ); + 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. */ + 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 */ @@ -8872,25 +9224,18 @@ suite_found: /* 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; + errCode = PORT_GetError(); + goto loser; } ssl_GetXmitBufLock(ss); rv = ssl3_SendServerHelloSequence(ss); ssl_ReleaseXmitBufLock(ss); if (rv != SECSuccess) { - errCode = PORT_GetError(); - goto loser; + errCode = PORT_GetError(); + goto loser; } - /* XXX_1 The call stack to here is: - * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here. - * ssl2_HandleClientHelloMessage returns whatever we return here. - * ssl_Do1stHandshake will continue looping if it gets back either - * SECSuccess or SECWouldBlock. - * SECSuccess is preferable here. See XXX_1 in sslgathr.c. - */ ssl_ReleaseSSL3HandshakeLock(ss); return SECSuccess; @@ -8905,150 +9250,135 @@ loser: /* 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) +** ssl3_SendServerHelloSequence <- ssl3_HandleClientHello (new session), +** ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session) */ -static SECStatus +SECStatus ssl3_SendServerHello(sslSocket *ss) { sslSessionID *sid; - SECStatus rv; - PRUint32 maxBytes = 65535; - PRUint32 length; - PRInt32 extensions_len = 0; + SECStatus rv; + PRUint32 maxBytes = 65535; + PRUint32 length; + PRInt32 extensions_len = 0; SSL3ProtocolVersion version; SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(), - ss->fd)); + ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - - if (!IS_DTLS(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; - } - } else { - PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } + 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; } sid = ss->sec.ci.sid; - extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, - &ss->xtnData.serverSenders[0]); + extensions_len = ssl3_CallHelloExtensionSenders( + ss, PR_FALSE, maxBytes, &ss->xtnData.serverHelloSenders[0]); if (extensions_len > 0) - extensions_len += 2; /* Add sizeof total extension length */ + extensions_len += 2; /* Add sizeof total extension length */ + + /* TLS 1.3 doesn't use the session_id or compression_method + * fields in the ServerHello. */ + length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH; + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + length += 1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength); + } + length += sizeof(ssl3CipherSuite); + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + length += 1; /* Compression */ + } + length += extensions_len; - length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 + - ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) + - sizeof(ssl3CipherSuite) + 1 + extensions_len; rv = ssl3_AppendHandshakeHeader(ss, server_hello, length); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } - if (IS_DTLS(ss)) { - version = dtls_TLSVersionToDTLSVersion(ss->version); + if (IS_DTLS(ss) && ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + version = dtls_TLSVersionToDTLSVersion(ss->version); } else { - version = ss->version; + version = tls13_EncodeDraftVersion(ss->version); } rv = ssl3_AppendHandshakeNumber(ss, version, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ - } - rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE); - return rv; + return rv; /* err set by AppendHandshake. */ } + /* Random already generated in ssl3_HandleClientHello */ rv = ssl3_AppendHandshake( - ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); + ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } - if (sid) - rv = ssl3_AppendHandshakeVariable( - ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); - else - rv = ssl3_AppendHandshakeNumber(ss, 0, 1); - if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + if (sid) { + rv = ssl3_AppendHandshakeVariable( + ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1); + } else { + rv = ssl3_AppendHandshakeNumber(ss, 0, 1); + } + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } } rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } - rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); - if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } } if (extensions_len) { - PRInt32 sent_len; - - extensions_len -= 2; - rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); - if (rv != SECSuccess) - return rv; /* err set by ssl3_SetupPendingCipherSpec */ - sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, - &ss->xtnData.serverSenders[0]); + PRInt32 sent_len; + + extensions_len -= 2; + rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); + if (rv != SECSuccess) + return rv; /* err set by ssl3_AppendHandshakeNumber */ + sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len, + &ss->xtnData.serverHelloSenders[0]); PORT_Assert(sent_len == extensions_len); - if (sent_len != extensions_len) { - if (sent_len >= 0) - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return SECFailure; - } + if (sent_len != extensions_len) { + if (sent_len >= 0) + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } } - rv = ssl3_SetupPendingCipherSpec(ss); - if (rv != SECSuccess) { - return rv; /* err set by ssl3_SetupPendingCipherSpec */ + + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + rv = ssl3_SetupPendingCipherSpec(ss); + if (rv != SECSuccess) { + return rv; /* err set by ssl3_SetupPendingCipherSpec */ + } } return SECSuccess; } -static SECStatus -ssl3_PickSignatureHashAlgorithm(sslSocket *ss, - SSLSignatureAndHashAlg* out); - -static SECStatus -ssl3_SendDHServerKeyExchange(sslSocket *ss) +SECStatus +ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef, + const ssl3DHParams *params, + sslEphemeralKeyPair **keyPair) { - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - SECStatus rv = SECFailure; - int length; - PRBool isTLS; - SECItem signed_hash = {siBuffer, NULL, 0}; - SSL3Hashes hashes; - SSLSignatureAndHashAlg sigAndHash; SECKEYDHParams dhParam; - - ssl3KeyPair *keyPair = NULL; - SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ + SECKEYPublicKey *pubKey = NULL; /* Ephemeral DH key */ SECKEYPrivateKey *privKey = NULL; /* Ephemeral DH key */ - int certIndex = -1; - - 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; - } + sslEphemeralKeyPair *pair; - dhParam.prime.data = ss->dheParams->prime.data; - dhParam.prime.len = ss->dheParams->prime.len; - dhParam.base.data = ss->dheParams->base.data; - dhParam.base.len = ss->dheParams->base.len; + 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)); @@ -9059,395 +9389,265 @@ ssl3_SendDHServerKeyExchange(sslSocket *ss) privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL); if (!privKey || !pubKey) { ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - goto loser; + return SECFailure; } - keyPair = ssl3_NewKeyPair(privKey, pubKey); - if (!keyPair) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - goto loser; + pair = ssl_NewEphemeralKeyPair(groupDef, privKey, pubKey); + if (!pair) { + SECKEY_DestroyPrivateKey(privKey); + SECKEY_DestroyPublicKey(pubKey); + + return SECFailure; } - PRINT_BUF(50, (ss, "DH public value:", - pubKey->u.dh.publicValue.data, - pubKey->u.dh.publicValue.len)); + *keyPair = pair; + return SECSuccess; +} - if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != 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; + + 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); - goto loser; + return SECFailure; + } + PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs); + + if (ss->ssl3.pwSpec->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_ComputeDHKeyHash(sigAndHash.hashAlg, + 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, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); + PR_TRUE /* padY */); if (rv != SECSuccess) { ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); goto loser; } - /* It has been suggested to test kea_def->signKeyType instead, and to use - * ssl_auth_* instead. Investigate what to do. See bug 102794. */ - if (kea_def->kea == kea_dhe_rsa) - certIndex = ssl_kea_rsa; - else - certIndex = ssl_kea_dh; - - isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); - rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY, - &signed_hash, isTLS); + certPrivateKey = ss->sec.serverCert->serverKeyPair->privKey; + rv = ssl3_SignHashes(ss, &hashes, certPrivateKey, &signed_hash); if (rv != SECSuccess) { - goto loser; /* ssl3_SignHashes has set err. */ - } - if (signed_hash.data == NULL) { - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto loser; + goto loser; /* ssl3_SignHashes has set err. */ } + length = 2 + pubKey->u.dh.prime.len + - 2 + pubKey->u.dh.base.len + - 2 + pubKey->u.dh.publicValue.len + - 2 + signed_hash.len; + 2 + pubKey->u.dh.base.len + + 2 + pubKey->u.dh.prime.len + + 2 + signed_hash.len; if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - length += 2; + length += 2; } rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + 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. */ + 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. */ + goto loser; /* err set by AppendHandshake. */ } - rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.dh.publicValue.data, - pubKey->u.dh.publicValue.len, 2); + rv = ssl_AppendPaddedDHKeyShare(ss, pubKey, PR_TRUE); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } + 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. */ + goto loser; /* err set by AppendHandshake. */ } PORT_Free(signed_hash.data); - ss->dheKeyPair = keyPair; return SECSuccess; loser: if (signed_hash.data) PORT_Free(signed_hash.data); - if (privKey) - SECKEY_DestroyPrivateKey(privKey); - if (pubKey) - SECKEY_DestroyPublicKey(pubKey); return SECFailure; } -/* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing - * elements of the handshake. (The negotiated cipher suite determines the - * signature algorithm.) 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_PickSignatureHashAlgorithm(sslSocket *ss, - SSLSignatureAndHashAlg* out) -{ - SSLSignType sigAlg; - PRUint32 policy; - unsigned int i, j; - - switch (ss->ssl3.hs.kea_def->kea) { - case kea_rsa: - case kea_rsa_export: - case kea_rsa_export_1024: - case kea_dh_rsa: - case kea_dh_rsa_export: - case kea_dhe_rsa: - case kea_dhe_rsa_export: - case kea_rsa_fips: - case kea_ecdh_rsa: - case kea_ecdhe_rsa: - sigAlg = ssl_sign_rsa; - break; - case kea_dh_dss: - case kea_dh_dss_export: - case kea_dhe_dss: - case kea_dhe_dss_export: - sigAlg = ssl_sign_dsa; - break; - case kea_ecdh_ecdsa: - case kea_ecdhe_ecdsa: - sigAlg = ssl_sign_ecdsa; - break; - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; - } - out->sigAlg = sigAlg; - - if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) { - /* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and - * prior. */ - out->hashAlg = ssl_hash_none; - return SECSuccess; - } - - if (ss->ssl3.hs.numClientSigAndHash == 0) { - /* If the client didn't provide any signature_algorithms extension then - * we can assume that they support SHA-1: - * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ - out->hashAlg = ssl_hash_sha1; - return SECSuccess; - } - - /* Here we look for the first server preference that the client has - * indicated support for in their signature_algorithms extension. */ - for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { - const SSLSignatureAndHashAlg *serverPref = - &ss->ssl3.signatureAlgorithms[i]; - SECOidTag hashOID; - if (serverPref->sigAlg != sigAlg) { - continue; - } - hashOID = ssl3_TLSHashAlgorithmToOID(serverPref->hashAlg); - if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) - || !(policy & NSS_USE_ALG_IN_SSL_KX)) { - /* we ignore hashes we don't support */ - continue; - } - for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) { - const SSLSignatureAndHashAlg *clientPref = - &ss->ssl3.hs.clientSigAndHash[j]; - if (clientPref->hashAlg == serverPref->hashAlg && - clientPref->sigAlg == sigAlg) { - out->hashAlg = serverPref->hashAlg; - return SECSuccess; - } - } - } - - PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM); - return SECFailure; -} - - static SECStatus ssl3_SendServerKeyExchange(sslSocket *ss) { - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - SECStatus rv = SECFailure; - int length; - PRBool isTLS; - SECItem signed_hash = {siBuffer, NULL, 0}; - SSL3Hashes hashes; - SECKEYPublicKey * sdPub; /* public key for step-down */ - SSLSignatureAndHashAlg sigAndHash; + const ssl3KEADef *kea_def = ss->ssl3.hs.kea_def; SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - - if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) { - return SECFailure; - } + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); switch (kea_def->exchKeyType) { - case kt_rsa: - /* Perform SSL Step-Down here. */ - sdPub = ss->stepDownKeyPair->pubKey; - PORT_Assert(sdPub != NULL); - if (!sdPub) { - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - return SECFailure; - } - rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, - sdPub->u.rsa.modulus, - sdPub->u.rsa.publicExponent, - &ss->ssl3.hs.client_random, - &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - return rv; - } + case ssl_kea_dh: { + return ssl3_SendDHServerKeyExchange(ss); + } - isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); - rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY, - &signed_hash, isTLS); - if (rv != SECSuccess) { - goto loser; /* ssl3_SignHashes has set err. */ - } - if (signed_hash.data == NULL) { - /* how can this happen and rv == SECSuccess ?? */ - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto loser; - } - length = 2 + sdPub->u.rsa.modulus.len + - 2 + sdPub->u.rsa.publicExponent.len + - 2 + signed_hash.len; - - if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - length += 2; - } - - rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } - - rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data, - sdPub->u.rsa.modulus.len, 2); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } - - rv = ssl3_AppendHandshakeVariable( - ss, sdPub->u.rsa.publicExponent.data, - sdPub->u.rsa.publicExponent.len, 2); - if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ - } - - if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash); - 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; - - case ssl_kea_dh: { - rv = ssl3_SendDHServerKeyExchange(ss); - return rv; - } - -#ifndef NSS_DISABLE_ECC - case kt_ecdh: { - rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash); - return rv; - } -#endif /* NSS_DISABLE_ECC */ - - case kt_null: - default: - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - break; + case ssl_kea_ecdh: { + return ssl3_SendECDHServerKeyExchange(ss); + } + + case ssl_kea_rsa: + case ssl_kea_null: + default: + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + break; } -loser: - if (signed_hash.data != NULL) - PORT_Free(signed_hash.data); + return SECFailure; } -static SECStatus -ssl3_EncodeCertificateRequestSigAlgs(sslSocket *ss, PRUint8 *buf, - unsigned maxLen, PRUint32 *len) +SECStatus +ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint8 *buf, unsigned maxLen, PRUint32 *len) { unsigned int i; + PRUint8 *p = buf; - PORT_Assert(maxLen >= ss->ssl3.signatureAlgorithmCount * 2); - if (maxLen < ss->ssl3.signatureAlgorithmCount * 2) { + PORT_Assert(maxLen >= ss->ssl3.signatureSchemeCount * 2); + if (maxLen < ss->ssl3.signatureSchemeCount * 2) { PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } - *len = 0; - for (i = 0; i < ss->ssl3.signatureAlgorithmCount; ++i) { - const SSLSignatureAndHashAlg *alg = &ss->ssl3.signatureAlgorithms[i]; - /* Note that we don't support a handshake hash with anything other than - * SHA-256, so asking for a signature from clients for something else - * would be inviting disaster. */ - if (alg->hashAlg == ssl_hash_sha256) { - buf[(*len)++] = (PRUint8)alg->hashAlg; - buf[(*len)++] = (PRUint8)alg->sigAlg; + for (i = 0; i < ss->ssl3.signatureSchemeCount; ++i) { + PRUint32 policy = 0; + SSLHashType hashType = ssl_SignatureSchemeToHashType( + ss->ssl3.signatureSchemes[i]); + SECOidTag hashOID = ssl3_HashTypeToOID(hashType); + + /* Skip RSA-PSS schemes if there are no tokens to verify them. */ + if (ssl_IsRsaPssSignatureScheme(ss->ssl3.signatureSchemes[i]) && + !PK11_TokenExists(auth_alg_defs[ssl_auth_rsa_pss])) { + continue; + } + + if ((NSS_GetAlgorithmPolicy(hashOID, &policy) != SECSuccess) || + (policy & NSS_USE_ALG_IN_SSL_KX)) { + p = ssl_EncodeUintX((PRUint32)ss->ssl3.signatureSchemes[i], 2, p); } } - if (*len == 0) { + if (p == buf) { PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); return SECFailure; } + *len = p - buf; return SECSuccess; } -static SECStatus -ssl3_SendCertificateRequest(sslSocket *ss) +void +ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calen, SECItem **names, + int *nnames) { - PRBool isTLS12; - SECItem * name; + SECItem *name; CERTDistNames *ca_list; - const PRUint8 *certTypes; - SECItem * names = NULL; - SECStatus rv; - int length; - int i; - int calen = 0; - int nnames = 0; - int certTypesLength; - PRUint8 sigAlgs[MAX_SIGNATURE_ALGORITHMS * 2]; - unsigned int sigAlgsLength = 0; - - 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)); + int i; - isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); + *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) { - ca_list = ssl3_server_ca_list; + ca_list = ssl3_server_ca_list; } if (ca_list != NULL) { - names = ca_list->names; - nnames = ca_list->nnames; + *names = ca_list->names; + *nnames = ca_list->nnames; } - for (i = 0, name = names; i < nnames; i++, name++) { - calen += 2 + name->len; + for (i = 0, name = *names; i < *nnames; i++, name++) { + *calen += 2 + name->len; } +} + +static SECStatus +ssl3_SendCertificateRequest(sslSocket *ss) +{ + PRBool isTLS12; + const PRUint8 *certTypes; + SECStatus rv; + int length; + SECItem *names; + int calen; + int nnames; + SECItem *name; + int i; + int certTypesLength; + PRUint8 sigAlgs[MAX_SIGNATURE_SCHEMES * 2]; + unsigned int sigAlgsLength = 0; + + SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake", + SSL_GETPID(), ss->fd)); - certTypes = certificate_types; + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); + + ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames); + certTypes = certificate_types; certTypesLength = sizeof certificate_types; length = 1 + certTypesLength + 2 + calen; if (isTLS12) { - rv = ssl3_EncodeCertificateRequestSigAlgs(ss, sigAlgs, sizeof(sigAlgs), - &sigAlgsLength); + rv = ssl3_EncodeSigAlgs(ss, sigAlgs, sizeof(sigAlgs), &sigAlgsLength); if (rv != SECSuccess) { return rv; } @@ -9456,27 +9656,27 @@ ssl3_SendCertificateRequest(sslSocket *ss) rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (isTLS12) { - rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); - if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ - } + rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } } rv = ssl3_AppendHandshakeNumber(ss, calen, 2); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + 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. */ - } + rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } } return SECSuccess; @@ -9488,100 +9688,116 @@ ssl3_SendServerHelloDone(sslSocket *ss) SECStatus rv; SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_FlushHandshake(ss, 0); if (rv != SECSuccess) { - return rv; /* error code set by ssl3_FlushHandshake */ + return rv; /* error code set by ssl3_FlushHandshake */ } return SECSuccess; } -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 Certificate Verify message +/* 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, SSL3Opaque *b, PRUint32 length, - SSL3Hashes *hashes) + SSL3Hashes *hashes) { - SECItem signed_hash = {siBuffer, NULL, 0}; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; - SSL3AlertDescription desc = handshake_failure; - PRBool isTLS, isTLS12; - SSLSignatureAndHashAlg sigAndHash; + SECItem signed_hash = { siBuffer, NULL, 0 }; + SECStatus rv; + int errCode = SSL_ERROR_RX_MALFORMED_CERT_VERIFY; + SSL3AlertDescription desc = handshake_failure; + PRBool isTLS; + SSLSignatureScheme sigScheme; + SSLHashType hashAlg; + SSL3Hashes localHashes; + SSL3Hashes *hashesForVerify = NULL; 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) ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + /* TLS 1.3 is handled by tls13_HandleCertificateVerify */ + PORT_Assert(ss->ssl3.prSpec->version <= SSL_LIBRARY_VERSION_TLS_1_2); isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0); - isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); if (ss->ssl3.hs.ws != wait_cert_verify) { - desc = unexpected_message; - errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; - goto alert_loser; + desc = unexpected_message; + errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY; + goto alert_loser; } if (!hashes) { PORT_Assert(0); - desc = internal_error; - errCode = SEC_ERROR_LIBRARY_FAILURE; - goto alert_loser; + desc = internal_error; + errCode = SEC_ERROR_LIBRARY_FAILURE; + goto alert_loser; } - if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); - if (rv != SECSuccess) { - goto loser; /* malformed or unsupported. */ - } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( - ss, &sigAndHash, ss->sec.peerCert); - if (rv != SECSuccess) { - errCode = PORT_GetError(); - desc = decrypt_error; - goto alert_loser; - } - - /* We only support CertificateVerify messages that use the handshake - * hash. */ - if (sigAndHash.hashAlg != hashes->hashAlg) { - errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM; - desc = decrypt_error; - goto alert_loser; - } + if (ss->ssl3.hs.hashType == handshake_hash_record) { + rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme); + if (rv != SECSuccess) { + goto loser; /* malformed or unsupported. */ + } + rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, + ss->sec.peerCert); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + desc = decrypt_error; + goto alert_loser; + } + + hashAlg = ssl_SignatureSchemeToHashType(sigScheme); + + if (hashes->u.pointer_to_hash_input.data) { + rv = ssl3_ComputeHandshakeHash(hashes->u.pointer_to_hash_input.data, + hashes->u.pointer_to_hash_input.len, + hashAlg, &localHashes); + } else { + rv = SECFailure; + } + + if (rv == SECSuccess) { + hashesForVerify = &localHashes; + } else { + errCode = SSL_ERROR_DIGEST_FAILURE; + desc = decrypt_error; + goto alert_loser; + } + } else { + hashesForVerify = hashes; + sigScheme = ssl_sig_none; } rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length); if (rv != SECSuccess) { - goto loser; /* malformed. */ + goto loser; /* malformed. */ } /* XXX verify that the key & kea match */ - rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash, - isTLS, ss->pkcs11PinArg); + rv = ssl3_VerifySignedHashes(ss, sigScheme, hashesForVerify, &signed_hash); if (rv != SECSuccess) { - errCode = PORT_GetError(); - desc = isTLS ? decrypt_error : handshake_failure; - goto alert_loser; + 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 */ + desc = isTLS ? decode_error : illegal_parameter; + goto alert_loser; /* malformed */ } ss->ssl3.hs.ws = wait_change_cipher; return SECSuccess; @@ -9593,78 +9809,76 @@ loser: 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_DeriveConnectionKeysPKCS11() (above) - * sendRSAClientKeyExchange() (above) - * ssl3_HandleRSAClientKeyExchange() (below) + * 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) + PK11SlotInfo *serverKeySlot) { - PK11SymKey * pms = NULL; - PK11SlotInfo * slot = serverKeySlot; - void * pwArg = ss->pkcs11PinArg; - SECItem param; - CK_VERSION version; + 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) ); + 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 == ss->ssl3.pwSpec); + 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 == ss->ssl3.pwSpec); calg = spec->cipher_def->calg; - PORT_Assert(alg2Mech[calg].calg == calg); - /* First get an appropriate slot. */ - mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN; - mechanism_array[1] = CKM_RSA_PKCS; - mechanism_array[2] = alg2Mech[calg].cmech; - - 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 */ - } - } + /* 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; + SSL3ProtocolVersion temp; - temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion); - version.major = MSB(temp); - version.minor = LSB(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); + version.major = MSB(ss->clientHelloVersion); + version.minor = LSB(ss->clientHelloVersion); } param.data = (unsigned char *)&version; - param.len = sizeof version; + param.len = sizeof version; pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, ¶m, 0, pwArg); if (!serverKeySlot) - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); if (pms == NULL) { - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); } return pms; } @@ -9684,192 +9898,120 @@ ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec, static SECStatus ssl3_HandleRSAClientKeyExchange(sslSocket *ss, SSL3Opaque *b, - PRUint32 length, - SECKEYPrivateKey *serverKey) -{ -#ifndef NO_PKCS11_BYPASS - unsigned char * cr = (unsigned char *)&ss->ssl3.hs.client_random; - unsigned char * sr = (unsigned char *)&ss->ssl3.hs.server_random; - ssl3CipherSpec * pwSpec = ss->ssl3.pwSpec; - unsigned int outLen = 0; - PRBool isTLS = PR_FALSE; - SECItem pmsItem = {siBuffer, NULL, 0}; - unsigned char rsaPmsBuf[SSL3_RSA_PMS_LENGTH]; -#endif - SECStatus rv; - SECItem enc_pms; + PRUint32 length, + sslKeyPair *serverKeyPair) +{ + SECStatus rv; + SECItem enc_pms; + PK11SymKey *tmpPms[2] = { NULL, NULL }; + PK11SlotInfo *slot; + int useFauxPms = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); - PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec); enc_pms.data = b; - enc_pms.len = length; -#ifndef NO_PKCS11_BYPASS - pmsItem.data = rsaPmsBuf; - pmsItem.len = sizeof rsaPmsBuf; -#endif + enc_pms.len = length; if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */ - PRInt32 kLen; - kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); - if (kLen < 0) { - PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - return SECFailure; - } - if ((unsigned)kLen < enc_pms.len) { - enc_pms.len = kLen; - } -#ifndef NO_PKCS11_BYPASS - isTLS = PR_TRUE; -#endif - } else { -#ifndef NO_PKCS11_BYPASS - isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0); -#endif + PRInt32 kLen; + kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len); + if (kLen < 0) { + PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + return SECFailure; + } + if ((unsigned)kLen < enc_pms.len) { + enc_pms.len = kLen; + } } -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - /* We have not implemented a tls_ExtendedMasterKeyDeriveBypass - * and will not negotiate this extension in bypass mode. This - * assert just double-checks that. - */ - PORT_Assert( - !ssl3_ExtensionNegotiated(ss, ssl_extended_master_secret_xtn)); - - /* TRIPLE BYPASS, get PMS directly from RSA decryption. - * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer, - * then, check for version rollback attack, then - * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in - * pwSpec->msItem. Finally call ssl3_InitPendingCipherSpec with - * ss and NULL, so that it will use the MS we've already derived here. - */ - - rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen, - sizeof rsaPmsBuf, enc_pms.data, enc_pms.len); - if (rv != SECSuccess) { - /* triple bypass failed. Let's try for a double bypass. */ - goto double_bypass; - } else if (ss->opt.detectRollBack) { - SSL3ProtocolVersion client_version = - (rsaPmsBuf[0] << 8) | rsaPmsBuf[1]; - - if (IS_DTLS(ss)) { - client_version = dtls_DTLSVersionToTLSVersion(client_version); - } - - if (client_version != ss->clientHelloVersion) { - /* Version roll-back detected. ensure failure. */ - rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf); - } - } - /* have PMS, build MS without PKCS11 */ - rv = ssl3_MasterSecretDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS, - PR_TRUE); - if (rv != SECSuccess) { - pwSpec->msItem.data = pwSpec->raw_master_secret; - pwSpec->msItem.len = SSL3_MASTER_SECRET_LENGTH; - PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len); - } - rv = ssl3_InitPendingCipherSpec(ss, NULL); - } else -#endif - { - PK11SymKey *tmpPms[2] = {NULL, NULL}; - PK11SlotInfo *slot; - int useFauxPms = 0; #define currentPms tmpPms[!useFauxPms] -#define unusedPms tmpPms[useFauxPms] -#define realPms tmpPms[1] -#define fauxPms tmpPms[0] +#define unusedPms tmpPms[useFauxPms] +#define realPms tmpPms[1] +#define fauxPms tmpPms[0] -#ifndef NO_PKCS11_BYPASS -double_bypass: -#endif + /* + * 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. + */ - /* - * 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; + } - /* Generate the bogus PMS (R) */ - slot = PK11_GetSlotFromPrivateKey(serverKey); + 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; } + } - 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; - } + ssl_GetSpecWriteLock(ss); + fauxPms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot); + ssl_ReleaseSpecWriteLock(ss); + PK11_FreeSlot(slot); - /* - * 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. - */ - realPms = PK11_PubUnwrapSymKey(serverKey, &enc_pms, - CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); - /* Temporarily use the PMS if unwrapping the real PMS fails. */ - useFauxPms |= (realPms == NULL); + if (fauxPms == NULL) { + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + return SECFailure; + } - /* 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, currentPms, NULL); + /* + * 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. + */ + realPms = PK11_PubUnwrapSymKey(serverKeyPair->privKey, &enc_pms, + CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0); + /* Temporarily use the PMS if unwrapping the real PMS fails. */ + useFauxPms |= (realPms == NULL); - /* If we succeeded, then select the true PMS and discard the - * FPMS. Else, select the FPMS and select the true PMS */ - useFauxPms |= (rv != SECSuccess); + /* 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, currentPms, NULL); - if (unusedPms) { - PK11_FreeSymKey(unusedPms); - } + /* If we succeeded, then select the true PMS and discard the + * FPMS. Else, select the FPMS and select the true PMS */ + useFauxPms |= (rv != SECSuccess); - /* This step will derive the MS from the PMS, among other things. */ - rv = ssl3_InitPendingCipherSpec(ss, currentPms); - PK11_FreeSymKey(currentPms); + if (unusedPms) { + PK11_FreeSymKey(unusedPms); } + /* This step will derive the MS from the PMS, among other things. */ + rv = ssl3_InitPendingCipherSpec(ss, currentPms); + PK11_FreeSymKey(currentPms); + if (rv != SECSuccess) { - SEND_ALERT - return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ + (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure); + return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ } #undef currentPms @@ -9884,238 +10026,231 @@ static SECStatus ssl3_HandleDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length, - SECKEYPublicKey *srvrPubKey, - SECKEYPrivateKey *serverKey) + sslKeyPair *serverKeyPair) { - PK11SymKey *pms; - SECStatus rv; - SECKEYPublicKey clntPubKey; - CK_MECHANISM_TYPE target; - PRBool isTLS; + 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) ); - PORT_Assert( srvrPubKey ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); clntPubKey.keyType = dhKey; - clntPubKey.u.dh.prime.len = srvrPubKey->u.dh.prime.len; - clntPubKey.u.dh.prime.data = srvrPubKey->u.dh.prime.data; - clntPubKey.u.dh.base.len = srvrPubKey->u.dh.base.len; - clntPubKey.u.dh.base.data = srvrPubKey->u.dh.base.data; + 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); + 2, &b, &length); if (rv != SECSuccess) { - goto loser; + 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; + if (isTLS) + target = CKM_TLS_MASTER_KEY_DERIVE_DH; + else + target = CKM_SSL3_MASTER_KEY_DERIVE_DH; - /* Determine the PMS */ - pms = PK11_PubDerive(serverKey, &clntPubKey, PR_FALSE, NULL, NULL, + /* 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_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); - goto loser; + ssl_FreeEphemeralKeyPairs(ss); + ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + return SECFailure; } - rv = ssl3_InitPendingCipherSpec(ss, pms); - PK11_FreeSymKey(pms); pms = NULL; - -loser: - if (ss->dheKeyPair) { - ssl3_FreeKeyPair(ss->dheKeyPair); - ss->dheKeyPair = NULL; - } + rv = ssl3_InitPendingCipherSpec(ss, pms); + PK11_FreeSymKey(pms); + ssl_FreeEphemeralKeyPairs(ss); return rv; } - -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 ClientKeyExchange message from the remote client +/* 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, SSL3Opaque *b, PRUint32 length) { - SECKEYPrivateKey *serverKey = NULL; - SECStatus rv; + sslKeyPair *serverKeyPair = NULL; + SECStatus rv; const ssl3KEADef *kea_def; - ssl3KeyPair *serverKeyPair = NULL; - SECKEYPublicKey *serverPubKey = NULL; SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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 (ss->ssl3.hs.usedStepDownKey) { - PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */ - && kea_def->exchKeyType == kt_rsa - && ss->stepDownKeyPair != NULL); - if (!kea_def->is_limited || - kea_def->exchKeyType != kt_rsa || - ss->stepDownKeyPair == NULL) { - /* shouldn't happen, don't use step down if it does */ - goto skip; - } - serverKeyPair = ss->stepDownKeyPair; - ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB; - } else -skip: - if (kea_def->kea == kea_dhe_dss || - kea_def->kea == kea_dhe_rsa) { - if (ss->dheKeyPair) { - serverKeyPair = ss->dheKeyPair; - if (serverKeyPair->pubKey) { - ss->sec.keaKeyBits = - SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); - } - } - } else -#ifndef NSS_DISABLE_ECC - /* XXX Using SSLKEAType to index server certifiates - * does not work for (EC)DHE ciphers. Until we have - * an indexing mechanism general enough for all key - * exchange algorithms, we'll need to deal with each - * one seprately. - */ - if ((kea_def->kea == kea_ecdhe_rsa) || - (kea_def->kea == kea_ecdhe_ecdsa)) { - if (ss->ephemeralECDHKeyPair != NULL) { - serverKeyPair = ss->ephemeralECDHKeyPair; - if (serverKeyPair->pubKey) { - ss->sec.keaKeyBits = - SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey); - } - } - } else -#endif - { - sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType; - serverKeyPair = sc->serverKeyPair; - ss->sec.keaKeyBits = sc->serverKeyBits; + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH); + return SECFailure; } - if (serverKeyPair) { - serverKey = serverKeyPair->privKey; + 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 (serverKey == NULL) { - SEND_ALERT - PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG); - return SECFailure; + 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; + ss->sec.keaType = kea_def->exchKeyType; switch (kea_def->exchKeyType) { - case kt_rsa: - rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey); - if (rv != SECSuccess) { - SEND_ALERT - return SECFailure; /* error code set */ - } - break; - - case ssl_kea_dh: - if (ss->dheKeyPair && ss->dheKeyPair->pubKey) { - serverPubKey = ss->dheKeyPair->pubKey; - } - if (!serverPubKey) { - PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; - } - rv = ssl3_HandleDHClientKeyExchange(ss, b, length, - serverPubKey, serverKey); - if (rv != SECSuccess) { - SSL3_SendAlert(ss, alert_fatal, handshake_failure); - return SECFailure; /* error code set */ - } - break; - -#ifndef NSS_DISABLE_ECC - case kt_ecdh: - /* XXX We really ought to be able to store multiple - * EC certs (a requirement if we wish to support both - * ECDH-RSA and ECDH-ECDSA key exchanges concurrently). - * When we make that change, we'll need an index other - * than kt_ecdh to pick the right EC certificate. - */ - if (serverKeyPair) { - serverPubKey = serverKeyPair->pubKey; - } - if (serverPubKey == NULL) { - /* XXX Is this the right error code? */ - PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE); - return SECFailure; - } - rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, - serverPubKey, serverKey); - if (ss->ephemeralECDHKeyPair) { - ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); - ss->ephemeralECDHKeyPair = NULL; - } - if (rv != SECSuccess) { - return SECFailure; /* error code set */ - } - break; -#endif /* NSS_DISABLE_ECC */ - - default: - (void) ssl3_HandshakeFailure(ss); - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; - } - ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher; - return SECSuccess; + 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. */ -static SECStatus +SECStatus ssl3_SendEmptyCertificate(sslSocket *ss) { - SECStatus rv; + SECStatus rv; + unsigned int len = 0; + PRBool isTLS13 = PR_FALSE; + const SECItem *context; - rv = ssl3_AppendHandshakeHeader(ss, certificate, 3); - if (rv == SECSuccess) { - rv = ssl3_AppendHandshakeNumber(ss, 0, 3); + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + PORT_Assert(ss->ssl3.hs.certificateRequest); + context = &ss->ssl3.hs.certificateRequest->context; + len = context->len + 1; + isTLS13 = PR_TRUE; } - return rv; /* error, if any, set by functions called above. */ + + rv = ssl3_AppendHandshakeHeader(ss, 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); } -SECStatus +/* + * 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, &ticket); + if (rv != SECSuccess) + goto loser; + + /* Serialize the handshake message. Length = + * lifetime (4) + ticket length (2) + ticket. */ + rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, + 4 + 2 + ticket.len); + if (rv != SECSuccess) + goto loser; + + /* This is a fixed value. */ + rv = ssl3_AppendHandshakeNumber(ss, TLS_EX_SESS_TICKET_LIFETIME_HINT, 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, SSL3Opaque *b, PRUint32 length) { SECStatus rv; SECItem ticketData; SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake", - SSL_GETPID(), ss->fd)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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; + 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 @@ -10124,28 +10259,28 @@ ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) */ ss->ssl3.hs.newSessionTicket.received_timestamp = ssl_Time(); if (length < 4) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); - return SECFailure; + (void)SSL3_SendAlert(ss, alert_fatal, decode_error); + PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET); + return SECFailure; } ss->ssl3.hs.newSessionTicket.ticket_lifetime_hint = - (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); + (PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); 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 */ + (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; + 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; @@ -10155,54 +10290,54 @@ ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) #ifdef NISCC_TEST static PRInt32 connNum = 0; -static SECStatus +static SECStatus get_fake_cert(SECItem *pCertItem, int *pIndex) { PRFileDesc *cf; - char * testdir; - char * startat; - char * stopat; + char *testdir; + char *startat; + char *stopat; const char *extension; - int fileNum; - PRInt32 numBytes = 0; - PRStatus prStatus; - PRFileInfo info; - char cfn[100]; + int fileNum; + PRInt32 numBytes = 0; + PRStatus prStatus; + PRFileInfo info; + char cfn[100]; pCertItem->data = 0; - if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) { - return SECSuccess; + if ((testdir = PR_GetEnvSecure("NISCC_TEST")) == NULL) { + return SECSuccess; } - *pIndex = (NULL != strstr(testdir, "root")); + *pIndex = (NULL != strstr(testdir, "root")); extension = (strstr(testdir, "simple") ? "" : ".der"); - fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; - if ((startat = PR_GetEnv("START_AT")) != NULL) { - fileNum += atoi(startat); + fileNum = PR_ATOMIC_INCREMENT(&connNum) - 1; + if ((startat = PR_GetEnvSecure("START_AT")) != NULL) { + fileNum += atoi(startat); } - if ((stopat = PR_GetEnv("STOP_AT")) != NULL && - fileNum >= atoi(stopat)) { - *pIndex = -1; - return SECSuccess; + if ((stopat = PR_GetEnvSecure("STOP_AT")) != NULL && + fileNum >= atoi(stopat)) { + *pIndex = -1; + return SECSuccess; } sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension); cf = PR_Open(cfn, PR_RDONLY, 0); if (!cf) { - goto loser; + goto loser; } prStatus = PR_GetOpenFileInfo(cf, &info); if (prStatus != PR_SUCCESS) { - PR_Close(cf); - goto loser; + PR_Close(cf); + goto loser; } pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size); if (pCertItem) { - numBytes = PR_Read(cf, pCertItem->data, info.size); + 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; + SECITEM_FreeItem(pCertItem, PR_FALSE); + PORT_SetError(SEC_ERROR_IO); + goto loser; } fprintf(stderr, "using %s\n", cfn); return SECSuccess; @@ -10221,76 +10356,80 @@ loser: static SECStatus ssl3_SendCertificate(sslSocket *ss) { - SECStatus rv; + SECStatus rv; CERTCertificateList *certChain; - int len = 0; - int i; - SSL3KEAType certIndex; + int certChainLen = 0; + int i; #ifdef NISCC_TEST - SECItem fakeCert; - int ndex = -1; + 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)); + SSL_GETPID(), ss->fd)); - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->sec.localCert) - CERT_DestroyCertificate(ss->sec.localCert); + CERT_DestroyCertificate(ss->sec.localCert); if (ss->sec.isServer) { - sslServerCerts * sc = NULL; - - /* XXX SSLKEAType isn't really a good choice for - * indexing certificates (it breaks when we deal - * with (EC)DHE-* cipher suites. This hack ensures - * the RSA cert is picked for (EC)DHE-RSA. - * Revisit this when we add server side support - * for ECDHE-ECDSA or client-side authentication - * using EC certificates. - */ - if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || - (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { - certIndex = kt_rsa; - } else { - certIndex = ss->ssl3.hs.kea_def->exchKeyType; - } - sc = ss->serverCerts + certIndex; - certChain = sc->serverCertChain; - ss->sec.authKeyBits = sc->serverKeyBits; - ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; - ss->sec.localCert = CERT_DupCertificate(sc->serverCert); + /* 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); + 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.certificateRequest); + context = ss->ssl3.hs.certificateRequest->context; + contextLen += context.len; + } + } if (certChain) { - for (i = 0; i < certChain->len; i++) { + for (i = 0; i < certChain->len; i++) { #ifdef NISCC_TEST - if (fakeCert.len > 0 && i == ndex) { - len += fakeCert.len + 3; - } else { - len += certChain->certs[i].len + 3; - } + if (fakeCert.len > 0 && i == ndex) { + certChainLen += fakeCert.len + 3; + } else { + certChainLen += certChain->certs[i].len + 3; + } #else - len += certChain->certs[i].len + 3; + certChainLen += certChain->certs[i].len + 3; #endif - } + } } - rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3); + rv = ssl3_AppendHandshakeHeader(ss, certificate, + contextLen + certChainLen + 3); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + 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, len, 3); + + rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } if (certChain) { for (i = 0; i < certChain->len; i++) { @@ -10308,7 +10447,7 @@ ssl3_SendCertificate(sslSocket *ss) certChain->certs[i].len, 3); #endif if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } } } @@ -10320,54 +10459,49 @@ ssl3_SendCertificate(sslSocket *ss) * Used by server only. * single-stapling, send only a single cert status */ -static SECStatus +SECStatus ssl3_SendCertificateStatus(sslSocket *ss) { SECStatus rv; int len = 0; SECItemArray *statusToSend = NULL; - SSL3KEAType certIndex; + const sslServerCert *serverCert; SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake", - SSL_GETPID(), ss->fd)); + 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); + 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; + return SECSuccess; /* Use certStatus based on the cert being used. */ - if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) || - (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) { - certIndex = kt_rsa; - } else { - certIndex = ss->ssl3.hs.kea_def->exchKeyType; - } - if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) { - statusToSend = ss->certStatusArray[certIndex]; + serverCert = ss->sec.serverCert; + if (serverCert->certStatusArray && serverCert->certStatusArray->len) { + statusToSend = serverCert->certStatusArray; } if (!statusToSend) - return SECSuccess; + return SECSuccess; /* Use the array's first item only (single stapling) */ len = 1 + statusToSend->items[0].len + 3; rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len); if (rv != SECSuccess) { - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ } rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1); if (rv != SECSuccess) - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ rv = ssl3_AppendHandshakeVariable(ss, - statusToSend->items[0].data, - statusToSend->items[0].len, - 3); + statusToSend->items[0].data, + statusToSend->items[0].len, + 3); if (rv != SECSuccess) - return rv; /* err set by AppendHandshake. */ + return rv; /* err set by AppendHandshake. */ return SECSuccess; } @@ -10375,30 +10509,38 @@ ssl3_SendCertificateStatus(sslSocket *ss) /* This is used to delete the CA certificates in the peer certificate chain * from the cert database after they've been validated. */ -static void +void ssl3_CleanupPeerCerts(sslSocket *ss) { - PLArenaPool * arena = ss->ssl3.peerCertArena; + PLArenaPool *arena = ss->ssl3.peerCertArena; ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain; for (; certs; certs = certs->next) { - CERT_DestroyCertificate(certs->cert); + CERT_DestroyCertificate(certs->cert); } - if (arena) PORT_FreeArena(arena, PR_FALSE); + 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_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 CertificateStatus message. +/* Called from ssl3_HandlePostHelloHandshakeMessage() when it has deciphered + * a complete ssl3 CertificateStatus message. * Caller must hold Handshake and RecvBuf locks. - * This is always called before ssl3_HandleCertificate, even if the Certificate - * message is sent first. */ static SECStatus ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - PRInt32 status, len; + SECStatus rv; if (ss->ssl3.hs.ws != wait_certificate_status) { (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); @@ -10406,84 +10548,96 @@ ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 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, SSL3Opaque *b, PRUint32 length) +{ + PRInt32 status, len; + PORT_Assert(!ss->sec.isServer); /* Consume the CertificateStatusType enum */ status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length); if (status != 1 /* ocsp */) { - goto format_loser; + ssl3_DecodeError(ss); /* sets error code */ + return SECFailure; } len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); if (len != length) { - goto format_loser; + ssl3_DecodeError(ss); /* sets error code */ + return SECFailure; } -#define MAX_CERTSTATUS_LEN 0x1ffff /* 128k - 1 */ - if (length > MAX_CERTSTATUS_LEN) - goto format_loser; +#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; + 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; + 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 ssl3_AuthCertificate(ss); - -format_loser: - return ssl3_DecodeError(ss); + return SECSuccess; } -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 Certificate message. +/* 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, SSL3Opaque *b, PRUint32 length) { - ssl3CertNode * c; - ssl3CertNode * lastCert = NULL; - PRInt32 remaining = 0; - PRInt32 size; - SECStatus rv; - PRBool isServer = (PRBool)(!!ss->sec.isServer); - PRBool isTLS; - SSL3AlertDescription desc; - int errCode = SSL_ERROR_RX_MALFORMED_CERTIFICATE; - SECItem certItem; - 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) ); + SSL_GETPID(), ss->fd)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - if ((isServer && ss->ssl3.hs.ws != wait_client_cert) || - (!isServer && ss->ssl3.hs.ws != wait_server_cert)) { - desc = unexpected_message; - errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE; - goto alert_loser; + 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.peerCert != NULL) { - if (ss->sec.peerKey) { - SECKEY_DestroyPublicKey(ss->sec.peerKey); - ss->sec.peerKey = NULL; - } - CERT_DestroyCertificate(ss->sec.peerCert); - ss->sec.peerCert = NULL; - } + return ssl3_CompleteHandleCertificate(ss, b, length); +} + +/* Called from ssl3_HandleCertificate + */ +SECStatus +ssl3_CompleteHandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +{ + ssl3CertNode *c; + ssl3CertNode *lastCert = NULL; + PRInt32 remaining = 0; + PRInt32 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); @@ -10493,98 +10647,103 @@ ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) ** normal no_certificates message to maximize interoperability. */ if (length) { - remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); - if (remaining < 0) - goto loser; /* fatal alert already sent by ConsumeHandshake. */ - if ((PRUint32)remaining > length) - goto decode_loser; + remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); + if (remaining < 0) + goto loser; /* fatal alert already sent by ConsumeHandshake. */ + if ((PRUint32)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; - } - ss->ssl3.hs.ws = wait_client_key; - return SECSuccess; + 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 */ + goto loser; /* don't send alerts on memory errors */ } /* First get the peer cert. */ remaining -= 3; if (remaining < 0) - goto decode_loser; + goto decode_loser; size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); if (size <= 0) - goto loser; /* fatal alert already sent by ConsumeHandshake. */ + goto loser; /* fatal alert already sent by ConsumeHandshake. */ if (remaining < size) - goto decode_loser; + goto decode_loser; certItem.data = b; certItem.len = size; - b += size; + b += size; length -= size; remaining -= size; ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); + 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; + /* 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) { - remaining -= 3; - if (remaining < 0) - goto decode_loser; - - size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); - if (size <= 0) - goto loser; /* fatal alert already sent by ConsumeHandshake. */ - - if (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; + remaining -= 3; + if (remaining < 0) + goto decode_loser; + + size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length); + if (size <= 0) + goto loser; /* fatal alert already sent by ConsumeHandshake. */ + + if (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; } if (remaining != 0) @@ -10592,11 +10751,13 @@ ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) SECKEY_UpdateCertPQG(ss->sec.peerCert); - if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) { - ss->ssl3.hs.ws = wait_certificate_status; - rv = SECSuccess; + 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 */ + rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */ } return rv; @@ -10604,14 +10765,14 @@ ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length) 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; + 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; @@ -10627,12 +10788,12 @@ loser: return SECFailure; } -static SECStatus +SECStatus ssl3_AuthCertificate(sslSocket *ss) { - SECStatus rv; - PRBool isServer = (PRBool)(!!ss->sec.isServer); - int errCode; + SECStatus rv; + PRBool isServer = ss->sec.isServer; + int errCode; ss->ssl3.hs.authCertificatePending = PR_FALSE; @@ -10642,30 +10803,29 @@ ssl3_AuthCertificate(sslSocket *ss) * Ask caller-supplied callback function to validate cert chain. */ rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd, - PR_TRUE, isServer); - if (rv) { - errCode = PORT_GetError(); - 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; - rv = SECFailure; - goto loser; - } - - ss->ssl3.hs.authCertificatePending = PR_TRUE; - rv = SECSuccess; - } - - if (rv != SECSuccess) { - ssl3_SendAlertForCertError(ss, errCode); - goto loser; - } + PR_TRUE, isServer); + if (rv != SECSuccess) { + errCode = PORT_GetError(); + 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; + } } ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); @@ -10673,84 +10833,106 @@ ssl3_AuthCertificate(sslSocket *ss) if (!ss->sec.isServer) { CERTCertificate *cert = ss->sec.peerCert; - /* set the server authentication and key exchange types and sizes - ** from the value in the cert. If the key exchange key is different, - ** it will get fixed when we handle the server key exchange message. - */ - SECKEYPublicKey * pubKey = CERT_ExtractPublicKey(cert); - ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType; - ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; - if (pubKey) { - KeyType pubKeyType; - PRInt32 minKey; - ss->sec.keaKeyBits = ss->sec.authKeyBits = - SECKEY_PublicKeyStrengthInBits(pubKey); + /* set the server authentication type and size from the value + ** in the cert. */ + SECKEYPublicKey *pubKey = CERT_ExtractPublicKey(cert); + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + /* These are filled in in tls13_HandleCertificateVerify and + * tls13_HandleServerKeyShare. */ + ss->sec.authType = ss->ssl3.hs.kea_def->authKeyType; + ss->sec.keaType = ss->ssl3.hs.kea_def->exchKeyType; + } + if (pubKey) { + KeyType pubKeyType; + PRInt32 minKey; + /* This partly fixes Bug 124230 and may cause problems for + * callers which depend on the old (wrong) behavior. */ + ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(pubKey); pubKeyType = SECKEY_GetPublicKeyType(pubKey); - minKey = ss->sec.authKeyBits; - switch (pubKeyType) { - case rsaKey: - case rsaPssKey: - case rsaOaepKey: - rv = NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey); - if (rv != SECSuccess) { - minKey = SSL_RSA_MIN_MODULUS_BITS; - } - break; - case dsaKey: - rv = NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey); - if (rv != SECSuccess) { - minKey = SSL_DSA_MIN_P_BITS; - } - break; - case dhKey: - rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey); - if (rv != SECSuccess) { - minKey = SSL_DH_MIN_P_BITS; - } - break; - default: - break; - } + minKey = ss->sec.authKeyBits; + switch (pubKeyType) { + case rsaKey: + case rsaPssKey: + case rsaOaepKey: + rv = + NSS_OptionGet(NSS_RSA_MIN_KEY_SIZE, &minKey); + if (rv != + SECSuccess) { + minKey = + SSL_RSA_MIN_MODULUS_BITS; + } + break; + case dsaKey: + rv = + NSS_OptionGet(NSS_DSA_MIN_KEY_SIZE, &minKey); + if (rv != + SECSuccess) { + minKey = + SSL_DSA_MIN_P_BITS; + } + break; + case dhKey: + rv = + NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minKey); + if (rv != + SECSuccess) { + minKey = + SSL_DH_MIN_P_BITS; + } + break; + default: + break; + } /* Too small: not good enough. Send a fatal alert. */ /* We aren't checking EC here on the understanding that we only * support curves we like, a decision that might need revisiting. */ - if ( ss->sec.authKeyBits < minKey) { + if (ss->sec.authKeyBits < minKey) { PORT_SetError(SSL_ERROR_WEAK_SERVER_CERT_KEY); (void)SSL3_SendAlert(ss, alert_fatal, ss->version >= SSL_LIBRARY_VERSION_TLS_1_0 - ? insufficient_security - : illegal_parameter); + ? insufficient_security + : illegal_parameter); SECKEY_DestroyPublicKey(pubKey); return SECFailure; } - SECKEY_DestroyPublicKey(pubKey); - pubKey = NULL; - } - - /* Ephemeral suites require ServerKeyExchange. Export cipher suites - * with RSA key exchange also require ServerKeyExchange if the - * authentication key exceeds the key size limit. */ - if (ss->ssl3.hs.kea_def->ephemeral || - (ss->ssl3.hs.kea_def->is_limited && - ss->ssl3.hs.kea_def->exchKeyType == ssl_kea_rsa && - ss->sec.authKeyBits > ss->ssl3.hs.kea_def->key_size_limit)) { - ss->ssl3.hs.ws = wait_server_key; /* require server_key_exchange */ + SECKEY_DestroyPublicKey(pubKey); + pubKey = NULL; + } + + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + TLS13_SET_HS_STATE(ss, wait_cert_verify); } else { - ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */ + /* 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 { - ss->ssl3.hs.ws = wait_client_key; + /* 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; - rv = SECFailure; - goto loser; + errCode = SEC_ERROR_LIBRARY_FAILURE; + goto loser; } - return rv; + return SECSuccess; loser: (void)ssl_MapLowLevelError(errCode); @@ -10760,7 +10942,7 @@ loser: static SECStatus ssl3_FinishHandshake(sslSocket *ss); static SECStatus -ssl3_AlwaysFail(sslSocket * ss) +ssl3_AlwaysFail(sslSocket *ss) { PORT_SetError(PR_INVALID_STATE_ERROR); return SECFailure; @@ -10776,61 +10958,63 @@ ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error) PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); if (ss->sec.isServer) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS); - return SECFailure; + 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; + 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; + 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); - /* Even if we blocked here, we have accomplished enough to claim - * success. Any remaining work will be taken care of by subsequent - * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. - */ - if (rv == SECWouldBlock) { - rv = SECSuccess; - } + 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); + /* Even if we blocked here, we have accomplished enough to claim + * success. Any remaining work will be taken care of by subsequent + * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc. + */ + if (rv == SECWouldBlock) { + rv = SECSuccess; + } } 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_WaitingForStartOfServerSecondRound(ss)) { - /* ssl3_SendClientSecondRound deferred the false start check because - * certificate authentication was pending, so we do it now if we still - * haven't received any of the server's second round yet. - */ - rv = ssl3_CheckFalseStart(ss); - } else { - rv = SECSuccess; - } + 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: @@ -10841,44 +11025,44 @@ done: } static SECStatus -ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, - PRBool isServer, - const SSL3Hashes * hashes, - TLSFinished * tlsFinished) +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}; + SECItem param = { siBuffer, NULL, 0 }; PK11Context *prf_context; unsigned int retLen; - if (!spec->master_secret || spec->bypassCiphers) { - const char *label = isServer ? "server finished" : "client finished"; - unsigned int len = 15; - - return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, - hashes->len, tlsFinished->verify_data, - sizeof tlsFinished->verify_data); + if (!spec->master_secret) { + const char *label = isServer ? "server finished" : "client finished"; + unsigned int len = 15; + HASH_HashType hashType = ssl3_GetTls12HashType(ss); + return ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw, + hashes->len, tlsFinished->verify_data, + sizeof tlsFinished->verify_data, hashType); } if (spec->version < SSL_LIBRARY_VERSION_TLS_1_2) { - tls_mac_params.prfMechanism = CKM_TLS_PRF; + tls_mac_params.prfMechanism = CKM_TLS_PRF; } else { - tls_mac_params.prfMechanism = CKM_SHA256; + tls_mac_params.prfMechanism = 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->master_secret, ¶m); + spec->master_secret, ¶m); if (!prf_context) - return SECFailure; + return SECFailure; - rv = PK11_DigestBegin(prf_context); + 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); + sizeof tlsFinished->verify_data); PORT_Assert(rv != SECSuccess || retLen == sizeof tlsFinished->verify_data); PK11_DestroyContext(prf_context, PR_TRUE); @@ -10892,55 +11076,36 @@ ssl3_ComputeTLSFinished(ssl3CipherSpec *spec, */ SECStatus ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, - unsigned int labelLen, const unsigned char *val, unsigned int valLen, - unsigned char *out, unsigned int outLen) + unsigned int labelLen, const unsigned char *val, unsigned int valLen, + unsigned char *out, unsigned int outLen, HASH_HashType tls12HashType) { SECStatus rv = SECSuccess; - if (spec->master_secret && !spec->bypassCiphers) { - SECItem param = {siBuffer, NULL, 0}; - CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; - PK11Context *prf_context; - unsigned int retLen; - - if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; - } - prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, - spec->master_secret, ¶m); - 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); + if (spec->master_secret) { + SECItem param = { siBuffer, NULL, 0 }; + CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL; + PK11Context *prf_context; + unsigned int retLen; + + if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { + mech = CKM_NSS_TLS_PRF_GENERAL_SHA256; + } + prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN, + spec->master_secret, ¶m); + 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); } else { - /* bypass PKCS11 */ -#ifdef NO_PKCS11_BYPASS - PORT_Assert(spec->master_secret); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - rv = SECFailure; -#else - SECItem inData = { siBuffer, }; - SECItem outData = { siBuffer, }; - PRBool isFIPS = PR_FALSE; - - inData.data = (unsigned char *) val; - inData.len = valLen; - outData.data = out; - outData.len = outLen; - if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) { - rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData, - &outData, isFIPS); - } else { - rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS); - } - PORT_Assert(rv != SECSuccess || outData.len == outLen); -#endif + PORT_Assert(spec->master_secret); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + rv = SECFailure; } return rv; } @@ -10953,31 +11118,32 @@ ssl3_SendNextProto(sslSocket *ss) { SECStatus rv; int padding_len; - static const unsigned char padding[32] = {0}; + static const unsigned char padding[32] = { 0 }; - if (ss->ssl3.nextProto.len == 0 || - ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) { - return SECSuccess; + 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)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); - padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32); + padding_len = 32 - ((ss->xtnData.nextProto.len + 2) % 32); - rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len + - 2 + padding_len); + rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->xtnData.nextProto.len + + 2 + + padding_len); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshakeHeader */ + return rv; /* error code set by AppendHandshakeHeader */ } - rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, - ss->ssl3.nextProto.len, 1); + rv = ssl3_AppendHandshakeVariable(ss, ss->xtnData.nextProto.data, + ss->xtnData.nextProto.len, 1); if (rv != SECSuccess) { - return rv; /* error code set by AppendHandshake */ + 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; /* error code set by AppendHandshake */ } return rv; } @@ -10989,31 +11155,32 @@ ssl3_SendNextProto(sslSocket *ss) static void ssl3_RecordKeyLog(sslSocket *ss) { +#ifdef NSS_ALLOW_SSLKEYLOGFILE SECStatus rv; SECItem *keyData; char buf[14 /* "CLIENT_RANDOM " */ + - SSL3_RANDOM_LENGTH*2 /* client_random */ + - 1 /* " " */ + - 48*2 /* master secret */ + + SSL3_RANDOM_LENGTH * 2 /* client_random */ + + 1 /* " " */ + + 48 * 2 /* master secret */ + 1 /* new line */]; unsigned int j; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (!ssl_keylog_iob) - return; + return; rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret); if (rv != SECSuccess) - return; + return; ssl_GetSpecReadLock(ss); /* keyData does not need to be freed. */ keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret); if (!keyData || !keyData->data || keyData->len != 48) { - ssl_ReleaseSpecReadLock(ss); - return; + ssl_ReleaseSpecReadLock(ss); + return; } /* https://developer.mozilla.org/en/NSS_Key_Log_Format */ @@ -11025,10 +11192,10 @@ ssl3_RecordKeyLog(sslSocket *ss) memcpy(buf, "CLIENT_RANDOM ", 14); j = 14; hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); - j += SSL3_RANDOM_LENGTH*2; + j += SSL3_RANDOM_LENGTH * 2; buf[j++] = ' '; hexEncode(buf + j, keyData->data, 48); - j += 48*2; + j += 48 * 2; buf[j++] = '\n'; PORT_Assert(j == sizeof(buf)); @@ -11039,6 +11206,7 @@ ssl3_RecordKeyLog(sslSocket *ss) return; fflush(ssl_keylog_iob); return; +#endif } /* called from ssl3_SendClientSecondRound @@ -11049,59 +11217,59 @@ 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; + 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)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); 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(cwSpec, isServer, &hashes, &tlsFinished); + rv = ssl3_ComputeTLSFinished(ss, cwSpec, isServer, &hashes, &tlsFinished); } ssl_ReleaseSpecReadLock(ss); if (rv != SECSuccess) { - goto fail; /* err code was set by ssl3_ComputeHandshakeHashes */ + 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, 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. */ + 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, 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, 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. */ + 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, 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 */ + goto fail; /* error code set by ssl3_FlushHandshake */ } ssl3_RecordKeyLog(ss); @@ -11117,298 +11285,315 @@ fail: */ SECStatus ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid, - ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType) -{ - PK11SymKey * wrappingKey = NULL; - PK11SlotInfo * symKeySlot; - void * pwArg = ss->pkcs11PinArg; - SECStatus rv = SECFailure; - PRBool isServer = ss->sec.isServer; - CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM; + ssl3CipherSpec *spec, SSLAuthType authType) +{ + 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(spec->master_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) { - PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); - } - } + 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) { + PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey); + } + } } else { - /* server socket using session cache. */ - mechanism = PK11_GetBestWrapMechanism(symKeySlot); - if (mechanism != CKM_INVALID_MECHANISM) { - wrappingKey = - getWrappingKey(ss, symKeySlot, effectiveExchKeyType, - mechanism, pwArg); - if (wrappingKey) { - mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ - } - } + /* server socket using session cache. */ + mechanism = PK11_GetBestWrapMechanism(symKeySlot); + if (mechanism != CKM_INVALID_MECHANISM) { + wrappingKey = + ssl3_GetWrappingKey(ss, symKeySlot, ss->sec.serverCert, + mechanism, pwArg); + if (wrappingKey) { + mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */ + } + } } sid->u.ssl3.masterWrapMech = mechanism; PK11_FreeSlot(symKeySlot); if (wrappingKey) { - SECItem wmsItem; + 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, - spec->master_secret, &wmsItem); - /* rv is examined below. */ - sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; - PK11_FreeSymKey(wrappingKey); + 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, + spec->master_secret, &wmsItem); + /* rv is examined below. */ + sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len; + PK11_FreeSymKey(wrappingKey); } return rv; } -/* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete - * ssl3 Finished message from the peer. +/* 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, SSL3Opaque *b, PRUint32 length, - const SSL3Hashes *hashes) + const SSL3Hashes *hashes) { - sslSessionID * sid = ss->sec.ci.sid; - SECStatus rv = SECSuccess; - PRBool isServer = ss->sec.isServer; - PRBool isTLS; - SSL3KEAType effectiveExchKeyType; + sslSessionID *sid = ss->sec.ci.sid; + SECStatus rv = SECSuccess; + PRBool isServer = ss->sec.isServer; + PRBool isTLS; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + 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)); + 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; + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED); + return SECFailure; } if (!hashes) { PORT_Assert(0); - SSL3_SendAlert(ss, alert_fatal, internal_error); + SSL3_SendAlert(ss, alert_fatal, internal_error); PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0); if (isTLS) { - TLSFinished tlsFinished; - - if (length != sizeof tlsFinished) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED); - return SECFailure; - } - rv = ssl3_ComputeTLSFinished(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, length)) { - (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error); - PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE); - return SECFailure; - } + 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 (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_KEAAllowsSessionTicket(ss->ssl3.hs.suite_def->key_exchange_alg)) { - /* 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. */ - } + (!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); /*************************************/ + ssl_ReleaseXmitBufLock(ss); /*************************************/ if (rv != SECSuccess) { return rv; } - if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || - ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { - effectiveExchKeyType = kt_rsa; - } else { - effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; - } + if (sid->cached == never_cached && !ss->opt.noCache) { + rv = ssl3_FillInCachedSID(ss, sid); - if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) { - /* fill in the sid */ - sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; - sid->u.ssl3.compression = ss->ssl3.hs.compression; - sid->u.ssl3.policy = ss->ssl3.policy; -#ifndef NSS_DISABLE_ECC - sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves; -#endif - sid->u.ssl3.exchKeyType = effectiveExchKeyType; - sid->version = ss->version; - sid->authAlgorithm = ss->sec.authAlgorithm; - sid->authKeyBits = ss->sec.authKeyBits; - sid->keaType = ss->sec.keaType; - sid->keaKeyBits = ss->sec.keaKeyBits; - sid->lastAccessTime = sid->creationTime = ssl_Time(); - sid->expirationTime = sid->creationTime + ssl3_sid_timeout; - sid->localCert = CERT_DupCertificate(ss->sec.localCert); - - ssl_GetSpecReadLock(ss); /*************************************/ - - /* Copy the master secret (wrapped or unwrapped) into the sid */ - if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { - sid->u.ssl3.keys.wrapped_master_secret_len = - ss->ssl3.crSpec->msItem.len; - memcpy(sid->u.ssl3.keys.wrapped_master_secret, - ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); - sid->u.ssl3.masterValid = PR_TRUE; - sid->u.ssl3.keys.msIsWrapped = PR_FALSE; - rv = SECSuccess; - } else { - rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, - ss->ssl3.crSpec, - effectiveExchKeyType); - sid->u.ssl3.keys.msIsWrapped = PR_TRUE; - } - ssl_ReleaseSpecReadLock(ss); /*************************************/ - - /* If the wrap failed, we don't cache the sid. - * The connection continues normally however. - */ - ss->ssl3.hs.cacheSID = rv == SECSuccess; + /* If the wrap failed, we don't cache the sid. + * The connection continues normally however. + */ + ss->ssl3.hs.cacheSID = rv == SECSuccess; } 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; - } + 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; - return SECWouldBlock; + ss->ssl3.hs.restartTarget = ssl3_FinishHandshake; + return SECWouldBlock; } rv = ssl3_FinishHandshake(ss); return rv; } +SECStatus +ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid) +{ + SECStatus rv; + + /* fill in the sid */ + sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite; + sid->u.ssl3.compression = ss->ssl3.hs.compression; + 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; + sid->lastAccessTime = sid->creationTime = ssl_Time(); + sid->expirationTime = sid->creationTime + ssl3_sid_timeout; + sid->localCert = CERT_DupCertificate(ss->sec.localCert); + if (ss->sec.isServer) { + memcpy(&sid->certType, &ss->sec.serverCert->certType, sizeof(sid->certType)); + } else { + sid->certType.authType = ssl_auth_null; + } + + if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT && + ss->xtnData.nextProto.data) { + if (SECITEM_CopyItem( + NULL, &sid->u.ssl3.alpnSelection, &ss->xtnData.nextProto) != SECSuccess) { + return SECFailure; /* error already set. */ + } + } + + ssl_GetSpecReadLock(ss); /*************************************/ + + /* Copy the master secret (wrapped or unwrapped) into the sid */ + if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) { + sid->u.ssl3.keys.wrapped_master_secret_len = + ss->ssl3.crSpec->msItem.len; + memcpy(sid->u.ssl3.keys.wrapped_master_secret, + ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len); + sid->u.ssl3.masterValid = PR_TRUE; + sid->u.ssl3.keys.msIsWrapped = PR_FALSE; + rv = SECSuccess; + } else { + rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid, + ss->ssl3.crSpec, + ss->ssl3.hs.kea_def->authKeyType); + sid->u.ssl3.keys.msIsWrapped = PR_TRUE; + } + ssl_ReleaseSpecReadLock(ss); /*************************************/ + + return rv; +} + /* The return type is SECStatus instead of void because this function needs * to have type sslRestartTarget. */ SECStatus -ssl3_FinishHandshake(sslSocket * ss) +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 ); + 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; + ss->handshake = NULL; /* 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 @@ -11416,23 +11601,23 @@ ssl3_FinishHandshake(sslSocket * ss) * 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 (*ss->sec.cache)(ss->sec.ci.sid) + * This must be done before we call ss->sec.cache(ss->sec.ci.sid) * 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); - ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); - /* The sid took over the ticket data */ - PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); + PORT_Assert(!ss->sec.isServer); + ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ss->ssl3.hs.newSessionTicket); + /* The sid took over the ticket data */ + PORT_Assert(!ss->ssl3.hs.newSessionTicket.ticket.data); ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; } if (ss->ssl3.hs.cacheSID) { - PORT_Assert(ss->sec.ci.sid->cached == never_cached); - (*ss->sec.cache)(ss->sec.ci.sid); - ss->ssl3.hs.cacheSID = PR_FALSE; + PORT_Assert(ss->sec.ci.sid->cached == never_cached); + ss->sec.cache(ss->sec.ci.sid); + ss->ssl3.hs.cacheSID = PR_FALSE; } ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */ @@ -11448,89 +11633,134 @@ ssl3_FinishHandshake(sslSocket * ss) * Caller must hold Handshake and RecvBuf locks. */ SECStatus -ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length, + PRBool endOfRecord) { - SECStatus rv = SECSuccess; - SSL3HandshakeType type = ss->ssl3.hs.msg_type; - SSL3Hashes hashes; /* computed hashes are put here. */ - SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */ - PRUint8 hdr[4]; - PRUint8 dtlsData[8]; - - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + SECStatus rv = SECSuccess; + SSL3HandshakeType type = ss->ssl3.hs.msg_type; + SSL3Hashes hashes; /* computed hashes are put here. */ + SSL3Hashes *hashesPtr = NULL; /* Set when hashes are computed */ + PRUint8 hdr[4]; + PRUint8 dtlsData[8]; + PRBool computeHashes = PR_FALSE; + PRUint16 epoch; + + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); /* * We have to compute the hashes before we update them with the * current message. */ - ssl_GetSpecReadLock(ss); /************************************/ - if(((type == finished) && (ss->ssl3.hs.ws == wait_finished)) || - ((type == certificate_verify) && (ss->ssl3.hs.ws == wait_cert_verify))) { - SSL3Sender sender = (SSL3Sender)0; - ssl3CipherSpec *rSpec = ss->ssl3.prSpec; - - if (type == finished) { - sender = ss->sec.isServer ? sender_client : sender_server; - rSpec = ss->ssl3.crSpec; - } - rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + if ((type == finished) && (ss->ssl3.hs.ws == wait_finished)) { + computeHashes = PR_TRUE; + } else if ((type == certificate_verify) && (ss->ssl3.hs.ws == wait_cert_verify)) { + if (ss->ssl3.hs.hashType == handshake_hash_record) { + /* We cannot compute the hash yet. We must wait until we have + * decoded the certificate_verify message in + * ssl3_HandleCertificateVerify, which will tell us which + * hash function we must use. + * + * (ssl3_HandleCertificateVerify cannot simply look at the + * buffer length itself, because at the time we reach it, + * additional handshake messages will have been added to the + * buffer, e.g. the certificate_verify message itself.) + * + * Therefore, we use SSL3Hashes.u.pointer_to_hash_input + * to signal the current state of the buffer. + * + * ssl3_HandleCertificateVerify will detect + * hashType == handshake_hash_record + * and use that information to calculate the hash. + */ + hashes.u.pointer_to_hash_input.data = ss->ssl3.hs.messages.buf; + hashes.u.pointer_to_hash_input.len = ss->ssl3.hs.messages.len; + hashesPtr = &hashes; + } else { + computeHashes = PR_TRUE; + } + } + } else { + if (type == certificate_verify) { + computeHashes = TLS13_IN_HS_STATE(ss, wait_cert_verify); + } else if (type == finished) { + computeHashes = + TLS13_IN_HS_STATE(ss, wait_cert_request, wait_finished); + } + } + + ssl_GetSpecReadLock(ss); /************************************/ + if (computeHashes) { + SSL3Sender sender = (SSL3Sender)0; + ssl3CipherSpec *rSpec = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3 ? ss->ssl3.crSpec + : ss->ssl3.prSpec; + + if (type == finished) { + sender = ss->sec.isServer ? sender_client : sender_server; + rSpec = ss->ssl3.crSpec; + } + rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender); if (rv == SECSuccess) { hashesPtr = &hashes; } } ssl_ReleaseSpecReadLock(ss); /************************************/ if (rv != SECSuccess) { - return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ + return rv; /* error code was set by ssl3_ComputeHandshakeHashes*/ } - SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), - ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); + SSL_TRC(30, ("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(), + ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type))); hdr[0] = (PRUint8)ss->ssl3.hs.msg_type; hdr[1] = (PRUint8)(length >> 16); - hdr[2] = (PRUint8)(length >> 8); - hdr[3] = (PRUint8)(length ); + hdr[2] = (PRUint8)(length >> 8); + hdr[3] = (PRUint8)(length); - /* Start new handshake hashes when we start a new handshake */ - if (ss->ssl3.hs.msg_type == client_hello) { - rv = ssl3_RestartHandshakeHashes(ss); - if (rv != SECSuccess) { - return rv; - } + /* Start new handshake hashes when we start a new handshake. Unless this is + * TLS 1.3 and we sent a HelloRetryRequest. */ + if (ss->ssl3.hs.msg_type == client_hello && !ss->ssl3.hs.helloRetry) { + rv = ssl3_RestartHandshakeHashes(ss); + if (rv != SECSuccess) { + return rv; + } } /* We should not include hello_request and hello_verify_request messages * in the handshake hashes */ if ((ss->ssl3.hs.msg_type != hello_request) && - (ss->ssl3.hs.msg_type != hello_verify_request)) { - rv = ssl3_UpdateHandshakeHashes(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(ss->ssl3.hs.recvMessageSeq); - dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); - - /* 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 ); + (ss->ssl3.hs.msg_type != hello_verify_request)) { + rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)hdr, 4); + if (rv != SECSuccess) + return rv; /* err code already set. */ - rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData, - sizeof(dtlsData)); - 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(ss->ssl3.hs.recvMessageSeq); + dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq); + + /* 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 = ssl3_UpdateHandshakeHashes(ss, (unsigned char *)dtlsData, + sizeof(dtlsData)); + if (rv != SECSuccess) + return rv; /* err code already set. */ + } - /* The message body */ - rv = ssl3_UpdateHandshakeHashes(ss, b, length); - if (rv != SECSuccess) return rv; /* err code already set. */ + /* The message body */ + rv = ssl3_UpdateHandshakeHashes(ss, b, length); + if (rv != SECSuccess) + return rv; /* err code already set. */ } - PORT_SetError(0); /* each message starts with no error. */ + PORT_SetError(0); /* each message starts with no error. */ if (ss->ssl3.hs.ws == wait_certificate_status && ss->ssl3.hs.msg_type != certificate_status) { @@ -11548,115 +11778,151 @@ ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length) } } + epoch = ss->ssl3.crSpec->epoch; switch (ss->ssl3.hs.msg_type) { - case 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 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 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; - case 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 certificate: - rv = ssl3_HandleCertificate(ss, b, length); - break; - case certificate_status: - rv = ssl3_HandleCertificateStatus(ss, b, length); - break; - case 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 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 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 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, hashesPtr); - break; - case 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 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 finished: - rv = ssl3_HandleFinished(ss, b, length, hashesPtr); - break; - default: - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); - rv = SECFailure; + case 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 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, hashesPtr); + } else { + rv = tls13_HandlePostHelloHandshakeMessage(ss, b, length, + hashesPtr); + } + 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; } if (IS_DTLS(ss) && (rv != SECFailure)) { - /* Increment the expected sequence number */ - ss->ssl3.hs.recvMessageSeq++; + /* Increment the expected sequence number */ + ss->ssl3.hs.recvMessageSeq++; + } + return rv; +} + +static SECStatus +ssl3_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, + PRUint32 length, SSL3Hashes *hashesPtr) +{ + SECStatus rv; + PORT_Assert(ss->version < SSL_LIBRARY_VERSION_TLS_1_3); + + switch (ss->ssl3.hs.msg_type) { + case 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 hello_retry_request: + /* This arrives here because - as a client - we haven't received a + * final decision on the version from the server. */ + rv = tls13_HandleHelloRetryRequest(ss, b, length); + break; + + case 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 certificate: + rv = ssl3_HandleCertificate(ss, b, length); + break; + case certificate_status: + rv = ssl3_HandleCertificateStatus(ss, b, length); + break; + case 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 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 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 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, hashesPtr); + break; + case 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 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 finished: + rv = ssl3_HandleFinished(ss, b, length, hashesPtr); + break; + default: + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE); + rv = SECFailure; } return rv; @@ -11680,109 +11946,111 @@ ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */ SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (buf->buf == NULL) { - *buf = *origBuf; + *buf = *origBuf; } 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 = (SSL3HandshakeType)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); - return SECFailure; - } + 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 = (SSL3HandshakeType)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); + return SECFailure; + } #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); - if (rv == SECFailure) { - /* This test wants to fall through on either - * SECSuccess or SECWouldBlock. - * ssl3_HandleHandshakeMessage MUST set the error code. - */ - return rv; - } - 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) { /* return if SECWouldBlock. */ - return rv; - } - } 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. */ - return SECFailure; - } - - 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); - if (rv == SECFailure) { - /* This test wants to fall through on either - * SECSuccess or SECWouldBlock. - * ssl3_HandleHandshakeMessage MUST set error code. - */ - return rv; - } - ss->ssl3.hs.msg_body.len = 0; - ss->ssl3.hs.msg_len = 0; - ss->ssl3.hs.header_bytes = 0; - if (rv != SECSuccess) { /* return if SECWouldBlock. */ - return rv; - } - } else { - PORT_Assert(buf->len == 0); - break; - } - } - } /* end loop */ - - origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ - buf->buf = NULL; /* not a leak. */ + /* 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); + if (rv == SECFailure) { + /* This test wants to fall through on either + * SECSuccess or SECWouldBlock. + * ssl3_HandleHandshakeMessage MUST set the error code. + */ + return rv; + } + 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) { /* return if SECWouldBlock. */ + return rv; + } + } 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. */ + return SECFailure; + } + + 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); + if (rv == SECFailure) { + /* This test wants to fall through on either + * SECSuccess or SECWouldBlock. + * ssl3_HandleHandshakeMessage MUST set error code. + */ + return rv; + } + ss->ssl3.hs.msg_body.len = 0; + ss->ssl3.hs.msg_len = 0; + ss->ssl3.hs.header_bytes = 0; + if (rv != SECSuccess) { /* return if SECWouldBlock. */ + return rv; + } + } else { + PORT_Assert(buf->len == 0); + break; + } + } + } /* end loop */ + + origBuf->len = 0; /* So ssl3_GatherAppDataRecord will keep looping. */ + buf->buf = NULL; /* not a leak. */ return SECSuccess; } @@ -11790,7 +12058,7 @@ ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf) * bits. They use the fact that arithmetic shift shifts-in the sign bit. * However, this is not ensured by the C standard so you may need to replace * them with something else for odd compilers. */ -#define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) ) +#define DUPLICATE_MSB_TO_ALL(x) ((unsigned)((int)(x) >> (sizeof(int) * 8 - 1))) #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x))) /* SECStatusToMask returns, in constant time, a mask value of all ones if @@ -11823,10 +12091,17 @@ ssl_ConstantTimeEQ8(unsigned char a, unsigned char b) return DUPLICATE_MSB_TO_ALL_8(c); } +/* 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 blockSize, + unsigned int macSize) { unsigned int paddingLength, good, t; const unsigned int overhead = 1 /* padding length byte */ + macSize; @@ -11834,23 +12109,23 @@ ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext, /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > plaintext->len) { - return SECFailure; + return SECFailure; } - paddingLength = plaintext->buf[plaintext->len-1]; + paddingLength = plaintext->buf[plaintext->len - 1]; /* SSLv3 padding bytes are random and cannot be checked. */ t = plaintext->len; - t -= paddingLength+overhead; + t -= paddingLength + overhead; /* If len >= paddingLength+overhead then the MSB of t is zero. */ good = DUPLICATE_MSB_TO_ALL(~t); /* SSLv3 requires that the padding is minimal. */ - t = blockSize - (paddingLength+1); + t = blockSize - (paddingLength + 1); good &= DUPLICATE_MSB_TO_ALL(~t); - plaintext->len -= good & (paddingLength+1); + plaintext->len -= good & (paddingLength + 1); return (good & SECSuccess) | (~good & SECFailure); } -static SECStatus +SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) { unsigned int paddingLength, good, t, toCheck, i; @@ -11859,12 +12134,12 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) /* These lengths are all public so we can test them in non-constant * time. */ if (overhead > plaintext->len) { - return SECFailure; + return SECFailure; } - paddingLength = plaintext->buf[plaintext->len-1]; + paddingLength = plaintext->buf[plaintext->len - 1]; t = plaintext->len; - t -= paddingLength+overhead; + t -= paddingLength + overhead; /* If len >= paddingLength+overhead then the MSB of t is zero. */ good = DUPLICATE_MSB_TO_ALL(~t); @@ -11877,20 +12152,20 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) * 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 = 255; /* maximum amount of padding. */ - if (toCheck > plaintext->len-1) { - toCheck = plaintext->len-1; + toCheck = 256; /* maximum amount of padding + 1. */ + if (toCheck > plaintext->len) { + toCheck = plaintext->len; } for (i = 0; i < toCheck; i++) { - unsigned int t = paddingLength - i; - /* If i <= paddingLength then the MSB of t is zero and mask is - * 0xff. Otherwise, mask is 0. */ - unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); - 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)); + unsigned int t = paddingLength - i; + /* If i <= paddingLength then the MSB of t is zero and mask is + * 0xff. Otherwise, mask is 0. */ + unsigned char mask = DUPLICATE_MSB_TO_ALL(~t); + 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, @@ -11900,10 +12175,10 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) good &= good >> 4; good &= good >> 2; good &= good >> 1; - good <<= sizeof(good)*8-1; + good <<= sizeof(good) * 8 - 1; good = DUPLICATE_MSB_TO_ALL(good); - plaintext->len -= good & (paddingLength+1); + plaintext->len -= good & (paddingLength + 1); return (good & SECSuccess) | (~good & SECFailure); } @@ -11914,9 +12189,9 @@ ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize) */ static void ssl_CBCExtractMAC(sslBuffer *plaintext, - unsigned int originalLength, - SSL3Opaque* out, - unsigned int macSize) + unsigned int originalLength, + SSL3Opaque *out, + unsigned int macSize) { unsigned char rotatedMac[MAX_MAC_LENGTH]; /* macEnd is the index of |plaintext->buf| just after the end of the @@ -11926,44 +12201,280 @@ ssl_CBCExtractMAC(sslBuffer *plaintext, /* 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, divSpoiler; + unsigned i, j; unsigned char rotateOffset; - if (originalLength > macSize + 255 + 1) - scanStart = originalLength - (macSize + 255 + 1); + if (originalLength > macSize + 255 + 1) { + scanStart = originalLength - (macSize + 255 + 1); + } - /* divSpoiler contains a multiple of macSize that is used to cause the - * modulo operation to be constant time. Without this, the time varies - * based on the amount of padding when running on Intel chips at least. - * - * The aim of right-shifting macSize is so that the compiler doesn't - * figure out that it can remove divSpoiler as that would require it - * to prove that macSize is always even, which I hope is beyond it. */ - divSpoiler = macSize >> 1; - divSpoiler <<= (sizeof(divSpoiler)-1)*8; - rotateOffset = (divSpoiler + macStart - scanStart) % macSize; + /* 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; - } + 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++) { - unsigned char offset = - (divSpoiler + macSize - rotateOffset + i) % macSize; - for (j = 0; j < macSize; j++) { - out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset); - } + for (j = 0; j < macSize; j++) { + out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, rotateOffset); + } + rotateOffset++; + rotateOffset = ssl_constantTimeSelect(ssl_ConstantTimeGE(rotateOffset, macSize), + 0, rotateOffset); + } +} + +/* 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, SSL3Ciphertext *cText, sslBuffer *plaintext, + SSL3AlertDescription *alert) +{ + ssl3CipherSpec *crSpec = ss->ssl3.crSpec; + const ssl3BulkCipherDef *cipher_def = crSpec->cipher_def; + PRBool isTLS; + unsigned int good; + unsigned int ivLen = 0; + SSL3ContentType rType; + unsigned int minLength; + unsigned int originalLen = 0; + unsigned char header[13]; + unsigned int headerLen; + SSL3Opaque hash[MAX_MAC_LENGTH]; + SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; + SSL3Opaque *givenHash; + unsigned int hashBytes = MAX_MAC_LENGTH + 1; + SECStatus rv; + + good = ~0U; + minLength = crSpec->mac_size; + if (cipher_def->type == type_block) { + /* CBC records have a padding length byte at the end. */ + minLength++; + if (crSpec->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 && + crSpec->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. + */ + SSL3Opaque iv[MAX_IV_LENGTH]; + 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 = crSpec->decode(crSpec->decodeContext, iv, &decoded, + sizeof(iv), cText->buf->buf, ivLen); + + good &= SECStatusToMask(rv); + } + + PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, + cText->buf->len - ivLen)); + + isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); + + if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { + *alert = record_overflow; + PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); + return SECFailure; + } + + rType = cText->type; + 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. */ + unsigned int decryptedLen = + cText->buf->len - cipher_def->explicit_nonce_size - + cipher_def->tag_size; + headerLen = ssl3_BuildRecordPseudoHeader( + header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, + rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); + PORT_Assert(headerLen <= sizeof(header)); + rv = crSpec->aead( + ss->sec.isServer ? &crSpec->client : &crSpec->server, + PR_TRUE, /* do decrypt */ + plaintext->buf, /* out */ + (int *)&plaintext->len, /* outlen */ + plaintext->space, /* maxout */ + cText->buf->buf, /* in */ + cText->buf->len, /* inlen */ + header, headerLen); + 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 = crSpec->decode( + crSpec->decodeContext, plaintext->buf, (int *)&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 = crSpec->mac_size; + + if (!isTLS) { + good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( + plaintext, blockSize, macSize)); + } else { + good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( + plaintext, macSize)); + } + } + + /* compute the MAC */ + headerLen = ssl3_BuildRecordPseudoHeader( + header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, + rType, isTLS, cText->version, IS_DTLS(ss), + plaintext->len - crSpec->mac_size); + PORT_Assert(headerLen <= sizeof(header)); + if (cipher_def->type == type_block) { + rv = ssl3_ComputeRecordMACConstantTime( + crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, + plaintext->buf, plaintext->len, originalLen, + hash, &hashBytes); + + ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, + crSpec->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 -= crSpec->mac_size; + } else { + /* This is safe because we checked the minLength above. */ + plaintext->len -= crSpec->mac_size; + + rv = ssl3_ComputeRecordMAC( + crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, + 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)crSpec->mac_size || + NSS_SecureMemcmp(givenHash, hash, crSpec->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; } /* if cText is non-null, then decipher, check MAC, and decompress the @@ -11991,40 +12502,29 @@ ssl_CBCExtractMAC(sslBuffer *plaintext, SECStatus ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) { - const ssl3BulkCipherDef *cipher_def; - ssl3CipherSpec * crSpec; - SECStatus rv; - unsigned int hashBytes = MAX_MAC_LENGTH + 1; - PRBool isTLS; - SSL3ContentType rType; - SSL3Opaque hash[MAX_MAC_LENGTH]; - SSL3Opaque givenHashBuf[MAX_MAC_LENGTH]; - SSL3Opaque *givenHash; - sslBuffer *plaintext; - sslBuffer temp_buf; - PRUint64 dtls_seq_num = 0; - unsigned int ivLen = 0; - unsigned int originalLen = 0; - unsigned int good; - unsigned int minLength; - unsigned char header[13]; - unsigned int headerLen; - - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + SECStatus rv; + PRBool isTLS; + sslSequenceNumber seq_num = 0; + ssl3CipherSpec *crSpec; + SSL3ContentType rType; + sslBuffer *plaintext; + sslBuffer temp_buf; + SSL3AlertDescription alert = internal_error; + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); if (!ss->ssl3.initialized) { - ssl_GetSSL3HandshakeLock(ss); - rv = ssl3_InitState(ss); - ssl_ReleaseSSL3HandshakeLock(ss); - if (rv != SECSuccess) { - return rv; /* ssl3_InitState has set the error code. */ - } + ssl_GetSSL3HandshakeLock(ss); + rv = ssl3_InitState(ss); + ssl_ReleaseSSL3HandshakeLock(ss); + if (rv != SECSuccess) { + return rv; /* ssl3_InitState has set the error code. */ + } } /* check for Token Presence */ if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) { - PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); - return SECFailure; + PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL); + return SECFailure; } /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX(). @@ -12032,257 +12532,113 @@ ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf) * message. */ if (cText == NULL) { - SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", - SSL_GETPID(), ss->fd)); - rType = content_handshake; - goto process_it; + SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake", + SSL_GETPID(), ss->fd)); + rType = content_handshake; + goto process_it; } ssl_GetSpecReadLock(ss); /******************************************/ - crSpec = ss->ssl3.crSpec; - cipher_def = crSpec->cipher_def; - - /* - * 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 (IS_DTLS(ss)) { - DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff; - - if (crSpec->epoch != epoch) { - ssl_ReleaseSpecReadLock(ss); - SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet " - "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch)); - /* Silently drop the packet */ - databuf->len = 0; /* Needed to ensure data not left around */ - return SECSuccess; - } - - dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) | - ((PRUint64)cText->seq_num.low); - - if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) { - ssl_ReleaseSpecReadLock(ss); - SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting " - "potentially replayed packet", SSL_GETPID(), ss->fd)); - /* Silently drop the packet */ - databuf->len = 0; /* Needed to ensure data not left around */ - return SECSuccess; - } - } + isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); - good = ~0U; - minLength = crSpec->mac_size; - if (cipher_def->type == type_block) { - /* CBC records have a padding length byte at the end. */ - minLength++; - if (crSpec->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; - } + if (IS_DTLS(ss)) { + PRBool sameEpoch; + if (!dtls_IsRelevant(ss, cText, &sameEpoch, &seq_num)) { + ssl_ReleaseSpecReadLock(ss); /*****************************/ + databuf->len = 0; /* Needed to ensure data not left around */ - /* 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; + /* Maybe retransmit if needed. */ + return dtls_MaybeRetransmitHandshake(ss, cText, sameEpoch); + } + } else { + seq_num = crSpec->read_seq_num + 1; } - - if (cipher_def->type == type_block && - crSpec->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. - */ - SSL3Opaque iv[MAX_IV_LENGTH]; - int decoded; - - ivLen = cipher_def->iv_size; - if (ivLen < 8 || ivLen > sizeof(iv)) { - ssl_ReleaseSpecReadLock(ss); - 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 = crSpec->decode(crSpec->decodeContext, iv, &decoded, - sizeof(iv), cText->buf->buf, ivLen); - - good &= SECStatusToMask(rv); + if (seq_num >= crSpec->cipher_def->max_records) { + ssl_ReleaseSpecReadLock(ss); /*****************************/ + SSL_TRC(3, ("%d: SSL[%d]: read sequence number at limit 0x%0llx", + SSL_GETPID(), ss->fd, seq_num)); + PORT_SetError(SSL_ERROR_TOO_MANY_RECORDS); + return SECFailure; } /* If we will be decompressing the buffer we need to decrypt somewhere * other than into databuf */ if (crSpec->decompressor) { - temp_buf.buf = NULL; - temp_buf.space = 0; - plaintext = &temp_buf; + temp_buf.buf = NULL; + temp_buf.space = 0; + plaintext = &temp_buf; } else { - plaintext = databuf; + plaintext = databuf; } - plaintext->len = 0; /* filled in by decode call below. */ + plaintext->len = 0; /* filled in by Unprotect call below. */ if (plaintext->space < MAX_FRAGMENT_LENGTH) { - rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); - if (rv != SECSuccess) { - ssl_ReleaseSpecReadLock(ss); - SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", - SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); - /* sslBuffer_Grow has set a memory error code. */ - /* Perhaps we should send an alert. (but we have no memory!) */ - return SECFailure; - } + rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048); + if (rv != SECSuccess) { + ssl_ReleaseSpecReadLock(ss); /*************************/ + SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", + SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048)); + /* sslBuffer_Grow has set a memory error code. */ + /* Perhaps we should send an alert. (but we have no memory!) */ + return SECFailure; + } } - PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen, - cText->buf->len - ivLen)); - - isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0); - - if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) { - ssl_ReleaseSpecReadLock(ss); - SSL3_SendAlert(ss, alert_fatal, record_overflow); - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - return SECFailure; + /* We're waiting for another ClientHello, which will appear unencrypted. + * Use the content type to tell whether this is should be discarded. + * + * XXX If we decide to remove the content type from encrypted records, this + * will become much more difficult to manage. */ + if (ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_hrr && + cText->type == content_application_data) { + ssl_ReleaseSpecReadLock(ss); /*****************************/ + PORT_Assert(ss->ssl3.hs.ws == wait_client_hello); + databuf->len = 0; + return SECSuccess; } - rType = cText->type; - 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. */ - unsigned int decryptedLen = - cText->buf->len - cipher_def->explicit_nonce_size - - cipher_def->tag_size; - headerLen = ssl3_BuildRecordPseudoHeader( - header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, - rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen); - PORT_Assert(headerLen <= sizeof(header)); - rv = crSpec->aead( - ss->sec.isServer ? &crSpec->client : &crSpec->server, - PR_TRUE, /* do decrypt */ - plaintext->buf, /* out */ - (int*) &plaintext->len, /* outlen */ - plaintext->space, /* maxout */ - cText->buf->buf, /* in */ - cText->buf->len, /* inlen */ - header, headerLen); - if (rv != SECSuccess) { - good = 0; - } +#ifdef UNSAFE_FUZZER_MODE + rv = Null_Cipher(NULL, plaintext->buf, (int *)&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. */ + if (crSpec->version < SSL_LIBRARY_VERSION_TLS_1_3 || + crSpec->cipher_def->calg == ssl_calg_null) { + /* Unencrypted TLS 1.3 records use the pre-TLS 1.3 format. */ + rv = ssl3_UnprotectRecord(ss, cText, plaintext, &alert); } 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 = crSpec->decode( - crSpec->decodeContext, plaintext->buf, (int *)&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 = crSpec->mac_size; - - if (!isTLS) { - good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding( - plaintext, blockSize, macSize)); - } else { - good &= SECStatusToMask(ssl_RemoveTLSCBCPadding( - plaintext, macSize)); - } - } - - /* compute the MAC */ - headerLen = ssl3_BuildRecordPseudoHeader( - header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num, - rType, isTLS, cText->version, IS_DTLS(ss), - plaintext->len - crSpec->mac_size); - PORT_Assert(headerLen <= sizeof(header)); - if (cipher_def->type == type_block) { - rv = ssl3_ComputeRecordMACConstantTime( - crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, - plaintext->buf, plaintext->len, originalLen, - hash, &hashBytes); - - ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf, - crSpec->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 -= crSpec->mac_size; - } else { - /* This is safe because we checked the minLength above. */ - plaintext->len -= crSpec->mac_size; - - rv = ssl3_ComputeRecordMAC( - crSpec, (PRBool)(!ss->sec.isServer), header, headerLen, - 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)crSpec->mac_size || - NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) { - /* We're allowed to leak whether or not the MAC check was correct */ - good = 0; - } + rv = tls13_UnprotectRecord(ss, cText, plaintext, &alert); } +#endif - if (good == 0) { -decrypt_loser: - /* must not hold spec lock when calling SSL3_SendAlert. */ - ssl_ReleaseSpecReadLock(ss); - - SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); - - if (!IS_DTLS(ss)) { - SSL3_SendAlert(ss, alert_fatal, bad_record_mac); - /* always log mac error, in case attacker can read server logs. */ - PORT_SetError(SSL_ERROR_BAD_MAC_READ); - return SECFailure; - } else { - /* Silently drop the packet */ + if (rv != SECSuccess) { + ssl_ReleaseSpecReadLock(ss); /***************************/ + + SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd)); + + if (IS_DTLS(ss) || + (ss->sec.isServer && + ss->ssl3.hs.zeroRttIgnore == ssl_0rtt_ignore_trial)) { + /* Silently drop the packet */ databuf->len = 0; /* Needed to ensure data not left around */ - return SECSuccess; - } + return SECSuccess; + } else { + 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; + } } - if (!IS_DTLS(ss)) { - ssl3_BumpSequenceNumber(&crSpec->read_seq_num); - } else { - dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num); + /* SECSuccess */ + crSpec->read_seq_num = seq_num; + if (IS_DTLS(ss)) { + dtls_RecordSetRecvd(&crSpec->recvdRecords, seq_num); } ssl_ReleaseSpecReadLock(ss); /*****************************************/ @@ -12290,86 +12646,95 @@ decrypt_loser: /* * The decrypted data is now in plaintext. */ + rType = cText->type; /* This must go after decryption because TLS 1.3 + * has encrypted content types. */ /* possibly decompress the record. If we aren't using compression then * plaintext == databuf and so the uncompressed data is already in * databuf. */ if (crSpec->decompressor) { - if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { - rv = sslBuffer_Grow( - databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", - SSL_GETPID(), ss->fd, - plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION)); - /* sslBuffer_Grow has set a memory error code. */ - /* Perhaps we should send an alert. (but we have no memory!) */ - PORT_Free(plaintext->buf); - return SECFailure; - } - } - - rv = crSpec->decompressor(crSpec->decompressContext, - databuf->buf, - (int*) &databuf->len, - databuf->space, - plaintext->buf, - plaintext->len); - - if (rv != SECSuccess) { - int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); - SSL3_SendAlert(ss, alert_fatal, - isTLS ? decompression_failure : bad_record_mac); - - /* There appears to be a bug with (at least) Apache + OpenSSL where - * resumed SSLv3 connections don't actually use compression. See - * comments 93-95 of - * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 - * - * So, if we get a decompression error, and the record appears to - * be already uncompressed, then we return a more specific error - * code to hopefully save somebody some debugging time in the - * future. - */ - if (plaintext->len >= 4) { - unsigned int len = ((unsigned int) plaintext->buf[1] << 16) | - ((unsigned int) plaintext->buf[2] << 8) | - (unsigned int) plaintext->buf[3]; - if (len == plaintext->len - 4) { - /* This appears to be uncompressed already */ - err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; - } - } - - PORT_Free(plaintext->buf); - PORT_SetError(err); - return SECFailure; - } - - PORT_Free(plaintext->buf); + if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) { + rv = sslBuffer_Grow( + databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION); + if (rv != SECSuccess) { + SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes", + SSL_GETPID(), ss->fd, + plaintext->len + + SSL3_COMPRESSION_MAX_EXPANSION)); + /* sslBuffer_Grow has set a memory error code. */ + /* Perhaps we should send an alert. (but we have no memory!) */ + PORT_Free(plaintext->buf); + return SECFailure; + } + } + + rv = crSpec->decompressor(crSpec->decompressContext, + databuf->buf, + (int *)&databuf->len, + databuf->space, + plaintext->buf, + plaintext->len); + + if (rv != SECSuccess) { + int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE); + SSL3_SendAlert(ss, alert_fatal, + isTLS ? decompression_failure + : bad_record_mac); + + /* There appears to be a bug with (at least) Apache + OpenSSL where + * resumed SSLv3 connections don't actually use compression. See + * comments 93-95 of + * https://bugzilla.mozilla.org/show_bug.cgi?id=275744 + * + * So, if we get a decompression error, and the record appears to + * be already uncompressed, then we return a more specific error + * code to hopefully save somebody some debugging time in the + * future. + */ + if (plaintext->len >= 4) { + unsigned int len = ((unsigned int)plaintext->buf[1] << 16) | + ((unsigned int)plaintext->buf[2] << 8) | + (unsigned int)plaintext->buf[3]; + if (len == plaintext->len - 4) { + /* This appears to be uncompressed already */ + err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD; + } + } + + PORT_Free(plaintext->buf); + PORT_SetError(err); + return SECFailure; + } + + PORT_Free(plaintext->buf); } /* - ** Having completed the decompression, check the length again. + ** Having completed the decompression, check the length again. */ if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) { - SSL3_SendAlert(ss, alert_fatal, record_overflow); - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - return SECFailure; + 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 == content_application_data) { - if (ss->firstHsDone) - return SECSuccess; - (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); - PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); - return SECFailure; + 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, databuf); + } + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA); + return SECFailure; } - /* It's a record that must be handled by ssl itself, not the application. +/* It's a record that must be handled by ssl itself, not the application. */ process_it: /* XXX Get the xmit lock here. Odds are very high that we'll be xmiting @@ -12381,29 +12746,29 @@ process_it: ** they return SECFailure or SECWouldBlock. */ switch (rType) { - case content_change_cipher_spec: - rv = ssl3_HandleChangeCipherSpecs(ss, databuf); - break; - case content_alert: - rv = ssl3_HandleAlert(ss, databuf); - break; - case content_handshake: - if (!IS_DTLS(ss)) { - rv = ssl3_HandleHandshake(ss, databuf); - } else { - rv = dtls_HandleHandshake(ss, databuf); - } - break; - /* - case content_application_data is handled before this switch - */ - default: - SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", - SSL_GETPID(), ss->fd, cText->type)); - /* XXX Send an alert ??? */ - PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); - rv = SECFailure; - break; + case content_change_cipher_spec: + rv = ssl3_HandleChangeCipherSpecs(ss, databuf); + break; + case content_alert: + rv = ssl3_HandleAlert(ss, databuf); + break; + case content_handshake: + if (!IS_DTLS(ss)) { + rv = ssl3_HandleHandshake(ss, databuf); + } else { + rv = dtls_HandleHandshake(ss, databuf); + } + break; + /* + case content_application_data is handled before this switch + */ + default: + SSL_DBG(("%d: SSL3[%d]: bogus content type=%d", + SSL_GETPID(), ss->fd, cText->type)); + PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE); + ssl3_DecodeError(ss); + rv = SECFailure; + break; } ssl_ReleaseSSL3HandshakeLock(ss); @@ -12414,94 +12779,113 @@ process_it: * 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; +} + /* Called from ssl3_InitState, immediately below. */ /* Caller must hold the SpecWriteLock. */ -static void -ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec) +void +ssl3_InitCipherSpec(ssl3CipherSpec *spec) { - spec->cipher_def = &bulk_cipher_defs[cipher_null]; + spec->cipher_def = &bulk_cipher_defs[cipher_null]; PORT_Assert(spec->cipher_def->cipher == cipher_null); - spec->mac_def = &mac_defs[mac_null]; + spec->mac_def = &mac_defs[mac_null]; PORT_Assert(spec->mac_def->mac == mac_null); - spec->encode = Null_Cipher; - spec->decode = Null_Cipher; - spec->destroy = NULL; - spec->compressor = NULL; - spec->decompressor = NULL; - spec->destroyCompressContext = NULL; + spec->encode = Null_Cipher; + spec->decode = Null_Cipher; + spec->compressor = NULL; + spec->decompressor = NULL; + spec->destroyCompressContext = NULL; spec->destroyDecompressContext = NULL; - spec->mac_size = 0; - spec->master_secret = NULL; - spec->bypassCiphers = PR_FALSE; + spec->mac_size = 0; + spec->master_secret = NULL; - spec->msItem.data = NULL; - spec->msItem.len = 0; + spec->msItem.data = NULL; + spec->msItem.len = 0; - spec->client.write_key = NULL; - spec->client.write_mac_key = NULL; + spec->client.write_key = NULL; + spec->client.write_mac_key = NULL; spec->client.write_mac_context = NULL; - spec->server.write_key = NULL; - spec->server.write_mac_key = NULL; + spec->server.write_key = NULL; + spec->server.write_mac_key = NULL; spec->server.write_mac_context = NULL; - spec->write_seq_num.high = 0; - spec->write_seq_num.low = 0; - - spec->read_seq_num.high = 0; - spec->read_seq_num.low = 0; + spec->write_seq_num = 0; + spec->read_seq_num = 0; + spec->epoch = 0; - spec->epoch = 0; + spec->refCt = 128; /* Arbitrarily high number to prevent + * non-TLS 1.3 cipherSpecs from being + * GCed. This will be overwritten with + * a valid refCt for TLS 1.3. */ dtls_InitRecvdRecords(&spec->recvdRecords); - - spec->version = ss->vrange.max; } -/* Called from: ssl3_SendRecord -** ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake() -** ssl3_SendClientHello() -** ssl3_HandleV2ClientHello() -** ssl3_HandleRecord() +/* Called from: ssl3_SendRecord +** ssl3_SendClientHello() +** ssl3_HandleV2ClientHello() +** ssl3_HandleRecord() ** ** This function should perhaps acquire and release the SpecWriteLock. ** ** */ -static SECStatus +SECStatus ssl3_InitState(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (ss->ssl3.initialized) - return SECSuccess; /* Function should be idempotent */ + return SECSuccess; /* Function should be idempotent */ ss->ssl3.policy = SSL_ALLOWED; + ssl_InitSecState(&ss->sec); + ssl_GetSpecWriteLock(ss); ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0]; ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1]; + ssl3_InitCipherSpec(ss->ssl3.crSpec); + ssl3_InitCipherSpec(ss->ssl3.prSpec); + ss->ssl3.crSpec->version = ss->ssl3.prSpec->version = ss->vrange.max; + ssl_ReleaseSpecWriteLock(ss); + ss->ssl3.hs.sendingSCSV = PR_FALSE; - ssl3_InitCipherSpec(ss, ss->ssl3.crSpec); - ssl3_InitCipherSpec(ss, ss->ssl3.prSpec); ss->ssl3.hs.preliminaryInfo = 0; - ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello; -#ifndef NSS_DISABLE_ECC - ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss); -#endif - ssl_ReleaseSpecWriteLock(ss); - - PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData)); + ssl3_ResetExtensionData(&ss->xtnData); + PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions); if (IS_DTLS(ss)) { - ss->ssl3.hs.sendMessageSeq = 0; - ss->ssl3.hs.recvMessageSeq = 0; - ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_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.sendMessageSeq = 0; + ss->ssl3.hs.recvMessageSeq = 0; + ss->ssl3.hs.rtTimeoutMs = 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.pskBinderKey = 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.certificateRequest = NULL; + PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs); PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space); ss->ssl3.hs.messages.buf = NULL; @@ -12509,83 +12893,14 @@ ssl3_InitState(sslSocket *ss) ss->ssl3.hs.receivedNewSessionTicket = PR_FALSE; PORT_Memset(&ss->ssl3.hs.newSessionTicket, 0, - sizeof(ss->ssl3.hs.newSessionTicket)); + sizeof(ss->ssl3.hs.newSessionTicket)); - ss->ssl3.initialized = PR_TRUE; - return SECSuccess; -} - -/* 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. - */ -ssl3KeyPair * -ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey) -{ - ssl3KeyPair * pair; + ss->ssl3.hs.zeroRttState = ssl_0rtt_none; - if (!privKey || !pubKey) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return NULL; - } - pair = PORT_ZNew(ssl3KeyPair); - if (!pair) - return NULL; /* error code is set. */ - pair->refCount = 1; - pair->privKey = privKey; - pair->pubKey = pubKey; - return pair; /* success */ -} - -ssl3KeyPair * -ssl3_GetKeyPairRef(ssl3KeyPair * keyPair) -{ - PR_ATOMIC_INCREMENT(&keyPair->refCount); - return keyPair; -} + ssl_FilterSupportedGroups(ss); -void -ssl3_FreeKeyPair(ssl3KeyPair * keyPair) -{ - PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount); - if (!newCount) { - if (keyPair->privKey) - SECKEY_DestroyPrivateKey(keyPair->privKey); - if (keyPair->pubKey) - SECKEY_DestroyPublicKey( keyPair->pubKey); - PORT_Free(keyPair); - } -} - -/* - * Creates the public and private RSA keys for SSL Step down. - * Called from SSL_ConfigSecureServer in sslsecur.c - */ -SECStatus -ssl3_CreateRSAStepDownKeys(sslSocket *ss) -{ - SECStatus rv = SECSuccess; - SECKEYPrivateKey * privKey; /* RSA step down key */ - SECKEYPublicKey * pubKey; /* RSA step down key */ - - if (ss->stepDownKeyPair) - ssl3_FreeKeyPair(ss->stepDownKeyPair); - ss->stepDownKeyPair = NULL; -#ifndef HACKED_EXPORT_SERVER - /* Sigh, should have a get key strength call for private keys */ - if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) > - EXPORT_RSA_KEY_LENGTH) { - /* need to ask for the key size in bits */ - privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB, - &pubKey, NULL); - if (!privKey || !pubKey || - !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - } - } -#endif - return rv; + ss->ssl3.initialized = PR_TRUE; + return SECSuccess; } /* record the export policy for this cipher suite */ @@ -12594,9 +12909,9 @@ ssl3_SetPolicy(ssl3CipherSuite which, int policy) { ssl3CipherSuiteCfg *suite; - suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); + suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites); if (suite == NULL) { - return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ } suite->policy = policy; @@ -12606,17 +12921,17 @@ ssl3_SetPolicy(ssl3CipherSuite which, int policy) SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy) { - ssl3CipherSuiteCfg *suite; - PRInt32 policy; - SECStatus rv; + const ssl3CipherSuiteCfg *suite; + PRInt32 policy; + SECStatus rv; suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); if (suite) { - policy = suite->policy; - rv = SECSuccess; + policy = suite->policy; + rv = SECSuccess; } else { - policy = SSL_NOT_ALLOWED; - rv = SECFailure; /* err code was set by Lookup. */ + policy = SSL_NOT_ALLOWED; + rv = SECFailure; /* err code was set by Lookup. */ } *oPolicy = policy; return rv; @@ -12628,9 +12943,9 @@ ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) { ssl3CipherSuiteCfg *suite; - suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); + suite = ssl_LookupCipherSuiteCfgMutable(which, cipherSuites); if (suite == NULL) { - return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ } suite->enabled = enabled; return SECSuccess; @@ -12640,17 +12955,17 @@ ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled) SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled) { - ssl3CipherSuiteCfg *suite; - PRBool pref; - SECStatus rv; + const ssl3CipherSuiteCfg *suite; + PRBool pref; + SECStatus rv; suite = ssl_LookupCipherSuiteCfg(which, cipherSuites); if (suite) { - pref = suite->enabled; - rv = SECSuccess; + pref = suite->enabled; + rv = SECSuccess; } else { - pref = SSL_NOT_ALLOWED; - rv = SECFailure; /* err code was set by Lookup. */ + pref = SSL_NOT_ALLOWED; + rv = SECFailure; /* err code was set by Lookup. */ } *enabled = pref; return rv; @@ -12661,67 +12976,77 @@ ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled) { ssl3CipherSuiteCfg *suite; - suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); + suite = ssl_LookupCipherSuiteCfgMutable(which, ss->cipherSuites); if (suite == NULL) { - return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ + return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */ } suite->enabled = enabled; return SECSuccess; } SECStatus -ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) +ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *enabled) { - ssl3CipherSuiteCfg *suite; - PRBool pref; - SECStatus rv; + const ssl3CipherSuiteCfg *suite; + PRBool pref; + SECStatus rv; suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites); if (suite) { - pref = suite->enabled; - rv = SECSuccess; + pref = suite->enabled; + rv = SECSuccess; } else { - pref = SSL_NOT_ALLOWED; - rv = SECFailure; /* err code was set by Lookup. */ + pref = SSL_NOT_ALLOWED; + rv = SECFailure; /* err code was set by Lookup. */ } *enabled = pref; return rv; } SECStatus -SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms, - unsigned int count) +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_SignaturePrefSet", + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SignatureSchemePrefSet", SSL_GETPID(), fd)); PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - if (!count || count > MAX_SIGNATURE_ALGORITHMS) { + 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.signatureAlgorithmCount = 0; + ss->ssl3.signatureSchemeCount = 0; for (i = 0; i < count; ++i) { - if (!ssl3_IsSupportedSignatureAlgorithm(&algorithms[i])) { - SSL_DBG(("%d: SSL[%d]: invalid signature algorithm set %d/%d", - SSL_GETPID(), fd, algorithms[i].sigAlg, - algorithms[i].hashAlg)); + if (!ssl_IsSupportedSignatureScheme(schemes[i])) { + SSL_DBG(("%d: SSL[%d]: invalid signature scheme %d ignored", + SSL_GETPID(), fd, schemes[i])); continue; } - ss->ssl3.signatureAlgorithms[ss->ssl3.signatureAlgorithmCount++] = - algorithms[i]; + ss->ssl3.signatureSchemes[ss->ssl3.signatureSchemeCount++] = schemes[i]; } - if (ss->ssl3.signatureAlgorithmCount == 0) { + if (ss->ssl3.signatureSchemeCount == 0) { PORT_SetError(SSL_ERROR_NO_SUPPORTED_SIGNATURE_ALGORITHM); return SECFailure; } @@ -12729,11 +13054,51 @@ SSL_SignaturePrefSet(PRFileDesc *fd, const SSLSignatureAndHashAlg *algorithms, } 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 requiredSpace; + unsigned int i; ss = ssl_FindSocket(fd); if (!ss) { @@ -12744,73 +13109,37 @@ SSL_SignaturePrefGet(PRFileDesc *fd, SSLSignatureAndHashAlg *algorithms, } if (!algorithms || !count || - maxCount < ss->ssl3.signatureAlgorithmCount) { + maxCount < ss->ssl3.signatureSchemeCount) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - requiredSpace = - ss->ssl3.signatureAlgorithmCount * sizeof(SSLSignatureAndHashAlg); - PORT_Memcpy(algorithms, ss->ssl3.signatureAlgorithms, requiredSpace); - *count = ss->ssl3.signatureAlgorithmCount; + 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() { - return MAX_SIGNATURE_ALGORITHMS; +SSL_SignatureMaxCount() +{ + 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.signatureAlgorithms, defaultSignatureAlgorithms, - sizeof(defaultSignatureAlgorithms)); - ss->ssl3.signatureAlgorithmCount = PR_ARRAY_SIZE(defaultSignatureAlgorithms); -} - -/* ssl3_config_match_init must have already been called by - * the caller of this function. - */ -SECStatus -ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) -{ - int i, count = 0; - - PORT_Assert(ss != 0); - if (!ss) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; - } - if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - *size = 0; - return SECSuccess; - } - if (cs == NULL) { - *size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE); - return SECSuccess; - } - - /* ssl3_config_match_init was called by the caller of this function. */ - for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) { - ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i]; - if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange, ss)) { - if (cs != NULL) { - *cs++ = 0x00; - *cs++ = (suite->cipher_suite >> 8) & 0xFF; - *cs++ = suite->cipher_suite & 0xFF; - } - count++; - } - } - *size = count; - return SECSuccess; + 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, +** 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. @@ -12820,41 +13149,42 @@ ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size) SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache) { - sslSessionID * sid = ss->sec.ci.sid; - SECStatus rv; + sslSessionID *sid = ss->sec.ci.sid; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); if (!ss->firstHsDone || - ((ss->version >= SSL_LIBRARY_VERSION_3_0) && - ss->ssl3.initialized && - (ss->ssl3.hs.ws != idle_handshake))) { - PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); - return SECFailure; + (ss->ssl3.initialized && (ss->ssl3.hs.ws != idle_handshake))) { + PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); + return SECFailure; } if (IS_DTLS(ss)) { - dtls_RehandshakeCleanup(ss); + dtls_RehandshakeCleanup(ss); } - if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) { - PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED); - return SECFailure; + 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 (sid && flushCache) { - if (ss->sec.uncache) - ss->sec.uncache(sid); /* remove it from whichever cache it's in. */ - ssl_FreeSID(sid); /* dec ref count and free if zero. */ - ss->sec.ci.sid = NULL; + ss->sec.uncache(sid); /* 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); /**************************************/ + ssl_GetXmitBufLock(ss); /**************************************/ /* start off a new handshake. */ - rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss) - : ssl3_SendClientHello(ss, PR_FALSE); + if (ss->sec.isServer) { + rv = ssl3_SendHelloRequest(ss); + } else { + rv = ssl3_SendClientHello(ss, client_hello_renegotiation); + } - ssl_ReleaseXmitBufLock(ss); /**************************************/ + ssl_ReleaseXmitBufLock(ss); /**************************************/ return rv; } @@ -12864,70 +13194,146 @@ ssl3_DestroySSL3Info(sslSocket *ss) { if (ss->ssl3.clientCertificate != NULL) - CERT_DestroyCertificate(ss->ssl3.clientCertificate); + CERT_DestroyCertificate(ss->ssl3.clientCertificate); if (ss->ssl3.clientPrivateKey != NULL) - SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); if (ss->ssl3.peerCertArena != NULL) - ssl3_CleanupPeerCerts(ss); + ssl3_CleanupPeerCerts(ss); if (ss->ssl3.clientCertChain != NULL) { - CERT_DestroyCertificateList(ss->ssl3.clientCertChain); - 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 */ -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - if (ss->ssl3.hs.hashType == handshake_hash_combo) { - SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE); - MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE); - } else if (ss->ssl3.hs.hashType == handshake_hash_single) { - ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE); - } - } -#endif if (ss->ssl3.hs.md5) { - PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE); + 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.clientSigAndHash) { - PORT_Free(ss->ssl3.hs.clientSigAndHash); + PK11_DestroyContext(ss->ssl3.hs.sha, PR_TRUE); } if (ss->ssl3.hs.messages.buf) { - PORT_Free(ss->ssl3.hs.messages.buf); - ss->ssl3.hs.messages.buf = NULL; - ss->ssl3.hs.messages.len = 0; - ss->ssl3.hs.messages.space = 0; + sslBuffer_Clear(&ss->ssl3.hs.messages); } /* 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); + + if (ss->ssl3.hs.certificateRequest) { + PORT_FreeArena(ss->ssl3.hs.certificateRequest->arena, PR_FALSE); + ss->ssl3.hs.certificateRequest = NULL; + } /* free up the CipherSpecs */ - ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/); - ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/); + ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE /*freeSrvName*/); + ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE /*freeSrvName*/); /* 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); - } + dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight); + if (ss->ssl3.hs.recvdFragments.buf) { + PORT_Free(ss->ssl3.hs.recvdFragments.buf); + } } - if (ss->ssl3.dheGroups) { - PORT_Free(ss->ssl3.dheGroups); - } + /* Destroy remote extensions */ + ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions); + ssl3_ResetExtensionData(&ss->xtnData); + + /* Destroy TLS 1.3 cipher specs */ + tls13_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.pskBinderKey) + PK11_FreeSymKey(ss->ssl3.hs.pskBinderKey); + 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); ss->ssl3.initialized = PR_FALSE; - SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); + SECITEM_FreeItem(&ss->xtnData.nextProto, 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; + + policyOid = MAP_NULL(kea_defs[suite->key_exchange_alg].oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL_KX)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); + continue; + } + + policyOid = MAP_NULL(ssl_GetBulkCipherDef(suite)->oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, SSL_NOT_ALLOWED); + continue; + } + + if (ssl_GetBulkCipherDef(suite)->type != type_aead) { + policyOid = MAP_NULL(mac_defs[suite->mac_alg].oid); + rv = NSS_GetAlgorithmPolicy(policyOid, &policy); + if (rv == SECSuccess && !(policy & NSS_USE_ALG_IN_SSL)) { + ssl_CipherPrefSetDefault(suite->cipher_suite, PR_FALSE); + ssl_CipherPolicySet(suite->cipher_suite, + SSL_NOT_ALLOWED); + continue; + } + } + } + + rv = ssl3_ConstrainRangeByPolicy(); + + return rv; } /* End of ssl3con.c */ diff --git a/nss/lib/ssl/ssl3ecc.c b/nss/lib/ssl/ssl3ecc.c index 94008a0..72c4ba5 100644 --- a/nss/lib/ssl/ssl3ecc.c +++ b/nss/lib/ssl/ssl3ecc.c @@ -8,10 +8,9 @@ /* ECC code moved here from ssl3con.c */ -#include "nss.h" #include "cert.h" #include "ssl.h" -#include "cryptohi.h" /* for DSAU_ stuff */ +#include "cryptohi.h" /* for DSAU_ stuff */ #include "keyhi.h" #include "secder.h" #include "secitem.h" @@ -19,6 +18,7 @@ #include "sslimpl.h" #include "sslproto.h" #include "sslerr.h" +#include "ssl3ext.h" #include "prtime.h" #include "prinrval.h" #include "prerror.h" @@ -31,145 +31,36 @@ #include <stdio.h> -#ifndef NSS_DISABLE_ECC - #ifndef PK11_SETATTRS -#define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \ - (x)->pValue=(v); (x)->ulValueLen = (l); +#define PK11_SETATTRS(x, id, v, l) \ + (x)->type = (id); \ + (x)->pValue = (v); \ + (x)->ulValueLen = (l); #endif -#define SSL_GET_SERVER_PUBLIC_KEY(sock, type) \ - (ss->serverCerts[type].serverKeyPair ? \ - ss->serverCerts[type].serverKeyPair->pubKey : NULL) - -#define SSL_IS_CURVE_NEGOTIATED(curvemsk, curveName) \ - ((curveName > ec_noName) && \ - (curveName < ec_pastLastName) && \ - ((1UL << curveName) & curvemsk) != 0) - - - -static SECStatus ssl3_CreateECDHEphemeralKeys(sslSocket *ss, ECName ec_curve); - -#define supportedCurve(x) (((x) > ec_noName) && ((x) < ec_pastLastName)) - -/* Table containing OID tags for elliptic curves named in the - * ECC-TLS IETF draft. - */ -static const SECOidTag ecName2OIDTag[] = { - 0, - SEC_OID_SECG_EC_SECT163K1, /* 1 */ - SEC_OID_SECG_EC_SECT163R1, /* 2 */ - SEC_OID_SECG_EC_SECT163R2, /* 3 */ - SEC_OID_SECG_EC_SECT193R1, /* 4 */ - SEC_OID_SECG_EC_SECT193R2, /* 5 */ - SEC_OID_SECG_EC_SECT233K1, /* 6 */ - SEC_OID_SECG_EC_SECT233R1, /* 7 */ - SEC_OID_SECG_EC_SECT239K1, /* 8 */ - SEC_OID_SECG_EC_SECT283K1, /* 9 */ - SEC_OID_SECG_EC_SECT283R1, /* 10 */ - SEC_OID_SECG_EC_SECT409K1, /* 11 */ - SEC_OID_SECG_EC_SECT409R1, /* 12 */ - SEC_OID_SECG_EC_SECT571K1, /* 13 */ - SEC_OID_SECG_EC_SECT571R1, /* 14 */ - SEC_OID_SECG_EC_SECP160K1, /* 15 */ - SEC_OID_SECG_EC_SECP160R1, /* 16 */ - SEC_OID_SECG_EC_SECP160R2, /* 17 */ - SEC_OID_SECG_EC_SECP192K1, /* 18 */ - SEC_OID_SECG_EC_SECP192R1, /* 19 */ - SEC_OID_SECG_EC_SECP224K1, /* 20 */ - SEC_OID_SECG_EC_SECP224R1, /* 21 */ - SEC_OID_SECG_EC_SECP256K1, /* 22 */ - SEC_OID_SECG_EC_SECP256R1, /* 23 */ - SEC_OID_SECG_EC_SECP384R1, /* 24 */ - SEC_OID_SECG_EC_SECP521R1, /* 25 */ -}; - -static const PRUint16 curve2bits[] = { - 0, /* ec_noName = 0, */ - 163, /* ec_sect163k1 = 1, */ - 163, /* ec_sect163r1 = 2, */ - 163, /* ec_sect163r2 = 3, */ - 193, /* ec_sect193r1 = 4, */ - 193, /* ec_sect193r2 = 5, */ - 233, /* ec_sect233k1 = 6, */ - 233, /* ec_sect233r1 = 7, */ - 239, /* ec_sect239k1 = 8, */ - 283, /* ec_sect283k1 = 9, */ - 283, /* ec_sect283r1 = 10, */ - 409, /* ec_sect409k1 = 11, */ - 409, /* ec_sect409r1 = 12, */ - 571, /* ec_sect571k1 = 13, */ - 571, /* ec_sect571r1 = 14, */ - 160, /* ec_secp160k1 = 15, */ - 160, /* ec_secp160r1 = 16, */ - 160, /* ec_secp160r2 = 17, */ - 192, /* ec_secp192k1 = 18, */ - 192, /* ec_secp192r1 = 19, */ - 224, /* ec_secp224k1 = 20, */ - 224, /* ec_secp224r1 = 21, */ - 256, /* ec_secp256k1 = 22, */ - 256, /* ec_secp256r1 = 23, */ - 384, /* ec_secp384r1 = 24, */ - 521, /* ec_secp521r1 = 25, */ - 65535 /* ec_pastLastName */ -}; - -typedef struct Bits2CurveStr { - PRUint16 bits; - ECName curve; -} Bits2Curve; - -static const Bits2Curve bits2curve [] = { - { 192, ec_secp192r1 /* = 19, fast */ }, - { 160, ec_secp160r2 /* = 17, fast */ }, - { 160, ec_secp160k1 /* = 15, */ }, - { 160, ec_secp160r1 /* = 16, */ }, - { 163, ec_sect163k1 /* = 1, */ }, - { 163, ec_sect163r1 /* = 2, */ }, - { 163, ec_sect163r2 /* = 3, */ }, - { 192, ec_secp192k1 /* = 18, */ }, - { 193, ec_sect193r1 /* = 4, */ }, - { 193, ec_sect193r2 /* = 5, */ }, - { 224, ec_secp224r1 /* = 21, fast */ }, - { 224, ec_secp224k1 /* = 20, */ }, - { 233, ec_sect233k1 /* = 6, */ }, - { 233, ec_sect233r1 /* = 7, */ }, - { 239, ec_sect239k1 /* = 8, */ }, - { 256, ec_secp256r1 /* = 23, fast */ }, - { 256, ec_secp256k1 /* = 22, */ }, - { 283, ec_sect283k1 /* = 9, */ }, - { 283, ec_sect283r1 /* = 10, */ }, - { 384, ec_secp384r1 /* = 24, fast */ }, - { 409, ec_sect409k1 /* = 11, */ }, - { 409, ec_sect409r1 /* = 12, */ }, - { 521, ec_secp521r1 /* = 25, fast */ }, - { 571, ec_sect571k1 /* = 13, */ }, - { 571, ec_sect571r1 /* = 14, */ }, - { 65535, ec_noName } -}; - -typedef struct ECDHEKeyPairStr { - ssl3KeyPair * pair; - int error; /* error code of the call-once function */ - PRCallOnceType once; -} ECDHEKeyPair; - -/* arrays of ECDHE KeyPairs */ -static ECDHEKeyPair gECDHEKeyPairs[ec_pastLastName]; - SECStatus -ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) +ssl_NamedGroup2ECParams(PLArenaPool *arena, const sslNamedGroupDef *ecGroup, + SECKEYECParams *params) { SECOidData *oidData = NULL; - if ((curve <= ec_noName) || (curve >= ec_pastLastName) || - ((oidData = SECOID_FindOIDByTag(ecName2OIDTag[curve])) == 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; } - SECITEM_AllocItem(arena, params, (2 + oidData->oid.len)); + 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 @@ -182,28 +73,45 @@ ssl3_ECName2Params(PLArenaPool * arena, ECName curve, SECKEYECParams * params) return SECSuccess; } -static ECName -params2ecName(SECKEYECParams * params) +const sslNamedGroupDef * +ssl_ECPubKey2NamedGroup(const SECKEYPublicKey *pubKey) { - SECItem oid = { siBuffer, NULL, 0}; + SECItem oid = { siBuffer, NULL, 0 }; SECOidData *oidData = NULL; - ECName i; + 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 ec_noName; + 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 ec_noName; - for (i = ec_noName + 1; i < ec_pastLastName; i++) { - if (ecName2OIDTag[i] == oidData->offset) - return i; + 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 ec_noName; + return NULL; } /* Caller must set hiLevel error code. */ @@ -211,21 +119,20 @@ static SECStatus ssl3_ComputeECDHKeyHash(SSLHashType hashAlg, SECItem ec_params, SECItem server_ecpoint, SSL3Random *client_rand, SSL3Random *server_rand, - SSL3Hashes *hashes, PRBool bypassPKCS11) + SSL3Hashes *hashes) { - PRUint8 * hashBuf; - PRUint8 * pBuf; - SECStatus rv = SECSuccess; - unsigned int bufLen; + PRUint8 *hashBuf; + PRUint8 *pBuf; + SECStatus rv = SECSuccess; + unsigned int bufLen; /* - * XXX For now, 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) + * 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]; + PRUint8 buf[2 * SSL3_RANDOM_LENGTH + 2 + 1 + 256]; - bufLen = 2*SSL3_RANDOM_LENGTH + ec_params.len + 1 + server_ecpoint.len; + bufLen = 2 * SSL3_RANDOM_LENGTH + ec_params.len + 1 + server_ecpoint.len; if (bufLen <= sizeof buf) { hashBuf = buf; } else { @@ -236,45 +143,44 @@ ssl3_ComputeECDHKeyHash(SSLHashType hashAlg, } memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH); - pBuf = hashBuf + SSL3_RANDOM_LENGTH; + pBuf = hashBuf + SSL3_RANDOM_LENGTH; memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH); - pBuf += SSL3_RANDOM_LENGTH; + pBuf += SSL3_RANDOM_LENGTH; memcpy(pBuf, ec_params.data, ec_params.len); - pBuf += 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; + pBuf += server_ecpoint.len; PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen); - rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes, - bypassPKCS11); + 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)); + hashes->u.s.md5, MD5_LENGTH)); PRINT_BUF(95, (NULL, "ECDHkey hash: SHA1 result", - hashes->u.s.sha, SHA1_LENGTH)); + 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) +ssl3_SendECDHClientKeyExchange(sslSocket *ss, SECKEYPublicKey *svrPubKey) { - PK11SymKey * pms = NULL; - SECStatus rv = SECFailure; - PRBool isTLS, isTLS12; - CK_MECHANISM_TYPE target; - SECKEYPublicKey *pubKey = NULL; /* Ephemeral ECDH key */ - SECKEYPrivateKey *privKey = NULL; /* Ephemeral ECDH key */ + 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)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); @@ -284,17 +190,22 @@ ssl3_SendECDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) PORT_SetError(SEC_ERROR_BAD_KEY); goto loser; } - /* XXX SHOULD CALL ssl3_CreateECDHEphemeralKeys here, instead! */ - privKey = SECKEY_CreateECPrivateKey(&svrPubKey->u.ec.DEREncodedParams, - &pubKey, ss->pkcs11PinArg); - if (!privKey || !pubKey) { - ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL); - rv = SECFailure; - 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)); + pubKey->u.ec.publicValue.data, + pubKey->u.ec.publicValue.len)); if (isTLS12) { target = CKM_TLS12_MASTER_KEY_DERIVE_DH; @@ -304,84 +215,108 @@ ssl3_SendECDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey) target = CKM_SSL3_MASTER_KEY_DERIVE_DH; } - /* Determine the PMS */ - pms = PK11_PubDeriveWithKDF(privKey, svrPubKey, PR_FALSE, NULL, NULL, - CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0, - CKD_NULL, NULL, NULL); + /* 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) { - SSL3AlertDescription desc = illegal_parameter; - (void)SSL3_SendAlert(ss, alert_fatal, desc); + (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); goto loser; } - SECKEY_DestroyPrivateKey(privKey); - privKey = NULL; - rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange, - pubKey->u.ec.publicValue.len + 1); + pubKey->u.ec.publicValue.len + 1); if (rv != SECSuccess) { - goto loser; /* err set by ssl3_AppendHandshake* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } - rv = ssl3_AppendHandshakeVariable(ss, - pubKey->u.ec.publicValue.data, - pubKey->u.ec.publicValue.len, 1); - SECKEY_DestroyPublicKey(pubKey); - pubKey = NULL; + 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* */ + goto loser; /* err set by ssl3_AppendHandshake* */ } - rv = ssl3_InitPendingCipherSpec(ss, pms); - PK11_FreeSymKey(pms); pms = NULL; - + rv = ssl3_InitPendingCipherSpec(ss, pms); if (rv != SECSuccess) { ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); goto loser; } - rv = SECSuccess; + PK11_FreeSymKey(pms); + ssl_FreeEphemeralKeyPair(keyPair); + return SECSuccess; loser: - if(pms) PK11_FreeSymKey(pms); - if(privKey) SECKEY_DestroyPrivateKey(privKey); - if(pubKey) SECKEY_DestroyPublicKey(pubKey); - return rv; + if (pms) + PK11_FreeSymKey(pms); + if (keyPair) + ssl_FreeEphemeralKeyPair(keyPair); + return SECFailure; +} + +/* This function returns the size of the key_exchange field in + * the KeyShareEntry structure, i.e.: + * opaque point <1..2^8-1>; */ +unsigned int +tls13_SizeOfECDHEKeyShareKEX(const SECKEYPublicKey *pubKey) +{ + PORT_Assert(pubKey->keyType == ecKey); + return pubKey->u.ec.publicValue.len; } +/* This function encodes the key_exchange field in + * the KeyShareEntry structure. */ +SECStatus +tls13_EncodeECDHEKeyShareKEX(const sslSocket *ss, const SECKEYPublicKey *pubKey) +{ + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(pubKey->keyType == ecKey); + + return ssl3_ExtAppendHandshake(ss, pubKey->u.ec.publicValue.data, + pubKey->u.ec.publicValue.len); +} /* ** Called from ssl3_HandleClientKeyExchange() */ SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, - PRUint32 length, - SECKEYPublicKey *srvrPubKey, - SECKEYPrivateKey *srvrPrivKey) + PRUint32 length, + sslKeyPair *serverKeyPair) { - PK11SymKey * pms; - SECStatus rv; - SECKEYPublicKey clntPubKey; - CK_MECHANISM_TYPE target; + 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) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); clntPubKey.keyType = ecKey; clntPubKey.u.ec.DEREncodedParams.len = - srvrPubKey->u.ec.DEREncodedParams.len; + serverKeyPair->pubKey->u.ec.DEREncodedParams.len; clntPubKey.u.ec.DEREncodedParams.data = - srvrPubKey->u.ec.DEREncodedParams.data; + serverKeyPair->pubKey->u.ec.DEREncodedParams.data; + clntPubKey.u.ec.encoding = serverKeyPair->pubKey->u.ec.encoding; rv = ssl3_ConsumeHandshakeVariable(ss, &clntPubKey.u.ec.publicValue, 1, &b, &length); if (rv != SECSuccess) { - SEND_ALERT - return SECFailure; /* XXX Who sets the error code?? */ + 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); @@ -396,131 +331,166 @@ ssl3_HandleECDHClientKeyExchange(sslSocket *ss, SSL3Opaque *b, } /* Determine the PMS */ - pms = PK11_PubDeriveWithKDF(srvrPrivKey, &clntPubKey, PR_FALSE, NULL, NULL, - CKM_ECDH1_DERIVE, target, CKA_DERIVE, 0, - CKD_NULL, NULL, NULL); + 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. */ - ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + errCode = ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE); + PORT_SetError(errCode); return SECFailure; } - rv = ssl3_InitPendingCipherSpec(ss, pms); + rv = ssl3_InitPendingCipherSpec(ss, pms); PK11_FreeSymKey(pms); if (rv != SECSuccess) { - SEND_ALERT - return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */ + /* error code set by ssl3_InitPendingCipherSpec */ + return SECFailure; } + ss->sec.keaGroup = ssl_ECPubKey2NamedGroup(&clntPubKey); return SECSuccess; } -ECName -ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits) +/* +** Take an encoded key share and make a public key out of it. +*/ +SECStatus +ssl_ImportECDHKeyShare(sslSocket *ss, SECKEYPublicKey *peerKey, + SSL3Opaque *b, PRUint32 length, + const sslNamedGroupDef *ecGroup) { - int i; + SECStatus rv; + SECItem ecPoint = { siBuffer, NULL, 0 }; - for ( i = 0; bits2curve[i].curve != ec_noName; i++) { - if (bits2curve[i].bits < requiredECCbits) - continue; - if (SSL_IS_CURVE_NEGOTIATED(curvemsk, bits2curve[i].curve)) { - return bits2curve[i].curve; - } + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + if (!length) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_ECDHE_KEY_SHARE); + return SECFailure; } - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return ec_noName; -} -/* find the "weakest link". Get strength of signature key and of sym key. - * choose curve for the weakest of those two. - */ -ECName -ssl3_GetCurveNameForServerSocket(sslSocket *ss) -{ - SECKEYPublicKey * svrPublicKey = NULL; - ECName ec_curve = ec_noName; - int signatureKeyStrength = 521; - int requiredECCbits = ss->sec.secretKeyBits * 2; - - if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa) { - svrPublicKey = SSL_GET_SERVER_PUBLIC_KEY(ss, kt_ecdh); - if (svrPublicKey) - ec_curve = params2ecName(&svrPublicKey->u.ec.DEREncodedParams); - if (!SSL_IS_CURVE_NEGOTIATED(ss->ssl3.hs.negotiatedECCurves, ec_curve)) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return ec_noName; - } - signatureKeyStrength = curve2bits[ ec_curve ]; - } else { - /* RSA is our signing cert */ - int serverKeyStrengthInBits; + /* 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; + } - svrPublicKey = SSL_GET_SERVER_PUBLIC_KEY(ss, kt_rsa); - if (!svrPublicKey) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return ec_noName; - } + 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; + } + if (ecGroup->name == ssl_grp_ec_curve25519) { + peerKey->u.ec.encoding = ECPoint_XOnly; + } else { + peerKey->u.ec.encoding = ECPoint_Uncompressed; + } - /* currently strength in bytes */ - serverKeyStrengthInBits = svrPublicKey->u.rsa.modulus.len; - if (svrPublicKey->u.rsa.modulus.data[0] == 0) { - serverKeyStrengthInBits--; - } - /* convert to strength in bits */ - serverKeyStrengthInBits *= BPB; + /* copy publicValue in peerKey */ + ecPoint.data = b; + ecPoint.len = length; - signatureKeyStrength = - SSL_RSASTRENGTH_TO_ECSTRENGTH(serverKeyStrengthInBits); + rv = SECITEM_CopyItem(peerKey->arena, &peerKey->u.ec.publicValue, &ecPoint); + if (rv != SECSuccess) { + return SECFailure; } - if ( requiredECCbits > signatureKeyStrength ) - requiredECCbits = signatureKeyStrength; - return ssl3_GetCurveWithECKeyStrength(ss->ssl3.hs.negotiatedECCurves, - requiredECCbits); + return SECSuccess; } -/* function to clear out the lists */ -static SECStatus -ssl3_ShutdownECDHECurves(void *appData, void *nssData) +const sslNamedGroupDef * +ssl_GetECGroupWithStrength(sslSocket *ss, unsigned int requiredECCbits) { int i; - ECDHEKeyPair *keyPair = &gECDHEKeyPairs[0]; - for (i=0; i < ec_pastLastName; i++, keyPair++) { - if (keyPair->pair) { - ssl3_FreeKeyPair(keyPair->pair); + 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; } } - memset(gECDHEKeyPairs, 0, sizeof gECDHEKeyPairs); - return SECSuccess; + + PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); + return NULL; } -static PRStatus -ssl3_ECRegister(void) +/* 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) { - SECStatus rv; - rv = NSS_RegisterShutdown(ssl3_ShutdownECDHECurves, gECDHEKeyPairs); - if (rv != SECSuccess) { - gECDHEKeyPairs[ec_noName].error = PORT_GetError(); + 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 (cert->certType.authType == ssl_auth_rsa_sign) { + certKeySize = SECKEY_PublicKeyStrengthInBits(cert->serverKeyPair->pubKey); + certKeySize = + SSL_RSASTRENGTH_TO_ECSTRENGTH(certKeySize); + } else if (cert->certType.authType == ssl_auth_ecdsa || + cert->certType.authType == ssl_auth_ecdh_rsa || + cert->certType.authType == ssl_auth_ecdh_ecdsa) { + const sslNamedGroupDef *groupDef = cert->certType.namedCurve; + + /* We won't select a certificate unless the named curve has been + * negotiated (or supported_curves was absent), double check that. */ + PORT_Assert(groupDef->keaType == ssl_kea_ecdh); + PORT_Assert(ssl_NamedGroupEnabled(ss, groupDef)); + if (!ssl_NamedGroupEnabled(ss, groupDef)) { + return NULL; + } + certKeySize = groupDef->bits; + } else { + PORT_Assert(0); + return NULL; } - return (PRStatus)rv; + 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 */ -static SECStatus -ssl3_CreateECDHEphemeralKeyPair(ECName ec_curve, ssl3KeyPair** keyPair) +SECStatus +ssl_CreateECDHEphemeralKeyPair(const sslSocket *ss, + const sslNamedGroupDef *ecGroup, + sslEphemeralKeyPair **keyPair) { - SECKEYPrivateKey * privKey = NULL; - SECKEYPublicKey * pubKey = NULL; - SECKEYECParams ecParams = { siBuffer, NULL, 0 }; + SECKEYPrivateKey *privKey = NULL; + SECKEYPublicKey *pubKey = NULL; + SECKEYECParams ecParams = { siBuffer, NULL, 0 }; + sslEphemeralKeyPair *pair; - if (ssl3_ECName2Params(NULL, ec_curve, &ecParams) != SECSuccess) { + if (ssl_NamedGroup2ECParams(NULL, ecGroup, &ecParams) != SECSuccess) { return SECFailure; } - privKey = SECKEY_CreateECPrivateKey(&ecParams, &pubKey, NULL); + privKey = SECKEY_CreateECPrivateKey(&ecParams, &pubKey, ss->pkcs11PinArg); SECITEM_FreeItem(&ecParams, PR_FALSE); - if (!privKey || !pubKey || !(*keyPair = ssl3_NewKeyPair(privKey, pubKey))) { + if (!privKey || !pubKey || + !(pair = ssl_NewEphemeralKeyPair(ecGroup, privKey, pubKey))) { if (privKey) { SECKEY_DestroyPrivateKey(privKey); } @@ -531,147 +501,117 @@ ssl3_CreateECDHEphemeralKeyPair(ECName ec_curve, ssl3KeyPair** keyPair) return SECFailure; } - return SECSuccess; -} - -/* CallOnce function, called once for each named curve. */ -static PRStatus -ssl3_CreateECDHEphemeralKeyPairOnce(void * arg) -{ - ECName ec_curve = (ECName)arg; - ssl3KeyPair * keyPair = NULL; - - PORT_Assert(gECDHEKeyPairs[ec_curve].pair == NULL); - - /* ok, no one has generated a global key for this curve yet, do so */ - if (ssl3_CreateECDHEphemeralKeyPair(ec_curve, &keyPair) != SECSuccess) { - gECDHEKeyPairs[ec_curve].error = PORT_GetError(); - return PR_FAILURE; - } - - gECDHEKeyPairs[ec_curve].pair = keyPair; - return PR_SUCCESS; -} - -/* - * Creates the ephemeral public and private ECDH keys used by - * server in ECDHE_RSA and ECDHE_ECDSA handshakes. - * For now, the elliptic curve is chosen to be the same - * strength as the signing certificate (ECC or RSA). - * We need an API to specify the curve. This won't be a real - * issue until we further develop server-side support for ECC - * cipher suites. - */ -static SECStatus -ssl3_CreateECDHEphemeralKeys(sslSocket *ss, ECName ec_curve) -{ - ssl3KeyPair * keyPair = NULL; - - /* if there's no global key for this curve, make one. */ - if (gECDHEKeyPairs[ec_curve].pair == NULL) { - PRStatus status; - - status = PR_CallOnce(&gECDHEKeyPairs[ec_noName].once, ssl3_ECRegister); - if (status != PR_SUCCESS) { - PORT_SetError(gECDHEKeyPairs[ec_noName].error); - return SECFailure; - } - status = PR_CallOnceWithArg(&gECDHEKeyPairs[ec_curve].once, - ssl3_CreateECDHEphemeralKeyPairOnce, - (void *)ec_curve); - if (status != PR_SUCCESS) { - PORT_SetError(gECDHEKeyPairs[ec_curve].error); - 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")); } } - - keyPair = gECDHEKeyPairs[ec_curve].pair; - PORT_Assert(keyPair != NULL); - if (!keyPair) - return SECFailure; - ss->ephemeralECDHKeyPair = ssl3_GetKeyPairRef(keyPair); - +#endif return SECSuccess; } SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) { - PLArenaPool * arena = NULL; - SECKEYPublicKey *peerKey = NULL; - PRBool isTLS, isTLS12; - SECStatus rv; - int errCode = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH; - SSL3AlertDescription desc = illegal_parameter; - SSL3Hashes hashes; - SECItem signature = {siBuffer, NULL, 0}; - - SECItem ec_params = {siBuffer, NULL, 0}; - SECItem ec_point = {siBuffer, NULL, 0}; - unsigned char paramBuf[3]; /* only for curve_type == named_curve */ - SSLSignatureAndHashAlg sigAndHash; - - sigAndHash.hashAlg = ssl_hash_none; + 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); - isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); - /* XXX This works only for named curves, revisit this when - * we support generic curves. - */ - ec_params.len = sizeof paramBuf; + 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. */ + goto loser; /* malformed. */ } /* Fail if the curve is not a named curve */ - if ((ec_params.data[0] != ec_type_named) || - (ec_params.data[1] != 0) || - !supportedCurve(ec_params.data[2])) { - errCode = SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE; - desc = handshake_failure; - goto alert_loser; + 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. */ + goto loser; /* malformed. */ } - /* Fail if the ec point uses compressed representation */ - if (ec_point.data[0] != EC_POINT_FORM_UNCOMPRESSED) { - errCode = SEC_ERROR_UNSUPPORTED_EC_POINT_FORM; - desc = handshake_failure; - goto alert_loser; + + /* Fail if the provided point has length 0. */ + if (!ec_point.len) { + /* desc and errCode are initialized already */ + goto alert_loser; } - if (isTLS12) { - rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length, - &sigAndHash); + /* 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) { - goto loser; /* malformed or unsupported. */ + goto loser; /* malformed or unsupported. */ } - rv = ssl3_CheckSignatureAndHashAlgorithmConsistency( - ss, &sigAndHash, ss->sec.peerCert); + rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, + ss->sec.peerCert); if (rv != SECSuccess) { goto 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. */ + goto loser; /* malformed. */ } if (length != 0) { if (isTLS) desc = decode_error; - goto alert_loser; /* malformed. */ + goto alert_loser; /* malformed. */ } - PRINT_BUF(60, (NULL, "Server EC params", ec_params.data, - ec_params.len)); + 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. */ @@ -681,19 +621,18 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) /* * check to make sure the hash is signed by right guy */ - rv = ssl3_ComputeECDHKeyHash(sigAndHash.hashAlg, ec_params, ec_point, + rv = ssl3_ComputeECDHKeyHash(hashAlg, ec_params, ec_point, &ss->ssl3.hs.client_random, &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); + &hashes); if (rv != SECSuccess) { errCode = ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); goto alert_loser; } - rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature, - isTLS, ss->pkcs11PinArg); - if (rv != SECSuccess) { + rv = ssl3_VerifySignedHashes(ss, sigScheme, &hashes, &signature); + if (rv != SECSuccess) { errCode = ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); goto alert_loser; @@ -701,38 +640,30 @@ ssl3_HandleECDHServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length) arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); if (arena == NULL) { - goto no_memory; + errCode = SEC_ERROR_NO_MEMORY; + goto loser; } peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey); if (peerKey == NULL) { - goto no_memory; + errCode = SEC_ERROR_NO_MEMORY; + goto loser; } + peerKey->arena = arena; - peerKey->arena = arena; - peerKey->keyType = ecKey; - - /* set up EC parameters in peerKey */ - if (ssl3_ECName2Params(arena, ec_params.data[2], - &peerKey->u.ec.DEREncodedParams) != SECSuccess) { - /* we should never get here since we already - * checked that we are dealing with a supported curve - */ - errCode = SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE; + /* create public key from point data */ + rv = ssl_ImportECDHKeyShare(ss, peerKey, ec_point.data, ec_point.len, + ecGroup); + if (rv != SECSuccess) { + /* error code is set */ + desc = handshake_failure; + errCode = PORT_GetError(); goto alert_loser; } - - /* copy publicValue in peerKey */ - if (SECITEM_CopyItem(arena, &peerKey->u.ec.publicValue, &ec_point)) - { - goto no_memory; - } - peerKey->pkcs11Slot = NULL; - peerKey->pkcs11ID = CK_INVALID_HANDLE; + peerKey->pkcs11Slot = NULL; + peerKey->pkcs11ID = CK_INVALID_HANDLE; ss->sec.peerKey = peerKey; - ss->ssl3.hs.ws = wait_cert_request; - return SECSuccess; alert_loser: @@ -741,134 +672,117 @@ loser: if (arena) { PORT_FreeArena(arena, PR_FALSE); } - PORT_SetError( errCode ); - return SECFailure; - -no_memory: /* no-memory error has already been set. */ - if (arena) { - PORT_FreeArena(arena, PR_FALSE); - } - ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); + PORT_SetError(errCode); return SECFailure; } SECStatus -ssl3_SendECDHServerKeyExchange( - sslSocket *ss, - const SSLSignatureAndHashAlg *sigAndHash) +ssl3_SendECDHServerKeyExchange(sslSocket *ss) { - const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def; - SECStatus rv = SECFailure; - int length; - PRBool isTLS, isTLS12; - SECItem signed_hash = {siBuffer, NULL, 0}; - SSL3Hashes hashes; - - SECKEYPublicKey * ecdhePub; - SECItem ec_params = {siBuffer, NULL, 0}; - unsigned char paramBuf[3]; - ECName curve; - SSL3KEAType certIndex; + 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 */ - curve = ssl3_GetCurveNameForServerSocket(ss); - if (curve == ec_noName) { + ecGroup = ssl_GetECGroupForServerSocket(ss); + if (!ecGroup) { goto loser; } + PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)); if (ss->opt.reuseServerECDHEKey) { - rv = ssl3_CreateECDHEphemeralKeys(ss, curve); + rv = ssl_CreateStaticECDHEKey(ss, ecGroup); + if (rv != SECSuccess) { + goto loser; + } + keyPair = (sslEphemeralKeyPair *)PR_NEXT_LINK(&ss->ephemeralKeyPairs); } else { - rv = ssl3_CreateECDHEphemeralKeyPair(curve, &ss->ephemeralECDHKeyPair); - } - if (rv != SECSuccess) { - goto loser; + rv = ssl_CreateECDHEphemeralKeyPair(ss, ecGroup, &keyPair); + if (rv != SECSuccess) { + goto loser; + } + PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs); } - ecdhePub = ss->ephemeralECDHKeyPair->pubKey; - PORT_Assert(ecdhePub != NULL); - if (!ecdhePub) { + PORT_Assert(keyPair); + if (!keyPair) { PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); return SECFailure; } - ec_params.len = sizeof paramBuf; + ec_params.len = sizeof(paramBuf); ec_params.data = paramBuf; - curve = params2ecName(&ecdhePub->u.ec.DEREncodedParams); - if (curve != ec_noName) { - ec_params.data[0] = ec_type_named; - ec_params.data[1] = 0x00; - ec_params.data[2] = curve; + 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->ssl3.pwSpec->version == SSL_LIBRARY_VERSION_TLS_1_2) { + hashAlg = ssl_SignatureSchemeToHashType(ss->ssl3.hs.signatureScheme); } else { - PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); - goto loser; + /* Use ssl_hash_none to represent the MD5+SHA1 combo. */ + hashAlg = ssl_hash_none; } - - rv = ssl3_ComputeECDHKeyHash(sigAndHash->hashAlg, - ec_params, - ecdhePub->u.ec.publicValue, + rv = ssl3_ComputeECDHKeyHash(hashAlg, ec_params, + pubKey->u.ec.publicValue, &ss->ssl3.hs.client_random, &ss->ssl3.hs.server_random, - &hashes, ss->opt.bypassPKCS11); + &hashes); if (rv != SECSuccess) { ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); goto loser; } - isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0); isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2); - /* XXX SSLKEAType isn't really a good choice for - * indexing certificates but that's all we have - * for now. - */ - if (kea_def->kea == kea_ecdhe_rsa) - certIndex = kt_rsa; - else /* kea_def->kea == kea_ecdhe_ecdsa */ - certIndex = kt_ecdh; - - rv = ssl3_SignHashes(&hashes, ss->serverCerts[certIndex].SERVERKEY, - &signed_hash, isTLS); + rv = ssl3_SignHashes(ss, &hashes, + ss->sec.serverCert->serverKeyPair->privKey, &signed_hash); if (rv != SECSuccess) { - goto loser; /* ssl3_SignHashes has set err. */ - } - if (signed_hash.data == NULL) { - /* how can this happen and rv == SECSuccess ?? */ - PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE); - goto loser; + goto loser; /* ssl3_SignHashes has set err. */ } length = ec_params.len + - 1 + ecdhePub->u.ec.publicValue.len + + 1 + pubKey->u.ec.publicValue.len + (isTLS12 ? 2 : 0) + 2 + signed_hash.len; rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + 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. */ + goto loser; /* err set by AppendHandshake. */ } - rv = ssl3_AppendHandshakeVariable(ss, ecdhePub->u.ec.publicValue.data, - ecdhePub->u.ec.publicValue.len, 1); + rv = ssl3_AppendHandshakeVariable(ss, pubKey->u.ec.publicValue.data, + pubKey->u.ec.publicValue.len, 1); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + goto loser; /* err set by AppendHandshake. */ } if (isTLS12) { - rv = ssl3_AppendSignatureAndHashAlgorithm(ss, sigAndHash); + rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.signatureScheme, 2); if (rv != SECSuccess) { - goto loser; /* err set by AppendHandshake. */ + 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. */ + goto loser; /* err set by AppendHandshake. */ } PORT_Free(signed_hash.data); @@ -880,76 +794,26 @@ loser: return SECFailure; } -/* Lists of ECC cipher suites for searching and disabling. */ - -static const ssl3CipherSuite ecdh_suites[] = { - 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 ecdh_ecdsa_suites[] = { - 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, - 0 /* end of list marker */ -}; - -static const ssl3CipherSuite ecdh_rsa_suites[] = { - 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 ecdhe_ecdsa_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_NULL_SHA, - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - 0 /* end of list marker */ -}; - -static const ssl3CipherSuite ecdhe_rsa_suites[] = { - 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_CBC_SHA, - TLS_ECDHE_RSA_WITH_NULL_SHA, - TLS_ECDHE_RSA_WITH_RC4_128_SHA, - 0 /* end of list marker */ -}; - /* List of all ECC cipher suites */ -static const ssl3CipherSuite ecSuites[] = { +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, @@ -965,195 +829,151 @@ static const ssl3CipherSuite ecSuites[] = { 0 /* end of list marker */ }; -/* On this socket, Disable the ECC cipher suites in the argument's list */ -SECStatus -ssl3_DisableECCSuites(sslSocket * ss, const ssl3CipherSuite * suite) -{ - if (!suite) - suite = ecSuites; - for (; *suite; ++suite) { - PORT_CheckSuccess(ssl3_CipherPrefSet(ss, *suite, PR_FALSE)); - } - return SECSuccess; -} +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 +}; -/* Look at the server certs configured on this socket, and disable any - * ECC cipher suites that are not supported by those certs. - */ -void -ssl3_FilterECCipherSuitesByServerCerts(sslSocket * ss) +/* Order(N^2). Yuk. */ +static PRBool +ssl_IsSuiteEnabled(const sslSocket *ss, const ssl3CipherSuite *list) { - CERTCertificate * svrCert; + const ssl3CipherSuite *suite; - svrCert = ss->serverCerts[kt_rsa].serverCert; - if (!svrCert) { - ssl3_DisableECCSuites(ss, ecdhe_rsa_suites); - } + for (suite = list; *suite; ++suite) { + PRBool enabled = PR_FALSE; + SECStatus rv = ssl3_CipherPrefGet(ss, *suite, &enabled); - svrCert = ss->serverCerts[kt_ecdh].serverCert; - if (!svrCert) { - ssl3_DisableECCSuites(ss, ecdh_suites); - ssl3_DisableECCSuites(ss, ecdhe_ecdsa_suites); - } else { - SECOidTag sigTag = SECOID_GetAlgorithmTag(&svrCert->signature); - - switch (sigTag) { - case SEC_OID_PKCS1_RSA_ENCRYPTION: - 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: - ssl3_DisableECCSuites(ss, ecdh_ecdsa_suites); - break; - 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: - ssl3_DisableECCSuites(ss, ecdh_rsa_suites); - break; - default: - ssl3_DisableECCSuites(ss, ecdh_suites); - break; - } + 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? */ -/* Order(N^2). Yuk. Also, this ignores export policy. */ PRBool -ssl3_IsECCEnabled(sslSocket * ss) +ssl_IsECCEnabled(const sslSocket *ss) { - const ssl3CipherSuite * suite; PK11SlotInfo *slot; /* make sure we can do ECC */ - slot = PK11_GetBestSlot(CKM_ECDH1_DERIVE, ss->pkcs11PinArg); + slot = PK11_GetBestSlot(CKM_ECDH1_DERIVE, ss->pkcs11PinArg); if (!slot) { return PR_FALSE; } PK11_FreeSlot(slot); /* make sure an ECC cipher is enabled */ - for (suite = ecSuites; *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; + return ssl_IsSuiteEnabled(ss, ssl_all_ec_suites); } -#define BE(n) 0, n - -/* Prefabricated TLS client hello extension, Elliptic Curves List, - * offers only 3 curves, the Suite B curves, 23-25 - */ -static const PRUint8 suiteBECList[12] = { - BE(10), /* Extension type */ - BE( 8), /* octets that follow ( 3 pairs + 1 length pair) */ - BE( 6), /* octets that follow ( 3 pairs) */ - BE(23), BE(24), BE(25) -}; - -/* Prefabricated TLS client hello extension, Elliptic Curves List, - * offers curves 1-25. - */ -static const PRUint8 tlsECList[56] = { - BE(10), /* Extension type */ - BE(52), /* octets that follow (25 pairs + 1 length pair) */ - BE(50), /* octets that follow (25 pairs) */ - BE( 1), BE( 2), BE( 3), BE( 4), BE( 5), BE( 6), BE( 7), - BE( 8), BE( 9), BE(10), BE(11), BE(12), BE(13), BE(14), BE(15), - BE(16), BE(17), BE(18), BE(19), BE(20), BE(21), BE(22), BE(23), - BE(24), BE(25) -}; - -static const PRUint8 ecPtFmt[6] = { - BE(11), /* Extension type */ - BE( 2), /* octets that follow */ - 1, /* octets that follow */ - 0 /* uncompressed type only */ -}; - -/* This function already presumes we can do ECC, ssl3_IsECCEnabled must be - * called before this function. It looks to see if we have a token which - * is capable of doing smaller than SuiteB curves. If the token can, we - * presume the token can do the whole SSL suite of curves. If it can't we - * presume the token that allowed ECC to be enabled can only do suite B - * curves. */ -static PRBool -ssl3_SuiteBOnly(sslSocket *ss) +PRBool +ssl_IsDHEEnabled(const sslSocket *ss) { - /* See if we can support small curves (like 163). If not, assume we can - * only support Suite-B curves (P-256, P-384, P-521). */ - PK11SlotInfo *slot = - PK11_GetBestSlotWithAttributes(CKM_ECDH1_DERIVE, 0, 163, - ss ? ss->pkcs11PinArg : NULL); - - if (!slot) { - /* nope, presume we can only do suite B */ - return PR_TRUE; - } - /* we can, presume we can do all curves */ - PK11_FreeSlot(slot); - return PR_FALSE; + return ssl_IsSuiteEnabled(ss, ssl_dhe_suites); } -/* Send our "canned" (precompiled) Supported Elliptic Curves extension, - * which says that we support all TLS-defined named curves. - */ +/* Send our Supported Groups extension. */ PRInt32 -ssl3_SendSupportedCurvesXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) +ssl_SendSupportedGroupsXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes) { - PRInt32 ecListSize = 0; - const PRUint8 *ecList = NULL; - - if (!ss || !ssl3_IsECCEnabled(ss)) + PRInt32 extension_length; + unsigned char enabledGroups[64]; + unsigned int enabledGroupsLen = 0; + unsigned int i; + PRBool ec; + PRBool ff = PR_FALSE; + + if (!ss) return 0; - if (ssl3_SuiteBOnly(ss)) { - ecListSize = sizeof suiteBECList; - ecList = suiteBECList; + /* 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 0; } else { - ecListSize = sizeof tlsECList; - ecList = tlsECList; + ec = ff = PR_TRUE; + } + + PORT_Assert(sizeof(enabledGroups) > SSL_NAMED_GROUP_COUNT * 2); + 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; + } + + if (append) { + (void)ssl_EncodeUintX(group->name, 2, &enabledGroups[enabledGroupsLen]); + } + enabledGroupsLen += 2; + } + + if (enabledGroupsLen == 0) { + return 0; } - if (maxBytes < (PRUint32)ecListSize) { + extension_length = + 2 /* extension type */ + + 2 /* extension length */ + + 2 /* enabled groups length */ + + enabledGroupsLen; + + if (maxBytes < (PRUint32)extension_length) { return 0; } + if (append) { - SECStatus rv = ssl3_AppendHandshake(ss, ecList, ecListSize); + SECStatus rv; + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_supported_groups_xtn, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_ExtAppendHandshakeVariable(ss, enabledGroups, + enabledGroupsLen, 2); if (rv != SECSuccess) return -1; if (!ss->sec.isServer) { - TLSExtensionData *xtnData = &ss->xtnData; xtnData->advertised[xtnData->numAdvertised++] = - ssl_elliptic_curves_xtn; + ssl_supported_groups_xtn; } } - return ecListSize; -} - -PRUint32 -ssl3_GetSupportedECCurveMask(sslSocket *ss) -{ - if (ssl3_SuiteBOnly(ss)) { - return SSL3_SUITE_B_SUPPORTED_CURVES_MASK; - } - return SSL3_ALL_SUPPORTED_CURVES_MASK; + return extension_length; } /* Send our "canned" (precompiled) Supported Point Formats extension, @@ -1161,126 +981,33 @@ ssl3_GetSupportedECCurveMask(sslSocket *ss) */ PRInt32 ssl3_SendSupportedPointFormatsXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) + const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) { - if (!ss || !ssl3_IsECCEnabled(ss)) + static const PRUint8 ecPtFmt[6] = { + 0, 11, /* Extension type */ + 0, 2, /* octets that follow */ + 1, /* octets that follow */ + 0 /* uncompressed type only */ + }; + + /* 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 0; if (append && maxBytes >= (sizeof ecPtFmt)) { - SECStatus rv = ssl3_AppendHandshake(ss, ecPtFmt, (sizeof ecPtFmt)); + SECStatus rv = ssl3_ExtAppendHandshake(ss, ecPtFmt, (sizeof ecPtFmt)); if (rv != SECSuccess) return -1; if (!ss->sec.isServer) { - TLSExtensionData *xtnData = &ss->xtnData; xtnData->advertised[xtnData->numAdvertised++] = ssl_ec_point_formats_xtn; } } - return (sizeof ecPtFmt); -} - -/* 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(sslSocket *ss, PRUint16 ex_type, - SECItem *data) -{ - int i; - - if (data->len < 2 || data->len > 255 || !data->data || - data->len != (unsigned int)data->data[0] + 1) { - return ssl3_DecodeError(ss); - } - for (i = data->len; --i > 0; ) { - if (data->data[i] == 0) { - /* indicate that we should send a reply */ - SECStatus rv; - rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type, - &ssl3_SendSupportedPointFormatsXtn); - return rv; - } - } - - /* evil client doesn't support uncompressed */ - ssl3_DisableECCSuites(ss, ecSuites); - return SECSuccess; -} - - -#define SSL3_GET_SERVER_PUBLICKEY(sock, type) \ - (ss->serverCerts[type].serverKeyPair ? \ - ss->serverCerts[type].serverKeyPair->pubKey : NULL) - -/* Extract the TLS curve name for the public key in our EC server cert. */ -ECName ssl3_GetSvrCertCurveName(sslSocket *ss) -{ - SECKEYPublicKey *srvPublicKey; - ECName ec_curve = ec_noName; - - srvPublicKey = SSL3_GET_SERVER_PUBLICKEY(ss, kt_ecdh); - if (srvPublicKey) { - ec_curve = params2ecName(&srvPublicKey->u.ec.DEREncodedParams); - } - return ec_curve; -} - -/* 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 -ssl3_HandleSupportedCurvesXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) -{ - PRInt32 list_len; - PRUint32 peerCurves = 0; - PRUint32 mutualCurves = 0; - PRUint16 svrCertCurveName; - - if (!data->data || data->len < 4) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - - /* get the length of elliptic_curve_list */ - list_len = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); - if (list_len < 0 || data->len != list_len || (data->len % 2) != 0) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - /* build bit vector of peer's supported curve names */ - while (data->len) { - PRInt32 curve_name = - ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); - if (curve_name < 0) { - return SECFailure; /* fatal alert already sent */ - } - if (curve_name > ec_noName && curve_name < ec_pastLastName) { - peerCurves |= (1U << curve_name); - } - } - /* What curves do we support in common? */ - mutualCurves = ss->ssl3.hs.negotiatedECCurves &= peerCurves; - if (!mutualCurves) { - /* no mutually supported EC Curves, disable ECC */ - ssl3_DisableECCSuites(ss, ecSuites); - return SECSuccess; - } - - /* if our ECC cert doesn't use one of these supported curves, - * disable ECC cipher suites that require an ECC cert. - */ - svrCertCurveName = ssl3_GetSvrCertCurveName(ss); - if (svrCertCurveName != ec_noName && - (mutualCurves & (1U << svrCertCurveName)) != 0) { - return SECSuccess; - } - /* Our EC cert doesn't contain a mutually supported curve. - * Disable all ECC cipher suites that require an EC cert - */ - ssl3_DisableECCSuites(ss, ecdh_ecdsa_suites); - ssl3_DisableECCSuites(ss, ecdhe_ecdsa_suites); - return SECSuccess; + return sizeof(ecPtFmt); } - -#endif /* NSS_DISABLE_ECC */ diff --git a/nss/lib/ssl/ssl3ext.c b/nss/lib/ssl/ssl3ext.c index cf04aba..0da41be 100644 --- a/nss/lib/ssl/ssl3ext.c +++ b/nss/lib/ssl/ssl3ext.c @@ -11,308 +11,123 @@ #include "nssrenam.h" #include "nss.h" #include "ssl.h" -#include "sslproto.h" #include "sslimpl.h" -#include "pk11pub.h" -#ifdef NO_PKCS11_BYPASS -#include "blapit.h" -#else -#include "blapi.h" -#endif -#include "prinit.h" - -static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN]; -static PK11SymKey *session_ticket_enc_key_pkcs11 = NULL; -static PK11SymKey *session_ticket_mac_key_pkcs11 = NULL; - -#ifndef NO_PKCS11_BYPASS -static unsigned char session_ticket_enc_key[AES_256_KEY_LENGTH]; -static unsigned char session_ticket_mac_key[SHA256_LENGTH]; - -static PRBool session_ticket_keys_initialized = PR_FALSE; -#endif -static PRCallOnceType generate_session_keys_once; - -/* forward static function declarations */ -static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss, - SECItem *data, EncryptedSessionTicket *enc_session_ticket); -static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf, - PRUint32 bytes); -static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, - PRInt32 lenSize); -static SECStatus ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, - PK11SymKey **aes_key, PK11SymKey **mac_key); -#ifndef NO_PKCS11_BYPASS -static SECStatus ssl3_GetSessionTicketKeys(const unsigned char **aes_key, - PRUint32 *aes_key_length, const unsigned char **mac_key, - PRUint32 *mac_key_length); -#endif -static PRInt32 ssl3_SendRenegotiationInfoXtn(sslSocket * ss, - PRBool append, PRUint32 maxBytes); -static SECStatus ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); -static SECStatus ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); -static SECStatus ssl3_ClientHandleAppProtoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); -static SECStatus ssl3_ServerHandleNextProtoNegoXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); -static SECStatus ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data); -static PRInt32 ssl3_ClientSendNextProtoNegoXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static PRInt32 ssl3_ClientSendAppProtoXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static PRInt32 ssl3_ServerSendAppProtoXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static PRInt32 ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static PRInt32 ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static SECStatus ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, - SECItem *data); -static SECStatus ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, - SECItem *data); -static PRInt32 ssl3_ServerSendStatusRequestXtn(sslSocket * ss, - PRBool append, PRUint32 maxBytes); -static SECStatus ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); -static SECStatus ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, - PRUint16 ex_type, - SECItem *data); -static PRInt32 ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append, - PRUint32 maxBytes); -static PRInt32 ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static SECStatus ssl3_ServerHandleSigAlgsXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data); - -static PRInt32 ssl3_ClientSendDraftVersionXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static SECStatus ssl3_ServerHandleDraftVersionXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data); -static PRInt32 ssl3_SendExtendedMasterSecretXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); -static SECStatus ssl3_HandleExtendedMasterSecretXtn(sslSocket *ss, - PRUint16 ex_type, - SECItem *data); - - -/* - * Write bytes. Using this function means the SECItem structure - * cannot be freed. The caller is expected to call this function - * on a shallow copy of the structure. - */ -static SECStatus -ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes) -{ - if (bytes > item->len) - return SECFailure; - - PORT_Memcpy(item->data, buf, bytes); - item->data += bytes; - item->len -= bytes; - return SECSuccess; -} - -/* - * Write a number in network byte order. Using this function means the - * SECItem structure cannot be freed. The caller is expected to call - * this function on a shallow copy of the structure. - */ -static SECStatus -ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize) -{ - SECStatus rv; - PRUint8 b[4]; - PRUint8 * p = b; - - switch (lenSize) { - case 4: - *p++ = (PRUint8) (num >> 24); - case 3: - *p++ = (PRUint8) (num >> 16); - case 2: - *p++ = (PRUint8) (num >> 8); - case 1: - *p = (PRUint8) num; - } - rv = ssl3_AppendToItem(item, &b[0], lenSize); - return rv; -} - -static SECStatus ssl3_SessionTicketShutdown(void* appData, void* nssData) -{ - if (session_ticket_enc_key_pkcs11) { - PK11_FreeSymKey(session_ticket_enc_key_pkcs11); - session_ticket_enc_key_pkcs11 = NULL; - } - if (session_ticket_mac_key_pkcs11) { - PK11_FreeSymKey(session_ticket_mac_key_pkcs11); - session_ticket_mac_key_pkcs11 = NULL; - } - PORT_Memset(&generate_session_keys_once, 0, - sizeof(generate_session_keys_once)); - return SECSuccess; -} - - -static PRStatus -ssl3_GenerateSessionTicketKeysPKCS11(void *data) -{ - SECStatus rv; - sslSocket *ss = (sslSocket *)data; - SECKEYPrivateKey *svrPrivKey = ss->serverCerts[kt_rsa].SERVERKEY; - SECKEYPublicKey *svrPubKey = ss->serverCerts[kt_rsa].serverKeyPair->pubKey; - - if (svrPrivKey == NULL || svrPubKey == NULL) { - SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.", - SSL_GETPID(), ss->fd)); - goto loser; - } - - /* Get a copy of the session keys from shared memory. */ - PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, - sizeof(SESS_TICKET_KEY_NAME_PREFIX)); - if (!ssl_GetSessionTicketKeysPKCS11(svrPrivKey, svrPubKey, - ss->pkcs11PinArg, &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], - &session_ticket_enc_key_pkcs11, &session_ticket_mac_key_pkcs11)) - return PR_FAILURE; - - rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL); - if (rv != SECSuccess) - goto loser; - - return PR_SUCCESS; - -loser: - ssl3_SessionTicketShutdown(NULL, NULL); - return PR_FAILURE; -} - -static SECStatus -ssl3_GetSessionTicketKeysPKCS11(sslSocket *ss, PK11SymKey **aes_key, - PK11SymKey **mac_key) -{ - if (PR_CallOnceWithArg(&generate_session_keys_once, - ssl3_GenerateSessionTicketKeysPKCS11, ss) != PR_SUCCESS) - return SECFailure; - - if (session_ticket_enc_key_pkcs11 == NULL || - session_ticket_mac_key_pkcs11 == NULL) - return SECFailure; - - *aes_key = session_ticket_enc_key_pkcs11; - *mac_key = session_ticket_mac_key_pkcs11; - return SECSuccess; -} - -#ifndef NO_PKCS11_BYPASS -static PRStatus -ssl3_GenerateSessionTicketKeys(void) -{ - PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, - sizeof(SESS_TICKET_KEY_NAME_PREFIX)); - - if (!ssl_GetSessionTicketKeys(&key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], - session_ticket_enc_key, session_ticket_mac_key)) - return PR_FAILURE; - - session_ticket_keys_initialized = PR_TRUE; - return PR_SUCCESS; -} - -static SECStatus -ssl3_GetSessionTicketKeys(const unsigned char **aes_key, - PRUint32 *aes_key_length, const unsigned char **mac_key, - PRUint32 *mac_key_length) -{ - if (PR_CallOnce(&generate_session_keys_once, - ssl3_GenerateSessionTicketKeys) != PR_SUCCESS) - return SECFailure; - - if (!session_ticket_keys_initialized) - return SECFailure; - - *aes_key = session_ticket_enc_key; - *aes_key_length = sizeof(session_ticket_enc_key); - *mac_key = session_ticket_mac_key; - *mac_key_length = sizeof(session_ticket_mac_key); - - return SECSuccess; -} -#endif +#include "sslproto.h" +#include "ssl3exthandle.h" +#include "tls13exthandle.h" /* 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 ssl3HelloExtensionHandler clientHelloHandlers[] = { - { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, -#ifndef NSS_DISABLE_ECC - { ssl_elliptic_curves_xtn, &ssl3_HandleSupportedCurvesXtn }, - { ssl_ec_point_formats_xtn, &ssl3_HandleSupportedPointFormatsXtn }, -#endif - { ssl_session_ticket_xtn, &ssl3_ServerHandleSessionTicketXtn }, +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_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn }, + { ssl_next_proto_nego_xtn, &ssl3_ServerHandleNextProtoNegoXtn }, { ssl_app_layer_protocol_xtn, &ssl3_ServerHandleAppProtoXtn }, - { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn }, - { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn }, + { ssl_use_srtp_xtn, &ssl3_ServerHandleUseSRTPXtn }, + { ssl_cert_status_xtn, &ssl3_ServerHandleStatusRequestXtn }, { ssl_signature_algorithms_xtn, &ssl3_ServerHandleSigAlgsXtn }, - { ssl_tls13_draft_version_xtn, &ssl3_ServerHandleDraftVersionXtn }, { ssl_extended_master_secret_xtn, &ssl3_HandleExtendedMasterSecretXtn }, + { ssl_signed_cert_timestamp_xtn, &ssl3_ServerHandleSignedCertTimestampXtn }, + { 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_ServerHandlePskKeyExchangeModesXtn }, + { ssl_tls13_short_header_xtn, &tls13_HandleShortHeaderXtn }, { -1, NULL } }; /* These two tables are used by the client, to handle server hello * extensions. */ -static const ssl3HelloExtensionHandler serverHelloHandlersTLS[] = { - { ssl_server_name_xtn, &ssl3_HandleServerNameXtn }, +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_session_ticket_xtn, &ssl3_ClientHandleSessionTicketXtn }, { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, - { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn }, + { ssl_next_proto_nego_xtn, &ssl3_ClientHandleNextProtoNegoXtn }, { ssl_app_layer_protocol_xtn, &ssl3_ClientHandleAppProtoXtn }, - { ssl_use_srtp_xtn, &ssl3_ClientHandleUseSRTPXtn }, - { ssl_cert_status_xtn, &ssl3_ClientHandleStatusRequestXtn }, + { 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_short_header_xtn, &tls13_HandleShortHeaderXtn }, { -1, NULL } }; -static const ssl3HelloExtensionHandler serverHelloHandlersSSL3[] = { +static const ssl3ExtensionHandler helloRetryRequestHandlers[] = { + { ssl_tls13_key_share_xtn, tls13_ClientHandleKeyShareXtnHrr }, + { ssl_tls13_cookie_xtn, tls13_ClientHandleHrrCookie }, + { -1, NULL } +}; + +static const ssl3ExtensionHandler serverHelloHandlersSSL3[] = { { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn }, { -1, NULL } }; +static const ssl3ExtensionHandler newSessionTicketHandlers[] = { + { ssl_tls13_ticket_early_data_info_xtn, + &tls13_ClientHandleTicketEarlyDataInfoXtn }, + { -1, 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 }, + { -1, 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 -ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = { - { ssl_server_name_xtn, &ssl3_SendServerNameXtn }, - { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn }, -#ifndef NSS_DISABLE_ECC - { ssl_elliptic_curves_xtn, &ssl3_SendSupportedCurvesXtn }, - { ssl_ec_point_formats_xtn, &ssl3_SendSupportedPointFormatsXtn }, -#endif - { ssl_session_ticket_xtn, &ssl3_SendSessionTicketXtn }, - { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn }, - { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn }, - { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn }, - { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn }, - { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn }, - { ssl_tls13_draft_version_xtn, &ssl3_ClientSendDraftVersionXtn }, - { ssl_extended_master_secret_xtn, &ssl3_SendExtendedMasterSecretXtn}, - /* any extra entries will appear as { 0, NULL } */ -}; - -static const -ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = { +static const ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = + { + { ssl_server_name_xtn, &ssl3_SendServerNameXtn }, + { 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_SendSessionTicketXtn }, + { ssl_next_proto_nego_xtn, &ssl3_ClientSendNextProtoNegoXtn }, + { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn }, + { ssl_use_srtp_xtn, &ssl3_ClientSendUseSRTPXtn }, + { ssl_cert_status_xtn, &ssl3_ClientSendStatusRequestXtn }, + { 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_tls13_short_header_xtn, &tls13_SendShortHeaderXtn }, + { ssl_signature_algorithms_xtn, &ssl3_ClientSendSigAlgsXtn }, + { ssl_tls13_cookie_xtn, &tls13_ClientSendHrrCookieXtn }, + { ssl_tls13_psk_key_exchange_modes_xtn, + &tls13_ClientSendPskKeyExchangeModesXtn }, + /* The pre_shared_key extension MUST be last. */ + { ssl_tls13_pre_shared_key_xtn, &tls13_ClientSendPreSharedKeyXtn }, + /* any extra entries will appear as { 0, NULL } */ + }; + +static const ssl3HelloExtensionSender clientHelloSendersSSL3[SSL_MAX_EXTENSIONS] = { { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn } /* any extra entries will appear as { 0, NULL } */ }; @@ -329,1638 +144,193 @@ arrayContainsExtension(const PRUint16 *array, PRUint32 len, PRUint16 ex_type) } PRBool -ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type) { - TLSExtensionData *xtnData = &ss->xtnData; +ssl3_ExtensionNegotiated(const sslSocket *ss, PRUint16 ex_type) +{ + const TLSExtensionData *xtnData = &ss->xtnData; return arrayContainsExtension(xtnData->negotiated, xtnData->numNegotiated, ex_type); } -static PRBool -ssl3_ClientExtensionAdvertised(sslSocket *ss, PRUint16 ex_type) { - TLSExtensionData *xtnData = &ss->xtnData; +PRBool +ssl3_ClientExtensionAdvertised(const sslSocket *ss, PRUint16 ex_type) +{ + const TLSExtensionData *xtnData = &ss->xtnData; return arrayContainsExtension(xtnData->advertised, xtnData->numAdvertised, ex_type); } -/* 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. +/* 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. */ -PRInt32 -ssl3_SendServerNameXtn(sslSocket * ss, PRBool append, - PRUint32 maxBytes) -{ - SECStatus rv; - if (!ss) - return 0; - if (!ss->sec.isServer) { - PRUint32 len; - PRNetAddr netAddr; - - /* must have a hostname */ - if (!ss->url || !ss->url[0]) - return 0; - /* must not be an IPv4 or IPv6 address */ - if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) { - /* is an IP address (v4 or v6) */ - return 0; - } - len = PORT_Strlen(ss->url); - if (append && maxBytes >= len + 9) { - /* extension_type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); - if (rv != SECSuccess) return -1; - /* length of extension_data */ - rv = ssl3_AppendHandshakeNumber(ss, len + 5, 2); - if (rv != SECSuccess) return -1; - /* length of server_name_list */ - rv = ssl3_AppendHandshakeNumber(ss, len + 3, 2); - if (rv != SECSuccess) return -1; - /* Name Type (sni_host_name) */ - rv = ssl3_AppendHandshake(ss, "\0", 1); - if (rv != SECSuccess) return -1; - /* HostName (length and value) */ - rv = ssl3_AppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2); - if (rv != SECSuccess) return -1; - if (!ss->sec.isServer) { - TLSExtensionData *xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = - ssl_server_name_xtn; - } - } - return len + 9; - } - /* Server side */ - if (append && maxBytes >= 4) { - rv = ssl3_AppendHandshakeNumber(ss, ssl_server_name_xtn, 2); - if (rv != SECSuccess) return -1; - /* length of extension_data */ - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) return -1; - } - return 4; -} - -/* handle an incoming SNI extension, by ignoring it. */ SECStatus -ssl3_HandleServerNameXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +ssl3_ParseExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length) { - SECItem *names = NULL; - PRUint32 listCount = 0, namesPos = 0, i; - TLSExtensionData *xtnData = &ss->xtnData; - SECItem ldata; - PRInt32 listLenBytes = 0; - - 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 */ - listLenBytes = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); - if (listLenBytes < 0) { - return SECFailure; - } - if (listLenBytes == 0 || listLenBytes != data->len) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - ldata = *data; - /* Calculate the size of the array.*/ - while (listLenBytes > 0) { - SECItem litem; - SECStatus rv; - PRInt32 type; - /* Skip Name Type (sni_host_name); checks are on the second pass */ - type = ssl3_ConsumeHandshakeNumber(ss, 1, &ldata.data, &ldata.len); - if (type < 0) { /* i.e., SECFailure cast to PRint32 */ - return SECFailure; - } - rv = ssl3_ConsumeHandshakeVariable(ss, &litem, 2, &ldata.data, &ldata.len); - if (rv != SECSuccess) { - return rv; - } - /* Adjust total length for consumed item, item len and type.*/ - listLenBytes -= litem.len + 3; - if (listLenBytes > 0 && !ldata.len) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - listCount += 1; - } - names = PORT_ZNewArray(SECItem, listCount); - if (!names) { - return SECFailure; - } - for (i = 0;i < listCount;i++) { - unsigned int j; - PRInt32 type; - SECStatus rv; - PRBool nametypePresent = PR_FALSE; - /* Name Type (sni_host_name) */ - type = ssl3_ConsumeHandshakeNumber(ss, 1, &data->data, &data->len); - /* Check if we have such type in the list */ - for (j = 0;j < listCount && names[j].data;j++) { - /* TODO bug 998524: .type is not assigned a value */ - if (names[j].type == type) { - nametypePresent = PR_TRUE; - break; - } - } - /* HostName (length and value) */ - rv = ssl3_ConsumeHandshakeVariable(ss, &names[namesPos], 2, - &data->data, &data->len); - if (rv != SECSuccess) { - PORT_Assert(0); - PORT_Free(names); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return rv; - } - if (nametypePresent == PR_FALSE) { - namesPos += 1; - } - } - /* Free old and set the new data. */ - if (xtnData->sniNameArr) { - PORT_Free(ss->xtnData.sniNameArr); - } - xtnData->sniNameArr = names; - xtnData->sniNameArrSize = namesPos; - xtnData->negotiated[xtnData->numNegotiated++] = ssl_server_name_xtn; - - return SECSuccess; -} - -/* 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. - */ -PRInt32 -ssl3_SendSessionTicketXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) -{ - PRInt32 extension_length; - NewSessionTicket *session_ticket = NULL; - sslSessionID *sid = ss->sec.ci.sid; - - /* Ignore the SessionTicket extension if processing is disabled. */ - if (!ss->opt.enableSessionTickets) - return 0; - - /* Empty extension length = extension_type (2-bytes) + - * length(extension_data) (2-bytes) - */ - extension_length = 4; - - /* If we are a client then send a session ticket if one is availble. - * Servers that support the extension and are willing to negotiate the - * the extension always respond with an empty extension. - */ - if (!ss->sec.isServer) { - /* 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) { - if (ss->xtnData.ticketTimestampVerified) { - extension_length += session_ticket->ticket.len; - } else if (!append && - (session_ticket->ticket_lifetime_hint == 0 || - (session_ticket->ticket_lifetime_hint + - session_ticket->received_timestamp > ssl_Time()))) { - extension_length += session_ticket->ticket.len; - ss->xtnData.ticketTimestampVerified = PR_TRUE; - } - } - } + /* Clean out the extensions list. */ + ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions); - if (maxBytes < (PRUint32)extension_length) { - PORT_Assert(0); - return 0; - } - if (append) { + while (*length) { SECStatus rv; - /* extension_type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2); - if (rv != SECSuccess) - goto loser; - if (session_ticket && session_ticket->ticket.data && - ss->xtnData.ticketTimestampVerified) { - rv = ssl3_AppendHandshakeVariable(ss, session_ticket->ticket.data, - session_ticket->ticket.len, 2); - ss->xtnData.ticketTimestampVerified = PR_FALSE; - ss->xtnData.sentSessionTicketInClientHello = PR_TRUE; - } else { - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - } - if (rv != SECSuccess) - goto loser; - - if (!ss->sec.isServer) { - TLSExtensionData *xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = - ssl_session_ticket_xtn; - } - } - return extension_length; - - loser: - ss->xtnData.ticketTimestampVerified = PR_FALSE; - return -1; -} - -/* handle an incoming Next Protocol Negotiation extension. */ -static SECStatus -ssl3_ServerHandleNextProtoNegoXtn(sslSocket * ss, PRUint16 ex_type, - SECItem *data) -{ - if (ss->firstHsDone || data->len != 0) { - /* Clients MUST send an empty NPN extension, if any. */ - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); - return SECFailure; - } - - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - - /* TODO: server side NPN support would require calling - * ssl3_RegisterServerHelloExtensionSender here in order to echo the - * extension back to the client. */ - - return SECSuccess; -} - -/* ssl3_ValidateNextProtoNego 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_ValidateNextProtoNego(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 (server side) and NPN (client side) */ -static SECStatus -ssl3_SelectAppProtocol(sslSocket *ss, PRUint16 ex_type, SECItem *data) -{ - SECStatus rv; - unsigned char resultBuffer[255]; - SECItem result = { siBuffer, resultBuffer, 0 }; - - rv = ssl3_ValidateNextProtoNego(data->data, data->len); - if (rv != SECSuccess) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); - return rv; - } - - PORT_Assert(ss->nextProtoCallback); - /* For ALPN, the cipher suite isn't 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_all & ~ssl_preinfo_cipher_suite)); - 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() */ - (void)SSL3_SendAlert(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); - /* TODO: crash */ - return SECFailure; - } - - SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); + PRInt32 extension_type; + SECItem extension_data = { siBuffer, NULL, 0 }; + TLSExtension *extension; + PRCList *cursor; - if (ex_type == ssl_app_layer_protocol_xtn && - ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NEGOTIATED) { - /* The callback might say OK, but then it picks a default value - one - * that was not listed. That's OK for NPN, but not ALPN. */ - (void)SSL3_SendAlert(ss, alert_fatal, no_application_protocol); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL); - return SECFailure; - } - - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &result); -} - -/* handle an incoming ALPN extension at the server */ -static SECStatus -ssl3_ServerHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) -{ - int 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. */ - (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); - return SECFailure; - } - - /* Unlike NPN, ALPN has extra redundant length information so that - * the extension is the same in both ClientHello and ServerHello. */ - count = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); - if (count != data->len) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - - if (!ss->nextProtoCallback) { - /* we're not configured for it */ - return SECSuccess; - } - - rv = ssl3_SelectAppProtocol(ss, ex_type, data); - if (rv != SECSuccess) { - return rv; - } - - /* prepare to send back a response, if we negotiated */ - if (ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED) { - rv = ssl3_RegisterServerHelloExtensionSender( - ss, ex_type, ssl3_ServerSendAppProtoXtn); - if (rv != SECSuccess) { - (void)SSL3_SendAlert(ss, alert_fatal, internal_error); - PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); - return rv; + /* Get the extension's type field */ + extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); + if (extension_type < 0) { /* failure to decode extension_type */ + return SECFailure; /* alert already sent */ } - } - return SECSuccess; -} - -static SECStatus -ssl3_ClientHandleNextProtoNegoXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data) -{ - PORT_Assert(!ss->firstHsDone); - if (ssl3_ExtensionNegotiated(ss, ssl_app_layer_protocol_xtn)) { - /* If the server negotiated ALPN then it has already told us what - * protocol to use, so it doesn't make sense for us to try to negotiate - * a different one by sending the NPN handshake message. However, if - * we've negotiated NPN then we're required to send the NPN handshake - * message. Thus, these two extensions cannot both be negotiated on the - * same connection. */ - (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); - PORT_SetError(SSL_ERROR_BAD_SERVER); - return SECFailure; - } - - /* We should only get this call if we sent the extension, so - * ss->nextProtoCallback needs to be non-NULL. However, it is possible - * that an application erroneously cleared the callback between the time - * we sent the ClientHello and now. */ - if (!ss->nextProtoCallback) { - PORT_Assert(0); - (void)SSL3_SendAlert(ss, alert_fatal, internal_error); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK); - return SECFailure; - } - - return ssl3_SelectAppProtocol(ss, ex_type, data); -} - -static SECStatus -ssl3_ClientHandleAppProtoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) -{ - SECStatus rv; - PRInt32 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) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); - return SECFailure; - } - - list_len = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); - /* The list has to be the entire extension. */ - if (list_len != data->len) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); - return SECFailure; - } - - rv = ssl3_ConsumeHandshakeVariable(ss, &protocol_name, 1, - &data->data, &data->len); - /* The list must have exactly one value. */ - if (rv != SECSuccess || data->len != 0) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); - return SECFailure; - } - - SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE); - ss->ssl3.nextProtoState = SSL_NEXT_PROTO_SELECTED; - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - return SECITEM_CopyItem(NULL, &ss->ssl3.nextProto, &protocol_name); -} - -static PRInt32 -ssl3_ClientSendNextProtoNegoXtn(sslSocket * ss, PRBool append, - PRUint32 maxBytes) -{ - PRInt32 extension_length; - - /* Renegotiations do not send this extension. */ - if (!ss->opt.enableNPN || !ss->nextProtoCallback || ss->firstHsDone) { - return 0; - } - - extension_length = 4; - - if (maxBytes < (PRUint32)extension_length) { - return 0; - } - if (append) { - SECStatus rv; - rv = ssl3_AppendHandshakeNumber(ss, ssl_next_proto_nego_xtn, 2); - if (rv != SECSuccess) - goto loser; - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - goto loser; - ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_next_proto_nego_xtn; - } - - return extension_length; - -loser: - return -1; -} - -static PRInt32 -ssl3_ClientSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) -{ - PRInt32 extension_length; - unsigned char *alpn_protos = NULL; - - /* Renegotiations do not send this extension. */ - if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.data || ss->firstHsDone) { - return 0; - } - - extension_length = 2 /* extension type */ + 2 /* extension length */ + - 2 /* protocol name list length */ + - ss->opt.nextProtoNego.len; - - if (maxBytes < (PRUint32)extension_length) { - return 0; - } - if (append) { - /* NPN requires that the client's fallback protocol is first in the - * list. However, ALPN sends protocols in preference order. So we - * allocate a buffer and move the first protocol to the end of the - * list. */ - SECStatus rv; - const unsigned int len = ss->opt.nextProtoNego.len; - - alpn_protos = PORT_Alloc(len); - if (alpn_protos == NULL) { - return SECFailure; - } - if (len > 0) { - /* Each protocol string is prefixed with a single byte length. */ - unsigned int i = ss->opt.nextProtoNego.data[0] + 1; - if (i <= len) { - memcpy(alpn_protos, &ss->opt.nextProtoNego.data[i], len - i); - memcpy(alpn_protos + len - i, ss->opt.nextProtoNego.data, i); - } else { - /* This seems to be invalid data so we'll send as-is. */ - memcpy(alpn_protos, ss->opt.nextProtoNego.data, len); + SSL_TRC(10, ("%d: SSL3[%d]: parsing extension %d", + SSL_GETPID(), ss->fd, extension_type)); + /* 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; } } - rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2); - if (rv != SECSuccess) { - goto loser; - } - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) { - goto loser; - } - rv = ssl3_AppendHandshakeVariable(ss, alpn_protos, len, 2); - PORT_Free(alpn_protos); - alpn_protos = NULL; - if (rv != SECSuccess) { - goto loser; - } - ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_app_layer_protocol_xtn; - } - - return extension_length; - -loser: - if (alpn_protos) { - PORT_Free(alpn_protos); - } - return -1; -} - -static PRInt32 -ssl3_ServerSendAppProtoXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) -{ - PRInt32 extension_length; - - /* we're in over our heads if any of these fail */ - PORT_Assert(ss->opt.enableALPN); - PORT_Assert(ss->ssl3.nextProto.data); - PORT_Assert(ss->ssl3.nextProto.len > 0); - PORT_Assert(ss->ssl3.nextProtoState == SSL_NEXT_PROTO_NEGOTIATED); - PORT_Assert(!ss->firstHsDone); - - extension_length = 2 /* extension type */ + 2 /* extension length */ + - 2 /* protocol name list */ + 1 /* name length */ + - ss->ssl3.nextProto.len; - - if (maxBytes < (PRUint32)extension_length) { - return 0; - } - if (append) { - SECStatus rv; - rv = ssl3_AppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2); - if (rv != SECSuccess) { - return -1; - } - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) { - return -1; - } - rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.nextProto.len + 1, 2); - if (rv != SECSuccess) { - return -1; - } - rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data, - ss->ssl3.nextProto.len, 1); + /* 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 -1; - } - } - - return extension_length; -} - -static SECStatus -ssl3_ClientHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data) -{ - /* The echoed extension must be empty. */ - if (data->len != 0) { - return SECSuccess; /* Ignore the extension. */ - } - - /* Keep track of negotiated extensions. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - - return SECSuccess; -} - -static PRInt32 -ssl3_ServerSendStatusRequestXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) -{ - PRInt32 extension_length; - SECStatus rv; - int i; - PRBool haveStatus = PR_FALSE; - - for (i = kt_null; i < kt_kea_size; i++) { - /* TODO: This is a temporary workaround. - * The correct code needs to see if we have an OCSP response for - * the server certificate being used, rather than if we have any - * OCSP response. See also ssl3_SendCertificateStatus. - */ - if (ss->certStatusArray[i] && ss->certStatusArray[i]->len) { - haveStatus = PR_TRUE; - break; - } - } - if (!haveStatus) - return 0; - - extension_length = 2 + 2; - if (maxBytes < (PRUint32)extension_length) { - return 0; - } - if (append) { - /* extension_type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); - if (rv != SECSuccess) - return -1; - /* length of extension_data */ - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - return -1; - } - - return extension_length; -} - -/* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the - * client side. See RFC 4366 section 3.6. */ -static PRInt32 -ssl3_ClientSendStatusRequestXtn(sslSocket * ss, PRBool append, - PRUint32 maxBytes) -{ - PRInt32 extension_length; - - if (!ss->opt.enableOCSPStapling) - return 0; - - /* extension_type (2-bytes) + - * length(extension_data) (2-bytes) + - * status_type (1) + - * responder_id_list length (2) + - * request_extensions length (2) - */ - extension_length = 9; - - if (maxBytes < (PRUint32)extension_length) { - PORT_Assert(0); - return 0; - } - if (append) { - SECStatus rv; - TLSExtensionData *xtnData; - - /* extension_type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); - if (rv != SECSuccess) - return -1; - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) - return -1; - rv = ssl3_AppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1); - if (rv != SECSuccess) - return -1; - /* A zero length responder_id_list means that the responders are - * implicitly known to the server. */ - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - return -1; - /* 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 = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - return -1; - - xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn; - } - return extension_length; -} - -/* - * NewSessionTicket - * Called from ssl3_HandleFinished - */ -SECStatus -ssl3_SendNewSessionTicket(sslSocket *ss) -{ - PRUint32 i; - SECStatus rv; - NewSessionTicket ticket; - SECItem plaintext; - SECItem plaintext_item = {0, NULL, 0}; - SECItem ciphertext = {0, NULL, 0}; - PRUint32 ciphertext_length; - PRBool ms_is_wrapped; - unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH]; - SECItem ms_item = {0, NULL, 0}; - SSL3KEAType effectiveExchKeyType = ssl_kea_null; - PRUint32 padding_length; - PRUint32 message_length; - PRUint32 cert_length; - PRUint8 length_buf[4]; - PRUint32 now; - PK11SymKey *aes_key_pkcs11; - PK11SymKey *mac_key_pkcs11; -#ifndef NO_PKCS11_BYPASS - const unsigned char *aes_key; - const unsigned char *mac_key; - PRUint32 aes_key_length; - PRUint32 mac_key_length; - PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; - AESContext *aes_ctx; - const SECHashObject *hashObj = NULL; - PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; - HMACContext *hmac_ctx; -#endif - CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; - PK11Context *aes_ctx_pkcs11; - CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; - PK11Context *hmac_ctx_pkcs11 = NULL; - unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; - unsigned int computed_mac_length; - unsigned char iv[AES_BLOCK_SIZE]; - SECItem ivItem; - SECItem *srvName = NULL; - PRUint32 srvNameLen = 0; - CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value, - * must be >= 0 */ - - 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)); - - ticket.ticket_lifetime_hint = TLS_EX_SESS_TICKET_LIFETIME_HINT; - cert_length = (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) ? - 3 + ss->sec.ci.sid->peerCert->derCert.len : 0; - - /* Get IV and encryption keys */ - ivItem.data = iv; - ivItem.len = sizeof(iv); - rv = PK11_GenerateRandom(iv, sizeof(iv)); - if (rv != SECSuccess) goto loser; - -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length, - &mac_key, &mac_key_length); - } else -#endif - { - rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11, - &mac_key_pkcs11); - } - if (rv != SECSuccess) goto loser; - - if (ss->ssl3.pwSpec->msItem.len && ss->ssl3.pwSpec->msItem.data) { - /* The master secret is available unwrapped. */ - ms_item.data = ss->ssl3.pwSpec->msItem.data; - ms_item.len = ss->ssl3.pwSpec->msItem.len; - ms_is_wrapped = PR_FALSE; - } else { - /* Extract the master secret wrapped. */ - sslSessionID sid; - PORT_Memset(&sid, 0, sizeof(sslSessionID)); - - if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa || - ss->ssl3.hs.kea_def->kea == kea_dhe_rsa) { - effectiveExchKeyType = kt_rsa; - } else { - effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType; + return rv; /* alert already sent */ } - rv = ssl3_CacheWrappedMasterSecret(ss, &sid, ss->ssl3.pwSpec, - effectiveExchKeyType); - 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; + extension = PORT_ZNew(TLSExtension); + if (!extension) { + return SECFailure; } - ms_is_wrapped = PR_TRUE; - } - /* Prep to send negotiated name */ - srvName = &ss->ssl3.pwSpec->srvVirtName; - if (srvName->data && srvName->len) { - srvNameLen = 2 + srvName->len; /* len bytes + name len */ - } - - ciphertext_length = - sizeof(PRUint16) /* ticket_version */ - + sizeof(SSL3ProtocolVersion) /* ssl_version */ - + sizeof(ssl3CipherSuite) /* ciphersuite */ - + 1 /* compression */ - + 10 /* cipher spec parameters */ - + 1 /* SessionTicket.ms_is_wrapped */ - + 1 /* effectiveExchKeyType */ - + 4 /* msWrapMech */ - + 2 /* master_secret.length */ - + ms_item.len /* master_secret */ - + 1 /* client_auth_type */ - + cert_length /* cert */ - + 1 /* server name type */ - + srvNameLen /* name len + length field */ - + 1 /* extendedMasterSecretUsed */ - + sizeof(ticket.ticket_lifetime_hint); - padding_length = AES_BLOCK_SIZE - - (ciphertext_length % AES_BLOCK_SIZE); - ciphertext_length += padding_length; - - message_length = - sizeof(ticket.ticket_lifetime_hint) /* ticket_lifetime_hint */ - + 2 /* length field for NewSessionTicket.ticket */ - + SESS_TICKET_KEY_NAME_LEN /* key_name */ - + AES_BLOCK_SIZE /* iv */ - + 2 /* length field for NewSessionTicket.ticket.encrypted_state */ - + ciphertext_length /* encrypted_state */ - + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */ - - if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL) - goto loser; - - plaintext = plaintext_item; - - /* ticket_version */ - rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION, - sizeof(PRUint16)); - if (rv != SECSuccess) goto loser; - - /* ssl_version */ - rv = ssl3_AppendNumberToItem(&plaintext, ss->version, - sizeof(SSL3ProtocolVersion)); - if (rv != SECSuccess) goto loser; - - /* ciphersuite */ - rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite, - sizeof(ssl3CipherSuite)); - if (rv != SECSuccess) goto loser; - - /* compression */ - rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1); - if (rv != SECSuccess) goto loser; - - /* cipher spec parameters */ - rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authAlgorithm, 1); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4); - if (rv != SECSuccess) goto loser; - - /* master_secret */ - rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, effectiveExchKeyType, 1); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len); - if (rv != SECSuccess) goto loser; - - /* client_identity */ - if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { - rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendNumberToItem(&plaintext, - ss->sec.ci.sid->peerCert->derCert.len, 3); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendToItem(&plaintext, - ss->sec.ci.sid->peerCert->derCert.data, - ss->sec.ci.sid->peerCert->derCert.len); - if (rv != SECSuccess) goto loser; - } else { - rv = ssl3_AppendNumberToItem(&plaintext, 0, 1); - if (rv != SECSuccess) goto loser; - } - - /* timestamp */ - now = ssl_Time(); - rv = ssl3_AppendNumberToItem(&plaintext, now, - sizeof(ticket.ticket_lifetime_hint)); - if (rv != SECSuccess) goto loser; - - if (srvNameLen) { - /* Name Type (sni_host_name) */ - rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1); - if (rv != SECSuccess) goto loser; - /* HostName (length and value) */ - rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2); - if (rv != SECSuccess) goto loser; - rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len); - if (rv != SECSuccess) goto loser; - } else { - /* No Name */ - rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME, - 1); - if (rv != SECSuccess) goto loser; - } - - /* extendedMasterSecretUsed */ - rv = ssl3_AppendNumberToItem( - &plaintext, ss->sec.ci.sid->u.ssl3.keys.extendedMasterSecretUsed, 1); - if (rv != SECSuccess) goto loser; - PORT_Assert(plaintext.len == padding_length); - for (i = 0; i < padding_length; i++) - plaintext.data[i] = (unsigned char)padding_length; - - if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) { - rv = SECFailure; - goto loser; - } - - /* Generate encrypted portion of ticket. */ -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - aes_ctx = (AESContext *)aes_ctx_buf; - rv = AES_InitContext(aes_ctx, aes_key, aes_key_length, iv, - NSS_AES_CBC, 1, AES_BLOCK_SIZE); - if (rv != SECSuccess) goto loser; - - rv = AES_Encrypt(aes_ctx, ciphertext.data, &ciphertext.len, - ciphertext.len, plaintext_item.data, - plaintext_item.len); - if (rv != SECSuccess) goto loser; - } else -#endif - { - aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech, - CKA_ENCRYPT, aes_key_pkcs11, &ivItem); - if (!aes_ctx_pkcs11) - goto loser; - - rv = PK11_CipherOp(aes_ctx_pkcs11, ciphertext.data, - (int *)&ciphertext.len, ciphertext.len, - plaintext_item.data, plaintext_item.len); - PK11_Finalize(aes_ctx_pkcs11); - PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE); - if (rv != SECSuccess) goto loser; - } - - /* Convert ciphertext length to network order. */ - length_buf[0] = (ciphertext.len >> 8) & 0xff; - length_buf[1] = (ciphertext.len ) & 0xff; - - /* Compute MAC. */ -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - hmac_ctx = (HMACContext *)hmac_ctx_buf; - hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); - if (HMAC_Init(hmac_ctx, hashObj, mac_key, - mac_key_length, PR_FALSE) != SECSuccess) - goto loser; - - HMAC_Begin(hmac_ctx); - HMAC_Update(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN); - HMAC_Update(hmac_ctx, iv, sizeof(iv)); - HMAC_Update(hmac_ctx, (unsigned char *)length_buf, 2); - HMAC_Update(hmac_ctx, ciphertext.data, ciphertext.len); - HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length, - sizeof(computed_mac)); - } else -#endif - { - SECItem macParam; - macParam.data = NULL; - macParam.len = 0; - hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech, - CKA_SIGN, mac_key_pkcs11, &macParam); - if (!hmac_ctx_pkcs11) - goto loser; - - rv = PK11_DigestBegin(hmac_ctx_pkcs11); - if (rv != SECSuccess) goto loser; - rv = PK11_DigestOp(hmac_ctx_pkcs11, key_name, - SESS_TICKET_KEY_NAME_LEN); - if (rv != SECSuccess) goto loser; - rv = PK11_DigestOp(hmac_ctx_pkcs11, iv, sizeof(iv)); - if (rv != SECSuccess) goto loser; - rv = PK11_DigestOp(hmac_ctx_pkcs11, (unsigned char *)length_buf, 2); - if (rv != SECSuccess) goto loser; - rv = PK11_DigestOp(hmac_ctx_pkcs11, ciphertext.data, ciphertext.len); - if (rv != SECSuccess) goto loser; - rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac, - &computed_mac_length, sizeof(computed_mac)); - if (rv != SECSuccess) goto loser; - } - - /* Serialize the handshake message. */ - rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, message_length); - if (rv != SECSuccess) goto loser; - - rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_lifetime_hint, - sizeof(ticket.ticket_lifetime_hint)); - if (rv != SECSuccess) goto loser; - - rv = ssl3_AppendHandshakeNumber(ss, - message_length - sizeof(ticket.ticket_lifetime_hint) - 2, 2); - if (rv != SECSuccess) goto loser; - - rv = ssl3_AppendHandshake(ss, key_name, SESS_TICKET_KEY_NAME_LEN); - if (rv != SECSuccess) goto loser; - - rv = ssl3_AppendHandshake(ss, iv, sizeof(iv)); - if (rv != SECSuccess) goto loser; - - rv = ssl3_AppendHandshakeVariable(ss, ciphertext.data, ciphertext.len, 2); - if (rv != SECSuccess) goto loser; - - rv = ssl3_AppendHandshake(ss, computed_mac, computed_mac_length); - if (rv != SECSuccess) goto loser; - -loser: - if (hmac_ctx_pkcs11) - PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); - if (plaintext_item.data) - SECITEM_FreeItem(&plaintext_item, PR_FALSE); - if (ciphertext.data) - SECITEM_FreeItem(&ciphertext, PR_FALSE); - - return rv; -} - -/* When a client receives a SessionTicket extension a NewSessionTicket - * message is expected during the handshake. - */ -SECStatus -ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data) -{ - if (data->len != 0) { - return SECSuccess; /* Ignore the extension. */ + extension->type = (PRUint16)extension_type; + extension->data = extension_data; + PR_APPEND_LINK(&extension->link, &ss->ssl3.hs.remoteExtensions); } - /* Keep track of negotiated extensions. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; return SECSuccess; } -SECStatus -ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data) +TLSExtension * +ssl3_FindExtension(sslSocket *ss, SSLExtensionType extension_type) { - SECStatus rv; - SECItem *decrypted_state = NULL; - SessionTicket *parsed_session_ticket = NULL; - sslSessionID *sid = NULL; - SSL3Statistics *ssl3stats; - - /* Ignore the SessionTicket extension if processing is disabled. */ - if (!ss->opt.enableSessionTickets) { - return SECSuccess; - } - - /* Keep track of negotiated extensions. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; + PRCList *cursor; - /* 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) { - ss->xtnData.emptySessionTicket = PR_TRUE; - } else { - PRUint32 i; - SECItem extension_data; - EncryptedSessionTicket enc_session_ticket; - unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; - unsigned int computed_mac_length; -#ifndef NO_PKCS11_BYPASS - const SECHashObject *hashObj; - const unsigned char *aes_key; - const unsigned char *mac_key; - PRUint32 aes_key_length; - PRUint32 mac_key_length; - PRUint64 hmac_ctx_buf[MAX_MAC_CONTEXT_LLONGS]; - HMACContext *hmac_ctx; - PRUint64 aes_ctx_buf[MAX_CIPHER_CONTEXT_LLONGS]; - AESContext *aes_ctx; -#endif - PK11SymKey *aes_key_pkcs11; - PK11SymKey *mac_key_pkcs11; - PK11Context *hmac_ctx_pkcs11; - CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; - PK11Context *aes_ctx_pkcs11; - CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; - unsigned char * padding; - PRUint32 padding_length; - unsigned char *buffer; - unsigned int buffer_len; - PRInt32 temp; - SECItem cert_item; - PRInt8 nameType = TLS_STE_NO_SERVER_NAME; - - /* Turn off stateless session resumption if the client sends a - * SessionTicket extension, even if the extension turns out to be - * malformed (ss->sec.ci.sid is non-NULL when doing session - * renegotiation.) - */ - if (ss->sec.ci.sid != NULL) { - if (ss->sec.uncache) - ss->sec.uncache(ss->sec.ci.sid); - ssl_FreeSID(ss->sec.ci.sid); - ss->sec.ci.sid = NULL; - } - - extension_data.data = data->data; /* Keep a copy for future use. */ - extension_data.len = data->len; - - if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) - != SECSuccess) { - return SECSuccess; /* Pretend it isn't there */ - } - - /* Get session ticket keys. */ -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - rv = ssl3_GetSessionTicketKeys(&aes_key, &aes_key_length, - &mac_key, &mac_key_length); - } else -#endif - { - rv = ssl3_GetSessionTicketKeysPKCS11(ss, &aes_key_pkcs11, - &mac_key_pkcs11); - } - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.", - SSL_GETPID(), ss->fd)); - goto loser; - } + for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions); + cursor != &ss->ssl3.hs.remoteExtensions; + cursor = PR_NEXT_LINK(cursor)) { + TLSExtension *extension = (TLSExtension *)cursor; - /* If the ticket sent by the client was generated under a key different - * from the one we have, bypass ticket processing. - */ - if (PORT_Memcmp(enc_session_ticket.key_name, key_name, - SESS_TICKET_KEY_NAME_LEN) != 0) { - SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.", - SSL_GETPID(), ss->fd)); - goto no_ticket; + if (extension->type == extension_type) { + return extension; } - - /* Verify the MAC on the ticket. MAC verification may also - * fail if the MAC key has been recently refreshed. - */ -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - hmac_ctx = (HMACContext *)hmac_ctx_buf; - hashObj = HASH_GetRawHashObject(HASH_AlgSHA256); - if (HMAC_Init(hmac_ctx, hashObj, mac_key, - sizeof(session_ticket_mac_key), PR_FALSE) != SECSuccess) - goto no_ticket; - HMAC_Begin(hmac_ctx); - HMAC_Update(hmac_ctx, extension_data.data, - extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); - if (HMAC_Finish(hmac_ctx, computed_mac, &computed_mac_length, - sizeof(computed_mac)) != SECSuccess) - goto no_ticket; - } else -#endif - { - SECItem macParam; - macParam.data = NULL; - macParam.len = 0; - hmac_ctx_pkcs11 = PK11_CreateContextBySymKey(macMech, - CKA_SIGN, mac_key_pkcs11, &macParam); - if (!hmac_ctx_pkcs11) { - SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.", - SSL_GETPID(), ss->fd, PORT_GetError())); - goto no_ticket; - } else { - SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.", - SSL_GETPID(), ss->fd)); - } - rv = PK11_DigestBegin(hmac_ctx_pkcs11); - rv = PK11_DigestOp(hmac_ctx_pkcs11, extension_data.data, - extension_data.len - TLS_EX_SESS_TICKET_MAC_LENGTH); - if (rv != SECSuccess) { - PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); - goto no_ticket; - } - rv = PK11_DigestFinal(hmac_ctx_pkcs11, computed_mac, - &computed_mac_length, sizeof(computed_mac)); - PK11_DestroyContext(hmac_ctx_pkcs11, PR_TRUE); - if (rv != SECSuccess) - goto no_ticket; - } - if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac, - computed_mac_length) != 0) { - SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.", - SSL_GETPID(), ss->fd)); - goto no_ticket; - } - - /* We ignore key_name for now. - * This is ok as MAC verification succeeded. - */ - - /* Decrypt the ticket. */ - - /* Plaintext is shorter than the ciphertext due to padding. */ - decrypted_state = SECITEM_AllocItem(NULL, NULL, - enc_session_ticket.encrypted_state.len); - -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11) { - aes_ctx = (AESContext *)aes_ctx_buf; - rv = AES_InitContext(aes_ctx, aes_key, - sizeof(session_ticket_enc_key), enc_session_ticket.iv, - NSS_AES_CBC, 0,AES_BLOCK_SIZE); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", - SSL_GETPID(), ss->fd)); - goto no_ticket; - } - - rv = AES_Decrypt(aes_ctx, decrypted_state->data, - &decrypted_state->len, decrypted_state->len, - enc_session_ticket.encrypted_state.data, - enc_session_ticket.encrypted_state.len); - if (rv != SECSuccess) - goto no_ticket; - } else -#endif - { - SECItem ivItem; - ivItem.data = enc_session_ticket.iv; - ivItem.len = AES_BLOCK_SIZE; - aes_ctx_pkcs11 = PK11_CreateContextBySymKey(cipherMech, - CKA_DECRYPT, aes_key_pkcs11, &ivItem); - if (!aes_ctx_pkcs11) { - SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", - SSL_GETPID(), ss->fd)); - goto no_ticket; - } - - rv = PK11_CipherOp(aes_ctx_pkcs11, decrypted_state->data, - (int *)&decrypted_state->len, decrypted_state->len, - enc_session_ticket.encrypted_state.data, - enc_session_ticket.encrypted_state.len); - PK11_Finalize(aes_ctx_pkcs11); - PK11_DestroyContext(aes_ctx_pkcs11, PR_TRUE); - if (rv != SECSuccess) - goto no_ticket; - } - - /* Check padding. */ - padding_length = - (PRUint32)decrypted_state->data[decrypted_state->len - 1]; - if (padding_length == 0 || padding_length > AES_BLOCK_SIZE) - goto no_ticket; - - padding = &decrypted_state->data[decrypted_state->len - padding_length]; - for (i = 0; i < padding_length; i++, padding++) { - if (padding_length != (PRUint32)*padding) - goto no_ticket; - } - - /* Deserialize session state. */ - buffer = decrypted_state->data; - buffer_len = decrypted_state->len; - - parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket)); - if (parsed_session_ticket == NULL) { - rv = SECFailure; - goto loser; - } - - /* Read ticket_version and reject if the version is wrong */ - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp != TLS_EX_SESS_TICKET_VERSION) goto no_ticket; - - parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp; - - /* Read SSLVersion. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp; - - /* Read cipher_suite. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp; - - /* Read compression_method. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->compression_method = (SSLCompressionMethod)temp; - - /* Read cipher spec parameters. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->authAlgorithm = (SSLSignType)temp; - temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->authKeyBits = (PRUint32)temp; - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->keaType = (SSLKEAType)temp; - temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->keaKeyBits = (PRUint32)temp; - - /* Read wrapped master_secret. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->ms_is_wrapped = (PRBool)temp; - - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->exchKeyType = (SSL3KEAType)temp; - - temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp; - - temp = ssl3_ConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); - if (temp < 0) goto no_ticket; - parsed_session_ticket->ms_length = (PRUint16)temp; - if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */ - parsed_session_ticket->ms_length > - sizeof(parsed_session_ticket->master_secret)) - goto no_ticket; - - /* Allow for the wrapped master secret to be longer. */ - if (buffer_len < parsed_session_ticket->ms_length) - goto no_ticket; - PORT_Memcpy(parsed_session_ticket->master_secret, buffer, - parsed_session_ticket->ms_length); - buffer += parsed_session_ticket->ms_length; - buffer_len -= parsed_session_ticket->ms_length; - - /* Read client_identity */ - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) - goto no_ticket; - parsed_session_ticket->client_identity.client_auth_type = - (ClientAuthenticationType)temp; - switch(parsed_session_ticket->client_identity.client_auth_type) { - case CLIENT_AUTH_ANONYMOUS: - break; - case CLIENT_AUTH_CERTIFICATE: - rv = ssl3_ConsumeHandshakeVariable(ss, &cert_item, 3, - &buffer, &buffer_len); - if (rv != SECSuccess) goto no_ticket; - rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert, - &cert_item); - if (rv != SECSuccess) goto no_ticket; - break; - default: - goto no_ticket; - } - /* Read timestamp. */ - temp = ssl3_ConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); - if (temp < 0) - goto no_ticket; - parsed_session_ticket->timestamp = (PRUint32)temp; - - /* Read server name */ - nameType = - ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (nameType != TLS_STE_NO_SERVER_NAME) { - SECItem name_item; - rv = ssl3_ConsumeHandshakeVariable(ss, &name_item, 2, &buffer, - &buffer_len); - if (rv != SECSuccess) goto no_ticket; - rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName, - &name_item); - if (rv != SECSuccess) goto no_ticket; - parsed_session_ticket->srvName.type = nameType; - } - - /* Read extendedMasterSecretUsed */ - temp = ssl3_ConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); - if (temp < 0) - goto no_ticket; - PORT_Assert(temp == PR_TRUE || temp == PR_FALSE); - parsed_session_ticket->extendedMasterSecretUsed = (PRBool)temp; - - /* Done parsing. Check that all bytes have been consumed. */ - if (buffer_len != padding_length) - goto no_ticket; - - /* Use the ticket if it has not expired, otherwise free the allocated - * memory since the ticket is of no use. - */ - if (parsed_session_ticket->timestamp != 0 && - parsed_session_ticket->timestamp + - TLS_EX_SESS_TICKET_LIFETIME_HINT > ssl_Time()) { - - sid = ssl3_NewSessionID(ss, PR_TRUE); - if (sid == NULL) { - rv = SECFailure; - goto loser; - } - - /* Copy over parameters. */ - sid->version = parsed_session_ticket->ssl_version; - sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite; - sid->u.ssl3.compression = parsed_session_ticket->compression_method; - sid->authAlgorithm = parsed_session_ticket->authAlgorithm; - sid->authKeyBits = parsed_session_ticket->authKeyBits; - sid->keaType = parsed_session_ticket->keaType; - sid->keaKeyBits = parsed_session_ticket->keaKeyBits; - - /* Copy master secret. */ -#ifndef NO_PKCS11_BYPASS - if (ss->opt.bypassPKCS11 && - parsed_session_ticket->ms_is_wrapped) - goto no_ticket; -#endif - if (parsed_session_ticket->ms_length > - sizeof(sid->u.ssl3.keys.wrapped_master_secret)) - goto no_ticket; - PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret, - parsed_session_ticket->master_secret, - parsed_session_ticket->ms_length); - sid->u.ssl3.keys.wrapped_master_secret_len = - parsed_session_ticket->ms_length; - sid->u.ssl3.exchKeyType = parsed_session_ticket->exchKeyType; - sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech; - sid->u.ssl3.keys.msIsWrapped = - parsed_session_ticket->ms_is_wrapped; - sid->u.ssl3.masterValid = PR_TRUE; - sid->u.ssl3.keys.resumable = PR_TRUE; - sid->u.ssl3.keys.extendedMasterSecretUsed = parsed_session_ticket-> - extendedMasterSecretUsed; - - /* Copy over client cert from session ticket if there is one. */ - if (parsed_session_ticket->peer_cert.data != NULL) { - if (sid->peerCert != NULL) - CERT_DestroyCertificate(sid->peerCert); - sid->peerCert = CERT_NewTempCertificate(ss->dbHandle, - &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE); - if (sid->peerCert == NULL) { - rv = SECFailure; - goto loser; - } - } - if (parsed_session_ticket->srvName.data != NULL) { - sid->u.ssl3.srvName = parsed_session_ticket->srvName; - } - ss->statelessResume = PR_TRUE; - ss->sec.ci.sid = sid; - } - } - - if (0) { -no_ticket: - SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.", - SSL_GETPID(), ss->fd)); - ssl3stats = SSL_GetStatistics(); - SSL_AtomicIncrementLong(& ssl3stats->hch_sid_ticket_parse_failures ); } - rv = SECSuccess; -loser: - /* ss->sec.ci.sid == sid if it did NOT come here via goto statement - * in that case do not free sid - */ - if (sid && (ss->sec.ci.sid != sid)) { - ssl_FreeSID(sid); - sid = NULL; - } - if (decrypted_state != NULL) { - SECITEM_FreeItem(decrypted_state, PR_TRUE); - decrypted_state = NULL; - } - - if (parsed_session_ticket != NULL) { - if (parsed_session_ticket->peer_cert.data) { - SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE); - } - PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket)); - } - - return rv; + return NULL; } -/* - * Read bytes. Using this function means the SECItem structure - * cannot be freed. The caller is expected to call this function - * on a shallow copy of the structure. - */ -static SECStatus -ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes) -{ - if (bytes > item->len) - return SECFailure; - - *buf = item->data; - item->data += bytes; - item->len -= bytes; - return SECSuccess; -} - -static SECStatus -ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data, - EncryptedSessionTicket *enc_session_ticket) -{ - if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name, - SESS_TICKET_KEY_NAME_LEN) != SECSuccess) - return SECFailure; - if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv, - AES_BLOCK_SIZE) != SECSuccess) - return SECFailure; - if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state, - 2, &data->data, &data->len) != SECSuccess) - return SECFailure; - if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac, - TLS_EX_SESS_TICKET_MAC_LENGTH) != SECSuccess) - return SECFailure; - if (data->len != 0) /* Make sure that we have consumed all bytes. */ - return SECFailure; - - return SECSuccess; -} - -/* go through hello extensions in buffer "b". +/* 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. + * Clients reject any extensions with unadvertised extension types + * + * In TLS >= 1.3, the client checks that extensions appear in the + * right phase. */ SECStatus -ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length) +ssl3_HandleParsedExtensions(sslSocket *ss, + SSL3HandshakeType handshakeMessage) { - const ssl3HelloExtensionHandler * handlers; + const ssl3ExtensionHandler *handlers; + PRBool isTLS13 = ss->version >= SSL_LIBRARY_VERSION_TLS_1_3; + PRCList *cursor; - if (ss->sec.isServer) { - handlers = clientHelloHandlers; - } else if (ss->version > SSL_LIBRARY_VERSION_3_0) { - handlers = serverHelloHandlersTLS; - } else { - handlers = serverHelloHandlersSSL3; + switch (handshakeMessage) { + case client_hello: + handlers = clientHelloHandlers; + break; + case new_session_ticket: + PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); + handlers = newSessionTicketHandlers; + break; + case hello_retry_request: + handlers = helloRetryRequestHandlers; + break; + case encrypted_extensions: + PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_TLS_1_3); + /* fall through */ + case server_hello: + if (ss->version > SSL_LIBRARY_VERSION_3_0) { + handlers = serverHelloHandlersTLS; + } else { + handlers = serverHelloHandlersSSL3; + } + break; + case certificate: + PORT_Assert(!ss->sec.isServer); + handlers = serverCertificateHandlers; + break; + default: + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + PORT_Assert(0); + return SECFailure; } - while (*length) { - const ssl3HelloExtensionHandler * handler; - SECStatus rv; - PRInt32 extension_type; - SECItem extension_data; - - /* Get the extension's type field */ - extension_type = ssl3_ConsumeHandshakeNumber(ss, 2, b, length); - if (extension_type < 0) /* failure to decode extension_type */ - return SECFailure; /* alert already sent */ - - /* 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 */ + for (cursor = PR_NEXT_LINK(&ss->ssl3.hs.remoteExtensions); + cursor != &ss->ssl3.hs.remoteExtensions; + cursor = PR_NEXT_LINK(cursor)) { + TLSExtension *extension = (TLSExtension *)cursor; + const ssl3ExtensionHandler *handler; /* Check whether the server sent an extension which was not advertised - * in the ClientHello. - */ + * in the ClientHello */ if (!ss->sec.isServer && - !ssl3_ClientExtensionAdvertised(ss, extension_type)) { + !ssl3_ClientExtensionAdvertised(ss, extension->type) && + (handshakeMessage != new_session_ticket) && + (extension->type != ssl_tls13_cookie_xtn)) { (void)SSL3_SendAlert(ss, alert_fatal, unsupported_extension); + PORT_SetError(SSL_ERROR_RX_UNEXPECTED_EXTENSION); return SECFailure; } - /* Check whether an extension has been sent multiple times. */ - if (ssl3_ExtensionNegotiated(ss, extension_type)) { - (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); + /* Check that this is a legal extension in TLS 1.3 */ + if (isTLS13 && !tls13_ExtensionAllowed(extension->type, handshakeMessage)) { + if (handshakeMessage == client_hello) { + /* Skip extensions not used in TLS 1.3 */ + continue; + } + tls13_FatalError(ss, SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION, + unsupported_extension); + 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; } /* find extension_type in table of Hello Extension Handlers */ for (handler = handlers; handler->ex_type >= 0; handler++) { /* if found, call this handler */ - if (handler->ex_type == extension_type) { - rv = (*handler->ex_handler)(ss, (PRUint16)extension_type, - &extension_data); + if (handler->ex_type == extension->type) { + SECStatus rv; + + rv = (*handler->ex_handler)(ss, &ss->xtnData, + (PRUint16)extension->type, + &extension->data); if (rv != SECSuccess) { if (!ss->ssl3.fatalAlertSent) { /* send a generic alert if the handler didn't already */ @@ -1974,18 +344,53 @@ ssl3_HandleHelloExtensions(sslSocket *ss, SSL3Opaque **b, PRUint32 *length) return SECSuccess; } +/* Syntactic sugar around ssl3_ParseExtensions and + * ssl3_HandleParsedExtensions. */ +SECStatus +ssl3_HandleExtensions(sslSocket *ss, + SSL3Opaque **b, PRUint32 *length, + SSL3HandshakeType 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_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type, - ssl3HelloExtensionSenderFunc cb) +ssl3_RegisterExtensionSender(const sslSocket *ss, + TLSExtensionData *xtnData, + PRUint16 ex_type, + ssl3HelloExtensionSenderFunc cb) { int i; - ssl3HelloExtensionSender *sender = &ss->xtnData.serverSenders[0]; - + ssl3HelloExtensionSender *sender; + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + sender = &xtnData->serverHelloSenders[0]; + } else { + if (tls13_ExtensionAllowed(ex_type, server_hello)) { + PORT_Assert(!tls13_ExtensionAllowed(ex_type, encrypted_extensions)); + sender = &xtnData->serverHelloSenders[0]; + } else if (tls13_ExtensionAllowed(ex_type, certificate)) { + sender = &xtnData->certificateSenders[0]; + } else { + PORT_Assert(tls13_ExtensionAllowed(ex_type, encrypted_extensions)); + sender = &xtnData->encryptedExtensionsSenders[0]; + } + } for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) { if (!sender->ex_sender) { - sender->ex_type = ex_type; + sender->ex_type = ex_type; sender->ex_sender = cb; return SECSuccess; } @@ -2010,675 +415,116 @@ ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, int i; if (!sender) { - sender = ss->version > SSL_LIBRARY_VERSION_3_0 ? - &clientHelloSendersTLS[0] : &clientHelloSendersSSL3[0]; + if (ss->vrange.max > SSL_LIBRARY_VERSION_3_0) { + sender = &clientHelloSendersTLS[0]; + } else { + sender = &clientHelloSendersSSL3[0]; + } } for (i = 0; i < SSL_MAX_EXTENSIONS; ++i, ++sender) { if (sender->ex_sender) { - PRInt32 extLen = (*sender->ex_sender)(ss, append, maxBytes); + PRInt32 extLen = (*sender->ex_sender)(ss, &ss->xtnData, append, maxBytes); if (extLen < 0) return -1; - maxBytes -= extLen; + maxBytes -= extLen; total_exten_len += extLen; } } return total_exten_len; } - -/* 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) - */ -static PRInt32 -ssl3_SendRenegotiationInfoXtn( - sslSocket * ss, - PRBool append, - PRUint32 maxBytes) +void +ssl3_DestroyRemoteExtensions(PRCList *list) { - PRInt32 len, needed; + PRCList *cur_p; - /* In draft-ietf-tls-renegotiation-03, 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 || ss->ssl3.hs.sendingSCSV) - return 0; - len = !ss->firstHsDone ? 0 : - (ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2 - : ss->ssl3.hs.finishedBytes); - needed = 5 + len; - if (maxBytes < (PRUint32)needed) { - return 0; - } - if (append) { - SECStatus rv; - /* extension_type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2); - if (rv != SECSuccess) return -1; - /* length of extension_data */ - rv = ssl3_AppendHandshakeNumber(ss, len + 1, 2); - if (rv != SECSuccess) return -1; - /* verify_Data from previous Finished message(s) */ - rv = ssl3_AppendHandshakeVariable(ss, - ss->ssl3.hs.finishedMsgs.data, len, 1); - if (rv != SECSuccess) return -1; - if (!ss->sec.isServer) { - TLSExtensionData *xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = - ssl_renegotiation_info_xtn; - } + while (!PR_CLIST_IS_EMPTY(list)) { + cur_p = PR_LIST_TAIL(list); + PR_REMOVE_LINK(cur_p); + PORT_Free(cur_p); } - return needed; -} - -static SECStatus -ssl3_ServerHandleStatusRequestXtn(sslSocket *ss, PRUint16 ex_type, - SECItem *data) -{ - SECStatus rv = SECSuccess; - - /* remember that we got this extension. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - PORT_Assert(ss->sec.isServer); - /* prepare to send back the appropriate response */ - rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type, - ssl3_ServerSendStatusRequestXtn); - return rv; } -/* This function runs in both the client and server. */ -static SECStatus -ssl3_HandleRenegotiationInfoXtn(sslSocket *ss, PRUint16 ex_type, SECItem *data) +/* Initialize the extension data block. */ +void +ssl3_InitExtensionData(TLSExtensionData *xtnData) { - SECStatus rv = SECSuccess; - PRUint32 len = 0; - - 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 ) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - if (len && NSS_SecureMemcmp(ss->ssl3.hs.finishedMsgs.data, - data->data + 1, len)) { - (void)SSL3_SendAlert(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. */ - ss->peerRequestedProtection = 1; - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - if (ss->sec.isServer) { - /* prepare to send back the appropriate response */ - rv = ssl3_RegisterServerHelloExtensionSender(ss, ex_type, - ssl3_SendRenegotiationInfoXtn); - } - return rv; + /* Set things up to the right starting state. */ + PORT_Memset(xtnData, 0, sizeof(*xtnData)); + xtnData->peerSupportsFfdheGroups = PR_FALSE; + PR_INIT_CLIST(&xtnData->remoteKeyShares); } -static PRInt32 -ssl3_ClientSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) +/* Free everything that has been allocated and then reset back to + * the starting state. */ +void +ssl3_ResetExtensionData(TLSExtensionData *xtnData) { - PRUint32 ext_data_len; - PRInt16 i; - SECStatus rv; - - if (!ss) - return 0; - - if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) - return 0; /* Not relevant */ - - ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1; - - if (append && maxBytes >= 4 + ext_data_len) { - /* Extension type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); - if (rv != SECSuccess) return -1; - /* Length of extension data */ - rv = ssl3_AppendHandshakeNumber(ss, ext_data_len, 2); - if (rv != SECSuccess) return -1; - /* Length of the SRTP cipher list */ - rv = ssl3_AppendHandshakeNumber(ss, - 2 * ss->ssl3.dtlsSRTPCipherCount, - 2); - if (rv != SECSuccess) return -1; - /* The SRTP ciphers */ - for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) { - rv = ssl3_AppendHandshakeNumber(ss, - ss->ssl3.dtlsSRTPCiphers[i], - 2); - } - /* Empty MKI value */ - ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); + /* Clean up. */ + ssl3_FreeSniNameArray(xtnData); + PORT_Free(xtnData->clientSigSchemes); + SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE); + tls13_DestroyKeyShares(&xtnData->remoteKeyShares); - ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_use_srtp_xtn; - } - - return 4 + ext_data_len; + /* Now reinit. */ + ssl3_InitExtensionData(xtnData); } -static PRInt32 -ssl3_ServerSendUseSRTPXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) +/* Thunks to let extension handlers operate on const sslSocket* objects. */ +SECStatus +ssl3_ExtAppendHandshake(const sslSocket *ss, const void *void_src, + PRInt32 bytes) { - SECStatus rv; - - /* Server side */ - if (!append || maxBytes < 9) { - return 9; - } - - /* Extension type */ - rv = ssl3_AppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); - if (rv != SECSuccess) return -1; - /* Length of extension data */ - rv = ssl3_AppendHandshakeNumber(ss, 5, 2); - if (rv != SECSuccess) return -1; - /* Length of the SRTP cipher list */ - rv = ssl3_AppendHandshakeNumber(ss, 2, 2); - if (rv != SECSuccess) return -1; - /* The selected cipher */ - rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.dtlsSRTPCipherSuite, 2); - if (rv != SECSuccess) return -1; - /* Empty MKI value */ - ssl3_AppendHandshakeVariable(ss, NULL, 0, 1); - - return 9; + return ssl3_AppendHandshake((sslSocket *)ss, void_src, bytes); } -static SECStatus -ssl3_ClientHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +SECStatus +ssl3_ExtAppendHandshakeNumber(const sslSocket *ss, PRInt32 num, + PRInt32 lenSize) { - SECStatus rv; - SECItem ciphers = {siBuffer, NULL, 0}; - PRUint16 i; - PRUint16 cipher = 0; - PRBool found = PR_FALSE; - SECItem litem; - - if (!data->data || !data->len) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - - /* Get the cipher list */ - rv = ssl3_ConsumeHandshakeVariable(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) { - (void)ssl3_DecodeError(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) { - (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); - PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO); - return SECFailure; - } - - /* Get the srtp_mki value */ - rv = ssl3_ConsumeHandshakeVariable(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) { - (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter); - PORT_SetError(SSL_ERROR_RX_MALFORMED_SERVER_HELLO); - return SECFailure; - } - - /* extra trailing bytes */ - if (data->len != 0) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - - /* OK, this looks fine. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn; - ss->ssl3.dtlsSRTPCipherSuite = cipher; - return SECSuccess; + return ssl3_AppendHandshakeNumber((sslSocket *)ss, num, lenSize); } -static SECStatus -ssl3_ServerHandleUseSRTPXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +SECStatus +ssl3_ExtAppendHandshakeVariable(const sslSocket *ss, + const SSL3Opaque *src, PRInt32 bytes, + PRInt32 lenSize) { - 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) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - - /* Get the cipher list */ - rv = ssl3_ConsumeHandshakeVariable(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) { - (void)ssl3_DecodeError(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_ConsumeHandshakeVariable(ss, &litem, 1, &data->data, &data->len); - if (rv != SECSuccess) { - return SECFailure; - } - - if (data->len != 0) { - (void)ssl3_DecodeError(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 */ - ss->ssl3.dtlsSRTPCipherSuite = cipher; - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ssl_use_srtp_xtn; - - return ssl3_RegisterServerHelloExtensionSender(ss, ssl_use_srtp_xtn, - ssl3_ServerSendUseSRTPXtn); + return ssl3_AppendHandshakeVariable((sslSocket *)ss, src, bytes, lenSize); } -/* ssl3_ServerHandleSigAlgsXtn handles the signature_algorithms extension - * from a client. - * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ -static SECStatus -ssl3_ServerHandleSigAlgsXtn(sslSocket * ss, PRUint16 ex_type, SECItem *data) +void +ssl3_ExtSendAlert(const sslSocket *ss, SSL3AlertLevel level, + SSL3AlertDescription desc) { - SECStatus rv; - SECItem algorithms; - const unsigned char *b; - unsigned int numAlgorithms, i; - - /* Ignore this extension if we aren't doing TLS 1.2 or greater. */ - if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) { - return SECSuccess; - } - - rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &data->data, - &data->len); - if (rv != SECSuccess) { - return SECFailure; - } - /* Trailing data, empty value, or odd-length value is invalid. */ - if (data->len != 0 || algorithms.len == 0 || (algorithms.len & 1) != 0) { - (void)SSL3_SendAlert(ss, alert_fatal, decode_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); - return SECFailure; - } - - numAlgorithms = algorithms.len/2; - - /* We don't care to process excessive numbers of algorithms. */ - if (numAlgorithms > 512) { - numAlgorithms = 512; - } - - ss->ssl3.hs.clientSigAndHash = - PORT_NewArray(SSLSignatureAndHashAlg, numAlgorithms); - if (!ss->ssl3.hs.clientSigAndHash) { - (void)SSL3_SendAlert(ss, alert_fatal, internal_error); - PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); - return SECFailure; - } - ss->ssl3.hs.numClientSigAndHash = 0; - - b = algorithms.data; - ss->ssl3.hs.numClientSigAndHash = 0; - for (i = 0; i < numAlgorithms; i++) { - SSLSignatureAndHashAlg *sigAndHash = - &ss->ssl3.hs.clientSigAndHash[ss->ssl3.hs.numClientSigAndHash]; - sigAndHash->hashAlg = (SSLHashType)*(b++); - sigAndHash->sigAlg = (SSLSignType)*(b++); - if (ssl3_IsSupportedSignatureAlgorithm(sigAndHash)) { - ++ss->ssl3.hs.numClientSigAndHash; - } - } - - if (!ss->ssl3.hs.numClientSigAndHash) { - /* We didn't understand any of the client's requested signature - * formats. We'll use the defaults. */ - PORT_Free(ss->ssl3.hs.clientSigAndHash); - ss->ssl3.hs.clientSigAndHash = NULL; - } - - /* Keep track of negotiated extensions. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - return SECSuccess; + (void)SSL3_SendAlert((sslSocket *)ss, level, desc); } -/* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS - * 1.2 ClientHellos. */ -static PRInt32 -ssl3_ClientSendSigAlgsXtn(sslSocket *ss, PRBool append, PRUint32 maxBytes) +void +ssl3_ExtDecodeError(const sslSocket *ss) { - PRInt32 extension_length; - unsigned int i; - PRInt32 pos=0; - PRUint32 policy; - PRUint8 buf[MAX_SIGNATURE_ALGORITHMS * 2]; - - if (ss->version < SSL_LIBRARY_VERSION_TLS_1_2) { - return 0; - } - - for (i=0; i < ss->ssl3.signatureAlgorithmCount; i++) { - SECOidTag hashOID = ssl3_TLSHashAlgorithmToOID( - ss->ssl3.signatureAlgorithms[i].hashAlg); - if ((NSS_GetAlgorithmPolicy(hashOID, & policy) != SECSuccess) || - (policy & NSS_USE_ALG_IN_SSL_KX)) { - buf[pos++] = ss->ssl3.signatureAlgorithms[i].hashAlg; - buf[pos++] = ss->ssl3.signatureAlgorithms[i].sigAlg; - } - } - - extension_length = - 2 /* extension type */ + - 2 /* extension length */ + - 2 /* supported_signature_algorithms length */ + - pos; - - if (maxBytes < extension_length) { - PORT_Assert(0); - return 0; - } - - if (append) { - SECStatus rv; - rv = ssl3_AppendHandshakeNumber(ss, ssl_signature_algorithms_xtn, 2); - if (rv != SECSuccess) { - return -1; - } - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) { - return -1; - } - - rv = ssl3_AppendHandshakeVariable(ss, buf, extension_length - 6, 2); - if (rv != SECSuccess) { - return -1; - } - - ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_signature_algorithms_xtn; - } - - return extension_length; + (void)ssl3_DecodeError((sslSocket *)ss); } -unsigned int -ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength) +SECStatus +ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length) { - unsigned int recordLength = 1 /* handshake message type */ + - 3 /* handshake message length */ + - clientHelloLength; - unsigned int extensionLength; - - if (recordLength < 256 || recordLength >= 512) { - return 0; - } - - extensionLength = 512 - recordLength; - /* Extensions take at least four bytes to encode. */ - if (extensionLength < 4) { - extensionLength = 4; - } - - return extensionLength; + return ssl3_ConsumeHandshake((sslSocket *)ss, v, bytes, b, length); } -/* ssl3_AppendPaddingExtension 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. */ PRInt32 -ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen, - PRUint32 maxBytes) -{ - unsigned int paddingLen = extensionLen - 4; - static unsigned char padding[256]; - - if (extensionLen == 0) { - return 0; - } - - if (extensionLen < 4 || - extensionLen > maxBytes || - paddingLen > sizeof(padding)) { - PORT_Assert(0); - return -1; - } - - if (SECSuccess != ssl3_AppendHandshakeNumber(ss, ssl_padding_xtn, 2)) - return -1; - if (SECSuccess != ssl3_AppendHandshakeNumber(ss, paddingLen, 2)) - return -1; - if (SECSuccess != ssl3_AppendHandshake(ss, padding, paddingLen)) - return -1; - - return extensionLen; -} - -/* ssl3_ClientSendDraftVersionXtn sends the TLS 1.3 temporary draft - * version extension. - * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */ -static PRInt32 -ssl3_ClientSendDraftVersionXtn(sslSocket * ss, PRBool append, PRUint32 maxBytes) -{ - PRInt32 extension_length; - - if (ss->version != SSL_LIBRARY_VERSION_TLS_1_3) { - return 0; - } - - extension_length = 6; /* Type + length + number */ - if (maxBytes < (PRUint32)extension_length) { - PORT_Assert(0); - return 0; - } - if (append) { - SECStatus rv; - rv = ssl3_AppendHandshakeNumber(ss, ssl_tls13_draft_version_xtn, 2); - if (rv != SECSuccess) - goto loser; - rv = ssl3_AppendHandshakeNumber(ss, extension_length - 4, 2); - if (rv != SECSuccess) - goto loser; - rv = ssl3_AppendHandshakeNumber(ss, TLS_1_3_DRAFT_VERSION, 2); - if (rv != SECSuccess) - goto loser; - ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_tls13_draft_version_xtn; - } - - return extension_length; - -loser: - return -1; -} - -/* ssl3_ServerHandleDraftVersionXtn handles the TLS 1.3 temporary draft - * version extension. - * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */ -static SECStatus -ssl3_ServerHandleDraftVersionXtn(sslSocket * ss, PRUint16 ex_type, - SECItem *data) +ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length) { - PRInt32 draft_version; - - /* Ignore this extension if we aren't doing TLS 1.3 */ - if (ss->version != SSL_LIBRARY_VERSION_TLS_1_3) { - return SECSuccess; - } - - if (data->len != 2) { - (void)ssl3_DecodeError(ss); - return SECFailure; - } - - /* Get the draft version out of the handshake */ - draft_version = ssl3_ConsumeHandshakeNumber(ss, 2, - &data->data, &data->len); - if (draft_version < 0) { - return SECFailure; - } - - /* Keep track of negotiated extensions. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - - if (draft_version != TLS_1_3_DRAFT_VERSION) { - /* - * Incompatible/broken TLS 1.3 implementation. Fall back to TLS 1.2. - * TODO(ekr@rtfm.com): It's not entirely clear it's safe to roll back - * here. Need to double-check. - */ - SSL_TRC(30, ("%d: SSL3[%d]: Incompatible version of TLS 1.3 (%d), " - "expected %d", - SSL_GETPID(), ss->fd, draft_version, TLS_1_3_DRAFT_VERSION)); - ss->version = SSL_LIBRARY_VERSION_TLS_1_2; - } - - return SECSuccess; + return ssl3_ConsumeHandshakeNumber((sslSocket *)ss, bytes, b, length); } -static PRInt32 -ssl3_SendExtendedMasterSecretXtn(sslSocket * ss, PRBool append, - PRUint32 maxBytes) -{ - PRInt32 extension_length; - - if (!ss->opt.enableExtendedMS) { - return 0; - } - -#ifndef NO_PKCS11_BYPASS - /* Extended MS can only be used w/o bypass mode */ - if (ss->opt.bypassPKCS11) { - PORT_Assert(0); - PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); - return -1; - } -#endif - - /* 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. */ - extension_length = 4; /* Type + length (0) */ - if (maxBytes < extension_length) { - PORT_Assert(0); - return 0; - } - - if (append) { - SECStatus rv; - rv = ssl3_AppendHandshakeNumber(ss, ssl_extended_master_secret_xtn, 2); - if (rv != SECSuccess) - goto loser; - rv = ssl3_AppendHandshakeNumber(ss, 0, 2); - if (rv != SECSuccess) - goto loser; - ss->xtnData.advertised[ss->xtnData.numAdvertised++] = - ssl_extended_master_secret_xtn; - } - - return extension_length; - -loser: - return -1; -} - - -static SECStatus -ssl3_HandleExtendedMasterSecretXtn(sslSocket * ss, PRUint16 ex_type, - SECItem *data) +SECStatus +ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i, + PRInt32 bytes, SSL3Opaque **b, + PRUint32 *length) { - if (ss->version < SSL_LIBRARY_VERSION_TLS_1_0) { - return SECSuccess; - } - - if (!ss->opt.enableExtendedMS) { - return SECSuccess; - } - -#ifndef NO_PKCS11_BYPASS - /* Extended MS can only be used w/o bypass mode */ - if (ss->opt.bypassPKCS11) { - PORT_Assert(0); - PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); - return SECFailure; - } -#endif - - if (data->len != 0) { - SSL_TRC(30, ("%d: SSL3[%d]: Bogus extended master secret extension", - SSL_GETPID(), ss->fd)); - return SECFailure; - } - - SSL_DBG(("%d: SSL[%d]: Negotiated extended master secret extension.", - SSL_GETPID(), ss->fd)); - - /* Keep track of negotiated extensions. */ - ss->xtnData.negotiated[ss->xtnData.numNegotiated++] = ex_type; - - if (ss->sec.isServer) { - return ssl3_RegisterServerHelloExtensionSender( - ss, ex_type, ssl3_SendExtendedMasterSecretXtn); - } - return SECSuccess; + return ssl3_ConsumeHandshakeVariable((sslSocket *)ss, i, bytes, b, length); } diff --git a/nss/lib/ssl/ssl3ext.h b/nss/lib/ssl/ssl3ext.h new file mode 100644 index 0000000..f93ad65 --- /dev/null +++ b/nss/lib/ssl/ssl3ext.h @@ -0,0 +1,156 @@ +/* -*- 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_ + +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 PRInt32 (*ssl3HelloExtensionSenderFunc)(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); + +/* registerable callback function that handles a received extension, + * of the given type. + */ +typedef SECStatus (*ssl3ExtensionHandlerFunc)(const sslSocket *ss, + TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); + +/* row in a table of hello extension senders */ +typedef struct { + PRInt32 ex_type; + ssl3HelloExtensionSenderFunc ex_sender; +} ssl3HelloExtensionSender; + +/* row in a table of hello extension handlers */ +typedef struct { + PRInt32 ex_type; + ssl3ExtensionHandlerFunc ex_handler; +} ssl3ExtensionHandler; + +struct TLSExtensionDataStr { + /* registered callbacks that send server hello extensions */ + ssl3HelloExtensionSender serverHelloSenders[SSL_MAX_EXTENSIONS]; + ssl3HelloExtensionSender encryptedExtensionsSenders[SSL_MAX_EXTENSIONS]; + ssl3HelloExtensionSender certificateSenders[SSL_MAX_EXTENSIONS]; + + /* Keep track of the extensions that are negotiated. */ + PRUint16 numAdvertised; + PRUint16 numNegotiated; + PRUint16 advertised[SSL_MAX_EXTENSIONS]; + 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) from the client. This is only valid for TLS 1.2 + * or later. */ + SSLSignatureScheme *clientSigSchemes; + unsigned int numClientSigScheme; + + /* 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 */ + + SECItem pskBinder; /* The PSK binder for the first PSK (TLS 1.3) */ + unsigned long pskBinderPrefixLen; /* The length of the binder input. */ + PRCList remoteKeyShares; /* The other side's public keys (TLS 1.3) */ +}; + +typedef struct TLSExtensionStr { + PRCList link; /* The linked list link */ + PRUint16 type; /* Extension type */ + SECItem data; /* Pointers into the handshake data. */ +} TLSExtension; + +SECStatus ssl3_HandleExtensions(sslSocket *ss, + SSL3Opaque **b, PRUint32 *length, + SSL3HandshakeType handshakeMessage); +SECStatus ssl3_ParseExtensions(sslSocket *ss, + SSL3Opaque **b, PRUint32 *length); +SECStatus ssl3_HandleParsedExtensions(sslSocket *ss, + SSL3HandshakeType handshakeMessage); +TLSExtension *ssl3_FindExtension(sslSocket *ss, + SSLExtensionType extension_type); +void ssl3_DestroyRemoteExtensions(PRCList *list); +void ssl3_InitExtensionData(TLSExtensionData *xtnData); +void ssl3_ResetExtensionData(TLSExtensionData *xtnData); + +PRBool ssl3_ExtensionNegotiated(const sslSocket *ss, PRUint16 ex_type); +PRBool ssl3_ClientExtensionAdvertised(const sslSocket *ss, PRUint16 ex_type); + +SECStatus ssl3_RegisterExtensionSender(const sslSocket *ss, + TLSExtensionData *xtnData, + PRUint16 ex_type, + ssl3HelloExtensionSenderFunc cb); +PRInt32 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, + const ssl3HelloExtensionSender *sender); + +unsigned int ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength); +PRInt32 ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen, + PRUint32 maxBytes); + +/* Thunks to let us operate on const sslSocket* objects. */ +SECStatus ssl3_ExtAppendHandshake(const sslSocket *ss, const void *void_src, + PRInt32 bytes); +SECStatus ssl3_ExtAppendHandshakeNumber(const sslSocket *ss, PRInt32 num, + PRInt32 lenSize); +SECStatus ssl3_ExtAppendHandshakeVariable(const sslSocket *ss, + const SSL3Opaque *src, PRInt32 bytes, + PRInt32 lenSize); +void ssl3_ExtSendAlert(const sslSocket *ss, SSL3AlertLevel level, + SSL3AlertDescription desc); +void ssl3_ExtDecodeError(const sslSocket *ss); +SECStatus ssl3_ExtConsumeHandshake(const sslSocket *ss, void *v, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length); +PRInt32 ssl3_ExtConsumeHandshakeNumber(const sslSocket *ss, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length); +SECStatus ssl3_ExtConsumeHandshakeVariable(const sslSocket *ss, SECItem *i, + PRInt32 bytes, SSL3Opaque **b, + PRUint32 *length); + +#endif diff --git a/nss/lib/ssl/ssl3exthandle.c b/nss/lib/ssl/ssl3exthandle.c new file mode 100644 index 0000000..2a80e26 --- /dev/null +++ b/nss/lib/ssl/ssl3exthandle.c @@ -0,0 +1,2579 @@ +/* -*- 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 "ssl3ext.h" +#include "ssl3exthandle.h" +#include "tls13exthandle.h" /* For tls13_ServerSendStatusRequestXtn. */ + +static unsigned char key_name[SESS_TICKET_KEY_NAME_LEN]; +static PK11SymKey *session_ticket_enc_key = NULL; +static PK11SymKey *session_ticket_mac_key = NULL; + +static PRCallOnceType generate_session_keys_once; + +static SECStatus ssl3_ParseEncryptedSessionTicket(sslSocket *ss, + SECItem *data, EncryptedSessionTicket *enc_session_ticket); +static SECStatus ssl3_AppendToItem(SECItem *item, const unsigned char *buf, + PRUint32 bytes); +static SECStatus ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes); +static SECStatus ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, + PRInt32 lenSize); +static SECStatus ssl3_GetSessionTicketKeys(sslSocket *ss, + PK11SymKey **aes_key, PK11SymKey **mac_key); +static SECStatus ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes); + +/* + * Write bytes. Using this function means the SECItem structure + * cannot be freed. The caller is expected to call this function + * on a shallow copy of the structure. + */ +static SECStatus +ssl3_AppendToItem(SECItem *item, const unsigned char *buf, PRUint32 bytes) +{ + if (bytes > item->len) + return SECFailure; + + PORT_Memcpy(item->data, buf, bytes); + item->data += bytes; + item->len -= bytes; + return SECSuccess; +} + +/* + * Write a number in network byte order. Using this function means the + * SECItem structure cannot be freed. The caller is expected to call + * this function on a shallow copy of the structure. + */ +static SECStatus +ssl3_AppendNumberToItem(SECItem *item, PRUint32 num, PRInt32 lenSize) +{ + SECStatus rv; + PRUint8 b[4]; + PRUint8 *p = b; + + switch (lenSize) { + case 4: + *p++ = (PRUint8)(num >> 24); + case 3: + *p++ = (PRUint8)(num >> 16); + case 2: + *p++ = (PRUint8)(num >> 8); + case 1: + *p = (PRUint8)num; + } + rv = ssl3_AppendToItem(item, &b[0], lenSize); + return rv; +} + +SECStatus +ssl3_SessionTicketShutdown(void *appData, void *nssData) +{ + if (session_ticket_enc_key) { + PK11_FreeSymKey(session_ticket_enc_key); + session_ticket_enc_key = NULL; + } + if (session_ticket_mac_key) { + PK11_FreeSymKey(session_ticket_mac_key); + session_ticket_mac_key = NULL; + } + PORT_Memset(&generate_session_keys_once, 0, + sizeof(generate_session_keys_once)); + return SECSuccess; +} + +static PRStatus +ssl3_GenerateSessionTicketKeys(void *data) +{ + SECStatus rv; + sslSocket *ss = (sslSocket *)data; + sslServerCertType certType = { ssl_auth_rsa_decrypt, NULL }; + const sslServerCert *sc; + SECKEYPrivateKey *svrPrivKey; + SECKEYPublicKey *svrPubKey; + + sc = ssl_FindServerCert(ss, &certType); + if (!sc || !sc->serverKeyPair) { + SSL_DBG(("%d: SSL[%d]: No ssl_auth_rsa_decrypt cert and key pair", + SSL_GETPID(), ss->fd)); + goto loser; + } + svrPrivKey = sc->serverKeyPair->privKey; + svrPubKey = sc->serverKeyPair->pubKey; + if (svrPrivKey == NULL || svrPubKey == NULL) { + SSL_DBG(("%d: SSL[%d]: Pub or priv key(s) is NULL.", + SSL_GETPID(), ss->fd)); + goto loser; + } + + /* Get a copy of the session keys from shared memory. */ + PORT_Memcpy(key_name, SESS_TICKET_KEY_NAME_PREFIX, + sizeof(SESS_TICKET_KEY_NAME_PREFIX)); + if (!ssl_GetSessionTicketKeys(svrPrivKey, svrPubKey, ss->pkcs11PinArg, + &key_name[SESS_TICKET_KEY_NAME_PREFIX_LEN], + &session_ticket_enc_key, &session_ticket_mac_key)) + return PR_FAILURE; + + rv = NSS_RegisterShutdown(ssl3_SessionTicketShutdown, NULL); + if (rv != SECSuccess) + goto loser; + + return PR_SUCCESS; + +loser: + ssl3_SessionTicketShutdown(NULL, NULL); + return PR_FAILURE; +} + +static SECStatus +ssl3_GetSessionTicketKeys(sslSocket *ss, PK11SymKey **aes_key, + PK11SymKey **mac_key) +{ + if (PR_CallOnceWithArg(&generate_session_keys_once, + ssl3_GenerateSessionTicketKeys, ss) != + PR_SUCCESS) + return SECFailure; + + if (session_ticket_enc_key == NULL || + session_ticket_mac_key == NULL) + return SECFailure; + + *aes_key = session_ticket_enc_key; + *mac_key = session_ticket_mac_key; + return SECSuccess; +} + +/* 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. + */ +PRInt32 +ssl3_SendServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + SECStatus rv; + if (!ss) + return 0; + if (!ss->sec.isServer) { + PRUint32 len; + PRNetAddr netAddr; + + /* must have a hostname */ + if (!ss->url || !ss->url[0]) + return 0; + /* must not be an IPv4 or IPv6 address */ + if (PR_SUCCESS == PR_StringToNetAddr(ss->url, &netAddr)) { + /* is an IP address (v4 or v6) */ + return 0; + } + len = PORT_Strlen(ss->url); + if (append && maxBytes >= len + 9) { + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_server_name_xtn, 2); + if (rv != SECSuccess) + return -1; + /* length of extension_data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, len + 5, 2); + if (rv != SECSuccess) + return -1; + /* length of server_name_list */ + rv = ssl3_ExtAppendHandshakeNumber(ss, len + 3, 2); + if (rv != SECSuccess) + return -1; + /* Name Type (sni_host_name) */ + rv = ssl3_ExtAppendHandshake(ss, "\0", 1); + if (rv != SECSuccess) + return -1; + /* HostName (length and value) */ + rv = ssl3_ExtAppendHandshakeVariable(ss, (PRUint8 *)ss->url, len, 2); + if (rv != SECSuccess) + return -1; + if (!ss->sec.isServer) { + xtnData->advertised[xtnData->numAdvertised++] = + ssl_server_name_xtn; + } + } + return len + 9; + } + /* Server side */ + if (append && maxBytes >= 4) { + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_server_name_xtn, 2); + if (rv != SECSuccess) + return -1; + /* length of extension_data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + } + return 4; +} + +/* Handle an incoming SNI extension. */ +SECStatus +ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data) +{ + SECItem *names = NULL; + PRInt32 listLenBytes = 0; + + 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 */ + listLenBytes = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (listLenBytes < 0) { + goto loser; /* alert already sent */ + } + if (listLenBytes == 0 || listLenBytes != data->len) { + goto alert_loser; + } + + /* Read ServerNameList. */ + while (data->len > 0) { + SECItem tmp; + SECStatus rv; + PRInt32 type; + + /* Read Name Type. */ + type = ssl3_ExtConsumeHandshakeNumber(ss, 1, &data->data, &data->len); + if (type < 0) { /* i.e., SECFailure cast to PRint32 */ + /* 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. + */ +PRInt32 +ssl3_SendSessionTicketXtn( + const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + NewSessionTicket *session_ticket = NULL; + sslSessionID *sid = ss->sec.ci.sid; + + /* 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->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + return 0; + } + + /* Ignore the SessionTicket extension if processing is disabled. */ + if (!ss->opt.enableSessionTickets) + return 0; + + /* Empty extension length = extension_type (2-bytes) + + * length(extension_data) (2-bytes) + */ + extension_length = 4; + + /* If we are a client then send a session ticket if one is availble. + * Servers that support the extension and are willing to negotiate the + * the extension always respond with an empty extension. + */ + if (!ss->sec.isServer) { + /* 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) { + if (xtnData->ticketTimestampVerified) { + extension_length += session_ticket->ticket.len; + } else if (!append && + (session_ticket->ticket_lifetime_hint == 0 || + (session_ticket->ticket_lifetime_hint + + session_ticket->received_timestamp > + ssl_Time()))) { + extension_length += session_ticket->ticket.len; + xtnData->ticketTimestampVerified = PR_TRUE; + } + } + } + + if (maxBytes < (PRUint32)extension_length) { + PORT_Assert(0); + return 0; + } + if (append) { + SECStatus rv; + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_session_ticket_xtn, 2); + if (rv != SECSuccess) + goto loser; + if (session_ticket && session_ticket->ticket.data && + xtnData->ticketTimestampVerified) { + rv = ssl3_ExtAppendHandshakeVariable(ss, session_ticket->ticket.data, + session_ticket->ticket.len, 2); + xtnData->ticketTimestampVerified = PR_FALSE; + xtnData->sentSessionTicketInClientHello = PR_TRUE; + } else { + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + } + if (rv != SECSuccess) + goto loser; + + if (!ss->sec.isServer) { + xtnData->advertised[xtnData->numAdvertised++] = + ssl_session_ticket_xtn; + } + } + return extension_length; + +loser: + xtnData->ticketTimestampVerified = PR_FALSE; + return -1; +} + +static SECStatus +ssl3_ParseEncryptedSessionTicket(sslSocket *ss, SECItem *data, + EncryptedSessionTicket *enc_session_ticket) +{ + if (ssl3_ConsumeFromItem(data, &enc_session_ticket->key_name, + SESS_TICKET_KEY_NAME_LEN) != + SECSuccess) + return SECFailure; + if (ssl3_ConsumeFromItem(data, &enc_session_ticket->iv, + AES_BLOCK_SIZE) != + SECSuccess) + return SECFailure; + if (ssl3_ConsumeHandshakeVariable(ss, &enc_session_ticket->encrypted_state, + 2, &data->data, &data->len) != + SECSuccess) + return SECFailure; + if (ssl3_ConsumeFromItem(data, &enc_session_ticket->mac, + TLS_EX_SESS_TICKET_MAC_LENGTH) != + SECSuccess) + return SECFailure; + if (data->len != 0) /* Make sure that we have consumed all bytes. */ + return SECFailure; + + return SECSuccess; +} + +/* handle an incoming Next Protocol Negotiation extension. */ +SECStatus +ssl3_ServerHandleNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + if (ss->firstHsDone || data->len != 0) { + /* Clients MUST send an empty NPN extension, if any. */ + PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); + return SECFailure; + } + + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + /* TODO: server side NPN support would require calling + * ssl3_RegisterServerHelloExtensionSender here in order to echo the + * extension back to the client. */ + + return SECSuccess; +} + +/* ssl3_ValidateNextProtoNego 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_ValidateNextProtoNego(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 (server side) and NPN (client side) */ +static SECStatus +ssl3_SelectAppProtocol(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data) +{ + SECStatus rv; + unsigned char resultBuffer[255]; + SECItem result = { siBuffer, resultBuffer, 0 }; + + rv = ssl3_ValidateNextProtoNego(data->data, data->len); + if (rv != SECSuccess) { + ssl3_ExtSendAlert(ss, alert_fatal, decode_error); + PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID); + return rv; + } + + PORT_Assert(ss->nextProtoCallback); + /* For ALPN, the cipher suite isn't 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_all & ~ssl_preinfo_cipher_suite)); + 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); + /* TODO: crash */ + return SECFailure; + } + + SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE); + + if (ex_type == ssl_app_layer_protocol_xtn && + xtnData->nextProtoState != SSL_NEXT_PROTO_NEGOTIATED) { + /* The callback might say OK, but then it picks a default value - one + * that was not listed. That's OK for NPN, but not ALPN. */ + ssl3_ExtSendAlert(ss, alert_fatal, no_application_protocol); + PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_PROTOCOL); + return SECFailure; + } + + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + return SECITEM_CopyItem(NULL, &xtnData->nextProto, &result); +} + +/* handle an incoming ALPN extension at the server */ +SECStatus +ssl3_ServerHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data) +{ + int 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; + } + + /* Unlike NPN, ALPN has extra redundant length information so that + * the extension is the same in both ClientHello and ServerHello. */ + count = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (count != data->len) { + ssl3_ExtDecodeError(ss); + return SECFailure; + } + + if (!ss->nextProtoCallback) { + /* we're not configured for it */ + return SECSuccess; + } + + rv = ssl3_SelectAppProtocol(ss, xtnData, ex_type, 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, ex_type, ssl3_ServerSendAppProtoXtn); + if (rv != SECSuccess) { + ssl3_ExtSendAlert(ss, alert_fatal, internal_error); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return rv; + } + } + return SECSuccess; +} + +SECStatus +ssl3_ClientHandleNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + PORT_Assert(!ss->firstHsDone); + + if (ssl3_ExtensionNegotiated(ss, ssl_app_layer_protocol_xtn)) { + /* If the server negotiated ALPN then it has already told us what + * protocol to use, so it doesn't make sense for us to try to negotiate + * a different one by sending the NPN handshake message. However, if + * we've negotiated NPN then we're required to send the NPN handshake + * message. Thus, these two extensions cannot both be negotiated on the + * same connection. */ + ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter); + PORT_SetError(SSL_ERROR_BAD_SERVER); + return SECFailure; + } + + /* We should only get this call if we sent the extension, so + * ss->nextProtoCallback needs to be non-NULL. However, it is possible + * that an application erroneously cleared the callback between the time + * we sent the ClientHello and now. */ + if (!ss->nextProtoCallback) { + PORT_Assert(0); + ssl3_ExtSendAlert(ss, alert_fatal, internal_error); + PORT_SetError(SSL_ERROR_NEXT_PROTOCOL_NO_CALLBACK); + return SECFailure; + } + + return ssl3_SelectAppProtocol(ss, xtnData, ex_type, data); +} + +SECStatus +ssl3_ClientHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data) +{ + SECStatus rv; + PRInt32 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; + } + + list_len = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + /* The list has to be the entire extension. */ + if (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; + } + + SECITEM_FreeItem(&xtnData->nextProto, PR_FALSE); + xtnData->nextProtoState = SSL_NEXT_PROTO_SELECTED; + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + return SECITEM_CopyItem(NULL, &xtnData->nextProto, &protocol_name); +} + +PRInt32 +ssl3_ClientSendNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + + /* Renegotiations do not send this extension. */ + if (!ss->opt.enableNPN || !ss->nextProtoCallback || ss->firstHsDone) { + return 0; + } + + extension_length = 4; + + if (maxBytes < (PRUint32)extension_length) { + return 0; + } + if (append) { + SECStatus rv; + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_next_proto_nego_xtn, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + goto loser; + xtnData->advertised[xtnData->numAdvertised++] = + ssl_next_proto_nego_xtn; + } + + return extension_length; + +loser: + return -1; +} + +PRInt32 +ssl3_ClientSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, PRUint32 maxBytes) +{ + PRInt32 extension_length; + unsigned char *alpn_protos = NULL; + + /* Renegotiations do not send this extension. */ + if (!ss->opt.enableALPN || !ss->opt.nextProtoNego.data || ss->firstHsDone) { + return 0; + } + + extension_length = 2 /* extension type */ + 2 /* extension length */ + + 2 /* protocol name list length */ + + ss->opt.nextProtoNego.len; + + if (maxBytes < (PRUint32)extension_length) { + return 0; + } + if (append) { + /* NPN requires that the client's fallback protocol is first in the + * list. However, ALPN sends protocols in preference order. So we + * allocate a buffer and move the first protocol to the end of the + * list. */ + SECStatus rv; + const unsigned int len = ss->opt.nextProtoNego.len; + + alpn_protos = PORT_Alloc(len); + if (alpn_protos == NULL) { + return SECFailure; + } + if (len > 0) { + /* Each protocol string is prefixed with a single byte length. */ + unsigned int i = ss->opt.nextProtoNego.data[0] + 1; + if (i <= len) { + memcpy(alpn_protos, &ss->opt.nextProtoNego.data[i], len - i); + memcpy(alpn_protos + len - i, ss->opt.nextProtoNego.data, i); + } else { + /* This seems to be invalid data so we'll send as-is. */ + memcpy(alpn_protos, ss->opt.nextProtoNego.data, len); + } + } + + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2); + if (rv != SECSuccess) { + goto loser; + } + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) { + goto loser; + } + rv = ssl3_ExtAppendHandshakeVariable(ss, alpn_protos, len, 2); + PORT_Free(alpn_protos); + alpn_protos = NULL; + if (rv != SECSuccess) { + goto loser; + } + xtnData->advertised[xtnData->numAdvertised++] = + ssl_app_layer_protocol_xtn; + } + + return extension_length; + +loser: + if (alpn_protos) { + PORT_Free(alpn_protos); + } + return -1; +} + +PRInt32 +ssl3_ServerSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, PRUint32 maxBytes) +{ + PRInt32 extension_length; + + /* 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); + + extension_length = 2 /* extension type */ + 2 /* extension length */ + + 2 /* protocol name list */ + 1 /* name length */ + + xtnData->nextProto.len; + + if (maxBytes < (PRUint32)extension_length) { + return 0; + } + if (append) { + SECStatus rv; + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_app_layer_protocol_xtn, 2); + if (rv != SECSuccess) { + return -1; + } + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) { + return -1; + } + rv = ssl3_ExtAppendHandshakeNumber(ss, xtnData->nextProto.len + 1, 2); + if (rv != SECSuccess) { + return -1; + } + rv = ssl3_ExtAppendHandshakeVariable(ss, xtnData->nextProto.data, + xtnData->nextProto.len, 1); + if (rv != SECSuccess) { + return -1; + } + } + + return extension_length; +} + +SECStatus +ssl3_ServerHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + ssl3HelloExtensionSenderFunc sender; + + PORT_Assert(ss->sec.isServer); + + /* remember that we got this extension. */ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + sender = tls13_ServerSendStatusRequestXtn; + } else { + sender = ssl3_ServerSendStatusRequestXtn; + } + return ssl3_RegisterExtensionSender(ss, xtnData, ex_type, sender); +} + +PRInt32 +ssl3_ServerSendStatusRequestXtn( + const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + const sslServerCert *serverCert = ss->sec.serverCert; + SECStatus rv; + + if (!serverCert->certStatusArray || + !serverCert->certStatusArray->len) { + return 0; + } + + extension_length = 2 + 2; + if (maxBytes < (PRUint32)extension_length) { + return 0; + } + if (append) { + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); + if (rv != SECSuccess) + return -1; + /* length of extension_data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + /* The certificate status data is sent in ssl3_SendCertificateStatus. */ + } + + return extension_length; +} + +/* ssl3_ClientSendStatusRequestXtn builds the status_request extension on the + * client side. See RFC 6066 section 8. */ +PRInt32 +ssl3_ClientSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + + if (!ss->opt.enableOCSPStapling) + return 0; + + /* extension_type (2-bytes) + + * length(extension_data) (2-bytes) + + * status_type (1) + + * responder_id_list length (2) + + * request_extensions length (2) + */ + extension_length = 9; + + if (maxBytes < (PRUint32)extension_length) { + PORT_Assert(0); + return 0; + } + if (append) { + SECStatus rv; + + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + return -1; + rv = ssl3_ExtAppendHandshakeNumber(ss, 1 /* status_type ocsp */, 1); + if (rv != SECSuccess) + return -1; + /* A zero length responder_id_list means that the responders are + * implicitly known to the server. */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + /* 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 = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + + xtnData->advertised[xtnData->numAdvertised++] = ssl_cert_status_xtn; + } + return extension_length; +} + +SECStatus +ssl3_ClientHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + 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++] = ex_type; + return SECSuccess; +} + +/* + * Called from ssl3_SendNewSessionTicket, tls13_SendNewSessionTicket + */ +SECStatus +ssl3_EncodeSessionTicket(sslSocket *ss, + const NewSessionTicket *ticket, + SECItem *ticket_data) +{ + PRUint32 i; + SECStatus rv; + SECItem plaintext; + SECItem plaintext_item = { 0, NULL, 0 }; + SECItem ciphertext = { 0, NULL, 0 }; + PRUint32 ciphertext_length; + SECItem ticket_buf = { 0, NULL, 0 }; + SECItem ticket_tmp = { 0, NULL, 0 }; + SECItem macParam = { 0, NULL, 0 }; + PRBool ms_is_wrapped; + unsigned char wrapped_ms[SSL3_MASTER_SECRET_LENGTH]; + SECItem ms_item = { 0, NULL, 0 }; + PRUint32 padding_length; + PRUint32 ticket_length; + PRUint32 cert_length = 0; + PRUint8 length_buf[4]; + PRUint32 now; + PK11SymKey *aes_key = NULL; + PK11SymKey *mac_key = NULL; + CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; + PK11Context *aes_ctx; + CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; + PK11Context *hmac_ctx = NULL; + unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; + unsigned int computed_mac_length; + unsigned char iv[AES_BLOCK_SIZE]; + SECItem ivItem; + SECItem *srvName = NULL; + PRUint32 srvNameLen = 0; + CK_MECHANISM_TYPE msWrapMech = 0; /* dummy default value, + * must be >= 0 */ + ssl3CipherSpec *spec; + const sslServerCertType *certType; + SECItem alpnSelection = { siBuffer, NULL, 0 }; + + 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)); + + if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { + cert_length = 3 + ss->sec.ci.sid->peerCert->derCert.len; + } + + /* Get IV and encryption keys */ + ivItem.data = iv; + ivItem.len = sizeof(iv); + rv = PK11_GenerateRandom(iv, sizeof(iv)); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_GetSessionTicketKeys(ss, &aes_key, &mac_key); + if (rv != SECSuccess) + goto loser; + + if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_3) { + spec = ss->ssl3.cwSpec; + } else { + spec = ss->ssl3.pwSpec; + } + if (spec->msItem.len && spec->msItem.data) { + /* The master secret is available unwrapped. */ + ms_item.data = spec->msItem.data; + ms_item.len = spec->msItem.len; + ms_is_wrapped = PR_FALSE; + } else { + /* Extract the master secret wrapped. */ + sslSessionID sid; + PORT_Memset(&sid, 0, sizeof(sslSessionID)); + + rv = ssl3_CacheWrappedMasterSecret(ss, &sid, spec, + ss->ssl3.hs.kea_def->authKeyType); + 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; + } + ms_is_wrapped = PR_TRUE; + } + /* Prep to send negotiated name */ + srvName = &ss->sec.ci.sid->u.ssl3.srvName; + if (srvName->data && srvName->len) { + srvNameLen = 2 + srvName->len; /* len bytes + name len */ + } + + if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT && + ss->xtnData.nextProto.data) { + alpnSelection = ss->xtnData.nextProto; + } + + ciphertext_length = + sizeof(PRUint16) /* ticket_version */ + + sizeof(SSL3ProtocolVersion) /* ssl_version */ + + sizeof(ssl3CipherSuite) /* ciphersuite */ + + 1 /* compression */ + + 10 /* cipher spec parameters */ + + 1 /* certType arguments */ + + 1 /* SessionTicket.ms_is_wrapped */ + + 4 /* msWrapMech */ + + 2 /* master_secret.length */ + + ms_item.len /* master_secret */ + + 1 /* client_auth_type */ + + cert_length /* cert */ + + 1 /* server name type */ + + srvNameLen /* name len + length field */ + + 1 /* extendedMasterSecretUsed */ + + sizeof(ticket->ticket_lifetime_hint) /* ticket lifetime hint */ + + sizeof(ticket->flags) /* ticket flags */ + + 1 + alpnSelection.len; /* npn value + length field. */ + padding_length = AES_BLOCK_SIZE - + (ciphertext_length % + AES_BLOCK_SIZE); + ciphertext_length += padding_length; + + if (SECITEM_AllocItem(NULL, &plaintext_item, ciphertext_length) == NULL) + goto loser; + + plaintext = plaintext_item; + + /* ticket_version */ + rv = ssl3_AppendNumberToItem(&plaintext, TLS_EX_SESS_TICKET_VERSION, + sizeof(PRUint16)); + if (rv != SECSuccess) + goto loser; + + /* ssl_version */ + rv = ssl3_AppendNumberToItem(&plaintext, ss->version, + sizeof(SSL3ProtocolVersion)); + if (rv != SECSuccess) + goto loser; + + /* ciphersuite */ + rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.cipher_suite, + sizeof(ssl3CipherSuite)); + if (rv != SECSuccess) + goto loser; + + /* compression */ + rv = ssl3_AppendNumberToItem(&plaintext, ss->ssl3.hs.compression, 1); + if (rv != SECSuccess) + goto loser; + + /* cipher spec parameters */ + rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authType, 1); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.authKeyBits, 4); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaType, 1); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, ss->sec.keaKeyBits, 4); + if (rv != SECSuccess) + goto loser; + + /* certificate type */ + certType = &ss->sec.serverCert->certType; + PORT_Assert(certType->authType == ss->sec.authType); + switch (ss->sec.authType) { + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: + PORT_Assert(certType->namedCurve); + PORT_Assert(certType->namedCurve->keaType == ssl_kea_ecdh); + /* EC curves only use the second of the two bytes. */ + PORT_Assert(certType->namedCurve->name < 256); + rv = ssl3_AppendNumberToItem(&plaintext, + certType->namedCurve->name, 1); + break; + default: + rv = ssl3_AppendNumberToItem(&plaintext, 0, 1); + break; + } + if (rv != SECSuccess) + goto loser; + + /* master_secret */ + rv = ssl3_AppendNumberToItem(&plaintext, ms_is_wrapped, 1); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, msWrapMech, 4); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, ms_item.len, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendToItem(&plaintext, ms_item.data, ms_item.len); + if (rv != SECSuccess) + goto loser; + + /* client_identity */ + if (ss->opt.requestCertificate && ss->sec.ci.sid->peerCert) { + rv = ssl3_AppendNumberToItem(&plaintext, CLIENT_AUTH_CERTIFICATE, 1); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendNumberToItem(&plaintext, + ss->sec.ci.sid->peerCert->derCert.len, 3); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendToItem(&plaintext, + ss->sec.ci.sid->peerCert->derCert.data, + ss->sec.ci.sid->peerCert->derCert.len); + if (rv != SECSuccess) + goto loser; + } else { + rv = ssl3_AppendNumberToItem(&plaintext, 0, 1); + if (rv != SECSuccess) + goto loser; + } + + /* timestamp */ + now = ssl_Time(); + rv = ssl3_AppendNumberToItem(&plaintext, now, + sizeof(ticket->ticket_lifetime_hint)); + if (rv != SECSuccess) + goto loser; + + if (srvNameLen) { + /* Name Type (sni_host_name) */ + rv = ssl3_AppendNumberToItem(&plaintext, srvName->type, 1); + if (rv != SECSuccess) + goto loser; + /* HostName (length and value) */ + rv = ssl3_AppendNumberToItem(&plaintext, srvName->len, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_AppendToItem(&plaintext, srvName->data, srvName->len); + if (rv != SECSuccess) + goto loser; + } else { + /* No Name */ + rv = ssl3_AppendNumberToItem(&plaintext, (char)TLS_STE_NO_SERVER_NAME, 1); + if (rv != SECSuccess) + goto loser; + } + + /* extendedMasterSecretUsed */ + rv = ssl3_AppendNumberToItem( + &plaintext, ss->sec.ci.sid->u.ssl3.keys.extendedMasterSecretUsed, 1); + if (rv != SECSuccess) + goto loser; + + /* Flags */ + rv = ssl3_AppendNumberToItem(&plaintext, ticket->flags, + sizeof(ticket->flags)); + if (rv != SECSuccess) + goto loser; + + /* NPN value. */ + PORT_Assert(alpnSelection.len < 256); + rv = ssl3_AppendNumberToItem(&plaintext, alpnSelection.len, 1); + if (rv != SECSuccess) + goto loser; + if (alpnSelection.len) { + rv = ssl3_AppendToItem(&plaintext, alpnSelection.data, alpnSelection.len); + if (rv != SECSuccess) + goto loser; + } + + PORT_Assert(plaintext.len == padding_length); + for (i = 0; i < padding_length; i++) + plaintext.data[i] = (unsigned char)padding_length; + + if (SECITEM_AllocItem(NULL, &ciphertext, ciphertext_length) == NULL) { + rv = SECFailure; + goto loser; + } + + /* Generate encrypted portion of ticket. */ + PORT_Assert(aes_key); + aes_ctx = PK11_CreateContextBySymKey(cipherMech, CKA_ENCRYPT, aes_key, &ivItem); + if (!aes_ctx) + goto loser; + + rv = PK11_CipherOp(aes_ctx, ciphertext.data, + (int *)&ciphertext.len, ciphertext.len, + plaintext_item.data, plaintext_item.len); + PK11_Finalize(aes_ctx); + PK11_DestroyContext(aes_ctx, PR_TRUE); + if (rv != SECSuccess) + goto loser; + + /* Convert ciphertext length to network order. */ + length_buf[0] = (ciphertext.len >> 8) & 0xff; + length_buf[1] = (ciphertext.len) & 0xff; + + /* Compute MAC. */ + PORT_Assert(mac_key); + hmac_ctx = PK11_CreateContextBySymKey(macMech, CKA_SIGN, mac_key, &macParam); + if (!hmac_ctx) + goto loser; + + rv = PK11_DigestBegin(hmac_ctx); + if (rv != SECSuccess) + goto loser; + rv = PK11_DigestOp(hmac_ctx, key_name, SESS_TICKET_KEY_NAME_LEN); + if (rv != SECSuccess) + goto loser; + rv = PK11_DigestOp(hmac_ctx, iv, sizeof(iv)); + if (rv != SECSuccess) + goto loser; + rv = PK11_DigestOp(hmac_ctx, (unsigned char *)length_buf, 2); + if (rv != SECSuccess) + goto loser; + rv = PK11_DigestOp(hmac_ctx, ciphertext.data, ciphertext.len); + if (rv != SECSuccess) + goto loser; + rv = PK11_DigestFinal(hmac_ctx, computed_mac, + &computed_mac_length, sizeof(computed_mac)); + if (rv != SECSuccess) + goto loser; + + ticket_length = + +SESS_TICKET_KEY_NAME_LEN /* key_name */ + + AES_BLOCK_SIZE /* iv */ + + 2 /* length field for NewSessionTicket.ticket.encrypted_state */ + + ciphertext_length /* encrypted_state */ + + TLS_EX_SESS_TICKET_MAC_LENGTH; /* mac */ + + if (SECITEM_AllocItem(NULL, &ticket_buf, ticket_length) == NULL) { + rv = SECFailure; + goto loser; + } + ticket_tmp = ticket_buf; /* Shallow copy because AppendToItem is + * destructive. */ + + rv = ssl3_AppendToItem(&ticket_tmp, key_name, SESS_TICKET_KEY_NAME_LEN); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_AppendToItem(&ticket_tmp, iv, sizeof(iv)); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_AppendNumberToItem(&ticket_tmp, ciphertext.len, 2); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_AppendToItem(&ticket_tmp, ciphertext.data, ciphertext.len); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_AppendToItem(&ticket_tmp, computed_mac, computed_mac_length); + if (rv != SECSuccess) + goto loser; + + /* Give ownership of memory to caller. */ + *ticket_data = ticket_buf; + ticket_buf.data = NULL; + +loser: + if (hmac_ctx) { + PK11_DestroyContext(hmac_ctx, PR_TRUE); + } + if (plaintext_item.data) { + SECITEM_FreeItem(&plaintext_item, PR_FALSE); + } + if (ciphertext.data) { + SECITEM_FreeItem(&ciphertext, PR_FALSE); + } + if (ticket_buf.data) { + SECITEM_FreeItem(&ticket_buf, PR_FALSE); + } + + return rv; +} + +/* When a client receives a SessionTicket extension a NewSessionTicket + * message is expected during the handshake. + */ +SECStatus +ssl3_ClientHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + if (data->len != 0) { + return SECSuccess; /* Ignore the extension. */ + } + + /* Keep track of negotiated extensions. */ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + return SECSuccess; +} + +/* Generic ticket processing code, common to TLS 1.0-1.2 and + * TLS 1.3. */ +SECStatus +ssl3_ProcessSessionTicketCommon(sslSocket *ss, SECItem *data) +{ + SECStatus rv; + SECItem *decrypted_state = NULL; + SessionTicket *parsed_session_ticket = NULL; + sslSessionID *sid = NULL; + SSL3Statistics *ssl3stats; + PRUint32 i; + SECItem extension_data; + EncryptedSessionTicket enc_session_ticket; + unsigned char computed_mac[TLS_EX_SESS_TICKET_MAC_LENGTH]; + unsigned int computed_mac_length; + PK11SymKey *aes_key = NULL; + PK11SymKey *mac_key = NULL; + PK11Context *hmac_ctx; + CK_MECHANISM_TYPE macMech = CKM_SHA256_HMAC; + PK11Context *aes_ctx; + CK_MECHANISM_TYPE cipherMech = CKM_AES_CBC; + unsigned char *padding; + PRUint32 padding_length; + unsigned char *buffer; + unsigned int buffer_len; + PRInt32 temp; + SECItem cert_item; + PRInt8 nameType = TLS_STE_NO_SERVER_NAME; + SECItem macParam = { siBuffer, NULL, 0 }; + SECItem alpn_item; + SECItem ivItem; + + /* Turn off stateless session resumption if the client sends a + * SessionTicket extension, even if the extension turns out to be + * malformed (ss->sec.ci.sid is non-NULL when doing session + * renegotiation.) + */ + if (ss->sec.ci.sid != NULL) { + ss->sec.uncache(ss->sec.ci.sid); + ssl_FreeSID(ss->sec.ci.sid); + ss->sec.ci.sid = NULL; + } + + extension_data.data = data->data; /* Keep a copy for future use. */ + extension_data.len = data->len; + + if (ssl3_ParseEncryptedSessionTicket(ss, data, &enc_session_ticket) != + SECSuccess) { + return SECSuccess; /* Pretend it isn't there */ + } + + /* Get session ticket keys. */ + rv = ssl3_GetSessionTicketKeys(ss, &aes_key, &mac_key); + if (rv != SECSuccess) { + SSL_DBG(("%d: SSL[%d]: Unable to get/generate session ticket keys.", + SSL_GETPID(), ss->fd)); + goto loser; + } + + /* If the ticket sent by the client was generated under a key different + * from the one we have, bypass ticket processing. + */ + if (PORT_Memcmp(enc_session_ticket.key_name, key_name, + SESS_TICKET_KEY_NAME_LEN) != 0) { + SSL_DBG(("%d: SSL[%d]: Session ticket key_name sent mismatch.", + SSL_GETPID(), ss->fd)); + goto no_ticket; + } + + /* Verify the MAC on the ticket. MAC verification may also + * fail if the MAC key has been recently refreshed. + */ + PORT_Assert(mac_key); + hmac_ctx = PK11_CreateContextBySymKey(macMech, CKA_SIGN, mac_key, &macParam); + if (!hmac_ctx) { + SSL_DBG(("%d: SSL[%d]: Unable to create HMAC context: %d.", + SSL_GETPID(), ss->fd, PORT_GetError())); + goto no_ticket; + } else { + SSL_DBG(("%d: SSL[%d]: Successfully created HMAC context.", + SSL_GETPID(), ss->fd)); + } + rv = PK11_DigestBegin(hmac_ctx); + if (rv != SECSuccess) { + PK11_DestroyContext(hmac_ctx, PR_TRUE); + goto no_ticket; + } + rv = PK11_DigestOp(hmac_ctx, extension_data.data, + extension_data.len - + TLS_EX_SESS_TICKET_MAC_LENGTH); + if (rv != SECSuccess) { + PK11_DestroyContext(hmac_ctx, PR_TRUE); + goto no_ticket; + } + rv = PK11_DigestFinal(hmac_ctx, computed_mac, + &computed_mac_length, sizeof(computed_mac)); + PK11_DestroyContext(hmac_ctx, PR_TRUE); + if (rv != SECSuccess) + goto no_ticket; + + if (NSS_SecureMemcmp(computed_mac, enc_session_ticket.mac, + computed_mac_length) != + 0) { + SSL_DBG(("%d: SSL[%d]: Session ticket MAC mismatch.", + SSL_GETPID(), ss->fd)); + goto no_ticket; + } + + /* We ignore key_name for now. + * This is ok as MAC verification succeeded. + */ + + /* Decrypt the ticket. */ + + /* Plaintext is shorter than the ciphertext due to padding. */ + decrypted_state = SECITEM_AllocItem(NULL, NULL, + enc_session_ticket.encrypted_state.len); + + PORT_Assert(aes_key); + ivItem.data = enc_session_ticket.iv; + ivItem.len = AES_BLOCK_SIZE; + aes_ctx = PK11_CreateContextBySymKey(cipherMech, CKA_DECRYPT, + aes_key, &ivItem); + if (!aes_ctx) { + SSL_DBG(("%d: SSL[%d]: Unable to create AES context.", + SSL_GETPID(), ss->fd)); + goto no_ticket; + } + + rv = PK11_CipherOp(aes_ctx, decrypted_state->data, + (int *)&decrypted_state->len, decrypted_state->len, + enc_session_ticket.encrypted_state.data, + enc_session_ticket.encrypted_state.len); + PK11_Finalize(aes_ctx); + PK11_DestroyContext(aes_ctx, PR_TRUE); + if (rv != SECSuccess) + goto no_ticket; + + /* Check padding. */ + padding_length = + (PRUint32)decrypted_state->data[decrypted_state->len - 1]; + if (padding_length == 0 || padding_length > AES_BLOCK_SIZE) + goto no_ticket; + + padding = &decrypted_state->data[decrypted_state->len - padding_length]; + for (i = 0; i < padding_length; i++, padding++) { + if (padding_length != (PRUint32)*padding) + goto no_ticket; + } + + /* Deserialize session state. */ + buffer = decrypted_state->data; + buffer_len = decrypted_state->len; + + parsed_session_ticket = PORT_ZAlloc(sizeof(SessionTicket)); + if (parsed_session_ticket == NULL) { + rv = SECFailure; + goto loser; + } + + /* Read ticket_version and reject if the version is wrong */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); + if (temp != TLS_EX_SESS_TICKET_VERSION) + goto no_ticket; + + parsed_session_ticket->ticket_version = (SSL3ProtocolVersion)temp; + + /* Read SSLVersion. */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->ssl_version = (SSL3ProtocolVersion)temp; + + /* Read cipher_suite. */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->cipher_suite = (ssl3CipherSuite)temp; + + /* Read compression_method. */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->compression_method = (SSLCompressionMethod)temp; + + /* Read cipher spec parameters. */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->authType = (SSLAuthType)temp; + temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->authKeyBits = (PRUint32)temp; + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->keaType = (SSLKEAType)temp; + temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->keaKeyBits = (PRUint32)temp; + + /* Read certificate slot */ + parsed_session_ticket->certType.authType = parsed_session_ticket->authType; + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + switch (parsed_session_ticket->authType) { + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: { + const sslNamedGroupDef *group = + ssl_LookupNamedGroup((SSLNamedGroup)temp); + if (!group || group->keaType != ssl_kea_ecdh) { + goto no_ticket; + } + parsed_session_ticket->certType.namedCurve = group; + } break; + default: + break; + } + + /* Read wrapped master_secret. */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->ms_is_wrapped = (PRBool)temp; + + temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->msWrapMech = (CK_MECHANISM_TYPE)temp; + + temp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->ms_length = (PRUint16)temp; + if (parsed_session_ticket->ms_length == 0 || /* sanity check MS. */ + parsed_session_ticket->ms_length > + sizeof(parsed_session_ticket->master_secret)) + goto no_ticket; + + /* Allow for the wrapped master secret to be longer. */ + if (buffer_len < parsed_session_ticket->ms_length) + goto no_ticket; + PORT_Memcpy(parsed_session_ticket->master_secret, buffer, + parsed_session_ticket->ms_length); + buffer += parsed_session_ticket->ms_length; + buffer_len -= parsed_session_ticket->ms_length; + + /* Read client_identity */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->client_identity.client_auth_type = + (ClientAuthenticationType)temp; + switch (parsed_session_ticket->client_identity.client_auth_type) { + case CLIENT_AUTH_ANONYMOUS: + break; + case CLIENT_AUTH_CERTIFICATE: + rv = ssl3_ExtConsumeHandshakeVariable(ss, &cert_item, 3, + &buffer, &buffer_len); + if (rv != SECSuccess) + goto no_ticket; + rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->peer_cert, + &cert_item); + if (rv != SECSuccess) + goto no_ticket; + break; + default: + goto no_ticket; + } + /* Read timestamp. */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 4, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + parsed_session_ticket->timestamp = (PRUint32)temp; + + /* Read server name */ + nameType = + ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (nameType != TLS_STE_NO_SERVER_NAME) { + SECItem name_item; + rv = ssl3_ExtConsumeHandshakeVariable(ss, &name_item, 2, &buffer, + &buffer_len); + if (rv != SECSuccess) + goto no_ticket; + rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->srvName, + &name_item); + if (rv != SECSuccess) + goto no_ticket; + parsed_session_ticket->srvName.type = nameType; + } + + /* Read extendedMasterSecretUsed */ + temp = ssl3_ExtConsumeHandshakeNumber(ss, 1, &buffer, &buffer_len); + if (temp < 0) + goto no_ticket; + PORT_Assert(temp == PR_TRUE || temp == PR_FALSE); + parsed_session_ticket->extendedMasterSecretUsed = (PRBool)temp; + + rv = ssl3_ExtConsumeHandshake(ss, &parsed_session_ticket->flags, 4, + &buffer, &buffer_len); + if (rv != SECSuccess) + goto no_ticket; + parsed_session_ticket->flags = PR_ntohl(parsed_session_ticket->flags); + + rv = ssl3_ExtConsumeHandshakeVariable(ss, &alpn_item, 1, &buffer, &buffer_len); + if (rv != SECSuccess) + goto no_ticket; + if (alpn_item.len != 0) { + rv = SECITEM_CopyItem(NULL, &parsed_session_ticket->alpnSelection, + &alpn_item); + if (rv != SECSuccess) + goto no_ticket; + if (alpn_item.len >= 256) + goto no_ticket; + } + + /* Done parsing. Check that all bytes have been consumed. */ + if (buffer_len != padding_length) + goto no_ticket; + + /* Use the ticket if it has not expired, otherwise free the allocated + * memory since the ticket is of no use. + */ + if (parsed_session_ticket->timestamp != 0 && + parsed_session_ticket->timestamp + + TLS_EX_SESS_TICKET_LIFETIME_HINT > + ssl_Time()) { + + sid = ssl3_NewSessionID(ss, PR_TRUE); + if (sid == NULL) { + rv = SECFailure; + goto loser; + } + + /* Copy over parameters. */ + sid->version = parsed_session_ticket->ssl_version; + sid->u.ssl3.cipherSuite = parsed_session_ticket->cipher_suite; + sid->u.ssl3.compression = parsed_session_ticket->compression_method; + sid->authType = parsed_session_ticket->authType; + sid->authKeyBits = parsed_session_ticket->authKeyBits; + sid->keaType = parsed_session_ticket->keaType; + sid->keaKeyBits = parsed_session_ticket->keaKeyBits; + memcpy(&sid->certType, &parsed_session_ticket->certType, + sizeof(sslServerCertType)); + + if (SECITEM_CopyItem(NULL, &sid->u.ssl3.locked.sessionTicket.ticket, + &extension_data) != SECSuccess) + goto no_ticket; + sid->u.ssl3.locked.sessionTicket.flags = parsed_session_ticket->flags; + + if (parsed_session_ticket->ms_length > + sizeof(sid->u.ssl3.keys.wrapped_master_secret)) + goto no_ticket; + PORT_Memcpy(sid->u.ssl3.keys.wrapped_master_secret, + parsed_session_ticket->master_secret, + parsed_session_ticket->ms_length); + sid->u.ssl3.keys.wrapped_master_secret_len = + parsed_session_ticket->ms_length; + sid->u.ssl3.masterWrapMech = parsed_session_ticket->msWrapMech; + sid->u.ssl3.keys.msIsWrapped = + parsed_session_ticket->ms_is_wrapped; + sid->u.ssl3.masterValid = PR_TRUE; + sid->u.ssl3.keys.resumable = PR_TRUE; + sid->u.ssl3.keys.extendedMasterSecretUsed = parsed_session_ticket->extendedMasterSecretUsed; + + /* Copy over client cert from session ticket if there is one. */ + if (parsed_session_ticket->peer_cert.data != NULL) { + if (sid->peerCert != NULL) + CERT_DestroyCertificate(sid->peerCert); + sid->peerCert = CERT_NewTempCertificate(ss->dbHandle, + &parsed_session_ticket->peer_cert, NULL, PR_FALSE, PR_TRUE); + if (sid->peerCert == NULL) { + rv = SECFailure; + goto loser; + } + } + if (parsed_session_ticket->srvName.data != NULL) { + if (sid->u.ssl3.srvName.data) { + SECITEM_FreeItem(&sid->u.ssl3.srvName, PR_FALSE); + } + sid->u.ssl3.srvName = parsed_session_ticket->srvName; + } + if (parsed_session_ticket->alpnSelection.data != NULL) { + sid->u.ssl3.alpnSelection = parsed_session_ticket->alpnSelection; + /* So we don't free below. */ + parsed_session_ticket->alpnSelection.data = NULL; + } + ss->statelessResume = PR_TRUE; + ss->sec.ci.sid = sid; + } + + if (0) { + no_ticket: + SSL_DBG(("%d: SSL[%d]: Session ticket parsing failed.", + SSL_GETPID(), ss->fd)); + ssl3stats = SSL_GetStatistics(); + SSL_AtomicIncrementLong(&ssl3stats->hch_sid_ticket_parse_failures); + } + rv = SECSuccess; + +loser: + /* ss->sec.ci.sid == sid if it did NOT come here via goto statement + * in that case do not free sid + */ + if (sid && (ss->sec.ci.sid != sid)) { + ssl_FreeSID(sid); + sid = NULL; + } + if (decrypted_state != NULL) { + SECITEM_FreeItem(decrypted_state, PR_TRUE); + decrypted_state = NULL; + } + + if (parsed_session_ticket != NULL) { + if (parsed_session_ticket->peer_cert.data) { + SECITEM_FreeItem(&parsed_session_ticket->peer_cert, PR_FALSE); + } + if (parsed_session_ticket->alpnSelection.data) { + SECITEM_FreeItem(&parsed_session_ticket->alpnSelection, PR_FALSE); + } + PORT_ZFree(parsed_session_ticket, sizeof(SessionTicket)); + } + + return rv; +} + +SECStatus +ssl3_ServerHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + + /* 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++] = ex_type; + + /* 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); +} + +/* + * Read bytes. Using this function means the SECItem structure + * cannot be freed. The caller is expected to call this function + * on a shallow copy of the structure. + */ +static SECStatus +ssl3_ConsumeFromItem(SECItem *item, unsigned char **buf, PRUint32 bytes) +{ + if (bytes > item->len) + return SECFailure; + + *buf = item->data; + item->data += bytes; + item->len -= bytes; + return SECSuccess; +} + +/* 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) + */ +PRInt32 +ssl3_SendRenegotiationInfoXtn( + const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 len = 0; + PRInt32 needed; + + /* In draft-ietf-tls-renegotiation-03, 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 || ss->ssl3.hs.sendingSCSV) + return 0; + if (ss->firstHsDone) { + len = ss->sec.isServer ? ss->ssl3.hs.finishedBytes * 2 + : ss->ssl3.hs.finishedBytes; + } + needed = 5 + len; + if (maxBytes < (PRUint32)needed) { + return 0; + } + if (append) { + SECStatus rv; + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_renegotiation_info_xtn, 2); + if (rv != SECSuccess) + return -1; + /* length of extension_data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, len + 1, 2); + if (rv != SECSuccess) + return -1; + /* verify_Data from previous Finished message(s) */ + rv = ssl3_ExtAppendHandshakeVariable(ss, + ss->ssl3.hs.finishedMsgs.data, len, 1); + if (rv != SECSuccess) + return -1; + if (!ss->sec.isServer) { + xtnData->advertised[xtnData->numAdvertised++] = + ssl_renegotiation_info_xtn; + } + } + return needed; +} + +/* This function runs in both the client and server. */ +SECStatus +ssl3_HandleRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data) +{ + SECStatus rv = SECSuccess; + PRUint32 len = 0; + + 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++] = ex_type; + if (ss->sec.isServer) { + /* prepare to send back the appropriate response */ + rv = ssl3_RegisterExtensionSender(ss, xtnData, ex_type, + ssl3_SendRenegotiationInfoXtn); + } + return rv; +} + +PRInt32 +ssl3_ClientSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, PRUint32 maxBytes) +{ + PRUint32 ext_data_len; + PRInt16 i; + SECStatus rv; + + if (!ss) + return 0; + + if (!IS_DTLS(ss) || !ss->ssl3.dtlsSRTPCipherCount) + return 0; /* Not relevant */ + + ext_data_len = 2 + 2 * ss->ssl3.dtlsSRTPCipherCount + 1; + + if (append && maxBytes >= 4 + ext_data_len) { + /* Extension type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); + if (rv != SECSuccess) + return -1; + /* Length of extension data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ext_data_len, 2); + if (rv != SECSuccess) + return -1; + /* Length of the SRTP cipher list */ + rv = ssl3_ExtAppendHandshakeNumber(ss, + 2 * ss->ssl3.dtlsSRTPCipherCount, + 2); + if (rv != SECSuccess) + return -1; + /* The SRTP ciphers */ + for (i = 0; i < ss->ssl3.dtlsSRTPCipherCount; i++) { + rv = ssl3_ExtAppendHandshakeNumber(ss, + ss->ssl3.dtlsSRTPCiphers[i], + 2); + if (rv != SECSuccess) + return -1; + } + /* Empty MKI value */ + ssl3_ExtAppendHandshakeVariable(ss, NULL, 0, 1); + + xtnData->advertised[xtnData->numAdvertised++] = + ssl_use_srtp_xtn; + } + + return 4 + ext_data_len; +} + +PRInt32 +ssl3_ServerSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, PRUint32 maxBytes) +{ + SECStatus rv; + + /* Server side */ + if (!append || maxBytes < 9) { + return 9; + } + + /* Extension type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_use_srtp_xtn, 2); + if (rv != SECSuccess) + return -1; + /* Length of extension data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 5, 2); + if (rv != SECSuccess) + return -1; + /* Length of the SRTP cipher list */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 2, 2); + if (rv != SECSuccess) + return -1; + /* The selected cipher */ + rv = ssl3_ExtAppendHandshakeNumber(ss, xtnData->dtlsSRTPCipherSuite, 2); + if (rv != SECSuccess) + return -1; + /* Empty MKI value */ + ssl3_ExtAppendHandshakeVariable(ss, NULL, 0, 1); + + return 9; +} + +SECStatus +ssl3_ClientHandleUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, 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, PRUint16 ex_type, 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_ServerHandleSigAlgsXtn handles the signature_algorithms extension + * from a client. + * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */ +SECStatus +ssl3_ServerHandleSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, 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->clientSigSchemes) { + PORT_Free(xtnData->clientSigSchemes); + xtnData->clientSigSchemes = NULL; + } + rv = ssl_ParseSignatureSchemes(ss, NULL, + &xtnData->clientSigSchemes, + &xtnData->numClientSigScheme, + &data->data, &data->len); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); + 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++] = ex_type; + return SECSuccess; +} + +/* ssl3_ClientSendSigAlgsXtn sends the signature_algorithm extension for TLS + * 1.2 ClientHellos. */ +PRInt32 +ssl3_ClientSendSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, PRUint32 maxBytes) +{ + PRInt32 extension_length; + PRUint8 buf[MAX_SIGNATURE_SCHEMES * 2]; + PRUint32 len; + SECStatus rv; + + if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_2) { + return 0; + } + + rv = ssl3_EncodeSigAlgs(ss, buf, sizeof(buf), &len); + if (rv != SECSuccess) { + return -1; + } + + extension_length = + 2 /* extension type */ + + 2 /* extension length */ + + 2 /* supported_signature_algorithms length */ + + len; + + if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv; + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_signature_algorithms_xtn, 2); + if (rv != SECSuccess) { + return -1; + } + rv = ssl3_ExtAppendHandshakeNumber(ss, len + 2, 2); + if (rv != SECSuccess) { + return -1; + } + + rv = ssl3_ExtAppendHandshakeVariable(ss, buf, len, 2); + if (rv != SECSuccess) { + return -1; + } + + xtnData->advertised[xtnData->numAdvertised++] = + ssl_signature_algorithms_xtn; + } + + return extension_length; +} + +/* Takes the size of the ClientHello, less the record header, and determines how + * much padding is required. */ +unsigned int +ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength) +{ + unsigned int recordLength = 1 /* handshake message type */ + + 3 /* handshake message length */ + + clientHelloLength; + unsigned int extensionLength; + + if (recordLength < 256 || recordLength >= 512) { + return 0; + } + + extensionLength = 512 - recordLength; + /* Extensions take at least four bytes to encode. Always include at least + * one byte of data if including the extension. 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. */ + if (extensionLength < 4 + 1) { + extensionLength = 4 + 1; + } + + return extensionLength; +} + +/* ssl3_AppendPaddingExtension 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. */ +PRInt32 +ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen, + PRUint32 maxBytes) +{ + unsigned int paddingLen = extensionLen - 4; + static unsigned char padding[252]; + + if (extensionLen == 0) { + return 0; + } + + if (extensionLen > maxBytes || + !paddingLen || + paddingLen > sizeof(padding)) { + PORT_Assert(0); + return -1; + } + + if (SECSuccess != ssl3_ExtAppendHandshakeNumber(ss, ssl_padding_xtn, 2)) + return -1; + if (SECSuccess != ssl3_ExtAppendHandshakeVariable(ss, padding, paddingLen, 2)) + return -1; + + return extensionLen; +} + +PRInt32 +ssl3_SendExtendedMasterSecretXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + + if (!ss->opt.enableExtendedMS) { + return 0; + } + + /* 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. */ + extension_length = 4; /* Type + length (0) */ + if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv; + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_extended_master_secret_xtn, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + goto loser; + xtnData->advertised[xtnData->numAdvertised++] = + ssl_extended_master_secret_xtn; + } + + return extension_length; + +loser: + return -1; +} + +SECStatus +ssl3_HandleExtendedMasterSecretXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + 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)); + 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++] = ex_type; + + if (ss->sec.isServer) { + return ssl3_RegisterExtensionSender( + ss, xtnData, ex_type, ssl3_SendExtendedMasterSecretXtn); + } + return SECSuccess; +} + +/* ssl3_ClientSendSignedCertTimestampXtn sends the signed_certificate_timestamp + * extension for TLS ClientHellos. */ +PRInt32 +ssl3_ClientSendSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length = 2 /* extension_type */ + + 2 /* length(extension_data) */; + + /* Only send the extension if processing is enabled. */ + if (!ss->opt.enableSignedCertTimestamps) + return 0; + + if (append && maxBytes >= extension_length) { + SECStatus rv; + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, + ssl_signed_cert_timestamp_xtn, + 2); + if (rv != SECSuccess) + goto loser; + /* zero length */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + goto loser; + xtnData->advertised[xtnData->numAdvertised++] = + ssl_signed_cert_timestamp_xtn; + } else if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + + return extension_length; +loser: + return -1; +} + +SECStatus +ssl3_ClientHandleSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + 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++] = ex_type; + return SECSuccess; +} + +PRInt32 +ssl3_ServerSendSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + const SECItem *scts = &ss->sec.serverCert->signedCertTimestamps; + + if (!scts->len) { + /* No timestamps to send */ + return 0; + } + + extension_length = 2 /* extension_type */ + + 2 /* length(extension_data) */ + + scts->len; + + if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + if (append) { + SECStatus rv; + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, + ssl_signed_cert_timestamp_xtn, + 2); + if (rv != SECSuccess) { + return -1; + } + /* extension_data */ + rv = ssl3_ExtAppendHandshakeVariable(ss, scts->data, scts->len, 2); + if (rv != SECSuccess) { + return -1; + } + } + + return extension_length; +} + +SECStatus +ssl3_ServerHandleSignedCertTimestampXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data) +{ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + PORT_Assert(ss->sec.isServer); + return ssl3_RegisterExtensionSender( + ss, xtnData, ex_type, 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, + PRUint16 ex_type, + SECItem *data) +{ + int i; + + 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 */ + SECStatus rv; + rv = ssl3_RegisterExtensionSender(ss, xtnData, ex_type, + &ssl3_SendSupportedPointFormatsXtn); + return rv; + } + } + + /* Poor client doesn't support uncompressed points. */ + PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); + return SECFailure; +} + +static SECStatus +ssl_UpdateSupportedGroups(sslSocket *ss, SECItem *data) +{ + PRInt32 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 */ + list_len = ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (list_len < 0 || 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; + PRInt32 curve_name = + ssl3_ConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (curve_name < 0) { + 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, + PRUint16 ex_type, 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, ex_type, + &ssl_SendSupportedGroupsXtn); + if (rv != SECSuccess) { + return SECFailure; /* error already set. */ + } + } + + /* Remember that we negotiated this extension. */ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + return SECSuccess; +} diff --git a/nss/lib/ssl/ssl3exthandle.h b/nss/lib/ssl/ssl3exthandle.h new file mode 100644 index 0000000..65223d6 --- /dev/null +++ b/nss/lib/ssl/ssl3exthandle.h @@ -0,0 +1,95 @@ +/* -*- 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_ + +PRInt32 ssl3_SendRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +SECStatus ssl3_HandleRenegotiationInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ClientHandleNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ClientHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ServerHandleNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ServerHandleAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +PRInt32 ssl3_ClientSendNextProtoNegoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +PRInt32 ssl3_ClientSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +PRInt32 ssl3_ServerSendAppProtoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +PRInt32 ssl3_ClientSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +PRInt32 ssl3_ServerSendUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +SECStatus ssl3_ClientHandleUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +SECStatus ssl3_ServerHandleUseSRTPXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +PRInt32 ssl3_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +SECStatus ssl3_ServerHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ClientHandleStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +PRInt32 ssl3_ClientSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +PRInt32 ssl3_ClientSendSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +SECStatus ssl3_ServerHandleSigAlgsXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); + +PRInt32 ssl3_ClientSendSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +SECStatus ssl3_ClientHandleSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +PRInt32 ssl3_ServerSendSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +SECStatus ssl3_ServerHandleSignedCertTimestampXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +PRInt32 ssl3_SendExtendedMasterSecretXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +SECStatus ssl3_HandleExtendedMasterSecretXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +SECStatus ssl3_ProcessSessionTicketCommon(sslSocket *ss, SECItem *data); +PRInt32 ssl3_SendServerNameXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +SECStatus ssl3_HandleServerNameXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl_HandleSupportedGroupsXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_HandleSupportedPointFormatsXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ClientHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +SECStatus ssl3_ServerHandleSessionTicketXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +PRInt32 ssl3_SendSessionTicketXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); + +PRInt32 ssl_SendSupportedGroupsXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +PRInt32 ssl3_SendSupportedPointFormatsXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +#endif diff --git a/nss/lib/ssl/ssl3gthr.c b/nss/lib/ssl/ssl3gthr.c index 23b9755..2bcc1d0 100644 --- a/nss/lib/ssl/ssl3gthr.c +++ b/nss/lib/ssl/ssl3gthr.c @@ -1,5 +1,5 @@ /* - * Gather (Read) entire SSL3 records from socket into buffer. + * 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 @@ -8,17 +8,70 @@ #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) +{ + SECStatus status; + + gs->state = GS_INIT; + gs->writeOffset = 0; + gs->readOffset = 0; + gs->dtlsPacketOffset = 0; + gs->dtlsPacket.len = 0; + status = sslBuffer_Grow(&gs->buf, 4096); + return status; +} + +/* 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] >= content_change_cipher_spec && + buf[0] <= content_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. + * 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) + * 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. * @@ -28,108 +81,147 @@ * * This loop returns when either * (a) an error or EOF occurs, - * (b) PR_WOULD_BLOCK_ERROR, - * (c) data (entire SSL3 record) has been received. + * (b) PR_WOULD_BLOCK_ERROR, + * (c) data (entire SSL3 record) has been received. */ static int -ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags) +ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags, ssl2Gather *ssl2gs) { unsigned char *bp; unsigned char *lbp; - int nb; - int err; - int rv = 1; + int nb; + int err; + int rv = 1; + PRUint8 v2HdrLength = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + 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; + gs->state = GS_HEADER; + gs->remainder = ss->ssl3.hs.shortHeaders ? 2 : 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: - /* - ** Have received SSL3 record header in gs->hdr. - ** Now extract the length of the following encrypted data, - ** and then read in the rest of the SSL3 record into gs->inbuf. - */ - gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4]; - - /* This is the max fragment length for an encrypted fragment - ** plus the size of the record header. - */ - if(gs->remainder > (MAX_FRAGMENT_LENGTH + 2048 + 5)) { - SSL3_SendAlert(ss, alert_fatal, unexpected_message); - 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; - } - break; /* End this case. Continue around the loop. */ - - - case GS_DATA: - /* - ** SSL3 record has been completely received. - */ - gs->state = GS_INIT; - return 1; - } + 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. */ + if (!ssl2gs || 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. */ + if (ss->ssl3.hs.shortHeaders) { + PRUint16 len = (gs->hdr[0] << 8) | gs->hdr[1]; + if (!(len & 0x8000)) { + SSL_DBG(("%d: SSL3[%d]: incorrectly formatted header")); + SSL3_SendAlert(ss, alert_fatal, illegal_parameter); + gs->state = GS_INIT; + PORT_SetError(SSL_ERROR_BAD_MAC_READ); + return SECFailure; + } + gs->remainder = len & ~0x8000; + } else { + gs->remainder = (gs->hdr[3] << 8) | gs->hdr[4]; + } + } 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++; + } + } + + /* This is the max length for an encrypted SSLv3+ fragment. */ + if (!v2HdrLength && + gs->remainder > (MAX_FRAGMENT_LENGTH + 2048)) { + SSL3_SendAlert(ss, alert_fatal, unexpected_message); + 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) { + gs->inbuf.len = 5 - v2HdrLength; + PORT_Memcpy(lbp, gs->hdr + v2HdrLength, gs->inbuf.len); + gs->remainder -= gs->inbuf.len; + lbp += gs->inbuf.len; + } + + break; /* End this case. Continue around the loop. */ + + 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)); + gs->state = GS_INIT; + return 1; + } } return rv; @@ -139,7 +231,7 @@ ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags) * Read in an entire DTLS record. * * Blocks here for blocking sockets, otherwise returns -1 with - * PR_WOULD_BLOCK_ERROR when socket would block. + * 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. @@ -147,43 +239,43 @@ ssl3_GatherData(sslSocket *ss, sslGather *gs, int flags) * 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) + * (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. + * (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; - int err; - int rv = 1; + int nb; + int err; + int rv = 1; SSL_TRC(30, ("dtls_GatherData")); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); gs->state = GS_HEADER; gs->offset = 0; - if (gs->dtlsPacketOffset == gs->dtlsPacket.len) { /* No data left */ + 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 is the max fragment length for an encrypted fragment - ** plus the size of the record header. - ** This magic constant is copied from ssl3_GatherData, with 5 changed - ** to 13 (the size of the record header). - */ + /* This is the max fragment length for an encrypted fragment + ** plus the size of the record header. + ** This magic constant is copied from ssl3_GatherData, with 5 changed + ** to 13 (the size of the record header). + */ if (gs->dtlsPacket.space < MAX_FRAGMENT_LENGTH + 2048 + 13) { err = sslBuffer_Grow(&gs->dtlsPacket, - MAX_FRAGMENT_LENGTH + 2048 + 13); - if (err) { /* realloc has set error code to no mem. */ + MAX_FRAGMENT_LENGTH + 2048 + 13); + if (err) { /* realloc has set error code to no mem. */ return err; } } @@ -213,7 +305,8 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) */ if ((gs->dtlsPacket.len - gs->dtlsPacketOffset) < 13) { SSL_DBG(("%d: SSL3[%d]: rest of DTLS packet " - "too short to contain header", SSL_GETPID(), ss->fd)); + "too short to contain header", + SSL_GETPID(), ss->fd)); PR_SetError(PR_WOULD_BLOCK_ERROR, 0); gs->dtlsPacketOffset = 0; gs->dtlsPacket.len = 0; @@ -228,7 +321,8 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) 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)); + "to contain rest of body", + SSL_GETPID(), ss->fd)); PR_SetError(PR_WOULD_BLOCK_ERROR, 0); gs->dtlsPacketOffset = 0; gs->dtlsPacket.len = 0; @@ -238,14 +332,14 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) /* OK, we have at least one complete packet, copy into inbuf */ 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; - } + err = sslBuffer_Grow(&gs->inbuf, gs->remainder); + if (err) { /* realloc has set error code to no mem. */ + return err; + } } memcpy(gs->inbuf.buf, gs->dtlsPacket.buf + gs->dtlsPacketOffset, - gs->remainder); + gs->remainder); gs->inbuf.len = gs->remainder; gs->offset = gs->remainder; gs->dtlsPacketOffset += gs->remainder; @@ -255,16 +349,16 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) } /* Gather in a record and when complete, Handle that record. - * Repeat this until the handshake is complete, + * Repeat this until the handshake is complete, * or until application data is available. * - * Returns 1 when the handshake is completed without error, or + * 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. * Returns -2 on SECWouldBlock return from ssl3_HandleRecord. * - * Called from ssl_GatherRecord1stHandshake in sslcon.c, + * Called from ssl_GatherRecord1stHandshake in sslcon.c, * and from SSL_ForceHandshake in sslsecur.c * and from ssl3_GatherAppDataRecord below (<- DoRecv in sslsecur.c). * @@ -273,9 +367,9 @@ dtls_GatherData(sslSocket *ss, sslGather *gs, int flags) int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags) { + int rv; SSL3Ciphertext cText; - int rv; - PRBool keepGoing = PR_TRUE; + PRBool keepGoing = PR_TRUE; SSL_TRC(30, ("ssl3_GatherCompleteHandshake")); @@ -283,145 +377,169 @@ ssl3_GatherCompleteHandshake(sslSocket *ss, int flags) * 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) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); do { - PRBool handleRecordNow = PR_FALSE; - - ssl_GetSSL3HandshakeLock(ss); - - /* 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 (int) SECFailure; - } - - /* Treat an empty msgState like a NULL msgState. (Most of the time - * when ssl3_HandleHandshake returns SECWouldBlock, it leaves - * behind a non-NULL but zero-length msgState). - * Test: async_cert_restart_server_sends_hello_request_first_in_separate_record - */ - if (ss->ssl3.hs.msgState.buf) { - if (ss->ssl3.hs.msgState.len == 0) { - ss->ssl3.hs.msgState.buf = NULL; - } else { - handleRecordNow = PR_TRUE; - } - } - - ssl_ReleaseSSL3HandshakeLock(ss); - - if (handleRecordNow) { - /* ssl3_HandleHandshake previously returned SECWouldBlock and the - * as-yet-unprocessed plaintext of that previous handshake record. - * We need to process it now before we overwrite it with the next - * handshake record. - */ - rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf); - } else { - /* 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)) { - rv = ssl3_GatherData(ss, &ss->gs, flags); - } 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)) { - ssl_GetSSL3HandshakeLock(ss); - dtls_CheckTimer(ss); - ssl_ReleaseSSL3HandshakeLock(ss); - /* Restore the error in case something succeeded */ - PORT_SetError(PR_WOULD_BLOCK_ERROR); - } - } - - if (rv <= 0) { - return rv; - } - - /* 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.type = (SSL3ContentType)ss->gs.hdr[0]; - cText.version = (ss->gs.hdr[1] << 8) | ss->gs.hdr[2]; - - if (IS_DTLS(ss)) { - int i; - - cText.version = dtls_DTLSVersionToTLSVersion(cText.version); - /* DTLS sequence number */ - cText.seq_num.high = 0; cText.seq_num.low = 0; - for (i = 0; i < 4; i++) { - cText.seq_num.high <<= 8; cText.seq_num.low <<= 8; - cText.seq_num.high |= ss->gs.hdr[3 + i]; - cText.seq_num.low |= ss->gs.hdr[7 + i]; - } - } - - cText.buf = &ss->gs.inbuf; - rv = ssl3_HandleRecord(ss, &cText, &ss->gs.buf); - } - 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); - PORT_Assert(cText.type == content_application_data); - 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_WaitingForStartOfServerSecondRound(ss)) { - keepGoing = PR_FALSE; - } else { - ss->ssl3.hs.canFalseStart = PR_FALSE; - } - } - ssl_ReleaseSSL3HandshakeLock(ss); + PRBool handleRecordNow = PR_FALSE; + + ssl_GetSSL3HandshakeLock(ss); + + /* 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 (int)SECFailure; + } + + /* Treat an empty msgState like a NULL msgState. (Most of the time + * when ssl3_HandleHandshake returns SECWouldBlock, it leaves + * behind a non-NULL but zero-length msgState). + * Test: async_cert_restart_server_sends_hello_request_first_in_separate_record + */ + if (ss->ssl3.hs.msgState.buf) { + if (ss->ssl3.hs.msgState.len == 0) { + ss->ssl3.hs.msgState.buf = NULL; + } else { + handleRecordNow = PR_TRUE; + } + } + + ssl_ReleaseSSL3HandshakeLock(ss); + + if (handleRecordNow) { + /* ssl3_HandleHandshake previously returned SECWouldBlock and the + * as-yet-unprocessed plaintext of that previous handshake record. + * We need to process it now before we overwrite it with the next + * handshake record. + */ + rv = ssl3_HandleRecord(ss, NULL, &ss->gs.buf); + } else { + /* 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->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. + */ + if (ss->ssl3.hs.shortHeaders) { + cText.type = content_application_data; + cText.version = SSL_LIBRARY_VERSION_TLS_1_0; + } else { + cText.type = (SSL3ContentType)ss->gs.hdr[0]; + cText.version = (ss->gs.hdr[1] << 8) | ss->gs.hdr[2]; + } + + if (IS_DTLS(ss)) { + sslSequenceNumber seq_num; + + cText.version = dtls_DTLSVersionToTLSVersion(cText.version); + /* DTLS sequence number */ + PORT_Memcpy(&seq_num, &ss->gs.hdr[3], sizeof(seq_num)); + cText.seq_num = PR_ntohll(seq_num); + } + + cText.buf = &ss->gs.inbuf; + rv = ssl3_HandleRecord(ss, &cText, &ss->gs.buf); + } + } + 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); + PORT_Assert(cText.type == content_application_data); + 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; + } + } + ssl_ReleaseSSL3HandshakeLock(ss); } while (keepGoing); + /* Service the DTLS timer so that the holddown timer eventually fires. */ + if (IS_DTLS(ss)) { + dtls_CheckTimer(ss); + } ss->gs.readOffset = 0; ss->gs.writeOffset = ss->gs.buf.len; return 1; @@ -441,14 +559,14 @@ ssl3_GatherCompleteHandshake(sslSocket *ss, int flags) int ssl3_GatherAppDataRecord(sslSocket *ss, int flags) { - int rv; + 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) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); do { - rv = ssl3_GatherCompleteHandshake(ss, flags); + rv = ssl3_GatherCompleteHandshake(ss, flags); } while (rv > 0 && ss->gs.buf.len == 0); return rv; diff --git a/nss/lib/ssl/ssl3prot.h b/nss/lib/ssl/ssl3prot.h index a93bef1..146cba4 100644 --- a/nss/lib/ssl/ssl3prot.h +++ b/nss/lib/ssl/ssl3prot.h @@ -1,3 +1,4 @@ +/* -*- 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. @@ -17,57 +18,58 @@ typedef PRUint16 SSL3ProtocolVersion; /* The TLS 1.3 draft version. Used to avoid negotiating * between incompatible pre-standard TLS 1.3 drafts. * TODO(ekr@rtfm.com): Remove when TLS 1.3 is published. */ -#define TLS_1_3_DRAFT_VERSION 3 +#define TLS_1_3_DRAFT_VERSION 18 typedef PRUint16 ssl3CipherSuite; /* The cipher suites are defined in sslproto.h */ -#define MAX_CERT_TYPES 10 -#define MAX_COMPRESSION_METHODS 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 MAX_CERT_TYPES 10 +#define MAX_COMPRESSION_METHODS 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 +#define SSL3_RECORD_HEADER_LENGTH 5 +#define TLS13_RECORD_HEADER_LENGTH_SHORT 2 /* SSL3_RECORD_HEADER_LENGTH + epoch/sequence_number */ -#define DTLS_RECORD_HEADER_LENGTH 13 +#define DTLS_RECORD_HEADER_LENGTH 13 -#define MAX_FRAGMENT_LENGTH 16384 +#define MAX_FRAGMENT_LENGTH 16384 typedef enum { content_change_cipher_spec = 20, - content_alert = 21, - content_handshake = 22, - content_application_data = 23 + content_alert = 21, + content_handshake = 22, + content_application_data = 23 } SSL3ContentType; typedef struct { - SSL3ContentType type; + SSL3ContentType type; SSL3ProtocolVersion version; - PRUint16 length; - SECItem fragment; + PRUint16 length; + SECItem fragment; } SSL3Plaintext; typedef struct { - SSL3ContentType type; + SSL3ContentType type; SSL3ProtocolVersion version; - PRUint16 length; - SECItem fragment; + PRUint16 length; + SECItem fragment; } SSL3Compressed; typedef struct { - SECItem content; + SECItem content; SSL3Opaque MAC[MAX_MAC_LENGTH]; } SSL3GenericStreamCipher; typedef struct { - SECItem content; + SECItem content; SSL3Opaque MAC[MAX_MAC_LENGTH]; - PRUint8 padding[MAX_PADDING_LENGTH]; - PRUint8 padding_length; + PRUint8 padding[MAX_PADDING_LENGTH]; + PRUint8 padding_length; } SSL3GenericBlockCipher; typedef enum { change_cipher_spec_choice = 1 } SSL3ChangeCipherSpecChoice; @@ -76,67 +78,74 @@ typedef struct { SSL3ChangeCipherSpecChoice choice; } SSL3ChangeCipherSpec; -typedef enum { alert_warning = 1, alert_fatal = 2 } SSL3AlertLevel; +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, + close_notify = 0, + end_of_early_data = 1, /* TLS 1.3 */ + 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 */ - unsupported_extension = 110, - certificate_unobtainable = 111, - unrecognized_name = 112, + 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, - no_application_protocol = 120 + bad_certificate_hash_value = 114, + no_application_protocol = 120, + /* invalid alert */ + no_alert = 256 } SSL3AlertDescription; typedef struct { - SSL3AlertLevel level; + SSL3AlertLevel level; SSL3AlertDescription description; } SSL3Alert; typedef enum { - hello_request = 0, - client_hello = 1, - server_hello = 2, + hello_request = 0, + client_hello = 1, + server_hello = 2, hello_verify_request = 3, - new_session_ticket = 4, - certificate = 11, + new_session_ticket = 4, + hello_retry_request = 6, + encrypted_extensions = 8, + certificate = 11, server_key_exchange = 12, certificate_request = 13, - server_hello_done = 14, - certificate_verify = 15, + server_hello_done = 14, + certificate_verify = 15, client_key_exchange = 16, - finished = 20, - certificate_status = 22, - next_proto = 67 + finished = 20, + certificate_status = 22, + next_proto = 67 } SSL3HandshakeType; typedef struct { @@ -153,20 +162,20 @@ typedef struct { } SSL3SessionID; typedef struct { - SSL3ProtocolVersion client_version; - SSL3Random random; - SSL3SessionID session_id; - SECItem cipher_suites; - PRUint8 cm_count; - SSLCompressionMethod compression_methods[MAX_COMPRESSION_METHODS]; + SSL3ProtocolVersion client_version; + SSL3Random random; + SSL3SessionID session_id; + SECItem cipher_suites; + PRUint8 cm_count; + SSLCompressionMethod compression_methods[MAX_COMPRESSION_METHODS]; } SSL3ClientHello; -typedef struct { - SSL3ProtocolVersion server_version; - SSL3Random random; - SSL3SessionID session_id; - ssl3CipherSuite cipher_suite; - SSLCompressionMethod compression_method; +typedef struct { + SSL3ProtocolVersion server_version; + SSL3Random random; + SSL3SessionID session_id; + ssl3CipherSuite cipher_suite; + SSLCompressionMethod compression_method; } SSL3ServerHello; typedef struct { @@ -179,24 +188,19 @@ typedef struct { typedef enum { kea_null, kea_rsa, - kea_rsa_export, - kea_rsa_export_1024, kea_dh_dss, - kea_dh_dss_export, kea_dh_rsa, - kea_dh_rsa_export, kea_dhe_dss, - kea_dhe_dss_export, kea_dhe_rsa, - kea_dhe_rsa_export, kea_dh_anon, - kea_dh_anon_export, - kea_rsa_fips, kea_ecdh_ecdsa, kea_ecdhe_ecdsa, kea_ecdh_rsa, kea_ecdhe_rsa, - kea_ecdh_anon + kea_ecdh_anon, + kea_ecdhe_psk, + kea_dhe_psk, + kea_tls13_any, } SSL3KeyExchangeAlgorithm; typedef struct { @@ -233,6 +237,7 @@ typedef struct { union { PRUint8 raw[64]; SSL3HashesIndividually s; + SECItem pointer_to_hash_input; } u; } SSL3Hashes; @@ -244,50 +249,25 @@ typedef struct { } SSL3ServerKeyExchange; 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 + 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 SECItem *SSL3DistinquishedName; - typedef struct { SSL3Opaque client_version[2]; SSL3Opaque random[46]; } SSL3RSAPreMasterSecret; -typedef SECItem SSL3EncryptedPreMasterSecret; - - typedef SSL3Opaque SSL3MasterSecret[48]; -typedef enum { implicit, explicit } SSL3PublicValueEncoding; - -typedef struct { - union { - SSL3Opaque implicit; - SECItem explicit; - } dh_public; -} SSL3ClientDiffieHellmanPublic; - -typedef struct { - union { - SSL3EncryptedPreMasterSecret rsa; - SSL3ClientDiffieHellmanPublic diffie_helman; - } exchange_keys; -} SSL3ClientKeyExchange; - -typedef SSL3Hashes SSL3PreSignedCertificateVerify; - -typedef SECItem SSL3CertificateVerify; - typedef enum { sender_client = 0x434c4e54, sender_server = 0x53525652 @@ -309,11 +289,19 @@ typedef struct { typedef struct { PRUint32 received_timestamp; PRUint32 ticket_lifetime_hint; - SECItem ticket; + PRUint32 flags; + PRUint32 ticket_age_add; + PRUint32 max_early_data_size; + SECItem ticket; } NewSessionTicket; typedef enum { - CLIENT_AUTH_ANONYMOUS = 0, + tls13_psk_ke = 0, + tls13_psk_dh_ke = 1 +} TLS13PskKEModes; + +typedef enum { + CLIENT_AUTH_ANONYMOUS = 0, CLIENT_AUTH_CERTIFICATE = 1 } ClientAuthenticationType; @@ -324,10 +312,10 @@ typedef struct { } identity; } ClientIdentity; -#define SESS_TICKET_KEY_NAME_LEN 16 -#define SESS_TICKET_KEY_NAME_PREFIX "NSS!" +#define SESS_TICKET_KEY_NAME_LEN 16 +#define SESS_TICKET_KEY_NAME_PREFIX "NSS!" #define SESS_TICKET_KEY_NAME_PREFIX_LEN 4 -#define SESS_TICKET_KEY_VAR_NAME_LEN 12 +#define SESS_TICKET_KEY_VAR_NAME_LEN 12 typedef struct { unsigned char *key_name; @@ -338,6 +326,6 @@ typedef struct { #define TLS_EX_SESS_TICKET_MAC_LENGTH 32 -#define TLS_STE_NO_SERVER_NAME -1 +#define TLS_STE_NO_SERVER_NAME -1 #endif /* __ssl3proto_h_ */ diff --git a/nss/lib/ssl/sslauth.c b/nss/lib/ssl/sslauth.c index b144336..5b5f672 100644 --- a/nss/lib/ssl/sslauth.c +++ b/nss/lib/ssl/sslauth.c @@ -1,3 +1,4 @@ +/* -*- 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/. */ @@ -17,12 +18,12 @@ SSL_PeerCertificate(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate", - SSL_GETPID(), fd)); - return 0; + 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 CERT_DupCertificate(ss->sec.peerCert); } return 0; } @@ -38,27 +39,27 @@ SSL_PeerCertificateChain(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificateChain", - SSL_GETPID(), fd)); - return NULL; + 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; + PORT_SetError(SSL_ERROR_NO_CERTIFICATE); + return NULL; } chain = CERT_NewCertList(); if (!chain) { - return NULL; + return NULL; } cert = CERT_DupCertificate(ss->sec.peerCert); if (CERT_AddCertToListTail(chain, cert) != SECSuccess) { - goto loser; + goto loser; } for (cur = ss->ssl3.peerCertChain; cur; cur = cur->next) { - cert = CERT_DupCertificate(cur->cert); - if (CERT_AddCertToListTail(chain, cert) != SECSuccess) { - goto loser; - } + cert = CERT_DupCertificate(cur->cert); + if (CERT_AddCertToListTail(chain, cert) != SECSuccess) { + goto loser; + } } return chain; @@ -75,102 +76,101 @@ SSL_LocalCertificate(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in PeerCertificate", - SSL_GETPID(), fd)); - return NULL; + 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); - } + 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) + char **ip, char **sp) { sslSocket *ss; - const char *cipherName; - PRBool isDes = PR_FALSE; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SecurityStatus", - SSL_GETPID(), fd)); - return SECFailure; + 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 (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; + *op = SSL_SECURITY_STATUS_OFF; } if (ss->opt.useSecurity && ss->enoughFirstHsDone) { - if (ss->version < SSL_LIBRARY_VERSION_3_0) { - cipherName = ssl_cipherName[ss->sec.cipherType]; - } else { - cipherName = ssl3_cipherName[ss->sec.cipherType]; - } - PORT_Assert(cipherName); - if (cipherName) { - if (PORT_Strstr(cipherName, "DES")) isDes = PR_TRUE; - - if (cp) { - *cp = PORT_Strdup(cipherName); + 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 (kp0) { - *kp0 = ss->sec.keyBits; - if (isDes) *kp0 = (*kp0 * 7) / 8; - } - if (kp1) { - *kp1 = ss->sec.secretKeyBits; - if (isDes) *kp1 = (*kp1 * 7) / 8; - } - if (op) { - if (ss->sec.keyBits == 0) { - *op = SSL_SECURITY_STATUS_OFF; - } else if (ss->sec.secretKeyBits < 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"); - } - } - } + 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; @@ -186,9 +186,9 @@ SSL_AuthCertificateHook(PRFileDesc *s, SSLAuthCertificate func, void *arg) ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in AuthCertificateHook", - SSL_GETPID(), s)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in AuthCertificateHook", + SSL_GETPID(), s)); + return SECFailure; } ss->authCertificate = func; @@ -198,17 +198,17 @@ SSL_AuthCertificateHook(PRFileDesc *s, SSLAuthCertificate func, void *arg) } /* NEED LOCKS IN HERE. */ -SECStatus +SECStatus SSL_GetClientAuthDataHook(PRFileDesc *s, SSLGetClientAuthData func, - void *arg) + void *arg) { sslSocket *ss; ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook", - SSL_GETPID(), s)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in GetClientAuthDataHook", + SSL_GETPID(), s)); + return SECFailure; } ss->getClientAuthData = func; @@ -217,77 +217,76 @@ SSL_GetClientAuthDataHook(PRFileDesc *s, SSLGetClientAuthData func, } /* NEED LOCKS IN HERE. */ -SECStatus +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; + 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 +/* 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; - PRTime now = PR_Now(); - SECItemArray * certStatusArray; - + SECStatus rv; + CERTCertDBHandle *handle; + sslSocket *ss; + SECCertUsage certUsage; + const char *hostname = NULL; + PRTime now = PR_Now(); + SECItemArray *certStatusArray; + ss = ssl_FindSocket(fd); PORT_Assert(ss != NULL); if (!ss) { - return SECFailure; + return SECFailure; } handle = (CERTCertDBHandle *)arg; certStatusArray = &ss->sec.ci.sid->peerCertStatus; 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); - } + 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); + now, ss->pkcs11PinArg, NULL); + + if (rv != SECSuccess || isServer) + return rv; - 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; + rv = CERT_VerifyCertName(ss->sec.peerCert, hostname); + else + rv = SECFailure; if (rv != SECSuccess) - PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); + PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN); return rv; } diff --git a/nss/lib/ssl/sslcert.c b/nss/lib/ssl/sslcert.c new file mode 100644 index 0000000..ea52455 --- /dev/null +++ b/nss/lib/ssl/sslcert.c @@ -0,0 +1,992 @@ +/* -*- 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 */ + +static const PRCallOnceType pristineCallOnce; +static PRCallOnceType setupServerCAListOnce; + +static SECStatus +serverCAListShutdown(void *appData, void *nssData) +{ + PORT_Assert(ssl3_server_ca_list); + if (ssl3_server_ca_list) { + CERT_FreeDistNames(ssl3_server_ca_list); + ssl3_server_ca_list = NULL; + } + setupServerCAListOnce = pristineCallOnce; + return SECSuccess; +} + +static PRStatus +serverCAListSetup(void *arg) +{ + CERTCertDBHandle *dbHandle = (CERTCertDBHandle *)arg; + SECStatus rv = NSS_RegisterShutdown(serverCAListShutdown, NULL); + PORT_Assert(SECSuccess == rv); + if (SECSuccess == rv) { + ssl3_server_ca_list = CERT_GetSSLCACerts(dbHandle); + return PR_SUCCESS; + } + return PR_FAILURE; +} + +sslServerCert * +ssl_NewServerCert(const sslServerCertType *certType) +{ + sslServerCert *sc = PORT_ZNew(sslServerCert); + if (!sc) { + return NULL; + } + memcpy(&sc->certType, certType, sizeof(sc->certType)); + sc->serverCert = NULL; + sc->serverCertChain = NULL; + sc->certStatusArray = NULL; + sc->signedCertTimestamps.len = 0; + return sc; +} + +sslServerCert * +ssl_CopyServerCert(const sslServerCert *oc) +{ + sslServerCert *sc; + + sc = ssl_NewServerCert(&oc->certType); + if (!sc) { + return NULL; + } + + 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; + 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); + } + PORT_ZFree(sc, sizeof(*sc)); +} + +sslServerCert * +ssl_FindServerCert(const sslSocket *ss, + const sslServerCertType *certType) +{ + PRCList *cursor; + + for (cursor = PR_NEXT_LINK(&ss->serverCerts); + cursor != &ss->serverCerts; + cursor = PR_NEXT_LINK(cursor)) { + sslServerCert *cert = (sslServerCert *)cursor; + if (cert->certType.authType != certType->authType) { + continue; + } + switch (cert->certType.authType) { + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: + /* Note: For deprecated APIs, we need to be able to find and + match a slot with any named curve. */ + if (certType->namedCurve && + cert->certType.namedCurve != certType->namedCurve) { + continue; + } + break; + default: + break; + } + return cert; + } + return NULL; +} + +sslServerCert * +ssl_FindServerCertByAuthType(const sslSocket *ss, SSLAuthType authType) +{ + sslServerCertType certType; + certType.authType = authType; + /* Setting the named curve to NULL ensures that all EC certificates + * are matched when searching for this slot. */ + certType.namedCurve = NULL; + return ssl_FindServerCert(ss, &certType); +} + +SECStatus +ssl_OneTimeCertSetup(sslSocket *ss, const sslServerCert *sc) +{ + if (PR_SUCCESS != PR_CallOnceWithArg(&setupServerCAListOnce, + &serverCAListSetup, + (void *)(ss->dbHandle))) { + return SECFailure; + } + return SECSuccess; +} + +/* Determine which slot a certificate fits into. SSLAuthType is known, but + * extra information needs to be worked out from the cert and key. */ +static void +ssl_PopulateCertType(sslServerCertType *certType, SSLAuthType authType, + CERTCertificate *cert, sslKeyPair *keyPair) +{ + certType->authType = authType; + switch (authType) { + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: + certType->namedCurve = ssl_ECPubKey2NamedGroup(keyPair->pubKey); + break; + default: + break; + } +} + +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) +{ + /* Copy over the key pair. */ + if (sc->serverKeyPair) { + ssl_FreeKeyPair(sc->serverKeyPair); + } + if (keyPair) { + /* Get the size of the cert's public key, and remember it. */ + sc->serverKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->pubKey); + if (sc->serverKeyBits == 0) { + return SECFailure; + } + + SECKEY_CacheStaticFlags(keyPair->privKey); + sc->serverKeyPair = ssl_GetKeyPairRef(keyPair); + } else { + sc->serverKeyPair = 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; +} + +static SECStatus +ssl_ConfigCert(sslSocket *ss, CERTCertificate *cert, + sslKeyPair *keyPair, const SSLExtraServerCertData *data) +{ + sslServerCert *oldsc; + sslServerCertType certType; + SECStatus rv; + sslServerCert *sc = NULL; + int error_code = SEC_ERROR_NO_MEMORY; + + PORT_Assert(cert); + PORT_Assert(keyPair); + PORT_Assert(data); + PORT_Assert(data->authType != ssl_auth_null); + + if (!cert || !keyPair || !data || data->authType == ssl_auth_null) { + error_code = SEC_ERROR_INVALID_ARGS; + goto loser; + } + + ssl_PopulateCertType(&certType, data->authType, cert, keyPair); + + /* Delete any existing certificate that matches this one, since we can only + * use one certificate of a given type. */ + oldsc = ssl_FindServerCert(ss, &certType); + if (oldsc) { + PR_REMOVE_LINK(&oldsc->link); + ssl_FreeServerCert(oldsc); + } + sc = ssl_NewServerCert(&certType); + if (!sc) { + goto loser; + } + + rv = ssl_PopulateServerCert(sc, cert, data->certChain); + if (rv != SECSuccess) { + goto loser; + } + rv = ssl_PopulateKeyPair(sc, keyPair); + if (rv != SECSuccess) { + error_code = SEC_ERROR_INVALID_ARGS; + goto loser; + } + rv = ssl_PopulateOCSPResponses(sc, data->stapledOCSPResponses); + if (rv != SECSuccess) { + goto loser; + } + rv = ssl_PopulateSignedCertTimestamps(sc, data->signedCertTimestamps); + if (rv != SECSuccess) { + goto loser; + } + PR_APPEND_LINK(&sc->link, &ss->serverCerts); + + /* This one-time setup depends on having the certificate in place. */ + rv = ssl_OneTimeCertSetup(ss, sc); + if (rv != SECSuccess) { + PR_REMOVE_LINK(&sc->link); + error_code = PORT_GetError(); + goto loser; + } + return SECSuccess; + +loser: + if (sc) { + ssl_FreeServerCert(sc); + } + /* This is the only way any of the calls above can fail, except the one time + * setup, which doesn't land here. */ + 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 key usages of the given RSA-PKCS1 certificate + * and configures one or multiple server certificates based on that data. + * + * If the data argument contains an authType value other than ssl_auth_null, + * then only that slot will be used. If that choice is invalid, + * then this will fail. */ +static SECStatus +ssl_ConfigRsaPkcs1CertByUsage(sslSocket *ss, CERTCertificate *cert, + sslKeyPair *keyPair, + SSLExtraServerCertData *data) +{ + SECStatus rv = SECFailure; + + PRBool ku_sig = (PRBool)(cert->keyUsage & KU_DIGITAL_SIGNATURE); + PRBool ku_enc = (PRBool)(cert->keyUsage & KU_KEY_ENCIPHERMENT); + + if ((data->authType == ssl_auth_rsa_sign && ku_sig) || + (data->authType == ssl_auth_rsa_pss && ku_sig) || + (data->authType == ssl_auth_rsa_decrypt && ku_enc)) { + return ssl_ConfigCert(ss, cert, keyPair, data); + } + + if (data->authType != ssl_auth_null || !(ku_sig || ku_enc)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + if (ku_sig) { + data->authType = ssl_auth_rsa_sign; + rv = ssl_ConfigCert(ss, cert, keyPair, data); + if (rv != SECSuccess) { + return rv; + } + + /* This certificate is RSA, assume that it's also PSS. */ + data->authType = ssl_auth_rsa_pss; + rv = ssl_ConfigCert(ss, cert, keyPair, data); + if (rv != SECSuccess) { + return rv; + } + } + + if (ku_enc) { + /* 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. */ + data->authType = ssl_auth_rsa_decrypt; + rv = ssl_ConfigCert(ss, cert, keyPair, data); + if (rv != SECSuccess) { + return rv; + } + } + + return rv; +} + +/* This function examines the type of certificate and its key usage and + * configures a certificate based on that information. For some certificates + * this can mean that multiple server certificates are configured. + * + * If the data argument contains an authType value other than ssl_auth_null, + * then only that slot will be used. If that choice is invalid, + * then this will fail. */ +static SECStatus +ssl_ConfigCertByUsage(sslSocket *ss, CERTCertificate *cert, + sslKeyPair *keyPair, const SSLExtraServerCertData *data) +{ + SECStatus rv = SECFailure; + SSLExtraServerCertData arg; + SECOidTag tag; + + PORT_Assert(data); + /* Take a (shallow) copy so that we can play with it */ + memcpy(&arg, data, sizeof(arg)); + + tag = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm); + switch (tag) { + case SEC_OID_X500_RSA_ENCRYPTION: + case SEC_OID_PKCS1_RSA_ENCRYPTION: + return ssl_ConfigRsaPkcs1CertByUsage(ss, cert, keyPair, &arg); + + case SEC_OID_PKCS1_RSA_PSS_SIGNATURE: + if (cert->keyUsage & KU_DIGITAL_SIGNATURE) { + arg.authType = ssl_auth_rsa_pss; + } + break; + + case SEC_OID_ANSIX9_DSA_SIGNATURE: + if (cert->keyUsage & KU_DIGITAL_SIGNATURE) { + arg.authType = ssl_auth_dsa; + } + break; + + case SEC_OID_ANSIX962_EC_PUBLIC_KEY: + if (cert->keyUsage & KU_KEY_ENCIPHERMENT) { + if ((cert->keyUsage & KU_DIGITAL_SIGNATURE) && + arg.authType == ssl_auth_null) { + /* See above regarding bad practice. */ + arg.authType = ssl_auth_ecdsa; + rv = ssl_ConfigCert(ss, cert, keyPair, &arg); + if (rv != SECSuccess) { + return rv; + } + } + + arg.authType = ssl_GetEcdhAuthType(cert); + } else if (cert->keyUsage & KU_DIGITAL_SIGNATURE) { + arg.authType = ssl_auth_ecdsa; + } + break; + + default: + break; + } + + /* Check that we successfully picked an authType */ + if (arg.authType == ssl_auth_null) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + /* |data->authType| has to either agree or be ssl_auth_null. */ + if (data && data->authType != ssl_auth_null && + data->authType != arg.authType) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + return ssl_ConfigCert(ss, cert, keyPair, &arg); +} + +/* This function adopts pubKey and destroys it if things go wrong. */ +static sslKeyPair * +ssl_MakeKeyPairForCert(SECKEYPrivateKey *key, SECKEYPublicKey *pubKey) +{ + sslKeyPair *keyPair = NULL; + SECKEYPrivateKey *privKeyCopy = NULL; + PK11SlotInfo *bestSlot; + + 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); + } + /* We adopted the public key, so we're responsible. */ + if (pubKey) { + SECKEY_DestroyPublicKey(pubKey); + } + } + return keyPair; +} + +/* Configure a certificate and private key. + * + * This function examines the certificate and key to determine which slot (or + * slots) to place the information in. As long as certificates are different + * (based on having different values of sslServerCertType), then this function + * can be called multiple times and the certificates will all be remembered. + */ +SECStatus +SSL_ConfigServerCert(PRFileDesc *fd, CERTCertificate *cert, + SECKEYPrivateKey *key, + const SSLExtraServerCertData *data, unsigned int data_len) +{ + sslSocket *ss; + SECKEYPublicKey *pubKey; + sslKeyPair *keyPair; + SECStatus rv; + SSLExtraServerCertData dataCopy = { + ssl_auth_null, NULL, NULL, NULL + }; + + 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); + } + + pubKey = CERT_ExtractPublicKey(cert); + if (!pubKey) { + return SECFailure; + } + + keyPair = ssl_MakeKeyPairForCert(key, pubKey); + if (!keyPair) { + /* pubKey is adopted by ssl_MakeKeyPairForCert() */ + PORT_SetError(SEC_ERROR_NO_MEMORY); + return SECFailure; + } + + rv = ssl_ConfigCertByUsage(ss, cert, keyPair, &dataCopy); + ssl_FreeKeyPair(keyPair); + return rv; +} + +/*******************************************************************/ +/* 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, SSLAuthType authType) +{ + SECOidTag tag = SECOID_GetAlgorithmTag(&cert->subjectPublicKeyInfo.algorithm); + switch (authType) { + case ssl_auth_rsa_decrypt: + case ssl_auth_rsa_sign: + return tag == SEC_OID_X500_RSA_ENCRYPTION || + tag == SEC_OID_PKCS1_RSA_ENCRYPTION; + case ssl_auth_dsa: + return tag == SEC_OID_ANSIX9_DSA_SIGNATURE; + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: + return tag == SEC_OID_ANSIX962_EC_PUBLIC_KEY; + case ssl_auth_null: + case ssl_auth_kea: + case ssl_auth_rsa_pss: /* not supported with deprecated APIs */ + return PR_FALSE; + default: + PORT_Assert(0); + return PR_FALSE; + } +} + +/* This finds an existing server cert slot and unlinks it, or it makes a new + * server cert slot of the right type. */ +static sslServerCert * +ssl_FindOrMakeCertType(sslSocket *ss, SSLAuthType authType) +{ + sslServerCert *sc; + sslServerCertType certType; + + certType.authType = authType; + /* Setting the named curve to NULL ensures that all EC certificates + * are matched when searching for this slot. */ + certType.namedCurve = NULL; + sc = ssl_FindServerCert(ss, &certType); + if (sc) { + PR_REMOVE_LINK(&sc->link); + return sc; + } + + return ssl_NewServerCert(&certType); +} + +static void +ssl_RemoveCertAndKeyByAuthType(sslSocket *ss, SSLAuthType authType) +{ + sslServerCert *sc; + + sc = ssl_FindServerCertByAuthType(ss, authType); + 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. */ + /* For ECC certificates, also leave the namedCurve parameter on the slot + * unchanged; the value will be updated when a key is added. */ + } +} + +static SECStatus +ssl_AddCertAndKeyByAuthType(sslSocket *ss, SSLAuthType authType, + CERTCertificate *cert, + const CERTCertificateList *certChainOpt, + sslKeyPair *keyPair) +{ + sslServerCert *sc; + SECStatus rv; + + if (!ssl_CertSuitableForAuthType(cert, authType)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + sc = ssl_FindOrMakeCertType(ss, authType); + if (!sc) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + return SECFailure; + } + rv = ssl_PopulateKeyPair(sc, keyPair); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + goto loser; + } + /* Now that we have a key pair, update the details of the slot. Many of the + * legacy functions create a slot with a namedCurve of NULL, which + * makes the slot unusable; this corrects that. */ + ssl_PopulateCertType(&sc->certType, authType, cert, keyPair); + rv = ssl_PopulateServerCert(sc, cert, certChainOpt); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + goto loser; + } + PR_APPEND_LINK(&sc->link, &ss->serverCerts); + return ssl_OneTimeCertSetup(ss, sc); +loser: + ssl_FreeServerCert(sc); + return SECFailure; +} + +static SECStatus +ssl_AddCertsByKEA(sslSocket *ss, CERTCertificate *cert, + const CERTCertificateList *certChainOpt, + SECKEYPrivateKey *key, SSLKEAType certType) +{ + SECKEYPublicKey *pubKey; + sslKeyPair *keyPair; + SECStatus rv; + + pubKey = CERT_ExtractPublicKey(cert); + if (!pubKey) { + return SECFailure; + } + + keyPair = ssl_MakeKeyPairForCert(key, pubKey); + if (!keyPair) { + /* Note: pubKey is adopted or freed by ssl_MakeKeyPairForCert() + * depending on whether it succeeds or not. */ + PORT_SetError(SEC_ERROR_NO_MEMORY); + return SECFailure; + } + + switch (certType) { + case ssl_kea_rsa: + rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_rsa_decrypt, + cert, certChainOpt, keyPair); + if (rv != SECSuccess) { + return SECFailure; + } + rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_rsa_sign, + cert, certChainOpt, keyPair); + break; + + case ssl_kea_dh: + rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_dsa, + cert, certChainOpt, keyPair); + break; + + case ssl_kea_ecdh: + rv = ssl_AddCertAndKeyByAuthType(ss, ssl_auth_ecdsa, + cert, certChainOpt, keyPair); + if (rv != SECSuccess) { + return SECFailure; + } + rv = ssl_AddCertAndKeyByAuthType(ss, ssl_GetEcdhAuthType(cert), + cert, certChainOpt, keyPair); + break; + + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + break; + } + + ssl_FreeKeyPair(keyPair); + return rv; +} + +/* Public deprecated function */ +SECStatus +SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert, + const CERTCertificateList *certChainOpt, + SECKEYPrivateKey *key, SSLKEAType certType) +{ + sslSocket *ss; + + ss = ssl_FindSocket(fd); + if (!ss) { + return SECFailure; + } + + if (!cert != !key) { /* Configure both, or neither */ + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + if (!cert) { + switch (certType) { + case ssl_kea_rsa: + ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_rsa_decrypt); + ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_rsa_sign); + break; + + case ssl_kea_dh: + ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_dsa); + break; + + case ssl_kea_ecdh: + ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_ecdsa); + ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_ecdh_rsa); + ssl_RemoveCertAndKeyByAuthType(ss, ssl_auth_ecdh_ecdsa); + break; + + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + return SECSuccess; + } + + return ssl_AddCertsByKEA(ss, cert, certChainOpt, key, certType); +} + +static SECStatus +ssl_SetOCSPResponsesInSlot(sslSocket *ss, SSLAuthType authType, + const SECItemArray *responses) +{ + sslServerCert *sc; + SECStatus rv; + + sc = ssl_FindOrMakeCertType(ss, authType); + if (!sc) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + 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_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, + SSLKEAType certType) +{ + sslSocket *ss; + SECStatus rv; + + ss = ssl_FindSocket(fd); + if (!ss) { + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetStapledOCSPResponses", + SSL_GETPID(), fd)); + return SECFailure; + } + + switch (certType) { + case ssl_kea_rsa: + rv = ssl_SetOCSPResponsesInSlot(ss, ssl_auth_rsa_decrypt, responses); + if (rv != SECSuccess) { + return SECFailure; + } + return ssl_SetOCSPResponsesInSlot(ss, ssl_auth_rsa_sign, responses); + + case ssl_kea_dh: + return ssl_SetOCSPResponsesInSlot(ss, ssl_auth_dsa, responses); + + case ssl_kea_ecdh: + rv = ssl_SetOCSPResponsesInSlot(ss, ssl_auth_ecdsa, responses); + if (rv != SECSuccess) { + return SECFailure; + } + rv = ssl_SetOCSPResponsesInSlot(ss, ssl_auth_ecdh_rsa, responses); + if (rv != SECSuccess) { + return SECFailure; + } + return ssl_SetOCSPResponsesInSlot(ss, ssl_auth_ecdh_ecdsa, responses); + + default: + SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetStapledOCSPResponses", + SSL_GETPID(), fd)); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } +} + +static SECStatus +ssl_SetSignedTimestampsInSlot(sslSocket *ss, SSLAuthType authType, + const SECItem *scts) +{ + sslServerCert *sc; + SECStatus rv; + + sc = ssl_FindOrMakeCertType(ss, authType); + if (!sc) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + 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 */ +SECStatus +SSL_SetSignedCertTimestamps(PRFileDesc *fd, const SECItem *scts, + SSLKEAType certType) +{ + sslSocket *ss; + SECStatus rv; + + ss = ssl_FindSocket(fd); + if (!ss) { + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSignedCertTimestamps", + SSL_GETPID(), fd)); + return SECFailure; + } + + switch (certType) { + case ssl_kea_rsa: + rv = ssl_SetSignedTimestampsInSlot(ss, ssl_auth_rsa_decrypt, scts); + if (rv != SECSuccess) { + return SECFailure; + } + return ssl_SetSignedTimestampsInSlot(ss, ssl_auth_rsa_sign, scts); + + case ssl_kea_dh: + return ssl_SetSignedTimestampsInSlot(ss, ssl_auth_dsa, scts); + + case ssl_kea_ecdh: + rv = ssl_SetSignedTimestampsInSlot(ss, ssl_auth_ecdsa, scts); + if (rv != SECSuccess) { + return SECFailure; + } + rv = ssl_SetSignedTimestampsInSlot(ss, ssl_auth_ecdh_rsa, scts); + if (rv != SECSuccess) { + return SECFailure; + } + return ssl_SetSignedTimestampsInSlot(ss, ssl_auth_ecdh_ecdsa, scts); + + default: + SSL_DBG(("%d: SSL[%d]: invalid cert type in SSL_SetSignedCertTimestamps", + SSL_GETPID(), fd)); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } +} + +/* 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/nss/lib/ssl/sslcert.h b/nss/lib/ssl/sslcert.h new file mode 100644 index 0000000..052c7d6 --- /dev/null +++ b/nss/lib/ssl/sslcert.h @@ -0,0 +1,59 @@ +/* -*- 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" + +/* The following struct identifies a single slot into which a certificate can be +** loaded. The authType field determines the basic slot, then additional +** parameters further narrow the slot. +** +** An EC key (ssl_auth_ecdsa or ssl_auth_ecdh_*) is assigned to a slot based on +** the named curve of the key. +*/ +typedef struct sslServerCertTypeStr { + SSLAuthType authType; + /* 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; +} sslServerCertType; + +typedef struct sslServerCertStr { + PRCList link; /* The linked list link */ + + sslServerCertType certType; /* The certificate slot this occupies */ + + /* 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; +} sslServerCert; + +extern sslServerCert *ssl_NewServerCert(const sslServerCertType *slot); +extern sslServerCert *ssl_CopyServerCert(const sslServerCert *oc); +extern sslServerCert *ssl_FindServerCert(const sslSocket *ss, + const sslServerCertType *slot); +extern sslServerCert *ssl_FindServerCertByAuthType(const sslSocket *ss, + SSLAuthType authType); +extern void ssl_FreeServerCert(sslServerCert *sc); + +#endif /* __sslcert_h_ */ diff --git a/nss/lib/ssl/sslcon.c b/nss/lib/ssl/sslcon.c index ccd0026..4481706 100644 --- a/nss/lib/ssl/sslcon.c +++ b/nss/lib/ssl/sslcon.c @@ -1,5 +1,5 @@ -/* - * SSL v2 handshake functions, and functions common to SSL2 and SSL3. +/* + * 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 @@ -9,8 +9,8 @@ #include "cert.h" #include "secitem.h" #include "sechash.h" -#include "cryptohi.h" /* for SGN_ funcs */ -#include "keyhi.h" /* for SECKEY_ high level functions. */ +#include "cryptohi.h" /* for SGN_ funcs */ +#include "keyhi.h" /* for SECKEY_ high level functions. */ #include "ssl.h" #include "sslimpl.h" #include "sslproto.h" @@ -18,2965 +18,118 @@ #include "sslerr.h" #include "pk11func.h" #include "prinit.h" -#include "prtime.h" /* for PR_Now() */ - -static PRBool policyWasSet; - -#define ssl2_NUM_SUITES_IMPLEMENTED 6 - -/* This list is sent back to the client when the client-hello message - * contains no overlapping ciphers, so the client can report what ciphers - * are supported by the server. Unlike allCipherSuites (above), this list - * is sorted by descending preference, not by cipherSuite number. - */ -static const PRUint8 implementedCipherSuites[ssl2_NUM_SUITES_IMPLEMENTED * 3] = { - SSL_CK_RC4_128_WITH_MD5, 0x00, 0x80, - SSL_CK_RC2_128_CBC_WITH_MD5, 0x00, 0x80, - SSL_CK_DES_192_EDE3_CBC_WITH_MD5, 0x00, 0xC0, - SSL_CK_DES_64_CBC_WITH_MD5, 0x00, 0x40, - SSL_CK_RC4_128_EXPORT40_WITH_MD5, 0x00, 0x80, - SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5, 0x00, 0x80 -}; - -typedef struct ssl2SpecsStr { - PRUint8 nkm; /* do this many hashes to generate key material. */ - PRUint8 nkd; /* size of readKey and writeKey in bytes. */ - PRUint8 blockSize; - PRUint8 blockShift; - CK_MECHANISM_TYPE mechanism; - PRUint8 keyLen; /* cipher symkey size in bytes. */ - PRUint8 pubLen; /* publicly reveal this many bytes of key. */ - PRUint8 ivLen; /* length of IV data at *ca. */ -} ssl2Specs; - -static const ssl2Specs ssl_Specs[] = { -/* NONE */ - { 0, 0, 0, 0, }, -/* SSL_CK_RC4_128_WITH_MD5 */ - { 2, 16, 1, 0, CKM_RC4, 16, 0, 0, }, -/* SSL_CK_RC4_128_EXPORT40_WITH_MD5 */ - { 2, 16, 1, 0, CKM_RC4, 16, 11, 0, }, -/* SSL_CK_RC2_128_CBC_WITH_MD5 */ - { 2, 16, 8, 3, CKM_RC2_CBC, 16, 0, 8, }, -/* SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 */ - { 2, 16, 8, 3, CKM_RC2_CBC, 16, 11, 8, }, -/* SSL_CK_IDEA_128_CBC_WITH_MD5 */ - { 0, 0, 0, 0, }, -/* SSL_CK_DES_64_CBC_WITH_MD5 */ - { 1, 8, 8, 3, CKM_DES_CBC, 8, 0, 8, }, -/* SSL_CK_DES_192_EDE3_CBC_WITH_MD5 */ - { 3, 24, 8, 3, CKM_DES3_CBC, 24, 0, 8, }, -}; - -#define SET_ERROR_CODE /* reminder */ -#define TEST_FOR_FAILURE /* reminder */ +#include "prtime.h" /* for PR_Now() */ /* ** 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" + " +us" + " +export" #ifdef TRACE - " +trace" + " +trace" #endif #ifdef DEBUG - " +debug" + " +debug" #endif - ; - -const char * const ssl_cipherName[] = { - "unknown", - "RC4", - "RC4-Export", - "RC2-CBC", - "RC2-CBC-Export", - "IDEA-CBC", - "DES-CBC", - "DES-EDE3-CBC", - "unknown", - "unknown", /* was fortezza, NO LONGER USED */ -}; - - -/* bit-masks, showing which SSLv2 suites are allowed. - * lsb corresponds to first cipher suite in allCipherSuites[]. - */ -static PRUint16 allowedByPolicy; /* all off by default */ -static PRUint16 maybeAllowedByPolicy; /* all off by default */ -static PRUint16 chosenPreference = 0xff; /* all on by default */ - -/* bit values for the above two bit masks */ -#define SSL_CB_RC4_128_WITH_MD5 (1 << SSL_CK_RC4_128_WITH_MD5) -#define SSL_CB_RC4_128_EXPORT40_WITH_MD5 (1 << SSL_CK_RC4_128_EXPORT40_WITH_MD5) -#define SSL_CB_RC2_128_CBC_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_WITH_MD5) -#define SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 (1 << SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5) -#define SSL_CB_IDEA_128_CBC_WITH_MD5 (1 << SSL_CK_IDEA_128_CBC_WITH_MD5) -#define SSL_CB_DES_64_CBC_WITH_MD5 (1 << SSL_CK_DES_64_CBC_WITH_MD5) -#define SSL_CB_DES_192_EDE3_CBC_WITH_MD5 (1 << SSL_CK_DES_192_EDE3_CBC_WITH_MD5) -#define SSL_CB_IMPLEMENTED \ - (SSL_CB_RC4_128_WITH_MD5 | \ - SSL_CB_RC4_128_EXPORT40_WITH_MD5 | \ - SSL_CB_RC2_128_CBC_WITH_MD5 | \ - SSL_CB_RC2_128_CBC_EXPORT40_WITH_MD5 | \ - SSL_CB_DES_64_CBC_WITH_MD5 | \ - SSL_CB_DES_192_EDE3_CBC_WITH_MD5) - - -/* Construct a socket's list of cipher specs from the global default values. - */ -static SECStatus -ssl2_ConstructCipherSpecs(sslSocket *ss) -{ - PRUint8 * cs = NULL; - unsigned int allowed; - unsigned int count; - int ssl3_count = 0; - int final_count; - int i; - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - count = 0; - PORT_Assert(ss != 0); - allowed = !ss->opt.enableSSL2 ? 0 : - (ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED); - while (allowed) { - if (allowed & 1) - ++count; - allowed >>= 1; - } - - /* Call ssl3_config_match_init() once here, - * instead of inside ssl3_ConstructV2CipherSpecsHack(), - * because the latter gets called twice below, - * and then again in ssl2_BeginClientHandshake(). - */ - ssl3_config_match_init(ss); - - /* ask SSL3 how many cipher suites it has. */ - rv = ssl3_ConstructV2CipherSpecsHack(ss, NULL, &ssl3_count); - if (rv < 0) - return rv; - count += ssl3_count; - - /* Allocate memory to hold cipher specs */ - if (count > 0) - cs = (PRUint8*) PORT_Alloc(count * 3); - else - PORT_SetError(SSL_ERROR_SSL_DISABLED); - if (cs == NULL) - return SECFailure; - - if (ss->cipherSpecs != NULL) { - PORT_Free(ss->cipherSpecs); - } - ss->cipherSpecs = cs; - ss->sizeCipherSpecs = count * 3; - - /* fill in cipher specs for SSL2 cipher suites */ - allowed = !ss->opt.enableSSL2 ? 0 : - (ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED); - for (i = 0; i < ssl2_NUM_SUITES_IMPLEMENTED * 3; i += 3) { - const PRUint8 * hs = implementedCipherSuites + i; - int ok = allowed & (1U << hs[0]); - if (ok) { - cs[0] = hs[0]; - cs[1] = hs[1]; - cs[2] = hs[2]; - cs += 3; - } - } - - /* now have SSL3 add its suites onto the end */ - rv = ssl3_ConstructV2CipherSpecsHack(ss, cs, &final_count); - - /* adjust for any difference between first pass and second pass */ - ss->sizeCipherSpecs -= (ssl3_count - final_count) * 3; - - return rv; -} - -/* This function is called immediately after ssl2_ConstructCipherSpecs() -** at the beginning of a handshake. It detects cases where a protocol -** (e.g. SSL2 or SSL3) is logically enabled, but all its cipher suites -** for that protocol have been disabled. If such cases, it clears the -** enable bit for the protocol. If no protocols remain enabled, or -** if no cipher suites are found, it sets the error code and returns -** SECFailure, otherwise it returns SECSuccess. -*/ -static SECStatus -ssl2_CheckConfigSanity(sslSocket *ss) -{ - unsigned int allowed; - int ssl3CipherCount = 0; - SECStatus rv; - - /* count the SSL2 and SSL3 enabled ciphers. - * if either is zero, clear the socket's enable for that protocol. - */ - if (!ss->cipherSpecs) - goto disabled; - - allowed = ss->allowedByPolicy & ss->chosenPreference; - if (! allowed) - ss->opt.enableSSL2 = PR_FALSE; /* not really enabled if no ciphers */ - - /* ssl3_config_match_init was called in ssl2_ConstructCipherSpecs(). */ - /* Ask how many ssl3 CipherSuites were enabled. */ - rv = ssl3_ConstructV2CipherSpecsHack(ss, NULL, &ssl3CipherCount); - if (rv != SECSuccess || ssl3CipherCount <= 0) { - /* SSL3/TLS not really enabled if no ciphers */ - ss->vrange.min = SSL_LIBRARY_VERSION_NONE; - ss->vrange.max = SSL_LIBRARY_VERSION_NONE; - } - - if (!ss->opt.enableSSL2 && SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - SSL_DBG(("%d: SSL[%d]: Can't handshake! all versions disabled.", - SSL_GETPID(), ss->fd)); -disabled: - PORT_SetError(SSL_ERROR_SSL_DISABLED); - return SECFailure; - } - return SECSuccess; -} - -/* - * Since this is a global (not per-socket) setting, we cannot use the - * HandshakeLock to protect this. Probably want a global lock. - */ -SECStatus -ssl2_SetPolicy(PRInt32 which, PRInt32 policy) -{ - PRUint32 bitMask; - SECStatus rv = SECSuccess; - - which &= 0x000f; - bitMask = 1 << which; - - if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - return SECFailure; - } - - if (policy == SSL_ALLOWED) { - allowedByPolicy |= bitMask; - maybeAllowedByPolicy |= bitMask; - } else if (policy == SSL_RESTRICTED) { - allowedByPolicy &= ~bitMask; - maybeAllowedByPolicy |= bitMask; - } else { - allowedByPolicy &= ~bitMask; - maybeAllowedByPolicy &= ~bitMask; - } - allowedByPolicy &= SSL_CB_IMPLEMENTED; - maybeAllowedByPolicy &= SSL_CB_IMPLEMENTED; - - policyWasSet = PR_TRUE; - return rv; -} - -SECStatus -ssl2_GetPolicy(PRInt32 which, PRInt32 *oPolicy) -{ - PRUint32 bitMask; - PRInt32 policy; - - which &= 0x000f; - bitMask = 1 << which; - - /* Caller assures oPolicy is not null. */ - if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - *oPolicy = SSL_NOT_ALLOWED; - return SECFailure; - } - - if (maybeAllowedByPolicy & bitMask) { - policy = (allowedByPolicy & bitMask) ? SSL_ALLOWED : SSL_RESTRICTED; - } else { - policy = SSL_NOT_ALLOWED; - } - - *oPolicy = policy; - return SECSuccess; -} - -/* - * Since this is a global (not per-socket) setting, we cannot use the - * HandshakeLock to protect this. Probably want a global lock. - * Called from SSL_CipherPrefSetDefault in sslsock.c - * These changes have no effect on any sslSockets already created. - */ -SECStatus -ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled) -{ - PRUint32 bitMask; - - which &= 0x000f; - bitMask = 1 << which; - - if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - return SECFailure; - } - - if (enabled) - chosenPreference |= bitMask; - else - chosenPreference &= ~bitMask; - chosenPreference &= SSL_CB_IMPLEMENTED; - - return SECSuccess; -} - -SECStatus -ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) -{ - PRBool rv = PR_FALSE; - PRUint32 bitMask; - - which &= 0x000f; - bitMask = 1 << which; - - if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - *enabled = PR_FALSE; - return SECFailure; - } - - rv = (PRBool)((chosenPreference & bitMask) != 0); - *enabled = rv; - return SECSuccess; -} - -SECStatus -ssl2_CipherPrefSet(sslSocket *ss, PRInt32 which, PRBool enabled) -{ - PRUint32 bitMask; - - which &= 0x000f; - bitMask = 1 << which; - - if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - return SECFailure; - } - - if (enabled) - ss->chosenPreference |= bitMask; - else - ss->chosenPreference &= ~bitMask; - ss->chosenPreference &= SSL_CB_IMPLEMENTED; - - return SECSuccess; -} - -SECStatus -ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled) -{ - PRBool rv = PR_FALSE; - PRUint32 bitMask; - - which &= 0x000f; - bitMask = 1 << which; - - if (!(bitMask & SSL_CB_IMPLEMENTED)) { - PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE); - *enabled = PR_FALSE; - return SECFailure; - } - - rv = (PRBool)((ss->chosenPreference & bitMask) != 0); - *enabled = rv; - return SECSuccess; -} - - -/* copy global default policy into socket. */ -void -ssl2_InitSocketPolicy(sslSocket *ss) -{ - ss->allowedByPolicy = allowedByPolicy; - ss->maybeAllowedByPolicy = maybeAllowedByPolicy; - ss->chosenPreference = chosenPreference; -} - - -/************************************************************************/ - -/* Called from ssl2_CreateSessionCypher(), which already holds handshake lock. - */ -static SECStatus -ssl2_CreateMAC(sslSecurityInfo *sec, SECItem *readKey, SECItem *writeKey, - int cipherChoice) -{ - switch (cipherChoice) { - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_WITH_MD5: - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC4_128_WITH_MD5: - case SSL_CK_DES_64_CBC_WITH_MD5: - case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: - sec->hash = HASH_GetHashObject(HASH_AlgMD5); - if (SECITEM_CopyItem(0, &sec->sendSecret, writeKey) || - SECITEM_CopyItem(0, &sec->rcvSecret, readKey)) { - return SECFailure; - } - break; - - default: - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } - sec->hashcx = (*sec->hash->create)(); - if (sec->hashcx == NULL) - return SECFailure; - return SECSuccess; -} - -/************************************************************************ - * All the Send functions below must acquire and release the socket's - * xmitBufLock. - */ - -/* Called from all the Send* functions below. */ -static SECStatus -ssl2_GetSendBuffer(sslSocket *ss, unsigned int len) -{ - SECStatus rv = SECSuccess; - - PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); - - if (len < 128) { - len = 128; - } - if (len > ss->sec.ci.sendBuf.space) { - rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, len); - if (rv != SECSuccess) { - SSL_DBG(("%d: SSL[%d]: ssl2_GetSendBuffer failed, tried to get %d bytes", - SSL_GETPID(), ss->fd, len)); - rv = SECFailure; - } - } - return rv; -} - -/* Called from: - * ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() - * ssl2_HandleRequestCertificate() <- ssl2_HandleMessage() <- - ssl_Do1stHandshake() - * ssl2_HandleMessage() <- ssl_Do1stHandshake() - * ssl2_HandleServerHelloMessage() <- ssl_Do1stHandshake() - after ssl2_BeginClientHandshake() - * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake() - after ssl2_BeginServerHandshake() - * - * Acquires and releases the socket's xmitBufLock. - */ -int -ssl2_SendErrorMessage(sslSocket *ss, int error) -{ - int rv; - PRUint8 msg[SSL_HL_ERROR_HBYTES]; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - msg[0] = SSL_MT_ERROR; - msg[1] = MSB(error); - msg[2] = LSB(error); - - ssl_GetXmitBufLock(ss); /***************************************/ - - SSL_TRC(3, ("%d: SSL[%d]: sending error %d", SSL_GETPID(), ss->fd, error)); - - ss->handshakeBegun = 1; - rv = (*ss->sec.send)(ss, msg, sizeof(msg), 0); - if (rv >= 0) { - rv = SECSuccess; - } - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/* Called from ssl2_TryToFinish(). - * Acquires and releases the socket's xmitBufLock. - */ -static SECStatus -ssl2_SendClientFinishedMessage(sslSocket *ss) -{ - SECStatus rv = SECSuccess; - int sent; - PRUint8 msg[1 + SSL_CONNECTIONID_BYTES]; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetXmitBufLock(ss); /***************************************/ - - if (ss->sec.ci.sentFinished == 0) { - ss->sec.ci.sentFinished = 1; - - SSL_TRC(3, ("%d: SSL[%d]: sending client-finished", - SSL_GETPID(), ss->fd)); - - msg[0] = SSL_MT_CLIENT_FINISHED; - PORT_Memcpy(msg+1, ss->sec.ci.connectionID, - sizeof(ss->sec.ci.connectionID)); - - DUMP_MSG(29, (ss, msg, 1 + sizeof(ss->sec.ci.connectionID))); - sent = (*ss->sec.send)(ss, msg, 1 + sizeof(ss->sec.ci.connectionID), 0); - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; - } - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/* Called from - * ssl2_HandleClientSessionKeyMessage() <- ssl2_HandleClientHelloMessage() - * ssl2_HandleClientHelloMessage() <- ssl_Do1stHandshake() - after ssl2_BeginServerHandshake() - * Acquires and releases the socket's xmitBufLock. - */ -static SECStatus -ssl2_SendServerVerifyMessage(sslSocket *ss) -{ - PRUint8 * msg; - int sendLen; - int sent; - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetXmitBufLock(ss); /***************************************/ - - sendLen = 1 + SSL_CHALLENGE_BYTES; - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) { - goto done; - } - - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_SERVER_VERIFY; - PORT_Memcpy(msg+1, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); - - DUMP_MSG(29, (ss, msg, sendLen)); - sent = (*ss->sec.send)(ss, msg, sendLen, 0); - - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; - -done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/* Called from ssl2_TryToFinish(). - * Acquires and releases the socket's xmitBufLock. - */ -static SECStatus -ssl2_SendServerFinishedMessage(sslSocket *ss) -{ - sslSessionID * sid; - PRUint8 * msg; - int sendLen, sent; - SECStatus rv = SECSuccess; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetXmitBufLock(ss); /***************************************/ - - if (ss->sec.ci.sentFinished == 0) { - ss->sec.ci.sentFinished = 1; - PORT_Assert(ss->sec.ci.sid != 0); - sid = ss->sec.ci.sid; - - SSL_TRC(3, ("%d: SSL[%d]: sending server-finished", - SSL_GETPID(), ss->fd)); - - sendLen = 1 + sizeof(sid->u.ssl2.sessionID); - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) { - goto done; - } - - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_SERVER_FINISHED; - PORT_Memcpy(msg+1, sid->u.ssl2.sessionID, - sizeof(sid->u.ssl2.sessionID)); - - DUMP_MSG(29, (ss, msg, sendLen)); - sent = (*ss->sec.send)(ss, msg, sendLen, 0); - - if (sent < 0) { - /* If send failed, it is now a bogus session-id */ - if (ss->sec.uncache) - (*ss->sec.uncache)(sid); - rv = (SECStatus)sent; - } else if (!ss->opt.noCache) { - if (sid->cached == never_cached) { - (*ss->sec.cache)(sid); - } - rv = SECSuccess; - } - ssl_FreeSID(sid); - ss->sec.ci.sid = 0; - } -done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/* Called from ssl2_ClientSetupSessionCypher() <- - * ssl2_HandleServerHelloMessage() - * after ssl2_BeginClientHandshake() - * Acquires and releases the socket's xmitBufLock. - */ -static SECStatus -ssl2_SendSessionKeyMessage(sslSocket *ss, int cipher, int keySize, - PRUint8 *ca, int caLen, - PRUint8 *ck, int ckLen, - PRUint8 *ek, int ekLen) -{ - PRUint8 * msg; - int sendLen; - int sent; - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetXmitBufLock(ss); /***************************************/ - - sendLen = SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen; - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) - goto done; - - SSL_TRC(3, ("%d: SSL[%d]: sending client-session-key", - SSL_GETPID(), ss->fd)); - - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_CLIENT_MASTER_KEY; - msg[1] = cipher; - msg[2] = MSB(keySize); - msg[3] = LSB(keySize); - msg[4] = MSB(ckLen); - msg[5] = LSB(ckLen); - msg[6] = MSB(ekLen); - msg[7] = LSB(ekLen); - msg[8] = MSB(caLen); - msg[9] = LSB(caLen); - PORT_Memcpy(msg+SSL_HL_CLIENT_MASTER_KEY_HBYTES, ck, ckLen); - PORT_Memcpy(msg+SSL_HL_CLIENT_MASTER_KEY_HBYTES+ckLen, ek, ekLen); - PORT_Memcpy(msg+SSL_HL_CLIENT_MASTER_KEY_HBYTES+ckLen+ekLen, ca, caLen); - - DUMP_MSG(29, (ss, msg, sendLen)); - sent = (*ss->sec.send)(ss, msg, sendLen, 0); - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; -done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/* Called from ssl2_TriggerNextMessage() <- ssl2_HandleMessage() - * Acquires and releases the socket's xmitBufLock. - */ -static SECStatus -ssl2_SendCertificateRequestMessage(sslSocket *ss) -{ - PRUint8 * msg; - int sent; - int sendLen; - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetXmitBufLock(ss); /***************************************/ - - sendLen = SSL_HL_REQUEST_CERTIFICATE_HBYTES + SSL_CHALLENGE_BYTES; - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) - goto done; - - SSL_TRC(3, ("%d: SSL[%d]: sending certificate request", - SSL_GETPID(), ss->fd)); - - /* Generate random challenge for client to encrypt */ - PK11_GenerateRandom(ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES); - - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_REQUEST_CERTIFICATE; - msg[1] = SSL_AT_MD5_WITH_RSA_ENCRYPTION; - PORT_Memcpy(msg + SSL_HL_REQUEST_CERTIFICATE_HBYTES, - ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES); - - DUMP_MSG(29, (ss, msg, sendLen)); - sent = (*ss->sec.send)(ss, msg, sendLen, 0); - rv = (sent >= 0) ? SECSuccess : (SECStatus)sent; -done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/* Called from ssl2_HandleRequestCertificate() <- ssl2_HandleMessage() - * Acquires and releases the socket's xmitBufLock. - */ -static int -ssl2_SendCertificateResponseMessage(sslSocket *ss, SECItem *cert, - SECItem *encCode) -{ - PRUint8 *msg; - int rv, sendLen; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetXmitBufLock(ss); /***************************************/ - - sendLen = SSL_HL_CLIENT_CERTIFICATE_HBYTES + encCode->len + cert->len; - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv) - goto done; - - SSL_TRC(3, ("%d: SSL[%d]: sending certificate response", - SSL_GETPID(), ss->fd)); - - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_CLIENT_CERTIFICATE; - msg[1] = SSL_CT_X509_CERTIFICATE; - msg[2] = MSB(cert->len); - msg[3] = LSB(cert->len); - msg[4] = MSB(encCode->len); - msg[5] = LSB(encCode->len); - PORT_Memcpy(msg + SSL_HL_CLIENT_CERTIFICATE_HBYTES, cert->data, cert->len); - PORT_Memcpy(msg + SSL_HL_CLIENT_CERTIFICATE_HBYTES + cert->len, - encCode->data, encCode->len); - - DUMP_MSG(29, (ss, msg, sendLen)); - rv = (*ss->sec.send)(ss, msg, sendLen, 0); - if (rv >= 0) { - rv = SECSuccess; - } -done: - ssl_ReleaseXmitBufLock(ss); /***************************************/ - return rv; -} - -/******************************************************************** -** Send functions above this line must aquire & release the socket's -** xmitBufLock. -** All the ssl2_Send functions below this line are called vis ss->sec.send -** and require that the caller hold the xmitBufLock. -*/ - -/* -** Called from ssl2_SendStream, ssl2_SendBlock, but not from ssl2_SendClear. -*/ -static SECStatus -ssl2_CalcMAC(PRUint8 * result, - sslSecurityInfo * sec, - const PRUint8 * data, - unsigned int dataLen, - unsigned int paddingLen) -{ - const PRUint8 * secret = sec->sendSecret.data; - unsigned int secretLen = sec->sendSecret.len; - unsigned long sequenceNumber = sec->sendSequence; - unsigned int nout; - PRUint8 seq[4]; - PRUint8 padding[32];/* XXX max blocksize? */ - - if (!sec->hash || !sec->hash->length) - return SECSuccess; - if (!sec->hashcx) - return SECFailure; - - /* Reset hash function */ - (*sec->hash->begin)(sec->hashcx); - - /* Feed hash the data */ - (*sec->hash->update)(sec->hashcx, secret, secretLen); - (*sec->hash->update)(sec->hashcx, data, dataLen); - PORT_Memset(padding, paddingLen, paddingLen); - (*sec->hash->update)(sec->hashcx, padding, paddingLen); - - seq[0] = (PRUint8) (sequenceNumber >> 24); - seq[1] = (PRUint8) (sequenceNumber >> 16); - seq[2] = (PRUint8) (sequenceNumber >> 8); - seq[3] = (PRUint8) (sequenceNumber); - - PRINT_BUF(60, (0, "calc-mac secret:", secret, secretLen)); - PRINT_BUF(60, (0, "calc-mac data:", data, dataLen)); - PRINT_BUF(60, (0, "calc-mac padding:", padding, paddingLen)); - PRINT_BUF(60, (0, "calc-mac seq:", seq, 4)); - - (*sec->hash->update)(sec->hashcx, seq, 4); - - /* Get result */ - (*sec->hash->end)(sec->hashcx, result, &nout, sec->hash->length); - - return SECSuccess; -} - -/* -** Maximum transmission amounts. These are tiny bit smaller than they -** need to be (they account for the MAC length plus some padding), -** assuming the MAC is 16 bytes long and the padding is a max of 7 bytes -** long. This gives an additional 9 bytes of slop to work within. -*/ -#define MAX_STREAM_CYPHER_LEN 0x7fe0 -#define MAX_BLOCK_CYPHER_LEN 0x3fe0 - -/* -** Send some data in the clear. -** Package up data with the length header and send it. -** -** Return count of bytes successfully written, or negative number (failure). -*/ -static PRInt32 -ssl2_SendClear(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) -{ - PRUint8 * out; - int rv; - unsigned int amount; - int count = 0; - - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); - - SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes in the clear", - SSL_GETPID(), ss->fd, len)); - PRINT_BUF(50, (ss, "clear data:", (PRUint8*) in, len)); - - while (len) { - amount = PR_MIN( len, MAX_STREAM_CYPHER_LEN ); - if (amount + 2 > ss->sec.writeBuf.space) { - rv = sslBuffer_Grow(&ss->sec.writeBuf, amount + 2); - if (rv != SECSuccess) { - count = rv; - break; - } - } - out = ss->sec.writeBuf.buf; - - /* - ** Construct message. - */ - out[0] = 0x80 | MSB(amount); - out[1] = LSB(amount); - PORT_Memcpy(&out[2], in, amount); - - /* Now send the data */ - rv = ssl_DefSend(ss, out, amount + 2, flags & ~ssl_SEND_FLAG_MASK); - if (rv < 0) { - if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { - rv = 0; - } else { - /* Return short write if some data already went out... */ - if (count == 0) - count = rv; - break; - } - } - - if ((unsigned)rv < (amount + 2)) { - /* Short write. Save the data and return. */ - if (ssl_SaveWriteData(ss, out + rv, amount + 2 - rv) - == SECFailure) { - count = SECFailure; - } else { - count += amount; - ss->sec.sendSequence++; - } - break; - } - - ss->sec.sendSequence++; - in += amount; - count += amount; - len -= amount; - } - - return count; -} - -/* -** Send some data, when using a stream cipher. Stream ciphers have a -** block size of 1. Package up the data with the length header -** and send it. -*/ -static PRInt32 -ssl2_SendStream(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) -{ - PRUint8 * out; - int rv; - int count = 0; - - int amount; - PRUint8 macLen; - int nout; - unsigned int buflen; - - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); - - SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes using stream cipher", - SSL_GETPID(), ss->fd, len)); - PRINT_BUF(50, (ss, "clear data:", (PRUint8*) in, len)); - - while (len) { - ssl_GetSpecReadLock(ss); /*************************************/ - - macLen = ss->sec.hash->length; - amount = PR_MIN( len, MAX_STREAM_CYPHER_LEN ); - buflen = amount + 2 + macLen; - if (buflen > ss->sec.writeBuf.space) { - rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen); - if (rv != SECSuccess) { - goto loser; - } - } - out = ss->sec.writeBuf.buf; - nout = amount + macLen; - out[0] = 0x80 | MSB(nout); - out[1] = LSB(nout); - - /* Calculate MAC */ - rv = ssl2_CalcMAC(out+2, /* put MAC here */ - &ss->sec, - in, amount, /* input addr & length */ - 0); /* no padding */ - if (rv != SECSuccess) - goto loser; - - /* Encrypt MAC */ - rv = (*ss->sec.enc)(ss->sec.writecx, out+2, &nout, macLen, out+2, macLen); - if (rv) goto loser; - - /* Encrypt data from caller */ - rv = (*ss->sec.enc)(ss->sec.writecx, out+2+macLen, &nout, amount, in, amount); - if (rv) goto loser; - - ssl_ReleaseSpecReadLock(ss); /*************************************/ - - PRINT_BUF(50, (ss, "encrypted data:", out, buflen)); - - rv = ssl_DefSend(ss, out, buflen, flags & ~ssl_SEND_FLAG_MASK); - if (rv < 0) { - if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { - SSL_TRC(50, ("%d: SSL[%d]: send stream would block, " - "saving data", SSL_GETPID(), ss->fd)); - rv = 0; - } else { - SSL_TRC(10, ("%d: SSL[%d]: send stream error %d", - SSL_GETPID(), ss->fd, PORT_GetError())); - /* Return short write if some data already went out... */ - if (count == 0) - count = rv; - goto done; - } - } - - if ((unsigned)rv < buflen) { - /* Short write. Save the data and return. */ - if (ssl_SaveWriteData(ss, out + rv, buflen - rv) == SECFailure) { - count = SECFailure; - } else { - count += amount; - ss->sec.sendSequence++; - } - goto done; - } - - ss->sec.sendSequence++; - in += amount; - count += amount; - len -= amount; - } - -done: - return count; - -loser: - ssl_ReleaseSpecReadLock(ss); - return SECFailure; -} - -/* -** Send some data, when using a block cipher. Package up the data with -** the length header and send it. -*/ -/* XXX assumes blocksize is > 7 */ -static PRInt32 -ssl2_SendBlock(sslSocket *ss, const PRUint8 *in, PRInt32 len, PRInt32 flags) -{ - PRUint8 * out; /* begining of output buffer. */ - PRUint8 * op; /* next output byte goes here. */ - int rv; /* value from funcs we called. */ - int count = 0; /* this function's return value. */ - - unsigned int hlen; /* output record hdr len, 2 or 3 */ - unsigned int macLen; /* MAC is this many bytes long. */ - int amount; /* of plaintext to go in record. */ - unsigned int padding; /* add this many padding byte. */ - int nout; /* ciphertext size after header. */ - unsigned int buflen; /* size of generated record. */ - - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); - - SSL_TRC(10, ("%d: SSL[%d]: sending %d bytes using block cipher", - SSL_GETPID(), ss->fd, len)); - PRINT_BUF(50, (ss, "clear data:", in, len)); - - while (len) { - ssl_GetSpecReadLock(ss); /*************************************/ - - macLen = ss->sec.hash->length; - /* Figure out how much to send, including mac and padding */ - amount = PR_MIN( len, MAX_BLOCK_CYPHER_LEN ); - nout = amount + macLen; - padding = nout & (ss->sec.blockSize - 1); - if (padding) { - hlen = 3; - padding = ss->sec.blockSize - padding; - nout += padding; - } else { - hlen = 2; - } - buflen = hlen + nout; - if (buflen > ss->sec.writeBuf.space) { - rv = sslBuffer_Grow(&ss->sec.writeBuf, buflen); - if (rv != SECSuccess) { - goto loser; - } - } - out = ss->sec.writeBuf.buf; - - /* Construct header */ - op = out; - if (padding) { - *op++ = MSB(nout); - *op++ = LSB(nout); - *op++ = padding; - } else { - *op++ = 0x80 | MSB(nout); - *op++ = LSB(nout); - } - - /* Calculate MAC */ - rv = ssl2_CalcMAC(op, /* MAC goes here. */ - &ss->sec, - in, amount, /* intput addr, len */ - padding); - if (rv != SECSuccess) - goto loser; - op += macLen; - - /* Copy in the input data */ - /* XXX could eliminate the copy by folding it into the encryption */ - PORT_Memcpy(op, in, amount); - op += amount; - if (padding) { - PORT_Memset(op, padding, padding); - op += padding; - } - - /* Encrypt result */ - rv = (*ss->sec.enc)(ss->sec.writecx, out+hlen, &nout, buflen-hlen, - out+hlen, op - (out + hlen)); - if (rv) - goto loser; - - ssl_ReleaseSpecReadLock(ss); /*************************************/ - - PRINT_BUF(50, (ss, "final xmit data:", out, op - out)); - - rv = ssl_DefSend(ss, out, op - out, flags & ~ssl_SEND_FLAG_MASK); - if (rv < 0) { - if (PORT_GetError() == PR_WOULD_BLOCK_ERROR) { - rv = 0; - } else { - SSL_TRC(10, ("%d: SSL[%d]: send block error %d", - SSL_GETPID(), ss->fd, PORT_GetError())); - /* Return short write if some data already went out... */ - if (count == 0) - count = rv; - goto done; - } - } - - if (rv < (op - out)) { - /* Short write. Save the data and return. */ - if (ssl_SaveWriteData(ss, out + rv, op - out - rv) == SECFailure) { - count = SECFailure; - } else { - count += amount; - ss->sec.sendSequence++; - } - goto done; - } - - ss->sec.sendSequence++; - in += amount; - count += amount; - len -= amount; - } - -done: - return count; - -loser: - ssl_ReleaseSpecReadLock(ss); - return SECFailure; -} - -/* -** Called from: ssl2_HandleServerHelloMessage, -** ssl2_HandleClientSessionKeyMessage, -** ssl2_HandleClientHelloMessage, -** -*/ -static void -ssl2_UseEncryptedSendFunc(sslSocket *ss) -{ - ssl_GetXmitBufLock(ss); - PORT_Assert(ss->sec.hashcx != 0); - - ss->gs.encrypted = 1; - ss->sec.send = (ss->sec.blockSize > 1) ? ssl2_SendBlock : ssl2_SendStream; - ssl_ReleaseXmitBufLock(ss); -} - -/* Called while initializing socket in ssl_CreateSecurityInfo(). -** This function allows us to keep the name of ssl2_SendClear static. -*/ -void -ssl2_UseClearSendFunc(sslSocket *ss) -{ - ss->sec.send = ssl2_SendClear; -} - -/************************************************************************ -** END of Send functions. * -*************************************************************************/ + ; /*********************************************************************** - * For SSL3, this gathers in and handles records/messages until either - * the handshake is complete or application data is available. - * - * For SSL2, this gathers in only the next SSLV2 record. + * 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 SECWouldBlock when that value is returned by ssl2_GatherRecord() or - * ssl3_GatherCompleteHandshake(). + * returns SECWouldBlock when that value is returned by + * ssl3_GatherCompleteHandshake(). * returns SECFailure on all other errors. * - * The gather functions called by ssl_GatherRecord1stHandshake are expected - * to return values interpreted as follows: + * 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. - * -2 : the function wants ssl_GatherRecord1stHandshake to be called again - * immediately, by ssl_Do1stHandshake. + * -2 : the function wants ssl_GatherRecord1stHandshake to be called again + * immediately, by ssl_Do1stHandshake. * * This code is similar to, and easily confused with, DoRecv() in sslsecur.c * - * This function is called from ssl_Do1stHandshake(). + * This function is called from ssl_Do1stHandshake(). * The following functions put ssl_GatherRecord1stHandshake into ss->handshake: - * ssl2_HandleMessage - * ssl2_HandleVerifyMessage - * ssl2_HandleServerHelloMessage - * ssl2_BeginClientHandshake - * ssl2_HandleClientSessionKeyMessage - * ssl3_RestartHandshakeAfterCertReq - * ssl3_RestartHandshakeAfterServerCert - * ssl2_HandleClientHelloMessage - * ssl2_BeginServerHandshake + * ssl_BeginClientHandshake + * ssl3_RestartHandshakeAfterCertReq + * ssl3_RestartHandshakeAfterServerCert + * ssl_BeginServerHandshake */ SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss) { int rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); ssl_GetRecvBufLock(ss); - /* The special case DTLS logic is needed here because the SSL/TLS - * version wants to auto-detect SSL2 vs. SSL3 on the initial handshake - * (ss->version == 0) but with DTLS it gets confused, so we force the - * SSL3 version. - */ - if ((ss->version >= SSL_LIBRARY_VERSION_3_0) || IS_DTLS(ss)) { - /* Wait for handshake to complete, or application data to arrive. */ - rv = ssl3_GatherCompleteHandshake(ss, 0); - } else { - /* See if we have a complete record */ - rv = ssl2_GatherRecord(ss, 0); - } + /* 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_GETPID(), ss->fd, rv)); ssl_ReleaseRecvBufLock(ss); if (rv <= 0) { - if (rv == SECWouldBlock) { - /* Progress is blocked waiting for callback completion. */ - SSL_TRC(10, ("%d: SSL[%d]: handshake blocked (need %d)", - SSL_GETPID(), ss->fd, ss->gs.remainder)); - return SECWouldBlock; - } - if (rv == 0) { - /* EOF. Loser */ - PORT_SetError(PR_END_OF_FILE_ERROR); - } - return SECFailure; /* rv is < 0 here. */ - } - - SSL_TRC(10, ("%d: SSL[%d]: got handshake record of %d bytes", - SSL_GETPID(), ss->fd, ss->gs.recordLen)); - - ss->handshake = 0; /* makes ssl_Do1stHandshake call ss->nextHandshake.*/ - return SECSuccess; -} - -/************************************************************************/ - -/* Called from ssl2_ServerSetupSessionCypher() - * ssl2_ClientSetupSessionCypher() - */ -static SECStatus -ssl2_FillInSID(sslSessionID * sid, - int cipher, - PRUint8 *keyData, - int keyLen, - PRUint8 *ca, - int caLen, - int keyBits, - int secretKeyBits, - SSLSignType authAlgorithm, - PRUint32 authKeyBits, - SSLKEAType keaType, - PRUint32 keaKeyBits) -{ - PORT_Assert(sid->references == 1); - PORT_Assert(sid->cached == never_cached); - PORT_Assert(sid->u.ssl2.masterKey.data == 0); - PORT_Assert(sid->u.ssl2.cipherArg.data == 0); - - sid->version = SSL_LIBRARY_VERSION_2; - - sid->u.ssl2.cipherType = cipher; - sid->u.ssl2.masterKey.data = (PRUint8*) PORT_Alloc(keyLen); - if (!sid->u.ssl2.masterKey.data) { - return SECFailure; - } - PORT_Memcpy(sid->u.ssl2.masterKey.data, keyData, keyLen); - sid->u.ssl2.masterKey.len = keyLen; - sid->u.ssl2.keyBits = keyBits; - sid->u.ssl2.secretKeyBits = secretKeyBits; - sid->authAlgorithm = authAlgorithm; - sid->authKeyBits = authKeyBits; - sid->keaType = keaType; - sid->keaKeyBits = keaKeyBits; - sid->lastAccessTime = sid->creationTime = ssl_Time(); - sid->expirationTime = sid->creationTime + ssl_sid_timeout; - - if (caLen) { - sid->u.ssl2.cipherArg.data = (PRUint8*) PORT_Alloc(caLen); - if (!sid->u.ssl2.cipherArg.data) { - return SECFailure; - } - sid->u.ssl2.cipherArg.len = caLen; - PORT_Memcpy(sid->u.ssl2.cipherArg.data, ca, caLen); - } - return SECSuccess; -} - -/* -** Construct session keys given the masterKey (tied to the session-id), -** the client's challenge and the server's nonce. -** -** Called from ssl2_CreateSessionCypher() <- -*/ -static SECStatus -ssl2_ProduceKeys(sslSocket * ss, - SECItem * readKey, - SECItem * writeKey, - SECItem * masterKey, - PRUint8 * challenge, - PRUint8 * nonce, - int cipherType) -{ - PK11Context * cx = 0; - unsigned nkm = 0; /* number of hashes to generate key mat. */ - unsigned nkd = 0; /* size of readKey and writeKey. */ - unsigned part; - unsigned i; - unsigned off; - SECStatus rv; - PRUint8 countChar; - PRUint8 km[3*16]; /* buffer for key material. */ - - readKey->data = 0; - writeKey->data = 0; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - rv = SECSuccess; - cx = PK11_CreateDigestContext(SEC_OID_MD5); - if (cx == NULL) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - return SECFailure; - } - - nkm = ssl_Specs[cipherType].nkm; - nkd = ssl_Specs[cipherType].nkd; - - readKey->data = (PRUint8*) PORT_Alloc(nkd); - if (!readKey->data) - goto loser; - readKey->len = nkd; - - writeKey->data = (PRUint8*) PORT_Alloc(nkd); - if (!writeKey->data) - goto loser; - writeKey->len = nkd; - - /* Produce key material */ - countChar = '0'; - for (i = 0, off = 0; i < nkm; i++, off += 16) { - rv = PK11_DigestBegin(cx); - rv |= PK11_DigestOp(cx, masterKey->data, masterKey->len); - rv |= PK11_DigestOp(cx, &countChar, 1); - rv |= PK11_DigestOp(cx, challenge, SSL_CHALLENGE_BYTES); - rv |= PK11_DigestOp(cx, nonce, SSL_CONNECTIONID_BYTES); - rv |= PK11_DigestFinal(cx, km+off, &part, MD5_LENGTH); - if (rv != SECSuccess) { - ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE); - rv = SECFailure; - goto loser; - } - countChar++; - } - - /* Produce keys */ - PORT_Memcpy(readKey->data, km, nkd); - PORT_Memcpy(writeKey->data, km + nkd, nkd); - -loser: - PK11_DestroyContext(cx, PR_TRUE); - return rv; -} - -/* Called from ssl2_ServerSetupSessionCypher() -** <- ssl2_HandleClientSessionKeyMessage() -** <- ssl2_HandleClientHelloMessage() -** and from ssl2_ClientSetupSessionCypher() -** <- ssl2_HandleServerHelloMessage() -*/ -static SECStatus -ssl2_CreateSessionCypher(sslSocket *ss, sslSessionID *sid, PRBool isClient) -{ - SECItem * rk = NULL; - SECItem * wk = NULL; - SECItem * param; - SECStatus rv; - int cipherType = sid->u.ssl2.cipherType; - PK11SlotInfo * slot = NULL; - CK_MECHANISM_TYPE mechanism; - SECItem readKey; - SECItem writeKey; - - void *readcx = 0; - void *writecx = 0; - readKey.data = 0; - writeKey.data = 0; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - if (ss->sec.ci.sid == 0) - goto sec_loser; /* don't crash if asserts are off */ - - /* Trying to cut down on all these switch statements that should be tables. - * So, test cipherType once, here, and then use tables below. - */ - switch (cipherType) { - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC4_128_WITH_MD5: - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_WITH_MD5: - case SSL_CK_DES_64_CBC_WITH_MD5: - case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: - break; - - default: - SSL_DBG(("%d: SSL[%d]: ssl2_CreateSessionCypher: unknown cipher=%d", - SSL_GETPID(), ss->fd, cipherType)); - PORT_SetError(isClient ? SSL_ERROR_BAD_SERVER : SSL_ERROR_BAD_CLIENT); - goto sec_loser; - } - - rk = isClient ? &readKey : &writeKey; - wk = isClient ? &writeKey : &readKey; - - /* Produce the keys for this session */ - rv = ssl2_ProduceKeys(ss, &readKey, &writeKey, &sid->u.ssl2.masterKey, - ss->sec.ci.clientChallenge, ss->sec.ci.connectionID, - cipherType); - if (rv != SECSuccess) - goto loser; - PRINT_BUF(7, (ss, "Session read-key: ", rk->data, rk->len)); - PRINT_BUF(7, (ss, "Session write-key: ", wk->data, wk->len)); - - PORT_Memcpy(ss->sec.ci.readKey, readKey.data, readKey.len); - PORT_Memcpy(ss->sec.ci.writeKey, writeKey.data, writeKey.len); - ss->sec.ci.keySize = readKey.len; - - /* Setup the MAC */ - rv = ssl2_CreateMAC(&ss->sec, rk, wk, cipherType); - if (rv != SECSuccess) - goto loser; - - /* First create the session key object */ - SSL_TRC(3, ("%d: SSL[%d]: using %s", SSL_GETPID(), ss->fd, - ssl_cipherName[cipherType])); - - - mechanism = ssl_Specs[cipherType].mechanism; - - /* set destructer before we call loser... */ - ss->sec.destroy = (void (*)(void*, PRBool)) PK11_DestroyContext; - slot = PK11_GetBestSlot(mechanism, ss->pkcs11PinArg); - if (slot == NULL) - goto loser; - - param = PK11_ParamFromIV(mechanism, &sid->u.ssl2.cipherArg); - if (param == NULL) - goto loser; - readcx = PK11_CreateContextByRawKey(slot, mechanism, PK11_OriginUnwrap, - CKA_DECRYPT, rk, param, - ss->pkcs11PinArg); - SECITEM_FreeItem(param, PR_TRUE); - if (readcx == NULL) - goto loser; - - /* build the client context */ - param = PK11_ParamFromIV(mechanism, &sid->u.ssl2.cipherArg); - if (param == NULL) - goto loser; - writecx = PK11_CreateContextByRawKey(slot, mechanism, PK11_OriginUnwrap, - CKA_ENCRYPT, wk, param, - ss->pkcs11PinArg); - SECITEM_FreeItem(param,PR_TRUE); - if (writecx == NULL) - goto loser; - PK11_FreeSlot(slot); - - rv = SECSuccess; - ss->sec.enc = (SSLCipher) PK11_CipherOp; - ss->sec.dec = (SSLCipher) PK11_CipherOp; - ss->sec.readcx = (void *) readcx; - ss->sec.writecx = (void *) writecx; - ss->sec.blockSize = ssl_Specs[cipherType].blockSize; - ss->sec.blockShift = ssl_Specs[cipherType].blockShift; - ss->sec.cipherType = sid->u.ssl2.cipherType; - ss->sec.keyBits = sid->u.ssl2.keyBits; - ss->sec.secretKeyBits = sid->u.ssl2.secretKeyBits; - goto done; - - loser: - if (ss->sec.destroy) { - if (readcx) (*ss->sec.destroy)(readcx, PR_TRUE); - if (writecx) (*ss->sec.destroy)(writecx, PR_TRUE); - } - ss->sec.destroy = NULL; - if (slot) PK11_FreeSlot(slot); - - sec_loser: - rv = SECFailure; - - done: - if (rk) { - SECITEM_ZfreeItem(rk, PR_FALSE); - } - if (wk) { - SECITEM_ZfreeItem(wk, PR_FALSE); - } - return rv; -} - -/* -** Setup the server ciphers given information from a CLIENT-MASTER-KEY -** message. -** "ss" pointer to the ssl-socket object -** "cipher" the cipher type to use -** "keyBits" the size of the final cipher key -** "ck" the clear-key data -** "ckLen" the number of bytes of clear-key data -** "ek" the encrypted-key data -** "ekLen" the number of bytes of encrypted-key data -** "ca" the cipher-arg data -** "caLen" the number of bytes of cipher-arg data -** -** The MASTER-KEY is constructed by first decrypting the encrypted-key -** data. This produces the SECRET-KEY-DATA. The MASTER-KEY is composed by -** concatenating the clear-key data with the SECRET-KEY-DATA. This code -** checks to make sure that the client didn't send us an improper amount -** of SECRET-KEY-DATA (it restricts the length of that data to match the -** spec). -** -** Called from ssl2_HandleClientSessionKeyMessage(). -*/ -static SECStatus -ssl2_ServerSetupSessionCypher(sslSocket *ss, int cipher, unsigned int keyBits, - PRUint8 *ck, unsigned int ckLen, - PRUint8 *ek, unsigned int ekLen, - PRUint8 *ca, unsigned int caLen) -{ - PRUint8 * dk = NULL; /* decrypted master key */ - sslSessionID * sid; - sslServerCerts * sc = ss->serverCerts + kt_rsa; - PRUint8 * kbuf = 0; /* buffer for RSA decrypted data. */ - unsigned int ddLen; /* length of RSA decrypted data in kbuf */ - unsigned int keySize; - unsigned int dkLen; /* decrypted key length in bytes */ - int modulusLen; - SECStatus rv; - PRUint16 allowed; /* cipher kinds enabled and allowed by policy */ - PRUint8 mkbuf[SSL_MAX_MASTER_KEY_BYTES]; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert((sc->SERVERKEY != 0)); - PORT_Assert((ss->sec.ci.sid != 0)); - sid = ss->sec.ci.sid; - - /* Trying to cut down on all these switch statements that should be tables. - * So, test cipherType once, here, and then use tables below. - */ - switch (cipher) { - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC4_128_WITH_MD5: - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_WITH_MD5: - case SSL_CK_DES_64_CBC_WITH_MD5: - case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: - break; - - default: - SSL_DBG(("%d: SSL[%d]: ssl2_ServerSetupSessionCypher: unknown cipher=%d", - SSL_GETPID(), ss->fd, cipher)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; - } - - allowed = ss->allowedByPolicy & ss->chosenPreference & SSL_CB_IMPLEMENTED; - if (!(allowed & (1 << cipher))) { - /* client chose a kind we don't allow! */ - SSL_DBG(("%d: SSL[%d]: disallowed cipher=%d", - SSL_GETPID(), ss->fd, cipher)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; - } - - keySize = ssl_Specs[cipher].keyLen; - if (keyBits != keySize * BPB) { - SSL_DBG(("%d: SSL[%d]: invalid master secret key length=%d (bits)!", - SSL_GETPID(), ss->fd, keyBits)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; - } - - if (ckLen != ssl_Specs[cipher].pubLen) { - SSL_DBG(("%d: SSL[%d]: invalid clear key length, ckLen=%d (bytes)!", - SSL_GETPID(), ss->fd, ckLen)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; - } - - if (caLen != ssl_Specs[cipher].ivLen) { - SSL_DBG(("%d: SSL[%d]: invalid key args length, caLen=%d (bytes)!", - SSL_GETPID(), ss->fd, caLen)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; - } - - modulusLen = PK11_GetPrivateModulusLen(sc->SERVERKEY); - if (modulusLen < 0) { - /* XXX If the key is bad, then PK11_PubDecryptRaw will fail below. */ - modulusLen = ekLen; - } - if (ekLen > (unsigned int)modulusLen || ekLen + ckLen < keySize) { - SSL_DBG(("%d: SSL[%d]: invalid encrypted key length, ekLen=%d (bytes)!", - SSL_GETPID(), ss->fd, ekLen)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto loser; - } - - /* allocate the buffer to hold the decrypted portion of the key. */ - kbuf = (PRUint8*)PORT_Alloc(modulusLen); - if (!kbuf) { - goto loser; - } - dkLen = keySize - ckLen; - dk = kbuf + modulusLen - dkLen; - - /* Decrypt encrypted half of the key. - ** NOTE: PK11_PubDecryptRaw will barf on a non-RSA key. This is - ** desired behavior here. - */ - rv = PK11_PubDecryptRaw(sc->SERVERKEY, kbuf, &ddLen, modulusLen, ek, ekLen); - if (rv != SECSuccess) - goto hide_loser; - - /* Is the length of the decrypted data (ddLen) the expected value? */ - if (modulusLen != ddLen) - goto hide_loser; - - /* Cheaply verify that PKCS#1 was used to format the encryption block */ - if ((kbuf[0] != 0x00) || (kbuf[1] != 0x02) || (dk[-1] != 0x00)) { - SSL_DBG(("%d: SSL[%d]: strange encryption block", - SSL_GETPID(), ss->fd)); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto hide_loser; - } - - /* Make sure we're not subject to a version rollback attack. */ - if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - static const PRUint8 threes[8] = { 0x03, 0x03, 0x03, 0x03, - 0x03, 0x03, 0x03, 0x03 }; - - if (PORT_Memcmp(dk - 8 - 1, threes, 8) == 0) { - PORT_SetError(SSL_ERROR_BAD_CLIENT); - goto hide_loser; - } - } - if (0) { -hide_loser: - /* Defense against the Bleichenbacher attack. - * Provide the client with NO CLUES that the decrypted master key - * was erroneous. Don't send any error messages. - * Instead, Generate a completely bogus master key . - */ - PK11_GenerateRandom(dk, dkLen); - } - - /* - ** Construct master key out of the pieces. - */ - if (ckLen) { - PORT_Memcpy(mkbuf, ck, ckLen); - } - PORT_Memcpy(mkbuf + ckLen, dk, dkLen); - - /* Fill in session-id */ - rv = ssl2_FillInSID(sid, cipher, mkbuf, keySize, ca, caLen, - keyBits, keyBits - (ckLen<<3), - ss->sec.authAlgorithm, ss->sec.authKeyBits, - ss->sec.keaType, ss->sec.keaKeyBits); - if (rv != SECSuccess) { - goto loser; - } - - /* Create session ciphers */ - rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE); - if (rv != SECSuccess) { - goto loser; - } - - SSL_TRC(1, ("%d: SSL[%d]: server, using %s cipher, clear=%d total=%d", - SSL_GETPID(), ss->fd, ssl_cipherName[cipher], - ckLen<<3, keySize<<3)); - rv = SECSuccess; - goto done; - - loser: - rv = SECFailure; - - done: - PORT_Free(kbuf); - return rv; -} - -/************************************************************************/ - -/* -** Rewrite the incoming cipher specs, comparing to list of specs we support, -** (ss->cipherSpecs) and eliminating anything we don't support -** -* Note: Our list may contain SSL v3 ciphers. -* We MUST NOT match on any of those. -* Fortunately, this is easy to detect because SSLv3 ciphers have zero -* in the first byte, and none of the SSLv2 ciphers do. -* -* Called from ssl2_HandleClientHelloMessage(). -* Returns the number of bytes of "qualified cipher specs", -* which is typically a multiple of 3, but will be zero if there are none. -*/ -static int -ssl2_QualifyCypherSpecs(sslSocket *ss, - PRUint8 * cs, /* cipher specs in client hello msg. */ - int csLen) -{ - PRUint8 * ms; - PRUint8 * hs; - PRUint8 * qs; - int mc; - int hc; - PRUint8 qualifiedSpecs[ssl2_NUM_SUITES_IMPLEMENTED * 3]; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - - if (!ss->cipherSpecs) { - SECStatus rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess || !ss->cipherSpecs) - return 0; - } - - PRINT_BUF(10, (ss, "specs from client:", cs, csLen)); - qs = qualifiedSpecs; - ms = ss->cipherSpecs; - for (mc = ss->sizeCipherSpecs; mc > 0; mc -= 3, ms += 3) { - if (ms[0] == 0) - continue; - for (hs = cs, hc = csLen; hc > 0; hs += 3, hc -= 3) { - if ((hs[0] == ms[0]) && - (hs[1] == ms[1]) && - (hs[2] == ms[2])) { - /* Copy this cipher spec into the "keep" section */ - qs[0] = hs[0]; - qs[1] = hs[1]; - qs[2] = hs[2]; - qs += 3; - break; - } - } - } - hc = qs - qualifiedSpecs; - PRINT_BUF(10, (ss, "qualified specs from client:", qualifiedSpecs, hc)); - PORT_Memcpy(cs, qualifiedSpecs, hc); - return hc; -} - -/* -** Pick the best cipher we can find, given the array of server cipher -** specs. Returns cipher number (e.g. SSL_CK_*), or -1 for no overlap. -** If successful, stores the master key size (bytes) in *pKeyLen. -** -** This is correct only for the client side, but presently -** this function is only called from -** ssl2_ClientSetupSessionCypher() <- ssl2_HandleServerHelloMessage() -** -** Note that most servers only return a single cipher suite in their -** ServerHello messages. So, the code below for finding the "best" cipher -** suite usually has only one choice. The client and server should send -** their cipher suite lists sorted in descending order by preference. -*/ -static int -ssl2_ChooseSessionCypher(sslSocket *ss, - int hc, /* number of cs's in hs. */ - PRUint8 * hs, /* server hello's cipher suites. */ - int * pKeyLen) /* out: sym key size in bytes. */ -{ - PRUint8 * ms; - unsigned int i; - int bestKeySize; - int bestRealKeySize; - int bestCypher; - int keySize; - int realKeySize; - PRUint8 * ohs = hs; - const PRUint8 * preferred; - static const PRUint8 noneSuch[3] = { 0, 0, 0 }; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - - if (!ss->cipherSpecs) { - SECStatus rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess || !ss->cipherSpecs) - goto loser; - } - - if (!ss->preferredCipher) { - unsigned int allowed = ss->allowedByPolicy & ss->chosenPreference & - SSL_CB_IMPLEMENTED; - if (allowed) { - preferred = implementedCipherSuites; - for (i = ssl2_NUM_SUITES_IMPLEMENTED; i > 0; --i) { - if (0 != (allowed & (1U << preferred[0]))) { - ss->preferredCipher = preferred; - break; - } - preferred += 3; - } - } - } - preferred = ss->preferredCipher ? ss->preferredCipher : noneSuch; - /* - ** Scan list of ciphers received from peer and look for a match in - ** our list. - * Note: Our list may contain SSL v3 ciphers. - * We MUST NOT match on any of those. - * Fortunately, this is easy to detect because SSLv3 ciphers have zero - * in the first byte, and none of the SSLv2 ciphers do. - */ - bestKeySize = bestRealKeySize = 0; - bestCypher = -1; - while (--hc >= 0) { - for (i = 0, ms = ss->cipherSpecs; i < ss->sizeCipherSpecs; i += 3, ms += 3) { - if ((hs[0] == preferred[0]) && - (hs[1] == preferred[1]) && - (hs[2] == preferred[2]) && - hs[0] != 0) { - /* Pick this cipher immediately! */ - *pKeyLen = (((hs[1] << 8) | hs[2]) + 7) >> 3; - return hs[0]; - } - if ((hs[0] == ms[0]) && (hs[1] == ms[1]) && (hs[2] == ms[2]) && - hs[0] != 0) { - /* Found a match */ - - /* Use secret keySize to determine which cipher is best */ - realKeySize = (hs[1] << 8) | hs[2]; - switch (hs[0]) { - case SSL_CK_RC4_128_EXPORT40_WITH_MD5: - case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: - keySize = 40; - break; - default: - keySize = realKeySize; - break; - } - if (keySize > bestKeySize) { - bestCypher = hs[0]; - bestKeySize = keySize; - bestRealKeySize = realKeySize; - } - } - } - hs += 3; - } - if (bestCypher < 0) { - /* - ** No overlap between server and client. Re-examine server list - ** to see what kind of ciphers it does support so that we can set - ** the error code appropriately. - */ - if ((ohs[0] == SSL_CK_RC4_128_WITH_MD5) || - (ohs[0] == SSL_CK_RC2_128_CBC_WITH_MD5)) { - PORT_SetError(SSL_ERROR_US_ONLY_SERVER); - } else if ((ohs[0] == SSL_CK_RC4_128_EXPORT40_WITH_MD5) || - (ohs[0] == SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5)) { - PORT_SetError(SSL_ERROR_EXPORT_ONLY_SERVER); - } else { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - } - SSL_DBG(("%d: SSL[%d]: no cipher overlap", SSL_GETPID(), ss->fd)); - goto loser; - } - *pKeyLen = (bestRealKeySize + 7) >> 3; - return bestCypher; - - loser: - return -1; -} - -static SECStatus -ssl2_ClientHandleServerCert(sslSocket *ss, PRUint8 *certData, int certLen) -{ - CERTCertificate *cert = NULL; - SECItem certItem; - - certItem.data = certData; - certItem.len = certLen; - - /* decode the certificate */ - cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); - - if (cert == NULL) { - SSL_DBG(("%d: SSL[%d]: decode of server certificate fails", - SSL_GETPID(), ss->fd)); - PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); - return SECFailure; - } - -#ifdef TRACE - { - if (ssl_trace >= 1) { - char *issuer; - char *subject; - issuer = CERT_NameToAscii(&cert->issuer); - subject = CERT_NameToAscii(&cert->subject); - SSL_TRC(1,("%d: server certificate issuer: '%s'", - SSL_GETPID(), issuer ? issuer : "OOPS")); - SSL_TRC(1,("%d: server name: '%s'", - SSL_GETPID(), subject ? subject : "OOPS")); - PORT_Free(issuer); - PORT_Free(subject); - } - } -#endif - - ss->sec.peerCert = cert; - return SECSuccess; -} - - -/* - * Format one block of data for public/private key encryption using - * the rules defined in PKCS #1. SSL2 does this itself to handle the - * rollback detection. - */ -#define RSA_BLOCK_MIN_PAD_LEN 8 -#define RSA_BLOCK_FIRST_OCTET 0x00 -#define RSA_BLOCK_AFTER_PAD_OCTET 0x00 -#define RSA_BLOCK_PUBLIC_OCTET 0x02 -unsigned char * -ssl_FormatSSL2Block(unsigned modulusLen, SECItem *data) -{ - unsigned char *block; - unsigned char *bp; - int padLen; - SECStatus rv; - int i; - - if (modulusLen < data->len + (3 + RSA_BLOCK_MIN_PAD_LEN)) { - PORT_SetError(SEC_ERROR_BAD_KEY); - return NULL; - } - block = (unsigned char *) PORT_Alloc(modulusLen); - if (block == NULL) - return NULL; - - bp = block; - - /* - * All RSA blocks start with two octets: - * 0x00 || BlockType - */ - *bp++ = RSA_BLOCK_FIRST_OCTET; - *bp++ = RSA_BLOCK_PUBLIC_OCTET; - - /* - * 0x00 || BT || Pad || 0x00 || ActualData - * 1 1 padLen 1 data->len - * Pad is all non-zero random bytes. - */ - padLen = modulusLen - data->len - 3; - PORT_Assert (padLen >= RSA_BLOCK_MIN_PAD_LEN); - rv = PK11_GenerateRandom(bp, padLen); - if (rv == SECFailure) goto loser; - /* replace all the 'zero' bytes */ - for (i = 0; i < padLen; i++) { - while (bp[i] == RSA_BLOCK_AFTER_PAD_OCTET) { - rv = PK11_GenerateRandom(bp+i, 1); - if (rv == SECFailure) goto loser; - } - } - bp += padLen; - *bp++ = RSA_BLOCK_AFTER_PAD_OCTET; - PORT_Memcpy (bp, data->data, data->len); - - return block; -loser: - if (block) PORT_Free(block); - return NULL; -} - -/* -** Given the server's public key and cipher specs, generate a session key -** that is ready to use for encrypting/decrypting the byte stream. At -** the same time, generate the SSL_MT_CLIENT_MASTER_KEY message and -** send it to the server. -** -** Called from ssl2_HandleServerHelloMessage() -*/ -static SECStatus -ssl2_ClientSetupSessionCypher(sslSocket *ss, PRUint8 *cs, int csLen) -{ - sslSessionID * sid; - PRUint8 * ca; /* points to iv data, or NULL if none. */ - PRUint8 * ekbuf = 0; - CERTCertificate * cert = 0; - SECKEYPublicKey * serverKey = 0; - unsigned modulusLen = 0; - SECStatus rv; - int cipher; - int keyLen; /* cipher symkey size in bytes. */ - int ckLen; /* publicly reveal this many bytes of key. */ - int caLen; /* length of IV data at *ca. */ - int nc; - - unsigned char *eblock; /* holds unencrypted PKCS#1 formatted key. */ - SECItem rek; /* holds portion of symkey to be encrypted. */ - - PRUint8 keyData[SSL_MAX_MASTER_KEY_BYTES]; - PRUint8 iv [8]; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - eblock = NULL; - - sid = ss->sec.ci.sid; - PORT_Assert(sid != 0); - - cert = ss->sec.peerCert; - - serverKey = CERT_ExtractPublicKey(cert); - if (!serverKey) { - SSL_DBG(("%d: SSL[%d]: extract public key failed: error=%d", - SSL_GETPID(), ss->fd, PORT_GetError())); - PORT_SetError(SSL_ERROR_BAD_CERTIFICATE); - rv = SECFailure; - goto loser2; - } - - ss->sec.authAlgorithm = ssl_sign_rsa; - ss->sec.keaType = ssl_kea_rsa; - ss->sec.keaKeyBits = \ - ss->sec.authKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey); - - /* Choose a compatible cipher with the server */ - nc = csLen / 3; - cipher = ssl2_ChooseSessionCypher(ss, nc, cs, &keyLen); - if (cipher < 0) { - /* ssl2_ChooseSessionCypher has set error code. */ - ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS); - goto loser; - } - - /* Generate the random keys */ - PK11_GenerateRandom(keyData, sizeof(keyData)); - - /* - ** Next, carve up the keys into clear and encrypted portions. The - ** clear data is taken from the start of keyData and the encrypted - ** portion from the remainder. Note that each of these portions is - ** carved in half, one half for the read-key and one for the - ** write-key. - */ - ca = 0; - - /* We know that cipher is a legit value here, because - * ssl2_ChooseSessionCypher doesn't return bogus values. - */ - ckLen = ssl_Specs[cipher].pubLen; /* cleartext key length. */ - caLen = ssl_Specs[cipher].ivLen; /* IV length. */ - if (caLen) { - PORT_Assert(sizeof iv >= caLen); - PK11_GenerateRandom(iv, caLen); - ca = iv; - } - - /* Fill in session-id */ - rv = ssl2_FillInSID(sid, cipher, keyData, keyLen, - ca, caLen, keyLen << 3, (keyLen - ckLen) << 3, - ss->sec.authAlgorithm, ss->sec.authKeyBits, - ss->sec.keaType, ss->sec.keaKeyBits); - if (rv != SECSuccess) { - goto loser; - } - - SSL_TRC(1, ("%d: SSL[%d]: client, using %s cipher, clear=%d total=%d", - SSL_GETPID(), ss->fd, ssl_cipherName[cipher], - ckLen<<3, keyLen<<3)); - - /* Now setup read and write ciphers */ - rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE); - if (rv != SECSuccess) { - goto loser; - } - - /* - ** Fill in the encryption buffer with some random bytes. Then - ** copy in the portion of the session key we are encrypting. - */ - modulusLen = SECKEY_PublicKeyStrength(serverKey); - rek.data = keyData + ckLen; - rek.len = keyLen - ckLen; - eblock = ssl_FormatSSL2Block(modulusLen, &rek); - if (eblock == NULL) - goto loser; - - /* Set up the padding for version 2 rollback detection. */ - /* XXX We should really use defines here */ - if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - PORT_Assert((modulusLen - rek.len) > 12); - PORT_Memset(eblock + modulusLen - rek.len - 8 - 1, 0x03, 8); - } - ekbuf = (PRUint8*) PORT_Alloc(modulusLen); - if (!ekbuf) - goto loser; - PRINT_BUF(10, (ss, "master key encryption block:", - eblock, modulusLen)); - - /* Encrypt ekitem */ - rv = PK11_PubEncryptRaw(serverKey, ekbuf, eblock, modulusLen, - ss->pkcs11PinArg); - if (rv) - goto loser; - - /* Now we have everything ready to send */ - rv = ssl2_SendSessionKeyMessage(ss, cipher, keyLen << 3, ca, caLen, - keyData, ckLen, ekbuf, modulusLen); - if (rv != SECSuccess) { - goto loser; - } - rv = SECSuccess; - goto done; - - loser: - rv = SECFailure; - - loser2: - done: - PORT_Memset(keyData, 0, sizeof(keyData)); - PORT_ZFree(ekbuf, modulusLen); - PORT_ZFree(eblock, modulusLen); - SECKEY_DestroyPublicKey(serverKey); - return rv; -} - -/************************************************************************/ - -/* - * Called from ssl2_HandleMessage in response to SSL_MT_SERVER_FINISHED message. - * Caller holds recvBufLock and handshakeLock - */ -static void -ssl2_ClientRegSessionID(sslSocket *ss, PRUint8 *s) -{ - sslSessionID *sid = ss->sec.ci.sid; - - /* Record entry in nonce cache */ - if (sid->peerCert == NULL) { - PORT_Memcpy(sid->u.ssl2.sessionID, s, sizeof(sid->u.ssl2.sessionID)); - sid->peerCert = CERT_DupCertificate(ss->sec.peerCert); - - } - if (!ss->opt.noCache && sid->cached == never_cached) - (*ss->sec.cache)(sid); -} - -/* Called from ssl2_HandleMessage() */ -static SECStatus -ssl2_TriggerNextMessage(sslSocket *ss) -{ - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - if ((ss->sec.ci.requiredElements & CIS_HAVE_CERTIFICATE) && - !(ss->sec.ci.sentElements & CIS_HAVE_CERTIFICATE)) { - ss->sec.ci.sentElements |= CIS_HAVE_CERTIFICATE; - rv = ssl2_SendCertificateRequestMessage(ss); - return rv; - } - return SECSuccess; -} - -/* See if it's time to send our finished message, or if the handshakes are -** complete. Send finished message if appropriate. -** Returns SECSuccess unless anything goes wrong. -** -** Called from ssl2_HandleMessage, -** ssl2_HandleVerifyMessage -** ssl2_HandleServerHelloMessage -** ssl2_HandleClientSessionKeyMessage -*/ -static SECStatus -ssl2_TryToFinish(sslSocket *ss) -{ - SECStatus rv; - char e, ef; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - e = ss->sec.ci.elements; - ef = e | CIS_HAVE_FINISHED; - if ((ef & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) { - if (ss->sec.isServer) { - /* Send server finished message if we already didn't */ - rv = ssl2_SendServerFinishedMessage(ss); - } else { - /* Send client finished message if we already didn't */ - rv = ssl2_SendClientFinishedMessage(ss); - } - if (rv != SECSuccess) { - return rv; - } - if ((e & ss->sec.ci.requiredElements) == ss->sec.ci.requiredElements) { - /* Totally finished */ - ss->handshake = 0; - return SECSuccess; - } - } - return SECSuccess; -} - -/* -** Called from ssl2_HandleRequestCertificate -*/ -static SECStatus -ssl2_SignResponse(sslSocket *ss, - SECKEYPrivateKey *key, - SECItem *response) -{ - SGNContext * sgn = NULL; - PRUint8 * challenge; - unsigned int len; - SECStatus rv = SECFailure; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - challenge = ss->sec.ci.serverChallenge; - len = ss->sec.ci.serverChallengeLen; - - /* Sign the expected data... */ - sgn = SGN_NewContext(SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION,key); - if (!sgn) - goto done; - rv = SGN_Begin(sgn); - if (rv != SECSuccess) - goto done; - rv = SGN_Update(sgn, ss->sec.ci.readKey, ss->sec.ci.keySize); - if (rv != SECSuccess) - goto done; - rv = SGN_Update(sgn, ss->sec.ci.writeKey, ss->sec.ci.keySize); - if (rv != SECSuccess) - goto done; - rv = SGN_Update(sgn, challenge, len); - if (rv != SECSuccess) - goto done; - rv = SGN_Update(sgn, ss->sec.peerCert->derCert.data, - ss->sec.peerCert->derCert.len); - if (rv != SECSuccess) - goto done; - rv = SGN_End(sgn, response); - if (rv != SECSuccess) - goto done; - -done: - SGN_DestroyContext(sgn, PR_TRUE); - return rv == SECSuccess ? SECSuccess : SECFailure; -} - -/* -** Try to handle a request-certificate message. Get client's certificate -** and private key and sign a message for the server to see. -** Caller must hold handshakeLock -** -** Called from ssl2_HandleMessage(). -*/ -static int -ssl2_HandleRequestCertificate(sslSocket *ss) -{ - CERTCertificate * cert = NULL; /* app-selected client cert. */ - SECKEYPrivateKey *key = NULL; /* priv key for cert. */ - SECStatus rv; - SECItem response; - int ret = 0; - PRUint8 authType; - - - /* - * These things all need to be initialized before we can "goto loser". - */ - response.data = NULL; - - /* get challenge info from connectionInfo */ - authType = ss->sec.ci.authType; - - if (authType != SSL_AT_MD5_WITH_RSA_ENCRYPTION) { - SSL_TRC(7, ("%d: SSL[%d]: unsupported auth type 0x%x", SSL_GETPID(), - ss->fd, authType)); - goto no_cert_error; - } - - /* Get certificate and private-key from client */ - if (!ss->getClientAuthData) { - SSL_TRC(7, ("%d: SSL[%d]: client doesn't support client-auth", - SSL_GETPID(), ss->fd)); - goto no_cert_error; - } - ret = (*ss->getClientAuthData)(ss->getClientAuthDataArg, ss->fd, - NULL, &cert, &key); - if ( ret == SECWouldBlock ) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - ret = -1; - goto loser; - } - - if (ret) { - goto no_cert_error; - } - - /* check what the callback function returned */ - if ((!cert) || (!key)) { - /* we are missing either the key or cert */ - if (cert) { - /* got a cert, but no key - free it */ - CERT_DestroyCertificate(cert); - cert = NULL; + if (rv == SECWouldBlock) { + /* Progress is blocked waiting for callback completion. */ + SSL_TRC(10, ("%d: SSL[%d]: handshake blocked (need %d)", + SSL_GETPID(), ss->fd, ss->gs.remainder)); + return SECWouldBlock; } - if (key) { - /* got a key, but no cert - free it */ - SECKEY_DestroyPrivateKey(key); - key = NULL; + if (rv == 0) { + /* EOF. Loser */ + PORT_SetError(PR_END_OF_FILE_ERROR); } - goto no_cert_error; - } - - rv = ssl2_SignResponse(ss, key, &response); - if ( rv != SECSuccess ) { - ret = -1; - goto loser; - } - - /* Send response message */ - ret = ssl2_SendCertificateResponseMessage(ss, &cert->derCert, &response); - - /* Now, remember the cert we sent. But first, forget any previous one. */ - if (ss->sec.localCert) { - CERT_DestroyCertificate(ss->sec.localCert); - } - ss->sec.localCert = CERT_DupCertificate(cert); - PORT_Assert(!ss->sec.ci.sid->localCert); - if (ss->sec.ci.sid->localCert) { - CERT_DestroyCertificate(ss->sec.ci.sid->localCert); + return SECFailure; /* rv is < 0 here. */ } - ss->sec.ci.sid->localCert = cert; - cert = NULL; - goto done; - - no_cert_error: - SSL_TRC(7, ("%d: SSL[%d]: no certificate (ret=%d)", SSL_GETPID(), - ss->fd, ret)); - ret = ssl2_SendErrorMessage(ss, SSL_PE_NO_CERTIFICATE); - - loser: - done: - if ( cert ) { - CERT_DestroyCertificate(cert); - } - if ( key ) { - SECKEY_DestroyPrivateKey(key); - } - if ( response.data ) { - PORT_Free(response.data); - } - - return ret; -} - -/* -** Called from ssl2_HandleMessage for SSL_MT_CLIENT_CERTIFICATE message. -** Caller must hold HandshakeLock and RecvBufLock, since cd and response -** are contained in the gathered input data. -*/ -static SECStatus -ssl2_HandleClientCertificate(sslSocket * ss, - PRUint8 certType, /* XXX unused */ - PRUint8 * cd, - unsigned int cdLen, - PRUint8 * response, - unsigned int responseLen) -{ - CERTCertificate *cert = NULL; - SECKEYPublicKey *pubKey = NULL; - VFYContext * vfy = NULL; - SECItem * derCert; - SECStatus rv = SECFailure; - SECItem certItem; - SECItem rep; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - - /* Extract the certificate */ - certItem.data = cd; - certItem.len = cdLen; - - cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL, - PR_FALSE, PR_TRUE); - if (cert == NULL) { - goto loser; - } - - /* save the certificate, since the auth routine will need it */ - ss->sec.peerCert = cert; - - /* Extract the public key */ - pubKey = CERT_ExtractPublicKey(cert); - if (!pubKey) - goto loser; - - /* Verify the response data... */ - rep.data = response; - rep.len = responseLen; - /* SSL 2.0 only supports RSA certs, so we don't have to worry about - * DSA here. */ - vfy = VFY_CreateContext(pubKey, &rep, SEC_OID_PKCS1_RSA_ENCRYPTION, - ss->pkcs11PinArg); - if (!vfy) - goto loser; - rv = VFY_Begin(vfy); - if (rv) - goto loser; - - rv = VFY_Update(vfy, ss->sec.ci.readKey, ss->sec.ci.keySize); - if (rv) - goto loser; - rv = VFY_Update(vfy, ss->sec.ci.writeKey, ss->sec.ci.keySize); - if (rv) - goto loser; - rv = VFY_Update(vfy, ss->sec.ci.serverChallenge, SSL_CHALLENGE_BYTES); - if (rv) - goto loser; - - derCert = &ss->serverCerts[kt_rsa].serverCert->derCert; - rv = VFY_Update(vfy, derCert->data, derCert->len); - if (rv) - goto loser; - rv = VFY_End(vfy); - if (rv) - goto loser; - - /* Now ask the server application if it likes the certificate... */ - rv = (SECStatus) (*ss->authCertificate)(ss->authCertificateArg, - ss->fd, PR_TRUE, PR_TRUE); - /* Hey, it liked it. */ - if (SECSuccess == rv) - goto done; - -loser: - ss->sec.peerCert = NULL; - CERT_DestroyCertificate(cert); - -done: - VFY_DestroyContext(vfy, PR_TRUE); - SECKEY_DestroyPublicKey(pubKey); - return rv; -} - -/* -** Handle remaining messages between client/server. Process finished -** messages from either side and any authentication requests. -** This should only be called for SSLv2 handshake messages, -** not for application data records. -** Caller must hold handshake lock. -** -** Called from ssl_Do1stHandshake(). -** -*/ -static SECStatus -ssl2_HandleMessage(sslSocket *ss) -{ - PRUint8 * data; - PRUint8 * cid; - unsigned len, certType, certLen, responseLen; - int rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - ssl_GetRecvBufLock(ss); - - data = ss->gs.buf.buf + ss->gs.recordOffset; - - if (ss->gs.recordLen < 1) { - goto bad_peer; - } - SSL_TRC(3, ("%d: SSL[%d]: received %d message", - SSL_GETPID(), ss->fd, data[0])); - DUMP_MSG(29, (ss, data, ss->gs.recordLen)); - - switch (data[0]) { - case SSL_MT_CLIENT_FINISHED: - if (ss->sec.ci.elements & CIS_HAVE_FINISHED) { - SSL_DBG(("%d: SSL[%d]: dup client-finished message", - SSL_GETPID(), ss->fd)); - goto bad_peer; - } - - /* See if nonce matches */ - len = ss->gs.recordLen - 1; - cid = data + 1; - if ((len != sizeof(ss->sec.ci.connectionID)) || - (PORT_Memcmp(ss->sec.ci.connectionID, cid, len) != 0)) { - SSL_DBG(("%d: SSL[%d]: bad connection-id", SSL_GETPID(), ss->fd)); - PRINT_BUF(5, (ss, "sent connection-id", - ss->sec.ci.connectionID, - sizeof(ss->sec.ci.connectionID))); - PRINT_BUF(5, (ss, "rcvd connection-id", cid, len)); - goto bad_peer; - } - - SSL_TRC(5, ("%d: SSL[%d]: got client finished, waiting for 0x%d", - SSL_GETPID(), ss->fd, - ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); - ss->sec.ci.elements |= CIS_HAVE_FINISHED; - break; - - case SSL_MT_SERVER_FINISHED: - if (ss->sec.ci.elements & CIS_HAVE_FINISHED) { - SSL_DBG(("%d: SSL[%d]: dup server-finished message", - SSL_GETPID(), ss->fd)); - goto bad_peer; - } - - if (ss->gs.recordLen - 1 != SSL2_SESSIONID_BYTES) { - SSL_DBG(("%d: SSL[%d]: bad server-finished message, len=%d", - SSL_GETPID(), ss->fd, ss->gs.recordLen)); - goto bad_peer; - } - ssl2_ClientRegSessionID(ss, data+1); - SSL_TRC(5, ("%d: SSL[%d]: got server finished, waiting for 0x%d", - SSL_GETPID(), ss->fd, - ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); - ss->sec.ci.elements |= CIS_HAVE_FINISHED; - break; - - case SSL_MT_REQUEST_CERTIFICATE: - len = ss->gs.recordLen - 2; - if ((len < SSL_MIN_CHALLENGE_BYTES) || - (len > SSL_MAX_CHALLENGE_BYTES)) { - /* Bad challenge */ - SSL_DBG(("%d: SSL[%d]: bad cert request message: code len=%d", - SSL_GETPID(), ss->fd, len)); - goto bad_peer; - } - - /* save auth request info */ - ss->sec.ci.authType = data[1]; - ss->sec.ci.serverChallengeLen = len; - PORT_Memcpy(ss->sec.ci.serverChallenge, data + 2, len); - - rv = ssl2_HandleRequestCertificate(ss); - if (rv == SECWouldBlock) { - SSL_TRC(3, ("%d: SSL[%d]: async cert request", - SSL_GETPID(), ss->fd)); - /* someone is handling this asynchronously */ - ssl_ReleaseRecvBufLock(ss); - return SECWouldBlock; - } - if (rv) { - SET_ERROR_CODE - goto loser; - } - break; - - case SSL_MT_CLIENT_CERTIFICATE: - if (!ss->authCertificate) { - /* Server asked for authentication and can't handle it */ - PORT_SetError(SSL_ERROR_BAD_SERVER); - goto loser; - } - if (ss->gs.recordLen < SSL_HL_CLIENT_CERTIFICATE_HBYTES) { - SET_ERROR_CODE - goto loser; - } - certType = data[1]; - certLen = (data[2] << 8) | data[3]; - responseLen = (data[4] << 8) | data[5]; - if (certType != SSL_CT_X509_CERTIFICATE) { - PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE); - goto loser; - } - if (certLen + responseLen + SSL_HL_CLIENT_CERTIFICATE_HBYTES - > ss->gs.recordLen) { - /* prevent overflow crash. */ - rv = SECFailure; - } else - rv = ssl2_HandleClientCertificate(ss, data[1], - data + SSL_HL_CLIENT_CERTIFICATE_HBYTES, - certLen, - data + SSL_HL_CLIENT_CERTIFICATE_HBYTES + certLen, - responseLen); - if (rv) { - (void)ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); - SET_ERROR_CODE - goto loser; - } - ss->sec.ci.elements |= CIS_HAVE_CERTIFICATE; - break; - - case SSL_MT_ERROR: - rv = (data[1] << 8) | data[2]; - SSL_TRC(2, ("%d: SSL[%d]: got error message, error=0x%x", - SSL_GETPID(), ss->fd, rv)); - - /* Convert protocol error number into API error number */ - switch (rv) { - case SSL_PE_NO_CYPHERS: - rv = SSL_ERROR_NO_CYPHER_OVERLAP; - break; - case SSL_PE_NO_CERTIFICATE: - rv = SSL_ERROR_NO_CERTIFICATE; - break; - case SSL_PE_BAD_CERTIFICATE: - rv = SSL_ERROR_BAD_CERTIFICATE; - break; - case SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE: - rv = SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE; - break; - default: - goto bad_peer; - } - /* XXX make certificate-request optionally fail... */ - PORT_SetError(rv); - goto loser; - - default: - SSL_DBG(("%d: SSL[%d]: unknown message %d", - SSL_GETPID(), ss->fd, data[0])); - goto loser; - } - - SSL_TRC(3, ("%d: SSL[%d]: handled %d message, required=0x%x got=0x%x", - SSL_GETPID(), ss->fd, data[0], - ss->sec.ci.requiredElements, ss->sec.ci.elements)); - - rv = ssl2_TryToFinish(ss); - if (rv != SECSuccess) - goto loser; - - ss->gs.recordLen = 0; - ssl_ReleaseRecvBufLock(ss); - - if (ss->handshake == 0) { - return SECSuccess; - } - - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleMessage; - return ssl2_TriggerNextMessage(ss); - - bad_peer: - PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT : SSL_ERROR_BAD_SERVER); - /* FALL THROUGH */ - - loser: - ssl_ReleaseRecvBufLock(ss); - return SECFailure; -} - -/************************************************************************/ - -/* Called from ssl_Do1stHandshake, after ssl2_HandleServerHelloMessage. -*/ -static SECStatus -ssl2_HandleVerifyMessage(sslSocket *ss) -{ - PRUint8 * data; - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - ssl_GetRecvBufLock(ss); - - data = ss->gs.buf.buf + ss->gs.recordOffset; - DUMP_MSG(29, (ss, data, ss->gs.recordLen)); - if ((ss->gs.recordLen != 1 + SSL_CHALLENGE_BYTES) || - (data[0] != SSL_MT_SERVER_VERIFY) || - NSS_SecureMemcmp(data+1, ss->sec.ci.clientChallenge, - SSL_CHALLENGE_BYTES)) { - /* Bad server */ - PORT_SetError(SSL_ERROR_BAD_SERVER); - goto loser; - } - ss->sec.ci.elements |= CIS_HAVE_VERIFY; - - SSL_TRC(5, ("%d: SSL[%d]: got server-verify, required=0x%d got=0x%x", - SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements, - ss->sec.ci.elements)); - - rv = ssl2_TryToFinish(ss); - if (rv) - goto loser; - - ss->gs.recordLen = 0; - ssl_ReleaseRecvBufLock(ss); - - if (ss->handshake == 0) { - return SECSuccess; - } - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleMessage; + ss->handshake = NULL; return SECSuccess; - - - loser: - ssl_ReleaseRecvBufLock(ss); - return SECFailure; } -/* Not static because ssl2_GatherData() tests ss->nextHandshake for this value. - * ICK! - * Called from ssl_Do1stHandshake after ssl2_BeginClientHandshake() - */ -SECStatus -ssl2_HandleServerHelloMessage(sslSocket *ss) +/* 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) { - sslSessionID * sid; - PRUint8 * cert; - PRUint8 * cs; - PRUint8 * data; - SECStatus rv; - unsigned int needed, sidHit, certLen, csLen, cidLen, certType, err; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - if (!ss->opt.enableSSL2) { - PORT_SetError(SSL_ERROR_SSL2_DISABLED); - return SECFailure; - } - - ssl_GetRecvBufLock(ss); - - PORT_Assert(ss->sec.ci.sid != 0); - sid = ss->sec.ci.sid; - - data = ss->gs.buf.buf + ss->gs.recordOffset; - DUMP_MSG(29, (ss, data, ss->gs.recordLen)); - - /* Make sure first message has some data and is the server hello message */ - if ((ss->gs.recordLen < SSL_HL_SERVER_HELLO_HBYTES) - || (data[0] != SSL_MT_SERVER_HELLO)) { - if ((data[0] == SSL_MT_ERROR) && (ss->gs.recordLen == 3)) { - err = (data[1] << 8) | data[2]; - if (err == SSL_PE_NO_CYPHERS) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - goto loser; - } - } - goto bad_server; - } - - sidHit = data[1]; - certType = data[2]; - ss->version = (data[3] << 8) | data[4]; - certLen = (data[5] << 8) | data[6]; - csLen = (data[7] << 8) | data[8]; - cidLen = (data[9] << 8) | data[10]; - cert = data + SSL_HL_SERVER_HELLO_HBYTES; - cs = cert + certLen; - - SSL_TRC(5, - ("%d: SSL[%d]: server-hello, hit=%d vers=%x certLen=%d csLen=%d cidLen=%d", - SSL_GETPID(), ss->fd, sidHit, ss->version, certLen, - csLen, cidLen)); - if (ss->version != SSL_LIBRARY_VERSION_2) { - if (ss->version < SSL_LIBRARY_VERSION_2) { - SSL_TRC(3, ("%d: SSL[%d]: demoting self (%x) to server version (%x)", - SSL_GETPID(), ss->fd, SSL_LIBRARY_VERSION_2, - ss->version)); - } else { - SSL_TRC(1, ("%d: SSL[%d]: server version is %x (we are %x)", - SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2)); - /* server claims to be newer but does not follow protocol */ - PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); - goto loser; - } - } - - if ((SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen + cidLen - > ss->gs.recordLen) - || (csLen % 3) != 0 - /* || cidLen < SSL_CONNECTIONID_BYTES || cidLen > 32 */ - ) { - goto bad_server; + 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; } - - /* Save connection-id. - ** This code only saves the first 16 byte of the connectionID. - ** If the connectionID is shorter than 16 bytes, it is zero-padded. - */ - if (cidLen < sizeof ss->sec.ci.connectionID) - memset(ss->sec.ci.connectionID, 0, sizeof ss->sec.ci.connectionID); - cidLen = PR_MIN(cidLen, sizeof ss->sec.ci.connectionID); - PORT_Memcpy(ss->sec.ci.connectionID, cs + csLen, cidLen); - - /* See if session-id hit */ - needed = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED | CIS_HAVE_VERIFY; - if (sidHit) { - if (certLen || csLen) { - /* Uh oh - bogus server */ - SSL_DBG(("%d: SSL[%d]: client, huh? hit=%d certLen=%d csLen=%d", - SSL_GETPID(), ss->fd, sidHit, certLen, csLen)); - goto bad_server; - } - - /* Total winner. */ - SSL_TRC(1, ("%d: SSL[%d]: client, using nonce for peer=0x%08x " - "port=0x%04x", - SSL_GETPID(), ss->fd, ss->sec.ci.peer, ss->sec.ci.port)); - ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); - ss->sec.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; - rv = ssl2_CreateSessionCypher(ss, sid, PR_TRUE); - if (rv != SECSuccess) { - goto loser; - } - } else { - if (certType != SSL_CT_X509_CERTIFICATE) { - PORT_SetError(SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE); - goto loser; - } - if (csLen == 0) { - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - SSL_DBG(("%d: SSL[%d]: no cipher overlap", - SSL_GETPID(), ss->fd)); - goto loser; - } - if (certLen == 0) { - SSL_DBG(("%d: SSL[%d]: client, huh? certLen=%d csLen=%d", - SSL_GETPID(), ss->fd, certLen, csLen)); - goto bad_server; - } - - if (sid->cached != never_cached) { - /* Forget our session-id - server didn't like it */ - SSL_TRC(7, ("%d: SSL[%d]: server forgot me, uncaching session-id", - SSL_GETPID(), ss->fd)); - if (ss->sec.uncache) - (*ss->sec.uncache)(sid); - ssl_FreeSID(sid); - ss->sec.ci.sid = sid = PORT_ZNew(sslSessionID); - if (!sid) { - goto loser; - } - sid->references = 1; - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; - } - - /* decode the server's certificate */ - rv = ssl2_ClientHandleServerCert(ss, cert, certLen); - if (rv != SECSuccess) { - if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) { - (void) ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); - } - goto loser; - } - - /* Setup new session cipher */ - rv = ssl2_ClientSetupSessionCypher(ss, cs, csLen); - if (rv != SECSuccess) { - if (PORT_GetError() == SSL_ERROR_BAD_CERTIFICATE) { - (void) ssl2_SendErrorMessage(ss, SSL_PE_BAD_CERTIFICATE); - } - goto loser; - } - } - - /* Build up final list of required elements */ - ss->sec.ci.elements = CIS_HAVE_MASTER_KEY; - ss->sec.ci.requiredElements = needed; - - if (!sidHit) { - /* verify the server's certificate. if sidHit, don't check signatures */ - rv = (* ss->authCertificate)(ss->authCertificateArg, ss->fd, - (PRBool)(!sidHit), PR_FALSE); - if (rv) { - if (ss->handleBadCert) { - rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd); - if ( rv ) { - if ( rv == SECWouldBlock ) { - SSL_DBG(("%d: SSL[%d]: SSL2 bad cert handler returned " - "SECWouldBlock", SSL_GETPID(), ss->fd)); - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - rv = SECFailure; - } else { - /* cert is bad */ - SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d", - SSL_GETPID(), ss->fd, PORT_GetError())); - } - goto loser; - } - /* cert is good */ - } else { - SSL_DBG(("%d: SSL[%d]: server certificate is no good: error=%d", - SSL_GETPID(), ss->fd, PORT_GetError())); - goto loser; - } - } - } - /* - ** At this point we have a completed session key and our session - ** cipher is setup and ready to go. Switch to encrypted write routine - ** as all future message data is to be encrypted. - */ - ssl2_UseEncryptedSendFunc(ss); - - rv = ssl2_TryToFinish(ss); - if (rv != SECSuccess) - goto loser; - - ss->gs.recordLen = 0; - - ssl_ReleaseRecvBufLock(ss); - - if (ss->handshake == 0) { - return SECSuccess; - } - - SSL_TRC(5, ("%d: SSL[%d]: got server-hello, required=0x%d got=0x%x", - SSL_GETPID(), ss->fd, ss->sec.ci.requiredElements, - ss->sec.ci.elements)); - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleVerifyMessage; return SECSuccess; - - bad_server: - PORT_SetError(SSL_ERROR_BAD_SERVER); - /* FALL THROUGH */ - - loser: - ssl_ReleaseRecvBufLock(ss); - return SECFailure; } /* Sends out the initial client Hello message on the connection. * Acquires and releases the socket's xmitBufLock. */ SECStatus -ssl2_BeginClientHandshake(sslSocket *ss) +ssl_BeginClientHandshake(sslSocket *ss) { - sslSessionID *sid; - PRUint8 *msg; - PRUint8 *cp; - PRUint8 *localCipherSpecs = NULL; - unsigned int localCipherSize; - unsigned int i; - int sendLen, sidLen = 0; - SECStatus rv; - TLSExtensionData *xtnData; + sslSessionID *sid; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); - ss->sec.isServer = 0; - ss->sec.sendSequence = 0; - ss->sec.rcvSequence = 0; + ss->sec.isServer = PR_FALSE; ssl_ChooseSessionIDProcs(&ss->sec); - if (!ss->cipherSpecs) { - rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess) - goto loser; - } - - /* count the SSL2 and SSL3 enabled ciphers. - * if either is zero, clear the socket's enable for that protocol. - */ - rv = ssl2_CheckConfigSanity(ss); + rv = ssl_CheckConfigSanity(ss); if (rv != SECSuccess) - goto loser; + goto loser; /* Get peer name of server */ rv = ssl_GetPeerInfo(ss); @@ -2990,14 +143,14 @@ ssl2_BeginClientHandshake(sslSocket *ss) */ if (PR_GetError() == PR_NOT_CONNECTED_ERROR) { char dummy; - (void) PR_Write(ss->fd->lower, &dummy, 0); + (void)PR_Write(ss->fd->lower, &dummy, 0); rv = ssl_GetPeerInfo(ss); if (rv < 0) { goto loser; } } #else - goto loser; + goto loser; #endif } @@ -3005,643 +158,73 @@ ssl2_BeginClientHandshake(sslSocket *ss) /* Try to find server in our session-id cache */ if (ss->opt.noCache) { - sid = NULL; + sid = NULL; } else { - sid = ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, - ss->url); + sid = ssl_LookupSID(&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 { + ss->sec.uncache(sid); + ssl_FreeSID(sid); + sid = NULL; + } } - while (sid) { /* this isn't really a loop */ - PRBool sidVersionEnabled = - (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) && - sid->version >= ss->vrange.min && - sid->version <= ss->vrange.max) || - (sid->version < SSL_LIBRARY_VERSION_3_0 && ss->opt.enableSSL2); - - /* if we're not doing this SID's protocol any more, drop it. */ - if (!sidVersionEnabled) { - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - break; - } - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - /* If the cipher in this sid is not enabled, drop it. */ - for (i = 0; i < ss->sizeCipherSpecs; i += 3) { - if (ss->cipherSpecs[i] == sid->u.ssl2.cipherType) - break; - } - if (i >= ss->sizeCipherSpecs) { - if (ss->sec.uncache) - ss->sec.uncache(sid); - ssl_FreeSID(sid); - sid = NULL; - break; - } - } - sidLen = sizeof(sid->u.ssl2.sessionID); - PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl2.sessionID, - sidLen)); - ss->version = sid->version; - PORT_Assert(!ss->sec.localCert); - if (ss->sec.localCert) { - CERT_DestroyCertificate(ss->sec.localCert); - } - ss->sec.localCert = CERT_DupCertificate(sid->localCert); - break; /* this isn't really a loop */ - } if (!sid) { - sidLen = 0; - sid = PORT_ZNew(sslSessionID); - if (!sid) { - goto loser; - } - sid->references = 1; - sid->cached = never_cached; - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; - if (ss->peerID != NULL) { - sid->peerID = PORT_Strdup(ss->peerID); - } - if (ss->url != NULL) { - sid->urlSvrName = PORT_Strdup(ss->url); - } + sid = PORT_ZNew(sslSessionID); + if (!sid) { + goto loser; + } + sid->references = 1; + sid->cached = never_cached; + sid->addr = ss->sec.ci.peer; + sid->port = ss->sec.ci.port; + if (ss->peerID != NULL) { + sid->peerID = PORT_Strdup(ss->peerID); + } + if (ss->url != NULL) { + sid->urlSvrName = PORT_Strdup(ss->url); + } } ss->sec.ci.sid = sid; PORT_Assert(sid != NULL); - if ((sid->version >= SSL_LIBRARY_VERSION_3_0 || !ss->opt.v2CompatibleHello) && - !SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - 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, PR_FALSE); - ssl_ReleaseXmitBufLock(ss); - ssl_ReleaseSSL3HandshakeLock(ss); - - return rv; - } -#ifndef NSS_DISABLE_ECC - /* ensure we don't neogtiate ECC cipher suites with SSL2 hello */ - ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */ - if (ss->cipherSpecs != NULL) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } -#endif /* NSS_DISABLE_ECC */ - - if (!ss->cipherSpecs) { - rv = ssl2_ConstructCipherSpecs(ss); - if (rv < 0) { - return rv; - } - } - localCipherSpecs = ss->cipherSpecs; - localCipherSize = ss->sizeCipherSpecs; - - /* Add 3 for SCSV */ - sendLen = SSL_HL_CLIENT_HELLO_HBYTES + localCipherSize + 3 + sidLen + - SSL_CHALLENGE_BYTES; - - /* Generate challenge bytes for server */ - PK11_GenerateRandom(ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); - - ssl_GetXmitBufLock(ss); /***************************************/ - - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv) - goto unlock_loser; - - /* Construct client-hello message */ - cp = msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_CLIENT_HELLO; - ss->clientHelloVersion = SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) ? - SSL_LIBRARY_VERSION_2 : ss->vrange.max; - - msg[1] = MSB(ss->clientHelloVersion); - msg[2] = LSB(ss->clientHelloVersion); - /* Add 3 for SCSV */ - msg[3] = MSB(localCipherSize + 3); - msg[4] = LSB(localCipherSize + 3); - msg[5] = MSB(sidLen); - msg[6] = LSB(sidLen); - msg[7] = MSB(SSL_CHALLENGE_BYTES); - msg[8] = LSB(SSL_CHALLENGE_BYTES); - cp += SSL_HL_CLIENT_HELLO_HBYTES; - PORT_Memcpy(cp, localCipherSpecs, localCipherSize); - cp += localCipherSize; - /* - * Add SCSV. SSL 2.0 cipher suites are listed before SSL 3.0 cipher - * suites in localCipherSpecs for compatibility with SSL 2.0 servers. - * Since SCSV looks like an SSL 3.0 cipher suite, we can't add it at - * the beginning. - */ - cp[0] = 0x00; - cp[1] = 0x00; - cp[2] = 0xff; - cp += 3; - if (sidLen) { - PORT_Memcpy(cp, sid->u.ssl2.sessionID, sidLen); - cp += sidLen; - } - PORT_Memcpy(cp, ss->sec.ci.clientChallenge, SSL_CHALLENGE_BYTES); - - /* Send it to the server */ - DUMP_MSG(29, (ss, msg, sendLen)); - ss->handshakeBegun = 1; - rv = (*ss->sec.send)(ss, msg, sendLen, 0); - - ssl_ReleaseXmitBufLock(ss); /***************************************/ - - if (rv < 0) { - goto loser; - } - - rv = ssl3_StartHandshakeHash(ss, msg, sendLen); - if (rv < 0) { - goto loser; - } - - /* - * Since we sent the SCSV, pretend we sent empty RI extension. We need - * to record the extension has been advertised after ssl3_InitState has - * been called, which ssl3_StartHandshakeHash took care for us above. - */ - xtnData = &ss->xtnData; - xtnData->advertised[xtnData->numAdvertised++] = ssl_renegotiation_info_xtn; - - /* Setup to receive servers hello message */ - ssl_GetRecvBufLock(ss); - ss->gs.recordLen = 0; - ssl_ReleaseRecvBufLock(ss); + ss->gs.state = GS_INIT; + ss->handshake = ssl_GatherRecord1stHandshake; - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleServerHelloMessage; - return SECSuccess; + /* ssl3_SendClientHello will override this if it succeeds. */ + ss->version = SSL_LIBRARY_VERSION_3_0; -unlock_loser: + ssl_GetSSL3HandshakeLock(ss); + ssl_GetXmitBufLock(ss); + rv = ssl3_SendClientHello(ss, client_hello_initial); ssl_ReleaseXmitBufLock(ss); -loser: - return SECFailure; -} - -/************************************************************************/ + ssl_ReleaseSSL3HandshakeLock(ss); -/* Handle the CLIENT-MASTER-KEY message. -** Acquires and releases RecvBufLock. -** Called from ssl2_HandleClientHelloMessage(). -*/ -static SECStatus -ssl2_HandleClientSessionKeyMessage(sslSocket *ss) -{ - PRUint8 * data; - unsigned int caLen; - unsigned int ckLen; - unsigned int ekLen; - unsigned int keyBits; - int cipher; - SECStatus rv; - - - ssl_GetRecvBufLock(ss); - - data = ss->gs.buf.buf + ss->gs.recordOffset; - DUMP_MSG(29, (ss, data, ss->gs.recordLen)); - - if ((ss->gs.recordLen < SSL_HL_CLIENT_MASTER_KEY_HBYTES) - || (data[0] != SSL_MT_CLIENT_MASTER_KEY)) { - goto bad_client; - } - cipher = data[1]; - keyBits = (data[2] << 8) | data[3]; - ckLen = (data[4] << 8) | data[5]; - ekLen = (data[6] << 8) | data[7]; - caLen = (data[8] << 8) | data[9]; - - SSL_TRC(5, ("%d: SSL[%d]: session-key, cipher=%d keyBits=%d ckLen=%d ekLen=%d caLen=%d", - SSL_GETPID(), ss->fd, cipher, keyBits, ckLen, ekLen, caLen)); - - if (ss->gs.recordLen < - SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen + caLen) { - SSL_DBG(("%d: SSL[%d]: protocol size mismatch dataLen=%d", - SSL_GETPID(), ss->fd, ss->gs.recordLen)); - goto bad_client; - } - - /* Use info from client to setup session key */ - rv = ssl2_ServerSetupSessionCypher(ss, cipher, keyBits, - data + SSL_HL_CLIENT_MASTER_KEY_HBYTES, ckLen, - data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen, ekLen, - data + SSL_HL_CLIENT_MASTER_KEY_HBYTES + ckLen + ekLen, caLen); - ss->gs.recordLen = 0; /* we're done with this record. */ - - ssl_ReleaseRecvBufLock(ss); - - if (rv != SECSuccess) { - goto loser; - } - ss->sec.ci.elements |= CIS_HAVE_MASTER_KEY; - ssl2_UseEncryptedSendFunc(ss); - - /* Send server verify message now that keys are established */ - rv = ssl2_SendServerVerifyMessage(ss); - if (rv != SECSuccess) - goto loser; - - rv = ssl2_TryToFinish(ss); - if (rv != SECSuccess) - goto loser; - if (ss->handshake == 0) { - return SECSuccess; - } - - SSL_TRC(5, ("%d: SSL[%d]: server: waiting for elements=0x%d", - SSL_GETPID(), ss->fd, - ss->sec.ci.requiredElements ^ ss->sec.ci.elements)); - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleMessage; - - return ssl2_TriggerNextMessage(ss); - -bad_client: - ssl_ReleaseRecvBufLock(ss); - PORT_SetError(SSL_ERROR_BAD_CLIENT); - /* FALLTHROUGH */ + return rv; loser: return SECFailure; } -/* -** Handle the initial hello message from the client -** -** not static because ssl2_GatherData() tests ss->nextHandshake for this value. -*/ -SECStatus -ssl2_HandleClientHelloMessage(sslSocket *ss) -{ - sslSessionID *sid; - sslServerCerts * sc; - CERTCertificate *serverCert; - PRUint8 *msg; - PRUint8 *data; - PRUint8 *cs; - PRUint8 *sd; - PRUint8 *cert = NULL; - PRUint8 *challenge; - unsigned int challengeLen; - SECStatus rv; - int csLen; - int sendLen; - int sdLen; - int certLen; - int pid; - int sent; - int gotXmitBufLock = 0; -#if defined(SOLARIS) && defined(i386) - volatile PRUint8 hit; -#else - int hit; -#endif - PRUint8 csImpl[sizeof implementedCipherSuites]; - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - sc = ss->serverCerts + kt_rsa; - serverCert = sc->serverCert; - - ssl_GetRecvBufLock(ss); - - - data = ss->gs.buf.buf + ss->gs.recordOffset; - DUMP_MSG(29, (ss, data, ss->gs.recordLen)); - - /* Make sure first message has some data and is the client hello message */ - if ((ss->gs.recordLen < SSL_HL_CLIENT_HELLO_HBYTES) - || (data[0] != SSL_MT_CLIENT_HELLO)) { - goto bad_client; - } - - /* Get peer name of client */ - rv = ssl_GetPeerInfo(ss); - if (rv != SECSuccess) { - goto loser; - } - - /* Examine version information */ - /* - * See if this might be a V2 client hello asking to use the V3 protocol - */ - if ((data[0] == SSL_MT_CLIENT_HELLO) && - (data[1] >= MSB(SSL_LIBRARY_VERSION_3_0)) && - !SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) { - rv = ssl3_HandleV2ClientHello(ss, data, ss->gs.recordLen); - if (rv != SECFailure) { /* Success */ - ss->handshake = NULL; - ss->nextHandshake = ssl_GatherRecord1stHandshake; - ss->securityHandshake = NULL; - ss->gs.state = GS_INIT; - - /* ssl3_HandleV3ClientHello has set ss->version, - ** and has gotten us a brand new sid. - */ - ss->sec.ci.sid->version = ss->version; - } - ssl_ReleaseRecvBufLock(ss); - return rv; - } - /* Previously, there was a test here to see if SSL2 was enabled. - ** If not, an error code was set, and SECFailure was returned, - ** without sending any error code to the other end of the connection. - ** That test has been removed. If SSL2 has been disabled, there - ** should be no SSL2 ciphers enabled, and consequently, the code - ** below should send the ssl2 error message SSL_PE_NO_CYPHERS. - ** We now believe this is the correct thing to do, even when SSL2 - ** has been explicitly disabled by the application. - */ - - /* Extract info from message */ - ss->version = (data[1] << 8) | data[2]; - - /* If some client thinks ssl v2 is 2.0 instead of 0.2, we'll allow it. */ - if (ss->version >= SSL_LIBRARY_VERSION_3_0) { - ss->version = SSL_LIBRARY_VERSION_2; - } - - csLen = (data[3] << 8) | data[4]; - sdLen = (data[5] << 8) | data[6]; - challengeLen = (data[7] << 8) | data[8]; - cs = data + SSL_HL_CLIENT_HELLO_HBYTES; - sd = cs + csLen; - challenge = sd + sdLen; - PRINT_BUF(7, (ss, "server, client session-id value:", sd, sdLen)); - - if (!csLen || (csLen % 3) != 0 || - (sdLen != 0 && sdLen != SSL2_SESSIONID_BYTES) || - challengeLen < SSL_MIN_CHALLENGE_BYTES || - challengeLen > SSL_MAX_CHALLENGE_BYTES || - (unsigned)ss->gs.recordLen != - SSL_HL_CLIENT_HELLO_HBYTES + csLen + sdLen + challengeLen) { - SSL_DBG(("%d: SSL[%d]: bad client hello message, len=%d should=%d", - SSL_GETPID(), ss->fd, ss->gs.recordLen, - SSL_HL_CLIENT_HELLO_HBYTES+csLen+sdLen+challengeLen)); - goto bad_client; - } - - SSL_TRC(3, ("%d: SSL[%d]: client version is %x", - SSL_GETPID(), ss->fd, ss->version)); - if (ss->version != SSL_LIBRARY_VERSION_2) { - if (ss->version > SSL_LIBRARY_VERSION_2) { - /* - ** Newer client than us. Things are ok because new clients - ** are required to be backwards compatible with old servers. - ** Change version number to our version number so that client - ** knows whats up. - */ - ss->version = SSL_LIBRARY_VERSION_2; - } else { - SSL_TRC(1, ("%d: SSL[%d]: client version is %x (we are %x)", - SSL_GETPID(), ss->fd, ss->version, SSL_LIBRARY_VERSION_2)); - PORT_SetError(SSL_ERROR_UNSUPPORTED_VERSION); - goto loser; - } - } - - /* Qualify cipher specs before returning them to client */ - csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen); - if (csLen == 0) { - /* no overlap, send client our list of supported SSL v2 ciphers. */ - cs = csImpl; - csLen = sizeof implementedCipherSuites; - PORT_Memcpy(cs, implementedCipherSuites, csLen); - csLen = ssl2_QualifyCypherSpecs(ss, cs, csLen); - if (csLen == 0) { - /* We don't support any SSL v2 ciphers! */ - ssl2_SendErrorMessage(ss, SSL_PE_NO_CYPHERS); - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - goto loser; - } - /* Since this handhsake is going to fail, don't cache it. */ - ss->opt.noCache = 1; - } - - /* Squirrel away the challenge for later */ - PORT_Memcpy(ss->sec.ci.clientChallenge, challenge, challengeLen); - - /* Examine message and see if session-id is good */ - ss->sec.ci.elements = 0; - if (sdLen > 0 && !ss->opt.noCache) { - SSL_TRC(7, ("%d: SSL[%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])); - sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sd, sdLen, ss->dbHandle); - } else { - sid = NULL; - } - if (sid) { - /* Got a good session-id. Short cut! */ - SSL_TRC(1, ("%d: SSL[%d]: server, using session-id for 0x%08x (age=%d)", - SSL_GETPID(), ss->fd, ss->sec.ci.peer, - ssl_Time() - sid->creationTime)); - PRINT_BUF(1, (ss, "session-id value:", sd, sdLen)); - ss->sec.ci.sid = sid; - ss->sec.ci.elements = CIS_HAVE_MASTER_KEY; - hit = 1; - certLen = 0; - csLen = 0; - - ss->sec.authAlgorithm = sid->authAlgorithm; - ss->sec.authKeyBits = sid->authKeyBits; - ss->sec.keaType = sid->keaType; - ss->sec.keaKeyBits = sid->keaKeyBits; - - rv = ssl2_CreateSessionCypher(ss, sid, PR_FALSE); - if (rv != SECSuccess) { - goto loser; - } - } else { - SECItem * derCert = &serverCert->derCert; - - SSL_TRC(7, ("%d: SSL[%d]: server, lookup nonce missed", - SSL_GETPID(), ss->fd)); - if (!serverCert) { - SET_ERROR_CODE - goto loser; - } - hit = 0; - sid = PORT_ZNew(sslSessionID); - if (!sid) { - goto loser; - } - sid->references = 1; - sid->addr = ss->sec.ci.peer; - sid->port = ss->sec.ci.port; - - /* Invent a session-id */ - ss->sec.ci.sid = sid; - PK11_GenerateRandom(sid->u.ssl2.sessionID+2, SSL2_SESSIONID_BYTES-2); - - pid = SSL_GETPID(); - sid->u.ssl2.sessionID[0] = MSB(pid); - sid->u.ssl2.sessionID[1] = LSB(pid); - cert = derCert->data; - certLen = derCert->len; - - /* pretend that server sids remember the local cert. */ - PORT_Assert(!sid->localCert); - if (sid->localCert) { - CERT_DestroyCertificate(sid->localCert); - } - sid->localCert = CERT_DupCertificate(serverCert); - - ss->sec.authAlgorithm = ssl_sign_rsa; - ss->sec.keaType = ssl_kea_rsa; - ss->sec.keaKeyBits = \ - ss->sec.authKeyBits = ss->serverCerts[kt_rsa].serverKeyBits; - } - - /* server sids don't remember the local cert, so whether we found - ** a sid or not, just "remember" we used the rsa server cert. - */ - if (ss->sec.localCert) { - CERT_DestroyCertificate(ss->sec.localCert); - } - ss->sec.localCert = CERT_DupCertificate(serverCert); - - /* Build up final list of required elements */ - ss->sec.ci.requiredElements = CIS_HAVE_MASTER_KEY | CIS_HAVE_FINISHED; - if (ss->opt.requestCertificate) { - ss->sec.ci.requiredElements |= CIS_HAVE_CERTIFICATE; - } - ss->sec.ci.sentElements = 0; - - /* Send hello message back to client */ - sendLen = SSL_HL_SERVER_HELLO_HBYTES + certLen + csLen - + SSL_CONNECTIONID_BYTES; - - ssl_GetXmitBufLock(ss); gotXmitBufLock = 1; - rv = ssl2_GetSendBuffer(ss, sendLen); - if (rv != SECSuccess) { - goto loser; - } - - SSL_TRC(3, ("%d: SSL[%d]: sending server-hello (%d)", - SSL_GETPID(), ss->fd, sendLen)); - - msg = ss->sec.ci.sendBuf.buf; - msg[0] = SSL_MT_SERVER_HELLO; - msg[1] = hit; - msg[2] = SSL_CT_X509_CERTIFICATE; - msg[3] = MSB(ss->version); - msg[4] = LSB(ss->version); - msg[5] = MSB(certLen); - msg[6] = LSB(certLen); - msg[7] = MSB(csLen); - msg[8] = LSB(csLen); - msg[9] = MSB(SSL_CONNECTIONID_BYTES); - msg[10] = LSB(SSL_CONNECTIONID_BYTES); - if (certLen) { - PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES, cert, certLen); - } - if (csLen) { - PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen, cs, csLen); - } - PORT_Memcpy(msg+SSL_HL_SERVER_HELLO_HBYTES+certLen+csLen, - ss->sec.ci.connectionID, SSL_CONNECTIONID_BYTES); - - DUMP_MSG(29, (ss, msg, sendLen)); - - ss->handshakeBegun = 1; - sent = (*ss->sec.send)(ss, msg, sendLen, 0); - if (sent < 0) { - goto loser; - } - ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0; - - ss->gs.recordLen = 0; - ss->handshake = ssl_GatherRecord1stHandshake; - if (hit) { - /* Old SID Session key is good. Go encrypted */ - ssl2_UseEncryptedSendFunc(ss); - - /* Send server verify message now that keys are established */ - rv = ssl2_SendServerVerifyMessage(ss); - if (rv != SECSuccess) - goto loser; - - ss->nextHandshake = ssl2_HandleMessage; - ssl_ReleaseRecvBufLock(ss); - rv = ssl2_TriggerNextMessage(ss); - return rv; - } - ss->nextHandshake = ssl2_HandleClientSessionKeyMessage; - ssl_ReleaseRecvBufLock(ss); - return SECSuccess; - - bad_client: - PORT_SetError(SSL_ERROR_BAD_CLIENT); - /* FALLTHROUGH */ - - loser: - if (gotXmitBufLock) { - ssl_ReleaseXmitBufLock(ss); gotXmitBufLock = 0; - } - SSL_TRC(10, ("%d: SSL[%d]: server, wait for client-hello lossage", - SSL_GETPID(), ss->fd)); - ssl_ReleaseRecvBufLock(ss); - return SECFailure; -} - SECStatus -ssl2_BeginServerHandshake(sslSocket *ss) +ssl_BeginServerHandshake(sslSocket *ss) { - SECStatus rv; - sslServerCerts * rsaAuth = ss->serverCerts + kt_rsa; + SECStatus rv; - ss->sec.isServer = 1; + ss->sec.isServer = PR_TRUE; + ss->ssl3.hs.ws = wait_client_hello; ssl_ChooseSessionIDProcs(&ss->sec); - ss->sec.sendSequence = 0; - ss->sec.rcvSequence = 0; - - /* don't turn on SSL2 if we don't have an RSA key and cert */ - if (!rsaAuth->serverKeyPair || !rsaAuth->SERVERKEY || - !rsaAuth->serverCert) { - ss->opt.enableSSL2 = PR_FALSE; - } - if (!ss->cipherSpecs) { - rv = ssl2_ConstructCipherSpecs(ss); - if (rv != SECSuccess) - goto loser; - } - - /* count the SSL2 and SSL3 enabled ciphers. - * if either is zero, clear the socket's enable for that protocol. - */ - rv = ssl2_CheckConfigSanity(ss); + rv = ssl_CheckConfigSanity(ss); if (rv != SECSuccess) - goto loser; + goto loser; - /* - ** Generate connection-id. Always do this, even if things fail - ** immediately. This way the random number generator is always - ** rolling around, every time we get a connection. - */ - PK11_GenerateRandom(ss->sec.ci.connectionID, - sizeof(ss->sec.ci.connectionID)); - - ss->gs.recordLen = 0; - ss->handshake = ssl_GatherRecord1stHandshake; - ss->nextHandshake = ssl2_HandleClientHelloMessage; + ss->handshake = ssl_GatherRecord1stHandshake; return SECSuccess; loser: @@ -3649,7 +232,7 @@ loser: } /* This function doesn't really belong in this file. -** It's here to keep AIX compilers from optimizing it away, +** It's here to keep AIX compilers from optimizing it away, ** and not including it in the DSO. */ diff --git a/nss/lib/ssl/ssldef.c b/nss/lib/ssl/ssldef.c index cc3ecc8..77a744c 100644 --- a/nss/lib/ssl/ssldef.c +++ b/nss/lib/ssl/ssldef.c @@ -10,14 +10,18 @@ #include "sslimpl.h" #if defined(WIN32) -#define MAP_ERROR(from,to) if (err == from) { PORT_SetError(to); } -#define DEFINE_ERROR PRErrorCode err = PR_GetError(); +#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 MAP_ERROR(from, to) #define DEFINE_ERROR #endif -int ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa) +int +ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -26,7 +30,8 @@ int ssl_DefConnect(sslSocket *ss, const PRNetAddr *sa) return rv; } -int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr) +int +ssl_DefBind(sslSocket *ss, const PRNetAddr *addr) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -35,7 +40,8 @@ int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr) return rv; } -int ssl_DefListen(sslSocket *ss, int backlog) +int +ssl_DefListen(sslSocket *ss, int backlog) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -44,7 +50,8 @@ int ssl_DefListen(sslSocket *ss, int backlog) return rv; } -int ssl_DefShutdown(sslSocket *ss, int how) +int +ssl_DefShutdown(sslSocket *ss, int how) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -53,19 +60,20 @@ int ssl_DefShutdown(sslSocket *ss, int how) return rv; } -int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags) +int +ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags) { PRFileDesc *lower = ss->fd->lower; int rv; 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) + 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; + PORT_Assert(rv <= len); + PORT_SetError(PR_BUFFER_OVERFLOW_ERROR); + rv = SECFailure; } return rv; } @@ -73,87 +81,91 @@ int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags) /* 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. + * Returns positive count if any data was written, else returns SECFailure. * Short writes may occur. Does not return SECWouldBlock. */ -int ssl_DefSend(sslSocket *ss, const unsigned char *buf, int len, int flags) +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 + /* 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; + 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; - } + 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) +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) + 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) +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; + 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) +int +ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -162,7 +174,8 @@ int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name) return rv; } -int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name) +int +ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name) { PRFileDesc *lower = ss->fd->lower; int rv; @@ -171,22 +184,23 @@ int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name) return rv; } -int ssl_DefClose(sslSocket *ss) +int +ssl_DefClose(sslSocket *ss) { PRFileDesc *fd; PRFileDesc *popped; - int rv; + int rv; - fd = ss->fd; + fd = ss->fd; - /* First, remove the SSL layer PRFileDesc from the socket's stack, + /* 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; + PORT_SetError(PR_BAD_DESCRIPTOR_ERROR); + return SECFailure; } ss->fd = NULL; @@ -194,17 +208,17 @@ int ssl_DefClose(sslSocket *ss) ** 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 = 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. + ** 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())); + SSL_GETPID(), fd, rv, PORT_GetError())); return rv; } diff --git a/nss/lib/ssl/sslenum.c b/nss/lib/ssl/sslenum.c index f69aed2..b5272d4 100644 --- a/nss/lib/ssl/sslenum.c +++ b/nss/lib/ssl/sslenum.c @@ -22,7 +22,11 @@ * * 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, order by symmetric encryption algorithm: + * * 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. @@ -30,16 +34,20 @@ * 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 four cipher - * suites, with the MSB zeroed, look like: - * TLS_KRB5_EXPORT_WITH_RC4_40_MD5 { 0x00,0x2B } + * 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 } @@ -47,9 +55,16 @@ * the third one. */ const PRUint16 SSL_ImplementedCiphers[] = { -#ifndef NSS_DISABLE_ECC + 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. */ @@ -59,14 +74,18 @@ const PRUint16 SSL_ImplementedCiphers[] = { 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, -#endif /* NSS_DISABLE_ECC */ 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, @@ -83,7 +102,6 @@ const PRUint16 SSL_ImplementedCiphers[] = { TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_DHE_DSS_WITH_RC4_128_SHA, -#ifndef NSS_DISABLE_ECC TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, @@ -92,9 +110,9 @@ const PRUint16 SSL_ImplementedCiphers[] = { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, -#endif /* NSS_DISABLE_ECC */ 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, @@ -102,7 +120,6 @@ const PRUint16 SSL_ImplementedCiphers[] = { TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, TLS_RSA_WITH_SEED_CBC_SHA, - SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_RC4_128_MD5, @@ -110,44 +127,24 @@ const PRUint16 SSL_ImplementedCiphers[] = { /* 56-bit DES "domestic" cipher suites */ TLS_DHE_RSA_WITH_DES_CBC_SHA, TLS_DHE_DSS_WITH_DES_CBC_SHA, - SSL_RSA_FIPS_WITH_DES_CBC_SHA, TLS_RSA_WITH_DES_CBC_SHA, - /* export ciphersuites with 1024-bit public key exchange keys */ - TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, - TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, - - /* export ciphersuites with 512-bit public key exchange keys */ - TLS_RSA_EXPORT_WITH_RC4_40_MD5, - TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - /* ciphersuites with no encryption */ -#ifndef NSS_DISABLE_ECC TLS_ECDHE_ECDSA_WITH_NULL_SHA, TLS_ECDHE_RSA_WITH_NULL_SHA, TLS_ECDH_RSA_WITH_NULL_SHA, TLS_ECDH_ECDSA_WITH_NULL_SHA, -#endif /* NSS_DISABLE_ECC */ TLS_RSA_WITH_NULL_SHA, TLS_RSA_WITH_NULL_SHA256, TLS_RSA_WITH_NULL_MD5, - /* SSL2 cipher suites. */ - SSL_EN_RC4_128_WITH_MD5, - SSL_EN_RC2_128_CBC_WITH_MD5, - SSL_EN_DES_192_EDE3_CBC_WITH_MD5, /* actually 112, not 192 */ - SSL_EN_DES_64_CBC_WITH_MD5, - SSL_EN_RC4_128_EXPORT40_WITH_MD5, - SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, - 0 - }; -const PRUint16 SSL_NumImplementedCiphers = +const PRUint16 SSL_NumImplementedCiphers = (sizeof SSL_ImplementedCiphers) / (sizeof SSL_ImplementedCiphers[0]) - 1; -const PRUint16 * +const PRUint16* SSL_GetImplementedCiphers(void) { return SSL_ImplementedCiphers; diff --git a/nss/lib/ssl/sslerr.c b/nss/lib/ssl/sslerr.c index f827221..edb9412 100644 --- a/nss/lib/ssl/sslerr.c +++ b/nss/lib/ssl/sslerr.c @@ -1,5 +1,5 @@ /* - * Function to set error code only when meaningful error has not already + * 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 @@ -12,30 +12,30 @@ #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 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(); + 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; + 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; + default: /* leave the majority of error codes alone. */ + return oldErr; } } diff --git a/nss/lib/ssl/sslerr.h b/nss/lib/ssl/sslerr.h index 192a107..751c335 100644 --- a/nss/lib/ssl/sslerr.h +++ b/nss/lib/ssl/sslerr.h @@ -7,6 +7,7 @@ #ifndef __SSL_ERR_H_ #define __SSL_ERR_H_ +/* clang-format off */ #define SSL_ERROR_BASE (-0x3000) #define SSL_ERROR_LIMIT (SSL_ERROR_BASE + 1000) @@ -16,200 +17,237 @@ #ifndef NO_SECURITY_ERROR_ENUM typedef enum { -SSL_ERROR_EXPORT_ONLY_SERVER = (SSL_ERROR_BASE + 0), -SSL_ERROR_US_ONLY_SERVER = (SSL_ERROR_BASE + 1), -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), -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), -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), -SSL_ERROR_BAD_CERT_DOMAIN = (SSL_ERROR_BASE + 12), -SSL_ERROR_POST_WARNING = (SSL_ERROR_BASE + 13), -SSL_ERROR_SSL2_DISABLED = (SSL_ERROR_BASE + 14), -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), -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), /* don't use */ -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), -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 became obsolete in NSS 3.14. */ -SSL_ERROR_NO_TRUSTED_SSL_CLIENT_CA = (SSL_ERROR_BASE + 89), -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), -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_END_OF_LIST /* let the c compiler determine the value of this. */ + 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), + 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_END_OF_LIST /* let the c compiler determine the value of this. */ } SSLErrorCodes; #endif /* NO_SECURITY_ERROR_ENUM */ +/* clang-format on */ + #endif /* __SSL_ERR_H_ */ diff --git a/nss/lib/ssl/sslerrstrs.c b/nss/lib/ssl/sslerrstrs.c index 34f4ea9..4e3db6d 100644 --- a/nss/lib/ssl/sslerrstrs.c +++ b/nss/lib/ssl/sslerrstrs.c @@ -7,20 +7,21 @@ #include "nssutil.h" #include "ssl.h" -#define ER3(name, value, str) {#name, str}, +#define ER3(name, value, str) { #name, str }, static const struct PRErrorMessage ssltext[] = { #include "SSLerrs.h" - {0,0} + { 0, 0 } }; static const struct PRErrorTable ssl_et = { ssltext, "sslerr", SSL_ERROR_BASE, - (sizeof ssltext)/(sizeof ssltext[0]) + (sizeof ssltext) / (sizeof ssltext[0]) }; static PRStatus -ssl_InitializePRErrorTableOnce(void) { +ssl_InitializePRErrorTableOnce(void) +{ return PR_ErrorInstallTable(&ssl_et); } @@ -30,5 +31,6 @@ SECStatus ssl_InitializePRErrorTable(void) { return (PR_SUCCESS == PR_CallOnce(&once, ssl_InitializePRErrorTableOnce)) - ? SECSuccess : SECFailure; + ? SECSuccess + : SECFailure; } diff --git a/nss/lib/ssl/sslgathr.c b/nss/lib/ssl/sslgathr.c deleted file mode 100644 index bdf470b..0000000 --- a/nss/lib/ssl/sslgathr.c +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Gather (Read) entire SSL2 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" - -/* Forward static declarations */ -static SECStatus ssl2_HandleV3HandshakeRecord(sslSocket *ss); - -/* -** Gather a single record of data from the receiving stream. This code -** first gathers the header (2 or 3 bytes long depending on the value of -** the most significant bit in the first byte) then gathers up the data -** for the record into gs->buf. This code handles non-blocking I/O -** and is to be called multiple times until ss->sec.recordLen != 0. -** This function decrypts the gathered record in place, in gs_buf. - * - * Caller must hold RecvBufLock. - * - * Returns +1 when it has gathered a complete SSLV2 record. - * Returns 0 if it hits EOF. - * Returns -1 (SECFailure) on any error - * Returns -2 (SECWouldBlock) when it gathers an SSL v3 client hello header. -** -** The SSL2 Gather State machine has 4 states: -** GS_INIT - Done reading in previous record. Haven't begun to read in -** next record. When ssl2_GatherData is called with the machine -** in this state, the machine will attempt to read the first 3 -** bytes of the SSL2 record header, and will advance the state -** to GS_HEADER. -** -** GS_HEADER - The machine is in this state while waiting for the completion -** of the first 3 bytes of the SSL2 record. When complete, the -** machine will compute the remaining unread length of this record -** and will initiate a read of that many bytes. The machine will -** advance to one of two states, depending on whether the record -** is encrypted (GS_MAC), or unencrypted (GS_DATA). -** -** GS_MAC - The machine is in this state while waiting for the remainder -** of the SSL2 record to be read in. When the read is completed, -** the machine checks the record for valid length, decrypts it, -** and checks and discards the MAC, then advances to GS_INIT. -** -** GS_DATA - The machine is in this state while waiting for the remainder -** of the unencrypted SSL2 record to be read in. Upon completion, -** the machine advances to the GS_INIT state and returns the data. -*/ -int -ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags) -{ - unsigned char * bp; - unsigned char * pBuf; - int nb, err, rv; - - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - - if (gs->state == GS_INIT) { - /* Initialize gathering engine */ - gs->state = GS_HEADER; - gs->remainder = 3; - gs->count = 3; - gs->offset = 0; - gs->recordLen = 0; - gs->recordPadding = 0; - gs->hdr[2] = 0; - - gs->writeOffset = 0; - gs->readOffset = 0; - } - if (gs->encrypted) { - PORT_Assert(ss->sec.hash != 0); - } - - pBuf = gs->buf.buf; - for (;;) { - SSL_TRC(30, ("%d: SSL[%d]: gather state %d (need %d more)", - SSL_GETPID(), ss->fd, gs->state, gs->remainder)); - bp = ((gs->state != GS_HEADER) ? pBuf : gs->hdr) + gs->offset; - nb = ssl_DefRecv(ss, bp, gs->remainder, flags); - if (nb > 0) { - PRINT_BUF(60, (ss, "raw gather data:", bp, nb)); - } - if (nb == 0) { - /* EOF */ - SSL_TRC(30, ("%d: SSL[%d]: EOF", SSL_GETPID(), ss->fd)); - rv = 0; - break; - } - if (nb < 0) { - SSL_DBG(("%d: SSL[%d]: recv error %d", SSL_GETPID(), ss->fd, - PR_GetError())); - rv = SECFailure; - break; - } - - gs->offset += nb; - gs->remainder -= nb; - - if (gs->remainder > 0) { - continue; - } - - /* Probably finished this piece */ - switch (gs->state) { - case GS_HEADER: - if (!SSL3_ALL_VERSIONS_DISABLED(&ss->vrange) && !ss->firstHsDone) { - - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - /* If this looks like an SSL3 handshake record, - ** and we're expecting an SSL2 Hello message from our peer, - ** handle it here. - */ - if (gs->hdr[0] == content_handshake) { - if ((ss->nextHandshake == ssl2_HandleClientHelloMessage) || - (ss->nextHandshake == ssl2_HandleServerHelloMessage)) { - rv = ssl2_HandleV3HandshakeRecord(ss); - if (rv == SECFailure) { - return SECFailure; - } - } - /* XXX_1 The call stack to here is: - * ssl_Do1stHandshake -> ssl_GatherRecord1stHandshake -> - * ssl2_GatherRecord -> here. - * We want to return all the way out to ssl_Do1stHandshake, - * and have it call ssl_GatherRecord1stHandshake again. - * ssl_GatherRecord1stHandshake will call - * ssl3_GatherCompleteHandshake when it is called again. - * - * Returning SECWouldBlock here causes - * ssl_GatherRecord1stHandshake to return without clearing - * ss->handshake, ensuring that ssl_Do1stHandshake will - * call it again immediately. - * - * If we return 1 here, ssl_GatherRecord1stHandshake will - * clear ss->handshake before returning, and thus will not - * be called again by ssl_Do1stHandshake. - */ - return SECWouldBlock; - } else if (gs->hdr[0] == content_alert) { - if (ss->nextHandshake == ssl2_HandleServerHelloMessage) { - /* XXX This is a hack. We're assuming that any failure - * XXX on the client hello is a failure to match - * XXX ciphers. - */ - PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP); - return SECFailure; - } - } - } - - /* we've got the first 3 bytes. The header may be two or three. */ - if (gs->hdr[0] & 0x80) { - /* This record has a 2-byte header, and no padding */ - gs->count = ((gs->hdr[0] & 0x7f) << 8) | gs->hdr[1]; - gs->recordPadding = 0; - } else { - /* This record has a 3-byte header that is all read in now. */ - gs->count = ((gs->hdr[0] & 0x3f) << 8) | gs->hdr[1]; - /* is_escape = (gs->hdr[0] & 0x40) != 0; */ - gs->recordPadding = gs->hdr[2]; - } - if (!gs->count) { - PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG); - goto cleanup; - } - - if (gs->count > gs->buf.space) { - err = sslBuffer_Grow(&gs->buf, gs->count); - if (err) { - return err; - } - pBuf = gs->buf.buf; - } - - - if (gs->hdr[0] & 0x80) { - /* we've already read in the first byte of the body. - ** Put it into the buffer. - */ - pBuf[0] = gs->hdr[2]; - gs->offset = 1; - gs->remainder = gs->count - 1; - } else { - gs->offset = 0; - gs->remainder = gs->count; - } - - if (gs->encrypted) { - gs->state = GS_MAC; - gs->recordLen = gs->count - gs->recordPadding - - ss->sec.hash->length; - } else { - gs->state = GS_DATA; - gs->recordLen = gs->count; - } - - break; - - - case GS_MAC: - /* Have read in entire rest of the ciphertext. - ** Check for valid length. - ** Decrypt it. - ** Check the MAC. - */ - PORT_Assert(gs->encrypted); - - { - unsigned int macLen; - int nout; - unsigned char mac[SSL_MAX_MAC_BYTES]; - - ssl_GetSpecReadLock(ss); /**********************************/ - - /* If this is a stream cipher, blockSize will be 1, - * and this test will always be false. - * If this is a block cipher, this will detect records - * that are not a multiple of the blocksize in length. - */ - if (gs->count & (ss->sec.blockSize - 1)) { - /* This is an error. Sender is misbehaving */ - SSL_DBG(("%d: SSL[%d]: sender, count=%d blockSize=%d", - SSL_GETPID(), ss->fd, gs->count, - ss->sec.blockSize)); - PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); - rv = SECFailure; - goto spec_locked_done; - } - PORT_Assert(gs->count == gs->offset); - - if (gs->offset == 0) { - rv = 0; /* means EOF. */ - goto spec_locked_done; - } - - /* Decrypt the portion of data that we just received. - ** Decrypt it in place. - */ - rv = (*ss->sec.dec)(ss->sec.readcx, pBuf, &nout, gs->offset, - pBuf, gs->offset); - if (rv != SECSuccess) { - goto spec_locked_done; - } - - - /* Have read in all the MAC portion of record - ** - ** Prepare MAC by resetting it and feeding it the shared secret - */ - macLen = ss->sec.hash->length; - if (gs->offset >= macLen) { - PRUint32 sequenceNumber = ss->sec.rcvSequence++; - unsigned char seq[4]; - - seq[0] = (unsigned char) (sequenceNumber >> 24); - seq[1] = (unsigned char) (sequenceNumber >> 16); - seq[2] = (unsigned char) (sequenceNumber >> 8); - seq[3] = (unsigned char) (sequenceNumber); - - (*ss->sec.hash->begin)(ss->sec.hashcx); - (*ss->sec.hash->update)(ss->sec.hashcx, ss->sec.rcvSecret.data, - ss->sec.rcvSecret.len); - (*ss->sec.hash->update)(ss->sec.hashcx, pBuf + macLen, - gs->offset - macLen); - (*ss->sec.hash->update)(ss->sec.hashcx, seq, 4); - (*ss->sec.hash->end)(ss->sec.hashcx, mac, &macLen, macLen); - - PORT_Assert(macLen == ss->sec.hash->length); - - ssl_ReleaseSpecReadLock(ss); /******************************/ - - if (NSS_SecureMemcmp(mac, pBuf, macLen) != 0) { - /* MAC's didn't match... */ - SSL_DBG(("%d: SSL[%d]: mac check failed, seq=%d", - SSL_GETPID(), ss->fd, ss->sec.rcvSequence)); - PRINT_BUF(1, (ss, "computed mac:", mac, macLen)); - PRINT_BUF(1, (ss, "received mac:", pBuf, macLen)); - PORT_SetError(SSL_ERROR_BAD_MAC_READ); - rv = SECFailure; - goto cleanup; - } - } else { - ssl_ReleaseSpecReadLock(ss); /******************************/ - } - - if (gs->recordPadding + macLen <= gs->offset) { - gs->recordOffset = macLen; - gs->readOffset = macLen; - gs->writeOffset = gs->offset - gs->recordPadding; - rv = 1; - } else { - PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); -cleanup: - /* nothing in the buffer any more. */ - gs->recordOffset = 0; - gs->readOffset = 0; - gs->writeOffset = 0; - rv = SECFailure; - } - - gs->recordLen = gs->writeOffset - gs->readOffset; - gs->recordPadding = 0; /* forget we did any padding. */ - gs->state = GS_INIT; - - - if (rv > 0) { - PRINT_BUF(50, (ss, "recv clear record:", - pBuf + gs->recordOffset, gs->recordLen)); - } - return rv; - -spec_locked_done: - ssl_ReleaseSpecReadLock(ss); - return rv; - } - - case GS_DATA: - /* Have read in all the DATA portion of record */ - - gs->recordOffset = 0; - gs->readOffset = 0; - gs->writeOffset = gs->offset; - PORT_Assert(gs->recordLen == gs->writeOffset - gs->readOffset); - gs->recordLen = gs->offset; - gs->recordPadding = 0; - gs->state = GS_INIT; - - ++ss->sec.rcvSequence; - - PRINT_BUF(50, (ss, "recv clear record:", - pBuf + gs->recordOffset, gs->recordLen)); - return 1; - - } /* end switch gs->state */ - } /* end gather loop. */ - return rv; -} - -/* -** Gather a single record of data from the receiving stream. This code -** first gathers the header (2 or 3 bytes long depending on the value of -** the most significant bit in the first byte) then gathers up the data -** for the record into the readBuf. This code handles non-blocking I/O -** and is to be called multiple times until ss->sec.recordLen != 0. - * - * Returns +1 when it has gathered a complete SSLV2 record. - * Returns 0 if it hits EOF. - * Returns -1 (SECFailure) on any error - * Returns -2 (SECWouldBlock) - * - * Called by ssl_GatherRecord1stHandshake in sslcon.c, - * and by DoRecv in sslsecur.c - * Caller must hold RecvBufLock. - */ -int -ssl2_GatherRecord(sslSocket *ss, int flags) -{ - return ssl2_GatherData(ss, &ss->gs, flags); -} - -/* Caller should hold RecvBufLock. */ -SECStatus -ssl_InitGather(sslGather *gs) -{ - SECStatus status; - - gs->state = GS_INIT; - gs->writeOffset = 0; - gs->readOffset = 0; - gs->dtlsPacketOffset = 0; - gs->dtlsPacket.len = 0; - status = sslBuffer_Grow(&gs->buf, 4096); - return status; -} - -/* Caller must hold RecvBufLock. */ -void -ssl_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); - } -} - -/* Caller must hold RecvBufLock. */ -static SECStatus -ssl2_HandleV3HandshakeRecord(sslSocket *ss) -{ - SECStatus rv; - - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - - /* We've read in 3 bytes, there are 2 more to go in an ssl3 header. */ - ss->gs.remainder = 2; - ss->gs.count = 0; - - /* Clearing these handshake pointers ensures that - * ssl_Do1stHandshake won't call ssl2_HandleMessage when we return. - */ - ss->nextHandshake = 0; - ss->securityHandshake = 0; - - /* Setting ss->version to an SSL 3.x value will cause - ** ssl_GatherRecord1stHandshake to invoke ssl3_GatherCompleteHandshake() - ** the next time it is called. - **/ - rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED, - PR_TRUE); - if (rv != SECSuccess) { - return rv; - } - - ss->sec.send = ssl3_SendApplicationData; - - return SECSuccess; -} diff --git a/nss/lib/ssl/sslgrp.c b/nss/lib/ssl/sslgrp.c new file mode 100644 index 0000000..eb53ad3 --- /dev/null +++ b/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/nss/lib/ssl/sslimpl.h b/nss/lib/ssl/sslimpl.h index ad31aae..09c3783 100644 --- a/nss/lib/ssl/sslimpl.h +++ b/nss/lib/ssl/sslimpl.h @@ -29,46 +29,41 @@ #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; + +#include "ssl3ext.h" + /* 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 SSLKEAType SSL3KEAType; typedef SSLMACAlgorithm SSL3MACAlgorithm; -typedef SSLSignType SSL3SignType; - -#define sign_null ssl_sign_null -#define sign_rsa ssl_sign_rsa -#define sign_dsa ssl_sign_dsa -#define sign_ecdsa ssl_sign_ecdsa - -#define calg_null ssl_calg_null -#define calg_rc4 ssl_calg_rc4 -#define calg_rc2 ssl_calg_rc2 -#define calg_des ssl_calg_des -#define calg_3des ssl_calg_3des -#define calg_idea ssl_calg_idea -#define calg_fortezza ssl_calg_fortezza /* deprecated, must preserve */ -#define calg_aes ssl_calg_aes -#define calg_camellia ssl_calg_camellia -#define calg_seed ssl_calg_seed -#define calg_aes_gcm ssl_calg_aes_gcm - -#define mac_null ssl_mac_null -#define mac_md5 ssl_mac_md5 -#define mac_sha ssl_mac_sha -#define hmac_md5 ssl_hmac_md5 -#define hmac_sha ssl_hmac_sha -#define hmac_sha256 ssl_hmac_sha256 -#define mac_aead ssl_mac_aead - -#define SET_ERROR_CODE /* reminder */ -#define SEND_ALERT /* reminder */ -#define TEST_FOR_FAILURE /* reminder */ -#define DEAL_WITH_FAILURE /* reminder */ + +#define calg_null ssl_calg_null +#define calg_rc4 ssl_calg_rc4 +#define calg_rc2 ssl_calg_rc2 +#define calg_des ssl_calg_des +#define calg_3des ssl_calg_3des +#define calg_idea ssl_calg_idea +#define calg_fortezza ssl_calg_fortezza /* deprecated, must preserve */ +#define calg_aes ssl_calg_aes +#define calg_camellia ssl_calg_camellia +#define calg_seed ssl_calg_seed +#define calg_aes_gcm ssl_calg_aes_gcm +#define calg_chacha20 ssl_calg_chacha20 + +#define mac_null ssl_mac_null +#define mac_md5 ssl_mac_md5 +#define mac_sha ssl_mac_sha +#define hmac_md5 ssl_hmac_md5 +#define hmac_sha ssl_hmac_sha +#define hmac_sha256 ssl_hmac_sha256 +#define hmac_sha384 ssl_hmac_sha384 +#define mac_aead ssl_mac_aead #if defined(DEBUG) || defined(TRACE) #ifdef __cplusplus @@ -85,192 +80,162 @@ extern int Debug; #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 DUMP_MSG(a,b) if (ssl_trace >= (a)) ssl_DumpMsg b +#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 DUMP_MSG(a,b) +#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 +#define SSL_DBG(b) \ + if (ssl_debug) \ + ssl_Trace b #else #define SSL_DBG(b) #endif -#include "private/pprthred.h" /* for PR_InMonitor() */ -#define ssl_InMonitor(m) PZ_InMonitor(m) +#define LSB(x) ((unsigned char)((x)&0xff)) +#define MSB(x) ((unsigned char)(((unsigned)(x)) >> 8)) -#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 + SSLAppOpWrite, + SSLAppOpRDWR, + SSLAppOpPost, + SSLAppOpHeader } SSLAppOperation; -#define SSL_MIN_MASTER_KEY_BYTES 5 -#define SSL_MAX_MASTER_KEY_BYTES 64 - -#define SSL2_SESSIONID_BYTES 16 -#define SSL3_SESSIONID_BYTES 32 - -#define SSL_MIN_CHALLENGE_BYTES 16 -#define SSL_MAX_CHALLENGE_BYTES 32 -#define SSL_CHALLENGE_BYTES 16 +#define SSL3_SESSIONID_BYTES 32 -#define SSL_CONNECTIONID_BYTES 16 +#define SSL_MIN_CHALLENGE_BYTES 16 +#define SSL_MAX_CHALLENGE_BYTES 32 -#define SSL_MIN_CYPHER_ARG_BYTES 0 -#define SSL_MAX_CYPHER_ARG_BYTES 32 - -#define SSL_MAX_MAC_BYTES 16 - -#define SSL3_RSA_PMS_LENGTH 48 #define SSL3_MASTER_SECRET_LENGTH 48 /* number of wrap mechanisms potentially used to wrap master secrets. */ -#define SSL_NUM_WRAP_MECHS 16 +#define SSL_NUM_WRAP_MECHS 16 /* This makes the cert cache entry exactly 4k. */ -#define SSL_MAX_CACHED_CERT_LEN 4060 - -#define NUM_MIXERS 9 - -/* Mask of the 25 named curves we support. */ -#define SSL3_ALL_SUPPORTED_CURVES_MASK 0x3fffffe -/* Mask of only 3 curves, suite B */ -#define SSL3_SUITE_B_SUPPORTED_CURVES_MASK 0x3800000 +#define SSL_MAX_CACHED_CERT_LEN 4060 #ifndef BPB #define BPB 8 /* Bits Per Byte */ #endif -#define EXPORT_RSA_KEY_LENGTH 64 /* bytes */ +/* 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 -#define INITIAL_DTLS_TIMEOUT_MS 1000 /* Default value from RFC 4347 = 1s*/ -#define MAX_DTLS_TIMEOUT_MS 60000 /* 1 minute */ -#define DTLS_FINISHED_TIMER_MS 120000 /* Time to wait in FINISHED state */ +/* default number of entries in namedGroupPreferences */ +#define SSL_NAMED_GROUP_COUNT 31 -typedef struct sslBufferStr sslBuffer; -typedef struct sslConnectInfoStr sslConnectInfo; -typedef struct sslGatherStr sslGather; -typedef struct sslSecurityInfoStr sslSecurityInfo; -typedef struct sslSessionIDStr sslSessionID; -typedef struct sslSocketStr sslSocket; -typedef struct sslSocketOpsStr sslSocketOps; +/* 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 struct ssl3StateStr ssl3State; -typedef struct ssl3CertNodeStr ssl3CertNode; -typedef struct ssl3BulkCipherDefStr ssl3BulkCipherDef; -typedef struct ssl3MACDefStr ssl3MACDef; -typedef struct ssl3KeyPairStr ssl3KeyPair; -typedef struct ssl3DHParamsStr ssl3DHParams; +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 struct { + /* 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; +} sslNamedGroupDef; + +typedef struct sslBufferStr sslBuffer; +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 ssl3BulkCipherDefStr ssl3BulkCipherDef; +typedef struct ssl3MACDefStr ssl3MACDef; +typedef struct sslKeyPairStr sslKeyPair; +typedef struct ssl3DHParamsStr ssl3DHParams; struct ssl3CertNodeStr { struct ssl3CertNodeStr *next; - CERTCertificate * cert; + CERTCertificate *cert; }; typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss); -/* This type points to the low layer send func, -** e.g. ssl2_SendStream or ssl3_SendPlainText. -** These functions return the same values as PR_Send, -** i.e. >= 0 means number of bytes sent, < 0 means error. -*/ -typedef PRInt32 (*sslSendFunc)(sslSocket *ss, const unsigned char *buf, - PRInt32 n, PRInt32 flags); - -typedef void (*sslSessionIDCacheFunc) (sslSessionID *sid); -typedef void (*sslSessionIDUncacheFunc)(sslSessionID *sid); -typedef sslSessionID *(*sslSessionIDLookupFunc)(const PRIPv6Addr *addr, - unsigned char* sid, - unsigned int sidLen, - CERTCertDBHandle * dbHandle); - -/* registerable callback function that either appends extension to buffer - * or returns length of data that it would have appended. - */ -typedef PRInt32 (*ssl3HelloExtensionSenderFunc)(sslSocket *ss, PRBool append, - PRUint32 maxBytes); - -/* registerable callback function that handles a received extension, - * of the given type. - */ -typedef SECStatus (* ssl3HelloExtensionHandlerFunc)(sslSocket *ss, - PRUint16 ex_type, - SECItem * data); - -/* row in a table of hello extension senders */ -typedef struct { - PRInt32 ex_type; - ssl3HelloExtensionSenderFunc ex_sender; -} ssl3HelloExtensionSender; - -/* row in a table of hello extension handlers */ -typedef struct { - PRInt32 ex_type; - ssl3HelloExtensionHandlerFunc ex_handler; -} ssl3HelloExtensionHandler; - -extern SECStatus -ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type, - ssl3HelloExtensionSenderFunc cb); - -extern PRInt32 -ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes, - const ssl3HelloExtensionSender *sender); - -extern unsigned int -ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength); - -extern PRInt32 -ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen, - PRUint32 maxBytes); +typedef void (*sslSessionIDCacheFunc)(sslSessionID *sid); +typedef void (*sslSessionIDUncacheFunc)(sslSessionID *sid); +typedef sslSessionID *(*sslSessionIDLookupFunc)(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 (*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); + 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 (*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 *); + 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_USE_EPOCH 0x10000000 /* DTLS only */ -#define ssl_SEND_FLAG_NO_RETRANSMIT 0x08000000 /* DTLS only */ +#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_CAP_RECORD_VERSION \ - 0x04000000 /* TLS only */ -#define ssl_SEND_FLAG_MASK 0x7f000000 + 0x04000000 /* TLS only */ +#define ssl_SEND_FLAG_MASK 0x7f000000 /* ** A buffer object. */ struct sslBufferStr { - unsigned char * buf; - unsigned int len; - unsigned int space; + unsigned char *buf; + unsigned int len; + unsigned int space; }; /* @@ -278,96 +243,76 @@ struct sslBufferStr { */ typedef struct { #if !defined(_WIN32) - unsigned int cipher_suite : 16; - unsigned int policy : 8; - unsigned int enabled : 1; - unsigned int isPresent : 1; + 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; + PRUint8 policy; + unsigned char enabled : 1; + unsigned char isPresent : 1; #endif } ssl3CipherSuiteCfg; -#ifndef NSS_DISABLE_ECC -#define ssl_V3_SUITES_IMPLEMENTED 64 -#else -#define ssl_V3_SUITES_IMPLEMENTED 40 -#endif /* NSS_DISABLE_ECC */ +#define ssl_V3_SUITES_IMPLEMENTED 71 #define MAX_DTLS_SRTP_CIPHER_SUITES 4 -/* MAX_SIGNATURE_ALGORITHMS allows for a large number of combinations of - * SSLSignType and SSLHashType, but not all combinations (specifically, this - * doesn't allow space for combinations with MD5). */ -#define MAX_SIGNATURE_ALGORITHMS 15 - +/* MAX_SIGNATURE_SCHEMES allows for all the values we support. */ +#define MAX_SIGNATURE_SCHEMES 15 typedef struct sslOptionsStr { /* If SSL_SetNextProtoNego has been called, then this contains the * list of supported protocols. */ SECItem nextProtoNego; - unsigned int useSecurity : 1; /* 1 */ - unsigned int useSocks : 1; /* 2 */ - unsigned int requestCertificate : 1; /* 3 */ - unsigned int requireCertificate : 2; /* 4-5 */ - unsigned int handshakeAsClient : 1; /* 6 */ - unsigned int handshakeAsServer : 1; /* 7 */ - unsigned int enableSSL2 : 1; /* 8 */ - unsigned int unusedBit9 : 1; /* 9 */ - unsigned int unusedBit10 : 1; /* 10 */ - unsigned int noCache : 1; /* 11 */ - unsigned int fdx : 1; /* 12 */ - unsigned int v2CompatibleHello : 1; /* 13 */ - unsigned int detectRollBack : 1; /* 14 */ - unsigned int noStepDown : 1; /* 15 */ - unsigned int bypassPKCS11 : 1; /* 16 */ - unsigned int noLocks : 1; /* 17 */ - unsigned int enableSessionTickets : 1; /* 18 */ - unsigned int enableDeflate : 1; /* 19 */ - unsigned int enableRenegotiation : 2; /* 20-21 */ - unsigned int requireSafeNegotiation : 1; /* 22 */ - unsigned int enableFalseStart : 1; /* 23 */ - unsigned int cbcRandomIV : 1; /* 24 */ - unsigned int enableOCSPStapling : 1; /* 25 */ - unsigned int enableNPN : 1; /* 26 */ - unsigned int enableALPN : 1; /* 27 */ - unsigned int reuseServerECDHEKey : 1; /* 28 */ - unsigned int enableFallbackSCSV : 1; /* 29 */ - unsigned int enableServerDhe : 1; /* 30 */ - unsigned int enableExtendedMS : 1; /* 31 */ + 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; + unsigned int enableRenegotiation : 2; + unsigned int requireSafeNegotiation : 1; + unsigned int enableFalseStart : 1; + unsigned int cbcRandomIV : 1; + unsigned int enableOCSPStapling : 1; + unsigned int enableNPN : 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 enableShortHeaders : 1; } sslOptions; typedef enum { sslHandshakingUndetermined = 0, - sslHandshakingAsClient, - sslHandshakingAsServer + sslHandshakingAsClient, + sslHandshakingAsServer } sslHandshakingType; -typedef struct sslServerCertsStr { - /* Configuration state for server sockets */ - CERTCertificate * serverCert; - CERTCertificateList * serverCertChain; - ssl3KeyPair * serverKeyPair; - unsigned int serverKeyBits; -} sslServerCerts; - -#define SERVERKEY serverKeyPair->privKey +#define SSL_LOCK_RANK_SPEC 255 -#define SSL_LOCK_RANK_SPEC 255 -#define SSL_LOCK_RANK_GLOBAL NSS_RWLOCK_RANK_NONE - -/* These are the valid values for shutdownHow. +/* 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 +** 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 */ +#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 @@ -375,85 +320,59 @@ typedef struct sslServerCertsStr { ** Everything in here is protected by the recvBufLock. */ struct sslGatherStr { - int state; /* see GS_ values below. */ /* ssl 2 & 3 */ + int state; /* see GS_ values below. */ /* "buf" holds received plaintext SSL records, after decrypt and MAC check. - * SSL2: recv'd ciphertext records are put here, then decrypted in place. - * SSL3: recv'd ciphertext records are put in inbuf (see below), then - * decrypted into buf. + * recv'd ciphertext records are put in inbuf (see below), then decrypted + * into buf. */ - sslBuffer buf; /*recvBufLock*/ /* ssl 2 & 3 */ + sslBuffer buf; /*recvBufLock*/ - /* number of bytes previously read into hdr or buf(ssl2) or inbuf (ssl3). - ** (offset - writeOffset) is the number of ciphertext bytes read in but + /* 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; /* ssl 2 & 3 */ + unsigned int offset; /* number of bytes to read in next call to ssl_DefRecv (recv) */ - unsigned int remainder; /* ssl 2 & 3 */ - - /* Number of ciphertext bytes to read in after 2-byte SSL record header. */ - unsigned int count; /* ssl2 only */ - - /* size of the final plaintext record. - ** == count - (recordPadding + MAC size) - */ - unsigned int recordLen; /* ssl2 only */ + unsigned int remainder; - /* number of bytes of padding to be removed after decrypting. */ - /* This value is taken from the record's hdr[2], which means a too large - * value could crash us. - */ - unsigned int recordPadding; /* ssl2 only */ - - /* plaintext DATA begins this many bytes into "buf". */ - unsigned int recordOffset; /* ssl2 only */ - - int encrypted; /* SSL2 session is now encrypted. ssl2 only */ - - /* These next two values are used by SSL2 and SSL3. - ** DoRecv uses them 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 + /* 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 + ** In the current implementation, this is made available before the ** MAC is checked!! */ - unsigned int readOffset; /* Spot where DATA reader (e.g. application + 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; + unsigned int writeOffset; /* Buffer for ssl3 to read (encrypted) data from the socket */ - sslBuffer inbuf; /*recvBufLock*/ /* ssl3 only */ + 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 + ** 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 SSL2, the plaintext portion is two bytes long. For SSl3 it is 5. - ** For DTLS it is 13. + ** For SSL3/TLS, the plaintext portion is 5 bytes long. For DTLS it is 13. */ - unsigned char hdr[13]; /* ssl 2 & 3 or dtls */ + unsigned char hdr[13]; /* Buffer for DTLS data read off the wire as a single datagram */ - sslBuffer dtlsPacket; + sslBuffer dtlsPacket; /* the start of the buffered DTLS record in dtlsPacket */ - unsigned int dtlsPacketOffset; + unsigned int dtlsPacketOffset; }; /* sslGather.state */ -#define GS_INIT 0 -#define GS_HEADER 1 -#define GS_MAC 2 -#define GS_DATA 3 -#define GS_PAD 4 - - +#define GS_INIT 0 +#define GS_HEADER 1 +#define GS_DATA 2 /* ** ssl3State and CipherSpec structs @@ -462,104 +381,87 @@ struct sslGatherStr { /* The SSL bulk cipher definition */ typedef enum { cipher_null, - cipher_rc4, - cipher_rc4_40, - cipher_rc4_56, - cipher_rc2, - cipher_rc2_40, - cipher_des, - cipher_3des, - cipher_des40, - cipher_idea, + 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_missing /* reserved for no such supported cipher */ + 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; +typedef enum { type_stream, + type_block, + type_aead } CipherType; #define MAX_IV_LENGTH 24 -/* - * Do not depend upon 64 bit arithmetic in the underlying machine. - */ -typedef struct { - PRUint32 high; - PRUint32 low; -} SSL3SequenceNumber; - +typedef PRUint64 sslSequenceNumber; typedef PRUint16 DTLSEpoch; typedef void (*DTLSTimerCb)(sslSocket *); -#define MAX_MAC_CONTEXT_BYTES 400 /* 400 is large enough for MD5, SHA-1, and - * SHA-256. For SHA-384 support, increase - * it to 712. */ -#define MAX_MAC_CONTEXT_LLONGS (MAX_MAC_CONTEXT_BYTES / 8) - -#define MAX_CIPHER_CONTEXT_BYTES 2080 -#define MAX_CIPHER_CONTEXT_LLONGS (MAX_CIPHER_CONTEXT_BYTES / 8) - typedef struct { - SSL3Opaque wrapped_master_secret[48]; - PRUint16 wrapped_master_secret_len; - PRUint8 msIsWrapped; - PRUint8 resumable; - PRUint8 extendedMasterSecretUsed; + SSL3Opaque wrapped_master_secret[48]; + PRUint16 wrapped_master_secret_len; + PRUint8 msIsWrapped; + PRUint8 resumable; + PRUint8 extendedMasterSecretUsed; } ssl3SidKeys; /* 52 bytes */ typedef struct { - PK11SymKey *write_key; - PK11SymKey *write_mac_key; + PK11SymKey *write_key; + PK11SymKey *write_mac_key; PK11Context *write_mac_context; - SECItem write_key_item; - SECItem write_iv_item; - SECItem write_mac_key_item; - SSL3Opaque write_iv[MAX_IV_LENGTH]; - PRUint64 cipher_context[MAX_CIPHER_CONTEXT_LLONGS]; + SECItem write_key_item; + SECItem write_iv_item; + SECItem write_mac_key_item; + SSL3Opaque write_iv[MAX_IV_LENGTH]; } ssl3KeyMaterial; -typedef SECStatus (*SSLCipher)(void * context, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen); +typedef SECStatus (*SSLCipher)(void *context, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen); typedef SECStatus (*SSLAEADCipher)( - ssl3KeyMaterial * keys, - PRBool doDecrypt, - unsigned char * out, - int * outlen, - int maxout, - const unsigned char *in, - int inlen, - const unsigned char *additionalData, - int additionalDataLen); -typedef SECStatus (*SSLCompressor)(void * context, - unsigned char * out, - int * outlen, - int maxout, + ssl3KeyMaterial *keys, + PRBool doDecrypt, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen, + const unsigned char *additionalData, + int additionalDataLen); +typedef SECStatus (*SSLCompressor)(void *context, + unsigned char *out, + int *outlen, + int maxout, const unsigned char *in, - int inlen); + int inlen); typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit); -/* The DTLS anti-replay window. 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. +/* 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 /* Packets; approximate - * Must be divisible by 8 - */ +#define DTLS_RECVD_RECORDS_WINDOW 1024 +#define RECORD_SEQ_MAX ((1ULL << 48) - 1) +PR_STATIC_ASSERT(DTLS_RECVD_RECORDS_WINDOW % 8 == 0); + typedef struct DTLSRecvdRecordsStr { - unsigned char data[DTLS_RECVD_RECORDS_WINDOW/8]; - PRUint64 left; - PRUint64 right; + unsigned char data[DTLS_RECVD_RECORDS_WINDOW / 8]; + sslSequenceNumber left; + sslSequenceNumber right; } DTLSRecvdRecords; /* @@ -568,198 +470,199 @@ typedef struct DTLSRecvdRecordsStr { ** (direct and indirect) is protected by the reader/writer lock ss->specLock. */ typedef struct { + PRCList link; const ssl3BulkCipherDef *cipher_def; - const ssl3MACDef * mac_def; + const ssl3MACDef *mac_def; SSLCompressionMethod compression_method; - int mac_size; - SSLCipher encode; - SSLCipher decode; - SSLAEADCipher aead; - SSLDestroy destroy; - void * encodeContext; - void * decodeContext; - SSLCompressor compressor; /* Don't name these fields compress */ - SSLCompressor decompressor; /* and uncompress because zconf.h */ - /* may define them as macros. */ - SSLDestroy destroyCompressContext; - void * compressContext; - SSLDestroy destroyDecompressContext; - void * decompressContext; - PRBool bypassCiphers; /* did double bypass (at least) */ - PK11SymKey * master_secret; - SSL3SequenceNumber write_seq_num; - SSL3SequenceNumber read_seq_num; + int mac_size; + SSLCipher encode; + SSLCipher decode; + SSLAEADCipher aead; + void *encodeContext; + void *decodeContext; + SSLCompressor compressor; /* Don't name these fields compress */ + SSLCompressor decompressor; /* and uncompress because zconf.h */ + /* may define them as macros. */ + SSLDestroy destroyCompressContext; + void *compressContext; + SSLDestroy destroyDecompressContext; + void *decompressContext; + PK11SymKey *master_secret; + sslSequenceNumber write_seq_num; + sslSequenceNumber read_seq_num; SSL3ProtocolVersion version; - ssl3KeyMaterial client; - ssl3KeyMaterial server; - SECItem msItem; - unsigned char key_block[NUM_MIXERS * MD5_LENGTH]; - unsigned char raw_master_secret[56]; - SECItem srvVirtName; /* for server: name that was negotiated - * with a client. For client - is - * always set to NULL.*/ - DTLSEpoch epoch; - DTLSRecvdRecords recvdRecords; + ssl3KeyMaterial client; + ssl3KeyMaterial server; + SECItem msItem; + DTLSEpoch epoch; + DTLSRecvdRecords recvdRecords; + + PRUint8 refCt; + const char *phase; } ssl3CipherSpec; -typedef enum { never_cached, - in_client_cache, - in_server_cache, - invalid_cache /* no longer in any cache. */ +typedef enum { never_cached, + in_client_cache, + in_server_cache, + invalid_cache /* no longer in any 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; - PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */ + sslSessionID *next; /* chain used for client sockets, only */ + Cached cached; + int references; + PRUint32 lastAccessTime; /* seconds since Jan 1, 1970 */ /* 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 */ - CERTCertificate * localCert; + CERTCertificate *peerCert; + SECItemArray peerCertStatus; /* client only */ + const char *peerID; /* client only */ + const char *urlSvrName; /* client only */ + sslServerCertType certType; + CERTCertificate *localCert; - PRIPv6Addr addr; - PRUint16 port; + PRIPv6Addr addr; + PRUint16 port; - SSL3ProtocolVersion version; + SSL3ProtocolVersion version; - PRUint32 creationTime; /* seconds since Jan 1, 1970 */ - PRUint32 expirationTime; /* seconds since Jan 1, 1970 */ + PRUint32 creationTime; /* seconds since Jan 1, 1970 */ + PRUint32 expirationTime; /* seconds since Jan 1, 1970 */ - SSLSignType authAlgorithm; - PRUint32 authKeyBits; - SSLKEAType keaType; - PRUint32 keaKeyBits; + SSLAuthType authType; + PRUint32 authKeyBits; + SSLKEAType keaType; + PRUint32 keaKeyBits; union { - struct { - /* the V2 code depends upon the size of sessionID. */ - unsigned char sessionID[SSL2_SESSIONID_BYTES]; - - /* Stuff used to recreate key and read/write cipher objects */ - SECItem masterKey; /* never wrapped */ - int cipherType; - SECItem cipherArg; - int keyBits; - int secretKeyBits; - } ssl2; - struct { - /* values that are copied into the server's on-disk SID cache. */ - PRUint8 sessionIDLength; - SSL3Opaque sessionID[SSL3_SESSIONID_BYTES]; - - ssl3CipherSuite cipherSuite; - SSLCompressionMethod compression; - int policy; - ssl3SidKeys keys; - CK_MECHANISM_TYPE masterWrapMech; - /* mechanism used to wrap master secret */ - SSL3KEAType exchKeyType; - /* key type used in exchange algorithm, - * and to wrap the sym wrapping key. */ -#ifndef NSS_DISABLE_ECC - PRUint32 negotiatedECCurves; -#endif /* NSS_DISABLE_ECC */ - - /* The following values are NOT restored from the server's on-disk - * session cache, but are restored from the client's cache. - */ - PK11SymKey * clientWriteKey; - PK11SymKey * serverWriteKey; - - /* 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; - - /* 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; + struct { + /* values that are copied into the server's on-disk SID cache. */ + PRUint8 sessionIDLength; + SSL3Opaque sessionID[SSL3_SESSIONID_BYTES]; + + ssl3CipherSuite cipherSuite; + SSLCompressionMethod compression; + int policy; + ssl3SidKeys keys; + /* mechanism used to wrap master secret */ + CK_MECHANISM_TYPE masterWrapMech; + + /* The following values are NOT restored from the server's on-disk + * session cache, but are restored from the client's cache. + */ + PK11SymKey *clientWriteKey; + PK11SymKey *serverWriteKey; + + /* 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 NPN/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; }; typedef struct ssl3CipherSuiteDefStr { - ssl3CipherSuite cipher_suite; - SSL3BulkCipher bulk_cipher_alg; - SSL3MACAlgorithm mac_alg; + ssl3CipherSuite cipher_suite; + SSL3BulkCipher bulk_cipher_alg; + SSL3MACAlgorithm mac_alg; SSL3KeyExchangeAlgorithm key_exchange_alg; + SSLHashType prf_hash; } ssl3CipherSuiteDef; /* ** There are tables of these, all const. */ typedef struct { + /* An identifier for this struct. */ SSL3KeyExchangeAlgorithm kea; - SSL3KEAType exchKeyType; - SSL3SignType signKeyType; - /* For export cipher suites: - * is_limited identifies a suite as having a limit on the key size. - * key_size_limit provides the corresponding limit. */ - PRBool is_limited; - unsigned int key_size_limit; - PRBool tls_keygen; + /* 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; + PRBool ephemeral; + /* An OID describing the key exchange */ + SECOidTag oid; } ssl3KEADef; /* ** There are tables of these, all const. */ struct ssl3BulkCipherDefStr { - SSL3BulkCipher cipher; + SSL3BulkCipher cipher; SSLCipherAlgorithm calg; - int key_size; - int secret_key_size; - CipherType type; - int iv_size; - int block_size; - int tag_size; /* authentication tag size for AEAD ciphers. */ - int explicit_nonce_size; /* for AEAD ciphers. */ + 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; }; /* @@ -768,54 +671,52 @@ struct ssl3BulkCipherDefStr { struct ssl3MACDefStr { SSL3MACAlgorithm mac; CK_MECHANISM_TYPE mmech; - int pad_size; - int mac_size; + int pad_size; + int mac_size; + SECOidTag oid; }; typedef enum { - wait_client_hello, - wait_client_cert, + 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_client_cert, wait_client_key, - wait_cert_verify, - wait_change_cipher, + wait_cert_verify, + wait_change_cipher, wait_finished, - wait_server_hello, + wait_server_hello, wait_certificate_status, - wait_server_cert, + wait_server_cert, wait_server_key, - wait_cert_request, + wait_cert_request, wait_hello_done, wait_new_session_ticket, - idle_handshake + wait_encrypted_extensions, + wait_invalid /* Invalid value. There is no handshake message "invalid". */ } SSL3WaitState; -/* - * TLS extension related constants and data structures. - */ -typedef struct TLSExtensionDataStr TLSExtensionData; -typedef struct SessionTicketDataStr SessionTicketData; - -struct TLSExtensionDataStr { - /* registered callbacks that send server hello extensions */ - ssl3HelloExtensionSender serverSenders[SSL_MAX_EXTENSIONS]; - /* Keep track of the extensions that are negotiated. */ - PRUint16 numAdvertised; - PRUint16 numNegotiated; - PRUint16 advertised[SSL_MAX_EXTENSIONS]; - PRUint16 negotiated[SSL_MAX_EXTENSIONS]; - - /* SessionTicket Extension related data. */ - PRBool ticketTimestampVerified; - PRBool emptySessionTicket; - PRBool sentSessionTicketInClientHello; - - /* 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; -}; +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 *); @@ -823,252 +724,283 @@ typedef SECStatus (*sslRestartTarget)(sslSocket *); ** A DTLS queued message (potentially to be retransmitted) */ typedef struct DTLSQueuedMessageStr { - PRCList link; /* The linked list link */ - DTLSEpoch epoch; /* The epoch to use */ - SSL3ContentType type; /* The message type */ - unsigned char *data; /* The data */ - PRUint16 len; /* The data length */ + PRCList link; /* The linked list link */ + ssl3CipherSpec *cwSpec; /* The cipher spec to use, null for none */ + SSL3ContentType type; /* The message type */ + unsigned char *data; /* The data */ + PRUint16 len; /* The data length */ } DTLSQueuedMessage; +typedef struct TLS13KeyShareEntryStr { + PRCList link; /* The linked list link */ + const sslNamedGroupDef *group; /* The group for the entry */ + SECItem key_exchange; /* The share itself */ +} TLS13KeyShareEntry; + +typedef struct TLS13EarlyDataStr { + PRCList link; /* The linked list link */ + 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_single = 2, /* A single hash */ + handshake_hash_record } SSL3HandshakeHashType; +/* This holds state for TLS 1.3 CertificateRequest handling. */ +typedef struct TLS13CertificateRequestStr { + PLArenaPool *arena; + SECItem context; + SSLSignatureScheme *signatureSchemes; + unsigned int signatureSchemeCount; + CERTDistNames ca_list; +} TLS13CertificateRequest; + /* ** 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; - SSL3WaitState ws; + SSL3Random server_random; + SSL3Random client_random; + 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 */ -#ifndef NO_PKCS11_BYPASS - /* Bypass mode: - * SSL 3.0 - TLS 1.1 use both |md5_cx| and |sha_cx|. |md5_cx| is used for - * MD5 and |sha_cx| for SHA-1. - * TLS 1.2 and later use only |sha_cx|, for SHA-256. NOTE: When we support - * SHA-384, increase MAX_MAC_CONTEXT_BYTES to 712. */ - PRUint64 md5_cx[MAX_MAC_CONTEXT_LLONGS]; - PRUint64 sha_cx[MAX_MAC_CONTEXT_LLONGS]; - const SECHashObject * sha_obj; - /* The function prototype of sha_obj->clone() does not match the prototype - * of the freebl <HASH>_Clone functions, so we need a dedicated function - * pointer for the <HASH>_Clone function. */ - void (*sha_clone)(void *dest, void *src); -#endif + sslBuffer messages; /* Accumulated 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|, for SHA-256. */ - /* NOTE: On the client side, TLS 1.2 and later use |md5| as a backup - * handshake hash for generating client auth signatures. Confusingly, the - * backup hash function is SHA-1. */ -#define backupHash md5 - PK11Context * md5; - PK11Context * sha; - -const ssl3KEADef * kea_def; - ssl3CipherSuite cipher_suite; -const ssl3CipherSuiteDef *suite_def; - SSLCompressionMethod compression; - 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 */ - SSL3HandshakeType msg_type; - unsigned long msg_len; - SECItem ca_list; /* used only by client */ - PRBool isResuming; /* are we resuming a session */ - PRBool usedStepDownKey; /* we did a server key exchange. */ - PRBool sendingSCSV; /* instead of empty RI */ - sslBuffer msgState; /* current state for handshake messages*/ - /* protected by recvBufLock */ + PK11Context *md5; + PK11Context *sha; + SSLSignatureScheme signatureScheme; + const ssl3KEADef *kea_def; + ssl3CipherSuite cipher_suite; + const ssl3CipherSuiteDef *suite_def; + SSLCompressionMethod compression; + 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 */ + SSL3HandshakeType msg_type; + unsigned long msg_len; + PRBool isResuming; /* we are resuming (not used in TLS 1.3) */ + PRBool sendingSCSV; /* instead of empty RI */ + sslBuffer msgState; /* current state for handshake messages*/ + /* protected by recvBufLock */ /* 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; + PRBool receivedNewSessionTicket; + NewSessionTicket newSessionTicket; - PRUint16 finishedBytes; /* size of single finished below */ + PRUint16 finishedBytes; /* size of single finished below */ union { - TLSFinished tFinished[2]; /* client, then server */ - SSL3Finished sFinished[2]; - SSL3Opaque data[72]; - } finishedMsgs; -#ifndef NSS_DISABLE_ECC - PRUint32 negotiatedECCurves; /* bit mask */ -#endif /* NSS_DISABLE_ECC */ - - PRBool authCertificatePending; + TLSFinished tFinished[2]; /* client, then server */ + SSL3Finished sFinished[2]; + SSL3Opaque data[72]; + } finishedMsgs; + + PRBool authCertificatePending; /* Which function should SSL_RestartHandshake* call if we're blocked? * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake, * or ssl3_AlwaysFail */ - sslRestartTarget restartTarget; + sslRestartTarget restartTarget; /* Shared state between ssl3_HandleFinished and ssl3_FinishHandshake */ - PRBool cacheSID; + PRBool cacheSID; - PRBool canFalseStart; /* Can/did we False Start */ + PRBool canFalseStart; /* Can/did we False Start */ /* Which preliminaryinfo values have been set. */ - PRUint32 preliminaryInfo; + PRUint32 preliminaryInfo; - /* clientSigAndHash contains the contents of the signature_algorithms - * extension (if any) from the client. This is only valid for TLS 1.2 - * or later. */ - SSLSignatureAndHashAlg *clientSigAndHash; - unsigned int numClientSigAndHash; + /* Parsed extensions */ + PRCList remoteExtensions; /* Parsed incoming extensions */ /* 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. */ - unsigned char cookie[32]; /* The cookie */ - unsigned char cookieLen; /* The length of the cookie */ - PRIntervalTime rtTimerStarted; /* When the timer was started */ - DTLSTimerCb rtTimerCb; /* The function to call on expiry */ - PRUint32 rtTimeoutMs; /* The length of the current timeout - * used for backoff (in ms) */ - PRUint32 rtRetries; /* The retry counter */ + 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. */ + PRIntervalTime rtTimerStarted; /* When the timer was started */ + DTLSTimerCb rtTimerCb; /* The function to call on expiry */ + PRUint32 rtTimeoutMs; /* The length of the current timeout + * used for backoff (in ms) */ + 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 PSK. */ + PK11SymKey *dheSecret; /* The (EC)DHE shared secret. */ + PK11SymKey *pskBinderKey; /* Used to compute the PSK binder. */ + 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 */ + /* The certificate request from the server. */ + TLS13CertificateRequest *certificateRequest; + PRCList cipherSpecs; /* The cipher specs in the sequence they + * will be applied. */ + ssl3CipherSpec *nullSpec; /* In case 0-RTT is rejected. */ + 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. */ + ssl3KEADef kea_def_mutable; /* Used to hold the writable kea_def + * we use for TLS 1.3 */ + PRBool shortHeaders; /* Assigned if we are doing short headers. */ } SSL3HandshakeState; - - /* ** This is the "ssl3" struct, as in "ss->ssl3". ** note: -** usually, crSpec == cwSpec and prSpec == pwSpec. +** usually, crSpec == cwSpec and prSpec == pwSpec. ** Sometimes, crSpec == pwSpec and prSpec == cwSpec. -** But there are never more than 2 actual specs. +** 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 + ** 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. */ - - CERTCertificate * clientCertificate; /* used by client */ - SECKEYPrivateKey * clientPrivateKey; /* used by client */ - CERTCertificateList *clientCertChain; /* used by client */ - PRBool sendEmptyCert; /* used by client */ - - int 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. */ - PRBool initialized; - SSL3HandshakeState hs; - ssl3CipherSpec specs[2]; /* one is current, one is pending. */ - - /* In a client: if the server supports Next Protocol Negotiation, then - * this is the protocol that was negotiated. + ssl3CipherSpec *crSpec; /* current read spec. */ + ssl3CipherSpec *prSpec; /* pending read spec. */ + ssl3CipherSpec *cwSpec; /* current write spec. */ + ssl3CipherSpec *pwSpec; /* pending write spec. */ + + CERTCertificate *clientCertificate; /* used by client */ + SECKEYPrivateKey *clientPrivateKey; /* used by client */ + CERTCertificateList *clientCertChain; /* used by client */ + PRBool sendEmptyCert; /* used by client */ + + int policy; + /* This says what cipher suites we can do, and should + * be either SSL_ALLOWED or SSL_RESTRICTED */ - SECItem nextProto; - SSLNextProtoState nextProtoState; - - PRUint16 mtu; /* Our estimate of the MTU */ + 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. */ + PRBool initialized; + SSL3HandshakeState hs; + ssl3CipherSpec specs[2]; /* one is current, one is pending. */ + + PRUint16 mtu; /* Our estimate of the MTU */ /* DTLS-SRTP cipher suite preferences (if any) */ - PRUint16 dtlsSRTPCiphers[MAX_DTLS_SRTP_CIPHER_SUITES]; - PRUint16 dtlsSRTPCipherCount; - PRUint16 dtlsSRTPCipherSuite; /* 0 if not selected */ - PRBool fatalAlertSent; - PRUint16 numDHEGroups; /* used by server */ - SSLDHEGroupType * dheGroups; /* used by server */ - PRBool dheWeakGroupEnabled; /* used by server */ + 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. */ - SSLSignatureAndHashAlg signatureAlgorithms[MAX_SIGNATURE_ALGORITHMS]; - unsigned int signatureAlgorithmCount; + 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; }; -#define DTLS_MAX_MTU 1500U /* Ethernet MTU but without subtracting the - * headers, so slightly larger than expected */ +/* 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 { - SSL3ContentType type; - SSL3ProtocolVersion version; - SSL3SequenceNumber seq_num; /* DTLS only */ - sslBuffer * buf; + SSL3ContentType type; + SSL3ProtocolVersion version; + sslSequenceNumber seq_num; /* DTLS only */ + sslBuffer *buf; } SSL3Ciphertext; -struct ssl3KeyPairStr { - SECKEYPrivateKey * privKey; - SECKEYPublicKey * pubKey; - PRInt32 refCount; /* use PR_Atomic calls for this. */ +struct sslKeyPairStr { + SECKEYPrivateKey *privKey; + SECKEYPublicKey *pubKey; + PRInt32 refCount; /* use PR_Atomic calls for this. */ }; +typedef struct { + PRCList link; + const sslNamedGroupDef *group; + sslKeyPair *keys; +} sslEphemeralKeyPair; + struct ssl3DHParamsStr { + SSLNamedGroup name; SECItem prime; /* p */ - SECItem base; /* g */ + SECItem base; /* g */ }; typedef struct SSLWrappedSymWrappingKeyStr { - SSL3Opaque wrappedSymmetricWrappingkey[512]; - 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. */ - SSL3KEAType exchKeyType; /* type of keys used to wrap SymWrapKey*/ - PRInt32 symWrapMechIndex; - PRUint16 wrappedSymKeyLen; + SSL3Opaque wrappedSymmetricWrappingkey[512]; + 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. */ + SSLAuthType authType; /* type of keys used to wrap SymWrapKey*/ + PRInt32 symWrapMechIndex; + PRUint16 wrappedSymKeyLen; } SSLWrappedSymWrappingKey; typedef struct SessionTicketStr { - PRUint16 ticket_version; - SSL3ProtocolVersion ssl_version; - ssl3CipherSuite cipher_suite; - SSLCompressionMethod compression_method; - SSLSignType authAlgorithm; - PRUint32 authKeyBits; - SSLKEAType keaType; - PRUint32 keaKeyBits; + PRUint16 ticket_version; + SSL3ProtocolVersion ssl_version; + ssl3CipherSuite cipher_suite; + SSLCompressionMethod compression_method; + SSLAuthType authType; + PRUint32 authKeyBits; + SSLKEAType keaType; + PRUint32 keaKeyBits; + sslServerCertType certType; /* - * exchKeyType and msWrapMech contain meaningful values only if - * ms_is_wrapped is true. + * msWrapMech contains a meaningful value only if ms_is_wrapped is true. */ - PRUint8 ms_is_wrapped; - SSLKEAType exchKeyType; /* XXX(wtc): same as keaType above? */ - CK_MECHANISM_TYPE msWrapMech; - PRUint16 ms_length; - SSL3Opaque master_secret[48]; - PRBool extendedMasterSecretUsed; - ClientIdentity client_identity; - SECItem peer_cert; - PRUint32 timestamp; - SECItem srvName; /* negotiated server name */ -} SessionTicket; + PRUint8 ms_is_wrapped; + CK_MECHANISM_TYPE msWrapMech; + PRUint16 ms_length; + SSL3Opaque master_secret[48]; + PRBool extendedMasterSecretUsed; + ClientIdentity client_identity; + SECItem peer_cert; + PRUint32 timestamp; + PRUint32 flags; + SECItem srvName; /* negotiated server name */ + SECItem alpnSelection; +} SessionTicket; /* * SSL2 buffers used in SSL3. @@ -1081,112 +1013,55 @@ typedef struct SessionTicketStr { /* ** This is "ci", as in "ss->sec.ci". ** -** Protection: All the variables in here are protected by -** firstHandshakeLock AND (in ssl3) ssl3HandshakeLock +** Protection: All the variables in here are protected by +** firstHandshakeLock AND ssl3HandshakeLock */ struct sslConnectInfoStr { /* outgoing handshakes appended to this. */ - sslBuffer sendBuf; /*xmitBufLock*/ /* ssl 2 & 3 */ - - PRIPv6Addr peer; /* ssl 2 & 3 */ - unsigned short port; /* ssl 2 & 3 */ - - sslSessionID *sid; /* ssl 2 & 3 */ - - /* see CIS_HAVE defines below for the bit values in *elements. */ - char elements; /* ssl2 only */ - char requiredElements; /* ssl2 only */ - char sentElements; /* ssl2 only */ + sslBuffer sendBuf; /*xmitBufLock*/ - char sentFinished; /* ssl2 only */ + PRIPv6Addr peer; + unsigned short port; - /* Length of server challenge. Used by client when saving challenge */ - int serverChallengeLen; /* ssl2 only */ - /* type of authentication requested by server */ - unsigned char authType; /* ssl2 only */ - - /* Challenge sent by client to server in client-hello message */ - /* SSL3 gets a copy of this. See ssl3_StartHandshakeHash(). */ - unsigned char clientChallenge[SSL_MAX_CHALLENGE_BYTES]; /* ssl 2 & 3 */ - - /* Connection-id sent by server to client in server-hello message */ - unsigned char connectionID[SSL_CONNECTIONID_BYTES]; /* ssl2 only */ - - /* Challenge sent by server to client in request-certificate message */ - unsigned char serverChallenge[SSL_MAX_CHALLENGE_BYTES]; /* ssl2 only */ - - /* Information kept to handle a request-certificate message */ - unsigned char readKey[SSL_MAX_MASTER_KEY_BYTES]; /* ssl2 only */ - unsigned char writeKey[SSL_MAX_MASTER_KEY_BYTES]; /* ssl2 only */ - unsigned keySize; /* ssl2 only */ + sslSessionID *sid; }; -/* bit values for ci->elements, ci->requiredElements, sentElements. */ -#define CIS_HAVE_MASTER_KEY 0x01 -#define CIS_HAVE_CERTIFICATE 0x02 -#define CIS_HAVE_FINISHED 0x04 -#define CIS_HAVE_VERIFY 0x08 - /* 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 (in ssl3) ssl3HandshakeLock. + * Unless otherwise specified below, the contents of this struct are + * protected by firstHandshakeLock AND ssl3HandshakeLock. */ struct sslSecurityInfoStr { - sslSendFunc send; /*xmitBufLock*/ /* ssl 2 & 3 */ - int isServer; /* Spec Lock?*/ /* ssl 2 & 3 */ - sslBuffer writeBuf; /*xmitBufLock*/ /* ssl 2 & 3 */ - - int cipherType; /* ssl 2 & 3 */ - int keyBits; /* ssl 2 & 3 */ - int secretKeyBits; /* ssl 2 & 3 */ - CERTCertificate *localCert; /* ssl 2 & 3 */ - CERTCertificate *peerCert; /* ssl 2 & 3 */ - SECKEYPublicKey *peerKey; /* ssl3 only */ - - SSLSignType authAlgorithm; - PRUint32 authKeyBits; - SSLKEAType keaType; - PRUint32 keaKeyBits; - /* - ** Procs used for SID cache (nonce) management. - ** Different implementations exist for clients/servers - ** The lookup proc is only used for servers. Baloney! - */ - sslSessionIDCacheFunc cache; /* ssl 2 & 3 */ - sslSessionIDUncacheFunc uncache; /* ssl 2 & 3 */ +#define SSL_ROLE(ss) (ss->sec.isServer ? "server" : "client") - /* - ** everything below here is for ssl2 only. - ** This stuff is equivalent to SSL3's "spec", and is protected by the - ** same "Spec Lock" as used for SSL3's specs. - */ - PRUint32 sendSequence; /*xmitBufLock*/ /* ssl2 only */ - PRUint32 rcvSequence; /*recvBufLock*/ /* ssl2 only */ - - /* Hash information; used for one-way-hash functions (MD2, MD5, etc.) */ - const SECHashObject *hash; /* Spec Lock */ /* ssl2 only */ - void *hashcx; /* Spec Lock */ /* ssl2 only */ + PRBool isServer; + sslBuffer writeBuf; /*xmitBufLock*/ - SECItem sendSecret; /* Spec Lock */ /* ssl2 only */ - SECItem rcvSecret; /* Spec Lock */ /* ssl2 only */ + CERTCertificate *localCert; + CERTCertificate *peerCert; + SECKEYPublicKey *peerKey; - /* Session cypher contexts; one for each direction */ - void *readcx; /* Spec Lock */ /* ssl2 only */ - void *writecx; /* Spec Lock */ /* ssl2 only */ - SSLCipher enc; /* Spec Lock */ /* ssl2 only */ - SSLCipher dec; /* Spec Lock */ /* ssl2 only */ - void (*destroy)(void *, PRBool); /* Spec Lock */ /* ssl2 only */ + SSLAuthType authType; + PRUint32 authKeyBits; + SSLSignatureScheme signatureScheme; + SSLKEAType keaType; + PRUint32 keaKeyBits; + const sslNamedGroupDef *keaGroup; + /* The selected certificate (for servers only). */ + const sslServerCert *serverCert; - /* Blocking information for the session cypher */ - int blockShift; /* Spec Lock */ /* ssl2 only */ - int blockSize; /* Spec Lock */ /* ssl2 only */ + /* + ** Procs used for SID cache (nonce) management. + ** Different implementations exist for clients/servers + ** The lookup proc is only used for servers. Baloney! + */ + sslSessionIDCacheFunc cache; + sslSessionIDUncacheFunc uncache; /* These are used during a connection handshake */ - sslConnectInfo ci; /* ssl 2 & 3 */ - + sslConnectInfo ci; }; /* @@ -1195,164 +1070,164 @@ struct sslSecurityInfoStr { ** Protection: XXX */ struct sslSocketStr { - PRFileDesc * fd; + PRFileDesc *fd; /* Pointer to operations vector for this socket */ - const sslSocketOps * ops; + const sslSocketOps *ops; /* SSL socket options */ - sslOptions opt; + sslOptions opt; /* Enabled version range */ - SSLVersionRange vrange; + SSLVersionRange vrange; /* 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 */ + 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 */ + sslSecurityInfo sec; /* not a pointer any more */ - /* protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock. */ - const char *url; /* ssl 2 & 3 */ + /* protected by firstHandshakeLock AND ssl3HandshakeLock. */ + const char *url; - sslHandshakeFunc handshake; /*firstHandshakeLock*/ - sslHandshakeFunc nextHandshake; /*firstHandshakeLock*/ - sslHandshakeFunc securityHandshake; /*firstHandshakeLock*/ + sslHandshakeFunc handshake; /*firstHandshakeLock*/ /* the following variable is only used with socks or other proxies. */ - char * peerID; /* String uniquely identifies target server. */ - - unsigned char * cipherSpecs; - unsigned int sizeCipherSpecs; -const unsigned char * preferredCipher; + char *peerID; /* String uniquely identifies target server. */ - ssl3KeyPair * stepDownKeyPair; /* RSA step down keys */ - - const ssl3DHParams *dheParams; /* DHE param */ - ssl3KeyPair * dheKeyPair; /* DHE keys */ + /* 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; - SSLBadCertHandler handleBadCert; - void *badCertArg; - SSLHandshakeCallback handshakeCallback; - void *handshakeCallbackData; - SSLCanFalseStartCallback canFalseStartCallback; - void *canFalseStartCallbackData; - void *pkcs11PinArg; - SSLNextProtoCallback nextProtoCallback; - void *nextProtoArg; - - 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. */ + SSLAuthCertificate authCertificate; + void *authCertificateArg; + SSLGetClientAuthData getClientAuthData; + void *getClientAuthDataArg; + SSLSNISocketConfig sniSocketConfig; + void *sniSocketConfigArg; + SSLBadCertHandler handleBadCert; + void *badCertArg; + SSLHandshakeCallback handshakeCallback; + void *handshakeCallbackData; + SSLCanFalseStartCallback canFalseStartCallback; + void *canFalseStartCallbackData; + void *pkcs11PinArg; + SSLNextProtoCallback nextProtoCallback; + void *nextProtoArg; + + 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; + 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; + PZMonitor *ssl3HandshakeLock; /* reader/writer lock, protects the secret data needed to encrypt and MAC - ** outgoing records, and to decrypt and MAC check incoming ciphertext + ** outgoing records, and to decrypt and MAC check incoming ciphertext ** records. */ - NSSRWLock * specLock; + NSSRWLock *specLock; - /* handle to perm cert db (and implicitly to the temp cert db) used - ** with this socket. + /* 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 */ + CERTCertDBHandle *dbHandle; - PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */ + PRThread *writerThread; /* thread holds SSL_LOCK_WRITER lock */ - PRUint16 allowedByPolicy; /* copy of global policy bits. */ - PRUint16 maybeAllowedByPolicy; /* copy of global policy bits. */ - PRUint16 chosenPreference; /* SSL2 cipher preferences. */ + PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */ sslHandshakingType handshaking; /* Gather object used for gathering data */ - sslGather gs; /*recvBufLock*/ + sslGather gs; /*recvBufLock*/ - sslBuffer saveBuf; /*xmitBufLock*/ - sslBuffer pendingBuf; /*xmitBufLock*/ + sslBuffer saveBuf; /*xmitBufLock*/ + sslBuffer pendingBuf; /*xmitBufLock*/ /* Configuration state for server sockets */ - /* server cert and key for each KEA type */ - sslServerCerts serverCerts[kt_kea_size]; - /* each cert needs its own status */ - SECItemArray * certStatusArray[kt_kea_size]; + /* One server cert and key for each authentication type. */ + PRCList /* <sslServerCert> */ serverCerts; ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED]; - ssl3KeyPair * ephemeralECDHKeyPair; /* for ECDHE-* handshake */ + + /* 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; + ssl3State ssl3; /* * TLS extension related data. */ /* True when the current session is a stateless resume. */ - PRBool statelessResume; - TLSExtensionData xtnData; + PRBool statelessResume; + TLSExtensionData xtnData; /* Whether we are doing stream or datagram mode */ - SSLProtocolVariant protocolVariant; + SSLProtocolVariant protocolVariant; }; - - -/* All the global data items declared here should be protected using the +/* All the global data items declared here should be protected using the ** ssl_global_data_lock, which is a reader/writer lock. */ -extern NSSRWLock * ssl_global_data_lock; -extern char ssl_debug; -extern char ssl_trace; -extern FILE * ssl_trace_iob; -extern FILE * ssl_keylog_iob; -extern CERTDistNames * ssl3_server_ca_list; -extern PRUint32 ssl_sid_timeout; -extern PRUint32 ssl3_sid_timeout; - -extern const char * const ssl_cipherName[]; -extern const char * const ssl3_cipherName[]; - -extern sslSessionIDLookupFunc ssl_sid_lookup; -extern sslSessionIDCacheFunc ssl_sid_cache; +extern NSSRWLock *ssl_global_data_lock; +extern char ssl_debug; +extern char ssl_trace; +extern FILE *ssl_trace_iob; +extern FILE *ssl_keylog_iob; +extern CERTDistNames *ssl3_server_ca_list; +extern PRUint32 ssl_sid_timeout; +extern PRUint32 ssl3_sid_timeout; + +extern const char *const ssl3_cipherName[]; + +extern sslSessionIDLookupFunc ssl_sid_lookup; +extern sslSessionIDCacheFunc ssl_sid_cache; extern sslSessionIDUncacheFunc ssl_sid_uncache; +extern const sslNamedGroupDef ssl_named_groups[]; + /************************************************************************/ SEC_BEGIN_PROTOS @@ -1370,15 +1245,15 @@ 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); + 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); + void *optval, PRInt32 *optlen); extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname, - const void *optval, PRInt32 optlen); + const void *optval, PRInt32 optlen); /* Implementation of ops for socks only case */ extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr); @@ -1388,7 +1263,7 @@ 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); + 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); @@ -1396,9 +1271,9 @@ extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len); 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); + int len, int flags); extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf, - int len, int flags); + 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); @@ -1410,88 +1285,83 @@ extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr); extern PRFileDesc *ssl_FindTop(sslSocket *ss); /* Gather funcs. */ -extern sslGather * ssl_NewGather(void); -extern SECStatus ssl_InitGather(sslGather *gs); -extern void ssl_DestroyGather(sslGather *gs); -extern int ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags); -extern int ssl2_GatherRecord(sslSocket *ss, int flags); -extern SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss); - -extern SECStatus ssl2_HandleClientHelloMessage(sslSocket *ss); -extern SECStatus ssl2_HandleServerHelloMessage(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(sslSocket *ss, const char *msg, const void *cp, int len); -extern void ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len); - -extern int ssl_SendSavedWriteData(sslSocket *ss); -extern SECStatus ssl_SaveWriteData(sslSocket *ss, - const void* p, unsigned int l); -extern SECStatus ssl2_BeginClientHandshake(sslSocket *ss); -extern SECStatus ssl2_BeginServerHandshake(sslSocket *ss); -extern int ssl_Do1stHandshake(sslSocket *ss); +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 int ssl_Do1stHandshake(sslSocket *ss); extern SECStatus sslBuffer_Grow(sslBuffer *b, unsigned int newLen); -extern SECStatus sslBuffer_Append(sslBuffer *b, const void * data, - unsigned int len); +extern SECStatus sslBuffer_Append(sslBuffer *b, const void *data, + unsigned int len); +extern void sslBuffer_Clear(sslBuffer *b); -extern void ssl2_UseClearSendFunc(sslSocket *ss); -extern void ssl_ChooseSessionIDProcs(sslSecurityInfo *sec); +extern void ssl_ChooseSessionIDProcs(sslSecurityInfo *sec); +extern void ssl3_InitCipherSpec(ssl3CipherSpec *spec); extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server); -extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, +extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, const char *urlSvrName); -extern void ssl_FreeSID(sslSessionID *sid); +extern void ssl_FreeSID(sslSessionID *sid); -extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in, - int len, int flags); +extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in, + int len, int flags); -extern PRBool ssl_FdIsBlocking(PRFileDesc *fd); +extern PRBool ssl_FdIsBlocking(PRFileDesc *fd); -extern PRBool ssl_SocketIsBlocking(sslSocket *ss); +extern PRBool ssl_SocketIsBlocking(sslSocket *ss); -extern void ssl3_SetAlwaysBlock(sslSocket *ss); +extern void ssl3_SetAlwaysBlock(sslSocket *ss); extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled); -extern void ssl_FinishHandshake(sslSocket *ss); +extern void 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); -/* Returns PR_TRUE if we are still waiting for the server to respond to our - * client second round. Once we've received any part of the server's second - * round then we don't bother trying to false start since it is almost always - * the case that the NewSessionTicket, ChangeCipherSoec, and Finished messages - * were sent in the same packet and we want to process them all at the same - * time. If we were to try to false start in the middle of the server's second - * round, then we would increase the number of I/O operations - * (SSL_ForceHandshake/PR_Recv/PR_Send/etc.) needed to finish the handshake. +extern SECStatus ssl3_InitState(sslSocket *ss); +extern SECStatus ssl3_RestartHandshakeHashes(sslSocket *ss); +extern SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss, + const unsigned char *b, + unsigned int l); + +/* 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_WaitingForStartOfServerSecondRound(sslSocket *ss); +extern PRBool ssl3_WaitingForServerSecondRound(sslSocket *ss); -extern SECStatus -ssl3_CompressMACEncryptRecord(ssl3CipherSpec * cwSpec, - PRBool isServer, - PRBool isDTLS, - PRBool capRecordVersion, - SSL3ContentType type, - const SSL3Opaque * pIn, - PRUint32 contentLen, - sslBuffer * wrBuf); -extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, - SSL3ContentType type, - const SSL3Opaque* pIn, PRInt32 nIn, - PRInt32 flags); - -#ifdef NSS_ENABLE_ZLIB +extern PRInt32 ssl3_SendRecord(sslSocket *ss, ssl3CipherSpec *cwSpec, + SSL3ContentType type, + const SSL3Opaque *pIn, PRInt32 nIn, + PRInt32 flags); + +#ifdef NSS_SSL_ENABLE_ZLIB /* * The DEFLATE algorithm can result in an expansion of 0.1% + 12 bytes. For a * maximum TLS record payload of 2**14 bytes, that's 29 bytes. */ #define SSL3_COMPRESSION_MAX_EXPANSION 29 -#else /* !NSS_ENABLE_ZLIB */ +#else /* !NSS_SSL_ENABLE_ZLIB */ #define SSL3_COMPRESSION_MAX_EXPANSION 0 #endif @@ -1499,68 +1369,109 @@ extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, * make sure there is room in the write buffer for padding and * other compression and cryptographic expansions. */ -#define SSL3_BUFFER_FUDGE 100 + SSL3_COMPRESSION_MAX_EXPANSION - -#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) +#define SSL3_BUFFER_FUDGE 100 + SSL3_COMPRESSION_MAX_EXPANSION + +#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) \ +#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) \ +#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); } +#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) \ +#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) \ +#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) \ +#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 @@ -1568,42 +1479,33 @@ extern PRInt32 ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch, */ #define SSL_LIBRARY_VERSION_NONE 0 -/* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version +/* 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. */ -#ifdef NSS_ENABLE_TLS_1_3 +#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 -/* Rename this macro SSL_ALL_VERSIONS_DISABLED when SSL 2.0 is removed. */ -#define SSL3_ALL_VERSIONS_DISABLED(vrange) \ +#define SSL_ALL_VERSIONS_DISABLED(vrange) \ ((vrange)->min == SSL_LIBRARY_VERSION_NONE) extern PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant, - SSL3ProtocolVersion version); - -extern SECStatus ssl3_KeyAndMacDeriveBypass(ssl3CipherSpec * pwSpec, - const unsigned char * cr, const unsigned char * sr, - PRBool isTLS, PRBool isExport); -extern SECStatus ssl3_MasterSecretDeriveBypass( ssl3CipherSpec * pwSpec, - const unsigned char * cr, const unsigned char * sr, - const SECItem * pms, PRBool isTLS, PRBool isRSA); + SSL3ProtocolVersion version); /* These functions are called from secnav, even though they're "private". */ -extern int ssl2_SendErrorMessage(struct sslSocketStr *ss, int error); extern int SSL_RestartHandshakeAfterCertReq(struct sslSocketStr *ss, - CERTCertificate *cert, - SECKEYPrivateKey *key, - CERTCertificateList *certChain); + 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); + SSL3AlertDescription desc); extern SECStatus ssl3_DecodeError(sslSocket *ss); extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error); @@ -1612,238 +1514,185 @@ extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error); * for dealing with SSL 3.0 clients sending SSL 2.0 format hellos */ extern SECStatus ssl3_HandleV2ClientHello( - sslSocket *ss, unsigned char *buffer, int length); -extern SECStatus ssl3_StartHandshakeHash( - sslSocket *ss, unsigned char *buf, int length); + sslSocket *ss, unsigned char *buffer, int length, PRUint8 padding); -/* - * SSL3 specific routines - */ -SECStatus ssl3_SendClientHello(sslSocket *ss, PRBool resending); +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, sslBuffer *out); +SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize); int ssl3_GatherAppDataRecord(sslSocket *ss, int flags); int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags); -/* - * When talking to export clients or using export cipher suites, servers - * with public RSA keys larger than 512 bits need to use a 512-bit public - * key, signed by the larger key. The smaller key is a "step down" key. - * Generate that key pair and keep it around. - */ -extern SECStatus ssl3_CreateRSAStepDownKeys(sslSocket *ss); -extern SECStatus ssl3_SelectDHParams(sslSocket *ss); +/* Create a new ref counted key pair object from two keys. */ +extern sslKeyPair *ssl_NewKeyPair(SECKEYPrivateKey *privKey, + SECKEYPublicKey *pubKey); -#ifndef NSS_DISABLE_ECC -extern void ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss); -extern PRBool ssl3_IsECCEnabled(sslSocket *ss); -extern SECStatus ssl3_DisableECCSuites(sslSocket * ss, - const ssl3CipherSuite * suite); -extern PRUint32 ssl3_GetSupportedECCurveMask(sslSocket *ss); +/* 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(const sslSocket *ss, + const SECKEYPublicKey *pubKey, + PRBool appendLength); +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 ) ) ) ) - -/* Types and names of elliptic curves used in TLS */ -typedef enum { ec_type_explicitPrime = 1, - ec_type_explicitChar2Curve = 2, - ec_type_named -} ECType; - -typedef enum { ec_noName = 0, - ec_sect163k1 = 1, - ec_sect163r1 = 2, - ec_sect163r2 = 3, - ec_sect193r1 = 4, - ec_sect193r2 = 5, - ec_sect233k1 = 6, - ec_sect233r1 = 7, - ec_sect239k1 = 8, - ec_sect283k1 = 9, - ec_sect283r1 = 10, - ec_sect409k1 = 11, - ec_sect409r1 = 12, - ec_sect571k1 = 13, - ec_sect571r1 = 14, - ec_secp160k1 = 15, - ec_secp160r1 = 16, - ec_secp160r2 = 17, - ec_secp192k1 = 18, - ec_secp192r1 = 19, - ec_secp224k1 = 20, - ec_secp224r1 = 21, - ec_secp256k1 = 22, - ec_secp256r1 = 23, - ec_secp384r1 = 24, - ec_secp521r1 = 25, - ec_pastLastName -} ECName; - -extern SECStatus ssl3_ECName2Params(PLArenaPool *arena, ECName curve, - SECKEYECParams *params); -ECName ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits); - - -#endif /* NSS_DISABLE_ECC */ +#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 ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled); -extern SECStatus ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled); extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on); -extern SECStatus ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *on); -extern SECStatus ssl2_CipherPrefSet(sslSocket *ss, PRInt32 which, PRBool enabled); -extern SECStatus ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled); +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 SECStatus ssl2_SetPolicy(PRInt32 which, PRInt32 policy); -extern SECStatus ssl2_GetPolicy(PRInt32 which, PRInt32 *policy); - -extern void ssl2_InitSocketPolicy(sslSocket *ss); -extern void ssl3_InitSocketPolicy(sslSocket *ss); -extern SECStatus ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, - unsigned char *cs, int *size); +extern void ssl3_InitSocketPolicy(sslSocket *ss); extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache); -extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, - PRUint32 length); +extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, + PRUint32 length, + PRBool endOfRecord); extern void ssl3_DestroySSL3Info(sslSocket *ss); -extern SECStatus ssl3_NegotiateVersion(sslSocket *ss, - SSL3ProtocolVersion peerVersion, - PRBool allowLargerPeerVersion); +extern SECStatus ssl_ClientReadVersion(sslSocket *ss, SSL3Opaque **b, + PRUint32 *length, + SSL3ProtocolVersion *version); +extern SECStatus ssl3_NegotiateVersion(sslSocket *ss, + SSL3ProtocolVersion peerVersion, + PRBool allowLargerPeerVersion); extern SECStatus ssl_GetPeerInfo(sslSocket *ss); -#ifndef NSS_DISABLE_ECC /* ECDH functions */ -extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket * ss, - SECKEYPublicKey * svrPubKey); -extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, - SSL3Opaque *b, PRUint32 length); -extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, - SSL3Opaque *b, PRUint32 length, - SECKEYPublicKey *srvrPubKey, - SECKEYPrivateKey *srvrPrivKey); -extern SECStatus ssl3_SendECDHServerKeyExchange( - sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash); -#endif +extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket *ss, + SECKEYPublicKey *svrPubKey); +extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, + SSL3Opaque *b, PRUint32 length); +extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, + SSL3Opaque *b, PRUint32 length, + sslKeyPair *serverKeys); +extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss); +extern SECStatus ssl_ImportECDHKeyShare( + sslSocket *ss, SECKEYPublicKey *peerKey, + SSL3Opaque *b, PRUint32 length, const sslNamedGroupDef *curve); +unsigned int tls13_SizeOfECDHEKeyShareKEX(const SECKEYPublicKey *pubKey); +SECStatus tls13_EncodeECDHEKeyShareKEX(const sslSocket *ss, + const SECKEYPublicKey *pubKey); extern SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg, - PRUint8 * hashBuf, - unsigned int bufLen, SSL3Hashes *hashes, - PRBool bypassPKCS11); + PRUint8 *hashBuf, + unsigned int bufLen, + SSL3Hashes *hashes); extern void ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName); extern SECStatus ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms); -extern SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, - PRInt32 bytes); -extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss, - SSL3HandshakeType t, PRUint32 length); -extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, - PRInt32 lenSize); -extern SECStatus ssl3_AppendHandshakeVariable( sslSocket *ss, - const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize); +extern SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, + PRInt32 bytes); +extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss, + SSL3HandshakeType t, PRUint32 length); +extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, + PRInt32 lenSize); +extern SECStatus ssl3_AppendHandshakeVariable(sslSocket *ss, + const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize); extern SECStatus ssl3_AppendSignatureAndHashAlgorithm( - sslSocket *ss, const SSLSignatureAndHashAlg* sigAndHash); -extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, - SSL3Opaque **b, PRUint32 *length); -extern PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, - SSL3Opaque **b, PRUint32 *length); -extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, - PRInt32 bytes, SSL3Opaque **b, PRUint32 *length); -extern PRBool ssl3_IsSupportedSignatureAlgorithm( - const SSLSignatureAndHashAlg *alg); -extern SECStatus ssl3_CheckSignatureAndHashAlgorithmConsistency( - sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash, - CERTCertificate* cert); -extern SECStatus ssl3_ConsumeSignatureAndHashAlgorithm( - sslSocket *ss, SSL3Opaque **b, PRUint32 *length, - SSLSignatureAndHashAlg *out); -extern SECStatus ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, - SECItem *buf, PRBool isTLS); -extern SECStatus ssl3_VerifySignedHashes(SSL3Hashes *hash, - CERTCertificate *cert, SECItem *buf, PRBool isTLS, - void *pwArg); -extern SECStatus ssl3_CacheWrappedMasterSecret(sslSocket *ss, - sslSessionID *sid, ssl3CipherSpec *spec, - SSL3KEAType effectiveExchKeyType); - -/* Functions that handle ClientHello and ServerHello extensions. */ -extern SECStatus ssl3_HandleServerNameXtn(sslSocket * ss, - PRUint16 ex_type, SECItem *data); -extern SECStatus ssl3_HandleSupportedCurvesXtn(sslSocket * ss, - PRUint16 ex_type, SECItem *data); -extern SECStatus ssl3_HandleSupportedPointFormatsXtn(sslSocket * ss, - PRUint16 ex_type, SECItem *data); -extern SECStatus ssl3_ClientHandleSessionTicketXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); -extern SECStatus ssl3_ServerHandleSessionTicketXtn(sslSocket *ss, - PRUint16 ex_type, SECItem *data); - -/* ClientHello and ServerHello extension senders. - * Note that not all extension senders are exposed here; only those that - * that need exposure. - */ -extern PRInt32 ssl3_SendSessionTicketXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); - -/* ClientHello and ServerHello extension senders. - * The code is in ssl3ext.c. - */ -extern PRInt32 ssl3_SendServerNameXtn(sslSocket *ss, PRBool append, - PRUint32 maxBytes); - -/* Assigns new cert, cert chain and keys to ss->serverCerts - * struct. If certChain is NULL, tries to find one. Aborts if - * fails to do so. If cert and keyPair are NULL - unconfigures - * sslSocket of kea type.*/ -extern SECStatus ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, - const CERTCertificateList *certChain, - ssl3KeyPair *keyPair, SSLKEAType kea); - -#ifndef NSS_DISABLE_ECC -extern PRInt32 ssl3_SendSupportedCurvesXtn(sslSocket *ss, - PRBool append, PRUint32 maxBytes); -extern PRInt32 ssl3_SendSupportedPointFormatsXtn(sslSocket *ss, - PRBool append, PRUint32 maxBytes); -#endif - -/* call the registered extension handlers. */ -extern SECStatus ssl3_HandleHelloExtensions(sslSocket *ss, - SSL3Opaque **b, PRUint32 *length); + sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash); +extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length); +extern PRInt32 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, + SSL3Opaque **b, PRUint32 *length); +extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, + PRInt32 bytes, SSL3Opaque **b, + PRUint32 *length); +extern PRUint8 *ssl_EncodeUintX(PRUint64 value, unsigned int bytes, + PRUint8 *to); +extern PRBool ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme); +extern SECStatus ssl_CheckSignatureSchemeConsistency( + sslSocket *ss, SSLSignatureScheme scheme, CERTCertificate *cert); +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, SSL3Opaque **b, PRUint32 *length, SSLSignatureScheme *out); +extern SECStatus ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash, + SECKEYPrivateKey *key, SECItem *buf); +extern SECStatus ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme, + SSL3Hashes *hash, SECItem *buf); +extern SECStatus ssl3_CacheWrappedMasterSecret( + sslSocket *ss, sslSessionID *sid, + ssl3CipherSpec *spec, SSLAuthType authType); +extern void ssl3_FreeSniNameArray(TLSExtensionData *xtnData); /* Hello Extension related routines. */ -extern PRBool ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type); extern void ssl3_SetSIDSessionTicket(sslSessionID *sid, - /*in/out*/ NewSessionTicket *session_ticket); -extern SECStatus ssl3_SendNewSessionTicket(sslSocket *ss); -extern PRBool ssl_GetSessionTicketKeys(unsigned char *keyName, - unsigned char *encKey, unsigned char *macKey); -extern PRBool ssl_GetSessionTicketKeysPKCS11(SECKEYPrivateKey *svrPrivKey, - SECKEYPublicKey *svrPubKey, void *pwArg, - unsigned char *keyName, PK11SymKey **aesKey, - PK11SymKey **macKey); + /*in/out*/ NewSessionTicket *session_ticket); +SECStatus ssl3_EncodeSessionTicket(sslSocket *ss, + const NewSessionTicket *ticket_input, + SECItem *ticket_data); +extern PRBool ssl_GetSessionTicketKeys(SECKEYPrivateKey *svrPrivKey, + SECKEYPublicKey *svrPubKey, void *pwArg, + unsigned char *keyName, PK11SymKey **aesKey, + PK11SymKey **macKey); +extern SECStatus ssl3_SessionTicketShutdown(void *appData, void *nssData); /* Tell clients to consider tickets valid for this long. */ -#define TLS_EX_SESS_TICKET_LIFETIME_HINT (2 * 24 * 60 * 60) /* 2 days */ -#define TLS_EX_SESS_TICKET_VERSION (0x0101) +#define TLS_EX_SESS_TICKET_LIFETIME_HINT (2 * 24 * 60 * 60) /* 2 days */ +#define TLS_EX_SESS_TICKET_VERSION (0x0103) -extern SECStatus ssl3_ValidateNextProtoNego(const unsigned char* data, - unsigned int length); +extern SECStatus ssl3_ValidateNextProtoNego(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); @@ -1853,30 +1702,18 @@ extern void ssl_FreePRSocket(PRFileDesc *fd); * various ciphers */ extern int ssl3_config_match_init(sslSocket *); - -/* Create a new ref counted key pair object from two keys. */ -extern ssl3KeyPair * ssl3_NewKeyPair( SECKEYPrivateKey * privKey, - SECKEYPublicKey * pubKey); - -/* get a new reference (bump ref count) to an ssl3KeyPair. */ -extern ssl3KeyPair * ssl3_GetKeyPairRef(ssl3KeyPair * keyPair); - -/* Decrement keypair's ref count and free if zero. */ -extern void ssl3_FreeKeyPair(ssl3KeyPair * keyPair); - /* calls for accessing wrapping keys across processes. */ extern PRBool -ssl_GetWrappingKey( PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk); +ssl_GetWrappingKey(PRInt32 symWrapMechIndex, SSLAuthType authType, + 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 + * 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 PRBool @@ -1893,42 +1730,101 @@ extern SECStatus ssl_InitSessionCacheLocks(PRBool lazyInit); extern SECStatus ssl_FreeSessionCacheLocks(void); - /**************** DTLS-specific functions **************/ -extern void dtls_FreeQueuedMessage(DTLSQueuedMessage *msg); -extern void dtls_FreeQueuedMessages(PRCList *lst); +extern void dtls_FreeHandshakeMessage(DTLSQueuedMessage *msg); extern void dtls_FreeHandshakeMessages(PRCList *lst); extern SECStatus dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf); extern SECStatus dtls_HandleHelloVerifyRequest(sslSocket *ss, - SSL3Opaque *b, PRUint32 length); + SSL3Opaque *b, PRUint32 length); extern SECStatus dtls_StageHandshakeMessage(sslSocket *ss); extern SECStatus dtls_QueueMessage(sslSocket *ss, SSL3ContentType type, - const SSL3Opaque *pIn, PRInt32 nIn); + const SSL3Opaque *pIn, PRInt32 nIn); extern SECStatus dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags); -extern SECStatus dtls_CompressMACEncryptRecord(sslSocket *ss, - DTLSEpoch epoch, - PRBool use_epoch, - SSL3ContentType type, - const SSL3Opaque *pIn, - PRUint32 contentLen, - sslBuffer *wrBuf); -SECStatus ssl3_DisableNonDTLSSuites(sslSocket * ss); -extern SECStatus dtls_StartTimer(sslSocket *ss, DTLSTimerCb cb); -extern SECStatus dtls_RestartTimer(sslSocket *ss, PRBool backoff, - DTLSTimerCb cb); +SECStatus ssl3_DisableNonDTLSSuites(sslSocket *ss); +extern SECStatus dtls_StartHolddownTimer(sslSocket *ss); extern void dtls_CheckTimer(sslSocket *ss); extern void dtls_CancelTimer(sslSocket *ss); -extern void dtls_FinishedTimerCb(sslSocket *ss); extern void dtls_SetMTU(sslSocket *ss, PRUint16 advertised); extern void dtls_InitRecvdRecords(DTLSRecvdRecords *records); -extern int dtls_RecordGetRecvd(DTLSRecvdRecords *records, PRUint64 seq); -extern void dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq); +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); +extern PRBool dtls_IsRelevant(sslSocket *ss, const SSL3Ciphertext *cText, + PRBool *sameEpoch, PRUint64 *seqNum); +extern SECStatus dtls_MaybeRetransmitHandshake(sslSocket *ss, + const SSL3Ciphertext *cText, + PRBool sameEpoch); + +CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg); +SECStatus ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites, + PRBool initHashes); +SECStatus ssl3_InitHandshakeHashes(sslSocket *ss); +SECStatus ssl3_ServerCallSNICallback(sslSocket *ss); +SECStatus ssl3_SetupPendingCipherSpec(sslSocket *ss); +SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags); +SECStatus ssl3_CompleteHandleCertificate(sslSocket *ss, + SSL3Opaque *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 ssl3_AuthCertificate(sslSocket *ss); +SECStatus ssl_ReadCertificateStatus(sslSocket *ss, SSL3Opaque *b, + PRUint32 length); +SECStatus ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint8 *buf, + unsigned maxLen, PRUint32 *len); +void ssl3_GetCertificateRequestCAs(sslSocket *ss, int *calenp, SECItem **namesp, + int *nnamesp); +SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss, SSL3Opaque **b, + PRUint32 *length, PLArenaPool *arena, + CERTDistNames *ca_list); +SECStatus ssl3_CompleteHandleCertificateRequest( + sslSocket *ss, const SSLSignatureScheme *signatureSchemes, + unsigned int signatureSchemeCount, CERTDistNames *ca_list); +SECStatus ssl3_SendServerHello(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); +PK11SymKey *ssl3_GetWrappingKey(sslSocket *ss, + PK11SlotInfo *masterSecretSlot, + const sslServerCert *serverCert, + CK_MECHANISM_TYPE masterWrapMech, + void *pwArg); +SECStatus ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid); +const ssl3CipherSuiteDef *ssl_LookupCipherSuiteDef(ssl3CipherSuite suite); +const ssl3BulkCipherDef * +ssl_GetBulkCipherDef(const ssl3CipherSuiteDef *cipher_def); +SECStatus ssl3_SelectServerCert(sslSocket *ss); +SECStatus ssl_PickSignatureScheme(sslSocket *ss, + SECKEYPublicKey *pubKey, + SECKEYPrivateKey *privKey, + const SSLSignatureScheme *peerSchemes, + unsigned int peerSchemeCount, + PRBool requireSha1); +SECOidTag ssl3_HashTypeToOID(SSLHashType hashType); +SSLHashType ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme); +KeyType ssl_SignatureSchemeToKeyType(SSLSignatureScheme scheme); + +SECStatus ssl3_SetCipherSuite(sslSocket *ss, ssl3CipherSuite chosenSuite, + PRBool initHashes); + +/* Pull in TLS 1.3 functions */ +#include "tls13con.h" /********************** misc calls *********************/ @@ -1940,19 +1836,19 @@ extern int ssl_MapLowLevelError(int hiLevelError); extern PRUint32 ssl_Time(void); -extern void SSL_AtomicIncrementLong(long * x); +extern void SSL_AtomicIncrementLong(long *x); + +SECStatus ssl3_ApplyNSSPolicy(void); -SECStatus SSL_DisableDefaultExportCipherSuites(void); -SECStatus SSL_DisableExportCipherSuites(PRFileDesc * fd); -PRBool SSL_IsExportCipherSuite(PRUint16 cipherSuite); +extern HASH_HashType +ssl3_GetTls12HashType(sslSocket *ss); extern SECStatus ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label, unsigned int labelLen, const unsigned char *val, unsigned int valLen, - unsigned char *out, unsigned int outLen); -extern SECOidTag -ssl3_TLSHashAlgorithmToOID(SSLHashType hashFunc); + unsigned char *out, unsigned int outLen, + HASH_HashType tls12HashType); #ifdef TRACE #define SSL_TRACE(msg) ssl_Trace msg diff --git a/nss/lib/ssl/sslinfo.c b/nss/lib/ssl/sslinfo.c index 216ab0f..665109d 100644 --- a/nss/lib/ssl/sslinfo.c +++ b/nss/lib/ssl/sslinfo.c @@ -1,42 +1,47 @@ +/* -*- 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 "ssl.h" #include "sslimpl.h" #include "sslproto.h" +#include "tls13hkdf.h" static const char * ssl_GetCompressionMethodName(SSLCompressionMethod compression) { switch (compression) { - case ssl_compression_null: - return "NULL"; + case ssl_compression_null: + return "NULL"; #ifdef NSS_ENABLE_ZLIB - case ssl_compression_deflate: - return "DEFLATE"; + case ssl_compression_deflate: + return "DEFLATE"; #endif - default: - return "???"; + default: + return "???"; } } -SECStatus +SECStatus SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) { - sslSocket * ss; - SSLChannelInfo inf; - sslSessionID * sid; + sslSocket *ss; + SSLChannelInfo inf; + sslSessionID *sid; - if (!info || len < sizeof inf.length) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + /* 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; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelInfo", + SSL_GETPID(), fd)); + return SECFailure; } memset(&inf, 0, sizeof inf); @@ -44,42 +49,61 @@ SSL_GetChannelInfo(PRFileDesc *fd, SSLChannelInfo *info, PRUintn len) if (ss->opt.useSecurity && ss->enoughFirstHsDone) { sid = ss->sec.ci.sid; - inf.protocolVersion = ss->version; - inf.authKeyBits = ss->sec.authKeyBits; - inf.keaKeyBits = ss->sec.keaKeyBits; - if (ss->version < SSL_LIBRARY_VERSION_3_0) { /* SSL2 */ - inf.cipherSuite = ss->sec.cipherType | 0xff00; - inf.compressionMethod = ssl_compression_null; - inf.compressionMethodName = "N/A"; - } else if (ss->ssl3.initialized) { /* SSL3 and TLS */ - 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; - inf.compressionMethod = ss->ssl3.cwSpec->compression_method; - ssl_ReleaseSpecReadLock(ss); - inf.compressionMethodName = - ssl_GetCompressionMethodName(inf.compressionMethod); - } - if (sid) { - inf.creationTime = sid->creationTime; - inf.lastAccessTime = sid->lastAccessTime; - inf.expirationTime = sid->expirationTime; - inf.extendedMasterSecretUsed = sid->u.ssl3.keys.extendedMasterSecretUsed; - - if (ss->version < SSL_LIBRARY_VERSION_3_0) { /* SSL2 */ - inf.sessionIDLength = SSL2_SESSIONID_BYTES; - memcpy(inf.sessionID, sid->u.ssl2.sessionID, - SSL2_SESSIONID_BYTES); - } else { - unsigned int sidLen = sid->u.ssl3.sessionIDLength; - sidLen = PR_MIN(sidLen, sizeof inf.sessionID); - inf.sessionIDLength = sidLen; - memcpy(inf.sessionID, sid->u.ssl3.sessionID, sidLen); - } - } + inf.protocolVersion = ss->version; + inf.authKeyBits = ss->sec.authKeyBits; + inf.keaKeyBits = ss->sec.keaKeyBits; + if (ss->ssl3.initialized) { + SSLCipherSuiteInfo cinfo; + SECStatus rv; + + 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; + inf.compressionMethod = ss->ssl3.cwSpec->compression_method; + ssl_ReleaseSpecReadLock(ss); + inf.compressionMethodName = + ssl_GetCompressionMethodName(inf.compressionMethod); + + /* 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.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 (sid) { + unsigned int sidLen; + + inf.creationTime = sid->creationTime; + inf.lastAccessTime = sid->lastAccessTime; + inf.expirationTime = sid->expirationTime; + 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); + } } memcpy(info, &inf, inf.length); @@ -95,7 +119,10 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, sslSocket *ss; SSLPreliminaryChannelInfo inf; - if (!info || len < sizeof inf.length) { + /* 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; } @@ -107,11 +134,6 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, return SECFailure; } - if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION); - return SECFailure; - } - memset(&inf, 0, sizeof(inf)); inf.length = PR_MIN(sizeof(inf), len); @@ -123,212 +145,197 @@ SSL_GetPreliminaryChannelInfo(PRFileDesc *fd, return SECSuccess; } +/* name */ +#define CS_(x) x, #x +#define CS(x) CS_(TLS_##x) -#define CS(x) x, #x -#define CK(x) x | 0xff00, #x - -#define S_DSA "DSA", ssl_auth_dsa -#define S_RSA "RSA", ssl_auth_rsa -#define S_KEA "KEA", ssl_auth_kea +/* 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 K_DHE "DHE", kt_dh -#define K_RSA "RSA", kt_rsa -#define K_KEA "KEA", kt_kea -#define K_ECDH "ECDH", kt_ecdh -#define K_ECDHE "ECDHE", kt_ecdh - -#define C_SEED "SEED", calg_seed +#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", calg_seed #define C_CAMELLIA "CAMELLIA", calg_camellia -#define C_AES "AES", calg_aes -#define C_RC4 "RC4", calg_rc4 -#define C_RC2 "RC2", calg_rc2 -#define C_DES "DES", calg_des -#define C_3DES "3DES", calg_3des -#define C_NULL "NULL", calg_null -#define C_SJ "SKIPJACK", calg_sj +#define C_AES "AES", calg_aes +#define C_RC4 "RC4", calg_rc4 +#define C_RC2 "RC2", calg_rc2 +#define C_DES "DES", calg_des +#define C_3DES "3DES", calg_3des +#define C_NULL "NULL", calg_null +#define C_SJ "SKIPJACK", calg_sj #define C_AESGCM "AES-GCM", calg_aes_gcm - -#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 - +#define C_CHACHA20 "CHACHA20POLY1305", 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 +#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 */ static const SSLCipherSuiteInfo suiteInfo[] = { -/* <------ Cipher suite --------------------> <auth> <KEA> <bulk cipher> <MAC> <FIPS> */ -{0,CS(TLS_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, - -{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, 1, 0, 0, }, - -{0,CS(TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, -{0,CS(TLS_DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256), S_DSA, K_DHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED,B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, 1, 0, 0, }, - -{0,CS(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES,B_3DES,M_SHA, 1, 0, 0, }, -{0,CS(SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 1, }, -{0,CS(TLS_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES,B_3DES,M_SHA, 1, 0, 0, }, - -{0,CS(TLS_DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0, }, -{0,CS(TLS_DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, 0, 0, 0, }, -{0,CS(SSL_RSA_FIPS_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 1, }, -{0,CS(TLS_RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 0, 0, }, - -{0,CS(TLS_RSA_EXPORT1024_WITH_RC4_56_SHA), S_RSA, K_RSA, C_RC4, B_56, M_SHA, 0, 1, 0, }, -{0,CS(TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 1, 0, }, -{0,CS(TLS_RSA_EXPORT_WITH_RC4_40_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0, }, -{0,CS(TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0, }, -{0,CS(TLS_RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL,B_0, M_SHA256, 0, 1, 0, }, -{0,CS(TLS_RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL,B_0, M_SHA, 0, 1, 0, }, -{0,CS(TLS_RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL,B_0, M_MD5, 0, 1, 0, }, - -#ifndef NSS_DISABLE_ECC -/* ECC cipher suites */ -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, }, - -{0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0, }, - -{0,CS(TLS_ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0, }, - -{0,CS(TLS_ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0, }, - -{0,CS(TLS_ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0, }, -{0,CS(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0, }, -#endif /* NSS_DISABLE_ECC */ - -/* SSL 2 table */ -{0,CK(SSL_CK_RC4_128_WITH_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_RC2_128_CBC_WITH_MD5), S_RSA, K_RSA, C_RC2, B_128, M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_DES_192_EDE3_CBC_WITH_MD5), S_RSA, K_RSA, C_3DES,B_3DES,M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_DES_64_CBC_WITH_MD5), S_RSA, K_RSA, C_DES, B_DES, M_MD5, 0, 0, 0, }, -{0,CK(SSL_CK_RC4_128_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC4, B_40, M_MD5, 0, 1, 0, }, -{0,CK(SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5), S_RSA, K_RSA, C_RC2, B_40, M_MD5, 0, 1, 0, } + /* <------ 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 }, + { 0, CS_(TLS_CHACHA20_POLY1305_SHA256), S_ANY, K_ANY, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_ANY }, + { 0, CS_(TLS_AES_256_GCM_SHA384), S_ANY, K_ANY, C_AESGCM, B_256, M_AEAD_128, F_NFIPS_STD, A_ANY }, + + { 0, CS(RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_RSA, C_AESGCM, B_128, M_AEAD_128, F_FIPS_STD, A_RSAD }, + { 0, CS(DHE_RSA_WITH_CHACHA20_POLY1305_SHA256), S_RSA, K_DHE, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_RSAS }, + + { 0, CS(DHE_RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_256, M_SHA, F_NFIPS_STD, A_RSAS }, + { 0, CS(DHE_DSS_WITH_CAMELLIA_256_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_256, M_SHA, F_NFIPS_STD, A_DSA }, + { 0, CS(DHE_RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_DHE, C_AES, B_256, M_SHA256, F_FIPS_STD, A_RSAS }, + { 0, CS(DHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_DHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_RSAS }, + { 0, CS(DHE_DSS_WITH_AES_256_CBC_SHA), S_DSA, K_DHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_DSA }, + { 0, CS(DHE_DSS_WITH_AES_256_CBC_SHA256), S_DSA, K_DHE, C_AES, B_256, M_SHA256, F_FIPS_STD, A_DSA }, + { 0, CS(RSA_WITH_CAMELLIA_256_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_256, M_SHA, F_NFIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_AES_256_CBC_SHA256), S_RSA, K_RSA, C_AES, B_256, M_SHA256, F_FIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_AES_256_CBC_SHA), S_RSA, K_RSA, C_AES, B_256, M_SHA, F_FIPS_STD, A_RSAD }, + + { 0, CS(DHE_RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_DHE, C_CAMELLIA, B_128, M_SHA, F_NFIPS_STD, A_RSAS }, + { 0, CS(DHE_DSS_WITH_CAMELLIA_128_CBC_SHA), S_DSA, K_DHE, C_CAMELLIA, B_128, M_SHA, F_NFIPS_STD, A_DSA }, + { 0, CS(DHE_DSS_WITH_RC4_128_SHA), S_DSA, K_DHE, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_DSA }, + { 0, CS(DHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_DHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_RSAS }, + { 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 }, + { 0, CS(DHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_DHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_RSAS }, + { 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 }, + { 0, CS(DHE_DSS_WITH_AES_128_CBC_SHA), S_DSA, K_DHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_DSA }, + { 0, CS(DHE_DSS_WITH_AES_128_CBC_SHA256), S_DSA, K_DHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_DSA }, + { 0, CS(RSA_WITH_SEED_CBC_SHA), S_RSA, K_RSA, C_SEED, B_128, M_SHA, F_FIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_CAMELLIA_128_CBC_SHA), S_RSA, K_RSA, C_CAMELLIA, B_128, M_SHA, F_NFIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_RC4_128_SHA), S_RSA, K_RSA, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_RC4_128_MD5), S_RSA, K_RSA, C_RC4, B_128, M_MD5, F_NFIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_RSA, C_AES, B_128, M_SHA256, F_FIPS_STD, A_RSAD }, + { 0, CS(RSA_WITH_AES_128_CBC_SHA), S_RSA, K_RSA, C_AES, B_128, M_SHA, F_FIPS_STD, A_RSAD }, + + { 0, CS(DHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_DHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_RSAS }, + { 0, CS(DHE_DSS_WITH_3DES_EDE_CBC_SHA), S_DSA, K_DHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_DSA }, + { 0, CS(RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_RSA, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_RSAD }, + + { 0, CS(DHE_RSA_WITH_DES_CBC_SHA), S_RSA, K_DHE, C_DES, B_DES, M_SHA, F_NFIPS_STD, A_RSAS }, + { 0, CS(DHE_DSS_WITH_DES_CBC_SHA), S_DSA, K_DHE, C_DES, B_DES, M_SHA, F_NFIPS_STD, A_DSA }, + { 0, CS(RSA_WITH_DES_CBC_SHA), S_RSA, K_RSA, C_DES, B_DES, M_SHA, F_NFIPS_STD, A_RSAD }, + + { 0, CS(RSA_WITH_NULL_SHA256), S_RSA, K_RSA, C_NULL, B_0, M_SHA256, F_EXPORT, A_RSAD }, + { 0, CS(RSA_WITH_NULL_SHA), S_RSA, K_RSA, C_NULL, B_0, M_SHA, F_EXPORT, A_RSAD }, + { 0, CS(RSA_WITH_NULL_MD5), S_RSA, K_RSA, C_NULL, B_0, M_MD5, F_EXPORT, A_RSAD }, + + /* 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 }, + { 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 }, + { 0, CS(ECDH_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_ECDH_E }, + { 0, CS(ECDH_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_ECDH_E }, + { 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 }, + { 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 }, + { 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 }, + + { 0, CS(ECDHE_ECDSA_WITH_NULL_SHA), S_ECDSA, K_ECDHE, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_ECDSA }, + { 0, CS(ECDHE_ECDSA_WITH_RC4_128_SHA), S_ECDSA, K_ECDHE, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_ECDSA }, + { 0, CS(ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA), S_ECDSA, K_ECDHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_ECDSA }, + { 0, CS(ECDHE_ECDSA_WITH_AES_128_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_ECDSA }, + { 0, CS(ECDHE_ECDSA_WITH_AES_128_CBC_SHA256), S_ECDSA, K_ECDHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_ECDSA }, + { 0, CS(ECDHE_ECDSA_WITH_AES_256_CBC_SHA), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_ECDSA }, + { 0, CS(ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256), S_ECDSA, K_ECDHE, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_ECDSA }, + + { 0, CS(ECDH_RSA_WITH_NULL_SHA), S_RSA, K_ECDH, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_ECDH_R }, + { 0, CS(ECDH_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDH, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_ECDH_R }, + { 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 }, + { 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 }, + { 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 }, + + { 0, CS(ECDHE_RSA_WITH_NULL_SHA), S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, F_NFIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_RC4_128_SHA), S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, F_NFIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_3DES_EDE_CBC_SHA), S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, F_FIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_AES_128_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_128, M_SHA, F_FIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, F_FIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_AES_256_CBC_SHA), S_RSA, K_ECDHE, C_AES, B_256, M_SHA, F_FIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256), S_RSA, K_ECDHE, C_CHACHA20, B_256, M_AEAD_128, F_NFIPS_STD, A_RSAS }, + { 0, CS(ECDHE_RSA_WITH_AES_256_CBC_SHA384), S_RSA, K_ECDHE, C_AES, B_256, M_SHA384, F_FIPS_STD, A_RSAS }, + { 0, CS(ECDHE_ECDSA_WITH_AES_256_CBC_SHA384), S_ECDSA, K_ECDHE, C_AES, B_256, M_SHA384, F_FIPS_STD, A_ECDSA }, + { 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 }, + { 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 }, + + { 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 }, + { 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 }, + { 0, CS(RSA_WITH_AES_256_GCM_SHA384), S_RSA, K_RSA, C_AESGCM, B_256, M_AEAD_128, F_FIPS_STD, A_RSAD }, }; #define NUM_SUITEINFOS ((sizeof suiteInfo) / (sizeof suiteInfo[0])) - -SECStatus SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, - SSLCipherSuiteInfo *info, PRUintn len) +SECStatus +SSL_GetCipherSuiteInfo(PRUint16 cipherSuite, + SSLCipherSuiteInfo *info, PRUintn len) { unsigned int i; - len = PR_MIN(len, sizeof suiteInfo[0]); - if (!info || len < sizeof suiteInfo[0].length) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + /* 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; - } + if (suiteInfo[i].cipherSuite == cipherSuite) { + memcpy(info, &suiteInfo[i], len); + info->length = len; + return SECSuccess; + } } + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } -/* This function might be a candidate to be public. - * Disables all export ciphers in the default set of enabled ciphers. - */ -SECStatus -SSL_DisableDefaultExportCipherSuites(void) -{ - const SSLCipherSuiteInfo * pInfo = suiteInfo; - unsigned int i; - - for (i = 0; i < NUM_SUITEINFOS; ++i, ++pInfo) { - if (pInfo->isExportable) { - PORT_CheckSuccess(SSL_CipherPrefSetDefault(pInfo->cipherSuite, PR_FALSE)); - } - } - return SECSuccess; -} - -/* This function might be a candidate to be public, - * except that it takes an sslSocket pointer as an argument. - * A Public version would take a PRFileDesc pointer. - * Disables all export ciphers in the default set of enabled ciphers. - */ -SECStatus -SSL_DisableExportCipherSuites(PRFileDesc * fd) -{ - const SSLCipherSuiteInfo * pInfo = suiteInfo; - unsigned int i; - - for (i = 0; i < NUM_SUITEINFOS; ++i, ++pInfo) { - if (pInfo->isExportable) { - PORT_CheckSuccess(SSL_CipherPrefSet(fd, pInfo->cipherSuite, PR_FALSE)); - } - } - return SECSuccess; -} - -/* Tells us if the named suite is exportable - * returns false for unknown suites. - */ -PRBool -SSL_IsExportCipherSuite(PRUint16 cipherSuite) -{ - unsigned int i; - for (i = 0; i < NUM_SUITEINFOS; i++) { - if (suiteInfo[i].cipherSuite == cipherSuite) { - return (PRBool)(suiteInfo[i].isExportable); - } - } - return PR_FALSE; -} - -SECItem* +SECItem * SSL_GetNegotiatedHostInfo(PRFileDesc *fd) { SECItem *sniName = NULL; @@ -337,9 +344,9 @@ SSL_GetNegotiatedHostInfo(PRFileDesc *fd) ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNegotiatedHostInfo", - SSL_GETPID(), fd)); - return NULL; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNegotiatedHostInfo", + SSL_GETPID(), fd)); + return NULL; } if (ss->sec.isServer) { @@ -347,14 +354,14 @@ SSL_GetNegotiatedHostInfo(PRFileDesc *fd) ss->ssl3.initialized) { /* TLS */ SECItem *crsName; ssl_GetSpecReadLock(ss); /*********************************/ - crsName = &ss->ssl3.cwSpec->srvVirtName; + 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); @@ -362,12 +369,30 @@ SSL_GetNegotiatedHostInfo(PRFileDesc *fd) PORT_Free(name); return NULL; } - sniName->data = (void*)name; - sniName->len = PORT_Strlen(name); + sniName->data = (void *)name; + sniName->len = PORT_Strlen(name); } return sniName; } +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) +{ + if (!secret) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + return tls13_HkdfExpandLabelRaw(secret, + tls13_GetHash(ss), + context, contextLen, + label, labelLen, + out, outLen); +} + SECStatus SSL_ExportKeyingMaterial(PRFileDesc *fd, const char *label, unsigned int labelLen, @@ -382,24 +407,32 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd, ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in ExportKeyingMaterial", - SSL_GETPID(), fd)); - return SECFailure; + 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_3_1_TLS) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_VERSION); - 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); } /* construct PRF arguments */ valLen = SSL3_RANDOM_LENGTH * 2; if (hasContext) { - valLen += 2 /* PRUint16 length */ + contextLen; + valLen += 2 /* PRUint16 length */ + contextLen; } val = PORT_Alloc(valLen); if (!val) { - return SECFailure; + return SECFailure; } i = 0; PORT_Memcpy(val + i, &ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH); @@ -407,10 +440,10 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd, PORT_Memcpy(val + i, &ss->ssl3.hs.server_random.rand, SSL3_RANDOM_LENGTH); i += SSL3_RANDOM_LENGTH; if (hasContext) { - val[i++] = contextLen >> 8; - val[i++] = contextLen; - PORT_Memcpy(val + i, context, contextLen); - i += contextLen; + val[i++] = contextLen >> 8; + val[i++] = contextLen; + PORT_Memcpy(val + i, context, contextLen); + i += contextLen; } PORT_Assert(i == valLen); @@ -419,14 +452,42 @@ SSL_ExportKeyingMaterial(PRFileDesc *fd, */ ssl_GetSpecReadLock(ss); if (!ss->ssl3.cwSpec->master_secret && !ss->ssl3.cwSpec->msItem.len) { - PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); - rv = SECFailure; + PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED); + rv = SECFailure; } else { - rv = ssl3_TLSPRFWithMasterSecret(ss->ssl3.cwSpec, label, labelLen, val, - valLen, out, outLen); + HASH_HashType ht = ssl3_GetTls12HashType(ss); + rv = ssl3_TLSPRFWithMasterSecret(ss->ssl3.cwSpec, label, labelLen, val, + valLen, out, outLen, ht); } 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/nss/lib/ssl/sslinit.c b/nss/lib/ssl/sslinit.c index bb9df25..0f38c0b 100644 --- a/nss/lib/ssl/sslinit.c +++ b/nss/lib/ssl/sslinit.c @@ -11,23 +11,49 @@ #include "secerr.h" #include "ssl.h" #include "sslimpl.h" +#include "sslproto.h" -static int ssl_inited = 0; +static int ssl_isInited = 0; +static PRCallOnceType ssl_init = { 0 }; -SECStatus -ssl_Init(void) +PRStatus +ssl_InitCallOnce(void *arg) { - if (!ssl_inited) { - if (ssl_InitializePRErrorTable() != SECSuccess) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return (SECFailure); - } + int *error = (int *)arg; + SECStatus rv; + rv = ssl_InitializePRErrorTable(); + if (rv != SECSuccess) { + *error = SEC_ERROR_NO_MEMORY; + return PR_FAILURE; + } #ifdef DEBUG - ssl3_CheckCipherSuiteOrderConsistency(); + ssl3_CheckCipherSuiteOrderConsistency(); #endif - ssl_inited = 1; + 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/nss/lib/ssl/sslmutex.c b/nss/lib/ssl/sslmutex.c index af683da..560a9e8 100644 --- a/nss/lib/ssl/sslmutex.c +++ b/nss/lib/ssl/sslmutex.c @@ -4,15 +4,16 @@ #include "seccomon.h" /* This ifdef should match the one in sslsnce.c */ -#if defined(XP_UNIX) || defined(XP_WIN32) || defined (XP_OS2) || defined(XP_BEOS) +#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_OS2) || defined(XP_BEOS) #include "sslmutex.h" #include "prerr.h" -static SECStatus single_process_sslMutex_Init(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Init(sslMutex* pMutex) { - PR_ASSERT(pMutex != 0 && pMutex->u.sslLock == 0 ); - + PR_ASSERT(pMutex != 0 && pMutex->u.sslLock == 0); + pMutex->u.sslLock = PR_NewLock(); if (!pMutex->u.sslLock) { return SECFailure; @@ -20,10 +21,11 @@ static SECStatus single_process_sslMutex_Init(sslMutex* pMutex) return SECSuccess; } -static SECStatus single_process_sslMutex_Destroy(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Destroy(sslMutex* pMutex) { PR_ASSERT(pMutex != 0); - PR_ASSERT(pMutex->u.sslLock!= 0); + PR_ASSERT(pMutex->u.sslLock != 0); if (!pMutex->u.sslLock) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; @@ -32,10 +34,11 @@ static SECStatus single_process_sslMutex_Destroy(sslMutex* pMutex) return SECSuccess; } -static SECStatus single_process_sslMutex_Unlock(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Unlock(sslMutex* pMutex) { - PR_ASSERT(pMutex != 0 ); - PR_ASSERT(pMutex->u.sslLock !=0); + PR_ASSERT(pMutex != 0); + PR_ASSERT(pMutex->u.sslLock != 0); if (!pMutex->u.sslLock) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; @@ -44,10 +47,11 @@ static SECStatus single_process_sslMutex_Unlock(sslMutex* pMutex) return SECSuccess; } -static SECStatus single_process_sslMutex_Lock(sslMutex* pMutex) +static SECStatus +single_process_sslMutex_Lock(sslMutex* pMutex) { PR_ASSERT(pMutex != 0); - PR_ASSERT(pMutex->u.sslLock != 0 ); + PR_ASSERT(pMutex->u.sslLock != 0); if (!pMutex->u.sslLock) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; @@ -66,7 +70,7 @@ static SECStatus single_process_sslMutex_Lock(sslMutex* pMutex) #include "pratom.h" #define SSL_MUTEX_MAGIC 0xfeedfd -#define NONBLOCKING_POSTS 1 /* maybe this is faster */ +#define NONBLOCKING_POSTS 1 /* maybe this is faster */ #if NONBLOCKING_POSTS @@ -82,20 +86,20 @@ setNonBlocking(int fd, int nonBlocking) flags = fcntl(fd, F_GETFL, 0); if (0 > flags) - return flags; + return flags; if (nonBlocking) - flags |= FNONBLOCK; + flags |= FNONBLOCK; else - flags &= ~FNONBLOCK; + flags &= ~FNONBLOCK; err = fcntl(fd, F_SETFL, flags); return err; } #endif SECStatus -sslMutex_Init(sslMutex *pMutex, int shared) +sslMutex_Init(sslMutex* pMutex, int shared) { - int err; + int err; PR_ASSERT(pMutex); pMutex->isMultiProcess = (PRBool)(shared != 0); if (!shared) { @@ -104,17 +108,17 @@ sslMutex_Init(sslMutex *pMutex, int shared) pMutex->u.pipeStr.mPipes[0] = -1; pMutex->u.pipeStr.mPipes[1] = -1; pMutex->u.pipeStr.mPipes[2] = -1; - pMutex->u.pipeStr.nWaiters = 0; + pMutex->u.pipeStr.nWaiters = 0; err = pipe(pMutex->u.pipeStr.mPipes); if (err) { - nss_MD_unix_map_default_error(errno); - return 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; + goto loser; #endif pMutex->u.pipeStr.mPipes[2] = SSL_MUTEX_MAGIC; @@ -135,26 +139,26 @@ loser: } SECStatus -sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) +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; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } close(pMutex->u.pipeStr.mPipes[0]); close(pMutex->u.pipeStr.mPipes[1]); if (processLocal) { - return SECSuccess; + 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; + pMutex->u.pipeStr.nWaiters = 0; return SECSuccess; } @@ -164,13 +168,12 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) /* 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 +** 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) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { PRInt32 newValue; if (PR_FALSE == pMutex->isMultiProcess) { @@ -178,30 +181,30 @@ sslMutex_Unlock(sslMutex *pMutex) } if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + 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; - } + 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) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { PRInt32 newValue; if (PR_FALSE == pMutex->isMultiProcess) { @@ -209,88 +212,88 @@ sslMutex_Lock(sslMutex *pMutex) } if (pMutex->u.pipeStr.mPipes[2] != SSL_MUTEX_MAGIC) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; + 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; - } + 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 +/* 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. +** So, we don't use them on those platforms. */ -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { - int cc; - char c = 1; + 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; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } do { - cc = write(pMutex->u.pipeStr.mPipes[1], &c, 1); + 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; + 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) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { - int cc; - char c; + 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; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return SECFailure; } do { - cc = read(pMutex->u.pipeStr.mPipes[0], &c, 1); + 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; + if (cc < 0) + nss_MD_unix_map_default_error(errno); + else + PORT_SetError(PR_UNKNOWN_ERROR); + return SECFailure; } return SECSuccess; @@ -314,7 +317,8 @@ sslMutex_Lock(sslMutex *pMutex) #ifdef WINNT -SECStatus sslMutex_2LevelInit(sslMutex *sem) +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 @@ -330,7 +334,8 @@ SECStatus sslMutex_2LevelInit(sslMutex *sem) return single_process_sslMutex_Init(sem); } -static SECStatus sslMutex_2LevelDestroy(sslMutex *sem) +static SECStatus +sslMutex_2LevelDestroy(sslMutex *sem) { return single_process_sslMutex_Destroy(sem); } @@ -345,26 +350,28 @@ sslMutex_Init(sslMutex *pMutex, int shared) #endif HANDLE hMutex; SECURITY_ATTRIBUTES attributes = - { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; + + PR_ASSERT(pMutex != 0 && (pMutex->u.sslMutx == 0 || + pMutex->u.sslMutx == + INVALID_HANDLE_VALUE)); - 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)) { + + if (!pMutex || ((hMutex = pMutex->u.sslMutx) != 0 && + hMutex != + INVALID_HANDLE_VALUE)) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; } @@ -383,28 +390,32 @@ SECStatus sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) { HANDLE hMutex; - int rv; + 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 */ +/* 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 (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 - || hMutex == INVALID_HANDLE_VALUE) { + + 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; @@ -416,21 +427,25 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) return retvalue; } -int +int sslMutex_Unlock(sslMutex *pMutex) { - BOOL success = FALSE; + BOOL success = FALSE; HANDLE hMutex; - PR_ASSERT(pMutex != 0 ); + 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 && + + PR_ASSERT(pMutex->u.sslMutx != 0 && pMutex->u.sslMutx != INVALID_HANDLE_VALUE); - if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 || - hMutex == INVALID_HANDLE_VALUE) { + if ((hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); return SECFailure; } @@ -441,66 +456,69 @@ sslMutex_Unlock(sslMutex *pMutex) } #ifdef WINNT return single_process_sslMutex_Unlock(pMutex); - /* release PRLock for other fibers in the process */ +/* release PRLock for other fibers in the process */ #else return SECSuccess; #endif } -int +int sslMutex_Lock(sslMutex *pMutex) { - HANDLE hMutex; - DWORD event; - DWORD lastError; + 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 */ + /* 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 && + PR_ASSERT(pMutex->u.sslMutx != 0 && pMutex->u.sslMutx != INVALID_HANDLE_VALUE); - if (!pMutex || (hMutex = pMutex->u.sslMutx) == 0 || - hMutex == INVALID_HANDLE_VALUE) { + if ((hMutex = pMutex->u.sslMutx) == 0 || hMutex == INVALID_HANDLE_VALUE) { PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return SECFailure; /* what else ? */ + 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_OBJECT_0: + case WAIT_ABANDONED: + rv = SECSuccess; + break; - case WAIT_TIMEOUT: + case WAIT_TIMEOUT: #if defined(WAIT_IO_COMPLETION) - case WAIT_IO_COMPLETION: + case WAIT_IO_COMPLETION: #endif - default: /* should never happen. nothing we can do. */ - PR_ASSERT(!("WaitForSingleObject returned invalid value.")); - PORT_SetError(PR_UNKNOWN_ERROR); - rv = SECFailure; - break; + default: /* should never happen. nothing we can do. */ + PR_ASSERT(!("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; + 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)) { + if (!(SECSuccess == retvalue && SECSuccess == rv)) { return SECFailure; } - + return SECSuccess; } @@ -509,8 +527,8 @@ sslMutex_Lock(sslMutex *pMutex) #include <errno.h> #include "unix_err.h" -SECStatus -sslMutex_Init(sslMutex *pMutex, int shared) +SECStatus +sslMutex_Init(sslMutex* pMutex, int shared) { int rv; PR_ASSERT(pMutex); @@ -528,8 +546,8 @@ sslMutex_Init(sslMutex *pMutex, int shared) return SECSuccess; } -SECStatus -sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) +SECStatus +sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal) { int rv; if (PR_FALSE == pMutex->isMultiProcess) { @@ -538,56 +556,56 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) /* semaphores are global resources. See SEM_DESTROY(3) man page */ if (processLocal) { - return SECSuccess; + return SECSuccess; } do { - rv = sem_destroy(&pMutex->u.sem); + rv = sem_destroy(&pMutex->u.sem); } while (rv < 0 && errno == EINTR); if (rv < 0) { - nss_MD_unix_map_default_error(errno); - return SECFailure; + nss_MD_unix_map_default_error(errno); + return SECFailure; } return SECSuccess; } -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +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); + rv = sem_post(&pMutex->u.sem); } while (rv < 0 && errno == EINTR); if (rv < 0) { - nss_MD_unix_map_default_error(errno); - return SECFailure; + nss_MD_unix_map_default_error(errno); + return SECFailure; } return SECSuccess; } -SECStatus -sslMutex_Lock(sslMutex *pMutex) +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); + rv = sem_wait(&pMutex->u.sem); } while (rv < 0 && errno == EINTR); if (rv < 0) { - nss_MD_unix_map_default_error(errno); - return SECFailure; + nss_MD_unix_map_default_error(errno); + return SECFailure; } return SECSuccess; } #else -SECStatus -sslMutex_Init(sslMutex *pMutex, int shared) +SECStatus +sslMutex_Init(sslMutex* pMutex, int shared) { PR_ASSERT(pMutex); pMutex->isMultiProcess = (PRBool)(shared != 0); @@ -599,8 +617,8 @@ sslMutex_Init(sslMutex *pMutex, int shared) return SECFailure; } -SECStatus -sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) +SECStatus +sslMutex_Destroy(sslMutex* pMutex, PRBool processLocal) { PR_ASSERT(pMutex); if (PR_FALSE == pMutex->isMultiProcess) { @@ -611,8 +629,8 @@ sslMutex_Destroy(sslMutex *pMutex, PRBool processLocal) return SECFailure; } -SECStatus -sslMutex_Unlock(sslMutex *pMutex) +SECStatus +sslMutex_Unlock(sslMutex* pMutex) { PR_ASSERT(pMutex); if (PR_FALSE == pMutex->isMultiProcess) { @@ -623,8 +641,8 @@ sslMutex_Unlock(sslMutex *pMutex) return SECFailure; } -SECStatus -sslMutex_Lock(sslMutex *pMutex) +SECStatus +sslMutex_Lock(sslMutex* pMutex) { PR_ASSERT(pMutex); if (PR_FALSE == pMutex->isMultiProcess) { diff --git a/nss/lib/ssl/sslmutex.h b/nss/lib/ssl/sslmutex.h index d374a88..7611148 100644 --- a/nss/lib/ssl/sslmutex.h +++ b/nss/lib/ssl/sslmutex.h @@ -4,20 +4,20 @@ #ifndef __SSLMUTEX_H_ #define __SSLMUTEX_H_ 1 -/* What SSL really wants is portable process-shared unnamed mutexes in +/* 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. + * 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. @@ -34,8 +34,7 @@ #include <wtypes.h> -typedef struct -{ +typedef struct { PRBool isMultiProcess; #ifdef WINNT /* on WINNT we need both the PRLock and the Win32 mutex for fibers */ @@ -43,25 +42,25 @@ typedef struct #else union { #endif - PRLock* sslLock; + PRLock *sslLock; HANDLE sslMutx; } u; } sslMutex; -typedef int sslPID; +typedef int sslPID; #elif defined(LINUX) || defined(AIX) || defined(BEOS) || defined(BSDI) || (defined(NETBSD) && __NetBSD_Version__ < 500000000) || defined(OPENBSD) #include <sys/types.h> #include "prtypes.h" -typedef struct { +typedef struct { PRBool isMultiProcess; union { - PRLock* sslLock; + PRLock *sslLock; struct { - int mPipes[3]; - PRInt32 nWaiters; + int mPipes[3]; + PRInt32 nWaiters; } pipeStr; } u; } sslMutex; @@ -70,15 +69,14 @@ 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 */ +#include <sys/types.h> /* for pid_t */ +#include <semaphore.h> /* for sem_t, and sem_* functions */ -typedef struct -{ +typedef struct { PRBool isMultiProcess; union { - PRLock* sslLock; - sem_t sem; + PRLock *sslLock; + sem_t sem; } u; } sslMutex; @@ -88,10 +86,10 @@ typedef pid_t sslPID; /* what platform is this ?? */ -typedef struct { +typedef struct { PRBool isMultiProcess; union { - PRLock* sslLock; + PRLock *sslLock; /* include cross-process locking mechanism here */ } u; } sslMutex; @@ -111,7 +109,7 @@ 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 + * with the current process. Leave any shared resources (including the state of * shared memory) intact. */ extern SECStatus sslMutex_Destroy(sslMutex *sem, PRBool processLocal); diff --git a/nss/lib/ssl/sslnonce.c b/nss/lib/ssl/sslnonce.c index 2e861f1..91cc870 100644 --- a/nss/lib/ssl/sslnonce.c +++ b/nss/lib/ssl/sslnonce.c @@ -1,5 +1,5 @@ -/* - * This file implements the CLIENT Session ID cache. +/* + * 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 @@ -22,18 +22,18 @@ PRUint32 ssl_sid_timeout = 100; PRUint32 ssl3_sid_timeout = 86400L; /* 24 hours */ static sslSessionID *cache = NULL; -static PZLock * cacheLock = NULL; +static PZLock *cacheLock = NULL; /* sids can be in one of 4 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. + * 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. */ -#define LOCK_CACHE lock_cache() -#define UNLOCK_CACHE PZ_Unlock(cacheLock) +#define LOCK_CACHE lock_cache() +#define UNLOCK_CACHE PZ_Unlock(cacheLock) static SECStatus ssl_InitClientSessionCacheLock(void) @@ -62,7 +62,7 @@ FreeSessionCacheLocks() SECStatus rv1, rv2; rv1 = ssl_FreeSymWrapKeysLock(); rv2 = ssl_FreeClientSessionCacheLock(); - if ( (SECSuccess == rv1) && (SECSuccess == rv2) ) { + if ((SECSuccess == rv1) && (SECSuccess == rv2)) { return SECSuccess; } return SECFailure; @@ -75,7 +75,7 @@ InitSessionCacheLocks(void) PRErrorCode rc; rv1 = ssl_InitSymWrapKeysLock(); rv2 = ssl_InitClientSessionCacheLock(); - if ( (SECSuccess == rv1) && (SECSuccess == rv2) ) { + if ((SECSuccess == rv1) && (SECSuccess == rv2)) { return SECSuccess; } rc = PORT_GetError(); @@ -101,7 +101,8 @@ ssl_FreeSessionCacheLocks() static PRCallOnceType lockOnce; /* free the session cache locks if they were initialized lazily */ -static SECStatus ssl_ShutdownLocks(void* appData, void* nssData) +static SECStatus +ssl_ShutdownLocks(void *appData, void *nssData) { PORT_Assert(PR_FALSE == LocksInitializedEarly); if (LocksInitializedEarly) { @@ -113,7 +114,8 @@ static SECStatus ssl_ShutdownLocks(void* appData, void* nssData) return SECSuccess; } -static PRStatus initSessionCacheLocksLazily(void) +static PRStatus +initSessionCacheLocksLazily(void) { SECStatus rv = InitSessionCacheLocks(); if (SECSuccess != rv) { @@ -139,10 +141,11 @@ ssl_InitSessionCacheLocks(PRBool lazyInit) if (lazyInit) { return (PR_SUCCESS == - PR_CallOnce(&lockOnce, initSessionCacheLocksLazily)) ? - SECSuccess : SECFailure; + PR_CallOnce(&lockOnce, initSessionCacheLocksLazily)) + ? SECSuccess + : SECFailure; } - + if (SECSuccess == InitSessionCacheLocks()) { LocksInitializedEarly = PR_TRUE; return SECSuccess; @@ -151,7 +154,7 @@ ssl_InitSessionCacheLocks(PRBool lazyInit) return SECFailure; } -static void +static void lock_cache(void) { ssl_InitSessionCacheLocks(PR_TRUE); @@ -168,63 +171,63 @@ ssl_DestroySID(sslSessionID *sid) PORT_Assert(sid->references == 0); PORT_Assert(sid->cached != in_client_cache); - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - SECITEM_ZfreeItem(&sid->u.ssl2.masterKey, PR_FALSE); - SECITEM_ZfreeItem(&sid->u.ssl2.cipherArg, PR_FALSE); - } else { - 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.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); - } + if (sid->u.ssl3.lock) { + PR_DestroyRWLock(sid->u.ssl3.lock); } if (sid->peerID != NULL) - PORT_Free((void *)sid->peerID); /* CONST */ + PORT_Free((void *)sid->peerID); /* CONST */ if (sid->urlSvrName != NULL) - PORT_Free((void *)sid->urlSvrName); /* CONST */ + PORT_Free((void *)sid->urlSvrName); /* CONST */ - if ( sid->peerCert ) { - CERT_DestroyCertificate(sid->peerCert); + if (sid->peerCert) { + CERT_DestroyCertificate(sid->peerCert); } if (sid->peerCertStatus.items) { SECITEM_FreeArray(&sid->peerCertStatus, PR_FALSE); } - if ( sid->localCert ) { - CERT_DestroyCertificate(sid->localCert); + if (sid->localCert) { + CERT_DestroyCertificate(sid->localCert); } - + + SECITEM_FreeItem(&sid->u.ssl3.alpnSelection, PR_FALSE); + 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. + * 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 +static void ssl_FreeLockedSID(sslSessionID *sid) { PORT_Assert(sid->references >= 1); if (--sid->references == 0) { - ssl_DestroySID(sid); + ssl_DestroySID(sid); } } /* 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. + * 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 @@ -244,57 +247,53 @@ ssl_FreeSID(sslSessionID *sid) */ sslSessionID * -ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, - const char * urlSvrName) +ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, + const char *urlSvrName) { sslSessionID **sidp; - sslSessionID * sid; - PRUint32 now; + sslSessionID *sid; + PRUint32 now; if (!urlSvrName) - return NULL; + return NULL; now = ssl_Time(); LOCK_CACHE; sidp = &cache; while ((sid = *sidp) != 0) { - PORT_Assert(sid->cached == in_client_cache); - PORT_Assert(sid->references >= 1); - - SSL_TRC(8, ("SSL: Lookup1: 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: lookup1, 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->version < SSL_LIBRARY_VERSION_3_0 || - sid->u.ssl3.keys.resumable) && - /* server hostname matches. */ - (sid->urlSvrName != NULL) && - ((0 == PORT_Strcmp(urlSvrName, sid->urlSvrName)) || - ((sid->peerCert != NULL) && (SECSuccess == - CERT_VerifyCertName(sid->peerCert, urlSvrName))) ) - ) { - /* Hit */ - sid->lastAccessTime = now; - sid->references++; - break; - } else { - sidp = &sid->next; - } + PORT_Assert(sid->cached == in_client_cache); + PORT_Assert(sid->references >= 1); + + SSL_TRC(8, ("SSL: Lookup1: 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: lookup1, 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; @@ -304,62 +303,51 @@ ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, const char *peerID, ** 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 +static void CacheSID(sslSessionID *sid) { - PRUint32 expirationPeriod; + PRUint32 expirationPeriod; 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)); + "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; } - /* XXX should be different trace for version 2 vs. version 3 */ - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - expirationPeriod = ssl_sid_timeout; - PRINT_BUF(8, (0, "sessionID:", - sid->u.ssl2.sessionID, sizeof(sid->u.ssl2.sessionID))); - PRINT_BUF(8, (0, "masterKey:", - sid->u.ssl2.masterKey.data, sid->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", - sid->u.ssl2.cipherArg.data, sid->u.ssl2.cipherArg.len)); - } else { - 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; - } - expirationPeriod = ssl3_sid_timeout; - 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; - } + 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; + } + expirationPeriod = ssl3_sid_timeout; + 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 && sid->expirationTime != 0); if (!sid->creationTime) - sid->lastAccessTime = sid->creationTime = ssl_Time(); + sid->lastAccessTime = sid->creationTime = ssl_Time(); if (!sid->expirationTime) - sid->expirationTime = sid->creationTime + expirationPeriod; + sid->expirationTime = sid->creationTime + expirationPeriod; /* * Put sid into the cache. Bump reference count to indicate that @@ -369,12 +357,12 @@ CacheSID(sslSessionID *sid) LOCK_CACHE; sid->references++; sid->cached = in_client_cache; - sid->next = cache; - cache = sid; + 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. @@ -386,43 +374,35 @@ UncacheSID(sslSessionID *zap) sslSessionID *sid; if (zap->cached != in_client_cache) { - return; + return; } - SSL_TRC(8,("SSL: Uncache: zap=0x%x cached=%d addr=0x%08x%08x%08x%08x port=0x%04x " - "time=%x cipher=%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.ssl2.cipherType)); - if (zap->version < SSL_LIBRARY_VERSION_3_0) { - PRINT_BUF(8, (0, "sessionID:", - zap->u.ssl2.sessionID, sizeof(zap->u.ssl2.sessionID))); - PRINT_BUF(8, (0, "masterKey:", - zap->u.ssl2.masterKey.data, zap->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", - zap->u.ssl2.cipherArg.data, zap->u.ssl2.cipherArg.len)); - } + 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) { + /* + ** 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 + * Although this function is static, it is called externally via * ss->sec.uncache(). */ static void @@ -431,19 +411,18 @@ LockAndUncacheSID(sslSessionID *zap) LOCK_CACHE; UncacheSID(zap); UNLOCK_CACHE; - } /* choose client or server cache functions for this sslsocket. */ -void +void ssl_ChooseSessionIDProcs(sslSecurityInfo *sec) { if (sec->isServer) { - sec->cache = ssl_sid_cache; - sec->uncache = ssl_sid_uncache; + sec->cache = ssl_sid_cache; + sec->uncache = ssl_sid_uncache; } else { - sec->cache = CacheSID; - sec->uncache = LockAndUncacheSID; + sec->cache = CacheSID; + sec->uncache = LockAndUncacheSID; } } @@ -452,8 +431,8 @@ void SSL_ClearSessionCache(void) { LOCK_CACHE; - while(cache != NULL) - UncacheSID(cache); + while (cache != NULL) + UncacheSID(cache); UNLOCK_CACHE; } @@ -461,9 +440,13 @@ SSL_ClearSessionCache(void) PRUint32 ssl_Time(void) { +#ifdef UNSAFE_FUZZER_MODE + return 1234; +#endif + PRUint32 myTime; #if defined(XP_UNIX) || defined(XP_WIN) || defined(_WINDOWS) || defined(XP_BEOS) - myTime = time(NULL); /* accurate until the year 2038. */ + myTime = time(NULL); /* accurate until the year 2038. */ #else /* portable, but possibly slower */ PRTime now; @@ -492,11 +475,11 @@ ssl3_SetSIDSessionTicket(sslSessionID *sid, * yet, so no locking is needed. */ if (sid->u.ssl3.lock) { - PR_RWLock_Wlock(sid->u.ssl3.lock); - if (sid->u.ssl3.locked.sessionTicket.ticket.data) { - SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket, - PR_FALSE); - } + PR_RWLock_Wlock(sid->u.ssl3.lock); + if (sid->u.ssl3.locked.sessionTicket.ticket.data) { + SECITEM_FreeItem(&sid->u.ssl3.locked.sessionTicket.ticket, + PR_FALSE); + } } PORT_Assert(!sid->u.ssl3.locked.sessionTicket.ticket.data); @@ -507,6 +490,6 @@ ssl3_SetSIDSessionTicket(sslSessionID *sid, newSessionTicket->ticket.len = 0; if (sid->u.ssl3.lock) { - PR_RWLock_Unlock(sid->u.ssl3.lock); + PR_RWLock_Unlock(sid->u.ssl3.lock); } } diff --git a/nss/lib/ssl/sslproto.h b/nss/lib/ssl/sslproto.h index 2db47a5..70daea0 100644 --- a/nss/lib/ssl/sslproto.h +++ b/nss/lib/ssl/sslproto.h @@ -1,6 +1,6 @@ /* * Various and sundry protocol constants. DON'T CHANGE THESE. These values - * are mostly defined by the SSL2, SSL3, or TLS protocol specifications. + * 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 @@ -10,6 +10,8 @@ #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 @@ -19,9 +21,9 @@ #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 0x0302 -#define SSL_LIBRARY_VERSION_DTLS_1_2 0x0303 -#define SSL_LIBRARY_VERSION_DTLS_1_3 0x0304 +#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 @@ -29,29 +31,7 @@ /* 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) - -/* Header lengths of some of the messages */ -#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 - -/* Security handshake protocol codes */ -#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_LIBRARY_VERSION_DTLS_1_3_WIRE SSL_LIBRARY_VERSION_DTLS_1_3 /* Certificate types */ #define SSL_CT_X509_CERTIFICATE 0x01 @@ -66,57 +46,27 @@ #define SSL_PE_BAD_CERTIFICATE 0x0004 #define SSL_PE_UNSUPPORTED_CERTIFICATE_TYPE 0x0006 -/* Cypher kinds (not the spec version!) */ -#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 - -/* Cipher enables. These are used only for SSL_EnableCipher - * These values define the SSL2 suites, and do not colide with the - * SSL3 Cipher suites defined below. - */ -#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 - /* 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_EXPORT_WITH_RC4_40_MD5 TLS_RSA_EXPORT_WITH_RC4_40_MD5 #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_EXPORT_WITH_RC2_CBC_40_MD5 TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 #define SSL_RSA_WITH_IDEA_CBC_SHA TLS_RSA_WITH_IDEA_CBC_SHA -#define SSL_RSA_EXPORT_WITH_DES40_CBC_SHA TLS_RSA_EXPORT_WITH_DES40_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_EXPORT_WITH_DES40_CBC_SHA TLS_DH_DSS_EXPORT_WITH_DES40_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_EXPORT_WITH_DES40_CBC_SHA TLS_DH_RSA_EXPORT_WITH_DES40_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_EXPORT_WITH_DES40_CBC_SHA TLS_DHE_DSS_EXPORT_WITH_DES40_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_EXPORT_WITH_DES40_CBC_SHA TLS_DHE_RSA_EXPORT_WITH_DES40_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_EXPORT_WITH_DES40_CBC_SHA TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA #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 SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5 TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 #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 @@ -127,39 +77,26 @@ #define TLS_RSA_WITH_NULL_MD5 0x0001 #define TLS_RSA_WITH_NULL_SHA 0x0002 -#define TLS_RSA_EXPORT_WITH_RC4_40_MD5 0x0003 #define TLS_RSA_WITH_RC4_128_MD5 0x0004 #define TLS_RSA_WITH_RC4_128_SHA 0x0005 -#define TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 0x0006 #define TLS_RSA_WITH_IDEA_CBC_SHA 0x0007 -#define TLS_RSA_EXPORT_WITH_DES40_CBC_SHA 0x0008 #define TLS_RSA_WITH_DES_CBC_SHA 0x0009 #define TLS_RSA_WITH_3DES_EDE_CBC_SHA 0x000a -#define TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA 0x000b #define TLS_DH_DSS_WITH_DES_CBC_SHA 0x000c #define TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA 0x000d -#define TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA 0x000e #define TLS_DH_RSA_WITH_DES_CBC_SHA 0x000f #define TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA 0x0010 -#define TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA 0x0011 #define TLS_DHE_DSS_WITH_DES_CBC_SHA 0x0012 #define TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA 0x0013 -#define TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 0x0014 #define TLS_DHE_RSA_WITH_DES_CBC_SHA 0x0015 #define TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA 0x0016 -#define TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 0x0017 #define TLS_DH_anon_WITH_RC4_128_MD5 0x0018 -#define TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA 0x0019 #define TLS_DH_anon_WITH_DES_CBC_SHA 0x001a #define TLS_DH_anon_WITH_3DES_EDE_CBC_SHA 0x001b -#define SSL_FORTEZZA_DMS_WITH_NULL_SHA 0x001c /* deprecated */ -#define SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA 0x001d /* deprecated */ -#define SSL_FORTEZZA_DMS_WITH_RC4_128_SHA 0x001e /* deprecated */ - #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 @@ -185,11 +122,6 @@ #define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x0045 #define TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA 0x0046 -#define TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA 0x0062 -#define TLS_RSA_EXPORT1024_WITH_RC4_56_SHA 0x0064 - -#define TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA 0x0063 -#define TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA 0x0065 #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 @@ -205,8 +137,11 @@ #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 @@ -253,20 +188,36 @@ #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 -/* Netscape "experimental" cipher suites. */ -#define SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA 0xffe0 -#define SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA 0xffe1 - -/* New non-experimental openly spec'ed versions of those cipher suites. */ -#define SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA 0xfeff -#define SSL_RSA_FIPS_WITH_DES_CBC_SHA 0xfefe +/* 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 */ @@ -275,4 +226,69 @@ #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/nss/lib/ssl/sslreveal.c b/nss/lib/ssl/sslreveal.c index d972998..4c124a1 100644 --- a/nss/lib/ssl/sslreveal.c +++ b/nss/lib/ssl/sslreveal.c @@ -1,4 +1,4 @@ -/* +/* * Accessor functions for SSLSocket private members. * * This Source Code Form is subject to the terms of the Mozilla Public @@ -13,100 +13,98 @@ /* 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 * +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; + 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) +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; -} + 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) +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; -} + sslSocket *sslsocket = NULL; + char *url = NULL; + + sslsocket = ssl_FindSocket(fd); + if (sslsocket && sslsocket->url) + url = PL_strdup(sslsocket->url); -/* given PRFileDesc, returns status information related to extensions + return url; +} + +/* given PRFileDesc, returns status information related to extensions * negotiated with peer during the handshake. */ SECStatus -SSL_HandshakeNegotiatedExtension(PRFileDesc * socket, +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) { - if (sslsocket->ssl3.initialized) { /* SSL3 and TLS */ - /* 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); + /* 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) { + if (sslsocket->ssl3.initialized) { /* SSL3 and TLS */ + /* 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; + return SECSuccess; } diff --git a/nss/lib/ssl/sslsecur.c b/nss/lib/ssl/sslsecur.c index 53b4885..eecf443 100644 --- a/nss/lib/ssl/sslsecur.c +++ b/nss/lib/ssl/sslsecur.c @@ -10,116 +10,68 @@ #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 "secoid.h" /* for SECOID_GetALgorithmTag */ +#include "pk11func.h" /* for PK11_GenerateRandom */ +#include "nss.h" /* for NSS_RegisterShutdown */ +#include "prinit.h" /* for PR_CallOnceWithArg */ -#define MAX_BLOCK_CYPHER_SIZE 32 - -#define TEST_FOR_FAILURE /* reminder */ -#define SET_ERROR_CODE /* reminder */ - -/* Returns a SECStatus: SECSuccess or SECFailure, NOT SECWouldBlock. - * +/* Returns a SECStatus: SECSuccess or SECFailure, NOT SECWouldBlock. + * * Currently, the list of functions called through ss->handshake is: - * + * * In sslsocks.c: * SocksGatherRecord - * SocksHandleReply + * SocksHandleReply * SocksStartGather * * In sslcon.c: * ssl_GatherRecord1stHandshake - * ssl2_HandleClientSessionKeyMessage - * ssl2_HandleMessage - * ssl2_HandleVerifyMessage - * ssl2_BeginClientHandshake - * ssl2_BeginServerHandshake - * ssl2_HandleClientHelloMessage - * ssl2_HandleServerHelloMessage - * - * The ss->handshake function returns SECWouldBlock under these conditions: - * 1. ssl_GatherRecord1stHandshake called ssl2_GatherData which read in - * the beginning of an SSL v3 hello message and returned SECWouldBlock - * to switch to SSL v3 handshake processing. + * ssl_BeginClientHandshake + * ssl_BeginServerHandshake * - * 2. ssl2_HandleClientHelloMessage discovered version 3.0 in the incoming - * v2 client hello msg, and called ssl3_HandleV2ClientHello which - * returned SECWouldBlock. + * The ss->handshake function returns SECWouldBlock if it was returned by + * one of the callback functions, via one of these paths: * - * 3. SECWouldBlock was returned by one of the callback functions, via - * one of these paths: - * - ssl2_HandleMessage() -> ssl2_HandleRequestCertificate() -> - * ss->getClientAuthData() + * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> + * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> + * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificate() -> + * ss->handleBadCert() * - * - ssl2_HandleServerHelloMessage() -> ss->handleBadCert() + * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> + * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> + * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificateRequest() -> + * ss->getClientAuthData() * - * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> - * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> - * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificate() -> - * ss->handleBadCert() - * - * - ssl_GatherRecord1stHandshake() -> ssl3_GatherCompleteHandshake() -> - * ssl3_HandleRecord() -> ssl3_HandleHandshake() -> - * ssl3_HandleHandshakeMessage() -> ssl3_HandleCertificateRequest() -> - * ss->getClientAuthData() - * - * 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 + * 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. */ -int +int ssl_Do1stHandshake(sslSocket *ss) { - int rv = SECSuccess; - int loopCount = 0; - - do { - 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)); - - if (ss->handshake == 0) { - /* Previous handshake finished. Switch to next one */ - ss->handshake = ss->nextHandshake; - ss->nextHandshake = 0; - } - if (ss->handshake == 0) { - /* Previous handshake finished. Switch to security handshake */ - ss->handshake = ss->securityHandshake; - ss->securityHandshake = 0; - } - if (ss->handshake == 0) { - /* for v3 this is done in ssl3_FinishHandshake */ - if (!ss->firstHsDone && ss->version < SSL_LIBRARY_VERSION_3_0) { - ssl_GetRecvBufLock(ss); - ss->gs.recordLen = 0; - ssl_FinishHandshake(ss); - ssl_ReleaseRecvBufLock(ss); - } - break; - } - rv = (*ss->handshake)(ss); - ++loopCount; - /* This code must continue to loop on SECWouldBlock, - * or any positive value. See XXX_1 comments. - */ - } while (rv != SECFailure); /* was (rv >= 0); XXX_1 */ + int 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)); if (rv == SECWouldBlock) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); - rv = SECFailure; + PORT_SetError(PR_WOULD_BLOCK_ERROR); + rv = SECFailure; } return rv; } @@ -127,22 +79,23 @@ ssl_Do1stHandshake(sslSocket *ss) void ssl_FinishHandshake(sslSocket *ss) { - PORT_Assert( ss->opt.noLocks || ssl_Have1stHandshakeLock(ss) ); - PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) ); + PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); 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; + ss->gs.readOffset = 0; if (ss->handshakeCallback) { - PORT_Assert(ss->version < SSL_LIBRARY_VERSION_3_0 || - (ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == - ssl_preinfo_all); - (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData); + PORT_Assert((ss->ssl3.hs.preliminaryInfo & ssl_preinfo_all) == + ssl_preinfo_all); + (ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData); } + + ssl_FreeEphemeralKeyPairs(ss); } /* @@ -152,7 +105,7 @@ ssl_FinishHandshake(sslSocket *ss) static SECStatus ssl3_AlwaysBlock(sslSocket *ss) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); /* perhaps redundant. */ + PORT_SetError(PR_WOULD_BLOCK_ERROR); /* perhaps redundant. */ return SECWouldBlock; } @@ -163,20 +116,19 @@ void ssl3_SetAlwaysBlock(sslSocket *ss) { if (!ss->firstHsDone) { - ss->handshake = ssl3_AlwaysBlock; - ss->nextHandshake = 0; + ss->handshake = ssl3_AlwaysBlock; } } -static SECStatus +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_DBG(("%d: SSL[%d]: bad socket in SetTimeout", SSL_GETPID(), fd)); + return SECFailure; } SSL_LOCK_READER(ss); ss->rTimeout = timeout; @@ -202,13 +154,13 @@ SSL_ResetHandshake(PRFileDesc *s, PRBool asServer) ss = ssl_FindSocket(s); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in ResetHandshake", SSL_GETPID(), s)); - return SECFailure; + 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; + return SECSuccess; SSL_LOCK_READER(ss); SSL_LOCK_WRITER(ss); @@ -218,19 +170,19 @@ SSL_ResetHandshake(PRFileDesc *s, PRBool asServer) ss->firstHsDone = PR_FALSE; ss->enoughFirstHsDone = PR_FALSE; - if ( asServer ) { - ss->handshake = ssl2_BeginServerHandshake; - ss->handshaking = sslHandshakingAsServer; + if (asServer) { + ss->handshake = ssl_BeginServerHandshake; + ss->handshaking = sslHandshakingAsServer; } else { - ss->handshake = ssl2_BeginClientHandshake; - ss->handshaking = sslHandshakingAsClient; + ss->handshake = ssl_BeginClientHandshake; + ss->handshaking = sslHandshakingAsClient; } - ss->nextHandshake = 0; - ss->securityHandshake = 0; ssl_GetRecvBufLock(ss); - status = ssl_InitGather(&ss->gs); + status = ssl3_InitGather(&ss->gs); ssl_ReleaseRecvBufLock(ss); + if (status != SECSuccess) + goto loser; ssl_GetSSL3HandshakeLock(ss); ss->ssl3.hs.canFalseStart = PR_FALSE; @@ -239,17 +191,21 @@ SSL_ResetHandshake(PRFileDesc *s, PRBool asServer) /* ** Blow away old security state and get a fresh setup. */ - ssl_GetXmitBufLock(ss); + ssl_GetXmitBufLock(ss); ssl_ResetSecurityInfo(&ss->sec, PR_TRUE); status = ssl_CreateSecurityInfo(ss); - ssl_ReleaseXmitBufLock(ss); + ssl_ReleaseXmitBufLock(ss); ssl_ReleaseSSL3HandshakeLock(ss); ssl_Release1stHandshakeLock(ss); + ssl3_DestroyRemoteExtensions(&ss->ssl3.hs.remoteExtensions); + ssl3_ResetExtensionData(&ss->xtnData); + if (!ss->TCPconnected) - ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr)); + ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr)); +loser: SSL_UNLOCK_WRITER(ss); SSL_UNLOCK_READER(ss); @@ -265,28 +221,22 @@ SECStatus SSL_ReHandshake(PRFileDesc *fd, PRBool flushCache) { sslSocket *ss; - SECStatus rv; - + SECStatus rv; + ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in RedoHandshake", SSL_GETPID(), fd)); + return SECFailure; } if (!ss->opt.useSecurity) - return SECSuccess; - + return SECSuccess; + ssl_Get1stHandshakeLock(ss); - /* SSL v2 protocol does not support subsequent handshakes. */ - if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - rv = SECFailure; - } else { - ssl_GetSSL3HandshakeLock(ss); - rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */ - ssl_ReleaseSSL3HandshakeLock(ss); - } + ssl_GetSSL3HandshakeLock(ss); + rv = ssl3_RedoHandshake(ss, flushCache); /* force full handshake. */ + ssl_ReleaseSSL3HandshakeLock(ss); ssl_Release1stHandshakeLock(ss); @@ -296,9 +246,10 @@ 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) +SSL_IMPORT SECStatus +SSL_ReHandshakeWithTimeout(PRFileDesc *fd, + PRBool flushCache, + PRIntervalTime timeout) { if (SECSuccess != ssl_SetTimeout(fd, timeout)) { return SECFailure; @@ -317,26 +268,26 @@ SSL_RedoHandshake(PRFileDesc *fd) */ SECStatus SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb, - void *client_data) + 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; + 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; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ssl_Get1stHandshakeLock(ss); ssl_GetSSL3HandshakeLock(ss); - ss->handshakeCallback = cb; + ss->handshakeCallback = cb; ss->handshakeCallbackData = client_data; ssl_ReleaseSSL3HandshakeLock(ss); @@ -350,26 +301,26 @@ SSL_HandshakeCallback(PRFileDesc *fd, SSLHandshakeCallback cb, */ SECStatus SSL_SetCanFalseStartCallback(PRFileDesc *fd, SSLCanFalseStartCallback cb, - void *arg) + 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; + 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; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ssl_Get1stHandshakeLock(ss); ssl_GetSSL3HandshakeLock(ss); - ss->canFalseStartCallback = cb; + ss->canFalseStartCallback = cb; ss->canFalseStartCallbackData = arg; ssl_ReleaseSSL3HandshakeLock(ss); @@ -386,90 +337,81 @@ SSL_RecommendedCanFalseStart(PRFileDesc *fd, PRBool *canFalseStart) *canFalseStart = PR_FALSE; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_RecommendedCanFalseStart", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_RecommendedCanFalseStart", + SSL_GETPID(), fd)); + return SECFailure; } if (!ss->ssl3.initialized) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + 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; + 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 +/* 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 +** For non-blocking sockets, returns PR_ERROR_WOULD_BLOCK if it cannot ** read the next handshake from the underlying socket. -** For SSLv2, returns when handshake is complete or fatal error occurs. -** For SSLv3, returns when handshake is complete, or application data has -** arrived that must be taken by application before handshake can continue, +** 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. +** Application should use handshake completion callback to tell which. */ SECStatus SSL_ForceHandshake(PRFileDesc *fd) { sslSocket *ss; - SECStatus rv = SECFailure; + SECStatus rv = SECFailure; ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in ForceHandshake", - SSL_GETPID(), fd)); - return rv; + 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 (!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_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); - } else if (gatherResult == SECWouldBlock) { - PORT_SetError(PR_WOULD_BLOCK_ERROR); - } - } else if (!ss->firstHsDone) { - rv = ssl_Do1stHandshake(ss); + 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); + } else if (gatherResult == SECWouldBlock) { + PORT_SetError(PR_WOULD_BLOCK_ERROR); + } } else { - /* tried to force handshake on an SSL 2 socket that has - ** already completed the handshake. */ - rv = SECSuccess; /* just pretend we did it. */ + PORT_Assert(!ss->firstHsDone); + rv = ssl_Do1stHandshake(ss); } ssl_Release1stHandshakeLock(ss); @@ -480,8 +422,9 @@ SSL_ForceHandshake(PRFileDesc *fd) /* ** Same as above, but with an I/O timeout. */ -SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, - PRIntervalTime timeout) +SSL_IMPORT SECStatus +SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, + PRIntervalTime timeout) { if (SECSuccess != ssl_SetTimeout(fd, timeout)) { return SECFailure; @@ -489,7 +432,6 @@ SSL_IMPORT SECStatus SSL_ForceHandshakeWithTimeout(PRFileDesc *fd, return SSL_ForceHandshake(fd); } - /************************************************************************/ /* @@ -502,52 +444,63 @@ sslBuffer_Grow(sslBuffer *b, unsigned int newLen) { newLen = PR_MAX(newLen, MAX_FRAGMENT_LENGTH + 2048); 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; - } - SSL_TRC(10, ("%d: SSL: grow buffer from %d to %d", - SSL_GETPID(), b->space, newLen)); - b->buf = newBuf; - b->space = newLen; + 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; + } + SSL_TRC(10, ("%d: SSL: grow buffer from %d to %d", + SSL_GETPID(), b->space, newLen)); + b->buf = newBuf; + b->space = newLen; } return SECSuccess; } -SECStatus -sslBuffer_Append(sslBuffer *b, const void * data, unsigned int len) +SECStatus +sslBuffer_Append(sslBuffer *b, const void *data, unsigned int len) { unsigned int newLen = b->len + len; SECStatus rv; rv = sslBuffer_Grow(b, newLen); if (rv != SECSuccess) - return rv; + return rv; PORT_Memcpy(b->buf + b->len, data, len); b->len += len; return SECSuccess; } +void +sslBuffer_Clear(sslBuffer *b) +{ + if (b->len > 0) { + PORT_Free(b->buf); + b->buf = NULL; + b->len = 0; + b->space = 0; + } +} + /* ** 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 +SECStatus ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len) { - SECStatus rv; + SECStatus rv; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + 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)); + SSL_GETPID(), ss->fd, len, ss->pendingBuf.len)); return rv; } @@ -557,25 +510,25 @@ ssl_SaveWriteData(sslSocket *ss, const void *data, unsigned int len) ** Returns count of the bytes sent, NOT a SECStatus. ** Caller must hold xmitBufLock */ -int +int ssl_SendSavedWriteData(sslSocket *ss) { - int rv = 0; + int rv = 0; - PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) ); + 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); - } + 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; } @@ -589,19 +542,18 @@ ssl_SendSavedWriteData(sslSocket *ss) ** ** Caller does NOT hold 1stHandshakeLock because that handshake is over. ** Caller doesn't call this until initial handshake is complete. -** For SSLv2, there is no subsequent handshake. -** For SSLv3, the call to ssl3_GatherAppDataRecord may encounter handshake +** The call to ssl3_GatherAppDataRecord may encounter handshake ** messages from a subsequent handshake. ** -** This code is similar to, and easily confused with, +** This code is similar to, and easily confused with, ** ssl_GatherRecord1stHandshake() in sslcon.c */ -static int +static int DoRecv(sslSocket *ss, unsigned char *out, int len, int flags) { - int rv; - int amount; - int available; + int rv; + int amount; + int available; /* ssl3_GatherAppDataRecord may call ssl_FinishHandshake, which needs the * 1stHandshakeLock. */ @@ -610,51 +562,45 @@ DoRecv(sslSocket *ss, unsigned char *out, int len, int flags) available = ss->gs.writeOffset - ss->gs.readOffset; if (available == 0) { - /* Get some more data */ - if (ss->version >= SSL_LIBRARY_VERSION_3_0) { - /* Wait for application data to arrive. */ - rv = ssl3_GatherAppDataRecord(ss, 0); - } else { - /* See if we have a complete record */ - rv = ssl2_GatherRecord(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 ((rv != SECWouldBlock) && - (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)); + /* 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 ((rv != SECWouldBlock) && + (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)) { @@ -671,13 +617,13 @@ DoRecv(sslSocket *ss, unsigned char *out, int len, int flags) 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; + ss->gs.readOffset += amount; } PORT_Assert(ss->gs.readOffset <= ss->gs.writeOffset); rv = amount; SSL_TRC(30, ("%d: SSL[%d]: amount=%d available=%d", - SSL_GETPID(), ss->fd, amount, available)); + SSL_GETPID(), ss->fd, amount, available)); PRINT_BUF(4, (ss, "DoRecv receiving plaintext:", out, amount)); done: @@ -688,271 +634,14 @@ done: /************************************************************************/ -/* -** Return SSLKEAType derived from cert's Public Key algorithm info. -*/ -SSLKEAType -NSS_FindCertKEAType(CERTCertificate * cert) -{ - SSLKEAType keaType = kt_null; - int tag; - - if (!cert) goto loser; - - tag = SECOID_GetAlgorithmTag(&(cert->subjectPublicKeyInfo.algorithm)); - - switch (tag) { - case SEC_OID_X500_RSA_ENCRYPTION: - case SEC_OID_PKCS1_RSA_ENCRYPTION: - keaType = kt_rsa; - break; - case SEC_OID_ANSIX9_DSA_SIGNATURE: /* hah, signature, not a key? */ - case SEC_OID_X942_DIFFIE_HELMAN_KEY: - keaType = kt_dh; - break; -#ifndef NSS_DISABLE_ECC - case SEC_OID_ANSIX962_EC_PUBLIC_KEY: - keaType = kt_ecdh; - break; -#endif /* NSS_DISABLE_ECC */ - default: - keaType = kt_null; - } - - loser: - - return keaType; -} - -static const PRCallOnceType pristineCallOnce; -static PRCallOnceType setupServerCAListOnce; - -static SECStatus serverCAListShutdown(void* appData, void* nssData) -{ - PORT_Assert(ssl3_server_ca_list); - if (ssl3_server_ca_list) { - CERT_FreeDistNames(ssl3_server_ca_list); - ssl3_server_ca_list = NULL; - } - setupServerCAListOnce = pristineCallOnce; - return SECSuccess; -} - -static PRStatus serverCAListSetup(void *arg) -{ - CERTCertDBHandle *dbHandle = (CERTCertDBHandle *)arg; - SECStatus rv = NSS_RegisterShutdown(serverCAListShutdown, NULL); - PORT_Assert(SECSuccess == rv); - if (SECSuccess == rv) { - ssl3_server_ca_list = CERT_GetSSLCACerts(dbHandle); - return PR_SUCCESS; - } - return PR_FAILURE; -} - -SECStatus -ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert, - const CERTCertificateList *certChain, - ssl3KeyPair *keyPair, SSLKEAType kea) -{ - CERTCertificateList *localCertChain = NULL; - sslServerCerts *sc = ss->serverCerts + kea; - - /* load the server certificate */ - if (sc->serverCert != NULL) { - CERT_DestroyCertificate(sc->serverCert); - sc->serverCert = NULL; - sc->serverKeyBits = 0; - } - /* load the server cert chain */ - if (sc->serverCertChain != NULL) { - CERT_DestroyCertificateList(sc->serverCertChain); - sc->serverCertChain = NULL; - } - if (cert) { - sc->serverCert = CERT_DupCertificate(cert); - /* get the size of the cert's public key, and remember it */ - sc->serverKeyBits = SECKEY_PublicKeyStrengthInBits(keyPair->pubKey); - if (!certChain) { - localCertChain = - CERT_CertChainFromCert(sc->serverCert, certUsageSSLServer, - PR_TRUE); - if (!localCertChain) - goto loser; - } - sc->serverCertChain = (certChain) ? CERT_DupCertList(certChain) : - localCertChain; - if (!sc->serverCertChain) { - goto loser; - } - localCertChain = NULL; /* consumed */ - } - - /* get keyPair */ - if (sc->serverKeyPair != NULL) { - ssl3_FreeKeyPair(sc->serverKeyPair); - sc->serverKeyPair = NULL; - } - if (keyPair) { - SECKEY_CacheStaticFlags(keyPair->privKey); - sc->serverKeyPair = ssl3_GetKeyPairRef(keyPair); - } - if (kea == kt_rsa && cert && sc->serverKeyBits > 512 && - !ss->opt.noStepDown && !ss->stepDownKeyPair) { - if (ssl3_CreateRSAStepDownKeys(ss) != SECSuccess) { - goto loser; - } - } - if (kea == ssl_kea_dh || kea == ssl_kea_rsa) { - if (ssl3_SelectDHParams(ss) != SECSuccess) { - goto loser; - } - } - return SECSuccess; - -loser: - if (localCertChain) { - CERT_DestroyCertificateList(localCertChain); - } - if (sc->serverCert != NULL) { - CERT_DestroyCertificate(sc->serverCert); - sc->serverCert = NULL; - } - if (sc->serverCertChain != NULL) { - CERT_DestroyCertificateList(sc->serverCertChain); - sc->serverCertChain = NULL; - } - if (sc->serverKeyPair != NULL) { - ssl3_FreeKeyPair(sc->serverKeyPair); - sc->serverKeyPair = NULL; - } - return SECFailure; -} - -/* XXX need to protect the data that gets changed here.!! */ - -SECStatus -SSL_ConfigSecureServer(PRFileDesc *fd, CERTCertificate *cert, - SECKEYPrivateKey *key, SSL3KEAType kea) -{ - - return SSL_ConfigSecureServerWithCertChain(fd, cert, NULL, key, kea); -} - -SECStatus -SSL_ConfigSecureServerWithCertChain(PRFileDesc *fd, CERTCertificate *cert, - const CERTCertificateList *certChainOpt, - SECKEYPrivateKey *key, SSL3KEAType kea) -{ - sslSocket *ss; - SECKEYPublicKey *pubKey = NULL; - ssl3KeyPair *keyPair = NULL; - SECStatus rv = SECFailure; - - ss = ssl_FindSocket(fd); - if (!ss) { - return SECFailure; - } - - /* Both key and cert must have a value or be NULL */ - /* Passing a value of NULL will turn off key exchange algorithms that were - * previously turned on */ - if (!cert != !key) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - - /* make sure the key exchange is recognized */ - if ((kea >= kt_kea_size) || (kea < kt_null)) { - PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG); - return SECFailure; - } - - if (kea != NSS_FindCertKEAType(cert)) { - PORT_SetError(SSL_ERROR_CERT_KEA_MISMATCH); - return SECFailure; - } - - if (cert) { - /* get the size of the cert's public key, and remember it */ - pubKey = CERT_ExtractPublicKey(cert); - if (!pubKey) - return SECFailure; - } - - if (key) { - SECKEYPrivateKey * keyCopy = NULL; - CK_MECHANISM_TYPE keyMech = CKM_INVALID_MECHANISM; - - if (key->pkcs11Slot) { - PK11SlotInfo * bestSlot; - bestSlot = PK11_ReferenceSlot(key->pkcs11Slot); - if (bestSlot) { - keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key); - PK11_FreeSlot(bestSlot); - } - } - if (keyCopy == NULL) - keyMech = PK11_MapSignKeyType(key->keyType); - if (keyMech != CKM_INVALID_MECHANISM) { - PK11SlotInfo * bestSlot; - /* XXX Maybe should be bestSlotMultiple? */ - bestSlot = PK11_GetBestSlot(keyMech, NULL /* wincx */); - if (bestSlot) { - keyCopy = PK11_CopyTokenPrivKeyToSessionPrivKey(bestSlot, key); - PK11_FreeSlot(bestSlot); - } - } - if (keyCopy == NULL) - keyCopy = SECKEY_CopyPrivateKey(key); - if (keyCopy == NULL) - goto loser; - keyPair = ssl3_NewKeyPair(keyCopy, pubKey); - if (keyPair == NULL) { - SECKEY_DestroyPrivateKey(keyCopy); - goto loser; - } - pubKey = NULL; /* adopted by serverKeyPair */ - } - if (ssl_ConfigSecureServer(ss, cert, certChainOpt, - keyPair, kea) == SECFailure) { - goto loser; - } - - /* Only do this once because it's global. */ - if (PR_SUCCESS == PR_CallOnceWithArg(&setupServerCAListOnce, - &serverCAListSetup, - (void *)(ss->dbHandle))) { - rv = SECSuccess; - } - -loser: - if (keyPair) { - ssl3_FreeKeyPair(keyPair); - } - if (pubKey) { - SECKEY_DestroyPublicKey(pubKey); - pubKey = NULL; - } - return rv; -} - -/************************************************************************/ - SECStatus ssl_CreateSecurityInfo(sslSocket *ss) { SECStatus status; - /* initialize sslv2 socket to send data in the clear. */ - ssl2_UseClearSendFunc(ss); - - ss->sec.blockSize = 1; - ss->sec.blockShift = 0; - - ssl_GetXmitBufLock(ss); + ssl_GetXmitBufLock(ss); status = sslBuffer_Grow(&ss->sec.writeBuf, 4096); - ssl_ReleaseXmitBufLock(ss); + ssl_ReleaseXmitBufLock(ss); return status; } @@ -960,50 +649,14 @@ ssl_CreateSecurityInfo(sslSocket *ss) SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os) { - ss->sec.send = os->sec.send; - ss->sec.isServer = os->sec.isServer; - ss->sec.keyBits = os->sec.keyBits; - ss->sec.secretKeyBits = os->sec.secretKeyBits; + ss->sec.isServer = os->sec.isServer; - ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert); + ss->sec.peerCert = CERT_DupCertificate(os->sec.peerCert); if (os->sec.peerCert && !ss->sec.peerCert) - goto loser; - - ss->sec.cache = os->sec.cache; - ss->sec.uncache = os->sec.uncache; - - /* we don't dup the connection info. */ - - ss->sec.sendSequence = os->sec.sendSequence; - ss->sec.rcvSequence = os->sec.rcvSequence; - - if (os->sec.hash && os->sec.hashcx) { - ss->sec.hash = os->sec.hash; - ss->sec.hashcx = os->sec.hash->clone(os->sec.hashcx); - if (os->sec.hashcx && !ss->sec.hashcx) - goto loser; - } else { - ss->sec.hash = NULL; - ss->sec.hashcx = NULL; - } - - if (SECITEM_CopyItem(0, &ss->sec.sendSecret, &os->sec.sendSecret)) - goto loser; - if (SECITEM_CopyItem(0, &ss->sec.rcvSecret, &os->sec.rcvSecret)) - goto loser; - - /* XXX following code is wrong if either cx != 0 */ - PORT_Assert(os->sec.readcx == 0); - PORT_Assert(os->sec.writecx == 0); - ss->sec.readcx = os->sec.readcx; - ss->sec.writecx = os->sec.writecx; - ss->sec.destroy = 0; - - ss->sec.enc = os->sec.enc; - ss->sec.dec = os->sec.dec; + goto loser; - ss->sec.blockShift = os->sec.blockShift; - ss->sec.blockSize = os->sec.blockSize; + ss->sec.cache = os->sec.cache; + ss->sec.uncache = os->sec.uncache; return SECSuccess; @@ -1014,61 +667,38 @@ loser: /* Reset sec back to its initial state. ** Caller holds any relevant locks. */ -void +void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset) { - /* Destroy MAC */ - if (sec->hash && sec->hashcx) { - (*sec->hash->destroy)(sec->hashcx, PR_TRUE); - sec->hashcx = NULL; - sec->hash = NULL; - } - SECITEM_ZfreeItem(&sec->sendSecret, PR_FALSE); - SECITEM_ZfreeItem(&sec->rcvSecret, PR_FALSE); - - /* Destroy ciphers */ - if (sec->destroy) { - (*sec->destroy)(sec->readcx, PR_TRUE); - (*sec->destroy)(sec->writecx, PR_TRUE); - sec->readcx = NULL; - sec->writecx = NULL; - } else { - PORT_Assert(sec->readcx == 0); - PORT_Assert(sec->writecx == 0); - } - sec->readcx = 0; - sec->writecx = 0; - if (sec->localCert) { - CERT_DestroyCertificate(sec->localCert); - sec->localCert = NULL; + CERT_DestroyCertificate(sec->localCert); + sec->localCert = NULL; } if (sec->peerCert) { - CERT_DestroyCertificate(sec->peerCert); - sec->peerCert = NULL; + CERT_DestroyCertificate(sec->peerCert); + sec->peerCert = NULL; } if (sec->peerKey) { - SECKEY_DestroyPublicKey(sec->peerKey); - sec->peerKey = NULL; + SECKEY_DestroyPublicKey(sec->peerKey); + sec->peerKey = NULL; } /* cleanup the ci */ if (sec->ci.sid != NULL) { - ssl_FreeSID(sec->ci.sid); + 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 +** Called from SSL_ResetHandshake (above), and ** from ssl_FreeSocket in sslsock.c ** Caller should hold relevant locks (e.g. XmitBufLock) */ -void +void ssl_DestroySecurityInfo(sslSecurityInfo *sec) { ssl_ResetSecurityInfo(sec, PR_FALSE); @@ -1081,35 +711,35 @@ ssl_DestroySecurityInfo(sslSecurityInfo *sec) /************************************************************************/ -int +int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *sa) { PRFileDesc *osfd = ss->fd->lower; int rv; - if ( ss->opt.handshakeAsServer ) { - ss->securityHandshake = ssl2_BeginServerHandshake; - ss->handshaking = sslHandshakingAsServer; + if (ss->opt.handshakeAsServer) { + ss->handshake = ssl_BeginServerHandshake; + ss->handshaking = sslHandshakingAsServer; } else { - ss->securityHandshake = ssl2_BeginClientHandshake; - ss->handshaking = sslHandshakingAsClient; + 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; + 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; - } + 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)); + SSL_GETPID(), ss->fd, rv)); return rv; } @@ -1142,19 +772,18 @@ ssl_SecureClose(sslSocket *ss) { int rv; - if (ss->version >= SSL_LIBRARY_VERSION_3_0 && - !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && - ss->firstHsDone && - !ss->recvdCloseNotify && - ss->ssl3.initialized) { + if (!(ss->shutdownHow & ssl_SHUTDOWN_SEND) && + ss->firstHsDone && + !ss->recvdCloseNotify && + ss->ssl3.initialized) { - /* We don't want the final alert to be Nagle delayed. */ - if (!ss->delayDisabled) { - ssl_EnableNagleDelay(ss, PR_FALSE); - ss->delayDisabled = 1; - } + /* 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); + (void)SSL3_SendAlert(ss, alert_warning, close_notify); } rv = ssl_DefClose(ss); return rv; @@ -1165,22 +794,21 @@ int ssl_SecureShutdown(sslSocket *ss, int nsprHow) { PRFileDesc *osfd = ss->fd->lower; - int rv; - PRIntn sslHow = nsprHow + 1; + int rv; + PRIntn sslHow = nsprHow + 1; if ((unsigned)nsprHow > PR_SHUTDOWN_BOTH) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return PR_FAILURE; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + return PR_FAILURE; } - if ((sslHow & ssl_SHUTDOWN_SEND) != 0 && - ss->version >= SSL_LIBRARY_VERSION_3_0 && - !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && - ss->firstHsDone && - !ss->recvdCloseNotify && - ss->ssl3.initialized) { + if ((sslHow & ssl_SHUTDOWN_SEND) != 0 && + !(ss->shutdownHow & ssl_SHUTDOWN_SEND) && + ss->firstHsDone && + !ss->recvdCloseNotify && + ss->ssl3.initialized) { - (void) SSL3_SendAlert(ss, alert_warning, close_notify); + (void)SSL3_SendAlert(ss, alert_warning, close_notify); } rv = osfd->methods->shutdown(osfd, nsprHow); @@ -1192,51 +820,56 @@ ssl_SecureShutdown(sslSocket *ss, int nsprHow) /************************************************************************/ - int ssl_SecureRecv(sslSocket *ss, unsigned char *buf, int len, int flags) { - int rv = 0; + int rv = 0; if (ss->shutdownHow & ssl_SHUTDOWN_RCV) { - PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); - return PR_FAILURE; + PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); + return PR_FAILURE; } if (flags & ~PR_MSG_PEEK) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - return PR_FAILURE; + 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); - } - + 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 || ss->nextHandshake || ss->securityHandshake) { - rv = ssl_Do1stHandshake(ss); - } - ssl_Release1stHandshakeLock(ss); + ssl_Get1stHandshakeLock(ss); + if (ss->handshake) { + rv = ssl_Do1stHandshake(ss); + } + ssl_Release1stHandshakeLock(ss); } if (rv < 0) { - return rv; + return rv; } - if (len == 0) return 0; + if (len == 0) + return 0; - rv = DoRecv(ss, (unsigned char*) buf, len, flags); + 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())); + SSL_GETPID(), ss->fd, rv, PORT_GetError())); return rv; } @@ -1253,97 +886,103 @@ ssl_SecureSend(sslSocket *ss, const unsigned char *buf, int len, int flags) int rv = 0; SSL_TRC(2, ("%d: SSL[%d]: SecureSend: sending %d bytes", - SSL_GETPID(), ss->fd, len)); + SSL_GETPID(), ss->fd, len)); if (ss->shutdownHow & ssl_SHUTDOWN_SEND) { - PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); - rv = PR_FAILURE; - goto done; + PORT_SetError(PR_SOCKET_SHUTDOWN_ERROR); + rv = PR_FAILURE; + goto done; } if (flags) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - rv = PR_FAILURE; - goto done; + 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; - } + 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; + goto done; } - if (len > 0) - ss->writerThread = PR_GetCurrentThread(); - /* If any of these is non-zero, the initial handshake is not 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 falseStart = PR_FALSE; - ssl_Get1stHandshakeLock(ss); - if (ss->opt.enableFalseStart && - ss->version >= SSL_LIBRARY_VERSION_3_0) { - ssl_GetSSL3HandshakeLock(ss); - falseStart = ss->ssl3.hs.canFalseStart; - ssl_ReleaseSSL3HandshakeLock(ss); - } - if (!falseStart && - (ss->handshake || ss->nextHandshake || ss->securityHandshake)) { - rv = ssl_Do1stHandshake(ss); - } - ssl_Release1stHandshakeLock(ss); + PRBool falseStart = PR_FALSE; + ssl_Get1stHandshakeLock(ss); + if (ss->opt.enableFalseStart || + (ss->opt.enable0RttData && !ss->sec.isServer)) { + ssl_GetSSL3HandshakeLock(ss); + /* The client can sometimes send before the handshake is fully + * complete. In TLS 1.2: false start; in TLS 1.3: 0-RTT. */ + falseStart = ss->ssl3.hs.canFalseStart || + ss->ssl3.hs.zeroRttState == ssl_0rtt_sent || + ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted; + ssl_ReleaseSSL3HandshakeLock(ss); + } + if (!falseStart && ss->handshake) { + rv = ssl_Do1stHandshake(ss); + } + ssl_Release1stHandshakeLock(ss); } if (rv < 0) { - ss->writerThread = NULL; - goto done; + ss->writerThread = NULL; + goto done; } /* Check for zero length writes after we do housekeeping so we make forward * progress. */ if (len == 0) { - rv = 0; - goto done; + rv = 0; + goto done; } PORT_Assert(buf != NULL); if (!buf) { - PORT_SetError(PR_INVALID_ARGUMENT_ERROR); - rv = PR_FAILURE; - goto done; + PORT_SetError(PR_INVALID_ARGUMENT_ERROR); + rv = PR_FAILURE; + goto done; } if (!ss->firstHsDone) { - PORT_Assert(ss->version >= SSL_LIBRARY_VERSION_3_0); #ifdef DEBUG - ssl_GetSSL3HandshakeLock(ss); - PORT_Assert(ss->ssl3.hs.canFalseStart); - ssl_ReleaseSSL3HandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); + PORT_Assert(!ss->sec.isServer && + (ss->ssl3.hs.canFalseStart || + ss->ssl3.hs.zeroRttState == ssl_0rtt_sent || + ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)); + ssl_ReleaseSSL3HandshakeLock(ss); #endif - SSL_TRC(3, ("%d: SSL[%d]: SecureSend: sending data due to false start", - SSL_GETPID(), ss->fd)); + SSL_TRC(3, ("%d: SSL[%d]: SecureSend: sending data due to false start", + SSL_GETPID(), ss->fd)); } - /* Send out the data using one of these functions: - * ssl2_SendClear, ssl2_SendStream, ssl2_SendBlock, - * ssl3_SendApplicationData - */ ssl_GetXmitBufLock(ss); - rv = (*ss->sec.send)(ss, buf, len, flags); + 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())); + 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)); + SSL_TRC(2, ("%d: SSL[%d]: SecureSend: returning %d count", + SSL_GETPID(), ss->fd, rv)); } return rv; } @@ -1358,12 +997,12 @@ 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; + SSL_DBG(("%d: SSL[%d]: bad socket in SSLBadCertHook", + SSL_GETPID(), fd)); + return SECFailure; } ss->handleBadCert = f; @@ -1380,24 +1019,24 @@ SSL_BadCertHook(PRFileDesc *fd, SSLBadCertHandler f, void *arg) SECStatus SSL_SetURL(PRFileDesc *fd, const char *url) { - sslSocket * ss = ssl_FindSocket(fd); - SECStatus rv = SECSuccess; + 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_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 */ + if (ss->url) { + PORT_Free((void *)ss->url); /* CONST */ } ss->url = (const char *)PORT_Strdup(url); - if ( ss->url == NULL ) { - rv = SECFailure; + if (ss->url == NULL) { + rv = SECFailure; } ssl_ReleaseSSL3HandshakeLock(ss); @@ -1412,7 +1051,7 @@ SSL_SetURL(PRFileDesc *fd, const char *url) SECStatus SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList) { - sslSocket * ss = ssl_FindSocket(fd); + sslSocket *ss = ssl_FindSocket(fd); CERTDistNames *names = NULL; if (!certList) { @@ -1420,9 +1059,9 @@ SSL_SetTrustAnchors(PRFileDesc *fd, CERTCertList *certList) return SECFailure; } if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTrustAnchors", + SSL_GETPID(), fd)); + return SECFailure; } names = CERT_DistNamesFromCertList(certList); @@ -1449,14 +1088,14 @@ int SSL_DataPending(PRFileDesc *fd) { sslSocket *ss; - int rv = 0; + 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); + ssl_GetRecvBufLock(ss); + rv = ss->gs.writeOffset - ss->gs.readOffset; + ssl_ReleaseRecvBufLock(ss); } return rv; @@ -1465,20 +1104,20 @@ SSL_DataPending(PRFileDesc *fd) SECStatus SSL_InvalidateSession(PRFileDesc *fd) { - sslSocket * ss = ssl_FindSocket(fd); - SECStatus rv = SECFailure; + sslSocket *ss = ssl_FindSocket(fd); + SECStatus rv = SECFailure; if (ss) { - ssl_Get1stHandshakeLock(ss); - ssl_GetSSL3HandshakeLock(ss); + ssl_Get1stHandshakeLock(ss); + ssl_GetSSL3HandshakeLock(ss); - if (ss->sec.ci.sid && ss->sec.uncache) { - ss->sec.uncache(ss->sec.ci.sid); - rv = SECSuccess; - } + if (ss->sec.ci.sid) { + ss->sec.uncache(ss->sec.ci.sid); + rv = SECSuccess; + } - ssl_ReleaseSSL3HandshakeLock(ss); - ssl_Release1stHandshakeLock(ss); + ssl_ReleaseSSL3HandshakeLock(ss); + ssl_Release1stHandshakeLock(ss); } return rv; } @@ -1486,32 +1125,26 @@ SSL_InvalidateSession(PRFileDesc *fd) SECItem * SSL_GetSessionID(PRFileDesc *fd) { - sslSocket * ss; - SECItem * item = NULL; + 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; - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - item->len = SSL2_SESSIONID_BYTES; - item->data = (unsigned char*)PORT_Alloc(item->len); - PORT_Memcpy(item->data, sid->u.ssl2.sessionID, item->len); - } else { - 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); + 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; } @@ -1519,14 +1152,14 @@ SSL_GetSessionID(PRFileDesc *fd) SECStatus SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle) { - sslSocket * ss; + sslSocket *ss; ss = ssl_FindSocket(fd); if (!ss) - return SECFailure; + return SECFailure; if (!dbHandle) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } ss->dbHandle = dbHandle; return SECSuccess; @@ -1536,10 +1169,10 @@ SSL_CertDBHandleSet(PRFileDesc *fd, CERTCertDBHandle *dbHandle) * this implementation exists to maintain link-time compatibility. */ int -SSL_RestartHandshakeAfterCertReq(sslSocket * ss, - CERTCertificate * cert, - SECKEYPrivateKey * key, - CERTCertificateList *certChain) +SSL_RestartHandshakeAfterCertReq(sslSocket *ss, + CERTCertificate *cert, + SECKEYPrivateKey *key, + CERTCertificateList *certChain) { PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return -1; @@ -1549,7 +1182,7 @@ SSL_RestartHandshakeAfterCertReq(sslSocket * ss, * this implementation exists to maintain link-time compatibility. */ int -SSL_RestartHandshakeAfterServerCert(sslSocket * ss) +SSL_RestartHandshakeAfterServerCert(sslSocket *ss) { PORT_SetError(PR_NOT_IMPLEMENTED_ERROR); return -1; @@ -1563,21 +1196,18 @@ SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode error) sslSocket *ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_AuthCertificateComplete", + SSL_GETPID(), fd)); + return SECFailure; } ssl_Get1stHandshakeLock(ss); if (!ss->ssl3.initialized) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } else if (ss->version < SSL_LIBRARY_VERSION_3_0) { - PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2); - rv = SECFailure; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } else { - rv = ssl3_AuthCertificateComplete(ss, error); + rv = ssl3_AuthCertificateComplete(ss, error); } ssl_Release1stHandshakeLock(ss); @@ -1586,7 +1216,7 @@ SSL_AuthCertificateComplete(PRFileDesc *fd, PRErrorCode error) } /* For more info see ssl.h */ -SECStatus +SECStatus SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func, void *arg) { @@ -1594,9 +1224,9 @@ SSL_SNISocketConfigHook(PRFileDesc *fd, SSLSNISocketConfig func, ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook", - SSL_GETPID(), fd)); - return SECFailure; + SSL_DBG(("%d: SSL[%d]: bad socket in SNISocketConfigHook", + SSL_GETPID(), fd)); + return SECFailure; } ss->sniSocketConfig = func; diff --git a/nss/lib/ssl/sslsnce.c b/nss/lib/ssl/sslsnce.c index f31b2e9..4a4005c 100644 --- a/nss/lib/ssl/sslsnce.c +++ b/nss/lib/ssl/sslsnce.c @@ -1,23 +1,23 @@ -/* This file implements the SERVER Session ID cache. +/* 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 +/* 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. + * 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. + * 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. @@ -33,10 +33,10 @@ * sidCacheSet sidCacheSets[ numSIDCacheSets ]; * sidCacheEntry sidCacheData[ numSIDCacheEntries]; * certCacheEntry certCacheData[numCertCacheEntries]; - * SSLWrappedSymWrappingKey keyCacheData[kt_kea_size][SSL_NUM_WRAP_MECHS]; + * SSLWrappedSymWrappingKey keyCacheData[ssl_auth_size][SSL_NUM_WRAP_MECHS]; * PRUint8 keyNameSuffix[SESS_TICKET_KEY_VAR_NAME_LEN] - * encKeyCacheEntry ticketEncKey; // Wrapped in non-bypass mode - * encKeyCacheEntry ticketMacKey; // Wrapped in non-bypass mode + * encKeyCacheEntry ticketEncKey; // Wrapped + * encKeyCacheEntry ticketMacKey; // Wrapped * PRBool ticketKeysValid; * sidCacheLock srvNameCacheLock; * srvNameCacheEntry srvNameData[ numSrvNameCacheEntries ]; @@ -44,7 +44,7 @@ */ #include "seccomon.h" -#if defined(XP_UNIX) || defined(XP_WIN32) || defined (XP_OS2) || defined(XP_BEOS) +#if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_OS2) || defined(XP_BEOS) #include "cert.h" #include "ssl.h" @@ -53,12 +53,8 @@ #include "pk11func.h" #include "base64.h" #include "keyhi.h" -#ifdef NO_PKCS11_BYPASS #include "blapit.h" #include "sechash.h" -#else -#include "blapi.h" -#endif #include <stdio.h> @@ -78,156 +74,142 @@ #include "win32err.h" #endif -#endif +#endif #include <sys/types.h> -#define SET_ERROR_CODE /* reminder */ - #include "nspr.h" #include "sslmutex.h" /* ** Format of a cache entry in the shared memory. -*/ +*/ struct sidCacheEntryStr { -/* 16 */ PRIPv6Addr addr; /* client's IP address */ -/* 4 */ PRUint32 creationTime; -/* 4 */ PRUint32 lastAccessTime; -/* 4 */ PRUint32 expirationTime; -/* 2 */ PRUint16 version; -/* 1 */ PRUint8 valid; -/* 1 */ PRUint8 sessionIDLength; -/* 32 */ PRUint8 sessionID[SSL3_SESSIONID_BYTES]; -/* 2 */ PRUint16 authAlgorithm; -/* 2 */ PRUint16 authKeyBits; -/* 2 */ PRUint16 keaType; -/* 2 */ PRUint16 keaKeyBits; -/* 72 - common header total */ + /* 16 */ PRIPv6Addr addr; /* client's IP address */ + /* 4 */ PRUint32 creationTime; + /* 4 */ PRUint32 lastAccessTime; + /* 4 */ PRUint32 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; + /* 72 - common header total */ union { - struct { -/* 64 */ PRUint8 masterKey[SSL_MAX_MASTER_KEY_BYTES]; -/* 32 */ PRUint8 cipherArg[SSL_MAX_CYPHER_ARG_BYTES]; - -/* 1 */ PRUint8 cipherType; -/* 1 */ PRUint8 masterKeyLen; -/* 1 */ PRUint8 keyBits; -/* 1 */ PRUint8 secretKeyBits; -/* 1 */ PRUint8 cipherArgLen; -/*101 */} ssl2; - - struct { -/* 2 */ ssl3CipherSuite cipherSuite; -/* 2 */ PRUint16 compression; /* SSLCompressionMethod */ - -/* 54 */ ssl3SidKeys keys; /* keys, wrapped as needed. */ - -/* 4 */ PRUint32 masterWrapMech; -/* 4 */ SSL3KEAType exchKeyType; -/* 4 */ PRInt32 certIndex; -/* 4 */ PRInt32 srvNameIndex; -/* 32 */ PRUint8 srvNameHash[SHA256_LENGTH]; /* SHA256 name hash */ -/*108 */} ssl3; -/* force sizeof(sidCacheEntry) to be a multiple of cache line size */ struct { -/*120 */ PRUint8 filler[120]; /* 72+120==192, a multiple of 16 */ - } forceSize; + /* 2 */ ssl3CipherSuite cipherSuite; + /* 2 */ PRUint16 compression; /* SSLCompressionMethod */ + + /* 54 */ 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 certTypeArgs; +/*104 */} ssl3; + +/* force sizeof(sidCacheEntry) to be a multiple of cache line size */ +struct { + /*120 */ PRUint8 filler[120]; /* 72+120==192, 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 */ + 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; + PRUint32 timeStamp; + sslMutex mutex; + sslPID pid; }; typedef struct sidCacheLockStr sidCacheLock; struct sidCacheSetStr { - PRIntn next; + PRIntn next; }; typedef struct sidCacheSetStr sidCacheSet; struct encKeyCacheEntryStr { - PRUint8 bytes[512]; - PRInt32 length; + PRUint8 bytes[512]; + PRInt32 length; }; typedef struct encKeyCacheEntryStr encKeyCacheEntry; -#define SSL_MAX_DNS_HOST_NAME 1024 +#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 */ + 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 cacheMemSize; - PRUint32 numSIDCacheLocks; - PRUint32 numSIDCacheSets; - PRUint32 numSIDCacheSetsPerLock; + PRUint32 numSIDCacheLocks; + PRUint32 numSIDCacheSets; + PRUint32 numSIDCacheSetsPerLock; - PRUint32 numSIDCacheEntries; - PRUint32 sidCacheSize; + PRUint32 numSIDCacheEntries; + PRUint32 sidCacheSize; - PRUint32 numCertCacheEntries; - PRUint32 certCacheSize; + PRUint32 numCertCacheEntries; + PRUint32 certCacheSize; - PRUint32 numKeyCacheEntries; - PRUint32 keyCacheSize; + PRUint32 numKeyCacheEntries; + PRUint32 keyCacheSize; - PRUint32 numSrvNameCacheEntries; - PRUint32 srvNameCacheSize; + PRUint32 numSrvNameCacheEntries; + PRUint32 srvNameCacheSize; - PRUint32 ssl2Timeout; - PRUint32 ssl3Timeout; + PRUint32 ssl3Timeout; - PRUint32 numSIDCacheLocksInitialized; + PRUint32 numSIDCacheLocksInitialized; /* These values are volatile, and are accessed through sharedCache-> */ - PRUint32 nextCertCacheEntry; /* certCacheLock protects */ - PRBool stopPolling; - PRBool everInherited; + 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; + 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; + char *cacheMem; + struct cacheDescStr *sharedCache; /* shared copy of this struct */ + PRFileMap *cacheMemMap; + PRThread *poller; + PRUint32 mutexTimeout; + PRBool shared; }; typedef struct cacheDescStr cacheDesc; @@ -235,48 +217,41 @@ static cacheDesc globalCache; static const char envVarName[] = { SSL_ENV_VAR_NAME }; -static PRBool isMultiProcess = PR_FALSE; - +static PRBool isMultiProcess = PR_FALSE; -#define DEF_SID_CACHE_ENTRIES 10000 +#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 DEF_KEY_CACHE_ENTRIES 250 +#define DEF_NAME_CACHE_ENTRIES 1000 -#define SID_CACHE_ENTRIES_PER_SET 128 -#define SID_ALIGNMENT 16 +#define SID_CACHE_ENTRIES_PER_SET 128 +#define SID_ALIGNMENT 16 -#define DEF_SSL2_TIMEOUT 100 /* seconds */ -#define MAX_SSL2_TIMEOUT 100 /* seconds */ -#define MIN_SSL2_TIMEOUT 5 /* seconds */ - -#define DEF_SSL3_TIMEOUT 86400L /* 24 hours */ -#define MAX_SSL3_TIMEOUT 86400L /* 24 hours */ -#define MIN_SSL3_TIMEOUT 5 /* seconds */ +#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 */ +#define MAX_SID_CACHE_LOCKS 8 /* two FDs per lock */ #elif defined(OSF1) -#define MAX_SID_CACHE_LOCKS 16 /* one FD per lock */ +#define MAX_SID_CACHE_LOCKS 16 /* one FD 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))) - +#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; +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, +static PRUint32 SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl); static SECStatus LaunchLockPoller(cacheDesc *cache); static SECStatus StopLockPoller(cacheDesc *cache); - struct inheritanceStr { PRUint32 cacheMemSize; PRUint32 fmStrLen; @@ -296,29 +271,28 @@ typedef struct inheritanceStr inheritance; #endif /* XP_UNIX || XP_BEOS */ - /************************************************************************/ static PRUint32 LockSidCacheLock(sidCacheLock *lock, PRUint32 now) { - SECStatus rv = sslMutex_Lock(&lock->mutex); + SECStatus rv = sslMutex_Lock(&lock->mutex); if (rv != SECSuccess) - return 0; + return 0; if (!now) - now = ssl_Time(); + now = ssl_Time(); lock->timeStamp = now; - lock->pid = myPid; + lock->pid = myPid; return now; } static SECStatus UnlockSidCacheLock(sidCacheLock *lock) { - SECStatus rv; + SECStatus rv; lock->pid = 0; - rv = sslMutex_Unlock(&lock->mutex); + rv = sslMutex_Unlock(&lock->mutex); return rv; } @@ -326,8 +300,8 @@ UnlockSidCacheLock(sidCacheLock *lock) static PRUint32 LockSet(cacheDesc *cache, PRUint32 set, PRUint32 now) { - PRUint32 lockNum = set % cache->numSIDCacheLocks; - sidCacheLock * lock = cache->sidCacheLocks + lockNum; + PRUint32 lockNum = set % cache->numSIDCacheLocks; + sidCacheLock *lock = cache->sidCacheLocks + lockNum; return LockSidCacheLock(lock, now); } @@ -335,28 +309,27 @@ LockSet(cacheDesc *cache, PRUint32 set, PRUint32 now) static SECStatus UnlockSet(cacheDesc *cache, PRUint32 set) { - PRUint32 lockNum = set % cache->numSIDCacheLocks; - sidCacheLock * lock = cache->sidCacheLocks + lockNum; + 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) +CacheCert(cacheDesc *cache, CERTCertificate *cert, sidCacheEntry *sce) { - PRUint32 now; - certCacheEntry cce; + 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; + (cert->derCert.data == NULL)) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return 0; } cce.sessionIDLength = sce->sessionIDLength; @@ -369,24 +342,23 @@ CacheCert(cacheDesc * cache, CERTCertificate *cert, sidCacheEntry *sce) now = LockSidCacheLock(cache->certCacheLock, 0); if (now) { - /* Find where to place the next cert cache entry. */ - cacheDesc * sharedCache = cache->sharedCache; - PRUint32 ndx = sharedCache->nextCertCacheEntry; + /* Find where to place the next cert cache entry. */ + cacheDesc *sharedCache = cache->sharedCache; + PRUint32 ndx = sharedCache->nextCertCacheEntry; - /* write the entry */ - cache->certCacheData[ndx] = cce; + /* write the entry */ + cache->certCacheData[ndx] = cce; - /* remember where we put it. */ - sce->u.ssl3.certIndex = ndx; + /* remember where we put it. */ + sce->u.ssl3.certIndex = ndx; - /* update the "next" cache entry index */ - sharedCache->nextCertCacheEntry = - (ndx + 1) % cache->numCertCacheEntries; + /* update the "next" cache entry index */ + sharedCache->nextCertCacheEntry = + (ndx + 1) % cache->numCertCacheEntries; - UnlockSidCacheLock(cache->certCacheLock); + UnlockSidCacheLock(cache->certCacheLock); } return now; - } /* Server configuration hash tables need to account the SECITEM.type @@ -395,9 +367,9 @@ static PLHashNumber Get32BitNameHash(const SECItem *name) { PLHashNumber rv = SECITEM_Hash(name); - + PRUint8 *rvc = (PRUint8 *)&rv; - rvc[ name->len % sizeof(rv) ] ^= name->type; + rvc[name->len % sizeof(rv)] ^= name->type; return rv; } @@ -405,27 +377,23 @@ Get32BitNameHash(const SECItem *name) /* Put a name in the cache. Update the cert index in the sce. */ static PRUint32 -CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) +CacheSrvName(cacheDesc *cache, SECItem *name, sidCacheEntry *sce) { - PRUint32 now; - PRUint32 ndx; - srvNameCacheEntry snce; + 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; + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return 0; } snce.type = name->type; snce.nameLen = name->len; PORT_Memcpy(snce.name, name->data, snce.nameLen); -#ifdef NO_PKCS11_BYPASS HASH_HashBuf(HASH_AlgSHA256, snce.nameHash, name->data, name->len); -#else - SHA256_HashBuf(snce.nameHash, (unsigned char*)name->data, - name->len); -#endif + /* get index of the next name */ ndx = Get32BitNameHash(name); /* get lock on cert cache */ @@ -441,7 +409,7 @@ CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) /* Copy hash into sid hash */ PORT_Memcpy(sce->u.ssl3.srvNameHash, snce.nameHash, SHA256_LENGTH); } - UnlockSidCacheLock(cache->srvNameCacheLock); + UnlockSidCacheLock(cache->srvNameCacheLock); } return now; } @@ -449,73 +417,47 @@ CacheSrvName(cacheDesc * cache, SECItem *name, sidCacheEntry *sce) /* ** Convert local SID to shared memory one */ -static void +static void ConvertFromSID(sidCacheEntry *to, sslSessionID *from) { - to->valid = 1; + to->valid = 1; to->version = from->version; - to->addr = from->addr; - to->creationTime = from->creationTime; - to->lastAccessTime = from->lastAccessTime; - to->expirationTime = from->expirationTime; - to->authAlgorithm = from->authAlgorithm; - to->authKeyBits = from->authKeyBits; - to->keaType = from->keaType; - to->keaKeyBits = from->keaKeyBits; - - if (from->version < SSL_LIBRARY_VERSION_3_0) { - if ((from->u.ssl2.masterKey.len > SSL_MAX_MASTER_KEY_BYTES) || - (from->u.ssl2.cipherArg.len > SSL_MAX_CYPHER_ARG_BYTES)) { - SSL_DBG(("%d: SSL: masterKeyLen=%d cipherArgLen=%d", - myPid, from->u.ssl2.masterKey.len, - from->u.ssl2.cipherArg.len)); - to->valid = 0; - return; - } - - to->u.ssl2.cipherType = from->u.ssl2.cipherType; - to->u.ssl2.masterKeyLen = from->u.ssl2.masterKey.len; - to->u.ssl2.cipherArgLen = from->u.ssl2.cipherArg.len; - to->u.ssl2.keyBits = from->u.ssl2.keyBits; - to->u.ssl2.secretKeyBits = from->u.ssl2.secretKeyBits; - to->sessionIDLength = SSL2_SESSIONID_BYTES; - PORT_Memcpy(to->sessionID, from->u.ssl2.sessionID, SSL2_SESSIONID_BYTES); - PORT_Memcpy(to->u.ssl2.masterKey, from->u.ssl2.masterKey.data, - from->u.ssl2.masterKey.len); - PORT_Memcpy(to->u.ssl2.cipherArg, from->u.ssl2.cipherArg.data, - from->u.ssl2.cipherArg.len); -#ifdef DEBUG - PORT_Memset(to->u.ssl2.masterKey+from->u.ssl2.masterKey.len, 0, - sizeof(to->u.ssl2.masterKey) - from->u.ssl2.masterKey.len); - PORT_Memset(to->u.ssl2.cipherArg+from->u.ssl2.cipherArg.len, 0, - sizeof(to->u.ssl2.cipherArg) - from->u.ssl2.cipherArg.len); -#endif - SSL_TRC(8, ("%d: SSL: ConvertSID: masterKeyLen=%d cipherArgLen=%d " - "time=%d addr=0x%08x%08x%08x%08x cipherType=%d", myPid, - to->u.ssl2.masterKeyLen, to->u.ssl2.cipherArgLen, - to->creationTime, 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.ssl2.cipherType)); - } else { - /* This is an SSL v3 session */ - - to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; - to->u.ssl3.compression = (PRUint16)from->u.ssl3.compression; - to->u.ssl3.keys = from->u.ssl3.keys; - to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech; - to->u.ssl3.exchKeyType = from->u.ssl3.exchKeyType; - 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); - - SSL_TRC(8, ("%d: SSL3: ConvertSID: time=%d addr=0x%08x%08x%08x%08x " - "cipherSuite=%d", - myPid, to->creationTime, 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)); - } + 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->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; + to->u.ssl3.compression = (PRUint16)from->u.ssl3.compression; + 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.certTypeArgs = 0U; + switch (from->authType) { + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: + PORT_Assert(from->certType.namedCurve); + to->u.ssl3.certTypeArgs = + (PRUint16)from->certType.namedCurve->name; + break; + default: + break; + } + + SSL_TRC(8, ("%d: SSL3: ConvertSID: time=%d addr=0x%08x%08x%08x%08x " + "cipherSuite=%d", + myPid, to->creationTime, 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)); } /* @@ -523,144 +465,106 @@ ConvertFromSID(sidCacheEntry *to, sslSessionID *from) ** This is only called from ServerSessionIDLookup(). */ static sslSessionID * -ConvertToSID(sidCacheEntry * from, - certCacheEntry * pcce, +ConvertToSID(sidCacheEntry *from, + certCacheEntry *pcce, srvNameCacheEntry *psnce, - CERTCertDBHandle * dbHandle) + CERTCertDBHandle *dbHandle) { sslSessionID *to; - PRUint16 version = from->version; to = PORT_ZNew(sslSessionID); if (!to) { - return 0; - } - - if (version < SSL_LIBRARY_VERSION_3_0) { - /* This is an SSL v2 session */ - to->u.ssl2.masterKey.data = - (unsigned char*) PORT_Alloc(from->u.ssl2.masterKeyLen); - if (!to->u.ssl2.masterKey.data) { - goto loser; - } - if (from->u.ssl2.cipherArgLen) { - to->u.ssl2.cipherArg.data = - (unsigned char*)PORT_Alloc(from->u.ssl2.cipherArgLen); - if (!to->u.ssl2.cipherArg.data) { - goto loser; - } - PORT_Memcpy(to->u.ssl2.cipherArg.data, from->u.ssl2.cipherArg, - from->u.ssl2.cipherArgLen); - } - - to->u.ssl2.cipherType = from->u.ssl2.cipherType; - to->u.ssl2.masterKey.len = from->u.ssl2.masterKeyLen; - to->u.ssl2.cipherArg.len = from->u.ssl2.cipherArgLen; - to->u.ssl2.keyBits = from->u.ssl2.keyBits; - to->u.ssl2.secretKeyBits = from->u.ssl2.secretKeyBits; -/* to->sessionIDLength = SSL2_SESSIONID_BYTES; */ - PORT_Memcpy(to->u.ssl2.sessionID, from->sessionID, SSL2_SESSIONID_BYTES); - PORT_Memcpy(to->u.ssl2.masterKey.data, from->u.ssl2.masterKey, - from->u.ssl2.masterKeyLen); - - SSL_TRC(8, ("%d: SSL: ConvertToSID: masterKeyLen=%d cipherArgLen=%d " - "time=%d addr=0x%08x%08x%08x%08x cipherType=%d", - myPid, to->u.ssl2.masterKey.len, - to->u.ssl2.cipherArg.len, to->creationTime, - 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.ssl2.cipherType)); - } else { - /* This is an SSL v3 session */ - - to->u.ssl3.sessionIDLength = from->sessionIDLength; - to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; - to->u.ssl3.compression = (SSLCompressionMethod)from->u.ssl3.compression; - to->u.ssl3.keys = from->u.ssl3.keys; - to->u.ssl3.masterWrapMech = from->u.ssl3.masterWrapMech; - to->u.ssl3.exchKeyType = from->u.ssl3.exchKeyType; - 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; - } + return 0; + } + + to->u.ssl3.sessionIDLength = from->sessionIDLength; + to->u.ssl3.cipherSuite = from->u.ssl3.cipherSuite; + to->u.ssl3.compression = (SSLCompressionMethod)from->u.ssl3.compression; + 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); + PORT_Memcpy(to->u.ssl3.sessionID, from->sessionID, from->sessionIDLength); - /* the portions of the SID that are only restored on the client - * are set to invalid values on the server. - */ - to->u.ssl3.clientWriteKey = NULL; - to->u.ssl3.serverWriteKey = NULL; + /* the portions of the SID that are only restored on the client + * are set to invalid values on the server. + */ + to->u.ssl3.clientWriteKey = NULL; + to->u.ssl3.serverWriteKey = NULL; - to->urlSvrName = NULL; + 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.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; + 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; + if (from->u.ssl3.certIndex != -1 && pcce) { + SECItem derCert; - derCert.len = pcce->certLength; - derCert.data = pcce->cert; + 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; - } + to->peerCert = CERT_NewTempCertificate(dbHandle, &derCert, NULL, + PR_FALSE, PR_TRUE); + if (to->peerCert == NULL) + goto loser; + } + to->certType.authType = from->authType; + switch (from->authType) { + case ssl_auth_ecdsa: + case ssl_auth_ecdh_rsa: + case ssl_auth_ecdh_ecdsa: + to->certType.namedCurve = + ssl_LookupNamedGroup((SSLNamedGroup)from->u.ssl3.certTypeArgs); + break; + default: + break; } - 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->authAlgorithm = from->authAlgorithm; - to->authKeyBits = from->authKeyBits; - to->keaType = from->keaType; - to->keaKeyBits = from->keaKeyBits; + 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; return to; - loser: +loser: if (to) { - if (version < SSL_LIBRARY_VERSION_3_0) { - if (to->u.ssl2.masterKey.data) - PORT_Free(to->u.ssl2.masterKey.data); - if (to->u.ssl2.cipherArg.data) - PORT_Free(to->u.ssl2.cipherArg.data); - } else { - SECITEM_FreeItem(&to->u.ssl3.srvName, PR_FALSE); - } - PORT_Free(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 +static PRUint32 SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl) { PRUint32 rv; @@ -668,18 +572,16 @@ SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl) memset(x, 0, sizeof x); if (nl > sizeof x) - 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; + 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! @@ -688,45 +590,45 @@ SIDindex(cacheDesc *cache, const PRIPv6Addr *addr, PRUint8 *s, unsigned nl) static sidCacheEntry * FindSID(cacheDesc *cache, PRUint32 setNum, PRUint32 now, const PRIPv6Addr *addr, unsigned char *sessionID, - unsigned sessionIDLength) + unsigned sessionIDLength) { - PRUint32 ndx = cache->sidCacheSets[setNum].next; - int i; + PRUint32 ndx = cache->sidCacheSets[setNum].next; + int i; - sidCacheEntry * set = cache->sidCacheData + - (setNum * SID_CACHE_ENTRIES_PER_SET); + 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; - } + 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); @@ -736,245 +638,206 @@ FindSID(cacheDesc *cache, PRUint32 setNum, PRUint32 now, /************************************************************************/ /* 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 + * Although it is static, this function is called via the global function * pointer ssl_sid_lookup. */ static sslSessionID * ServerSessionIDLookup(const PRIPv6Addr *addr, - unsigned char *sessionID, - unsigned int sessionIDLength, - CERTCertDBHandle * dbHandle) + unsigned char *sessionID, + unsigned int sessionIDLength, + CERTCertDBHandle *dbHandle) { - sslSessionID * sid = 0; - sidCacheEntry * psce; - certCacheEntry *pcce = 0; + sslSessionID *sid = 0; + sidCacheEntry *psce; + certCacheEntry *pcce = 0; srvNameCacheEntry *psnce = 0; - cacheDesc * cache = &globalCache; - PRUint32 now; - PRUint32 set; - PRInt32 cndx; - sidCacheEntry sce; - certCacheEntry cce; + 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; + return NULL; psce = FindSID(cache, set, now, addr, sessionID, sessionIDLength); if (psce) { - if (psce->version >= SSL_LIBRARY_VERSION_3_0) { - 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); + 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 { - /* what the ??. Didn't get the cert cache lock. - ** Don't invalidate the SID cache entry, but don't find it. + /* The cert doesen't match the SID cache entry, + ** so invalidate the SID cache entry. */ - PORT_Assert(!("Didn't get cert Cache Lock!")); + 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_Assert(!("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); + } + 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 { - /* what the ??. Didn't get the cert cache lock. - ** Don't invalidate the SID cache entry, but don't find it. + /* The name doesen't match the SID cache entry, + ** so invalidate the SID cache entry. */ - PORT_Assert(!("Didn't get name Cache Lock!")); + 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_Assert(!("Didn't get name Cache Lock!")); + psce = 0; + psnce = 0; } } - if (psce) { - psce->lastAccessTime = now; - sce = *psce; /* grab a copy while holding the lock */ - } + if (psce) { + psce->lastAccessTime = now; + 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); + /* 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. +** Place a sid into the cache, if it isn't already there. */ -static void +static void ServerSessionIDCache(sslSessionID *sid) { sidCacheEntry sce; - PRUint32 now = 0; - PRUint16 version = sid->version; - cacheDesc * cache = &globalCache; + PRUint32 now = 0; + cacheDesc *cache = &globalCache; - if ((version >= SSL_LIBRARY_VERSION_3_0) && - (sid->u.ssl3.sessionIDLength == 0)) { - return; + if (sid->u.ssl3.sessionIDLength == 0) { + return; } if (sid->cached == never_cached || sid->cached == invalid_cache) { - PRUint32 set; - - PORT_Assert(sid->creationTime != 0); - if (!sid->creationTime) - sid->lastAccessTime = sid->creationTime = ssl_Time(); - if (version < SSL_LIBRARY_VERSION_3_0) { - /* override caller's expiration time, which uses client timeout - * duration, not server timeout duration. - */ - sid->expirationTime = sid->creationTime + cache->ssl2Timeout; - SSL_TRC(8, ("%d: SSL: CacheMT: cached=%d addr=0x%08x%08x%08x%08x time=%x " - "cipher=%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, sid->u.ssl2.cipherType)); - PRINT_BUF(8, (0, "sessionID:", sid->u.ssl2.sessionID, - SSL2_SESSIONID_BYTES)); - PRINT_BUF(8, (0, "masterKey:", sid->u.ssl2.masterKey.data, - sid->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", sid->u.ssl2.cipherArg.data, - sid->u.ssl2.cipherArg.len)); - - } else { - /* override caller's expiration time, which uses client timeout - * duration, not server timeout duration. - */ - sid->expirationTime = sid->creationTime + cache->ssl3Timeout; - 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, sid->u.ssl3.cipherSuite)); - PRINT_BUF(8, (0, "sessionID:", sid->u.ssl3.sessionID, - sid->u.ssl3.sessionIDLength)); - } - - ConvertFromSID(&sce, sid); - - if (version >= SSL_LIBRARY_VERSION_3_0) { - SECItem *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); - } - } + PRUint32 set; + SECItem *name; + + PORT_Assert(sid->creationTime != 0); + if (!sid->creationTime) + sid->lastAccessTime = sid->creationTime = ssl_Time(); + /* override caller's expiration time, which uses client timeout + * duration, not server timeout duration. + */ + sid->expirationTime = sid->creationTime + cache->ssl3Timeout; + 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, 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; + 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; + /* Write out new cache entry */ + cache->sidCacheData[ndx] = sce; - cache->sidCacheSets[set].next = - (next + 1) % SID_CACHE_ENTRIES_PER_SET; + cache->sidCacheSets[set].next = + (next + 1) % SID_CACHE_ENTRIES_PER_SET; - UnlockSet(cache, set); - sid->cached = in_server_cache; - } + 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. +** ssl_sid_uncache. This invalidates the referenced cache entry. */ -static void +static void ServerSessionIDUncache(sslSessionID *sid) { - cacheDesc * cache = &globalCache; - PRUint8 * sessionID; - unsigned int sessionIDLength; - PRErrorCode err; - PRUint32 set; - PRUint32 now; + 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. + 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(); - if (sid->version < SSL_LIBRARY_VERSION_3_0) { - sessionID = sid->u.ssl2.sessionID; - sessionIDLength = SSL2_SESSIONID_BYTES; - SSL_TRC(8, ("%d: SSL: UncacheMT: valid=%d addr=0x%08x%08x%08x%08x time=%x " - "cipher=%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, sid->u.ssl2.cipherType)); - PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength)); - PRINT_BUF(8, (0, "masterKey:", sid->u.ssl2.masterKey.data, - sid->u.ssl2.masterKey.len)); - PRINT_BUF(8, (0, "cipherArg:", sid->u.ssl2.cipherArg.data, - sid->u.ssl2.cipherArg.len)); - } else { - 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, sid->u.ssl3.cipherSuite)); - PRINT_BUF(8, (0, "sessionID:", sessionID, sessionIDLength)); - } + 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, 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); + psce = FindSID(cache, set, now, &sid->addr, sessionID, sessionIDLength); + if (psce) { + psce->valid = 0; + } + UnlockSet(cache, set); } sid->cached = invalid_cache; PORT_SetError(err); @@ -985,7 +848,8 @@ ServerSessionIDUncache(sslSessionID *sid) #define INCL_DOSPROCESS #include <os2.h> -long gettid(void) +long +gettid(void) { PTIB ptib; PPIB ppib; @@ -1000,59 +864,59 @@ 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->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; + PR_CloseFileMap(cache->cacheMemMap); + cache->cacheMemMap = NULL; } memset(cache, 0, sizeof *cache); } static SECStatus InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, - int maxSrvNameCacheEntries, PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, const char *directory, PRBool shared) + int maxSrvNameCacheEntries, PRUint32 ssl3_timeout, + const char *directory, PRBool shared) { - ptrdiff_t ptr; + 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) ) { + 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; + /* Already done */ + return SECSuccess; } /* make sure loser can clean up properly */ cache->shared = shared; - cache->cacheMem = cacheMem = NULL; + cache->cacheMem = cacheMem = NULL; cache->cacheMemMap = cacheMemMap = NULL; cache->sharedCache = (cacheDesc *)0; @@ -1063,71 +927,71 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, cache->poller = NULL; cache->mutexTimeout = 0; - cache->numSIDCacheEntries = maxCacheEntries ? maxCacheEntries + cache->numSIDCacheEntries = maxCacheEntries ? maxCacheEntries : DEF_SID_CACHE_ENTRIES; - cache->numSIDCacheSets = - SID_HOWMANY(cache->numSIDCacheEntries, SID_CACHE_ENTRIES_PER_SET); + cache->numSIDCacheSets = + SID_HOWMANY(cache->numSIDCacheEntries, SID_CACHE_ENTRIES_PER_SET); - cache->numSIDCacheEntries = - cache->numSIDCacheSets * 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->numSIDCacheLocks = + PR_MIN(cache->numSIDCacheSets, ssl_max_sid_cache_locks); - cache->numSIDCacheSetsPerLock = - SID_HOWMANY(cache->numSIDCacheSets, cache->numSIDCacheLocks); + cache->numSIDCacheSetsPerLock = + SID_HOWMANY(cache->numSIDCacheSets, cache->numSIDCacheLocks); - cache->numCertCacheEntries = (maxCertCacheEntries > 0) ? - maxCertCacheEntries : 0; - cache->numSrvNameCacheEntries = (maxSrvNameCacheEntries >= 0) ? - maxSrvNameCacheEntries : DEF_NAME_CACHE_ENTRIES; + 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; + 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; + 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; + cache->sidCacheSets = (sidCacheSet *)ptr; ptr = (ptrdiff_t)(cache->sidCacheSets + cache->numSIDCacheSets); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); - cache->sidCacheData = (sidCacheEntry *)ptr; + 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; + 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; + 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->keyCacheData = (SSLWrappedSymWrappingKey *)ptr; + cache->certCacheSize = + (char *)cache->keyCacheData - (char *)cache->certCacheData; - cache->numKeyCacheEntries = kt_kea_size * SSL_NUM_WRAP_MECHS; + cache->numKeyCacheEntries = ssl_auth_size * 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->keyCacheSize = (char *)ptr - (char *)cache->keyCacheData; cache->ticketKeyNameSuffix = (PRUint8 *)ptr; ptr = (ptrdiff_t)(cache->ticketKeyNameSuffix + - SESS_TICKET_KEY_VAR_NAME_LEN); + SESS_TICKET_KEY_VAR_NAME_LEN); ptr = SID_ROUNDUP(ptr, SID_ALIGNMENT); cache->ticketEncKey = (encKeyCacheEntry *)ptr; @@ -1150,66 +1014,54 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, cache->cacheMemSize = ptr; - if (ssl2_timeout) { - if (ssl2_timeout > MAX_SSL2_TIMEOUT) { - ssl2_timeout = MAX_SSL2_TIMEOUT; - } - if (ssl2_timeout < MIN_SSL2_TIMEOUT) { - ssl2_timeout = MIN_SSL2_TIMEOUT; - } - cache->ssl2Timeout = ssl2_timeout; - } else { - cache->ssl2Timeout = DEF_SSL2_TIMEOUT; - } - - 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; + 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; + cache->ssl3Timeout = DEF_SSL3_TIMEOUT; } if (shared) { - /* Create file names */ +/* Create file names */ #if defined(XP_UNIX) || defined(XP_BEOS) - /* 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); + /* 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()); + 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()); + 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; - } + if (!cfn) { + goto loser; + } - /* Create cache */ - cacheMemMap = PR_OpenAnonFileMap(cfn, cache->cacheMemSize, - PR_PROT_READWRITE); + /* Create cache */ + cacheMemMap = PR_OpenAnonFileMap(cfn, cache->cacheMemSize, + PR_PROT_READWRITE); - PR_smprintf_free(cfn); - if(!cacheMemMap) { - goto loser; - } + PR_smprintf_free(cfn); + if (!cacheMemMap) { + goto loser; + } cacheMem = PR_MemMap(cacheMemMap, 0, cache->cacheMemSize); } else { cacheMem = PORT_Alloc(cache->cacheMemSize); } - - if (! cacheMem) { + + if (!cacheMem) { goto loser; } @@ -1221,53 +1073,40 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, /* save private copies of these values */ cache->cacheMemMap = cacheMemMap; - cache->cacheMem = cacheMem; + cache->cacheMem = cacheMem; cache->sharedCache = (cacheDesc *)cacheMem; - /* Fix pointers in our private copy of cache descriptor to point to - ** spaces in shared memory + /* 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); + 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_Time(); 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; - } + 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; + pLock->pid = 0; } cache->numSIDCacheLocksInitialized = locks_initialized; @@ -1275,6 +1114,7 @@ InitCache(cacheDesc *cache, int maxCacheEntries, int maxCertCacheEntries, loser: CloseCache(cache); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } @@ -1294,8 +1134,8 @@ SSL_SetMaxServerCacheLocks(PRUint32 maxLocks) ** the maximum, other than trial and error. */ if (maxLocks < 3) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + 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. */ @@ -1304,13 +1144,12 @@ SSL_SetMaxServerCacheLocks(PRUint32 maxLocks) static SECStatus ssl_ConfigServerSessionIDCacheInstanceWithOpt(cacheDesc *cache, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, + PRUint32 ssl3_timeout, + const char *directory, PRBool shared, - int maxCacheEntries, - int maxCertCacheEntries, - int maxSrvNameCacheEntries) + int maxCacheEntries, + int maxCertCacheEntries, + int maxSrvNameCacheEntries) { SECStatus rv; @@ -1320,52 +1159,49 @@ ssl_ConfigServerSessionIDCacheInstanceWithOpt(cacheDesc *cache, rv = ssl_Init(); if (rv != SECSuccess) { - return rv; + return rv; } myPid = SSL_GETPID(); if (!directory) { - directory = DEFAULT_CACHE_DIRECTORY; + directory = DEFAULT_CACHE_DIRECTORY; } rv = InitCache(cache, maxCacheEntries, maxCertCacheEntries, - maxSrvNameCacheEntries, ssl2_timeout, ssl3_timeout, - directory, shared); + maxSrvNameCacheEntries, ssl3_timeout, directory, shared); if (rv) { - SET_ERROR_CODE - return SECFailure; + return SECFailure; } - ssl_sid_lookup = ServerSessionIDLookup; - ssl_sid_cache = ServerSessionIDCache; + ssl_sid_lookup = ServerSessionIDLookup; + ssl_sid_cache = ServerSessionIDCache; ssl_sid_uncache = ServerSessionIDUncache; return SECSuccess; } SECStatus -SSL_ConfigServerSessionIDCacheInstance( cacheDesc *cache, - int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, PRBool shared) +SSL_ConfigServerSessionIDCacheInstance(cacheDesc *cache, + int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory, PRBool shared) { return ssl_ConfigServerSessionIDCacheInstanceWithOpt(cache, - ssl2_timeout, ssl3_timeout, directory, shared, - maxCacheEntries, + maxCacheEntries, -1, -1); } SECStatus -SSL_ConfigServerSessionIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +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); + return SSL_ConfigServerSessionIDCacheInstance(&globalCache, + maxCacheEntries, ssl2_timeout, ssl3_timeout, directory, PR_FALSE); } SECStatus @@ -1390,56 +1226,55 @@ SSL_ShutdownServerSessionIDCache(void) * if the cache will be shared by multiple processes. */ static SECStatus -ssl_ConfigMPServerSIDCacheWithOpt( PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, - int maxCacheEntries, - int maxCertCacheEntries, - int maxSrvNameCacheEntries) +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; + char *envValue; + char *inhValue; + cacheDesc *cache = &globalCache; + PRUint32 fmStrLen; + SECStatus result; + PRStatus prStatus; + SECStatus putEnvFailed; inheritance inherit; - char fmString[PR_FILEMAP_STRING_BUFSIZE]; + char fmString[PR_FILEMAP_STRING_BUFSIZE]; isMultiProcess = PR_TRUE; result = ssl_ConfigServerSessionIDCacheInstanceWithOpt(cache, - ssl2_timeout, ssl3_timeout, directory, PR_TRUE, - maxCacheEntries, maxCacheEntries, maxSrvNameCacheEntries); - if (result != SECSuccess) + ssl3_timeout, directory, PR_TRUE, + maxCacheEntries, maxCacheEntries, maxSrvNameCacheEntries); + if (result != SECSuccess) return result; - prStatus = PR_ExportFileMapAsString(cache->cacheMemMap, + prStatus = PR_ExportFileMapAsString(cache->cacheMemMap, sizeof fmString, fmString); if ((prStatus != PR_SUCCESS) || !(fmStrLen = strlen(fmString))) { - SET_ERROR_CODE - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } - inherit.cacheMemSize = cache->cacheMemSize; - inherit.fmStrLen = fmStrLen; + inherit.cacheMemSize = cache->cacheMemSize; + inherit.fmStrLen = fmStrLen; inhValue = BTOA_DataToAscii((unsigned char *)&inherit, sizeof inherit); if (!inhValue || !strlen(inhValue)) { - SET_ERROR_CODE - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } envValue = PR_smprintf("%s,%s", inhValue, fmString); if (!envValue || !strlen(envValue)) { - SET_ERROR_CODE - return SECFailure; + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; } PORT_Free(inhValue); putEnvFailed = (SECStatus)NSS_PutEnv(envVarName, envValue); PR_smprintf_free(envValue); if (putEnvFailed) { - SET_ERROR_CODE + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); result = SECFailure; } @@ -1454,13 +1289,12 @@ ssl_ConfigMPServerSIDCacheWithOpt( PRUint32 ssl2_timeout, * if the cache will be shared by multiple processes. */ SECStatus -SSL_ConfigMPServerSIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +SSL_ConfigMPServerSIDCache(int maxCacheEntries, + PRUint32 ssl2_timeout, + PRUint32 ssl3_timeout, + const char *directory) { - return ssl_ConfigMPServerSIDCacheWithOpt(ssl2_timeout, - ssl3_timeout, + return ssl_ConfigMPServerSIDCacheWithOpt(ssl3_timeout, directory, maxCacheEntries, -1, -1); @@ -1468,44 +1302,43 @@ SSL_ConfigMPServerSIDCache( int maxCacheEntries, SECStatus SSL_ConfigServerSessionIDCacheWithOpt( - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory, - int maxCacheEntries, - int maxCertCacheEntries, - int maxSrvNameCacheEntries, - PRBool enableMPCache) + 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, - ssl2_timeout, ssl3_timeout, directory, PR_FALSE, - maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries); + return ssl_ConfigServerSessionIDCacheInstanceWithOpt(&globalCache, + ssl3_timeout, directory, PR_FALSE, + maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries); } else { - return ssl_ConfigMPServerSIDCacheWithOpt(ssl2_timeout, ssl3_timeout, - directory, maxCacheEntries, maxCertCacheEntries, - maxSrvNameCacheEntries); + return ssl_ConfigMPServerSIDCacheWithOpt(ssl3_timeout, directory, + maxCacheEntries, maxCertCacheEntries, maxSrvNameCacheEntries); } } SECStatus -SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) +SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char *envString) { - unsigned char * decoString = NULL; - char * fmString = NULL; - char * myEnvString = NULL; - unsigned int decoLen; - inheritance inherit; - cacheDesc my; + 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; + sidCacheLock *newLocks; + int locks_initialized = 0; + int locks_to_initialize = 0; #endif - SECStatus status = ssl_Init(); + SECStatus status = ssl_Init(); if (status != SECSuccess) { - return status; + return status; } myPid = SSL_GETPID(); @@ -1515,110 +1348,94 @@ SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) ** If not, we'll set it below. */ if (isMultiProcess) { - if (cache && cache->sharedCache) { - cache->sharedCache->everInherited = PR_TRUE; - } - return SECSuccess; /* already done. */ + if (cache && cache->sharedCache) { + cache->sharedCache->everInherited = PR_TRUE; + } + return SECSuccess; /* already done. */ } ssl_InitSessionCacheLocks(PR_FALSE); - ssl_sid_lookup = ServerSessionIDLookup; - ssl_sid_cache = ServerSessionIDCache; + ssl_sid_lookup = ServerSessionIDLookup; + ssl_sid_cache = ServerSessionIDCache; ssl_sid_uncache = ServerSessionIDUncache; if (!envString) { - envString = getenv(envVarName); - if (!envString) { - SET_ERROR_CODE - return SECFailure; - } + envString = PR_GetEnvSecure(envVarName); + if (!envString) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } } myEnvString = PORT_Strdup(envString); - if (!myEnvString) - return SECFailure; + if (!myEnvString) + return SECFailure; fmString = strchr(myEnvString, ','); - if (!fmString) - goto loser; + if (!fmString) + goto loser; *fmString++ = 0; decoString = ATOB_AsciiToData(myEnvString, &decoLen); if (!decoString) { - SET_ERROR_CODE - goto loser; + goto loser; } if (decoLen != sizeof inherit) { - SET_ERROR_CODE - goto loser; + goto loser; } PORT_Memcpy(&inherit, decoString, sizeof inherit); - if (strlen(fmString) != inherit.fmStrLen ) { - goto loser; + if (strlen(fmString) != inherit.fmStrLen) { + goto loser; } memset(cache, 0, sizeof *cache); - cache->cacheMemSize = inherit.cacheMemSize; + cache->cacheMemSize = inherit.cacheMemSize; /* Create cache */ cache->cacheMemMap = PR_ImportFileMapFromString(fmString); - if(! cache->cacheMemMap) { - goto loser; + if (!cache->cacheMemMap) { + goto loser; } cache->cacheMem = PR_MemMap(cache->cacheMemMap, 0, cache->cacheMemSize); - if (! cache->cacheMem) { - goto loser; + if (!cache->cacheMem) { + goto loser; } - cache->sharedCache = (cacheDesc *)cache->cacheMem; + cache->sharedCache = (cacheDesc *)cache->cacheMem; if (cache->sharedCache->cacheMemSize != cache->cacheMemSize) { - SET_ERROR_CODE - goto loser; + 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 + /* 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. */ + 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 + /* 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->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->cacheMem = my.cacheMem; cache->sharedCache = (cacheDesc *)cache->cacheMem; #ifdef WINNT @@ -1633,34 +1450,34 @@ SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) ** 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. + ** 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; + goto loser; /* copy the old locks */ - memcpy(newLocks, cache->sidCacheLocks, + memcpy(newLocks, cache->sidCacheLocks, locks_to_initialize * sizeof(sidCacheLock)); cache->sidCacheLocks = newLocks; - /* fix the locks */ + /* 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; + SECStatus err; err = sslMutex_2LevelInit(&newLocks[locks_initialized].mutex); - if (err != SECSuccess) { - cache->numSIDCacheLocksInitialized = locks_initialized; - goto loser; - } + 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; + cache->keyCacheLock = cache->sidCacheLocks + cache->numSIDCacheLocks; + cache->certCacheLock = cache->keyCacheLock + 1; + cache->srvNameCacheLock = cache->certCacheLock + 1; #endif PORT_Free(myEnvString); @@ -1674,112 +1491,113 @@ SSL_InheritMPServerSIDCacheInstance(cacheDesc *cache, const char * envString) loser: PORT_Free(myEnvString); - if (decoString) - PORT_Free(decoString); + if (decoString) + PORT_Free(decoString); CloseCache(cache); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return SECFailure; } SECStatus -SSL_InheritMPServerSIDCache(const char * envString) +SSL_InheritMPServerSIDCache(const char *envString) { return SSL_InheritMPServerSIDCacheInstance(&globalCache, envString); } #if defined(XP_UNIX) || defined(XP_BEOS) -#define SID_LOCK_EXPIRATION_TIMEOUT 30 /* seconds */ +#define SID_LOCK_EXPIRATION_TIMEOUT 30 /* seconds */ static void -LockPoller(void * arg) +LockPoller(void *arg) { - cacheDesc * cache = (cacheDesc *)arg; - cacheDesc * sharedCache = cache->sharedCache; - sidCacheLock * pLock; + 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; + 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_Time(); - 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 */ + while (!sharedCache->stopPolling) { + PR_Sleep(timeout); + if (sharedCache->stopPolling) + break; + + now = ssl_Time(); + 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 +static SECStatus LaunchLockPoller(cacheDesc *cache) { - const char * timeoutString; - PRThread * pollerThread; + const char *timeoutString; + PRThread *pollerThread; cache->mutexTimeout = SID_LOCK_EXPIRATION_TIMEOUT; - timeoutString = getenv("NSS_SSL_SERVER_CACHE_MUTEX_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 */ + 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); + pollerThread = + PR_CreateThread(PR_USER_THREAD, LockPoller, cache, PR_PRIORITY_NORMAL, + PR_GLOBAL_THREAD, PR_JOINABLE_THREAD, 0); if (!pollerThread) { - return SECFailure; + return SECFailure; } cache->poller = pollerThread; return SECSuccess; } /* Stop the thread that polls cache for expired locks */ -static SECStatus +static SECStatus StopLockPoller(cacheDesc *cache) { if (!cache->poller) { - return SECSuccess; + return SECSuccess; } cache->sharedCache->stopPolling = PR_TRUE; if (PR_Interrupt(cache->poller) != PR_SUCCESS) { - return SECFailure; + return SECFailure; } if (PR_JoinThread(cache->poller) != PR_SUCCESS) { - return SECFailure; + return SECFailure; } cache->poller = NULL; return SECSuccess; @@ -1790,58 +1608,58 @@ StopLockPoller(cacheDesc *cache) * Code dealing with shared wrapped symmetric wrapping keys below * ************************************************************************/ -/* If now is zero, it implies that the lock is not held, and must be -** aquired here. +/* If now is zero, it implies that the lock is not held, and must be +** aquired here. */ static PRBool -getSvrWrappingKey(PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk, - cacheDesc * cache, - PRUint32 lockTime) +getSvrWrappingKey(PRInt32 symWrapMechIndex, + SSLAuthType authType, + SSLWrappedSymWrappingKey *wswk, + cacheDesc *cache, + PRUint32 lockTime) { - PRUint32 ndx = (exchKeyType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; - SSLWrappedSymWrappingKey * pwswk = cache->keyCacheData + ndx; - PRUint32 now = 0; - PRBool rv = PR_FALSE; + PRUint32 ndx = (authType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; + SSLWrappedSymWrappingKey *pwswk = cache->keyCacheData + ndx; + PRUint32 now = 0; + PRBool rv = PR_FALSE; if (!cache->cacheMem) { /* cache is uninitialized */ - PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); - return rv; + PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); + return rv; } if (!lockTime) { - lockTime = now = LockSidCacheLock(cache->keyCacheLock, now); - if (!lockTime) { - return rv; - } + lockTime = now = LockSidCacheLock(cache->keyCacheLock, now); + if (!lockTime) { + return rv; + } } - if (pwswk->exchKeyType == exchKeyType && - pwswk->symWrapMechIndex == symWrapMechIndex && - pwswk->wrappedSymKeyLen != 0) { - *wswk = *pwswk; - rv = PR_TRUE; + if (pwswk->authType == authType && + pwswk->symWrapMechIndex == symWrapMechIndex && + pwswk->wrappedSymKeyLen != 0) { + *wswk = *pwswk; + rv = PR_TRUE; } if (now) { - UnlockSidCacheLock(cache->keyCacheLock); + UnlockSidCacheLock(cache->keyCacheLock); } return rv; } PRBool -ssl_GetWrappingKey( PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk) +ssl_GetWrappingKey(PRInt32 symWrapMechIndex, + SSLAuthType authType, + SSLWrappedSymWrappingKey *wswk) { PRBool rv; - PORT_Assert( (unsigned)exchKeyType < kt_kea_size); - PORT_Assert( (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); - if ((unsigned)exchKeyType < kt_kea_size && + PORT_Assert((unsigned)authType < ssl_auth_size); + PORT_Assert((unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); + if ((unsigned)authType < ssl_auth_size && (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS) { - rv = getSvrWrappingKey(symWrapMechIndex, exchKeyType, wswk, - &globalCache, 0); + rv = getSvrWrappingKey(symWrapMechIndex, authType, wswk, + &globalCache, 0); } else { - rv = PR_FALSE; + rv = PR_FALSE; } return rv; @@ -1850,21 +1668,21 @@ ssl_GetWrappingKey( PRInt32 symWrapMechIndex, /* Wrap and cache a session ticket key. */ static PRBool WrapTicketKey(SECKEYPublicKey *svrPubKey, PK11SymKey *symKey, - const char *keyName, encKeyCacheEntry* cacheEntry) + const char *keyName, encKeyCacheEntry *cacheEntry) { - SECItem wrappedKey = {siBuffer, NULL, 0}; + 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; + 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 session ticket %s.", - SSL_GETPID(), "unknown", keyName)); - return PR_FALSE; + if (PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, symKey, &wrappedKey) != + SECSuccess) { + SSL_DBG(("%d: SSL[%s]: Unable to wrap session ticket %s.", + SSL_GETPID(), "unknown", keyName)); + return PR_FALSE; } cacheEntry->length = wrappedKey.len; return PR_TRUE; @@ -1890,10 +1708,11 @@ GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey, } if (PK11_GenerateRandom(ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN) != SECSuccess) { - SSL_DBG(("%d: SSL[%s]: Unable to generate random key name bytes.", - SSL_GETPID(), "unknown")); - goto loser; + SESS_TICKET_KEY_VAR_NAME_LEN) != + SECSuccess) { + SSL_DBG(("%d: SSL[%s]: Unable to generate random key name bytes.", + SSL_GETPID(), "unknown")); + goto loser; } mechanismArray[0] = CKM_AES_CBC; @@ -1901,17 +1720,17 @@ GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey, slot = PK11_GetBestSlotMultiple(mechanismArray, 2, pwArg); if (slot) { - aesKeyTmp = PK11_KeyGen(slot, mechanismArray[0], NULL, + aesKeyTmp = PK11_KeyGen(slot, mechanismArray[0], NULL, AES_256_KEY_LENGTH, pwArg); - macKeyTmp = PK11_KeyGen(slot, mechanismArray[1], NULL, + macKeyTmp = PK11_KeyGen(slot, mechanismArray[1], NULL, SHA256_LENGTH, pwArg); - PK11_FreeSlot(slot); + PK11_FreeSlot(slot); } if (aesKeyTmp == NULL || macKeyTmp == NULL) { - SSL_DBG(("%d: SSL[%s]: Unable to generate session ticket keys.", - SSL_GETPID(), "unknown")); - goto loser; + SSL_DBG(("%d: SSL[%s]: Unable to generate session ticket keys.", + SSL_GETPID(), "unknown")); + goto loser; } PORT_Memcpy(keyName, ticketKeyNameSuffix, SESS_TICKET_KEY_VAR_NAME_LEN); *aesKey = aesKeyTmp; @@ -1920,9 +1739,9 @@ GenerateTicketKeys(void *pwArg, unsigned char *keyName, PK11SymKey **aesKey, loser: if (aesKeyTmp) - PK11_FreeSymKey(aesKeyTmp); + PK11_FreeSymKey(aesKeyTmp); if (macKeyTmp) - PK11_FreeSymKey(macKeyTmp); + PK11_FreeSymKey(macKeyTmp); return PR_FALSE; } @@ -1952,9 +1771,9 @@ GenerateAndWrapTicketKeys(SECKEYPublicKey *svrPubKey, void *pwArg, loser: if (aesKeyTmp) - PK11_FreeSymKey(aesKeyTmp); + PK11_FreeSymKey(aesKeyTmp); if (macKeyTmp) - PK11_FreeSymKey(macKeyTmp); + PK11_FreeSymKey(macKeyTmp); return PR_FALSE; } @@ -1962,7 +1781,7 @@ static PRBool UnwrapCachedTicketKeys(SECKEYPrivateKey *svrPrivKey, unsigned char *keyName, PK11SymKey **aesKey, PK11SymKey **macKey) { - SECItem wrappedKey = {siBuffer, NULL, 0}; + SECItem wrappedKey = { siBuffer, NULL, 0 }; PK11SymKey *aesKeyTmp = NULL; PK11SymKey *macKeyTmp = NULL; cacheDesc *cache = &globalCache; @@ -1971,41 +1790,41 @@ UnwrapCachedTicketKeys(SECKEYPrivateKey *svrPrivKey, unsigned char *keyName, wrappedKey.len = cache->ticketEncKey->length; PORT_Assert(wrappedKey.len <= sizeof(cache->ticketEncKey->bytes)); aesKeyTmp = PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey, - CKM_AES_CBC, CKA_DECRYPT, 0); + 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); + 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]: Unable to unwrap session ticket keys.", + SSL_GETPID(), "unknown")); + goto loser; } SSL_DBG(("%d: SSL[%s]: Successfully unwrapped session ticket keys.", - SSL_GETPID(), "unknown")); + SSL_GETPID(), "unknown")); PORT_Memcpy(keyName, cache->ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN); + SESS_TICKET_KEY_VAR_NAME_LEN); *aesKey = aesKeyTmp; *macKey = macKeyTmp; return PR_TRUE; loser: if (aesKeyTmp) - PK11_FreeSymKey(aesKeyTmp); + PK11_FreeSymKey(aesKeyTmp); if (macKeyTmp) - PK11_FreeSymKey(macKeyTmp); + PK11_FreeSymKey(macKeyTmp); return PR_FALSE; } PRBool -ssl_GetSessionTicketKeysPKCS11(SECKEYPrivateKey *svrPrivKey, - SECKEYPublicKey *svrPubKey, void *pwArg, - unsigned char *keyName, PK11SymKey **aesKey, - PK11SymKey **macKey) +ssl_GetSessionTicketKeys(SECKEYPrivateKey *svrPrivKey, + SECKEYPublicKey *svrPubKey, void *pwArg, + unsigned char *keyName, PK11SymKey **aesKey, + PK11SymKey **macKey) { PRUint32 now = 0; PRBool rv = PR_FALSE; @@ -2020,143 +1839,80 @@ ssl_GetSessionTicketKeysPKCS11(SECKEYPrivateKey *svrPrivKey, now = LockSidCacheLock(cache->keyCacheLock, now); if (!now) - return rv; + return rv; if (!*(cache->ticketKeysValid)) { - /* Keys do not exist, create them. */ - if (!GenerateAndWrapTicketKeys(svrPubKey, pwArg, keyName, - aesKey, macKey)) - goto loser; - keysGenerated = PR_TRUE; - *(cache->ticketKeysValid) = 1; + /* Keys do not exist, create them. */ + if (!GenerateAndWrapTicketKeys(svrPubKey, pwArg, keyName, + aesKey, macKey)) + goto loser; + keysGenerated = PR_TRUE; + *(cache->ticketKeysValid) = 1; } rv = PR_TRUE; - loser: +loser: UnlockSidCacheLock(cache->keyCacheLock); if (rv && !keysGenerated) - rv = UnwrapCachedTicketKeys(svrPrivKey, keyName, aesKey, macKey); - return rv; -} - -PRBool -ssl_GetSessionTicketKeys(unsigned char *keyName, unsigned char *encKey, - unsigned char *macKey) -{ - PRBool rv = PR_FALSE; - PRUint32 now = 0; - cacheDesc *cache = &globalCache; - PRUint8 ticketMacKey[SHA256_LENGTH], ticketEncKey[AES_256_KEY_LENGTH]; - PRUint8 ticketKeyNameSuffixLocal[SESS_TICKET_KEY_VAR_NAME_LEN]; - PRUint8 *ticketMacKeyPtr, *ticketEncKeyPtr, *ticketKeyNameSuffix; - PRBool cacheIsEnabled = PR_TRUE; - - if (!cache->cacheMem) { /* cache is uninitialized */ - cacheIsEnabled = PR_FALSE; - ticketKeyNameSuffix = ticketKeyNameSuffixLocal; - ticketEncKeyPtr = ticketEncKey; - ticketMacKeyPtr = ticketMacKey; - } else { - /* these values have constant memory locations in the cache. - * Ok to reference them without holding the lock. */ - ticketKeyNameSuffix = cache->ticketKeyNameSuffix; - ticketEncKeyPtr = cache->ticketEncKey->bytes; - ticketMacKeyPtr = cache->ticketMacKey->bytes; - } - - if (cacheIsEnabled) { - /* Grab lock if initialized. */ - now = LockSidCacheLock(cache->keyCacheLock, now); - if (!now) - return rv; - } - /* Going to regenerate keys on every call if cache was not - * initialized. */ - if (!cacheIsEnabled || !*(cache->ticketKeysValid)) { - if (PK11_GenerateRandom(ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN) != SECSuccess) - goto loser; - if (PK11_GenerateRandom(ticketEncKeyPtr, - AES_256_KEY_LENGTH) != SECSuccess) - goto loser; - if (PK11_GenerateRandom(ticketMacKeyPtr, - SHA256_LENGTH) != SECSuccess) - goto loser; - if (cacheIsEnabled) { - *(cache->ticketKeysValid) = 1; - } - } - - rv = PR_TRUE; - - loser: - if (cacheIsEnabled) { - UnlockSidCacheLock(cache->keyCacheLock); - } - if (rv) { - PORT_Memcpy(keyName, ticketKeyNameSuffix, - SESS_TICKET_KEY_VAR_NAME_LEN); - PORT_Memcpy(encKey, ticketEncKeyPtr, AES_256_KEY_LENGTH); - PORT_Memcpy(macKey, ticketMacKeyPtr, SHA256_LENGTH); - } + rv = UnwrapCachedTicketKeys(svrPrivKey, keyName, aesKey, macKey); return rv; } /* 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 + * 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. */ PRBool ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk) { - cacheDesc * cache = &globalCache; - PRBool rv = PR_FALSE; - SSL3KEAType exchKeyType = wswk->exchKeyType; - /* type of keys used to wrap SymWrapKey*/ - PRInt32 symWrapMechIndex = wswk->symWrapMechIndex; - PRUint32 ndx; - PRUint32 now = 0; + cacheDesc *cache = &globalCache; + PRBool rv = PR_FALSE; + SSLAuthType authType = wswk->authType; + /* type of keys used to wrap SymWrapKey*/ + PRInt32 symWrapMechIndex = wswk->symWrapMechIndex; + PRUint32 ndx; + PRUint32 now = 0; SSLWrappedSymWrappingKey myWswk; if (!cache->cacheMem) { /* cache is uninitialized */ - PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); - return 0; + PORT_SetError(SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED); + return 0; } - PORT_Assert( (unsigned)exchKeyType < kt_kea_size); - if ((unsigned)exchKeyType >= kt_kea_size) - return 0; + PORT_Assert((unsigned)authType < ssl_auth_size); + if ((unsigned)authType >= ssl_auth_size) + return 0; - PORT_Assert( (unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); - if ((unsigned)symWrapMechIndex >= SSL_NUM_WRAP_MECHS) - return 0; + PORT_Assert((unsigned)symWrapMechIndex < SSL_NUM_WRAP_MECHS); + if ((unsigned)symWrapMechIndex >= SSL_NUM_WRAP_MECHS) + return 0; - ndx = (exchKeyType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; - PORT_Memset(&myWswk, 0, sizeof myWswk); /* eliminate UMRs. */ + ndx = (authType * SSL_NUM_WRAP_MECHS) + symWrapMechIndex; + PORT_Memset(&myWswk, 0, sizeof myWswk); /* eliminate UMRs. */ now = LockSidCacheLock(cache->keyCacheLock, now); if (now) { - rv = getSvrWrappingKey(wswk->symWrapMechIndex, wswk->exchKeyType, - &myWswk, cache, now); - if (rv) { - /* 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); + rv = getSvrWrappingKey(wswk->symWrapMechIndex, wswk->authType, + &myWswk, cache, now); + if (rv) { + /* 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 */ +#else /* MAC version or other platform */ #include "seccomon.h" #include "cert.h" @@ -2164,67 +1920,67 @@ ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk) #include "sslimpl.h" SECStatus -SSL_ConfigServerSessionIDCache( int maxCacheEntries, - PRUint32 ssl2_timeout, - PRUint32 ssl3_timeout, - const char * directory) +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)"); + 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) +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)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_ConfigMPServerSIDCache)"); return SECFailure; } SECStatus -SSL_InheritMPServerSIDCache(const char * envString) +SSL_InheritMPServerSIDCache(const char *envString) { - PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_InheritMPServerSIDCache)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_InheritMPServerSIDCache)"); return SECFailure; } PRBool -ssl_GetWrappingKey( PRInt32 symWrapMechIndex, - SSL3KEAType exchKeyType, - SSLWrappedSymWrappingKey *wswk) +ssl_GetWrappingKey(PRInt32 symWrapMechIndex, + SSLAuthType authType, + SSLWrappedSymWrappingKey *wswk) { PRBool rv = PR_FALSE; - PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_GetWrappingKey)"); + PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_GetWrappingKey)"); return rv; } /* 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 + * 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. */ PRBool ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk) { - PRBool rv = PR_FALSE; + PRBool rv = PR_FALSE; PR_ASSERT(!"SSL servers are not supported on this platform. (ssl_SetWrappingKey)"); return rv; } -PRUint32 +PRUint32 SSL_GetMaxServerCacheLocks(void) { PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_GetMaxServerCacheLocks)"); return -1; } -SECStatus +SECStatus SSL_SetMaxServerCacheLocks(PRUint32 maxLocks) { PR_ASSERT(!"SSL servers are not supported on this platform. (SSL_SetMaxServerCacheLocks)"); diff --git a/nss/lib/ssl/sslsock.c b/nss/lib/ssl/sslsock.c index f735009..626f4a9 100644 --- a/nss/lib/ssl/sslsock.c +++ b/nss/lib/ssl/sslsock.c @@ -1,3 +1,4 @@ +/* -*- 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. @@ -14,42 +15,37 @@ #include "sslproto.h" #include "nspr.h" #include "private/pprio.h" -#ifndef NO_PKCS11_BYPASS -#include "blapi.h" -#endif #include "nss.h" #include "pk11pqg.h" -#define SET_ERROR_CODE /* reminder */ - -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_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 +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 }; /* @@ -57,35 +53,37 @@ static const sslSocketOps ssl_secure_ops = { /* SSL. */ */ static sslOptions ssl_defaults = { { siBuffer, NULL, 0 }, /* nextProtoNego */ - PR_TRUE, /* useSecurity */ - PR_FALSE, /* useSocks */ - PR_FALSE, /* requestCertificate */ - 2, /* requireCertificate */ - PR_FALSE, /* handshakeAsClient */ - PR_FALSE, /* handshakeAsServer */ - PR_FALSE, /* enableSSL2 */ /* now defaults to off in NSS 3.13 */ - PR_FALSE, /* unusedBit9 */ - PR_FALSE, /* unusedBit10 */ - PR_FALSE, /* noCache */ - PR_FALSE, /* fdx */ - PR_FALSE, /* v2CompatibleHello */ /* now defaults to off in NSS 3.13 */ - PR_TRUE, /* detectRollBack */ - PR_FALSE, /* noStepDown */ - PR_FALSE, /* bypassPKCS11 */ - PR_FALSE, /* noLocks */ - PR_FALSE, /* enableSessionTickets */ - PR_FALSE, /* enableDeflate */ - 2, /* enableRenegotiation (default: requires extension) */ - PR_FALSE, /* requireSafeNegotiation */ - PR_FALSE, /* enableFalseStart */ - PR_TRUE, /* cbcRandomIV */ - PR_FALSE, /* enableOCSPStapling */ - PR_TRUE, /* enableNPN */ - PR_FALSE, /* enableALPN */ - PR_TRUE, /* reuseServerECDHEKey */ - PR_FALSE, /* enableFallbackSCSV */ - PR_TRUE, /* enableServerDhe */ - PR_FALSE /* enableExtendedMS */ + PR_TRUE, /* useSecurity */ + PR_FALSE, /* useSocks */ + PR_FALSE, /* requestCertificate */ + 2, /* requireCertificate */ + PR_FALSE, /* handshakeAsClient */ + PR_FALSE, /* handshakeAsServer */ + PR_FALSE, /* noCache */ + PR_FALSE, /* fdx */ + PR_TRUE, /* detectRollBack */ + PR_FALSE, /* noLocks */ + PR_FALSE, /* enableSessionTickets */ + PR_FALSE, /* enableDeflate */ + 2, /* enableRenegotiation (default: requires extension) */ + PR_FALSE, /* requireSafeNegotiation */ + PR_FALSE, /* enableFalseStart */ + PR_TRUE, /* cbcRandomIV */ + PR_FALSE, /* enableOCSPStapling */ + PR_FALSE, /* enableNPN */ + PR_TRUE, /* enableALPN */ + PR_TRUE, /* reuseServerECDHEKey */ + PR_FALSE, /* enableFallbackSCSV */ + PR_TRUE, /* enableServerDhe */ + PR_FALSE, /* enableExtendedMS */ + PR_FALSE, /* enableSignedCertTimestamps */ + PR_FALSE, /* requireDHENamedGroups */ + PR_FALSE, /* enable0RttData */ +#ifdef NSS_ENABLE_TLS13_SHORT_HEADERS + PR_TRUE /* enableShortHeaders */ +#else + PR_FALSE /* enableShortHeaders */ +#endif }; /* @@ -102,23 +100,30 @@ static SSLVersionRange versions_defaults_datagram = { }; #define VERSIONS_DEFAULTS(variant) \ - (variant == ssl_variant_stream ? &versions_defaults_stream : \ - &versions_defaults_datagram) - -sslSessionIDLookupFunc ssl_sid_lookup; -sslSessionIDCacheFunc ssl_sid_cache; + (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; +sslSessionIDCacheFunc ssl_sid_cache; sslSessionIDUncacheFunc ssl_sid_uncache; static PRBool ssl_inited = PR_FALSE; 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; -FILE * ssl_keylog_iob; +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; +#endif + char lockStatus[] = "Locks are ENABLED. "; #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */ @@ -129,12 +134,66 @@ static const PRUint16 srtpCiphers[] = { 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); +static SECStatus ssl_MakeLocks(sslSocket *ss); +static void ssl_SetDefaultsFromEnvironment(void); +static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, + PRDescIdentity id); /************************************************************************/ @@ -205,116 +264,90 @@ ssl_DupSocket(sslSocket *os) SECStatus rv; ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant); - if (ss) { - ss->opt = os->opt; - ss->opt.useSocks = PR_FALSE; - ss->vrange = os->vrange; - - 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) */ - ss->allowedByPolicy = os->allowedByPolicy; - ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy; - ss->chosenPreference = os->chosenPreference; - 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.signatureAlgorithms, os->ssl3.signatureAlgorithms, - sizeof(ss->ssl3.signatureAlgorithms[0]) * - os->ssl3.signatureAlgorithmCount); - ss->ssl3.signatureAlgorithmCount = os->ssl3.signatureAlgorithmCount; - - ss->ssl3.dheWeakGroupEnabled = os->ssl3.dheWeakGroupEnabled; - ss->ssl3.numDHEGroups = os->ssl3.numDHEGroups; - if (os->ssl3.dheGroups) { - ss->ssl3.dheGroups = PORT_NewArray(SSLDHEGroupType, - os->ssl3.numDHEGroups); - if (!ss->ssl3.dheGroups) { + 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->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; - } - PORT_Memcpy(ss->ssl3.dheGroups, os->ssl3.dheGroups, - sizeof(SSLDHEGroupType) * os->ssl3.numDHEGroups); - } else { - ss->ssl3.dheGroups = NULL; + PR_APPEND_LINK(&sc->link, &ss->serverCerts); } - if (os->cipherSpecs) { - ss->cipherSpecs = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs); - if (ss->cipherSpecs) - PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs, - os->sizeCipherSpecs); - ss->sizeCipherSpecs = os->sizeCipherSpecs; - ss->preferredCipher = os->preferredCipher; - } else { - ss->cipherSpecs = NULL; /* produced lazily */ - ss->sizeCipherSpecs = 0; - ss->preferredCipher = NULL; + PR_INIT_CLIST(&ss->ephemeralKeyPairs); + 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); } - if (ss->opt.useSecurity) { - /* This int should be SSLKEAType, but CC on Irix complains, - * during the for loop. - */ - int i; - sslServerCerts * oc = os->serverCerts; - sslServerCerts * sc = ss->serverCerts; - - for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) { - if (oc->serverCert && oc->serverCertChain) { - sc->serverCert = CERT_DupCertificate(oc->serverCert); - sc->serverCertChain = CERT_DupCertList(oc->serverCertChain); - if (!sc->serverCertChain) - goto loser; - } else { - sc->serverCert = NULL; - sc->serverCertChain = NULL; - } - sc->serverKeyPair = oc->serverKeyPair ? - ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL; - if (oc->serverKeyPair && !sc->serverKeyPair) - goto loser; - sc->serverKeyBits = oc->serverKeyBits; - ss->certStatusArray[i] = !os->certStatusArray[i] ? NULL : - SECITEM_DupArray(NULL, os->certStatusArray[i]); - } - ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL : - ssl3_GetKeyPairRef(os->stepDownKeyPair); - ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL : - ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair); - ss->dheKeyPair = !os->dheKeyPair ? NULL : - ssl3_GetKeyPairRef(os->dheKeyPair); - ss->dheParams = os->dheParams; -/* - * 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->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; - - /* Create security data */ - rv = ssl_CopySecurityInfo(ss, os); - if (rv != SECSuccess) { - goto loser; - } + /* + * 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->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; + + /* Create security data */ + rv = ssl_CopySecurityInfo(ss, os); + if (rv != SECSuccess) { + goto loser; } } return ss; @@ -363,10 +396,7 @@ ssl_DestroyLocks(sslSocket *ss) static void ssl_DestroySocketContents(sslSocket *ss) { - /* "i" should be of type SSLKEAType, but CC on IRIX complains during - * the for loop. - */ - int i; + PRCList *cursor; /* Free up socket */ ssl_DestroySecurityInfo(&ss->sec); @@ -375,49 +405,22 @@ ssl_DestroySocketContents(sslSocket *ss) PORT_Free(ss->saveBuf.buf); PORT_Free(ss->pendingBuf.buf); - ssl_DestroyGather(&ss->gs); + ssl3_DestroyGather(&ss->gs); if (ss->peerID != NULL) PORT_Free(ss->peerID); if (ss->url != NULL) - PORT_Free((void *)ss->url); /* CONST */ - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - - /* Clean up server configuration */ - for (i=kt_null; i < kt_kea_size; i++) { - sslServerCerts * sc = ss->serverCerts + i; - if (sc->serverCert != NULL) - CERT_DestroyCertificate(sc->serverCert); - if (sc->serverCertChain != NULL) - CERT_DestroyCertificateList(sc->serverCertChain); - if (sc->serverKeyPair != NULL) - ssl3_FreeKeyPair(sc->serverKeyPair); - if (ss->certStatusArray[i] != NULL) { - SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE); - ss->certStatusArray[i] = NULL; - } - } - if (ss->stepDownKeyPair) { - ssl3_FreeKeyPair(ss->stepDownKeyPair); - ss->stepDownKeyPair = NULL; - } - if (ss->ephemeralECDHKeyPair) { - ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); - ss->ephemeralECDHKeyPair = NULL; - } - if (ss->dheKeyPair) { - ssl3_FreeKeyPair(ss->dheKeyPair); - ss->dheKeyPair = 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); } + ssl_FreeEphemeralKeyPairs(ss); SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE); - if (ss->xtnData.sniNameArr) { - PORT_Free(ss->xtnData.sniNameArr); - ss->xtnData.sniNameArr = NULL; - } + ssl3_FreeSniNameArray(&ss->xtnData); } /* @@ -426,11 +429,11 @@ ssl_DestroySocketContents(sslSocket *ss) void ssl_FreeSocket(sslSocket *ss) { -/* Get every lock you can imagine! -** Caller already holds these: -** SSL_LOCK_READER(ss); -** SSL_LOCK_WRITER(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); @@ -461,15 +464,15 @@ ssl_FreeSocket(sslSocket *ss) SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled) { - PRFileDesc * osfd = ss->fd->lower; - SECStatus rv = SECFailure; + PRFileDesc *osfd = ss->fd->lower; + SECStatus rv = SECFailure; PRSocketOptionData opt; - opt.option = PR_SockOpt_NoDelay; + opt.option = PR_SockOpt_NoDelay; opt.value.no_delay = (PRBool)!enabled; if (osfd->methods->setsocketoption) { - rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt); + rv = (SECStatus)osfd->methods->setsocketoption(osfd, &opt); } else { PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0); } @@ -487,7 +490,7 @@ ssl_ChooseOps(sslSocket *ss) static SECStatus PrepareSocket(sslSocket *ss) { - SECStatus rv = SECSuccess; + SECStatus rv = SECSuccess; ssl_ChooseOps(ss); return rv; @@ -499,35 +502,8 @@ SSL_Enable(PRFileDesc *fd, int which, PRBool on) return SSL_OptionSet(fd, which, on); } -#ifndef NO_PKCS11_BYPASS -static const PRCallOnceType pristineCallOnce; -static PRCallOnceType setupBypassOnce; - -static SECStatus SSL_BypassShutdown(void* appData, void* nssData) -{ - /* unload freeBL shared library from memory */ - BL_Unload(); - setupBypassOnce = pristineCallOnce; - return SECSuccess; -} - -static PRStatus SSL_BypassRegisterShutdown(void) -{ - SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL); - PORT_Assert(SECSuccess == rv); - return SECSuccess == rv ? PR_SUCCESS : PR_FAILURE; -} -#endif - -static PRStatus SSL_BypassSetup(void) -{ -#ifdef NO_PKCS11_BYPASS - /* Guarantee binary compatibility */ - return PR_SUCCESS; -#else - return PR_CallOnce(&setupBypassOnce, &SSL_BypassRegisterShutdown); -#endif -} +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". @@ -535,7 +511,14 @@ static PRStatus SSL_BypassSetup(void) static void ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) { - if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { + if (on) { + /* 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 (on) { vrange->min = SSL_LIBRARY_VERSION_TLS_1_0; vrange->max = SSL_LIBRARY_VERSION_TLS_1_0; @@ -565,7 +548,14 @@ ssl_EnableTLS(SSLVersionRange *vrange, PRBool on) static void ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on) { - if (SSL3_ALL_VERSIONS_DISABLED(vrange)) { + if (on) { + /* 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 (on) { vrange->min = SSL_LIBRARY_VERSION_3_0; vrange->max = SSL_LIBRARY_VERSION_3_0; @@ -573,13 +563,13 @@ ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on) return; } - if (on) { + if (on) { /* 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 { + } 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); @@ -595,8 +585,8 @@ SECStatus SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on) { sslSocket *ss = ssl_FindSocket(fd); - SECStatus rv = SECSuccess; - PRBool holdingLocks; + SECStatus rv = SECSuccess; + PRBool holdingLocks; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd)); @@ -608,231 +598,192 @@ SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on) ssl_GetSSL3HandshakeLock(ss); switch (which) { - case SSL_SOCKS: - ss->opt.useSocks = PR_FALSE; - rv = PrepareSocket(ss); - if (on) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } - break; - - case SSL_SECURITY: - ss->opt.useSecurity = on; - rv = PrepareSocket(ss); - break; - - case SSL_REQUEST_CERTIFICATE: - ss->opt.requestCertificate = on; - break; + case SSL_SOCKS: + ss->opt.useSocks = PR_FALSE; + rv = PrepareSocket(ss); + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + } + break; - case SSL_REQUIRE_CERTIFICATE: - ss->opt.requireCertificate = on; - break; + case SSL_SECURITY: + ss->opt.useSecurity = on; + rv = PrepareSocket(ss); + break; - case SSL_HANDSHAKE_AS_CLIENT: - if ( ss->opt.handshakeAsServer && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + case SSL_REQUEST_CERTIFICATE: + ss->opt.requestCertificate = on; break; - } - ss->opt.handshakeAsClient = on; - break; - case SSL_HANDSHAKE_AS_SERVER: - if ( ss->opt.handshakeAsClient && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + case SSL_REQUIRE_CERTIFICATE: + ss->opt.requireCertificate = on; break; - } - ss->opt.handshakeAsServer = on; - break; - case SSL_ENABLE_TLS: - if (IS_DTLS(ss)) { - if (on) { + case SSL_HANDSHAKE_AS_CLIENT: + if (ss->opt.handshakeAsServer && on) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; + break; } + ss->opt.handshakeAsClient = on; break; - } - ssl_EnableTLS(&ss->vrange, on); - ss->preferredCipher = NULL; - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - break; - case SSL_ENABLE_SSL3: - if (IS_DTLS(ss)) { - if (on) { + case SSL_HANDSHAKE_AS_SERVER: + if (ss->opt.handshakeAsClient && on) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; + break; } + ss->opt.handshakeAsServer = on; break; - } - ssl_EnableSSL3(&ss->vrange, on); - ss->preferredCipher = NULL; - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - break; - case SSL_ENABLE_SSL2: - if (IS_DTLS(ss)) { + case SSL_ENABLE_TLS: + if (IS_DTLS(ss)) { + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; /* not allowed */ + } + break; + } + ssl_EnableTLS(&ss->vrange, on); + break; + + case SSL_ENABLE_SSL3: + if (IS_DTLS(ss)) { + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; /* not allowed */ + } + break; + } + ssl_EnableSSL3(&ss->vrange, on); + 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 (on) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; } break; - } - ss->opt.enableSSL2 = on; - if (on) { - ss->opt.v2CompatibleHello = on; - } - ss->preferredCipher = NULL; - if (ss->cipherSpecs) { - PORT_Free(ss->cipherSpecs); - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; - } - break; - case SSL_NO_CACHE: - ss->opt.noCache = on; - break; - - case SSL_ENABLE_FDX: - if (on && ss->opt.noLocks) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } - ss->opt.fdx = on; - break; + case SSL_NO_CACHE: + ss->opt.noCache = on; + break; - case SSL_V2_COMPATIBLE_HELLO: - if (IS_DTLS(ss)) { - if (on) { + case SSL_ENABLE_FDX: + if (on && ss->opt.noLocks) { PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; /* not allowed */ + rv = SECFailure; } + ss->opt.fdx = on; break; - } - ss->opt.v2CompatibleHello = on; - if (!on) { - ss->opt.enableSSL2 = on; - } - break; - case SSL_ROLLBACK_DETECTION: - ss->opt.detectRollBack = on; - break; + case SSL_ROLLBACK_DETECTION: + ss->opt.detectRollBack = on; + break; - case SSL_NO_STEP_DOWN: - ss->opt.noStepDown = on; - if (on) - SSL_DisableExportCipherSuites(fd); - break; + case SSL_NO_STEP_DOWN: + break; - case SSL_BYPASS_PKCS11: - if (ss->handshakeBegun) { - PORT_SetError(PR_INVALID_STATE_ERROR); - rv = SECFailure; - } else { - if (PR_FALSE != on) { - if (PR_SUCCESS == SSL_BypassSetup() ) { -#ifdef NO_PKCS11_BYPASS - ss->opt.bypassPKCS11 = PR_FALSE; -#else - ss->opt.bypassPKCS11 = on; -#endif - } else { - rv = SECFailure; + case SSL_BYPASS_PKCS11: + break; + + case SSL_NO_LOCKS: + if (on && ss->opt.fdx) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + } + if (on && ssl_force_locks) + on = PR_FALSE; /* silent override */ + ss->opt.noLocks = on; + if (on) { + locksEverDisabled = PR_TRUE; + strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); + } else if (!holdingLocks) { + rv = ssl_MakeLocks(ss); + if (rv != SECSuccess) { + ss->opt.noLocks = PR_TRUE; } - } else { - ss->opt.bypassPKCS11 = PR_FALSE; } - } - break; + break; - case SSL_NO_LOCKS: - if (on && ss->opt.fdx) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; - } - if (on && ssl_force_locks) - on = PR_FALSE; /* silent override */ - ss->opt.noLocks = on; - if (on) { - locksEverDisabled = PR_TRUE; - strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); - } else if (!holdingLocks) { - rv = ssl_MakeLocks(ss); - if (rv != SECSuccess) { - ss->opt.noLocks = PR_TRUE; + case SSL_ENABLE_SESSION_TICKETS: + ss->opt.enableSessionTickets = on; + break; + + case SSL_ENABLE_DEFLATE: + ss->opt.enableDeflate = on; + break; + + case SSL_ENABLE_RENEGOTIATION: + if (IS_DTLS(ss) && on != SSL_RENEGOTIATE_NEVER) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; + break; } - } - break; + ss->opt.enableRenegotiation = on; + break; - case SSL_ENABLE_SESSION_TICKETS: - ss->opt.enableSessionTickets = on; - break; + case SSL_REQUIRE_SAFE_NEGOTIATION: + ss->opt.requireSafeNegotiation = on; + break; - case SSL_ENABLE_DEFLATE: - ss->opt.enableDeflate = on; - break; + case SSL_ENABLE_FALSE_START: + ss->opt.enableFalseStart = on; + break; - case SSL_ENABLE_RENEGOTIATION: - ss->opt.enableRenegotiation = on; - break; + case SSL_CBC_RANDOM_IV: + ss->opt.cbcRandomIV = on; + break; - case SSL_REQUIRE_SAFE_NEGOTIATION: - ss->opt.requireSafeNegotiation = on; - break; + case SSL_ENABLE_OCSP_STAPLING: + ss->opt.enableOCSPStapling = on; + break; - case SSL_ENABLE_FALSE_START: - ss->opt.enableFalseStart = on; - break; + case SSL_ENABLE_NPN: + break; - case SSL_CBC_RANDOM_IV: - ss->opt.cbcRandomIV = on; - break; + case SSL_ENABLE_ALPN: + ss->opt.enableALPN = on; + break; - case SSL_ENABLE_OCSP_STAPLING: - ss->opt.enableOCSPStapling = on; - break; + case SSL_REUSE_SERVER_ECDHE_KEY: + ss->opt.reuseServerECDHEKey = on; + break; - case SSL_ENABLE_NPN: - ss->opt.enableNPN = on; - break; + case SSL_ENABLE_FALLBACK_SCSV: + ss->opt.enableFallbackSCSV = on; + break; - case SSL_ENABLE_ALPN: - ss->opt.enableALPN = on; - break; + case SSL_ENABLE_SERVER_DHE: + ss->opt.enableServerDhe = on; + break; - case SSL_REUSE_SERVER_ECDHE_KEY: - ss->opt.reuseServerECDHEKey = on; - break; + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + ss->opt.enableExtendedMS = on; + break; - case SSL_ENABLE_FALLBACK_SCSV: - ss->opt.enableFallbackSCSV = on; - break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + ss->opt.enableSignedCertTimestamps = on; + break; - case SSL_ENABLE_SERVER_DHE: - ss->opt.enableServerDhe = on; - break; + case SSL_REQUIRE_DH_NAMED_GROUPS: + ss->opt.requireDHENamedGroups = on; + break; - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - ss->opt.enableExtendedMS = on; - break; + case SSL_ENABLE_0RTT_DATA: + ss->opt.enable0RttData = on; + break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } /* We can't use the macros for releasing the locks here, @@ -852,8 +803,8 @@ SECStatus SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) { sslSocket *ss = ssl_FindSocket(fd); - SECStatus rv = SECSuccess; - PRBool on = PR_FALSE; + SECStatus rv = SECSuccess; + PRBool on = PR_FALSE; if (!pOn) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -869,49 +820,103 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) ssl_GetSSL3HandshakeLock(ss); switch (which) { - case SSL_SOCKS: on = PR_FALSE; break; - case SSL_SECURITY: on = ss->opt.useSecurity; break; - case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break; - case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break; - case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient; break; - case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer; break; - case SSL_ENABLE_TLS: - on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0; - break; - case SSL_ENABLE_SSL3: - on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0; - break; - case SSL_ENABLE_SSL2: on = ss->opt.enableSSL2; break; - case SSL_NO_CACHE: on = ss->opt.noCache; break; - case SSL_ENABLE_FDX: on = ss->opt.fdx; break; - case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello; break; - case SSL_ROLLBACK_DETECTION: on = ss->opt.detectRollBack; break; - case SSL_NO_STEP_DOWN: on = ss->opt.noStepDown; break; - case SSL_BYPASS_PKCS11: on = ss->opt.bypassPKCS11; break; - case SSL_NO_LOCKS: on = ss->opt.noLocks; break; - case SSL_ENABLE_SESSION_TICKETS: - on = ss->opt.enableSessionTickets; - break; - case SSL_ENABLE_DEFLATE: on = ss->opt.enableDeflate; break; - case SSL_ENABLE_RENEGOTIATION: - on = ss->opt.enableRenegotiation; break; - case SSL_REQUIRE_SAFE_NEGOTIATION: - on = ss->opt.requireSafeNegotiation; break; - case SSL_ENABLE_FALSE_START: on = ss->opt.enableFalseStart; break; - case SSL_CBC_RANDOM_IV: on = ss->opt.cbcRandomIV; break; - case SSL_ENABLE_OCSP_STAPLING: on = ss->opt.enableOCSPStapling; break; - case SSL_ENABLE_NPN: on = ss->opt.enableNPN; break; - case SSL_ENABLE_ALPN: on = ss->opt.enableALPN; break; - case SSL_REUSE_SERVER_ECDHE_KEY: - on = ss->opt.reuseServerECDHEKey; break; - case SSL_ENABLE_FALLBACK_SCSV: on = ss->opt.enableFallbackSCSV; break; - case SSL_ENABLE_SERVER_DHE: on = ss->opt.enableServerDhe; break; - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - on = ss->opt.enableExtendedMS; break; - - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + case SSL_SOCKS: + on = PR_FALSE; + break; + case SSL_SECURITY: + on = ss->opt.useSecurity; + break; + case SSL_REQUEST_CERTIFICATE: + on = ss->opt.requestCertificate; + break; + case SSL_REQUIRE_CERTIFICATE: + on = ss->opt.requireCertificate; + break; + case SSL_HANDSHAKE_AS_CLIENT: + on = ss->opt.handshakeAsClient; + break; + case SSL_HANDSHAKE_AS_SERVER: + on = ss->opt.handshakeAsServer; + break; + case SSL_ENABLE_TLS: + on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0; + break; + case SSL_ENABLE_SSL3: + on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0; + break; + case SSL_ENABLE_SSL2: + case SSL_V2_COMPATIBLE_HELLO: + on = PR_FALSE; + break; + case SSL_NO_CACHE: + on = ss->opt.noCache; + break; + case SSL_ENABLE_FDX: + on = ss->opt.fdx; + break; + case SSL_ROLLBACK_DETECTION: + on = ss->opt.detectRollBack; + break; + case SSL_NO_STEP_DOWN: + on = PR_FALSE; + break; + case SSL_BYPASS_PKCS11: + on = PR_FALSE; + break; + case SSL_NO_LOCKS: + on = ss->opt.noLocks; + break; + case SSL_ENABLE_SESSION_TICKETS: + on = ss->opt.enableSessionTickets; + break; + case SSL_ENABLE_DEFLATE: + on = ss->opt.enableDeflate; + break; + case SSL_ENABLE_RENEGOTIATION: + on = ss->opt.enableRenegotiation; + break; + case SSL_REQUIRE_SAFE_NEGOTIATION: + on = ss->opt.requireSafeNegotiation; + break; + case SSL_ENABLE_FALSE_START: + on = ss->opt.enableFalseStart; + break; + case SSL_CBC_RANDOM_IV: + on = ss->opt.cbcRandomIV; + break; + case SSL_ENABLE_OCSP_STAPLING: + on = ss->opt.enableOCSPStapling; + break; + case SSL_ENABLE_NPN: + on = ss->opt.enableNPN; + break; + case SSL_ENABLE_ALPN: + on = ss->opt.enableALPN; + break; + case SSL_REUSE_SERVER_ECDHE_KEY: + on = ss->opt.reuseServerECDHEKey; + break; + case SSL_ENABLE_FALLBACK_SCSV: + on = ss->opt.enableFallbackSCSV; + break; + case SSL_ENABLE_SERVER_DHE: + on = ss->opt.enableServerDhe; + break; + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + on = ss->opt.enableExtendedMS; + break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + on = ss->opt.enableSignedCertTimestamps; + break; + case SSL_REQUIRE_DH_NAMED_GROUPS: + on = ss->opt.requireDHENamedGroups; + break; + case SSL_ENABLE_0RTT_DATA: + on = ss->opt.enable0RttData; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } ssl_ReleaseSSL3HandshakeLock(ss); @@ -924,8 +929,8 @@ SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn) SECStatus SSL_OptionGetDefault(PRInt32 which, PRBool *pOn) { - SECStatus rv = SECSuccess; - PRBool on = PR_FALSE; + SECStatus rv = SECSuccess; + PRBool on = PR_FALSE; if (!pOn) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -935,58 +940,100 @@ SSL_OptionGetDefault(PRInt32 which, PRBool *pOn) ssl_SetDefaultsFromEnvironment(); switch (which) { - case SSL_SOCKS: on = PR_FALSE; break; - case SSL_SECURITY: on = ssl_defaults.useSecurity; break; - case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break; - case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break; - case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient; break; - case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer; break; - case SSL_ENABLE_TLS: - on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0; - break; - case SSL_ENABLE_SSL3: - on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0; - break; - case SSL_ENABLE_SSL2: on = ssl_defaults.enableSSL2; break; - case SSL_NO_CACHE: on = ssl_defaults.noCache; break; - case SSL_ENABLE_FDX: on = ssl_defaults.fdx; break; - case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello; break; - case SSL_ROLLBACK_DETECTION: on = ssl_defaults.detectRollBack; break; - case SSL_NO_STEP_DOWN: on = ssl_defaults.noStepDown; break; - case SSL_BYPASS_PKCS11: on = ssl_defaults.bypassPKCS11; break; - case SSL_NO_LOCKS: on = ssl_defaults.noLocks; break; - case SSL_ENABLE_SESSION_TICKETS: - on = ssl_defaults.enableSessionTickets; - break; - case SSL_ENABLE_DEFLATE: on = ssl_defaults.enableDeflate; break; - case SSL_ENABLE_RENEGOTIATION: - on = ssl_defaults.enableRenegotiation; break; - case SSL_REQUIRE_SAFE_NEGOTIATION: - on = ssl_defaults.requireSafeNegotiation; - break; - case SSL_ENABLE_FALSE_START: on = ssl_defaults.enableFalseStart; break; - case SSL_CBC_RANDOM_IV: on = ssl_defaults.cbcRandomIV; break; - case SSL_ENABLE_OCSP_STAPLING: - on = ssl_defaults.enableOCSPStapling; - break; - case SSL_ENABLE_NPN: on = ssl_defaults.enableNPN; break; - case SSL_ENABLE_ALPN: on = ssl_defaults.enableALPN; break; - case SSL_REUSE_SERVER_ECDHE_KEY: - on = ssl_defaults.reuseServerECDHEKey; - break; - case SSL_ENABLE_FALLBACK_SCSV: - on = ssl_defaults.enableFallbackSCSV; - break; - case SSL_ENABLE_SERVER_DHE: - on = ssl_defaults.enableServerDhe; - break; - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - on = ssl_defaults.enableExtendedMS; - break; - - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - rv = SECFailure; + case SSL_SOCKS: + on = PR_FALSE; + break; + case SSL_SECURITY: + on = ssl_defaults.useSecurity; + break; + case SSL_REQUEST_CERTIFICATE: + on = ssl_defaults.requestCertificate; + break; + case SSL_REQUIRE_CERTIFICATE: + on = ssl_defaults.requireCertificate; + break; + case SSL_HANDSHAKE_AS_CLIENT: + on = ssl_defaults.handshakeAsClient; + break; + case SSL_HANDSHAKE_AS_SERVER: + on = ssl_defaults.handshakeAsServer; + break; + case SSL_ENABLE_TLS: + on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0; + break; + case SSL_ENABLE_SSL3: + on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0; + break; + case SSL_ENABLE_SSL2: + case SSL_V2_COMPATIBLE_HELLO: + on = PR_FALSE; + break; + case SSL_NO_CACHE: + on = ssl_defaults.noCache; + break; + case SSL_ENABLE_FDX: + on = ssl_defaults.fdx; + break; + case SSL_ROLLBACK_DETECTION: + on = ssl_defaults.detectRollBack; + break; + case SSL_NO_STEP_DOWN: + on = PR_FALSE; + break; + case SSL_BYPASS_PKCS11: + on = PR_FALSE; + break; + case SSL_NO_LOCKS: + on = ssl_defaults.noLocks; + break; + case SSL_ENABLE_SESSION_TICKETS: + on = ssl_defaults.enableSessionTickets; + break; + case SSL_ENABLE_DEFLATE: + on = ssl_defaults.enableDeflate; + break; + case SSL_ENABLE_RENEGOTIATION: + on = ssl_defaults.enableRenegotiation; + break; + case SSL_REQUIRE_SAFE_NEGOTIATION: + on = ssl_defaults.requireSafeNegotiation; + break; + case SSL_ENABLE_FALSE_START: + on = ssl_defaults.enableFalseStart; + break; + case SSL_CBC_RANDOM_IV: + on = ssl_defaults.cbcRandomIV; + break; + case SSL_ENABLE_OCSP_STAPLING: + on = ssl_defaults.enableOCSPStapling; + break; + case SSL_ENABLE_NPN: + on = ssl_defaults.enableNPN; + break; + case SSL_ENABLE_ALPN: + on = ssl_defaults.enableALPN; + break; + case SSL_REUSE_SERVER_ECDHE_KEY: + on = ssl_defaults.reuseServerECDHEKey; + break; + case SSL_ENABLE_FALLBACK_SCSV: + on = ssl_defaults.enableFallbackSCSV; + break; + case SSL_ENABLE_SERVER_DHE: + on = ssl_defaults.enableServerDhe; + break; + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + on = ssl_defaults.enableExtendedMS; + break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + on = ssl_defaults.enableSignedCertTimestamps; + break; + case SSL_ENABLE_0RTT_DATA: + on = ssl_defaults.enable0RttData; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + rv = SECFailure; } *pOn = on; @@ -1012,171 +1059,160 @@ SSL_OptionSetDefault(PRInt32 which, PRBool on) ssl_SetDefaultsFromEnvironment(); switch (which) { - case SSL_SOCKS: - ssl_defaults.useSocks = PR_FALSE; - if (on) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - break; + case SSL_SOCKS: + ssl_defaults.useSocks = PR_FALSE; + if (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + break; - case SSL_SECURITY: - ssl_defaults.useSecurity = on; - break; + case SSL_SECURITY: + ssl_defaults.useSecurity = on; + break; - case SSL_REQUEST_CERTIFICATE: - ssl_defaults.requestCertificate = on; - break; + case SSL_REQUEST_CERTIFICATE: + ssl_defaults.requestCertificate = on; + break; - case SSL_REQUIRE_CERTIFICATE: - ssl_defaults.requireCertificate = on; - break; + case SSL_REQUIRE_CERTIFICATE: + ssl_defaults.requireCertificate = on; + break; - case SSL_HANDSHAKE_AS_CLIENT: - if ( ssl_defaults.handshakeAsServer && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - ssl_defaults.handshakeAsClient = on; - break; + case SSL_HANDSHAKE_AS_CLIENT: + if (ssl_defaults.handshakeAsServer && on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + ssl_defaults.handshakeAsClient = on; + break; - case SSL_HANDSHAKE_AS_SERVER: - if ( ssl_defaults.handshakeAsClient && on ) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - ssl_defaults.handshakeAsServer = on; - break; + case SSL_HANDSHAKE_AS_SERVER: + if (ssl_defaults.handshakeAsClient && on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + ssl_defaults.handshakeAsServer = on; + break; - case SSL_ENABLE_TLS: - ssl_EnableTLS(&versions_defaults_stream, on); - break; + case SSL_ENABLE_TLS: + ssl_EnableTLS(&versions_defaults_stream, on); + break; - case SSL_ENABLE_SSL3: - ssl_EnableSSL3(&versions_defaults_stream, on); - break; + case SSL_ENABLE_SSL3: + ssl_EnableSSL3(&versions_defaults_stream, on); + break; - case SSL_ENABLE_SSL2: - ssl_defaults.enableSSL2 = on; - if (on) { - ssl_defaults.v2CompatibleHello = on; - } - 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 (on) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + break; - case SSL_NO_CACHE: - ssl_defaults.noCache = on; - break; + case SSL_NO_CACHE: + ssl_defaults.noCache = on; + break; - case SSL_ENABLE_FDX: - if (on && ssl_defaults.noLocks) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - ssl_defaults.fdx = on; - break; + case SSL_ENABLE_FDX: + if (on && ssl_defaults.noLocks) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + ssl_defaults.fdx = on; + break; - case SSL_V2_COMPATIBLE_HELLO: - ssl_defaults.v2CompatibleHello = on; - if (!on) { - ssl_defaults.enableSSL2 = on; - } - break; - - case SSL_ROLLBACK_DETECTION: - ssl_defaults.detectRollBack = on; - break; - - case SSL_NO_STEP_DOWN: - ssl_defaults.noStepDown = on; - if (on) - SSL_DisableDefaultExportCipherSuites(); - break; - - case SSL_BYPASS_PKCS11: - if (PR_FALSE != on) { - if (PR_SUCCESS == SSL_BypassSetup()) { -#ifdef NO_PKCS11_BYPASS - ssl_defaults.bypassPKCS11 = PR_FALSE; -#else - ssl_defaults.bypassPKCS11 = on; -#endif - } else { + case SSL_ROLLBACK_DETECTION: + ssl_defaults.detectRollBack = on; + break; + + case SSL_NO_STEP_DOWN: + break; + + case SSL_BYPASS_PKCS11: + break; + + case SSL_NO_LOCKS: + if (on && ssl_defaults.fdx) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - } else { - ssl_defaults.bypassPKCS11 = PR_FALSE; - } - break; + if (on && ssl_force_locks) + on = PR_FALSE; /* silent override */ + ssl_defaults.noLocks = on; + if (on) { + locksEverDisabled = PR_TRUE; + strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); + } + break; - case SSL_NO_LOCKS: - if (on && ssl_defaults.fdx) { - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; - } - if (on && ssl_force_locks) - on = PR_FALSE; /* silent override */ - ssl_defaults.noLocks = on; - if (on) { - locksEverDisabled = PR_TRUE; - strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED."); - } - break; + case SSL_ENABLE_SESSION_TICKETS: + ssl_defaults.enableSessionTickets = on; + break; - case SSL_ENABLE_SESSION_TICKETS: - ssl_defaults.enableSessionTickets = on; - break; + case SSL_ENABLE_DEFLATE: + ssl_defaults.enableDeflate = on; + break; - case SSL_ENABLE_DEFLATE: - ssl_defaults.enableDeflate = on; - break; + case SSL_ENABLE_RENEGOTIATION: + ssl_defaults.enableRenegotiation = on; + break; - case SSL_ENABLE_RENEGOTIATION: - ssl_defaults.enableRenegotiation = on; - break; + case SSL_REQUIRE_SAFE_NEGOTIATION: + ssl_defaults.requireSafeNegotiation = on; + break; - case SSL_REQUIRE_SAFE_NEGOTIATION: - ssl_defaults.requireSafeNegotiation = on; - break; + case SSL_ENABLE_FALSE_START: + ssl_defaults.enableFalseStart = on; + break; - case SSL_ENABLE_FALSE_START: - ssl_defaults.enableFalseStart = on; - break; + case SSL_CBC_RANDOM_IV: + ssl_defaults.cbcRandomIV = on; + break; - case SSL_CBC_RANDOM_IV: - ssl_defaults.cbcRandomIV = on; - break; + case SSL_ENABLE_OCSP_STAPLING: + ssl_defaults.enableOCSPStapling = on; + break; - case SSL_ENABLE_OCSP_STAPLING: - ssl_defaults.enableOCSPStapling = on; - break; + case SSL_ENABLE_NPN: + break; - case SSL_ENABLE_NPN: - ssl_defaults.enableNPN = on; - break; + case SSL_ENABLE_ALPN: + ssl_defaults.enableALPN = on; + break; - case SSL_ENABLE_ALPN: - ssl_defaults.enableALPN = on; - break; + case SSL_REUSE_SERVER_ECDHE_KEY: + ssl_defaults.reuseServerECDHEKey = on; + break; - case SSL_REUSE_SERVER_ECDHE_KEY: - ssl_defaults.reuseServerECDHEKey = on; - break; + case SSL_ENABLE_FALLBACK_SCSV: + ssl_defaults.enableFallbackSCSV = on; + break; - case SSL_ENABLE_FALLBACK_SCSV: - ssl_defaults.enableFallbackSCSV = on; - break; + case SSL_ENABLE_SERVER_DHE: + ssl_defaults.enableServerDhe = on; + break; + + case SSL_ENABLE_EXTENDED_MASTER_SECRET: + ssl_defaults.enableExtendedMS = on; + break; - case SSL_ENABLE_SERVER_DHE: - ssl_defaults.enableServerDhe = on; - break; + case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS: + ssl_defaults.enableSignedCertTimestamps = on; + break; - case SSL_ENABLE_EXTENDED_MASTER_SECRET: - ssl_defaults.enableExtendedMS = on; - break; + case SSL_ENABLE_0RTT_DATA: + ssl_defaults.enable0RttData = on; + break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } return SECSuccess; } @@ -1186,12 +1222,12 @@ 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; + 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; } } @@ -1202,36 +1238,33 @@ ssl_IsRemovedCipherSuite(PRInt32 suite) SECStatus SSL_SetPolicy(long which, int policy) { - if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) { - /* one of the two old FIPS ciphers */ - if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) - which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA; - else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA) - which = SSL_RSA_FIPS_WITH_DES_CBC_SHA; - } if (ssl_IsRemovedCipherSuite(which)) return SECSuccess; return SSL_CipherPolicySet(which, policy); } SECStatus -SSL_CipherPolicySet(PRInt32 which, PRInt32 policy) +ssl_CipherPolicySet(PRInt32 which, PRInt32 policy) { - SECStatus rv = ssl_Init(); - - if (rv != SECSuccess) { - return rv; - } + SECStatus rv = SECSuccess; if (ssl_IsRemovedCipherSuite(which)) { rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { - rv = ssl2_SetPolicy(which, policy); } 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; + } + return ssl_CipherPolicySet(which, policy); +} SECStatus SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy) @@ -1245,8 +1278,6 @@ SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy) if (ssl_IsRemovedCipherSuite(which)) { *oPolicy = SSL_NOT_ALLOWED; rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { - rv = ssl2_GetPolicy(which, oPolicy); } else { rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy); } @@ -1261,19 +1292,20 @@ SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy) SECStatus SSL_EnableCipher(long which, PRBool enabled) { - if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) { - /* one of the two old FIPS ciphers */ - if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) - which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA; - else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA) - which = SSL_RSA_FIPS_WITH_DES_CBC_SHA; - } 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(); @@ -1281,25 +1313,13 @@ SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled) if (rv != SECSuccess) { return rv; } - - if (ssl_IsRemovedCipherSuite(which)) - return SECSuccess; - if (enabled && ssl_defaults.noStepDown && SSL_IsExportCipherSuite(which)) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; - } - if (SSL_IS_SSL2_CIPHER(which)) { - rv = ssl2_CipherPrefSetDefault(which, enabled); - } else { - rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled); - } - return rv; + return ssl_CipherPrefSetDefault(which, enabled); } SECStatus SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) { - SECStatus rv; + SECStatus rv; if (!enabled) { PORT_SetError(SEC_ERROR_INVALID_ARGS); @@ -1308,8 +1328,6 @@ SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) if (ssl_IsRemovedCipherSuite(which)) { *enabled = PR_FALSE; rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { - rv = ssl2_CipherPrefGetDefault(which, enabled); } else { rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled); } @@ -1319,7 +1337,6 @@ SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled) SECStatus SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled) { - SECStatus rv; sslSocket *ss = ssl_FindSocket(fd); if (!ss) { @@ -1328,22 +1345,13 @@ SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled) } if (ssl_IsRemovedCipherSuite(which)) return SECSuccess; - if (enabled && ss->opt.noStepDown && SSL_IsExportCipherSuite(which)) { - PORT_SetError(SEC_ERROR_INVALID_ALGORITHM); - return SECFailure; - } - if (SSL_IS_SSL2_CIPHER(which)) { - rv = ssl2_CipherPrefSet(ss, which, enabled); - } else { - rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled); - } - return rv; + return ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled); } SECStatus SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled) { - SECStatus rv; + SECStatus rv; sslSocket *ss = ssl_FindSocket(fd); if (!enabled) { @@ -1358,8 +1366,6 @@ SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled) if (ssl_IsRemovedCipherSuite(which)) { *enabled = PR_FALSE; rv = SECSuccess; - } else if (SSL_IS_SSL2_CIPHER(which)) { - rv = ssl2_CipherPrefGet(ss, which, enabled); } else { rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled); } @@ -1369,8 +1375,16 @@ SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled) SECStatus NSS_SetDomesticPolicy(void) { - SECStatus status = SECSuccess; + 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 bee loaded */ + } for (cipher = SSL_ImplementedCiphers; *cipher != 0; ++cipher) { status = SSL_SetPolicy(*cipher, SSL_ALLOWED); @@ -1393,13 +1407,54 @@ NSS_SetFrancePolicy(void) } SECStatus -SSL_DHEGroupPrefSet(PRFileDesc *fd, - SSLDHEGroupType *groups, +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; - - if ((num_groups && !groups) || (!num_groups && groups)) { + 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; } @@ -1410,25 +1465,73 @@ SSL_DHEGroupPrefSet(PRFileDesc *fd, return SECFailure; } - if (ss->ssl3.dheGroups) { - PORT_Free(ss->ssl3.dheGroups); - ss->ssl3.dheGroups = NULL; - ss->ssl3.numDHEGroups = 0; + 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; } - if (groups) { - ss->ssl3.dheGroups = PORT_NewArray(SSLDHEGroupType, num_groups); - if (!ss->ssl3.dheGroups) { - PORT_SetError(SEC_ERROR_NO_MEMORY); - return SECFailure; + 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; + } } - PORT_Memcpy(ss->ssl3.dheGroups, groups, - sizeof(SSLDHEGroupType) * num_groups); + if (!duplicate) { + enabled[k++] = groupDef; + } + } + for (i = 0; i < k; ++i) { + ss->namedGroupPreferences[i] = enabled[i]; } + return SECSuccess; } - PRCallOnceType gWeakDHParamsRegisterOnce; int gWeakDHParamsRegisterError; @@ -1438,6 +1541,7 @@ int gWeakDHParamsError; * 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) @@ -1447,7 +1551,7 @@ ssl3_CreateWeakDHParams(void) PORT_Assert(!gWeakDHParams && !gWeakParamsPQG); - rv = PK11_PQG_ParamGenV2(1024, 160, 64 /*maximum seed that will work*/, + rv = PK11_PQG_ParamGenV2(WEAK_DHE_SIZE, 160, 64 /*maximum seed that will work*/, &gWeakParamsPQG, &vfy); if (rv != SECSuccess) { gWeakDHParamsError = PORT_GetError(); @@ -1457,7 +1561,7 @@ ssl3_CreateWeakDHParams(void) rv = PK11_PQG_VerifyParams(gWeakParamsPQG, vfy, &passed); if (rv != SECSuccess || passed != SECSuccess) { SSL_DBG(("%d: PK11_PQG_VerifyParams failed in ssl3_CreateWeakDHParams", - SSL_GETPID())); + SSL_GETPID())); gWeakDHParamsError = PORT_GetError(); return PR_FAILURE; } @@ -1468,6 +1572,7 @@ ssl3_CreateWeakDHParams(void) 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; @@ -1536,69 +1641,163 @@ SSL_EnableWeakDHEPrimeGroup(PRFileDesc *fd, PRBool enabled) #include "dhe-param.c" -static const SSLDHEGroupType ssl_default_dhe_groups[] = { - ssl_ff_dhe_2048_group -}; - -/* Keep this array synchronized with the index definitions in SSLDHEGroupType */ -static const ssl3DHParams *all_ssl3DHParams[] = { - NULL, /* ssl_dhe_group_none */ - &ff_dhe_2048, - &ff_dhe_3072, - &ff_dhe_4096, - &ff_dhe_6144, - &ff_dhe_8192, -}; +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; +} -static SSLDHEGroupType -selectDHEGroup(sslSocket *ss, const SSLDHEGroupType *groups, PRUint16 num_groups) +/* This validates dh_Ys against the group prime. */ +PRBool +ssl_IsValidDHEShare(const SECItem *dh_p, const SECItem *dh_Ys) { - if (!groups || !num_groups) - return ssl_dhe_group_none; + unsigned int size_p = SECKEY_BigIntegerBitLength(dh_p); + unsigned int size_y = SECKEY_BigIntegerBitLength(dh_Ys); + unsigned int commonPart; + int cmp; - /* We don't have automatic group parameter selection yet - * (potentially) based on socket parameters, e.g. key sizes. - * For now, we return the first available group from the allowed list. */ - return groups[0]; + 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; } -/* Ensure DH parameters have been selected */ +/* 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 -ssl3_SelectDHParams(sslSocket *ss) +ssl_ValidateDHENamedGroup(sslSocket *ss, + const SECItem *dh_p, + const SECItem *dh_g, + const sslNamedGroupDef **groupDef, + const ssl3DHParams **dhParams) { - SSLDHEGroupType selectedGroup = ssl_dhe_group_none; + unsigned int i; - if (ss->ssl3.dheWeakGroupEnabled) { - ss->dheParams = gWeakDHParams; - } else { - if (ss->ssl3.dheGroups) { - selectedGroup = selectDHEGroup(ss, ss->ssl3.dheGroups, - ss->ssl3.numDHEGroups); - } else { - size_t number_of_default_groups = PR_ARRAY_SIZE(ssl_default_dhe_groups); - selectedGroup = selectDHEGroup(ss, ssl_default_dhe_groups, - number_of_default_groups); + 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; } - if (selectedGroup == ssl_dhe_group_none || - selectedGroup >= ssl_dhe_group_max) { - return SECFailure; + params = ssl_GetDHEParams(ss->namedGroupPreferences[i]); + PORT_Assert(params); + if (SECITEM_ItemsAreEqual(¶ms->prime, dh_p)) { + if (!SECITEM_ItemsAreEqual(¶ms->base, dh_g)) { + return SECFailure; + } + if (groupDef) + *groupDef = ss->namedGroupPreferences[i]; + if (dhParams) + *dhParams = params; + return SECSuccess; } + } - ss->dheParams = all_ssl3DHParams[selectedGroup]; + 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 + }; + + /* 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) { + *groupDef = &weak_group_def; + return SECSuccess; + } + if (ss->ssl3.dhePreferredGroup && + ssl_NamedGroupEnabled(ss, ss->ssl3.dhePreferredGroup)) { + *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) { + *groupDef = ss->namedGroupPreferences[i]; + return SECSuccess; + } } - 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(); + sslSocket *ns = NULL; + PRStatus rv; + PRNetAddr addr; + SECStatus status = ssl_Init(); if (status != SECSuccess) { return NULL; @@ -1608,10 +1807,10 @@ ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant) /* 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); + 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)); + SSL_GETPID(), model)); return NULL; } ns = ssl_DupSocket(ss); @@ -1622,12 +1821,12 @@ ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant) rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER); if (rv != PR_SUCCESS) { ssl_FreeSocket(ns); - SET_ERROR_CODE + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); return NULL; } #if defined(DEBUG) || defined(FORCE_PR_ASSERT) { - sslSocket * ss = ssl_FindSocket(fd); + sslSocket *ss = ssl_FindSocket(fd); PORT_Assert(ss == ns); } #endif @@ -1692,13 +1891,13 @@ ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd, } /* For each protocol in server preference, see if we support it. */ - for (i = 0; i < protos_len; ) { - for (j = 0; j < ss->opt.nextProtoNego.len; ) { + for (i = 0; i < protos_len;) { + for (j = 0; j < ss->opt.nextProtoNego.len;) { if (protos[i] == ss->opt.nextProtoNego.data[j] && - PORT_Memcmp(&protos[i+1], &ss->opt.nextProtoNego.data[j+1], - protos[i]) == 0) { + PORT_Memcmp(&protos[i + 1], &ss->opt.nextProtoNego.data[j + 1], + protos[i]) == 0) { /* We found a match. */ - ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED; + ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED; result = &protos[i]; goto found; } @@ -1711,7 +1910,7 @@ ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd, * protocols configured, or none of its options match ours. In this case we * request our favoured protocol. */ /* This will be treated as a failure for ALPN. */ - ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP; + ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP; result = ss->opt.nextProtoNego.data; found: @@ -1730,7 +1929,7 @@ SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data, { sslSocket *ss; SECStatus rv; - SECItem dataItem = { siBuffer, (unsigned char *) data, length }; + SECItem dataItem = { siBuffer, (unsigned char *)data, length }; ss = ssl_FindSocket(fd); if (!ss) { @@ -1770,16 +1969,16 @@ SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf, return SECFailure; } - *state = ss->ssl3.nextProtoState; + *state = ss->xtnData.nextProtoState; - if (ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT && - ss->ssl3.nextProto.data) { - if (ss->ssl3.nextProto.len > bufLenMax) { + 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->ssl3.nextProto.data, ss->ssl3.nextProto.len); - *bufLen = ss->ssl3.nextProto.len; + PORT_Memcpy(buf, ss->xtnData.nextProto.data, ss->xtnData.nextProto.len); + *bufLen = ss->xtnData.nextProto.len; } else { *bufLen = 0; } @@ -1787,9 +1986,10 @@ SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf, return SECSuccess; } -SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, - const PRUint16 *ciphers, - unsigned int numCiphers) +SECStatus +SSL_SetSRTPCiphers(PRFileDesc *fd, + const PRUint16 *ciphers, + unsigned int numCiphers) { sslSocket *ss; unsigned int i; @@ -1821,8 +2021,9 @@ SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, ciphers[i]; } else { SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher " - "suite specified: 0x%04hx", SSL_GETPID(), fd, - ciphers[i])); + "suite specified: 0x%04hx", + SSL_GETPID(), fd, + ciphers[i])); } } @@ -1837,7 +2038,7 @@ SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd, SECStatus SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher) { - sslSocket * ss; + sslSocket *ss; ss = ssl_FindSocket(fd); if (!ss) { @@ -1847,22 +2048,20 @@ SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher) return SECFailure; } - if (!ss->ssl3.dtlsSRTPCipherSuite) { + if (!ss->xtnData.dtlsSRTPCipherSuite) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } - *cipher = ss->ssl3.dtlsSRTPCipherSuite; + *cipher = ss->xtnData.dtlsSRTPCipherSuite; return SECSuccess; } PRFileDesc * SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) { - sslSocket * sm = NULL, *ss = NULL; - int i; - sslServerCerts * mc = NULL; - sslServerCerts * sc = NULL; + sslSocket *sm = NULL, *ss = NULL; + PRCList *cursor; if (model == NULL) { PR_SetError(SEC_ERROR_INVALID_ARGS, 0); @@ -1881,69 +2080,51 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) return NULL; } - ss->opt = sm->opt; + ss->opt = sm->opt; ss->vrange = sm->vrange; 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.signatureAlgorithms, sm->ssl3.signatureAlgorithms, - sizeof(ss->ssl3.signatureAlgorithms[0]) * - sm->ssl3.signatureAlgorithmCount); - ss->ssl3.signatureAlgorithmCount = sm->ssl3.signatureAlgorithmCount; + 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; } - /* This int should be SSLKEAType, but CC on Irix complains, - * during the for loop. - */ - for (i=kt_null; i < kt_kea_size; i++) { - mc = &(sm->serverCerts[i]); - sc = &(ss->serverCerts[i]); - if (mc->serverCert && mc->serverCertChain) { - if (sc->serverCert) { - CERT_DestroyCertificate(sc->serverCert); - } - sc->serverCert = CERT_DupCertificate(mc->serverCert); - if (sc->serverCertChain) { - CERT_DestroyCertificateList(sc->serverCertChain); - } - sc->serverCertChain = CERT_DupCertList(mc->serverCertChain); - if (!sc->serverCertChain) - goto loser; - if (sm->certStatusArray[i]) { - if (ss->certStatusArray[i]) { - SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE); - ss->certStatusArray[i] = NULL; - } - ss->certStatusArray[i] = SECITEM_DupArray(NULL, sm->certStatusArray[i]); - if (!ss->certStatusArray[i]) - goto loser; - } - } - if (mc->serverKeyPair) { - if (sc->serverKeyPair) { - ssl3_FreeKeyPair(sc->serverKeyPair); - } - sc->serverKeyPair = ssl3_GetKeyPairRef(mc->serverKeyPair); - sc->serverKeyBits = mc->serverKeyBits; - } + while (!PR_CLIST_IS_EMPTY(&ss->serverCerts)) { + cursor = PR_LIST_TAIL(&ss->serverCerts); + PR_REMOVE_LINK(cursor); + ssl_FreeServerCert((sslServerCert *)cursor); } - if (sm->stepDownKeyPair) { - if (ss->stepDownKeyPair) { - ssl3_FreeKeyPair(ss->stepDownKeyPair); - } - ss->stepDownKeyPair = ssl3_GetKeyPairRef(sm->stepDownKeyPair); + 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); } - if (sm->ephemeralECDHKeyPair) { - if (ss->ephemeralECDHKeyPair) { - ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair); - } - ss->ephemeralECDHKeyPair = - ssl3_GetKeyPairRef(sm->ephemeralECDHKeyPair); + + 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); } + 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) { @@ -1951,53 +2132,147 @@ SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd) } ss->ssl3.ca_list = CERT_DupDistNames(sm->ssl3.ca_list); if (!ss->ssl3.ca_list) { - goto loser; + return NULL; } } if (sm->authCertificate) - ss->authCertificate = sm->authCertificate; + ss->authCertificate = sm->authCertificate; if (sm->authCertificateArg) - ss->authCertificateArg = sm->authCertificateArg; + ss->authCertificateArg = sm->authCertificateArg; if (sm->getClientAuthData) - ss->getClientAuthData = sm->getClientAuthData; + ss->getClientAuthData = sm->getClientAuthData; if (sm->getClientAuthDataArg) - ss->getClientAuthDataArg = sm->getClientAuthDataArg; + ss->getClientAuthDataArg = sm->getClientAuthDataArg; if (sm->sniSocketConfig) - ss->sniSocketConfig = sm->sniSocketConfig; + ss->sniSocketConfig = sm->sniSocketConfig; if (sm->sniSocketConfigArg) - ss->sniSocketConfigArg = sm->sniSocketConfigArg; + ss->sniSocketConfigArg = sm->sniSocketConfigArg; if (sm->handleBadCert) - ss->handleBadCert = sm->handleBadCert; + ss->handleBadCert = sm->handleBadCert; if (sm->badCertArg) - ss->badCertArg = sm->badCertArg; + ss->badCertArg = sm->badCertArg; if (sm->handshakeCallback) - ss->handshakeCallback = sm->handshakeCallback; + ss->handshakeCallback = sm->handshakeCallback; if (sm->handshakeCallbackData) ss->handshakeCallbackData = sm->handshakeCallbackData; if (sm->pkcs11PinArg) - ss->pkcs11PinArg = sm->pkcs11PinArg; + ss->pkcs11PinArg = sm->pkcs11PinArg; return fd; -loser: - return NULL; +} + +/* + * Get the user supplied range + */ +static SECStatus +ssl3_GetRangePolicy(SSLProtocolVariant protocolVariant, SSLVersionRange *prange) +{ + SECStatus rv; + PRUint32 policy; + PRInt32 option; + + /* only use policy constraints if we've set the apply ssl policy bit */ + rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy); + if ((rv != SECSuccess) || !(policy & NSS_USE_POLICY_IN_SSL)) { + return SECFailure; + } + rv = NSS_OptionGet(VERSIONS_POLICY_MIN(protocolVariant), &option); + if (rv != SECSuccess) { + return rv; + } + prange->min = (PRUint16)option; + rv = NSS_OptionGet(VERSIONS_POLICY_MAX(protocolVariant), &option); + if (rv != SECSuccess) { + return rv; + } + prange->max = (PRUint16)option; + if (prange->max < prange->min) { + return SECFailure; /* don't accept an invalid policy */ + } + return SECSuccess; +} + +/* + * Constrain a single protocol variant's range based on the user policy + */ +static SECStatus +ssl3_ConstrainVariantRangeByPolicy(SSLProtocolVariant protocolVariant) +{ + SSLVersionRange vrange; + SSLVersionRange pvrange; + SECStatus rv; + + vrange = *VERSIONS_DEFAULTS(protocolVariant); + rv = ssl3_GetRangePolicy(protocolVariant, &pvrange); + if (rv != SECSuccess) { + return SECSuccess; /* we don't have any policy */ + } + vrange.min = PR_MAX(vrange.min, pvrange.min); + vrange.max = PR_MIN(vrange.max, pvrange.max); + if (vrange.max >= vrange.min) { + *VERSIONS_DEFAULTS(protocolVariant) = vrange; + } else { + /* there was no overlap, turn off range altogether */ + pvrange.min = pvrange.max = SSL_LIBRARY_VERSION_NONE; + *VERSIONS_DEFAULTS(protocolVariant) = pvrange; + } + return SECSuccess; +} + +static PRBool +ssl_VersionIsSupportedByPolicy(SSLProtocolVariant protocolVariant, + SSL3ProtocolVersion version) +{ + SSLVersionRange pvrange; + SECStatus rv; + + rv = ssl3_GetRangePolicy(protocolVariant, &pvrange); + if (rv == SECSuccess) { + if ((version > pvrange.max) || (version < pvrange.min)) { + return PR_FALSE; /* disallowed by policy */ + } + } + return PR_TRUE; +} + +/* + * This is called at SSL init time to constrain the existing range based + * on user supplied policy. + */ +SECStatus +ssl3_ConstrainRangeByPolicy(void) +{ + SECStatus rv; + rv = ssl3_ConstrainVariantRangeByPolicy(ssl_variant_stream); + if (rv != SECSuccess) { + return rv; + } + rv = ssl3_ConstrainVariantRangeByPolicy(ssl_variant_datagram); + if (rv != SECSuccess) { + return rv; + } + return SECSuccess; } PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version) { - switch (protocolVariant) { - case ssl_variant_stream: - return (version >= SSL_LIBRARY_VERSION_3_0 && - version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); - case ssl_variant_datagram: - return (version >= SSL_LIBRARY_VERSION_TLS_1_1 && - version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); - default: - /* Can't get here */ - PORT_Assert(PR_FALSE); + if (!ssl_VersionIsSupportedByPolicy(protocolVariant, version)) { return PR_FALSE; } + switch (protocolVariant) { + case ssl_variant_stream: + return (version >= SSL_LIBRARY_VERSION_3_0 && + version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); + case ssl_variant_datagram: + return (version >= SSL_LIBRARY_VERSION_TLS_1_1 && + version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED); + default: + /* Can't get here */ + PORT_Assert(PR_FALSE); + return PR_FALSE; + } } /* Returns PR_TRUE if the given version range is valid and @@ -2010,7 +2285,28 @@ ssl3_VersionRangeIsValid(SSLProtocolVariant protocolVariant, return vrange && vrange->min <= vrange->max && ssl3_VersionIsSupported(protocolVariant, vrange->min) && - ssl3_VersionIsSupported(protocolVariant, vrange->max); + ssl3_VersionIsSupported(protocolVariant, vrange->max) && + (vrange->min > SSL_LIBRARY_VERSION_3_0 || + vrange->max < SSL_LIBRARY_VERSION_TLS_1_3); +} + +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 @@ -2023,17 +2319,21 @@ SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant, } switch (protocolVariant) { - case ssl_variant_stream: - vrange->min = SSL_LIBRARY_VERSION_3_0; - vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; - break; - case ssl_variant_datagram: - vrange->min = SSL_LIBRARY_VERSION_TLS_1_1; - vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; - break; - default: - PORT_SetError(SEC_ERROR_INVALID_ARGS); - return SECFailure; + case ssl_variant_stream: + vrange->min = SSL_LIBRARY_VERSION_3_0; + vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; + // We don't allow SSLv3 and TLSv1.3 together. + if (vrange->max == SSL_LIBRARY_VERSION_TLS_1_3) { + vrange->min = SSL_LIBRARY_VERSION_TLS_1_0; + } + break; + case ssl_variant_datagram: + vrange->min = SSL_LIBRARY_VERSION_TLS_1_1; + vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED; + break; + default: + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; } return SECSuccess; @@ -2044,7 +2344,8 @@ SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant, SSLVersionRange *vrange) { if ((protocolVariant != ssl_variant_stream && - protocolVariant != ssl_variant_datagram) || !vrange) { + protocolVariant != ssl_variant_datagram) || + !vrange) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return SECFailure; } @@ -2074,8 +2375,8 @@ SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange) sslSocket *ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeGet", - SSL_GETPID(), fd)); + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeGet", + SSL_GETPID(), fd)); return SECFailure; } @@ -2101,8 +2402,8 @@ SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange) sslSocket *ss = ssl_FindSocket(fd); if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeSet", - SSL_GETPID(), fd)); + SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeSet", + SSL_GETPID(), fd)); return SECFailure; } @@ -2114,6 +2415,14 @@ SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange) 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 = *vrange; ssl_ReleaseSSL3HandshakeLock(ss); @@ -2122,20 +2431,54 @@ SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange) 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; + 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; + PORT_SetError(SEC_ERROR_NOT_INITIALIZED); + return NULL; } return &ss->sec.ci.sid->peerCertStatus; @@ -2146,14 +2489,14 @@ SSL_PeerStapledOCSPResponses(PRFileDesc *fd) ** They all get called through the NSPRIOMethods table below. */ -static PRFileDesc * PR_CALLBACK +static PRFileDesc *PR_CALLBACK ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) { - sslSocket *ss; - sslSocket *ns = NULL; - PRFileDesc *newfd = NULL; + sslSocket *ss; + sslSocket *ns = NULL; + PRFileDesc *newfd = NULL; PRFileDesc *osfd; - PRStatus status; + PRStatus status; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2184,7 +2527,7 @@ ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) ssl_ReleaseSSL3HandshakeLock(ss); ssl_Release1stHandshakeLock(ss); SSL_UNLOCK_WRITER(ss); - SSL_UNLOCK_READER(ss); /* ss isn't used below here. */ + SSL_UNLOCK_READER(ss); /* ss isn't used below here. */ if (ns == NULL) goto loser; @@ -2197,12 +2540,12 @@ ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout) /* 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 = ssl2_BeginClientHandshake; + if (ns->opt.useSecurity) { + if (ns->opt.handshakeAsClient) { + ns->handshake = ssl_BeginClientHandshake; ss->handshaking = sslHandshakingAsClient; } else { - ns->handshake = ssl2_BeginServerHandshake; + ns->handshake = ssl_BeginServerHandshake; ss->handshaking = sslHandshakingAsServer; } } @@ -2221,7 +2564,7 @@ static PRStatus PR_CALLBACK ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout) { sslSocket *ss; - PRStatus rv; + PRStatus rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2245,8 +2588,8 @@ ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout) static PRStatus PR_CALLBACK ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr) { - sslSocket * ss = ssl_GetPrivate(fd); - PRStatus rv; + sslSocket *ss = ssl_GetPrivate(fd); + PRStatus rv; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd)); @@ -2265,8 +2608,8 @@ ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr) static PRStatus PR_CALLBACK ssl_Listen(PRFileDesc *fd, PRIntn backlog) { - sslSocket * ss = ssl_GetPrivate(fd); - PRStatus rv; + sslSocket *ss = ssl_GetPrivate(fd); + PRStatus rv; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd)); @@ -2285,8 +2628,8 @@ ssl_Listen(PRFileDesc *fd, PRIntn backlog) static PRStatus PR_CALLBACK ssl_Shutdown(PRFileDesc *fd, PRIntn how) { - sslSocket * ss = ssl_GetPrivate(fd); - PRStatus rv; + sslSocket *ss = ssl_GetPrivate(fd); + PRStatus rv; if (!ss) { SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd)); @@ -2314,7 +2657,7 @@ static PRStatus PR_CALLBACK ssl_Close(PRFileDesc *fd) { sslSocket *ss; - PRStatus rv; + PRStatus rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2342,7 +2685,7 @@ ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags, PRIntervalTime timeout) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2353,7 +2696,7 @@ ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags, ss->rTimeout = timeout; if (!ss->opt.fdx) ss->wTimeout = timeout; - rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags); + rv = (*ss->ops->recv)(ss, (unsigned char *)buf, len, flags); SSL_UNLOCK_READER(ss); return rv; } @@ -2363,7 +2706,7 @@ ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags, PRIntervalTime timeout) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2374,7 +2717,7 @@ ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags, ss->wTimeout = timeout; if (!ss->opt.fdx) ss->rTimeout = timeout; - rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags); + rv = (*ss->ops->send)(ss, (const unsigned char *)buf, len, flags); SSL_UNLOCK_WRITER(ss); return rv; } @@ -2383,7 +2726,7 @@ static int PR_CALLBACK ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2394,7 +2737,7 @@ ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len) 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); + rv = (*ss->ops->read)(ss, (unsigned char *)buf, len); SSL_UNLOCK_READER(ss); return rv; } @@ -2403,7 +2746,7 @@ static int PR_CALLBACK ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len) { sslSocket *ss; - int rv; + int rv; ss = ssl_GetPrivate(fd); if (!ss) { @@ -2414,7 +2757,7 @@ ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len) 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); + rv = (*ss->ops->write)(ss, (const unsigned char *)buf, len); SSL_UNLOCK_WRITER(ss); return rv; } @@ -2437,9 +2780,9 @@ ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr) SECStatus ssl_GetPeerInfo(sslSocket *ss) { - PRFileDesc * osfd; - int rv; - PRNetAddr sin; + PRFileDesc *osfd; + int rv; + PRNetAddr sin; osfd = ss->fd->lower; @@ -2476,35 +2819,6 @@ ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name) } SECStatus -SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses, - SSLKEAType kea) -{ - sslSocket *ss; - - ss = ssl_FindSocket(fd); - if (!ss) { - SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetStapledOCSPResponses", - SSL_GETPID(), fd)); - return SECFailure; - } - - if ( kea <= 0 || kea >= kt_kea_size) { - SSL_DBG(("%d: SSL[%d]: invalid key in SSL_SetStapledOCSPResponses", - SSL_GETPID(), fd)); - return SECFailure; - } - - if (ss->certStatusArray[kea]) { - SECITEM_FreeArray(ss->certStatusArray[kea], PR_TRUE); - ss->certStatusArray[kea] = NULL; - } - if (responses) { - ss->certStatusArray[kea] = SECITEM_DupArray(NULL, responses); - } - return (ss->certStatusArray[kea] || !responses) ? SECSuccess : SECFailure; -} - -SECStatus SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID) { sslSocket *ss; @@ -2531,15 +2845,15 @@ 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; + 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 */ + return 0; /* don't poll on this socket */ } if (ss->opt.useSecurity && @@ -2565,40 +2879,38 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) new_flags |= PR_POLL_READ; } } else - /* First handshake is in progress */ - if (ss->lastWriteBlocked) { + /* First handshake is in progress */ + if (ss->lastWriteBlocked) { 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. */ + 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. - */ - if (!(ss->version >= SSL_LIBRARY_VERSION_3_0 && - ss->ssl3.hs.canFalseStart)) { - new_flags ^= PR_POLL_WRITE; /* don't select on write. */ - } - new_flags |= PR_POLL_READ; /* do select on read. */ + /* 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. + */ + if (!ss->ssl3.hs.canFalseStart) { + 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. */ + *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. */ + new_flags |= PR_POLL_WRITE; /* also select on write. */ } - if (ss->version >= SSL_LIBRARY_VERSION_3_0 && - ss->ssl3.hs.restartTarget != NULL) { + 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. @@ -2626,8 +2938,8 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) } if (new_flags && (fd->lower->methods->poll != NULL)) { - PRInt16 lower_out_flags = 0; - PRInt16 lower_new_flags; + 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)) { @@ -2640,7 +2952,7 @@ ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags) new_flags = how_flags; } else { *p_out_flags = lower_out_flags; - new_flags = lower_new_flags; + new_flags = lower_new_flags; } } @@ -2665,14 +2977,13 @@ ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd, return sd->methods->sendfile(sd, &sfd, flags, timeout); } - PRBool ssl_FdIsBlocking(PRFileDesc *fd) { PRSocketOptionData opt; - PRStatus status; + PRStatus status; - opt.option = PR_SockOpt_Nonblocking; + opt.option = PR_SockOpt_Nonblocking; opt.value.non_blocking = PR_FALSE; status = PR_GetSocketOption(fd, &opt); if (status != PR_SUCCESS) @@ -2686,23 +2997,23 @@ ssl_SocketIsBlocking(sslSocket *ss) return ssl_FdIsBlocking(ss->fd); } -PRInt32 sslFirstBufSize = 8 * 1024; -PRInt32 sslCopyLimit = 1024; +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 = { 0, 0 }; - char buf[MAX_FRAGMENT_LENGTH]; + 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); @@ -2721,28 +3032,37 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, blocking = ssl_FdIsBlocking(fd); #define K16 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; \ - } \ - } \ +#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; \ + PR_ASSERT(!blocking); \ + return sent + rv; \ } -#define SEND(bfr, len) \ - do { \ +#define SEND(bfr, len) \ + do { \ rv = ssl_Send(fd, bfr, len, 0, timeout); \ - HANDLE_ERR(rv, len) \ - sent += len; \ + HANDLE_ERR(rv, len) \ + sent += len; \ } while (0) /* Make sure the first write is at least 8 KB, if possible. */ @@ -2762,23 +3082,23 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, GET_VECTOR; toCopy = PR_MIN(left, myIov.iov_len); PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy); - bufLen += toCopy; - left -= toCopy; + bufLen += toCopy; + left -= toCopy; myIov.iov_base += toCopy; - myIov.iov_len -= toCopy; + myIov.iov_len -= toCopy; } - SEND( buf, bufLen ); + SEND(buf, bufLen); } while (vectors || myIov.iov_len) { - PRInt32 addLen; + 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; + myIov.iov_len -= K16; } if (!myIov.iov_len) continue; @@ -2788,13 +3108,13 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, } 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; + 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 ); + SEND(myIov.iov_base, myIov.iov_len); myIov.iov_len = 0; continue; } @@ -2804,25 +3124,24 @@ ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors, 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. */ - ) { + 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; + iov[1].iov_len % K16 + addLen <= left + limit) { + addLen = left; } else addLen = 0; } while (addLen); - SEND( buf, bufLen ); + SEND(buf, bufLen); } return sent; } @@ -2859,14 +3178,16 @@ ssl_FSync(PRFileDesc *fd) } static PRInt32 PR_CALLBACK -ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) { +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) { +ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) +{ PRInt64 res; PORT_Assert(0); @@ -2911,85 +3232,83 @@ ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags, 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 */ + 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; + PRIOMethods *new_methods = &combined_methods; const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods(); - const PRIOMethods *my_methods = &ssl_methods; + 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; - + 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; @@ -3006,8 +3325,8 @@ ssl_InitIOLayer(void) static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id) { - PRFileDesc *layer = NULL; - PRStatus status; + PRFileDesc *layer = NULL; + PRStatus status; if (!ssl_inited) { status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer); @@ -3055,24 +3374,24 @@ ssl_MakeLocks(sslSocket *ss) ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL); if (!ss->firstHandshakeLock) goto loser; - ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL); + ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL); if (!ss->ssl3HandshakeLock) goto loser; - ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL); + ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL); if (!ss->specLock) goto loser; - ss->recvBufLock = PZ_NewMonitor(nssILockSSL); + ss->recvBufLock = PZ_NewMonitor(nssILockSSL); if (!ss->recvBufLock) goto loser; - ss->xmitBufLock = PZ_NewMonitor(nssILockSSL); + ss->xmitBufLock = PZ_NewMonitor(nssILockSSL); if (!ss->xmitBufLock) goto loser; - ss->writerThread = NULL; + ss->writerThread = NULL; if (ssl_lock_readers) { - ss->recvLock = PZ_NewLock(nssILockSSL); + ss->recvLock = PZ_NewLock(nssILockSSL); if (!ss->recvLock) goto loser; - ss->sendLock = PZ_NewLock(nssILockSSL); + ss->sendLock = PZ_NewLock(nssILockSSL); if (!ss->sendLock) goto loser; } @@ -3086,19 +3405,19 @@ loser: #define NSS_HAVE_GETENV 1 #endif -#define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */ +#define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */ static void ssl_SetDefaultsFromEnvironment(void) { -#if defined( NSS_HAVE_GETENV ) +#if defined(NSS_HAVE_GETENV) static int firsttime = 1; if (firsttime) { - char * ev; + char *ev; firsttime = 0; #ifdef DEBUG - ev = getenv("SSLDEBUGFILE"); + ev = PR_GetEnvSecure("SSLDEBUGFILE"); if (ev && ev[0]) { ssl_trace_iob = fopen(ev, "w"); } @@ -3106,19 +3425,20 @@ ssl_SetDefaultsFromEnvironment(void) ssl_trace_iob = stderr; } #ifdef TRACE - ev = getenv("SSLTRACE"); + ev = PR_GetEnvSecure("SSLTRACE"); if (ev && ev[0]) { ssl_trace = atoi(ev); SSL_TRACE(("SSL: tracing set to %d", ssl_trace)); } #endif /* TRACE */ - ev = getenv("SSLDEBUG"); + ev = PR_GetEnvSecure("SSLDEBUG"); if (ev && ev[0]) { ssl_debug = atoi(ev); SSL_TRACE(("SSL: debugging set to %d", ssl_debug)); } #endif /* DEBUG */ - ev = getenv("SSLKEYLOGFILE"); +#ifdef NSS_ALLOW_SSLKEYLOGFILE + ev = PR_GetEnvSecure("SSLKEYLOGFILE"); if (ev && ev[0]) { ssl_keylog_iob = fopen(ev, "a"); if (!ssl_keylog_iob) { @@ -3131,22 +3451,15 @@ ssl_SetDefaultsFromEnvironment(void) SSL_TRACE(("SSL: logging SSL/TLS secrets to %s", ev)); } } -#ifndef NO_PKCS11_BYPASS - ev = getenv("SSLBYPASS"); - if (ev && ev[0]) { - ssl_defaults.bypassPKCS11 = (ev[0] == '1'); - SSL_TRACE(("SSL: bypass default set to %d", \ - ssl_defaults.bypassPKCS11)); - } -#endif /* NO_PKCS11_BYPASS */ - ev = getenv("SSLFORCELOCKS"); +#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 = getenv("NSS_SSL_ENABLE_RENEGOTIATION"); + ev = PR_GetEnvSecure("NSS_SSL_ENABLE_RENEGOTIATION"); if (ev) { if (ev[0] == '1' || LOWER(ev[0]) == 'u') ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED; @@ -3159,13 +3472,13 @@ ssl_SetDefaultsFromEnvironment(void) SSL_TRACE(("SSL: enableRenegotiation set to %d", ssl_defaults.enableRenegotiation)); } - ev = getenv("NSS_SSL_REQUIRE_SAFE_NEGOTIATION"); + 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)); + PR_TRUE)); } - ev = getenv("NSS_SSL_CBC_RANDOM_IV"); + 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")); @@ -3174,13 +3487,172 @@ ssl_SetDefaultsFromEnvironment(void) #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) +{ + 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) +{ + 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); + } +} + /* ** Create a newsocket structure for a file descriptor. */ static sslSocket * ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant) { + SECStatus rv; sslSocket *ss; + int i; ssl_SetDefaultsFromEnvironment(); @@ -3188,76 +3660,83 @@ ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant) makeLocks = PR_TRUE; /* Make a new socket and get it ready */ - ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket)); - if (ss) { - /* This should be of type SSLKEAType, but CC on IRIX - * complains during the for loop. - */ - int i; - SECStatus status; - - ss->opt = ssl_defaults; - ss->opt.useSocks = PR_FALSE; - ss->opt.noLocks = !makeLocks; - ss->vrange = *VERSIONS_DEFAULTS(protocolVariant); - ss->protocolVariant = protocolVariant; - - ss->peerID = NULL; - ss->rTimeout = PR_INTERVAL_NO_TIMEOUT; - ss->wTimeout = PR_INTERVAL_NO_TIMEOUT; - ss->cTimeout = PR_INTERVAL_NO_TIMEOUT; - ss->cipherSpecs = NULL; - ss->sizeCipherSpecs = 0; /* produced lazily */ - ss->preferredCipher = NULL; - ss->url = NULL; - - for (i=kt_null; i < kt_kea_size; i++) { - sslServerCerts * sc = ss->serverCerts + i; - sc->serverCert = NULL; - sc->serverCertChain = NULL; - sc->serverKeyPair = NULL; - sc->serverKeyBits = 0; - ss->certStatusArray[i] = NULL; - } - ss->stepDownKeyPair = NULL; - - ss->dheParams = NULL; - ss->dheKeyPair = NULL; - - 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->handleBadCert = NULL; - ss->badCertArg = NULL; - ss->pkcs11PinArg = NULL; - ss->ephemeralECDHKeyPair = NULL; - - ssl_ChooseOps(ss); - ssl2_InitSocketPolicy(ss); - ssl3_InitSocketPolicy(ss); - PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight); - - if (makeLocks) { - status = ssl_MakeLocks(ss); - if (status != SECSuccess) - goto loser; - } - status = ssl_CreateSecurityInfo(ss); - if (status != SECSuccess) + ss = (sslSocket *)PORT_ZAlloc(sizeof(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; + + 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); + + 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->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); + if (makeLocks) { + rv = ssl_MakeLocks(ss); + if (rv != SECSuccess) goto loser; - status = ssl_InitGather(&ss->gs); - if (status != SECSuccess) { -loser: - ssl_DestroySocketContents(ss); - ssl_DestroyLocks(ss); - PORT_Free(ss); - ss = NULL; - } } + rv = ssl_CreateSecurityInfo(ss); + if (rv != SECSuccess) + goto loser; + rv = ssl3_InitGather(&ss->gs); + if (rv != SECSuccess) + goto loser; + ssl3_InitExtensionData(&ss->xtnData); 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; } diff --git a/nss/lib/ssl/sslt.h b/nss/lib/ssl/sslt.h index cd742bb..506b78d 100644 --- a/nss/lib/ssl/sslt.h +++ b/nss/lib/ssl/sslt.h @@ -10,6 +10,8 @@ #define __sslt_h_ #include "prtypes.h" +#include "secitem.h" +#include "certt.h" typedef struct SSL3StatisticsStr { /* statistics from ssl3_SendClientHello (sch) */ @@ -36,12 +38,15 @@ typedef struct SSL3StatisticsStr { /* 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_size /* number of ssl_kea_ algorithms */ + 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. @@ -49,21 +54,20 @@ typedef enum { ** 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 - +#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 + 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 @@ -80,86 +84,211 @@ typedef enum { ssl_hash_sha512 = 6 } SSLHashType; +/* Deprecated */ typedef struct SSLSignatureAndHashAlgStr { SSLHashType hashAlg; SSLSignType sigAlg; } SSLSignatureAndHashAlg; typedef enum { - ssl_auth_null = 0, - ssl_auth_rsa = 1, - ssl_auth_dsa = 2, - ssl_auth_kea = 3, - ssl_auth_ecdsa = 4 + 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_sha256 = 0x0804, + ssl_sig_rsa_pss_sha384 = 0x0805, + ssl_sig_rsa_pss_sha512 = 0x0806, + ssl_sig_ed25519 = 0x0807, + ssl_sig_ed448 = 0x0808, + + 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; + +/* +** 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, /* static RSA */ + 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 PKCS#1.5 signing */ + ssl_auth_rsa_pss = 8, + ssl_auth_psk = 9, + ssl_auth_tls13_any = 10, + ssl_auth_size /* number of authentication types */ } SSLAuthType; +/* 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_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_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 +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 */ + 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; +} SSLExtraServerCertData; + typedef struct SSLChannelInfoStr { - PRUint32 length; - PRUint16 protocolVersion; - PRUint16 cipherSuite; + /* 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; /* server authentication info */ - PRUint32 authKeyBits; + PRUint32 authKeyBits; /* key exchange algorithm info */ - PRUint32 keaKeyBits; + 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]; + 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; + 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; + 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; + + /* 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_all (ssl_preinfo_version|ssl_preinfo_cipher_suite) +#define ssl_preinfo_all (ssl_preinfo_version | ssl_preinfo_cipher_suite) typedef struct SSLPreliminaryChannelInfoStr { - /* This is set to the length of the struct. */ + /* 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_*). */ @@ -168,43 +297,57 @@ typedef struct SSLPreliminaryChannelInfoStr { PRUint16 protocolVersion; /* Cipher suite: test (valuesSet & ssl_preinfo_cipher_suite) */ PRUint16 cipherSuite; + + /* When adding new fields to this structure, please document the + * NSS version in which they were added. */ } SSLPreliminaryChannelInfo; typedef struct SSLCipherSuiteInfoStr { - PRUint16 length; - PRUint16 cipherSuite; + /* 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; + const char* cipherSuiteName; /* server authentication info */ - const char * authAlgorithmName; - SSLAuthType authAlgorithm; + const char* authAlgorithmName; + SSLAuthType authAlgorithm; /* deprecated, use |authType| */ /* key exchange algorithm info */ - const char * keaTypeName; - SSLKEAType keaType; + const char* keaTypeName; + SSLKEAType keaType; /* symmetric encryption info */ - const char * symCipherName; - SSLCipherAlgorithm symCipher; - PRUint16 symKeyBits; - PRUint16 symKeySpace; - PRUint16 effectiveKeyBits; + 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; - PRUintn nonStandard : 1; - PRUintn reservedBits :29; - + 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; + + /* When adding new fields to this structure, please document the + * NSS version in which they were added. */ } SSLCipherSuiteInfo; typedef enum { @@ -218,32 +361,47 @@ typedef struct SSLVersionRangeStr { } SSLVersionRange; typedef enum { - SSL_sni_host_name = 0, + 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, -#ifndef NSS_DISABLE_ECC - ssl_elliptic_curves_xtn = 10, - ssl_ec_point_formats_xtn = 11, -#endif - ssl_signature_algorithms_xtn = 13, - ssl_use_srtp_xtn = 14, - ssl_app_layer_protocol_xtn = 16, - ssl_padding_xtn = 21, - ssl_extended_master_secret_xtn = 23, - ssl_session_ticket_xtn = 35, - ssl_next_proto_nego_xtn = 13172, - ssl_renegotiation_info_xtn = 0xff01, - ssl_tls13_draft_version_xtn = 0xff02 /* experimental number */ + 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_session_ticket_xtn = 35, + ssl_tls13_key_share_xtn = 40, + 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, + ssl_next_proto_nego_xtn = 13172, + ssl_renegotiation_info_xtn = 0xff01, + ssl_tls13_short_header_xtn = 0xff03 } SSLExtensionType; -#define SSL_MAX_EXTENSIONS 12 /* doesn't include ssl_padding_xtn. */ +/* This is the old name for the supported_groups extensions. */ +#define ssl_elliptic_curves_xtn ssl_supported_groups_xtn + +/* SSL_MAX_EXTENSIONS doesn't include ssl_padding_xtn. It 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 are smaller. */ +#define SSL_MAX_EXTENSIONS 19 +/* Deprecated */ typedef enum { ssl_dhe_group_none = 0, ssl_ff_dhe_2048_group = 1, diff --git a/nss/lib/ssl/ssltrace.c b/nss/lib/ssl/ssltrace.c index ee540d5..b1fdde7 100644 --- a/nss/lib/ssl/ssltrace.c +++ b/nss/lib/ssl/ssltrace.c @@ -6,6 +6,7 @@ * 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" @@ -15,25 +16,26 @@ 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 */ + "................" /* 0x */ + "................" /* 1x */ + " !\"#$%&'()*+,-./" /* 2x */ + "0123456789:;<=>?" /* 3x */ + "@ABCDEFGHIJKLMNO" /* 4x */ + "PQRSTUVWXYZ[\\]^_" /* 5x */ + "`abcdefghijklmno" /* 6x */ + "pqrstuvwxyz{|}~." /* 7x */ + "................" /* 8x */ + "................" /* 9x */ + "................" /* ax */ + "................" /* bx */ + "................" /* cx */ + "................" /* dx */ + "................" /* ex */ + "................" /* fx */ }; -void ssl_PrintBuf(sslSocket *ss, const char *msg, const void *vp, int len) +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]; @@ -41,203 +43,72 @@ void ssl_PrintBuf(sslSocket *ss, const char *msg, const void *vp, int len) 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)); - } - 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)); - } -} - -#define LEN(cp) (((cp)[0] << 8) | ((cp)[1])) - -static void PrintType(sslSocket *ss, char *msg) -{ - if (ss) { - SSL_TRACE(("%d: SSL[%d]: dump-msg: %s", SSL_GETPID(), ss->fd, - msg)); + SSL_TRACE(("%d: SSL[%d]: %s [Len: %d]", SSL_GETPID(), ss->fd, + msg, len)); } else { - SSL_TRACE(("%d: SSL: dump-msg: %s", SSL_GETPID(), msg)); + SSL_TRACE(("%d: SSL: %s [Len: %d]", SSL_GETPID(), msg, len)); } -} -static void PrintInt(sslSocket *ss, char *msg, unsigned v) -{ - if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s=%u", SSL_GETPID(), ss->fd, - msg, v)); - } else { - SSL_TRACE(("%d: SSL: %s=%u", SSL_GETPID(), msg, v)); + if (!cp) { + SSL_TRACE((" <NULL>")); + return; } -} -/* PrintBuf is just like ssl_PrintBuf above, except that: - * a) It prefixes each line of the buffer with "XX: SSL[xxx] " - * b) It dumps only hex, not ASCII. - */ -static void PrintBuf(sslSocket *ss, char *msg, unsigned char *cp, int len) -{ - char buf[80]; - char *bp; - - 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)); - } + 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++ = ' '; - if (bp + 4 > buf + 50) { - *bp = 0; - if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s", - SSL_GETPID(), ss->fd, buf)); - } else { - SSL_TRACE(("%d: SSL: %s", SSL_GETPID(), buf)); - } - bp = buf; - } + 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) { - *bp = 0; - if (ss) { - SSL_TRACE(("%d: SSL[%d]: %s", - SSL_GETPID(), ss->fd, buf)); - } else { - SSL_TRACE(("%d: SSL: %s", SSL_GETPID(), buf)); - } + *ap = 0; + SSL_TRACE((" %s", buf)); } } -void ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len) +void +ssl_Trace(const char *format, ...) { - switch (bp[0]) { - case SSL_MT_ERROR: - PrintType(ss, "Error"); - PrintInt(ss, "error", LEN(bp+1)); - break; - - case SSL_MT_CLIENT_HELLO: - { - unsigned lcs = LEN(bp+3); - unsigned ls = LEN(bp+5); - unsigned lc = LEN(bp+7); - - PrintType(ss, "Client-Hello"); - - PrintInt(ss, "version (Major)", bp[1]); - PrintInt(ss, "version (minor)", bp[2]); - - PrintBuf(ss, "cipher-specs", bp+9, lcs); - PrintBuf(ss, "session-id", bp+9+lcs, ls); - PrintBuf(ss, "challenge", bp+9+lcs+ls, lc); - } - break; - case SSL_MT_CLIENT_MASTER_KEY: - { - unsigned lck = LEN(bp+4); - unsigned lek = LEN(bp+6); - unsigned lka = LEN(bp+8); - - PrintType(ss, "Client-Master-Key"); - - PrintInt(ss, "cipher-choice", bp[1]); - PrintInt(ss, "key-length", LEN(bp+2)); - - PrintBuf(ss, "clear-key", bp+10, lck); - PrintBuf(ss, "encrypted-key", bp+10+lck, lek); - PrintBuf(ss, "key-arg", bp+10+lck+lek, lka); - } - break; - case SSL_MT_CLIENT_FINISHED: - PrintType(ss, "Client-Finished"); - PrintBuf(ss, "connection-id", bp+1, len-1); - break; - case SSL_MT_SERVER_HELLO: - { - unsigned lc = LEN(bp+5); - unsigned lcs = LEN(bp+7); - unsigned lci = LEN(bp+9); + char buf[2000]; + va_list args; - PrintType(ss, "Server-Hello"); + if (ssl_trace_iob) { + va_start(args, format); + PR_vsnprintf(buf, sizeof(buf), format, args); + va_end(args); - PrintInt(ss, "session-id-hit", bp[1]); - PrintInt(ss, "certificate-type", bp[2]); - PrintInt(ss, "version (Major)", bp[3]); - PrintInt(ss, "version (minor)", bp[3]); - PrintBuf(ss, "certificate", bp+11, lc); - PrintBuf(ss, "cipher-specs", bp+11+lc, lcs); - PrintBuf(ss, "connection-id", bp+11+lc+lcs, lci); - } - break; - case SSL_MT_SERVER_VERIFY: - PrintType(ss, "Server-Verify"); - PrintBuf(ss, "challenge", bp+1, len-1); - break; - case SSL_MT_SERVER_FINISHED: - PrintType(ss, "Server-Finished"); - PrintBuf(ss, "session-id", bp+1, len-1); - break; - case SSL_MT_REQUEST_CERTIFICATE: - PrintType(ss, "Request-Certificate"); - PrintInt(ss, "authentication-type", bp[1]); - PrintBuf(ss, "certificate-challenge", bp+2, len-2); - break; - case SSL_MT_CLIENT_CERTIFICATE: - { - unsigned lc = LEN(bp+2); - unsigned lr = LEN(bp+4); - PrintType(ss, "Client-Certificate"); - PrintInt(ss, "certificate-type", bp[1]); - PrintBuf(ss, "certificate", bp+6, lc); - PrintBuf(ss, "response", bp+6+lc, lr); - } - break; - default: - ssl_PrintBuf(ss, "sending *unknown* message type", bp, len); - return; + fputs(buf, ssl_trace_iob); + fputs("\n", ssl_trace_iob); } } void -ssl_Trace(const char *format, ... ) +ssl_PrintKey(const sslSocket *ss, const char *msg, PK11SymKey *key) { - char buf[2000]; - va_list args; + SECStatus rv; + SECItem *rawkey; - 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); + 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/nss/lib/ssl/tls13con.c b/nss/lib/ssl/tls13con.c new file mode 100644 index 0000000..68a2a2c --- /dev/null +++ b/nss/lib/ssl/tls13con.c @@ -0,0 +1,4509 @@ +/* -*- 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 "tls13hkdf.h" +#include "tls13con.h" +#include "tls13exthandle.h" + +typedef enum { + TrafficKeyEarlyApplicationData, + TrafficKeyHandshake, + TrafficKeyApplicationData +} TrafficKeyType; + +typedef enum { + CipherSpecRead, + CipherSpecWrite, +} CipherSpecDirection; + +static SECStatus tls13_SetCipherSpec(sslSocket *ss, TrafficKeyType type, + CipherSpecDirection install, + PRBool deleteSecret); +static SECStatus tls13_AESGCM( + ssl3KeyMaterial *keys, + PRBool doDecrypt, + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + const unsigned char *additionalData, int additionalDataLen); +static SECStatus tls13_ChaCha20Poly1305( + ssl3KeyMaterial *keys, + PRBool doDecrypt, + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + const unsigned char *additionalData, int additionalDataLen); +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); + +static SECStatus tls13_HandleServerKeyShare(sslSocket *ss); +static SECStatus tls13_HandleEncryptedExtensions(sslSocket *ss, SSL3Opaque *b, + PRUint32 length); +static SECStatus tls13_SendCertificate(sslSocket *ss); +static SECStatus tls13_HandleCertificate( + sslSocket *ss, SSL3Opaque *b, PRUint32 length); +static SECStatus tls13_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, + PRUint32 length); +static SECStatus +tls13_SendCertificateVerify(sslSocket *ss, SECKEYPrivateKey *privKey); +static SECStatus tls13_HandleCertificateVerify( + sslSocket *ss, SSL3Opaque *b, PRUint32 length, + SSL3Hashes *hashes); +static SECStatus tls13_RecoverWrappedSharedSecret(sslSocket *ss, + sslSessionID *sid); +static SECStatus +tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key, + const char *prefix, + const char *suffix, + const SSL3Hashes *hashes, + PK11SymKey **dest); +static void tls13_SetNullCipherSpec(sslSocket *ss, ssl3CipherSpec **specp); +static SECStatus tls13_SendEndOfEarlyData(sslSocket *ss); +static SECStatus tls13_SendFinished(sslSocket *ss, PK11SymKey *baseKey); +static SECStatus tls13_ComputePskBinderHash(sslSocket *ss, + unsigned long prefixLength, + SSL3Hashes *hashes); +static SECStatus tls13_VerifyFinished(sslSocket *ss, SSL3HandshakeType message, + PK11SymKey *secret, + SSL3Opaque *b, PRUint32 length, + const SSL3Hashes *hashes); +static SECStatus tls13_ClientHandleFinished(sslSocket *ss, + SSL3Opaque *b, PRUint32 length, + const SSL3Hashes *hashes); +static SECStatus tls13_ServerHandleFinished(sslSocket *ss, + SSL3Opaque *b, PRUint32 length, + const SSL3Hashes *hashes); +static SECStatus tls13_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, + PRUint32 length); +static SECStatus tls13_ComputeHandshakeHashes(sslSocket *ss, + SSL3Hashes *hashes); +static SECStatus tls13_ComputeEarlySecrets(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, const SSL3Hashes *hashes, + PRBool sending, PRUint8 *output, unsigned int *outputLen, + unsigned int maxOutputLen); +static SECStatus tls13_SendClientSecondRound(sslSocket *ss); +static SECStatus tls13_FinishHandshake(sslSocket *ss); + +const char kHkdfLabelClient[] = "client"; +const char kHkdfLabelServer[] = "server"; +const char kHkdfLabelPskBinderKey[] = "resumption psk binder key"; +const char kHkdfLabelEarlyTrafficSecret[] = "early traffic secret"; +const char kHkdfLabelEarlyExporterSecret[] = "early exporter master secret"; +const char kHkdfLabelHandshakeTrafficSecret[] = "handshake traffic secret"; +const char kHkdfLabelApplicationTrafficSecret[] = "application traffic secret"; +const char kHkdfLabelFinishedSecret[] = "finished"; +const char kHkdfLabelResumptionMasterSecret[] = "resumption master secret"; +const char kHkdfLabelExporterMasterSecret[] = "exporter master secret"; +const char kHkdfPurposeKey[] = "key"; +const char kHkdfPurposeIv[] = "iv"; + +#define TRAFFIC_SECRET(ss, dir, name) ((ss->sec.isServer ^ \ + (dir == CipherSpecWrite)) \ + ? ss->ssl3.hs.client##name \ + : ss->ssl3.hs.server##name) + +const SSL3ProtocolVersion kTlsRecordVersion = SSL_LIBRARY_VERSION_TLS_1_0; +const SSL3ProtocolVersion kDtlsRecordVersion = SSL_LIBRARY_VERSION_TLS_1_1; + +/* 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); + +/* 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) +{ + 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(wait_client_hello); + STATE_CASE(wait_client_cert); + STATE_CASE(wait_cert_verify); + STATE_CASE(wait_finished); + STATE_CASE(wait_server_hello); + STATE_CASE(wait_server_cert); + STATE_CASE(wait_cert_request); + STATE_CASE(wait_encrypted_extensions); + STATE_CASE(idle_handshake); + 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; +} + +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) +{ + /* 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; +} + +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_GetHkdfMechanismForHash(SSLHashType hash) +{ + switch (hash) { + case ssl_hash_sha256: + return CKM_NSS_HKDF_SHA256; + case ssl_hash_sha384: + return CKM_NSS_HKDF_SHA384; + default: + PORT_Assert(0); + } + return CKM_NSS_HKDF_SHA256; +} + +CK_MECHANISM_TYPE +tls13_GetHkdfMechanism(sslSocket *ss) +{ + return tls13_GetHkdfMechanismForHash(tls13_GetHash(ss)); +} + +static CK_MECHANISM_TYPE +tls13_GetHmacMechanism(sslSocket *ss) +{ + switch (tls13_GetHash(ss)) { + case ssl_hash_sha256: + return CKM_SHA256_HMAC; + case ssl_hash_sha384: + return CKM_SHA384_HMAC; + default: + PORT_Assert(0); + } + return CKM_SHA256_HMAC; +} + +SECStatus +tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef) +{ + SECStatus rv; + sslEphemeralKeyPair *keyPair = NULL; + 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; + } + + PR_APPEND_LINK(&keyPair->link, &ss->ephemeralKeyPairs); + return rv; +} + +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) +{ + unsigned int i; + SSL3Statistics *ssl3stats = SSL_GetStatistics(); + NewSessionTicket *session_ticket = NULL; + sslSessionID *sid = ss->sec.ci.sid; + unsigned int numShares = 0; + + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + PORT_Assert(PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)); + + /* Select the first enabled group. + * TODO(ekr@rtfm.com): be smarter about offering the group + * that the other side negotiated if we are resuming. */ + for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) { + SECStatus rv; + if (!ss->namedGroupPreferences[i]) { + continue; + } + rv = tls13_CreateKeyShare(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; + } + + /* Below here checks if we can do stateless resumption. */ + if (sid->cached == never_cached || + sid->version < SSL_LIBRARY_VERSION_TLS_1_3) { + return SECSuccess; + } + + /* 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 (session_ticket->ticket_lifetime_hint == 0 || + (session_ticket->ticket_lifetime_hint + + session_ticket->received_timestamp > + ssl_Time())) { + ss->statelessResume = PR_TRUE; + } + + if (ss->statelessResume) { + SECStatus rv; + + 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); + ss->sec.uncache(ss->sec.ci.sid); + ssl_FreeSID(ss->sec.ci.sid); + ss->sec.ci.sid = NULL; + return SECFailure; + } + + rv = ssl3_SetCipherSuite(ss, ss->sec.ci.sid->u.ssl3.cipherSuite, PR_FALSE); + if (rv != SECSuccess) { + FATAL_ERROR(ss, PORT_GetError(), internal_error); + return SECFailure; + } + + rv = tls13_ComputeEarlySecrets(ss); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + } + + return SECSuccess; +} + +static SECStatus +tls13_ImportDHEKeyShare(sslSocket *ss, SECKEYPublicKey *peerKey, + SSL3Opaque *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; +} + +static SECStatus +tls13_HandleKeyShare(sslSocket *ss, + TLS13KeyShareEntry *entry, + sslKeyPair *keyPair) +{ + PORTCheapArenaPool arena; + SECKEYPublicKey *peerKey; + CK_MECHANISM_TYPE mechanism; + PRErrorCode errorCode; + SECStatus rv; + + 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(ss, peerKey, + entry->key_exchange.data, + entry->key_exchange.len, + entry->group); + mechanism = CKM_ECDH1_DERIVE; + break; + case ssl_kea_dh: + rv = tls13_ImportDHEKeyShare(ss, peerKey, + entry->key_exchange.data, + entry->key_exchange.len, + keyPair->pubKey); + mechanism = CKM_DH_PKCS_DERIVE; + break; + default: + PORT_Assert(0); + goto loser; + } + if (rv != SECSuccess) { + goto loser; + } + + ss->ssl3.hs.dheSecret = PK11_PubDeriveWithKDF( + keyPair->privKey, peerKey, PR_FALSE, NULL, NULL, mechanism, + tls13_GetHkdfMechanism(ss), CKA_DERIVE, 0, CKD_NULL, NULL, NULL); + if (!ss->ssl3.hs.dheSecret) { + ssl_MapLowLevelError(SSL_ERROR_KEY_EXCHANGE_FAILURE); + goto loser; + } + 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; +} + +SECStatus +tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, + PRUint32 length, SSL3Hashes *hashesPtr) +{ + if (ss->sec.isServer && ss->ssl3.hs.zeroRttIgnore != ssl_0rtt_ignore_none) { + SSL_TRC(3, ("%d: TLS13[%d]: %s 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 certificate: + return tls13_HandleCertificate(ss, b, length); + + case certificate_request: + return tls13_HandleCertificateRequest(ss, b, length); + + case certificate_verify: + if (!hashesPtr) { + FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY, unexpected_message); + return SECFailure; + } + return tls13_HandleCertificateVerify(ss, b, length, hashesPtr); + + case encrypted_extensions: + return tls13_HandleEncryptedExtensions(ss, b, length); + + case new_session_ticket: + return tls13_HandleNewSessionTicket(ss, b, length); + + case finished: + if (!hashesPtr) { + FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, unexpected_message); + return SECFailure; + } + if (ss->sec.isServer) { + return tls13_ServerHandleFinished(ss, b, length, hashesPtr); + } else { + return tls13_ClientHandleFinished(ss, b, length, hashesPtr); + } + + 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))); + if (!sid->u.ssl3.keys.msIsWrapped) { + PORT_Assert(0); /* I think this can't happen. */ + return SECFailure; + } + + /* 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, it's coordinates are stored with the ticket. */ + if (ss->sec.isServer) { + const sslServerCert *serverCert; + + serverCert = ssl_FindServerCert(ss, &sid->certType); + PORT_Assert(serverCert); + wrapKey = ssl3_GetWrappingKey(ss, NULL, serverCert, + 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; + + /* unwrap the "master secret" which is actually RMS. */ + ss->ssl3.hs.resumptionMasterSecret = PK11_UnwrapSymKeyWithFlags( + wrapKey, sid->u.ssl3.masterWrapMech, + NULL, &wrappedMS, + CKM_SSL3_MASTER_KEY_DERIVE, + CKA_DERIVE, + tls13_GetHashSizeForHash(hashType), + CKF_SIGN | CKF_VERIFY); + PK11_FreeSymKey(wrapKey); + if (!ss->ssl3.hs.resumptionMasterSecret) { + return SECFailure; + } + + PRINT_KEY(50, (ss, "Recovered RMS", ss->ssl3.hs.resumptionMasterSecret)); + + return SECSuccess; +} + +/* Key Derivation Functions. + * + * Below is the key schedule from [draft-ietf-tls-tls13]. + * + * * The relevant functions from this file are indicated by tls13_Foo(). + * 0 + * | + * v + * PSK -> HKDF-Extract + * | + * v + * Early Secret ---> Derive-Secret(., "client early traffic secret", + * | ClientHello) + * | = client_early_traffic_secret + * v + * (EC)DHE -> HKDF-Extract + * | + * v + * Handshake Secret + * | + * +---------> Derive-Secret(., "client handshake traffic secret", + * | ClientHello...ServerHello) + * | = client_handshake_traffic_secret + * | + * +---------> Derive-Secret(., "server handshake traffic secret", + * | ClientHello...ServerHello) + * | = server_handshake_traffic_secret + * | + * v + * 0 -> HKDF-Extract + * | + * v + * Master Secret + * | + * +---------> Derive-Secret(., "client application traffic secret", + * | ClientHello...Server Finished) + * | = client_traffic_secret_0 + * | + * +---------> Derive-Secret(., "server application traffic secret", + * | ClientHello...Server Finished) + * | = server_traffic_secret_0 + * | + * +---------> Derive-Secret(., "exporter master secret", + * | ClientHello...Client Finished) + * | = exporter_secret + * | + * +---------> Derive-Secret(., "resumption master secret", + * ClientHello...Client Finished) + * = resumption_secret + * + */ + +static SECStatus +tls13_ComputeEarlySecrets(sslSocket *ss) +{ + SECStatus rv = SECSuccess; + + SSL_TRC(5, ("%d: TLS13[%d]: compute early secrets (%s)", + SSL_GETPID(), ss->fd, SSL_ROLE(ss))); + + /* Extract off the resumptionMasterSecret (if present), else pass the NULL + * resumptionMasterSecret which will be internally translated to zeroes. */ + PORT_Assert(!ss->ssl3.hs.currentSecret); + rv = tls13_HkdfExtract(NULL, ss->ssl3.hs.resumptionMasterSecret, + tls13_GetHash(ss), &ss->ssl3.hs.currentSecret); + if (rv != SECSuccess) { + return SECFailure; + } + + PORT_Assert(ss->statelessResume == (ss->ssl3.hs.resumptionMasterSecret != NULL)); + if (ss->statelessResume) { + PRUint8 buf[1] = { 0 }; + SSL3Hashes hashes; + + PK11_FreeSymKey(ss->ssl3.hs.resumptionMasterSecret); + ss->ssl3.hs.resumptionMasterSecret = NULL; + + rv = PK11_HashBuf(ssl3_HashTypeToOID(tls13_GetHash(ss)), + hashes.u.raw, buf, 0); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + hashes.len = tls13_GetHashSize(ss); + + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + NULL, kHkdfLabelPskBinderKey, &hashes, + &ss->ssl3.hs.pskBinderKey); + if (rv != SECSuccess) { + return SECFailure; + } + + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + NULL, kHkdfLabelEarlyExporterSecret, + &hashes, &ss->ssl3.hs.earlyExporterSecret); + if (rv != SECSuccess) { + return SECFailure; + } + } else { + PORT_Assert(!ss->ssl3.hs.resumptionMasterSecret); + } + + return SECSuccess; +} + +static SECStatus +tls13_ComputeHandshakeSecrets(sslSocket *ss) +{ + SECStatus rv; + PK11SymKey *newSecret = NULL; + + SSL_TRC(5, ("%d: TLS13[%d]: compute handshake secrets (%s)", + SSL_GETPID(), ss->fd, SSL_ROLE(ss))); + + /* First update |currentSecret| to add |dheSecret|, if any. */ + PORT_Assert(ss->ssl3.hs.currentSecret); + PORT_Assert(ss->ssl3.hs.dheSecret); + rv = tls13_HkdfExtract(ss->ssl3.hs.currentSecret, ss->ssl3.hs.dheSecret, + tls13_GetHash(ss), &newSecret); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return rv; + } + PK11_FreeSymKey(ss->ssl3.hs.dheSecret); + ss->ssl3.hs.dheSecret = NULL; + PK11_FreeSymKey(ss->ssl3.hs.currentSecret); + ss->ssl3.hs.currentSecret = newSecret; + + /* Now compute |*HsTrafficSecret| */ + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + kHkdfLabelClient, + kHkdfLabelHandshakeTrafficSecret, NULL, + &ss->ssl3.hs.clientHsTrafficSecret); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return rv; + } + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + kHkdfLabelServer, + kHkdfLabelHandshakeTrafficSecret, NULL, + &ss->ssl3.hs.serverHsTrafficSecret); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return rv; + } + + 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_HkdfExtract(ss->ssl3.hs.currentSecret, + NULL, + tls13_GetHash(ss), + &newSecret); + + 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_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + kHkdfLabelClient, + kHkdfLabelApplicationTrafficSecret, + NULL, + &ss->ssl3.hs.clientTrafficSecret); + if (rv != SECSuccess) { + return SECFailure; + } + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + kHkdfLabelServer, + kHkdfLabelApplicationTrafficSecret, + NULL, + &ss->ssl3.hs.serverTrafficSecret); + if (rv != SECSuccess) { + return SECFailure; + } + + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + NULL, kHkdfLabelExporterMasterSecret, + NULL, &ss->ssl3.hs.exporterSecret); + if (rv != SECSuccess) { + return SECFailure; + } + + return SECSuccess; +} + +static SECStatus +tls13_ComputeFinalSecrets(sslSocket *ss) +{ + SECStatus rv; + PK11SymKey *resumptionMasterSecret = NULL; + + PORT_Assert(!ss->ssl3.crSpec->master_secret); + PORT_Assert(!ss->ssl3.cwSpec->master_secret); + + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + NULL, kHkdfLabelResumptionMasterSecret, + NULL, &resumptionMasterSecret); + PK11_FreeSymKey(ss->ssl3.hs.currentSecret); + ss->ssl3.hs.currentSecret = NULL; + if (rv != SECSuccess) { + return SECFailure; + } + + /* This is pretty gross. TLS 1.3 uses a number of master secrets: + * The master secret to generate the keys and then the resumption + * master secret for future connections. To make this work without + * refactoring too much of the SSLv3 code, we store the RMS in + * |crSpec->master_secret| and |cwSpec->master_secret|. + */ + ss->ssl3.crSpec->master_secret = resumptionMasterSecret; + ss->ssl3.cwSpec->master_secret = + PK11_ReferenceSymKey(ss->ssl3.crSpec->master_secret); + + 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; +} + +/* 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; + } + + if (tls13_GetHashForCipherSuite(sid->u.ssl3.cipherSuite) != tls13_GetHashForCipherSuite(ss->ssl3.hs.cipher_suite)) { + 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->certType); + if (!sc || !sc->serverCert) { + return PR_FALSE; + } + + return PR_TRUE; +} + +static PRBool +tls13_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; +} + +static PRBool +tls13_CanNegotiateZeroRtt(sslSocket *ss, const sslSessionID *sid) +{ + PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_sent); + + if (!sid) + return PR_FALSE; + PORT_Assert(ss->statelessResume); + if (!ss->statelessResume) + return PR_FALSE; + if (ss->ssl3.hs.cipher_suite != sid->u.ssl3.cipherSuite) + return PR_FALSE; + if (!ss->opt.enable0RttData) + return PR_FALSE; + if (!(sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data)) + return PR_FALSE; + if (SECITEM_CompareItem(&ss->xtnData.nextProto, + &sid->u.ssl3.alpnSelection) != 0) + 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 we rejected 0-RTT on the first ClientHello, then we can just say that + * there is no 0-RTT for the second. We shouldn't get any more. Reset the + * ignore state so that we treat decryption failure 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; + 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->statelessResume); + ss->ssl3.hs.zeroRttState = ssl_0rtt_accepted; + ss->ssl3.hs.zeroRttIgnore = ssl_0rtt_ignore_none; +} + +/* 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, TLS13KeyShareEntry **clientShare) +{ + unsigned int index; + TLS13KeyShareEntry *entry = NULL; + const sslNamedGroupDef *preferredGroup = NULL; + + /* We insist on DHE. */ + if (ss->statelessResume) { + 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; + } + 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 ? "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)); + + if (!entry) { + return tls13_SendHelloRetryRequest(ss, preferredGroup); + } + + PORT_Assert(preferredGroup == entry->group); + *clientShare = entry; + + 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 (cert->certType.authType == ssl_auth_rsa_pss || + cert->certType.authType == ssl_auth_rsa_decrypt) { + continue; + } + + rv = ssl_PickSignatureScheme(ss, + cert->serverKeyPair->pubKey, + cert->serverKeyPair->privKey, + ss->xtnData.clientSigSchemes, + ss->xtnData.numClientSigScheme, + PR_FALSE); + if (rv == SECSuccess) { + /* Found one. */ + ss->sec.serverCert = cert; + ss->sec.authType = cert->certType.authType; + ss->ssl3.hs.kea_def_mutable.authKeyType = cert->certType.authType; + ss->sec.authKeyBits = cert->serverKeyBits; + return SECSuccess; + } + } + + FATAL_ERROR(ss, SSL_ERROR_UNSUPPORTED_SIGNATURE_ALGORITHM, + handshake_failure); + return SECFailure; +} + +static SECStatus +tls13_NegotiateAuthentication(sslSocket *ss) +{ + SECStatus rv; + + if (ss->statelessResume) { + SSL_TRC(3, ("%d: TLS13[%d]: selected PSK authentication", + SSL_GETPID(), ss->fd)); + ss->ssl3.hs.signatureScheme = ssl_sig_none; + ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk; + return SECSuccess; + } + + SSL_TRC(3, ("%d: TLS13[%d]: selected certificate authentication", + SSL_GETPID(), ss->fd)); + /* We've now established that we need to sign.... */ + rv = tls13_SelectServerCert(ss); + if (rv != SECSuccess) { + return SECFailure; + } + ss->ssl3.hs.kea_def_mutable.authKeyType = + ss->sec.serverCert->certType.authType; + 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) +{ + SECStatus rv; + SSL3Statistics *ssl3stats = SSL_GetStatistics(); + TLS13KeyShareEntry *clientShare = NULL; + int j; + ssl3CipherSuite previousCipherSuite; + + if (ssl3_ExtensionNegotiated(ss, ssl_tls13_early_data_xtn)) { + ss->ssl3.hs.zeroRttState = ssl_0rtt_sent; + + if (IS_DTLS(ss)) { + /* Save the null spec, which we should be currently reading. We will + * use this when 0-RTT sending is over. */ + ssl_GetSpecReadLock(ss); + ss->ssl3.hs.nullSpec = ss->ssl3.crSpec; + tls13_CipherSpecAddRef(ss->ssl3.hs.nullSpec); + PORT_Assert(ss->ssl3.hs.nullSpec->cipher_def->cipher == cipher_null); + ssl_ReleaseSpecReadLock(ss); + } + } + +#ifndef PARANOID + /* Look for a matching cipher suite. */ + j = ssl3_config_match_init(ss); + if (j <= 0) { /* no ciphers are working/supported by PK11 */ + FATAL_ERROR(ss, PORT_GetError(), internal_error); + goto loser; + } +#endif + + previousCipherSuite = ss->ssl3.hs.cipher_suite; + rv = ssl3_NegotiateCipherSuite(ss, suites, PR_FALSE); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SSL_ERROR_NO_CYPHER_OVERLAP, 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 && + ss->ssl3.hs.cipher_suite != previousCipherSuite) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CLIENT_HELLO, handshake_failure); + 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, &clientShare); + if (rv != SECSuccess) { + goto loser; + } + + /* If we didn't find a client key share, we have to retry. */ + if (!clientShare) { + if (sid) { /* Free the sid. */ + ss->sec.uncache(sid); + 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->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; + } + + 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.serverCert = ssl_FindServerCert(ss, &sid->certType); + PORT_Assert(ss->sec.serverCert); + ss->sec.localCert = CERT_DupCertificate(ss->sec.serverCert->serverCert); + if (sid->peerCert != NULL) { + ss->sec.peerCert = CERT_DupCertificate(sid->peerCert); + } + ssl3_RegisterExtensionSender( + ss, &ss->xtnData, + ssl_tls13_pre_shared_key_xtn, tls13_ServerSendPreSharedKeyXtn); + + tls13_NegotiateZeroRtt(ss, sid); + } else { + if (sid) { /* we had a sid, but it's no longer valid, free it */ + SSL_AtomicIncrementLong(&ssl3stats->hch_sid_cache_not_ok); + if (ss->sec.uncache) + ss->sec.uncache(sid); + ssl_FreeSID(sid); + sid = NULL; + } + tls13_NegotiateZeroRtt(ss, NULL); + } + + /* Need to compute early secrets. */ + rv = tls13_ComputeEarlySecrets(ss); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + + /* Now that we have the binder key check the binder. */ + if (ss->statelessResume) { + SSL3Hashes hashes; + + rv = tls13_ComputePskBinderHash(ss, ss->xtnData.pskBinderPrefixLen, + &hashes); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + + rv = tls13_VerifyFinished(ss, client_hello, + ss->ssl3.hs.pskBinderKey, + 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); + ss->sec.uncache(sid); + ssl_FreeSID(sid); + } else { + 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_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + kHkdfLabelClient, + kHkdfLabelEarlyTrafficSecret, + NULL, /* Current running hash. */ + &ss->ssl3.hs.clientEarlyTrafficSecret); + 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; + } + + return SECSuccess; + +loser: + if (sid) { + ss->sec.uncache(sid); + ssl_FreeSID(sid); + } + return SECFailure; +} + +static SECStatus +tls13_SendHelloRetryRequest(sslSocket *ss, const sslNamedGroupDef *selectedGroup) +{ + SECStatus rv; + + SSL_TRC(3, ("%d: TLS13[%d]: send hello retry request handshake", + SSL_GETPID(), ss->fd)); + + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + /* We asked already, but made no progress. */ + if (ss->ssl3.hs.helloRetry) { + FATAL_ERROR(ss, SSL_ERROR_BAD_2ND_CLIENT_HELLO, illegal_parameter); + return SECFailure; + } + + ssl_GetXmitBufLock(ss); + rv = ssl3_AppendHandshakeHeader(ss, hello_retry_request, + 2 + /* version */ + 2 + /* extension length */ + 2 + /* group extension id */ + 2 + /* group extension length */ + 2 /* group */); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + + rv = ssl3_AppendHandshakeNumber( + ss, tls13_EncodeDraftVersion(ss->version), 2); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + + /* Length of extensions. */ + rv = ssl3_AppendHandshakeNumber(ss, 2 + 2 + 2, 2); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + + /* Key share extension - currently the only reason we send this. */ + rv = ssl3_AppendHandshakeNumber(ss, ssl_tls13_key_share_xtn, 2); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + /* Key share extension length. */ + rv = ssl3_AppendHandshakeNumber(ss, 2, 2); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + rv = ssl3_AppendHandshakeNumber(ss, selectedGroup->name, 2); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + goto loser; + } + + rv = ssl3_FlushHandshake(ss, 0); + if (rv != SECSuccess) { + goto loser; /* error code set by ssl3_FlushHandshake */ + } + 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: + 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_CreateKeyShare(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); + 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; + int calen; + SECItem *names; + int nnames; + SECItem *name; + int i; + PRUint8 sigSchemes[MAX_SIGNATURE_SCHEMES * 2]; + unsigned int sigSchemesLength = 0; + int length; + + SSL_TRC(3, ("%d: TLS13[%d]: begin send certificate_request", + SSL_GETPID(), ss->fd)); + + rv = ssl3_EncodeSigAlgs(ss, sigSchemes, sizeof(sigSchemes), + &sigSchemesLength); + if (rv != SECSuccess) { + return rv; + } + + ssl3_GetCertificateRequestCAs(ss, &calen, &names, &nnames); + length = 1 + 0 /* length byte for empty request context */ + + 2 + sigSchemesLength + 2 + calen + 2; + + rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } + rv = ssl3_AppendHandshakeNumber(ss, 0, 1); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } + rv = ssl3_AppendHandshakeVariable(ss, sigSchemes, sigSchemesLength, 2); + 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. */ + } + } + rv = ssl3_AppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) { + return rv; /* err set by AppendHandshake. */ + } + + return SECSuccess; +} + +SECStatus +tls13_HandleHelloRetryRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +{ + SECStatus rv; + PRInt32 tmp; + SSL3ProtocolVersion version; + + 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; + } + + /* Client only. */ + rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST, + wait_server_hello); + if (rv != SECSuccess) { + return SECFailure; + } + + /* Fool me once, shame on you; fool me twice... */ + if (ss->ssl3.hs.helloRetry) { + FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_HELLO_RETRY_REQUEST, + unexpected_message); + return SECFailure; + } + + if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent) { + /* Oh well, back to the start. */ + tls13_SetNullCipherSpec(ss, &ss->ssl3.cwSpec); + ss->ssl3.hs.zeroRttState = ssl_0rtt_ignored; + } else { + PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none); + } + + /* Version. */ + rv = ssl_ClientReadVersion(ss, &b, &length, &version); + if (rv != SECSuccess) { + return SECFailure; /* alert already sent */ + } + if (version > ss->vrange.max || version < SSL_LIBRARY_VERSION_TLS_1_3) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST, + protocol_version); + return SECFailure; + } + + /* Extensions. */ + tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); + if (tmp < 0) { + return SECFailure; /* error code already set */ + } + /* Extensions must be non-empty and use the remainder of the message. + * This means that a HelloRetryRequest cannot be a no-op: we must have an + * extension, it must be one that we understand and recognize as being valid + * for HelloRetryRequest, and all the extensions we permit cause us to + * modify our ClientHello in some way. */ + if (!tmp || tmp != length) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_HELLO_RETRY_REQUEST, + decode_error); + return SECFailure; + } + + rv = ssl3_HandleExtensions(ss, &b, &length, hello_retry_request); + if (rv != SECSuccess) { + return SECFailure; /* Error code set below */ + } + + ss->ssl3.hs.helloRetry = PR_TRUE; + + ssl_GetXmitBufLock(ss); + rv = ssl3_SendClientHello(ss, client_hello_retry); + ssl_ReleaseXmitBufLock(ss); + if (rv != SECSuccess) { + return SECFailure; + } + + return SECSuccess; +} + +static SECStatus +tls13_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +{ + SECStatus rv; + TLS13CertificateRequest *certRequest = NULL; + SECItem context = { siBuffer, NULL, 0 }; + PLArenaPool *arena; + PRInt32 extensionsLength; + + 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 */ + rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST, + wait_cert_request); + if (rv != SECSuccess) { + return SECFailure; + } + + PORT_Assert(ss->ssl3.clientCertChain == NULL); + PORT_Assert(ss->ssl3.clientCertificate == NULL); + PORT_Assert(ss->ssl3.clientPrivateKey == NULL); + PORT_Assert(ss->ssl3.hs.certificateRequest == NULL); + + arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE); + if (!arena) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + + rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length); + if (rv != SECSuccess) + goto loser; + + /* We don't support post-handshake client auth, the certificate request + * context must always be null. */ + if (context.len > 0) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, illegal_parameter); + goto loser; + } + + certRequest = PORT_ArenaZNew(arena, TLS13CertificateRequest); + if (!certRequest) + goto loser; + certRequest->arena = arena; + certRequest->ca_list.arena = arena; + + rv = ssl_ParseSignatureSchemes(ss, arena, + &certRequest->signatureSchemes, + &certRequest->signatureSchemeCount, + &b, &length); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, + decode_error); + goto loser; + } + + rv = ssl3_ParseCertificateRequestCAs(ss, &b, &length, arena, + &certRequest->ca_list); + if (rv != SECSuccess) + goto loser; /* alert already sent */ + + /* Verify that the extensions length is correct. */ + extensionsLength = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); + if (extensionsLength < 0) { + goto loser; /* alert already sent */ + } + if (extensionsLength != length) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_CERT_REQUEST, + illegal_parameter); + goto loser; + } + + rv = SECITEM_CopyItem(arena, &certRequest->context, &context); + if (rv != SECSuccess) + goto loser; + + TLS13_SET_HS_STATE(ss, wait_server_cert); + ss->ssl3.hs.certificateRequest = certRequest; + + return SECSuccess; + +loser: + PORT_FreeArena(arena, PR_FALSE); + return SECFailure; +} + +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, + CipherSpecWrite, PR_FALSE); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + ss->ssl3.hs.shortHeaders = ssl3_ExtensionNegotiated( + ss, ssl_tls13_short_header_xtn); + + if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) { + rv = ssl3_RegisterExtensionSender(ss, &ss->xtnData, ssl_tls13_early_data_xtn, + tls13_ServerSendEarlyDataXtn); + if (rv != SECSuccess) { + return SECFailure; /* Error code set already. */ + } + } + + rv = tls13_SendEncryptedExtensions(ss); + if (rv != SECSuccess) { + return SECFailure; /* error code is set. */ + } + + if (ss->opt.requestCertificate) { + 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. */ + } + + 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_SendServerHello(ss); + if (rv != SECSuccess) { + return rv; /* err code is set. */ + } + + 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, + CipherSpecWrite, PR_FALSE); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) { + rv = tls13_SetCipherSpec(ss, + TrafficKeyEarlyApplicationData, + CipherSpecRead, PR_TRUE); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + } else { + PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_none || + ss->ssl3.hs.zeroRttState == ssl_0rtt_ignored); + + rv = tls13_SetCipherSpec(ss, + TrafficKeyHandshake, + CipherSpecRead, PR_FALSE); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + } + + TLS13_SET_HS_STATE(ss, + ss->opt.requestCertificate ? wait_client_cert + : wait_finished); + return SECSuccess; +} + +SECStatus +tls13_HandleServerHelloPart2(sslSocket *ss) +{ + SECStatus rv; + sslSessionID *sid = ss->sec.ci.sid; + SSL3Statistics *ssl3stats = SSL_GetStatistics(); + + if (ssl3_ExtensionNegotiated(ss, ssl_tls13_pre_shared_key_xtn)) { + PORT_Assert(ss->statelessResume); + } else { + if (ss->ssl3.hs.currentSecret) { + PORT_Assert(ss->statelessResume); + PK11_FreeSymKey(ss->ssl3.hs.currentSecret); + ss->ssl3.hs.currentSecret = NULL; + } + ss->statelessResume = PR_FALSE; + } + + if (ss->statelessResume) { + 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->statelessResume) { + /* PSK */ + ss->ssl3.hs.kea_def_mutable.authKeyType = ssl_auth_psk; + 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 { + /* !PSK */ + if (ssl3_ClientExtensionAdvertised(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. */ + ss->sec.uncache(sid); + } + } + + if (!ss->ssl3.hs.currentSecret) { + PORT_Assert(!ss->statelessResume); + + /* If we don't already have the Early Secret we need to make it + * now. */ + rv = tls13_ComputeEarlySecrets(ss); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + } + + /* 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_ComputeHandshakeSecrets(ss); + if (rv != SECSuccess) { + return SECFailure; /* error code is set. */ + } + + ss->ssl3.hs.shortHeaders = ssl3_ExtensionNegotiated( + ss, ssl_tls13_short_header_xtn); + + rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake, + CipherSpecRead, 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); + 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 }; + PRInt32 extensionsLen = 0; + PRUint32 maxBytes = 65535; + + 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); + } + + /* Get the extensions length. This only applies to the leaf cert, + * because we don't yet send extensions for non-leaf certs. */ + extensionsLen = ssl3_CallHelloExtensionSenders( + ss, PR_FALSE, maxBytes, &ss->xtnData.certificateSenders[0]); + + if (!ss->sec.isServer) { + PORT_Assert(ss->ssl3.hs.certificateRequest); + context = ss->ssl3.hs.certificateRequest->context; + } + if (certChain) { + for (i = 0; i < certChain->len; i++) { + certChainLen += + 3 + certChain->certs[i].len + /* cert length + cert */ + 2 + (!i ? extensionsLen : 0); /* extensions length + extensions */ + } + } + + rv = ssl3_AppendHandshakeHeader(ss, 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) { + return SECFailure; /* err set by AppendHandshake. */ + } + + rv = ssl3_AppendHandshakeNumber(ss, certChainLen, 3); + if (rv != SECSuccess) { + return SECFailure; /* err set by AppendHandshake. */ + } + if (certChain) { + for (i = 0; i < certChain->len; i++) { + PRInt32 sentLen; + + rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data, + certChain->certs[i].len, 3); + if (rv != SECSuccess) { + return SECFailure; /* err set by AppendHandshake. */ + } + + if (i) { + /* Not end-entity. */ + rv = ssl3_AppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) { + return SECFailure; /* err set by AppendHandshake. */ + } + continue; + } + + /* End-entity, send extensions. */ + rv = ssl3_AppendHandshakeNumber(ss, extensionsLen, 2); + if (rv != SECSuccess) { + return SECFailure; /* err set by AppendHandshake. */ + } + + sentLen = ssl3_CallHelloExtensionSenders( + ss, PR_TRUE, extensionsLen, + &ss->xtnData.certificateSenders[0]); + PORT_Assert(sentLen == extensionsLen); + if (sentLen != extensionsLen) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + } + } + + return SECSuccess; +} + +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, + 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, SSL3Opaque *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) { + 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; + + /* Process the context string */ + rv = ssl3_ConsumeHandshakeVariable(ss, &context, 1, &b, &length); + if (rv != SECSuccess) + return SECFailure; + + if (context.len) { + /* The context string MUST be empty */ + 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 */ +} + +void +tls13_CipherSpecAddRef(ssl3CipherSpec *spec) +{ + ++spec->refCt; + SSL_TRC(10, ("%d: TLS13[-]: Increment ref ct for spec %d. new ct = %d", + SSL_GETPID(), spec, spec->refCt)); +} + +/* This function is never called on a spec which is on the + * cipherSpecs list. */ +void +tls13_CipherSpecRelease(ssl3CipherSpec *spec) +{ + PORT_Assert(spec->refCt > 0); + --spec->refCt; + SSL_TRC(10, ("%d: TLS13[-]: decrement refct for spec %d. phase=%s new ct = %d", + SSL_GETPID(), spec, spec->phase, spec->refCt)); + if (!spec->refCt) { + SSL_TRC(10, ("%d: TLS13[-]: Freeing spec %d. phase=%s", + SSL_GETPID(), spec, spec->phase)); + PR_REMOVE_LINK(&spec->link); + ssl3_DestroyCipherSpec(spec, PR_TRUE); + PORT_Free(spec); + } +} + +/* 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)) + */ +static SECStatus +tls13_DeriveSecret(sslSocket *ss, PK11SymKey *key, + const char *prefix, + const char *suffix, + const SSL3Hashes *hashes, + PK11SymKey **dest) +{ + SECStatus rv; + SSL3Hashes hashesTmp; + 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)); + if (!hashes) { + rv = tls13_ComputeHandshakeHashes(ss, &hashesTmp); + if (rv != SECSuccess) { + PORT_Assert(0); /* Should never fail */ + ssl_MapLowLevelError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + hashes = &hashesTmp; + } + + rv = tls13_HkdfExpandLabel(key, tls13_GetHash(ss), + hashes->u.raw, hashes->len, + label, strlen(label), + tls13_GetHkdfMechanism(ss), + tls13_GetHashSize(ss), dest); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + return SECSuccess; +} + +/* Derive traffic keys for the next cipher spec in the queue. */ +static SECStatus +tls13_DeriveTrafficKeys(sslSocket *ss, ssl3CipherSpec *spec, + TrafficKeyType type, + CipherSpecDirection direction, + PRBool deleteSecret) +{ + size_t keySize = spec->cipher_def->key_size; + size_t ivSize = spec->cipher_def->iv_size + + spec->cipher_def->explicit_nonce_size; /* This isn't always going to + * work, but it does for + * AES-GCM */ + CK_MECHANISM_TYPE bulkAlgorithm = ssl3_Alg2Mech(spec->cipher_def->calg); + PK11SymKey **prkp = NULL; + PK11SymKey *prk = NULL; + PRBool clientKey; + ssl3KeyMaterial *target; + const char *phase; + 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"; + + if (ss->sec.isServer ^ (direction == CipherSpecWrite)) { + clientKey = PR_TRUE; + target = &spec->client; + } else { + clientKey = PR_FALSE; + target = &spec->server; + } + + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + switch (type) { + case TrafficKeyEarlyApplicationData: + PORT_Assert(clientKey); + phase = kHkdfPhaseEarlyApplicationDataKeys; + prkp = &ss->ssl3.hs.clientEarlyTrafficSecret; + break; + case TrafficKeyHandshake: + phase = kHkdfPhaseHandshakeKeys; + prkp = clientKey ? &ss->ssl3.hs.clientHsTrafficSecret : &ss->ssl3.hs.serverHsTrafficSecret; + break; + case TrafficKeyApplicationData: + phase = kHkdfPhaseApplicationDataKeys; + prkp = clientKey ? &ss->ssl3.hs.clientTrafficSecret : &ss->ssl3.hs.serverTrafficSecret; + 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 phase='%s'", + SSL_GETPID(), ss->fd, + (direction == CipherSpecWrite) ? "write" : "read", phase)); + PORT_Assert(phase); + spec->phase = phase; + + rv = tls13_HkdfExpandLabel(prk, tls13_GetHash(ss), + NULL, 0, + kHkdfPurposeKey, strlen(kHkdfPurposeKey), + bulkAlgorithm, keySize, + &target->write_key); + 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), + target->write_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; +} + +static SECStatus +tls13_SetupPendingCipherSpec(sslSocket *ss) +{ + ssl3CipherSpec *pSpec; + ssl3CipherSuite suite = ss->ssl3.hs.cipher_suite; + const ssl3BulkCipherDef *bulk = ssl_GetBulkCipherDef( + ssl_LookupCipherSuiteDef(suite)); + + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + + ssl_GetSpecWriteLock(ss); /*******************************/ + + pSpec = ss->ssl3.pwSpec; + /* Version isn't set when we send 0-RTT data. */ + pSpec->version = PR_MAX(SSL_LIBRARY_VERSION_TLS_1_3, ss->version); + + SSL_TRC(3, ("%d: TLS13[%d]: Set Pending Cipher Suite to 0x%04x", + SSL_GETPID(), ss->fd, suite)); + pSpec->cipher_def = bulk; + + ssl_ReleaseSpecWriteLock(ss); /*******************************/ + return SECSuccess; +} + +/* Install a new cipher spec for this direction. */ +static SECStatus +tls13_SetCipherSpec(sslSocket *ss, TrafficKeyType type, + CipherSpecDirection direction, PRBool deleteSecret) +{ + SECStatus rv; + ssl3CipherSpec *spec = NULL; + ssl3CipherSpec **specp = (direction == CipherSpecRead) ? &ss->ssl3.crSpec : &ss->ssl3.cwSpec; + /* 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 = PORT_ZNew(ssl3CipherSpec); + if (!spec) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + return SECFailure; + } + spec->refCt = 1; + PR_APPEND_LINK(&spec->link, &ss->ssl3.hs.cipherSpecs); + ss->ssl3.pwSpec = ss->ssl3.prSpec = spec; + + rv = tls13_SetupPendingCipherSpec(ss); + if (rv != SECSuccess) + return SECFailure; + + switch (spec->cipher_def->calg) { + case calg_aes_gcm: + spec->aead = tls13_AESGCM; + break; + case calg_chacha20: + spec->aead = tls13_ChaCha20Poly1305; + break; + default: + PORT_Assert(0); + return SECFailure; + break; + } + + rv = tls13_DeriveTrafficKeys(ss, spec, type, direction, + deleteSecret); + if (rv != SECSuccess) { + return SECFailure; + } + + /* We use the epoch for cipher suite identification, so increment + * it in both TLS and DTLS. */ + if ((*specp)->epoch == PR_UINT16_MAX) { + return SECFailure; + } + spec->epoch = (*specp)->epoch + 1; + + if (!IS_DTLS(ss)) { + spec->read_seq_num = spec->write_seq_num = 0; + } else { + /* The sequence number has the high 16 bits as the epoch. */ + spec->read_seq_num = spec->write_seq_num = + (sslSequenceNumber)spec->epoch << 48; + + dtls_InitRecvdRecords(&spec->recvdRecords); + } + + /* Now that we've set almost everything up, finally cut over. */ + ssl_GetSpecWriteLock(ss); + tls13_CipherSpecRelease(*specp); /* May delete old cipher. */ + *specp = spec; /* Overwrite. */ + ssl_ReleaseSpecWriteLock(ss); + + SSL_TRC(3, ("%d: TLS13[%d]: %s installed key for phase='%s'.%d dir=%s", + SSL_GETPID(), ss->fd, SSL_ROLE(ss), + spec->phase, spec->epoch, + direction == CipherSpecRead ? "read" : "write")); + + return SECSuccess; +} + +static SECStatus +tls13_ComputeHandshakeHashes(sslSocket *ss, + SSL3Hashes *hashes) +{ + SECStatus rv; + PK11Context *ctx = NULL; + + 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; + } + + PRINT_BUF(10, (NULL, "Handshake hash computed over saved messages", + ss->ssl3.hs.messages.buf, + ss->ssl3.hs.messages.len)); + + if (PK11_DigestOp(ctx, + ss->ssl3.hs.messages.buf, + ss->ssl3.hs.messages.len) != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + goto loser; + } + } 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; + } + PORT_Assert(hashes->len == tls13_GetHashSize(ss)); + PK11_DestroyContext(ctx, PR_TRUE); + + return SECSuccess; + +loser: + PK11_DestroyContext(ctx, PR_TRUE); + return SECFailure; +} + +void +tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *offer) +{ + SECITEM_ZfreeItem(&offer->key_exchange, PR_FALSE); + PORT_ZFree(offer, sizeof(*offer)); +} + +void +tls13_DestroyKeyShares(PRCList *list) +{ + PRCList *cur_p; + + 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)); + } +} + +void +tls13_DestroyCipherSpecs(PRCList *list) +{ + PRCList *cur_p; + + while (!PR_CLIST_IS_EMPTY(list)) { + cur_p = PR_LIST_TAIL(list); + PR_REMOVE_LINK(cur_p); + ssl3_DestroyCipherSpec((ssl3CipherSpec *)cur_p, PR_FALSE); + PORT_Free(cur_p); + } +} + +/* 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(ssl3KeyMaterial *keys, + const unsigned char *seqNumBuf, unsigned int seqNumLen, + unsigned char *nonce, unsigned int nonceLen) +{ + size_t i; + + PORT_Assert(nonceLen == 12); + memcpy(nonce, keys->write_iv, 12); + + /* XOR the last 8 bytes of the IV with the sequence number. */ + PORT_Assert(seqNumLen == 8); + for (i = 0; i < 8; ++i) { + nonce[4 + i] ^= seqNumBuf[i]; + } +} + +/* Implement the SSLAEADCipher interface defined in sslimpl.h. + * + * That interface takes the additional data (see below) and reinterprets that as + * a sequence number. In TLS 1.3 there is no additional data so this value is + * just the encoded sequence number. + */ +static SECStatus +tls13_AEAD(ssl3KeyMaterial *keys, PRBool doDecrypt, + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + CK_MECHANISM_TYPE mechanism, + unsigned char *aeadParams, unsigned int aeadParamLength) +{ + SECStatus rv; + unsigned int uOutLen = 0; + SECItem param = { + siBuffer, aeadParams, aeadParamLength + }; + + if (doDecrypt) { + rv = PK11_Decrypt(keys->write_key, mechanism, ¶m, + out, &uOutLen, maxout, in, inlen); + } else { + rv = PK11_Encrypt(keys->write_key, mechanism, ¶m, + out, &uOutLen, maxout, in, inlen); + } + *outlen = (int)uOutLen; + + return rv; +} + +static SECStatus +tls13_AESGCM(ssl3KeyMaterial *keys, + PRBool doDecrypt, + unsigned char *out, + int *outlen, + int maxout, + const unsigned char *in, + int inlen, + const unsigned char *additionalData, + int additionalDataLen) +{ + CK_GCM_PARAMS gcmParams; + unsigned char nonce[12]; + + memset(&gcmParams, 0, sizeof(gcmParams)); + gcmParams.pIv = nonce; + gcmParams.ulIvLen = sizeof(nonce); + gcmParams.pAAD = NULL; + gcmParams.ulAADLen = 0; + gcmParams.ulTagBits = 128; /* GCM measures tag length in bits. */ + + tls13_WriteNonce(keys, additionalData, additionalDataLen, + nonce, sizeof(nonce)); + return tls13_AEAD(keys, doDecrypt, out, outlen, maxout, in, inlen, + CKM_AES_GCM, + (unsigned char *)&gcmParams, sizeof(gcmParams)); +} + +static SECStatus +tls13_ChaCha20Poly1305(ssl3KeyMaterial *keys, PRBool doDecrypt, + unsigned char *out, int *outlen, int maxout, + const unsigned char *in, int inlen, + const unsigned char *additionalData, + int additionalDataLen) +{ + CK_NSS_AEAD_PARAMS aeadParams; + unsigned char nonce[12]; + + memset(&aeadParams, 0, sizeof(aeadParams)); + aeadParams.pNonce = nonce; + aeadParams.ulNonceLen = sizeof(nonce); + aeadParams.pAAD = NULL; /* No AAD in TLS 1.3. */ + aeadParams.ulAADLen = 0; + aeadParams.ulTagLen = 16; /* The Poly1305 tag is 16 octets. */ + + tls13_WriteNonce(keys, additionalData, additionalDataLen, + nonce, sizeof(nonce)); + return tls13_AEAD(keys, doDecrypt, out, outlen, maxout, in, inlen, + CKM_NSS_CHACHA20_POLY1305, + (unsigned char *)&aeadParams, sizeof(aeadParams)); +} + +static SECStatus +tls13_HandleEncryptedExtensions(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +{ + SECStatus rv; + PRInt32 innerLength; + SECItem oldNpn = { 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; + } + + innerLength = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length); + if (innerLength < 0) { + 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 NPN value. Stash + * it for comparison. */ + if (ss->ssl3.hs.zeroRttState == ssl_0rtt_sent && + ss->xtnData.nextProtoState == SSL_NEXT_PROTO_EARLY_VALUE) { + oldNpn = ss->xtnData.nextProto; + ss->xtnData.nextProto.data = NULL; + ss->xtnData.nextProtoState = SSL_NEXT_PROTO_NO_SUPPORT; + } + rv = ssl3_HandleExtensions(ss, &b, &length, 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->statelessResume) { + /* 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(&oldNpn, &ss->xtnData.nextProto)) { + SECITEM_FreeItem(&oldNpn, 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(&oldNpn, 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); + } + + return SECSuccess; +} + +static SECStatus +tls13_SendEncryptedExtensions(sslSocket *ss) +{ + SECStatus rv; + PRInt32 extensions_len = 0; + PRInt32 sent_len = 0; + PRUint32 maxBytes = 65535; + + 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)); + + extensions_len = ssl3_CallHelloExtensionSenders( + ss, PR_FALSE, maxBytes, &ss->xtnData.encryptedExtensionsSenders[0]); + + rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions, + extensions_len + 2); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2); + if (rv != SECSuccess) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + sent_len = ssl3_CallHelloExtensionSenders( + ss, PR_TRUE, extensions_len, + &ss->xtnData.encryptedExtensionsSenders[0]); + PORT_Assert(sent_len == extensions_len); + if (sent_len != extensions_len) { + LOG_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE); + PORT_Assert(sent_len == 0); + return SECFailure; + } + + return SECSuccess; +} + +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, 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, SSL3Opaque *b, PRUint32 length, + SSL3Hashes *hashes) +{ + SECItem signed_hash = { siBuffer, NULL, 0 }; + SECStatus rv; + SSLSignatureScheme sigScheme; + SSLHashType hashAlg; + SSL3Hashes tbsHash; + + 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; + } + PORT_Assert(hashes); + + rv = ssl_ConsumeSignatureScheme(ss, &b, &length, &sigScheme); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_CERT_VERIFY); + return SECFailure; + } + + rv = ssl_CheckSignatureSchemeConsistency(ss, sigScheme, ss->sec.peerCert); + if (rv != SECSuccess) { + /* Error set already */ + 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; + } + + rv = ssl3_VerifySignedHashes(ss, sigScheme, &tbsHash, &signed_hash); + if (rv != SECSuccess) { + FATAL_ERROR(ss, PORT_GetError(), decrypt_error); + return SECFailure; + } + + /* Set the auth type. */ + if (!ss->sec.isServer) { + switch (ssl_SignatureSchemeToKeyType(sigScheme)) { + case rsaKey: + ss->sec.authType = ssl_auth_rsa_sign; + break; + case ecKey: + ss->sec.authType = ssl_auth_ecdsa; + break; + default: + PORT_Assert(PR_FALSE); + } + } + + /* Request a client certificate now if one was requested. */ + if (ss->ssl3.hs.certificateRequest) { + TLS13CertificateRequest *req = ss->ssl3.hs.certificateRequest; + + PORT_Assert(!ss->sec.isServer); + rv = ssl3_CompleteHandleCertificateRequest(ss, req->signatureSchemes, + req->signatureSchemeCount, + &req->ca_list); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return rv; + } + } + + TLS13_SET_HS_STATE(ss, wait_finished); + + return SECSuccess; +} + +static SECStatus +tls13_ComputePskBinderHash(sslSocket *ss, unsigned long prefixLength, + SSL3Hashes *hashes) +{ + SECStatus rv; + + PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(prefixLength <= ss->ssl3.hs.messages.len); + + PRINT_BUF(10, (NULL, "Handshake hash computed over ClientHello prefix", + ss->ssl3.hs.messages.buf, prefixLength)); + rv = PK11_HashBuf(ssl3_HashTypeToOID(tls13_GetHash(ss)), + hashes->u.raw, + ss->ssl3.hs.messages.buf, prefixLength); + if (rv != SECSuccess) { + ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE); + goto loser; + } + hashes->len = tls13_GetHashSize(ss); + + PRINT_BUF(10, (NULL, "PSK Binder hash", + hashes->u.raw, hashes->len)); + + return SECSuccess; + +loser: + return SECFailure; +} +/* Compute the PSK Binder This is kind of sneaky.*/ +SECStatus +tls13_ComputePskBinder(sslSocket *ss, PRBool sending, + unsigned int prefixLength, + PRUint8 *output, unsigned int *outputLen, + unsigned int maxOutputLen) +{ + SSL3Hashes hashes; + SECStatus rv; + + rv = tls13_ComputePskBinderHash(ss, prefixLength, &hashes); + if (rv != SECSuccess) + return SECFailure; + + return tls13_ComputeFinished(ss, ss->ssl3.hs.pskBinderKey, &hashes, + sending, output, outputLen, maxOutputLen); +} + +static SECStatus +tls13_ComputeFinished(sslSocket *ss, PK11SymKey *baseKey, + const SSL3Hashes *hashes, + PRBool sending, PRUint8 *output, unsigned int *outputLen, + unsigned int maxOutputLen) +{ + SECStatus rv; + PK11Context *hmacCtx = NULL; + CK_MECHANISM_TYPE macAlg = tls13_GetHmacMechanism(ss); + 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, + tls13_GetHash(ss), + NULL, 0, + label, strlen(label), + tls13_GetHmacMechanism(ss), + tls13_GetHashSize(ss), &secret); + if (rv != SECSuccess) { + goto abort; + } + + PORT_Assert(hashes->len == tls13_GetHashSize(ss)); + hmacCtx = PK11_CreateContextBySymKey(macAlg, CKA_SIGN, + secret, ¶m); + 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_GetHashSize(ss)); + rv = PK11_DigestFinal(hmacCtx, output, &outputLenUint, maxOutputLen); + if (rv != SECSuccess) + goto abort; + *outputLen = outputLenUint; + + PK11_FreeSymKey(secret); + PK11_DestroyContext(hmacCtx, PR_TRUE); + 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, &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, 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, SSL3HandshakeType message, + PK11SymKey *secret, + SSL3Opaque *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, 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 == 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_ClientHandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, + const SSL3Hashes *hashes) +{ + 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_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, + wait_finished); + if (rv != SECSuccess) { + return SECFailure; + } + + rv = tls13_VerifyFinished(ss, finished, + ss->ssl3.hs.serverHsTrafficSecret, + b, length, hashes); + if (rv != SECSuccess) + return SECFailure; + + return tls13_SendClientSecondRound(ss); +} + +static SECStatus +tls13_ServerHandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length, + const SSL3Hashes *hashes) +{ + SECStatus rv; + PK11SymKey *secret; + + 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)); + + rv = TLS13_CHECK_HS_STATE(ss, SSL_ERROR_RX_UNEXPECTED_FINISHED, wait_finished); + if (rv != SECSuccess) { + return SECFailure; + } + + if (TLS13_IN_HS_STATE(ss, wait_finished)) { + secret = ss->ssl3.hs.clientHsTrafficSecret; + } else { + secret = ss->ssl3.hs.clientEarlyTrafficSecret; + } + + rv = tls13_VerifyFinished(ss, finished, secret, b, length, hashes); + if (rv != SECSuccess) + return SECFailure; + + rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData, + CipherSpecRead, PR_TRUE); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + + rv = tls13_FinishHandshake(ss); + if (rv != SECSuccess) { + return SECFailure; /* Error code and alerts handled below */ + } + ssl_GetXmitBufLock(ss); + if (ss->opt.enableSessionTickets) { + rv = tls13_SendNewSessionTicket(ss); + if (rv != SECSuccess) { + ssl_ReleaseXmitBufLock(ss); + return SECFailure; /* Error code and alerts handled below */ + } + rv = ssl3_FlushHandshake(ss, 0); + } + ssl_ReleaseXmitBufLock(ss); + if (rv != SECSuccess) + return SECFailure; + + return SECSuccess; +} + +static SECStatus +tls13_FinishHandshake(sslSocket *ss) +{ + SECStatus rv; + + PORT_Assert(ss->opt.noLocks || ssl_HaveRecvBufLock(ss)); + PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss)); + PORT_Assert(ss->ssl3.hs.restartTarget == NULL); + + rv = tls13_ComputeFinalSecrets(ss); + if (rv != SECSuccess) + return SECFailure; + + /* 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); + + ssl_FinishHandshake(ss); + + return SECSuccess; +} + +/* Do the parts of sending the client's second round that require + * the XmitBuf lock. */ +static SECStatus +tls13_SendClientSecondFlight(sslSocket *ss, PRBool sendClientCert, + SSL3AlertDescription *sendAlert) +{ + SECStatus rv; + + PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss)); + + *sendAlert = internal_error; + + if (ss->ssl3.sendEmptyCert) { + ss->ssl3.sendEmptyCert = PR_FALSE; + rv = ssl3_SendEmptyCertificate(ss); + /* Don't send verify */ + if (rv != SECSuccess) { + return SECFailure; /* error code is set. */ + } + } else if (sendClientCert) { + rv = tls13_SendCertificate(ss); + if (rv != SECSuccess) { + return SECFailure; /* error code is set. */ + } + } + if (ss->ssl3.hs.certificateRequest) { + PORT_FreeArena(ss->ssl3.hs.certificateRequest->arena, PR_FALSE); + ss->ssl3.hs.certificateRequest = NULL; + } + + if (sendClientCert) { + rv = tls13_SendCertificateVerify(ss, ss->ssl3.clientPrivateKey); + SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey); + ss->ssl3.clientPrivateKey = NULL; + if (rv != SECSuccess) { + return SECFailure; /* err is set. */ + } + } + + rv = tls13_SendFinished(ss, ss->ssl3.hs.clientHsTrafficSecret); + if (rv != SECSuccess) { + return SECFailure; /* err code was set. */ + } + rv = ssl3_FlushHandshake(ss, IS_DTLS(ss) ? ssl_SEND_FLAG_NO_RETRANSMIT : 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. */ + *sendAlert = no_alert; + return SECFailure; + } + + rv = dtls_StartHolddownTimer(ss); + if (rv != SECSuccess) { + return SECFailure; /* err code was set. */ + } + + return SECSuccess; +} + +static SECStatus +tls13_SendClientSecondRound(sslSocket *ss) +{ + SECStatus rv; + PRBool sendClientCert; + SSL3AlertDescription sendAlert = no_alert; + + 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; + + /* 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) { + SSL_TRC(3, ("%d: TLS13[%d]: deferring ssl3_SendClientSecondRound because" + " certificate authentication is still pending.", + SSL_GETPID(), ss->fd)); + ss->ssl3.hs.restartTarget = tls13_SendClientSecondRound; + return SECWouldBlock; + } + + if (ss->ssl3.hs.zeroRttState != ssl_0rtt_none) { + if (ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted) { + rv = tls13_SendEndOfEarlyData(ss); + if (rv != SECSuccess) { + return SECFailure; /* Error code already set. */ + } + } + if (IS_DTLS(ss) && !ss->ssl3.hs.helloRetry) { + /* Reset the counters so that the next epoch isn't set + * incorrectly. */ + tls13_SetNullCipherSpec(ss, &ss->ssl3.cwSpec); + } + } + + rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake, + CipherSpecWrite, PR_FALSE); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SSL_ERROR_INIT_CIPHER_SUITE_FAILURE, internal_error); + return SECFailure; + } + + rv = tls13_ComputeApplicationSecrets(ss); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + + rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData, + CipherSpecRead, PR_FALSE); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + + ssl_GetXmitBufLock(ss); /*******************************/ + rv = tls13_SendClientSecondFlight(ss, sendClientCert, &sendAlert); + ssl_ReleaseXmitBufLock(ss); /*******************************/ + if (rv != SECSuccess) { + if (sendAlert != no_alert) { + FATAL_ERROR(ss, PORT_GetError(), sendAlert); + } else { + LOG_ERROR(ss, PORT_GetError()); + } + return SECFailure; + } + rv = tls13_SetCipherSpec(ss, TrafficKeyApplicationData, + CipherSpecWrite, PR_TRUE); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + 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<1..2^16-1>; + * TicketExtension extensions<0..2^16-2>; + * } NewSessionTicket; + */ + +#define MAX_EARLY_DATA_SIZE (2 << 16) /* Arbitrary limit. */ + +SECStatus +tls13_SendNewSessionTicket(sslSocket *ss) +{ + PRUint16 message_length; + SECItem ticket_data = { 0, NULL, 0 }; + SECStatus rv; + NewSessionTicket ticket = { 0 }; + PRUint32 max_early_data_size_len = 0; + 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 = TLS_EX_SESS_TICKET_LIFETIME_HINT; + + rv = ssl3_EncodeSessionTicket(ss, &ticket, &ticket_data); + if (rv != SECSuccess) + goto loser; + + message_length = + 4 + /* lifetime */ + 4 + /* ticket_age_add */ + 2 + max_early_data_size_len + /* max_early_data_size_len */ + 2 + /* ticket length */ + ticket_data.len; + + rv = ssl3_AppendHandshakeHeader(ss, new_session_ticket, + message_length); + if (rv != SECSuccess) + goto loser; + + /* This is a fixed value. */ + rv = ssl3_AppendHandshakeNumber(ss, TLS_EX_SESS_TICKET_LIFETIME_HINT, 4); + if (rv != SECSuccess) + goto loser; + + /* The ticket age obfuscator. */ + rv = PK11_GenerateRandom((PRUint8 *)&ticket.ticket_age_add, + sizeof(ticket.ticket_age_add)); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_AppendHandshakeNumber(ss, ticket.ticket_age_add, 4); + 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, 2); + if (rv != SECSuccess) + goto loser; + + if (max_early_data_size_len) { + rv = ssl3_AppendHandshakeNumber( + ss, ssl_tls13_ticket_early_data_info_xtn, 2); + if (rv != SECSuccess) + goto loser; + + /* Length */ + rv = ssl3_AppendHandshakeNumber(ss, 4, 2); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_AppendHandshakeNumber(ss, MAX_EARLY_DATA_SIZE, 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; +} + +static SECStatus +tls13_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length) +{ + SECStatus rv; + PRInt32 tmp; + PRUint32 utmp; + NewSessionTicket ticket = { 0 }; + SECItem data; + 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 (!ss->firstHsDone || ss->sec.isServer) { + FATAL_ERROR(ss, SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET, + unexpected_message); + return SECFailure; + } + + ticket.received_timestamp = ssl_Time(); + tmp = ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length); + if (tmp < 0) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET, + decode_error); + return SECFailure; + } + ticket.ticket_lifetime_hint = (PRUint32)tmp; + 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); + + /* 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) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET, + decode_error); + return SECFailure; + } + + rv = ssl3_HandleExtensions(ss, &data.data, + &data.len, 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 (length != 0) { + FATAL_ERROR(ss, SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET, + decode_error); + return SECFailure; + } + + if (!ss->opt.noCache) { + 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) { + /* 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. */ + ss->sec.uncache(ss->sec.ci.sid); + ssl_FreeSID(ss->sec.ci.sid); + ss->sec.ci.sid = sid; + } + + ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &ticket); + PORT_Assert(!ticket.ticket.data); + + rv = ssl3_FillInCachedSID(ss, ss->sec.ci.sid); + if (rv != SECSuccess) + return SECFailure; + + /* Cache the session. */ + ss->sec.cache(ss->sec.ci.sid); + } + + return SECSuccess; +} + +typedef enum { + ExtensionNotUsed, + ExtensionClientOnly, + ExtensionSendClear, + ExtensionSendClearOrHrr, + ExtensionSendHrr, + ExtensionSendEncrypted, + ExtensionSendCertificate, + ExtensionNewSessionTicket +} Tls13ExtensionStatus; + +static const struct { + PRUint16 ex_value; + Tls13ExtensionStatus status; +} KnownExtensions[] = { + { ssl_server_name_xtn, ExtensionSendEncrypted }, + { ssl_supported_groups_xtn, ExtensionSendEncrypted }, + { ssl_ec_point_formats_xtn, ExtensionNotUsed }, + { ssl_signature_algorithms_xtn, ExtensionClientOnly }, + { ssl_use_srtp_xtn, ExtensionSendEncrypted }, + { ssl_app_layer_protocol_xtn, ExtensionSendEncrypted }, + { ssl_padding_xtn, ExtensionNotUsed }, + { ssl_extended_master_secret_xtn, ExtensionNotUsed }, + { ssl_session_ticket_xtn, ExtensionClientOnly }, + { ssl_tls13_key_share_xtn, ExtensionSendClearOrHrr }, + { ssl_tls13_pre_shared_key_xtn, ExtensionSendClear }, + { ssl_tls13_early_data_xtn, ExtensionSendEncrypted }, + { ssl_next_proto_nego_xtn, ExtensionNotUsed }, + { ssl_renegotiation_info_xtn, ExtensionNotUsed }, + { ssl_signed_cert_timestamp_xtn, ExtensionSendCertificate }, + { ssl_cert_status_xtn, ExtensionSendCertificate }, + { ssl_tls13_ticket_early_data_info_xtn, ExtensionNewSessionTicket }, + { ssl_tls13_cookie_xtn, ExtensionSendHrr }, + { ssl_tls13_short_header_xtn, ExtensionSendClear } +}; + +PRBool +tls13_ExtensionAllowed(PRUint16 extension, SSL3HandshakeType message) +{ + unsigned int i; + + PORT_Assert((message == client_hello) || + (message == server_hello) || + (message == hello_retry_request) || + (message == encrypted_extensions) || + (message == new_session_ticket) || + (message == certificate)); + + for (i = 0; i < PR_ARRAY_SIZE(KnownExtensions); i++) { + if (KnownExtensions[i].ex_value == extension) + break; + } + if (i == PR_ARRAY_SIZE(KnownExtensions)) { + /* We have never heard of this extension which is OK + * in client_hello and new_session_ticket. */ + return (message == client_hello) || + (message == new_session_ticket); + } + + switch (KnownExtensions[i].status) { + case ExtensionNotUsed: + return PR_FALSE; + case ExtensionClientOnly: + return message == client_hello; + case ExtensionSendClear: + return message == client_hello || + message == server_hello; + case ExtensionSendClearOrHrr: + return message == client_hello || + message == server_hello || + message == hello_retry_request; + case ExtensionSendHrr: + return message == client_hello || + message == hello_retry_request; + case ExtensionSendEncrypted: + return message == client_hello || + message == encrypted_extensions; + case ExtensionNewSessionTicket: + return message == new_session_ticket; + case ExtensionSendCertificate: + return message == client_hello || + message == certificate; + } + + PORT_Assert(0); + + /* Not reached */ + return PR_TRUE; +} + +/* TLS 1.3 doesn't actually have additional data but the aead function + * signature overloads additional data to carry the record sequence + * number and that's what we put here. The TLS 1.3 AEAD functions + * just use this input as the sequence number and not as additional + * data. */ +static void +tls13_FormatAdditionalData(PRUint8 *aad, unsigned int length, + sslSequenceNumber seqNum) +{ + PRUint8 *ptr = aad; + + PORT_Assert(length == 8); + ptr = ssl_EncodeUintX(seqNum, 8, ptr); + PORT_Assert((ptr - aad) == length); +} + +SECStatus +tls13_ProtectRecord(sslSocket *ss, + ssl3CipherSpec *cwSpec, + SSL3ContentType type, + const SSL3Opaque *pIn, + PRUint32 contentLen, + sslBuffer *wrBuf) +{ + const ssl3BulkCipherDef *cipher_def = cwSpec->cipher_def; + const int tagLen = cipher_def->tag_size; + SECStatus rv; + + SSL_TRC(3, ("%d: TLS13[%d]: spec=%d (%s) protect record 0x%0llx len=%u", + SSL_GETPID(), ss->fd, cwSpec, cwSpec->phase, + cwSpec->write_seq_num, contentLen)); + + if (contentLen + 1 + tagLen > wrBuf->space) { + 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(wrBuf->buf, pIn, contentLen); + + if (cipher_def->calg == ssl_calg_null) { + /* Shortcut for plaintext */ + wrBuf->len = contentLen; + } else { + PRUint8 aad[8]; + PORT_Assert(cipher_def->type == type_aead); + + /* Add the content type at the end. */ + wrBuf->buf[contentLen] = type; + + tls13_FormatAdditionalData(aad, sizeof(aad), cwSpec->write_seq_num); + rv = cwSpec->aead( + ss->sec.isServer ? &cwSpec->server : &cwSpec->client, + PR_FALSE, /* do encrypt */ + wrBuf->buf, /* output */ + (int *)&wrBuf->len, /* out len */ + wrBuf->space, /* max out */ + wrBuf->buf, contentLen + 1, /* input */ + aad, sizeof(aad)); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE); + return SECFailure; + } + } + + 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() witn an appropriate code. + */ +SECStatus +tls13_UnprotectRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext, + SSL3AlertDescription *alert) +{ + ssl3CipherSpec *crSpec = ss->ssl3.crSpec; + const ssl3BulkCipherDef *cipher_def = crSpec->cipher_def; + PRUint8 aad[8]; + SECStatus rv; + + *alert = bad_record_mac; /* Default alert for most issues. */ + + SSL_TRC(3, ("%d: TLS13[%d]: spec=%d (%s) unprotect record 0x%0llx len=%u", + SSL_GETPID(), ss->fd, crSpec, crSpec->phase, + crSpec->read_seq_num, cText->buf->len)); + + /* 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 < cipher_def->tag_size) { + 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; + } + + /* Verify that the content type is right, even though we overwrite it. */ + if (cText->type != content_application_data) { + SSL_TRC(3, + ("%d: TLS13[%d]: record has invalid exterior content type=%d", + SSL_GETPID(), ss->fd, cText->type)); + /* Do we need a better error here? */ + PORT_SetError(SSL_ERROR_BAD_MAC_READ); + return SECFailure; + } + + /* Check the version number in the record */ + if ((IS_DTLS(ss) && cText->version != kDtlsRecordVersion) || + (!IS_DTLS(ss) && cText->version != kTlsRecordVersion)) { + /* 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); + tls13_FormatAdditionalData(aad, sizeof(aad), + IS_DTLS(ss) ? cText->seq_num + : crSpec->read_seq_num); + rv = crSpec->aead( + ss->sec.isServer ? &crSpec->client : &crSpec->server, + PR_TRUE, /* do decrypt */ + plaintext->buf, /* out */ + (int *)&plaintext->len, /* outlen */ + plaintext->space, /* maxout */ + cText->buf->buf, /* in */ + cText->buf->len, /* inlen */ + aad, sizeof(aad)); + if (rv != SECSuccess) { + SSL_TRC(3, + ("%d: TLS13[%d]: record has bogus MAC", + SSL_GETPID(), ss->fd)); + PORT_SetError(SSL_ERROR_BAD_MAC_READ); + 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, cText->type)); + /* It's safe to report this specifically because it happened + * after the MAC has been verified. */ + PORT_SetError(SSL_ERROR_BAD_BLOCK_PADDING); + return SECFailure; + } + + /* Record the type. */ + cText->type = plaintext->buf[plaintext->len - 1]; + --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, cText->type)); + + 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. + * 5. The server is willing to accept 0-RTT. + * 6. 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 (!ss->statelessResume) + return PR_FALSE; + if ((sid->u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) == 0) + return PR_FALSE; + return tls13_AlpnTagAllowed(ss, &sid->u.ssl3.alpnSelection); +} + +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_ClientExtensionAdvertised(ss, ssl_tls13_early_data_xtn)) { + return SECSuccess; + } + + ss->ssl3.hs.zeroRttState = ssl_0rtt_sent; + ss->ssl3.hs.zeroRttSuite = ss->ssl3.hs.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 rv; + } + + /* Null spec... */ + ssl_GetSpecReadLock(ss); + ss->ssl3.hs.nullSpec = ss->ssl3.cwSpec; + tls13_CipherSpecAddRef(ss->ssl3.hs.nullSpec); + ssl_ReleaseSpecReadLock(ss); + + /* Cipher suite already set in tls13_SetupClientHello. */ + ss->ssl3.hs.preliminaryInfo = 0; /* TODO(ekr@rtfm.com) Fill this in. + * bug 1281255. */ + + rv = tls13_DeriveSecret(ss, ss->ssl3.hs.currentSecret, + kHkdfLabelClient, + kHkdfLabelEarlyTrafficSecret, + NULL, + &ss->ssl3.hs.clientEarlyTrafficSecret); + if (rv != SECSuccess) + return SECFailure; + + rv = tls13_SetCipherSpec(ss, TrafficKeyEarlyApplicationData, + CipherSpecWrite, PR_TRUE); + if (rv != SECSuccess) { + return rv; + } + + return SECSuccess; +} + +PRInt32 +tls13_Read0RttData(sslSocket *ss, void *buf, PRInt32 len) +{ + TLS13EarlyData *msg; + + PORT_Assert(!PR_CLIST_IS_EMPTY(&ss->ssl3.hs.bufferedEarlyData)); + msg = (TLS13EarlyData *)PR_NEXT_LINK(&ss->ssl3.hs.bufferedEarlyData); + + PR_REMOVE_LINK(&msg->link); + if (msg->data.len > len) { + PORT_SetError(SSL_ERROR_ILLEGAL_PARAMETER_ALERT); + return SECFailure; + } + len = msg->data.len; + + PORT_Memcpy(buf, msg->data.data, msg->data.len); + SECITEM_ZfreeItem(&msg->data, PR_FALSE); + PORT_ZFree(msg, sizeof(*msg)); + + return len; +} + +/* 0-RTT data will be followed by a different cipher spec; this resets the + * current spec to the null spec so that the following state can be set as + * though 0-RTT didn't happen. TODO: work out if this is the best plan. */ +static void +tls13_SetNullCipherSpec(sslSocket *ss, ssl3CipherSpec **specp) +{ + PORT_Assert(ss->ssl3.hs.nullSpec); + + ssl_GetSpecWriteLock(ss); + tls13_CipherSpecRelease(*specp); + *specp = ss->ssl3.hs.nullSpec; + ssl_ReleaseSpecWriteLock(ss); + ss->ssl3.hs.nullSpec = NULL; +} + +static SECStatus +tls13_SendEndOfEarlyData(sslSocket *ss) +{ + SECStatus rv; + + SSL_TRC(3, ("%d: TLS13[%d]: send end_of_early_data extension", + SSL_GETPID(), ss->fd)); + + rv = SSL3_SendAlert(ss, alert_warning, end_of_early_data); + if (rv != SECSuccess) { + FATAL_ERROR(ss, SEC_ERROR_LIBRARY_FAILURE, internal_error); + return SECFailure; + } + + ss->ssl3.hs.zeroRttState = ssl_0rtt_done; + return SECSuccess; +} + +SECStatus +tls13_HandleEndOfEarlyData(sslSocket *ss) +{ + SECStatus rv; + + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3 || + ss->ssl3.hs.zeroRttState != ssl_0rtt_accepted) { + (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message); + PORT_SetError(SSL_ERROR_END_OF_EARLY_DATA_ALERT); + return SECFailure; + } + + PORT_Assert(TLS13_IN_HS_STATE(ss, ss->opt.requestCertificate ? wait_client_cert : wait_finished)); + + if (IS_DTLS(ss)) { + /* Reset the cipher spec so that the epoch counter is properly reset. */ + tls13_SetNullCipherSpec(ss, &ss->ssl3.crSpec); + } + + rv = tls13_SetCipherSpec(ss, TrafficKeyHandshake, + CipherSpecRead, PR_FALSE); + if (rv != SECSuccess) { + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + ss->ssl3.hs.zeroRttState = ssl_0rtt_done; + return SECSuccess; +} + +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_EncodeDraftVersion(SSL3ProtocolVersion version) +{ +#ifdef TLS_1_3_DRAFT_VERSION + if (version == SSL_LIBRARY_VERSION_TLS_1_3) { + return 0x7f00 | TLS_1_3_DRAFT_VERSION; + } +#endif + return (PRUint16)version; +} + +/* Pick the highest version we support that is also advertised. */ +SECStatus +tls13_NegotiateVersion(sslSocket *ss, const TLSExtension *supported_versions) +{ + PRUint16 version; + /* Make a copy so we're nondestructive*/ + SECItem data = supported_versions->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) { + PRUint16 wire = tls13_EncodeDraftVersion(version); + 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; +} diff --git a/nss/lib/ssl/tls13con.h b/nss/lib/ssl/tls13con.h new file mode 100644 index 0000000..c39c62a --- /dev/null +++ b/nss/lib/ssl/tls13con.h @@ -0,0 +1,88 @@ +/* -*- 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_ + +typedef enum { + StaticSharedSecret, + EphemeralSharedSecret +} SharedSecretType; + +#define TLS13_MAX_FINISHED_SIZE 64 + +SECStatus tls13_UnprotectRecord( + sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *plaintext, + 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) + +SSLHashType tls13_GetHashForCipherSuite(ssl3CipherSuite suite); +SSLHashType tls13_GetHash(const sslSocket *ss); +unsigned int tls13_GetHashSizeForHash(SSLHashType hash); +unsigned int tls13_GetHashSize(const sslSocket *ss); +CK_MECHANISM_TYPE tls13_GetHkdfMechanism(sslSocket *ss); +void tls13_FatalError(sslSocket *ss, PRErrorCode prError, + SSL3AlertDescription desc); +SECStatus tls13_SetupClientHello(sslSocket *ss); +SECStatus tls13_MaybeDo0RTTHandshake(sslSocket *ss); +PRBool tls13_AllowPskCipher(const sslSocket *ss, + const ssl3CipherSuiteDef *cipher_def); +PRBool tls13_PskSuiteEnabled(sslSocket *ss); +SECStatus tls13_ComputePskBinder(sslSocket *ss, PRBool sending, + unsigned int prefixLength, + PRUint8 *output, unsigned int *outputLen, + unsigned int maxOutputLen); +SECStatus tls13_HandleClientHelloPart2(sslSocket *ss, + const SECItem *suites, + sslSessionID *sid); +SECStatus tls13_HandleServerHelloPart2(sslSocket *ss); +SECStatus tls13_HandlePostHelloHandshakeMessage(sslSocket *ss, SSL3Opaque *b, + PRUint32 length, + SSL3Hashes *hashesPtr); +SECStatus tls13_HandleHelloRetryRequest(sslSocket *ss, SSL3Opaque *b, + PRUint32 length); +void tls13_DestroyKeyShareEntry(TLS13KeyShareEntry *entry); +void tls13_DestroyKeyShares(PRCList *list); +SECStatus tls13_CreateKeyShare(sslSocket *ss, const sslNamedGroupDef *groupDef); +void tls13_DestroyEarlyData(PRCList *list); +void tls13_CipherSpecAddRef(ssl3CipherSpec *spec); +void tls13_CipherSpecRelease(ssl3CipherSpec *spec); +void tls13_DestroyCipherSpecs(PRCList *list); +PRBool tls13_ExtensionAllowed(PRUint16 extension, SSL3HandshakeType message); +SECStatus tls13_ProtectRecord(sslSocket *ss, + ssl3CipherSpec *cwSpec, + SSL3ContentType type, + const SSL3Opaque *pIn, + PRUint32 contentLen, + sslBuffer *wrBuf); +PRInt32 tls13_Read0RttData(sslSocket *ss, void *buf, PRInt32 len); +SECStatus tls13_HandleEndOfEarlyData(sslSocket *ss); +SECStatus tls13_HandleEarlyApplicationData(sslSocket *ss, sslBuffer *origBuf); +PRBool tls13_ClientAllow0Rtt(const sslSocket *ss, const sslSessionID *sid); +PRUint16 tls13_EncodeDraftVersion(SSL3ProtocolVersion version); +PRUint16 tls13_DecodeDraftVersion(PRUint16 version); +SECStatus tls13_NegotiateVersion(sslSocket *ss, + const TLSExtension *supported_versions); +SECStatus tls13_SendNewSessionTicket(sslSocket *ss); + +#endif /* __tls13con_h_ */ diff --git a/nss/lib/ssl/tls13exthandle.c b/nss/lib/ssl/tls13exthandle.c new file mode 100644 index 0000000..be93b97 --- /dev/null +++ b/nss/lib/ssl/tls13exthandle.c @@ -0,0 +1,1169 @@ +/* -*- 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 "tls13exthandle.h" + +PRInt32 +tls13_ServerSendStatusRequestXtn( + const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + const sslServerCert *serverCert = ss->sec.serverCert; + const SECItem *item; + SECStatus rv; + + if (!serverCert->certStatusArray || + !serverCert->certStatusArray->len) { + return 0; + } + + item = &serverCert->certStatusArray->items[0]; + + /* Only send the first entry. */ + extension_length = 2 + 2 + 1 /* status_type */ + 3 + item->len; + if (maxBytes < (PRUint32)extension_length) { + return 0; + } + if (append) { + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_cert_status_xtn, 2); + if (rv != SECSuccess) + return -1; + /* length of extension_data */ + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + return -1; + /* status_type == ocsp */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 1 /*ocsp*/, 1); + if (rv != SECSuccess) + return rv; /* err set by AppendHandshake. */ + /* opaque OCSPResponse<1..2^24-1> */ + rv = ssl3_ExtAppendHandshakeVariable(ss, item->data, item->len, 3); + if (rv != SECSuccess) + return rv; /* err set by AppendHandshake. */ + } + + return extension_length; +} + +/* + * [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>; + */ +static 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; +} + +static PRUint32 +tls13_SizeOfClientKeyShareExtension(const sslSocket *ss) +{ + PRCList *cursor; + /* Size is: extension(2) + extension_len(2) + client_shares(2) */ + PRUint32 size = 2 + 2 + 2; + for (cursor = PR_NEXT_LINK(&ss->ephemeralKeyPairs); + cursor != &ss->ephemeralKeyPairs; + cursor = PR_NEXT_LINK(cursor)) { + sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor; + size += tls13_SizeOfKeyShareEntry(keyPair->keys->pubKey); + } + return size; +} + +static SECStatus +tls13_EncodeKeyShareEntry(const sslSocket *ss, const sslEphemeralKeyPair *keyPair) +{ + SECStatus rv; + SECKEYPublicKey *pubKey = keyPair->keys->pubKey; + unsigned int size = tls13_SizeOfKeyShareEntry(pubKey); + + rv = ssl3_ExtAppendHandshakeNumber(ss, keyPair->group->name, 2); + if (rv != SECSuccess) + return rv; + rv = ssl3_ExtAppendHandshakeNumber(ss, size - 4, 2); + if (rv != SECSuccess) + return rv; + + switch (pubKey->keyType) { + case ecKey: + rv = tls13_EncodeECDHEKeyShareKEX(ss, pubKey); + break; + case dhKey: + rv = ssl_AppendPaddedDHKeyShare(ss, pubKey, PR_FALSE); + break; + default: + PORT_Assert(0); + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + break; + } + + return rv; +} + +PRInt32 +tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRUint32 extension_length; + + if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) { + return 0; + } + + /* 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)); + + extension_length = tls13_SizeOfClientKeyShareExtension(ss); + if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv; + PRCList *cursor; + + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_key_share_xtn, 2); + if (rv != SECSuccess) + goto loser; + + /* The extension length */ + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + goto loser; + + /* The length of KeyShares */ + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 6, 2); + if (rv != SECSuccess) + goto loser; + + for (cursor = PR_NEXT_LINK(&ss->ephemeralKeyPairs); + cursor != &ss->ephemeralKeyPairs; + cursor = PR_NEXT_LINK(cursor)) { + sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor; + rv = tls13_EncodeKeyShareEntry(ss, keyPair); + if (rv != SECSuccess) + goto loser; + } + + xtnData->advertised[xtnData->numAdvertised++] = + ssl_tls13_key_share_xtn; + } + + return extension_length; + +loser: + return -1; +} + +static SECStatus +tls13_HandleKeyShareEntry(const sslSocket *ss, TLSExtensionData *xtnData, SECItem *data) +{ + SECStatus rv; + PRInt32 group; + const sslNamedGroupDef *groupDef; + TLS13KeyShareEntry *ks = NULL; + SECItem share = { siBuffer, NULL, 0 }; + + group = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (group < 0) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); + goto loser; + } + groupDef = ssl_LookupNamedGroup(group); + rv = ssl3_ExtConsumeHandshakeVariable(ss, &share, 2, &data->data, + &data->len); + if (rv != SECSuccess) { + goto loser; + } + /* If the group is disabled, continue. */ + if (!groupDef) { + return SECSuccess; + } + + ks = PORT_ZNew(TLS13KeyShareEntry); + if (!ks) + goto loser; + ks->group = groupDef; + + rv = SECITEM_CopyItem(NULL, &ks->key_exchange, &share); + if (rv != SECSuccess) + goto loser; + + PR_APPEND_LINK(&ks->link, &xtnData->remoteKeyShares); + return SECSuccess; + +loser: + if (ks) + 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, PRUint16 ex_type, SECItem *data) +{ + SECStatus rv; + PORT_Assert(PR_CLIST_IS_EMPTY(&xtnData->remoteKeyShares)); + + PORT_Assert(!ss->sec.isServer); + if (ss->version < SSL_LIBRARY_VERSION_TLS_1_3) { + /* This can't happen because the extension processing + * code filters out TLS 1.3 extensions when not in + * TLS 1.3 mode. */ + PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); + return SECFailure; + } + + SSL_TRC(3, ("%d: SSL3[%d]: handle key_share extension", + SSL_GETPID(), ss->fd)); + + rv = tls13_HandleKeyShareEntry(ss, xtnData, data); + if (rv != SECSuccess) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); + return SECFailure; + } + + if (data->len) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); + return SECFailure; + } + + return SECSuccess; +} + +SECStatus +tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, SECItem *data) +{ + SECStatus rv; + PRInt32 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)); + + tmp = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (tmp < 0) { + 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_CreateKeyShare(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, PRUint16 ex_type, SECItem *data) +{ + SECStatus rv; + PRInt32 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.) */ + length = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, + &data->len); + if (length < 0) + goto loser; + if (length != data->len) { + /* Check for consistency */ + PORT_SetError(SSL_ERROR_RX_MALFORMED_KEY_SHARE); + goto loser; + } + + while (data->len) { + rv = tls13_HandleKeyShareEntry(ss, xtnData, data); + if (rv != SECSuccess) + goto loser; + } + + /* Check that the client only offered one share if this is + * after HRR. */ + if (ss->ssl3.hs.helloRetry) { + if (PR_PREV_LINK(&xtnData->remoteKeyShares) != + PR_NEXT_LINK(&xtnData->remoteKeyShares)) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_CLIENT_HELLO); + goto loser; + } + } + + return SECSuccess; + +loser: + tls13_DestroyKeyShares(&xtnData->remoteKeyShares); + return SECFailure; +} + +PRInt32 +tls13_ServerSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRUint32 extension_length; + PRUint32 entry_length; + 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); + + entry_length = tls13_SizeOfKeyShareEntry(keyPair->keys->pubKey); + extension_length = 2 + 2 + entry_length; /* Type + length + entry_length */ + if (maxBytes < extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_key_share_xtn, 2); + if (rv != SECSuccess) + goto loser; + + rv = ssl3_ExtAppendHandshakeNumber(ss, entry_length, 2); + if (rv != SECSuccess) + goto loser; + + rv = tls13_EncodeKeyShareEntry(ss, keyPair); + if (rv != SECSuccess) + goto loser; + } + + return extension_length; + +loser: + return -1; +} + +/* 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; + + * Presently the only way to get a PSK is by resumption, so this is + * really a ticket label and there will be at most one. + */ +PRInt32 +tls13_ClientSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length; + PRInt32 identities_length; + PRInt32 binders_length; + NewSessionTicket *session_ticket; + + /* We only set statelessResume on the client in TLS 1.3 code. */ + if (!ss->statelessResume) + return 0; + + PORT_Assert(ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_3); + + /* The length computations are simplified by the fact that there + * is just one ticket at most. */ + session_ticket = &ss->sec.ci.sid->u.ssl3.locked.sessionTicket; + identities_length = + 2 + /* vector length */ + 2 + session_ticket->ticket.len + /* identity length + ticket len */ + 4; /* obfuscated_ticket_age */ + binders_length = + 2 + /* vector length */ + 1 + tls13_GetHashSizeForHash( + tls13_GetHashForCipherSuite(ss->sec.ci.sid->u.ssl3.cipherSuite)); + extension_length = + 2 + 2 + /* Type + length */ + identities_length + binders_length; + + if (maxBytes < (PRUint32)extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv; + PRUint32 age; + unsigned int prefixLength; + PRUint8 binder[TLS13_MAX_FINISHED_SIZE]; + unsigned int binderLen; + + /* extension_type */ + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_pre_shared_key_xtn, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_length - 4, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_ExtAppendHandshakeNumber(ss, identities_length - 2, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_ExtAppendHandshakeVariable(ss, session_ticket->ticket.data, + session_ticket->ticket.len, 2); + if (rv != SECSuccess) + goto loser; + + /* Obfuscated age. */ + age = ssl_Time() - session_ticket->received_timestamp; + age += session_ticket->ticket_age_add; + rv = ssl3_ExtAppendHandshakeNumber(ss, age, 4); + if (rv != SECSuccess) + goto loser; + + /* Now the binders. */ + prefixLength = ss->ssl3.hs.messages.len; + rv = tls13_ComputePskBinder(CONST_CAST(sslSocket, ss), PR_TRUE, + prefixLength, binder, &binderLen, + sizeof(binder)); + if (rv != SECSuccess) + goto loser; + PORT_Assert(binderLen == tls13_GetHashSize(ss)); + rv = ssl3_ExtAppendHandshakeNumber(ss, binders_length - 2, 2); + if (rv != SECSuccess) + goto loser; + rv = ssl3_ExtAppendHandshakeVariable(ss, + binder, binderLen, 1); + if (rv != SECSuccess) + goto loser; + + PRINT_BUF(50, (ss, "Sending PreSharedKey value", + session_ticket->ticket.data, + session_ticket->ticket.len)); + + xtnData->sentSessionTicketInClientHello = PR_TRUE; + xtnData->advertised[xtnData->numAdvertised++] = + ssl_tls13_pre_shared_key_xtn; + } + return extension_length; + +loser: + xtnData->ticketTimestampVerified = PR_FALSE; + return -1; +} + +/* Handle a TLS 1.3 PreSharedKey Extension. We only accept PSKs + * that contain session tickets. */ +SECStatus +tls13_ServerHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + SECItem inner; + SECStatus rv; + unsigned int numIdentities = 0; + unsigned int numBinders = 0; + + 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; + } + + /* 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 utmp; + + rv = ssl3_ExtConsumeHandshakeVariable(ss, &label, 2, + &inner.data, &inner.len); + if (rv != SECSuccess) + return rv; + if (!label.len) { + goto alert_loser; + } + + /* Read and discard session ticket age. Bug 1295163 */ + rv = ssl3_ExtConsumeHandshake(ss, &utmp, 4, + &inner.data, &inner.len); + if (rv != SECSuccess) + return rv; + + if (!numIdentities) { + PRINT_BUF(50, (ss, "Handling PreSharedKey value", + label.data, label.len)); + rv = ssl3_ProcessSessionTicketCommon( + CONST_CAST(sslSocket, ss), &label); + /* 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; + } + ++numIdentities; + } + + xtnData->pskBinderPrefixLen = ss->ssl3.hs.messages.len - 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; + + /* Keep track of negotiated extensions. Note that this does not + * mean we are resuming. */ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + return SECSuccess; + +alert_loser: + ssl3_ExtSendAlert(ss, alert_fatal, illegal_parameter); + PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY); + return SECFailure; +} + +PRInt32 +tls13_ServerSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extension_length = + 2 + 2 + 2; /* type + len + index */ + SECStatus rv; + + if (maxBytes < (PRUint32)extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_pre_shared_key_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, 2, 2); + if (rv != SECSuccess) + return -1; + + /* We only process the first session ticket the client sends, + * so the index is always 0. */ + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + } + + return extension_length; +} + +/* Handle a TLS 1.3 PreSharedKey Extension. We only accept PSKs + * that contain session tickets. */ +SECStatus +tls13_ClientHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + PRInt32 index; + + 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; + } + + index = ssl3_ExtConsumeHandshakeNumber(ss, 2, &data->data, &data->len); + if (index < 0) + 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) { + PORT_SetError(SSL_ERROR_MALFORMED_PRE_SHARED_KEY); + return SECFailure; + } + + /* Keep track of negotiated extensions. */ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + return SECSuccess; +} + +/* + * struct { } EarlyDataIndication; + */ +PRInt32 +tls13_ClientSendEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + SECStatus rv; + PRInt32 extension_length; + + if (!tls13_ClientAllow0Rtt(ss, ss->sec.ci.sid)) + return 0; + + /* type + length */ + extension_length = 2 + 2; + + if (maxBytes < (PRUint32)extension_length) { + PORT_Assert(0); + return 0; + } + + if (append) { + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_early_data_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + } + + xtnData->advertised[xtnData->numAdvertised++] = + ssl_tls13_early_data_xtn; + + return extension_length; +} + +SECStatus +tls13_ServerHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + 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 (data->len) { + PORT_SetError(SSL_ERROR_MALFORMED_EARLY_DATA); + return SECFailure; + } + + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + return SECSuccess; +} + +/* This is only registered if we are sending it. */ +PRInt32 +tls13_ServerSendEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes) +{ + SSL_TRC(3, ("%d: TLS13[%d]: send early_data extension", + SSL_GETPID(), ss->fd)); + + PORT_Assert(ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted); + if (maxBytes < 4) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv; + + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_early_data_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + } + + return 4; +} + +/* This will only be called if we also offered the extension. */ +SECStatus +tls13_ClientHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + 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) { + 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++] = ex_type; + + return SECSuccess; +} + +SECStatus +tls13_ClientHandleTicketEarlyDataInfoXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data) +{ + PRUint32 utmp; + SECStatus rv; + + SSL_TRC(3, ("%d: TLS13[%d]: handle early_data_info extension", + SSL_GETPID(), ss->fd)); + + /* If we are doing < TLS 1.3, then ignore this. */ + 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 { + * ProtocolVersion versions<2..254>; + * } SupportedVersions; + */ +PRInt32 +tls13_ClientSendSupportedVersionsXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes) +{ + PRInt32 extensions_len; + PRUint16 version; + SECStatus rv; + + if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3) { + return 0; + } + + SSL_TRC(3, ("%d: TLS13[%d]: send supported_versions extension", + SSL_GETPID(), ss->fd)); + + /* Extension type, extension len fiels, vector len field, + * length of the values. */ + extensions_len = 2 + 2 + 1 + + 2 * (ss->vrange.max - ss->vrange.min + 1); + + if (maxBytes < (PRUint32)extensions_len) { + PORT_Assert(0); + return 0; + } + + if (append) { + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_supported_versions_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, extensions_len - 4, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, extensions_len - 5, 1); + if (rv != SECSuccess) + return -1; + + for (version = ss->vrange.max; version >= ss->vrange.min; --version) { + rv = ssl3_ExtAppendHandshakeNumber( + ss, tls13_EncodeDraftVersion(version), 2); + if (rv != SECSuccess) + return -1; + } + } + + return extensions_len; +} + +/* + * struct { + * opaque cookie<1..2^16-1>; + * } Cookie; + */ +SECStatus +tls13_ClientHandleHrrCookie(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, 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; +} + +PRInt32 +tls13_ClientSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, PRUint32 maxBytes) +{ + PRInt32 extension_len; + + if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 || + !ss->ssl3.hs.cookie.len) { + return 0; + } + + SSL_TRC(3, ("%d: TLS13[%d]: send cookie extension", SSL_GETPID(), ss->fd)); + + /* Extension type, length, cookie length, cookie value. */ + extension_len = 2 + 2 + 2 + ss->ssl3.hs.cookie.len; + + if (maxBytes < (PRUint32)extension_len) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_cookie_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_len - 4, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeVariable(ss, ss->ssl3.hs.cookie.data, + ss->ssl3.hs.cookie.len, 2); + if (rv != SECSuccess) + return -1; + } + return extension_len; +} + +/* + * enum { psk_ke(0), psk_dhe_ke(1), (255) } PskKeyExchangeMode; + * + * struct { + * PskKeyExchangeMode ke_modes<1..255>; + * } PskKeyExchangeModes; + */ +PRInt32 +tls13_ClientSendPskKeyExchangeModesXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes) +{ + static const PRUint8 ke_modes[] = { tls13_psk_dh_ke }; + static const unsigned long ke_modes_len = sizeof(ke_modes); + PRInt32 extension_len; + + if (ss->vrange.max < SSL_LIBRARY_VERSION_TLS_1_3 || + ss->opt.noCache) { + return 0; + } + + extension_len = + 2 + 2 + /* Type + length */ + 1 + ke_modes_len; /* key exchange modes vector */ + + SSL_TRC(3, ("%d: TLS13[%d]: send psk key exchange modes extension", + SSL_GETPID(), ss->fd)); + + if (maxBytes < (PRUint32)extension_len) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv = ssl3_ExtAppendHandshakeNumber( + ss, ssl_tls13_psk_key_exchange_modes_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, extension_len - 4, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeVariable( + ss, ke_modes, ke_modes_len, 1); + if (rv != SECSuccess) + return -1; + } + return extension_len; +} + +SECStatus +tls13_ServerHandlePskKeyExchangeModesXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRUint16 ex_type, 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++] = ex_type; + + return SECSuccess; +} + +PRInt32 +tls13_SendShortHeaderXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes) +{ + PRUint32 extension_len = 2 + 2; /* Type + length (0). */ + + if (!ss->opt.enableShortHeaders) { + return 0; + } + + /* Presently this is incompatible with 0-RTT. We will fix if + * it becomes more than an experiment. */ + if (ss->opt.enable0RttData) { + return 0; + } + + if (IS_DTLS(ss)) { + return 0; + } + + SSL_TRC(3, ("%d: TLS13[%d]: send short_header extension", + SSL_GETPID(), ss->fd)); + + if (maxBytes < extension_len) { + PORT_Assert(0); + return 0; + } + + if (append) { + SECStatus rv; + + rv = ssl3_ExtAppendHandshakeNumber(ss, ssl_tls13_short_header_xtn, 2); + if (rv != SECSuccess) + return -1; + + rv = ssl3_ExtAppendHandshakeNumber(ss, 0, 2); + if (rv != SECSuccess) + return -1; + + xtnData->advertised[xtnData->numAdvertised++] = + ssl_tls13_short_header_xtn; + } + + return extension_len; +} + +SECStatus +tls13_HandleShortHeaderXtn( + const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + 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; + } + + /* Presently this is incompatible with 0-RTT. We will fix if + * it becomes more than an experiment. */ + if (ss->opt.enable0RttData) { + return SECSuccess; + } + + if (IS_DTLS(ss)) { + PORT_SetError(SSL_ERROR_EXTENSION_DISALLOWED_FOR_VERSION); + return SECFailure; + } + + if (data->len) { + PORT_SetError(SSL_ERROR_RX_MALFORMED_HANDSHAKE); + return SECFailure; + } + + if (!ss->opt.enableShortHeaders) { + /* Ignore. */ + return SECSuccess; + } + + /* Keep track of negotiated extensions. */ + xtnData->negotiated[xtnData->numNegotiated++] = ex_type; + + if (ss->sec.isServer) { + SECStatus rv; + + rv = ssl3_RegisterExtensionSender(ss, xtnData, + ssl_tls13_short_header_xtn, + tls13_SendShortHeaderXtn); + if (rv != SECSuccess) { + return SECFailure; + } + } + + return SECSuccess; +} diff --git a/nss/lib/ssl/tls13exthandle.h b/nss/lib/ssl/tls13exthandle.h new file mode 100644 index 0000000..b798c6b --- /dev/null +++ b/nss/lib/ssl/tls13exthandle.h @@ -0,0 +1,74 @@ +/* -*- 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_ + +PRInt32 tls13_ServerSendStatusRequestXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +PRInt32 tls13_ClientSendKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +SECStatus tls13_ClientHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +SECStatus tls13_ClientHandleKeyShareXtnHrr(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +SECStatus tls13_ServerHandleKeyShareXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +PRInt32 tls13_ServerSendKeyShareXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +PRInt32 tls13_ClientSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRBool append, + PRUint32 maxBytes); +SECStatus tls13_ServerHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +SECStatus tls13_ClientHandlePreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRUint16 ex_type, + SECItem *data); +PRInt32 tls13_ServerSendPreSharedKeyXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +PRInt32 tls13_ClientSendEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +SECStatus tls13_ServerHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +SECStatus tls13_ClientHandleEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +PRInt32 tls13_ServerSendEarlyDataXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +SECStatus tls13_ClientHandleTicketEarlyDataInfoXtn( + const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +PRInt32 tls13_ClientSendSupportedVersionsXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +SECStatus tls13_ClientHandleHrrCookie(const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); +PRInt32 tls13_ClientSendHrrCookieXtn(const sslSocket *ss, TLSExtensionData *xtnData, + PRBool append, + PRUint32 maxBytes); +PRInt32 tls13_ClientSendPskKeyExchangeModesXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +SECStatus tls13_ServerHandlePskKeyExchangeModesXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRUint16 ex_type, SECItem *data); +PRInt32 tls13_SendShortHeaderXtn(const sslSocket *ss, + TLSExtensionData *xtnData, + PRBool append, PRUint32 maxBytes); +SECStatus tls13_HandleShortHeaderXtn( + const sslSocket *ss, TLSExtensionData *xtnData, PRUint16 ex_type, + SECItem *data); + +#endif diff --git a/nss/lib/ssl/tls13hkdf.c b/nss/lib/ssl/tls13hkdf.c new file mode 100644 index 0000000..7e69bb8 --- /dev/null +++ b/nss/lib/ssl/tls13hkdf.c @@ -0,0 +1,270 @@ +/* -*- 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_NSS_HKDF_SHA256, 32 }, + { ssl_hash_sha384, CKM_NSS_HKDF_SHA384, 48 }, + { ssl_hash_sha512, CKM_NSS_HKDF_SHA512, 64 } +}; + +SECStatus +tls13_HkdfExtract(PK11SymKey *ikm1, PK11SymKey *ikm2in, SSLHashType baseHash, + PK11SymKey **prkp) +{ + CK_NSS_HKDFParams params; + SECItem paramsi; + SECStatus rv; + SECItem *salt; + PK11SymKey *prk; + static const PRUint8 zeroKeyBuf[HASH_LENGTH_MAX]; + PK11SymKey *zeroKey = NULL; + PK11SlotInfo *slot = NULL; + PK11SymKey *ikm2; + + params.bExtract = CK_TRUE; + params.bExpand = CK_FALSE; + params.pInfo = NULL; + params.ulInfoLen = 0UL; + + if (ikm1) { + /* TODO(ekr@rtfm.com): This violates the PKCS#11 key boundary + * but is imposed on us by the present HKDF interface. */ + rv = PK11_ExtractKeyValue(ikm1); + if (rv != SECSuccess) + return rv; + + salt = PK11_GetKeyData(ikm1); + if (!salt) + return SECFailure; + + params.pSalt = salt->data; + params.ulSaltLen = salt->len; + PORT_Assert(salt->len > 0); + } else { + /* Per documentation for CKM_NSS_HKDF_*: + * + * If the optional salt is given, it is used; otherwise, the salt is + * set to a sequence of zeros equal in length to the HMAC output. + */ + params.pSalt = NULL; + params.ulSaltLen = 0UL; + } + paramsi.data = (unsigned char *)¶ms; + 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 (!ikm2in) { + SECItem zeroItem = { + siBuffer, + (unsigned char *)zeroKeyBuf, + kTlsHkdfInfo[baseHash].hashSize + }; + slot = PK11_GetInternalSlot(); + if (!slot) { + return SECFailure; + } + zeroKey = PK11_ImportSymKey(slot, + kTlsHkdfInfo[baseHash].pkcs11Mech, + PK11_OriginUnwrap, + CKA_DERIVE, &zeroItem, NULL); + if (!zeroKey) + return SECFailure; + ikm2 = zeroKey; + } else { + ikm2 = ikm2in; + } + 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, kTlsHkdfInfo[baseHash].pkcs11Mech, + ¶msi, kTlsHkdfInfo[baseHash].pkcs11Mech, + CKA_DERIVE, kTlsHkdfInfo[baseHash].hashSize); + if (zeroKey) + PK11_FreeSymKey(zeroKey); + if (slot) + PK11_FreeSlot(slot); + if (!prk) + return SECFailure; + + PRINT_KEY(50, (NULL, "HKDF Extract", prk)); + *prkp = prk; + + 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, + PK11SymKey **keyp) +{ + CK_NSS_HKDFParams 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]; + PRUint8 *ptr = info; + unsigned int infoLen; + PK11SymKey *derived; + const char *kLabelPrefix = "TLS 1.3, "; + const unsigned int kLabelPrefixLen = strlen(kLabelPrefix); + + if (handshakeHash) { + if (handshakeHashLen > 255) { + PORT_Assert(0); + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + } else { + PORT_Assert(!handshakeHashLen); + } + + /* + * [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 + * + */ + infoLen = 2 + 1 + kLabelPrefixLen + labelLen + 1 + handshakeHashLen; + if (infoLen > sizeof(info)) { + PORT_Assert(0); + goto abort; + } + + ptr = ssl_EncodeUintX(keySize, 2, ptr); + ptr = ssl_EncodeUintX(labelLen + kLabelPrefixLen, 1, ptr); + PORT_Memcpy(ptr, kLabelPrefix, kLabelPrefixLen); + ptr += kLabelPrefixLen; + PORT_Memcpy(ptr, label, labelLen); + ptr += labelLen; + ptr = ssl_EncodeUintX(handshakeHashLen, 1, ptr); + if (handshakeHash) { + PORT_Memcpy(ptr, handshakeHash, handshakeHashLen); + ptr += handshakeHashLen; + } + PORT_Assert((ptr - info) == infoLen); + + params.bExtract = CK_FALSE; + params.bExpand = CK_TRUE; + params.pInfo = info; + params.ulInfoLen = infoLen; + paramsi.data = (unsigned char *)¶ms; + paramsi.len = sizeof(params); + + derived = PK11_DeriveWithFlags(prk, kTlsHkdfInfo[baseHash].pkcs11Mech, + ¶msi, algorithm, + CKA_DERIVE, keySize, + CKF_SIGN | CKF_VERIFY); + if (!derived) + return SECFailure; + + *keyp = derived; + +#ifdef TRACE + if (ssl_trace >= 10) { + /* Make sure the label is null terminated. */ + char labelStr[100]; + PORT_Memcpy(labelStr, label, labelLen); + labelStr[labelLen] = 0; + SSL_TRC(50, ("HKDF Expand: label=[TLS 1.3, ] + '%s',requested length=%d", + labelStr, keySize)); + } + PRINT_KEY(50, (NULL, "PRK", prk)); + PRINT_BUF(50, (NULL, "Hash", handshakeHash, handshakeHashLen)); + PRINT_BUF(50, (NULL, "Info", info, infoLen)); + PRINT_KEY(50, (NULL, "Derived key", derived)); +#endif + + return SECSuccess; + +abort: + PORT_SetError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE); + return SECFailure; +} + +SECStatus +tls13_HkdfExpandLabelRaw(PK11SymKey *prk, SSLHashType baseHash, + const PRUint8 *handshakeHash, unsigned int handshakeHashLen, + const char *label, unsigned int labelLen, + unsigned char *output, unsigned int outputLen) +{ + PK11SymKey *derived = NULL; + SECItem *rawkey; + SECStatus rv; + + rv = tls13_HkdfExpandLabel(prk, baseHash, handshakeHash, handshakeHashLen, + label, labelLen, + kTlsHkdfInfo[baseHash].pkcs11Mech, outputLen, + &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/nss/lib/ssl/tls13hkdf.h b/nss/lib/ssl/tls13hkdf.h new file mode 100644 index 0000000..78347a1 --- /dev/null +++ b/nss/lib/ssl/tls13hkdf.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 __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, + 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, + PK11SymKey **keyp); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/nss/lib/ssl/unix_err.c b/nss/lib/ssl/unix_err.c index 1857cfe..d4390b8 100644 --- a/nss/lib/ssl/unix_err.c +++ b/nss/lib/ssl/unix_err.c @@ -1,12 +1,12 @@ /* -*- 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 + * 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/. */ @@ -18,7 +18,7 @@ #include "prerror.h" #endif -#if defined (__bsdi__) || defined(NTO) || defined(DARWIN) || defined(BEOS) +#if defined(__bsdi__) || defined(NTO) || defined(DARWIN) || defined(BEOS) #undef _PR_POLL_AVAILABLE #endif @@ -30,357 +30,547 @@ /* forward declarations. */ void nss_MD_unix_map_default_error(int err); -void nss_MD_unix_map_opendir_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) +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; + 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) +void +nss_MD_unix_readdir_error(int err) { PRErrorCode prError; switch (err) { - case ENOENT: prError = PR_NO_MORE_FILES_ERROR; break; + case ENOENT: + prError = PR_NO_MORE_FILES_ERROR; + break; #ifdef EOVERFLOW - case EOVERFLOW: prError = PR_IO_ERROR; break; + 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; + 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) +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; + 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) +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; + 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) +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; + 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) +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; + 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) +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; + 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) +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) +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; + 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) +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; + 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) +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; + 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) +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) +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; + 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) +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; + 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) +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; + 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) +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) +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) +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) +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) +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) +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) +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; + 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) +void +nss_MD_unix_map_connect_error(int err) { PRErrorCode prError; switch (err) { - case EACCES: prError = PR_ADDRESS_NOT_SUPPORTED_ERROR; break; + 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; + /* + * 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; + 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) +void +nss_MD_unix_map_bind_error(int err) { PRErrorCode prError; switch (err) { - case EINVAL: prError = PR_SOCKET_ADDRESS_IS_BOUND_ERROR; break; + 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; + * 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) +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) +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) +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; + 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) +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; + 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) +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; + 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) +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; + 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) +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; + 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) +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; + 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) +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; + 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) +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) +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) +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; + 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) +void +nss_MD_unix_map_poll_revents_error(int err) { if (err & POLLNVAL) PR_SetError(PR_BAD_DESCRIPTOR_ERROR, EBADF); @@ -393,125 +583,255 @@ void nss_MD_unix_map_poll_revents_error(int err) } #endif /* _PR_POLL_AVAILABLE */ - -void nss_MD_unix_map_flock_error(int err) +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; + 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) +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; + 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) +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) +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; - /* + 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; + case EALREADY: + prError = PR_ALREADY_INITIATED_ERROR; + break; #endif - case EBADF: prError = PR_BAD_DESCRIPTOR_ERROR; break; + case EBADF: + prError = PR_BAD_DESCRIPTOR_ERROR; + break; #ifdef EBADMSG - case EBADMSG: prError = PR_IO_ERROR; break; + 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; + 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; + case EDIRCORRUPTED: + prError = PR_DIRECTORY_CORRUPTED_ERROR; + break; #endif #ifdef EDQUOT - case EDQUOT: prError = PR_NO_DEVICE_SPACE_ERROR; break; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + 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; + case EWOULDBLOCK: + prError = PR_WOULD_BLOCK_ERROR; + break; #endif - case EXDEV: prError = PR_NOT_SAME_DEVICE_ERROR; break; + case EXDEV: + prError = PR_NOT_SAME_DEVICE_ERROR; + break; - default: prError = PR_UNKNOWN_ERROR; break; + default: + prError = PR_UNKNOWN_ERROR; + break; } PR_SetError(prError, err); } diff --git a/nss/lib/ssl/unix_err.h b/nss/lib/ssl/unix_err.h index be7fe29..5d7d547 100644 --- a/nss/lib/ssl/unix_err.h +++ b/nss/lib/ssl/unix_err.h @@ -1,11 +1,11 @@ /* * This file essentially replicates NSPR's source for the functions that - * map system-specific error codes to NSPR error codes. We would use + * 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/. */ diff --git a/nss/lib/ssl/win32err.c b/nss/lib/ssl/win32err.c index a70010d..caa12b9 100644 --- a/nss/lib/ssl/win32err.c +++ b/nss/lib/ssl/win32err.c @@ -1,12 +1,12 @@ /* -*- 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 + * 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/. */ @@ -33,79 +33,94 @@ /* forward declaration. */ void nss_MD_win32_map_default_error(PRInt32 err); -void nss_MD_win32_map_opendir_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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +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) +void +nss_MD_win32_map_fsync_error(PRInt32 err) { nss_MD_win32_map_default_error(err); } @@ -113,231 +128,423 @@ void nss_MD_win32_map_fsync_error(PRInt32 err) /* * For both CloseHandle() and closesocket(). */ -void nss_MD_win32_map_close_error(PRInt32 err) +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) +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) +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) +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) +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; + 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) +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; + 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) +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; + 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) +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) +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; + 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) +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; + 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) +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; + 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) +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) +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; + 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) +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) +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) +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) +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) +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. +** context, WSAENOTSOCK is equivalent to EBADF on Unix. */ -void nss_MD_win32_map_select_error(PRInt32 err) +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; + 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) +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) +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; + 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; + 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; + 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/nss/lib/ssl/win32err.h b/nss/lib/ssl/win32err.h index 8ce588e..a698849 100644 --- a/nss/lib/ssl/win32err.h +++ b/nss/lib/ssl/win32err.h @@ -1,11 +1,11 @@ /* * This file essentially replicates NSPR's source for the functions that - * map system-specific error codes to NSPR error codes. We would use + * 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/. */ |