Home | History | Annotate | Download | only in ssl
      1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
      2 /*
      3  * SSL3 Protocol
      4  *
      5  * This Source Code Form is subject to the terms of the Mozilla Public
      6  * License, v. 2.0. If a copy of the MPL was not distributed with this
      7  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      8 
      9 /* TODO(ekr): Implement HelloVerifyRequest on server side. OK for now. */
     10 
     11 #include "cert.h"
     12 #include "ssl.h"
     13 #include "cryptohi.h"	/* for DSAU_ stuff */
     14 #include "keyhi.h"
     15 #include "secder.h"
     16 #include "secitem.h"
     17 #include "sechash.h"
     18 
     19 #include "sslimpl.h"
     20 #include "sslproto.h"
     21 #include "sslerr.h"
     22 #include "prtime.h"
     23 #include "prinrval.h"
     24 #include "prerror.h"
     25 #include "pratom.h"
     26 #include "prthread.h"
     27 
     28 #include "pk11func.h"
     29 #include "secmod.h"
     30 #ifndef NO_PKCS11_BYPASS
     31 #include "blapi.h"
     32 #endif
     33 
     34 /* This is a bodge to allow this code to be compiled against older NSS headers
     35  * that don't contain the TLS 1.2 changes. */
     36 #ifndef CKM_NSS_TLS_PRF_GENERAL_SHA256
     37 #define CKM_NSS_TLS_PRF_GENERAL_SHA256          (CKM_NSS + 21)
     38 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256    (CKM_NSS + 22)
     39 #define CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256   (CKM_NSS + 23)
     40 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
     41 #endif
     42 
     43 /* This is a bodge to allow this code to be compiled against older NSS
     44  * headers. */
     45 #ifndef CKM_NSS_CHACHA20_POLY1305
     46 #define CKM_NSS_CHACHA20_POLY1305               (CKM_NSS + 26)
     47 
     48 typedef struct CK_NSS_AEAD_PARAMS {
     49     CK_BYTE_PTR  pIv;  /* This is the nonce. */
     50     CK_ULONG     ulIvLen;
     51     CK_BYTE_PTR  pAAD;
     52     CK_ULONG     ulAADLen;
     53     CK_ULONG     ulTagLen;
     54 } CK_NSS_AEAD_PARAMS;
     55 
     56 #endif
     57 
     58 #include <stdio.h>
     59 #ifdef NSS_ENABLE_ZLIB
     60 #include "zlib.h"
     61 #endif
     62 #ifdef LINUX
     63 #include <dlfcn.h>
     64 #endif
     65 
     66 #ifndef PK11_SETATTRS
     67 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
     68 		(x)->pValue=(v); (x)->ulValueLen = (l);
     69 #endif
     70 
     71 static SECStatus ssl3_AuthCertificate(sslSocket *ss);
     72 static void      ssl3_CleanupPeerCerts(sslSocket *ss);
     73 static void      ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid);
     74 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
     75                                        PK11SlotInfo * serverKeySlot);
     76 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
     77 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
     78 static SECStatus ssl3_HandshakeFailure(      sslSocket *ss);
     79 static SECStatus ssl3_InitState(             sslSocket *ss);
     80 static SECStatus ssl3_SendCertificate(       sslSocket *ss);
     81 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss);
     82 static SECStatus ssl3_SendEmptyCertificate(  sslSocket *ss);
     83 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
     84 static SECStatus ssl3_SendNextProto(         sslSocket *ss);
     85 static SECStatus ssl3_SendEncryptedExtensions(sslSocket *ss);
     86 static SECStatus ssl3_SendFinished(          sslSocket *ss, PRInt32 flags);
     87 static SECStatus ssl3_SendServerHello(       sslSocket *ss);
     88 static SECStatus ssl3_SendServerHelloDone(   sslSocket *ss);
     89 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss);
     90 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss,
     91                                              const unsigned char *b,
     92                                              unsigned int l);
     93 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
     94 static int       ssl3_OIDToTLSHashAlgorithm(SECOidTag oid);
     95 
     96 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
     97 			     int maxOutputLen, const unsigned char *input,
     98 			     int inputLen);
     99 #ifndef NO_PKCS11_BYPASS
    100 static SECStatus ssl3_AESGCMBypass(ssl3KeyMaterial *keys, PRBool doDecrypt,
    101 				   unsigned char *out, int *outlen, int maxout,
    102 				   const unsigned char *in, int inlen,
    103 				   const unsigned char *additionalData,
    104 				   int additionalDataLen);
    105 #endif
    106 
    107 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
    108 #define MIN_SEND_BUF_LENGTH  4000
    109 
    110 /* This list of SSL3 cipher suites is sorted in descending order of
    111  * precedence (desirability).  It only includes cipher suites we implement.
    112  * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
    113  * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
    114  */
    115 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
    116    /*      cipher_suite                         policy      enabled is_present*/
    117 #ifdef NSS_ENABLE_ECC
    118  { TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    119  { TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    120  { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    121  { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    122 #endif /* NSS_ENABLE_ECC */
    123  { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,    SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    124  { TLS_RSA_WITH_AES_128_GCM_SHA256,        SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    125 
    126 #ifdef NSS_ENABLE_ECC
    127  { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    128  { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    129 #endif /* NSS_ENABLE_ECC */
    130  { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    131  { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    132  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    133  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,    SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    134  { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    135 #ifdef NSS_ENABLE_ECC
    136  { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    137  { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    138 #endif /* NSS_ENABLE_ECC */
    139  { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    140  { TLS_RSA_WITH_AES_256_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    141  { TLS_RSA_WITH_AES_256_CBC_SHA256,	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    142 
    143 #ifdef NSS_ENABLE_ECC
    144  { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,       SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    145  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    146  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    147  { TLS_ECDHE_RSA_WITH_RC4_128_SHA,         SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    148  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    149  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    150 #endif /* NSS_ENABLE_ECC */
    151  { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    152  { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    153  { TLS_DHE_DSS_WITH_RC4_128_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    154  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,       SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    155  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,    SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    156  { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    157 #ifdef NSS_ENABLE_ECC
    158  { TLS_ECDH_RSA_WITH_RC4_128_SHA,          SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    159  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    160  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,        SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    161  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    162 #endif /* NSS_ENABLE_ECC */
    163  { TLS_RSA_WITH_SEED_CBC_SHA,              SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    164  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    165  { SSL_RSA_WITH_RC4_128_SHA,               SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    166  { SSL_RSA_WITH_RC4_128_MD5,               SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
    167  { TLS_RSA_WITH_AES_128_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    168  { TLS_RSA_WITH_AES_128_CBC_SHA256,	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    169 
    170 #ifdef NSS_ENABLE_ECC
    171  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    172  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    173 #endif /* NSS_ENABLE_ECC */
    174  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    175  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    176 #ifdef NSS_ENABLE_ECC
    177  { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    178  { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    179 #endif /* NSS_ENABLE_ECC */
    180  { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    181  { SSL_RSA_WITH_3DES_EDE_CBC_SHA,          SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
    182 
    183 
    184  { SSL_DHE_RSA_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    185  { SSL_DHE_DSS_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    186  { SSL_RSA_FIPS_WITH_DES_CBC_SHA,          SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    187  { SSL_RSA_WITH_DES_CBC_SHA,               SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    188  { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,     SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    189  { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    190 
    191  { SSL_RSA_EXPORT_WITH_RC4_40_MD5,         SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    192  { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,     SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    193 
    194 #ifdef NSS_ENABLE_ECC
    195  { TLS_ECDHE_ECDSA_WITH_NULL_SHA,          SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    196  { TLS_ECDHE_RSA_WITH_NULL_SHA,            SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    197  { TLS_ECDH_RSA_WITH_NULL_SHA,             SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    198  { TLS_ECDH_ECDSA_WITH_NULL_SHA,           SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    199 #endif /* NSS_ENABLE_ECC */
    200  { SSL_RSA_WITH_NULL_SHA,                  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    201  { TLS_RSA_WITH_NULL_SHA256,               SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    202  { SSL_RSA_WITH_NULL_MD5,                  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    203 
    204 };
    205 
    206 /* This list of SSL3 compression methods is sorted in descending order of
    207  * precedence (desirability).  It only includes compression methods we
    208  * implement.
    209  */
    210 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = {
    211 #ifdef NSS_ENABLE_ZLIB
    212     ssl_compression_deflate,
    213 #endif
    214     ssl_compression_null
    215 };
    216 
    217 static const int compressionMethodsCount =
    218     sizeof(compressions) / sizeof(compressions[0]);
    219 
    220 /* compressionEnabled returns true iff the compression algorithm is enabled
    221  * for the given SSL socket. */
    222 static PRBool
    223 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
    224 {
    225     switch (compression) {
    226     case ssl_compression_null:
    227 	return PR_TRUE;  /* Always enabled */
    228 #ifdef NSS_ENABLE_ZLIB
    229     case ssl_compression_deflate:
    230 	return ss->opt.enableDeflate;
    231 #endif
    232     default:
    233 	return PR_FALSE;
    234     }
    235 }
    236 
    237 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
    238     ct_RSA_sign,
    239 #ifdef NSS_ENABLE_ECC
    240     ct_ECDSA_sign,
    241 #endif /* NSS_ENABLE_ECC */
    242     ct_DSS_sign,
    243 };
    244 
    245 /* This block is the contents of the supported_signature_algorithms field of
    246  * our TLS 1.2 CertificateRequest message, in wire format. See
    247  * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
    248  *
    249  * This block contains only sha256 entries because we only support TLS 1.2
    250  * CertificateVerify messages that use the handshake hash. */
    251 static const PRUint8 supported_signature_algorithms[] = {
    252     tls_hash_sha256, tls_sig_rsa,
    253 #ifdef NSS_ENABLE_ECC
    254     tls_hash_sha256, tls_sig_ecdsa,
    255 #endif
    256     tls_hash_sha256, tls_sig_dsa,
    257 };
    258 
    259 #define EXPORT_RSA_KEY_LENGTH 64	/* bytes */
    260 
    261 
    262 /* This global item is used only in servers.  It is is initialized by
    263 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
    264 */
    265 CERTDistNames *ssl3_server_ca_list = NULL;
    266 static SSL3Statistics ssl3stats;
    267 
    268 /* indexed by SSL3BulkCipher */
    269 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
    270     /*                                       |--------- Lengths --------| */
    271     /* cipher             calg               k  s  type         i  b  t  n */
    272     /*                                       e  e               v  l  a  o */
    273     /*                                       y  c               |  o  g  n */
    274     /*                                       |  r               |  c  |  c */
    275     /*                                       |  e               |  k  |  e */
    276     /*                                       |  t               |  |  |  | */
    277     {cipher_null,         calg_null,         0, 0, type_stream, 0, 0, 0, 0},
    278     {cipher_rc4,          calg_rc4,         16,16, type_stream, 0, 0, 0, 0},
    279     {cipher_rc4_40,       calg_rc4,         16, 5, type_stream, 0, 0, 0, 0},
    280     {cipher_rc4_56,       calg_rc4,         16, 7, type_stream, 0, 0, 0, 0},
    281     {cipher_rc2,          calg_rc2,         16,16, type_block,  8, 8, 0, 0},
    282     {cipher_rc2_40,       calg_rc2,         16, 5, type_block,  8, 8, 0, 0},
    283     {cipher_des,          calg_des,          8, 8, type_block,  8, 8, 0, 0},
    284     {cipher_3des,         calg_3des,        24,24, type_block,  8, 8, 0, 0},
    285     {cipher_des40,        calg_des,          8, 5, type_block,  8, 8, 0, 0},
    286     {cipher_idea,         calg_idea,        16,16, type_block,  8, 8, 0, 0},
    287     {cipher_aes_128,      calg_aes,         16,16, type_block, 16,16, 0, 0},
    288     {cipher_aes_256,      calg_aes,         32,32, type_block, 16,16, 0, 0},
    289     {cipher_camellia_128, calg_camellia,    16,16, type_block, 16,16, 0, 0},
    290     {cipher_camellia_256, calg_camellia,    32,32, type_block, 16,16, 0, 0},
    291     {cipher_seed,         calg_seed,        16,16, type_block, 16,16, 0, 0},
    292     {cipher_aes_128_gcm,  calg_aes_gcm,     16,16, type_aead,   4, 0,16, 8},
    293     {cipher_chacha20,     calg_chacha20,    32,32, type_aead,   0, 0,16, 0},
    294     {cipher_missing,      calg_null,         0, 0, type_stream, 0, 0, 0, 0},
    295 };
    296 
    297 static const ssl3KEADef kea_defs[] =
    298 { /* indexed by SSL3KeyExchangeAlgorithm */
    299     /* kea              exchKeyType signKeyType is_limited limit  tls_keygen */
    300     {kea_null,           kt_null,     sign_null, PR_FALSE,   0, PR_FALSE},
    301     {kea_rsa,            kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_FALSE},
    302     {kea_rsa_export,     kt_rsa,      sign_rsa,  PR_TRUE,  512, PR_FALSE},
    303     {kea_rsa_export_1024,kt_rsa,      sign_rsa,  PR_TRUE, 1024, PR_FALSE},
    304     {kea_dh_dss,         kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
    305     {kea_dh_dss_export,  kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
    306     {kea_dh_rsa,         kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
    307     {kea_dh_rsa_export,  kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
    308     {kea_dhe_dss,        kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
    309     {kea_dhe_dss_export, kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
    310     {kea_dhe_rsa,        kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
    311     {kea_dhe_rsa_export, kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
    312     {kea_dh_anon,        kt_dh,       sign_null, PR_FALSE,   0, PR_FALSE},
    313     {kea_dh_anon_export, kt_dh,       sign_null, PR_TRUE,  512, PR_FALSE},
    314     {kea_rsa_fips,       kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_TRUE },
    315 #ifdef NSS_ENABLE_ECC
    316     {kea_ecdh_ecdsa,     kt_ecdh,     sign_ecdsa,  PR_FALSE, 0, PR_FALSE},
    317     {kea_ecdhe_ecdsa,    kt_ecdh,     sign_ecdsa,  PR_FALSE,   0, PR_FALSE},
    318     {kea_ecdh_rsa,       kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
    319     {kea_ecdhe_rsa,      kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
    320     {kea_ecdh_anon,      kt_ecdh,     sign_null,  PR_FALSE,   0, PR_FALSE},
    321 #endif /* NSS_ENABLE_ECC */
    322 };
    323 
    324 /* must use ssl_LookupCipherSuiteDef to access */
    325 static const ssl3CipherSuiteDef cipher_suite_defs[] =
    326 {
    327 /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg */
    328 
    329     {SSL_NULL_WITH_NULL_NULL,       cipher_null,   mac_null, kea_null},
    330     {SSL_RSA_WITH_NULL_MD5,         cipher_null,   mac_md5, kea_rsa},
    331     {SSL_RSA_WITH_NULL_SHA,         cipher_null,   mac_sha, kea_rsa},
    332     {TLS_RSA_WITH_NULL_SHA256,      cipher_null,   hmac_sha256, kea_rsa},
    333     {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
    334     {SSL_RSA_WITH_RC4_128_MD5,      cipher_rc4,    mac_md5, kea_rsa},
    335     {SSL_RSA_WITH_RC4_128_SHA,      cipher_rc4,    mac_sha, kea_rsa},
    336     {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
    337                                     cipher_rc2_40, mac_md5, kea_rsa_export},
    338 #if 0 /* not implemented */
    339     {SSL_RSA_WITH_IDEA_CBC_SHA,     cipher_idea,   mac_sha, kea_rsa},
    340     {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
    341                                     cipher_des40,  mac_sha, kea_rsa_export},
    342 #endif
    343     {SSL_RSA_WITH_DES_CBC_SHA,      cipher_des,    mac_sha, kea_rsa},
    344     {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,   mac_sha, kea_rsa},
    345     {SSL_DHE_DSS_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_dss},
    346     {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
    347                                     cipher_3des,   mac_sha, kea_dhe_dss},
    348     {TLS_DHE_DSS_WITH_RC4_128_SHA,  cipher_rc4,    mac_sha, kea_dhe_dss},
    349 #if 0 /* not implemented */
    350     {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
    351                                     cipher_des40,  mac_sha, kea_dh_dss_export},
    352     {SSL_DH_DSS_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_dss},
    353     {SSL_DH_DSS_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_dss},
    354     {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
    355                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
    356     {SSL_DH_RSA_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_rsa},
    357     {SSL_DH_RSA_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_rsa},
    358     {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
    359                                     cipher_des40,  mac_sha, kea_dh_dss_export},
    360     {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
    361                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
    362 #endif
    363     {SSL_DHE_RSA_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_rsa},
    364     {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
    365                                     cipher_3des,   mac_sha, kea_dhe_rsa},
    366 #if 0
    367     {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
    368     {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
    369                                     cipher_des40,  mac_sha, kea_dh_anon_export},
    370     {SSL_DH_ANON_DES_CBC_SHA,       cipher_des,    mac_sha, kea_dh_anon},
    371     {SSL_DH_ANON_3DES_CBC_SHA,      cipher_3des,   mac_sha, kea_dh_anon},
    372 #endif
    373 
    374 
    375 /* New TLS cipher suites */
    376     {TLS_RSA_WITH_AES_128_CBC_SHA,     	cipher_aes_128, mac_sha, kea_rsa},
    377     {TLS_RSA_WITH_AES_128_CBC_SHA256,	cipher_aes_128, hmac_sha256, kea_rsa},
    378     {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dhe_dss},
    379     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dhe_rsa},
    380     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa},
    381     {TLS_RSA_WITH_AES_256_CBC_SHA,     	cipher_aes_256, mac_sha, kea_rsa},
    382     {TLS_RSA_WITH_AES_256_CBC_SHA256,	cipher_aes_256, hmac_sha256, kea_rsa},
    383     {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dhe_dss},
    384     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dhe_rsa},
    385     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa},
    386 #if 0
    387     {TLS_DH_DSS_WITH_AES_128_CBC_SHA,  	cipher_aes_128, mac_sha, kea_dh_dss},
    388     {TLS_DH_RSA_WITH_AES_128_CBC_SHA,  	cipher_aes_128, mac_sha, kea_dh_rsa},
    389     {TLS_DH_ANON_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dh_anon},
    390     {TLS_DH_DSS_WITH_AES_256_CBC_SHA,  	cipher_aes_256, mac_sha, kea_dh_dss},
    391     {TLS_DH_RSA_WITH_AES_256_CBC_SHA,  	cipher_aes_256, mac_sha, kea_dh_rsa},
    392     {TLS_DH_ANON_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dh_anon},
    393 #endif
    394 
    395     {TLS_RSA_WITH_SEED_CBC_SHA,	    cipher_seed,   mac_sha, kea_rsa},
    396 
    397     {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
    398     {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
    399      cipher_camellia_128, mac_sha, kea_dhe_dss},
    400     {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
    401      cipher_camellia_128, mac_sha, kea_dhe_rsa},
    402     {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,	cipher_camellia_256, mac_sha, kea_rsa},
    403     {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
    404      cipher_camellia_256, mac_sha, kea_dhe_dss},
    405     {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
    406      cipher_camellia_256, mac_sha, kea_dhe_rsa},
    407 
    408     {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
    409                                     cipher_des,    mac_sha,kea_rsa_export_1024},
    410     {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
    411                                     cipher_rc4_56, mac_sha,kea_rsa_export_1024},
    412 
    413     {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
    414     {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des,    mac_sha, kea_rsa_fips},
    415 
    416     {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa},
    417     {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa},
    418     {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa},
    419     {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa},
    420     {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdhe_rsa},
    421     {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, cipher_chacha20, mac_aead, kea_ecdhe_ecdsa},
    422 
    423 #ifdef NSS_ENABLE_ECC
    424     {TLS_ECDH_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdh_ecdsa},
    425     {TLS_ECDH_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdh_ecdsa},
    426     {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
    427     {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
    428     {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
    429 
    430     {TLS_ECDHE_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdhe_ecdsa},
    431     {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
    432     {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
    433     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
    434     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa},
    435     {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
    436 
    437     {TLS_ECDH_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_rsa},
    438     {TLS_ECDH_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_rsa},
    439     {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_rsa},
    440     {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_rsa},
    441     {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_rsa},
    442 
    443     {TLS_ECDHE_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdhe_rsa},
    444     {TLS_ECDHE_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdhe_rsa},
    445     {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdhe_rsa},
    446     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdhe_rsa},
    447     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa},
    448     {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdhe_rsa},
    449 
    450 #if 0
    451     {TLS_ECDH_anon_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_anon},
    452     {TLS_ECDH_anon_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_anon},
    453     {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_anon},
    454     {TLS_ECDH_anon_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_anon},
    455     {TLS_ECDH_anon_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_anon},
    456 #endif
    457 #endif /* NSS_ENABLE_ECC */
    458 };
    459 
    460 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
    461     0x80000000L,
    462     CKM_RSA_PKCS,
    463     CKM_DH_PKCS_DERIVE,
    464     CKM_KEA_KEY_DERIVE,
    465     CKM_ECDH1_DERIVE
    466 };
    467 
    468 typedef struct SSLCipher2MechStr {
    469     SSLCipherAlgorithm  calg;
    470     CK_MECHANISM_TYPE   cmech;
    471 } SSLCipher2Mech;
    472 
    473 /* indexed by type SSLCipherAlgorithm */
    474 static const SSLCipher2Mech alg2Mech[] = {
    475     /* calg,          cmech  */
    476     { calg_null     , (CK_MECHANISM_TYPE)0x80000000L	},
    477     { calg_rc4      , CKM_RC4				},
    478     { calg_rc2      , CKM_RC2_CBC			},
    479     { calg_des      , CKM_DES_CBC			},
    480     { calg_3des     , CKM_DES3_CBC			},
    481     { calg_idea     , CKM_IDEA_CBC			},
    482     { calg_fortezza , CKM_SKIPJACK_CBC64                },
    483     { calg_aes      , CKM_AES_CBC			},
    484     { calg_camellia , CKM_CAMELLIA_CBC			},
    485     { calg_seed     , CKM_SEED_CBC			},
    486     { calg_aes_gcm  , CKM_AES_GCM			},
    487     { calg_chacha20 , CKM_NSS_CHACHA20_POLY1305		},
    488 /*  { calg_init     , (CK_MECHANISM_TYPE)0x7fffffffL    }  */
    489 };
    490 
    491 #define mmech_invalid  (CK_MECHANISM_TYPE)0x80000000L
    492 #define mmech_md5      CKM_SSL3_MD5_MAC
    493 #define mmech_sha      CKM_SSL3_SHA1_MAC
    494 #define mmech_md5_hmac CKM_MD5_HMAC
    495 #define mmech_sha_hmac CKM_SHA_1_HMAC
    496 #define mmech_sha256_hmac CKM_SHA256_HMAC
    497 #define mmech_sha384_hmac CKM_SHA384_HMAC
    498 #define mmech_sha512_hmac CKM_SHA512_HMAC
    499 
    500 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
    501     /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
    502     /* mac      mmech       pad_size  mac_size                       */
    503     { mac_null, mmech_invalid,    0,  0          },
    504     { mac_md5,  mmech_md5,       48,  MD5_LENGTH },
    505     { mac_sha,  mmech_sha,       40,  SHA1_LENGTH},
    506     {hmac_md5,  mmech_md5_hmac,   0,  MD5_LENGTH },
    507     {hmac_sha,  mmech_sha_hmac,   0,  SHA1_LENGTH},
    508     {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH},
    509     { mac_aead, mmech_invalid,    0,  0          },
    510 };
    511 
    512 /* indexed by SSL3BulkCipher */
    513 const char * const ssl3_cipherName[] = {
    514     "NULL",
    515     "RC4",
    516     "RC4-40",
    517     "RC4-56",
    518     "RC2-CBC",
    519     "RC2-CBC-40",
    520     "DES-CBC",
    521     "3DES-EDE-CBC",
    522     "DES-CBC-40",
    523     "IDEA-CBC",
    524     "AES-128",
    525     "AES-256",
    526     "Camellia-128",
    527     "Camellia-256",
    528     "SEED-CBC",
    529     "AES-128-GCM",
    530     "missing"
    531 };
    532 
    533 #ifdef NSS_ENABLE_ECC
    534 /* The ECCWrappedKeyInfo structure defines how various pieces of
    535  * information are laid out within wrappedSymmetricWrappingkey
    536  * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
    537  * a 512-byte buffer (see sslimpl.h), the variable length field
    538  * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
    539  *
    540  * XXX For now, NSS only supports named elliptic curves of size 571 bits
    541  * or smaller. The public value will fit within 145 bytes and EC params
    542  * will fit within 12 bytes. We'll need to revisit this when NSS
    543  * supports arbitrary curves.
    544  */
    545 #define MAX_EC_WRAPPED_KEY_BUFLEN  504
    546 
    547 typedef struct ECCWrappedKeyInfoStr {
    548     PRUint16 size;            /* EC public key size in bits */
    549     PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
    550     PRUint16 pubValueLen;     /* length (in bytes) of EC public value */
    551     PRUint16 wrappedKeyLen;   /* length (in bytes) of the wrapped key */
    552     PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
    553     /* EC public-key params, the EC public value and the wrapped key  */
    554 } ECCWrappedKeyInfo;
    555 #endif /* NSS_ENABLE_ECC */
    556 
    557 #if defined(TRACE)
    558 
    559 static char *
    560 ssl3_DecodeHandshakeType(int msgType)
    561 {
    562     char * rv;
    563     static char line[40];
    564 
    565     switch(msgType) {
    566     case hello_request:	        rv = "hello_request (0)";               break;
    567     case client_hello:	        rv = "client_hello  (1)";               break;
    568     case server_hello:	        rv = "server_hello  (2)";               break;
    569     case hello_verify_request:  rv = "hello_verify_request (3)";        break;
    570     case certificate:	        rv = "certificate  (11)";               break;
    571     case server_key_exchange:	rv = "server_key_exchange (12)";        break;
    572     case certificate_request:	rv = "certificate_request (13)";        break;
    573     case server_hello_done:	rv = "server_hello_done   (14)";        break;
    574     case certificate_verify:	rv = "certificate_verify  (15)";        break;
    575     case client_key_exchange:	rv = "client_key_exchange (16)";        break;
    576     case finished:	        rv = "finished     (20)";               break;
    577     default:
    578         sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
    579 	rv = line;
    580     }
    581     return rv;
    582 }
    583 
    584 static char *
    585 ssl3_DecodeContentType(int msgType)
    586 {
    587     char * rv;
    588     static char line[40];
    589 
    590     switch(msgType) {
    591     case content_change_cipher_spec:
    592                                 rv = "change_cipher_spec (20)";         break;
    593     case content_alert:	        rv = "alert      (21)";                 break;
    594     case content_handshake:	rv = "handshake  (22)";                 break;
    595     case content_application_data:
    596                                 rv = "application_data (23)";           break;
    597     default:
    598         sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
    599 	rv = line;
    600     }
    601     return rv;
    602 }
    603 
    604 #endif
    605 
    606 SSL3Statistics *
    607 SSL_GetStatistics(void)
    608 {
    609     return &ssl3stats;
    610 }
    611 
    612 typedef struct tooLongStr {
    613 #if defined(IS_LITTLE_ENDIAN)
    614     PRInt32 low;
    615     PRInt32 high;
    616 #else
    617     PRInt32 high;
    618     PRInt32 low;
    619 #endif
    620 } tooLong;
    621 
    622 void SSL_AtomicIncrementLong(long * x)
    623 {
    624     if ((sizeof *x) == sizeof(PRInt32)) {
    625         PR_ATOMIC_INCREMENT((PRInt32 *)x);
    626     } else {
    627     	tooLong * tl = (tooLong *)x;
    628 	if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
    629 	    PR_ATOMIC_INCREMENT(&tl->high);
    630     }
    631 }
    632 
    633 static PRBool
    634 ssl3_CipherSuiteAllowedForVersionRange(
    635     ssl3CipherSuite cipherSuite,
    636     const SSLVersionRange *vrange)
    637 {
    638     switch (cipherSuite) {
    639     /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
    640      * later. This set of cipher suites is similar to, but different from, the
    641      * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
    642      */
    643     case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
    644     case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
    645     /*   SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:      never implemented
    646      *   SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA:   never implemented
    647      *   SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA:   never implemented
    648      *   SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:  never implemented
    649      *   SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:  never implemented
    650      *   SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5:     never implemented
    651      *   SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA:  never implemented
    652      */
    653 	return vrange->min <= SSL_LIBRARY_VERSION_TLS_1_0;
    654     case TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305:
    655     case TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305:
    656     case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
    657     case TLS_RSA_WITH_AES_256_CBC_SHA256:
    658     case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
    659     case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
    660     case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
    661     case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
    662     case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
    663     case TLS_DHE_RSA_WITH_AES_128_GCM_SHA256:
    664     case TLS_RSA_WITH_AES_128_CBC_SHA256:
    665     case TLS_RSA_WITH_AES_128_GCM_SHA256:
    666     case TLS_RSA_WITH_NULL_SHA256:
    667 	return vrange->max >= SSL_LIBRARY_VERSION_TLS_1_2;
    668     default:
    669 	return PR_TRUE;
    670     }
    671 }
    672 
    673 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
    674 /* XXX This does a linear search.  A binary search would be better. */
    675 static const ssl3CipherSuiteDef *
    676 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
    677 {
    678     int cipher_suite_def_len =
    679 	sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
    680     int i;
    681 
    682     for (i = 0; i < cipher_suite_def_len; i++) {
    683 	if (cipher_suite_defs[i].cipher_suite == suite)
    684 	    return &cipher_suite_defs[i];
    685     }
    686     PORT_Assert(PR_FALSE);  /* We should never get here. */
    687     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
    688     return NULL;
    689 }
    690 
    691 /* Find the cipher configuration struct associate with suite */
    692 /* XXX This does a linear search.  A binary search would be better. */
    693 static ssl3CipherSuiteCfg *
    694 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
    695 {
    696     int i;
    697 
    698     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
    699 	if (suites[i].cipher_suite == suite)
    700 	    return &suites[i];
    701     }
    702     /* return NULL and let the caller handle it.  */
    703     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
    704     return NULL;
    705 }
    706 
    707 
    708 /* Initialize the suite->isPresent value for config_match
    709  * Returns count of enabled ciphers supported by extant tokens,
    710  * regardless of policy or user preference.
    711  * If this returns zero, the user cannot do SSL v3.
    712  */
    713 int
    714 ssl3_config_match_init(sslSocket *ss)
    715 {
    716     ssl3CipherSuiteCfg *      suite;
    717     const ssl3CipherSuiteDef *cipher_def;
    718     SSLCipherAlgorithm        cipher_alg;
    719     CK_MECHANISM_TYPE         cipher_mech;
    720     SSL3KEAType               exchKeyType;
    721     int                       i;
    722     int                       numPresent		= 0;
    723     int                       numEnabled		= 0;
    724     PRBool                    isServer;
    725     sslServerCerts           *svrAuth;
    726 
    727     PORT_Assert(ss);
    728     if (!ss) {
    729     	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    730 	return 0;
    731     }
    732     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
    733     	return 0;
    734     }
    735     isServer = (PRBool)(ss->sec.isServer != 0);
    736 
    737     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
    738 	suite = &ss->cipherSuites[i];
    739 	if (suite->enabled) {
    740 	    ++numEnabled;
    741 	    /* We need the cipher defs to see if we have a token that can handle
    742 	     * this cipher.  It isn't part of the static definition.
    743 	     */
    744 	    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
    745 	    if (!cipher_def) {
    746 	    	suite->isPresent = PR_FALSE;
    747 		continue;
    748 	    }
    749 	    cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
    750 	    PORT_Assert(  alg2Mech[cipher_alg].calg == cipher_alg);
    751 	    cipher_mech = alg2Mech[cipher_alg].cmech;
    752 	    exchKeyType =
    753 	    	    kea_defs[cipher_def->key_exchange_alg].exchKeyType;
    754 #ifndef NSS_ENABLE_ECC
    755 	    svrAuth = ss->serverCerts + exchKeyType;
    756 #else
    757 	    /* XXX SSLKEAType isn't really a good choice for
    758 	     * indexing certificates. It doesn't work for
    759 	     * (EC)DHE-* ciphers. Here we use a hack to ensure
    760 	     * that the server uses an RSA cert for (EC)DHE-RSA.
    761 	     */
    762 	    switch (cipher_def->key_exchange_alg) {
    763 	    case kea_ecdhe_rsa:
    764 #if NSS_SERVER_DHE_IMPLEMENTED
    765 	    /* XXX NSS does not yet implement the server side of _DHE_
    766 	     * cipher suites.  Correcting the computation for svrAuth,
    767 	     * as the case below does, causes NSS SSL servers to begin to
    768 	     * negotiate cipher suites they do not implement.  So, until
    769 	     * server side _DHE_ is implemented, keep this disabled.
    770 	     */
    771 	    case kea_dhe_rsa:
    772 #endif
    773 		svrAuth = ss->serverCerts + kt_rsa;
    774 		break;
    775 	    case kea_ecdh_ecdsa:
    776 	    case kea_ecdh_rsa:
    777 	        /*
    778 		 * XXX We ought to have different indices for
    779 		 * ECDSA- and RSA-signed EC certificates so
    780 		 * we could support both key exchange mechanisms
    781 		 * simultaneously. For now, both of them use
    782 		 * whatever is in the certificate slot for kt_ecdh
    783 		 */
    784 	    default:
    785 		svrAuth = ss->serverCerts + exchKeyType;
    786 		break;
    787 	    }
    788 #endif /* NSS_ENABLE_ECC */
    789 
    790 	    /* Mark the suites that are backed by real tokens, certs and keys */
    791 	    suite->isPresent = (PRBool)
    792 		(((exchKeyType == kt_null) ||
    793 		   ((!isServer || (svrAuth->serverKeyPair &&
    794 		                   svrAuth->SERVERKEY &&
    795 				   svrAuth->serverCertChain)) &&
    796 		    PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
    797 		((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
    798 	    if (suite->isPresent)
    799 	    	++numPresent;
    800 	}
    801     }
    802     PORT_Assert(numPresent > 0 || numEnabled == 0);
    803     if (numPresent <= 0) {
    804 	PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
    805     }
    806     return numPresent;
    807 }
    808 
    809 
    810 /* return PR_TRUE if suite matches policy, enabled state and is applicable to
    811  * the given version range. */
    812 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
    813 ** of a cipher that was NOT_ALLOWED.  So, if this is ever called with
    814 ** policy == SSL_NOT_ALLOWED, report no match.
    815 */
    816 /* adjust suite enabled to the availability of a token that can do the
    817  * cipher suite. */
    818 static PRBool
    819 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled,
    820 	     const SSLVersionRange *vrange)
    821 {
    822     PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
    823     if (policy == SSL_NOT_ALLOWED || !enabled)
    824     	return PR_FALSE;
    825     return (PRBool)(suite->enabled &&
    826                     suite->isPresent &&
    827 	            suite->policy != SSL_NOT_ALLOWED &&
    828 		    suite->policy <= policy &&
    829 		    ssl3_CipherSuiteAllowedForVersionRange(
    830                         suite->cipher_suite, vrange));
    831 }
    832 
    833 /* return number of cipher suites that match policy, enabled state and are
    834  * applicable for the configured protocol version range. */
    835 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
    836 static int
    837 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
    838 {
    839     int i, count = 0;
    840 
    841     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
    842     	return 0;
    843     }
    844     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
    845 	if (config_match(&ss->cipherSuites[i], policy, enabled, &ss->vrange))
    846 	    count++;
    847     }
    848     if (count <= 0) {
    849 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
    850     }
    851     return count;
    852 }
    853 
    854 /*
    855  * Null compression, mac and encryption functions
    856  */
    857 
    858 static SECStatus
    859 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
    860 	    const unsigned char *input, int inputLen)
    861 {
    862     if (inputLen > maxOutputLen) {
    863         *outputLen = 0;  /* Match PK11_CipherOp in setting outputLen */
    864         PORT_SetError(SEC_ERROR_OUTPUT_LEN);
    865         return SECFailure;
    866     }
    867     *outputLen = inputLen;
    868     if (input != output)
    869 	PORT_Memcpy(output, input, inputLen);
    870     return SECSuccess;
    871 }
    872 
    873 /*
    874  * SSL3 Utility functions
    875  */
    876 
    877 /* allowLargerPeerVersion controls whether the function will select the
    878  * highest enabled SSL version or fail when peerVersion is greater than the
    879  * highest enabled version.
    880  *
    881  * If allowLargerPeerVersion is true, peerVersion is the peer's highest
    882  * enabled version rather than the peer's selected version.
    883  */
    884 SECStatus
    885 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
    886 		      PRBool allowLargerPeerVersion)
    887 {
    888     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
    889 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
    890 	return SECFailure;
    891     }
    892 
    893     if (peerVersion < ss->vrange.min ||
    894 	(peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
    895 	PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
    896 	return SECFailure;
    897     }
    898 
    899     ss->version = PR_MIN(peerVersion, ss->vrange.max);
    900     PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
    901 
    902     return SECSuccess;
    903 }
    904 
    905 static SECStatus
    906 ssl3_GetNewRandom(SSL3Random *random)
    907 {
    908     PRUint32 gmt = ssl_Time();
    909     SECStatus rv;
    910 
    911     random->rand[0] = (unsigned char)(gmt >> 24);
    912     random->rand[1] = (unsigned char)(gmt >> 16);
    913     random->rand[2] = (unsigned char)(gmt >>  8);
    914     random->rand[3] = (unsigned char)(gmt);
    915 
    916     /* first 4 bytes are reserverd for time */
    917     rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
    918     if (rv != SECSuccess) {
    919 	ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
    920     }
    921     return rv;
    922 }
    923 
    924 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
    925 SECStatus
    926 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
    927                 PRBool isTLS)
    928 {
    929     SECStatus rv		= SECFailure;
    930     PRBool    doDerEncode       = PR_FALSE;
    931     int       signatureLen;
    932     SECItem   hashItem;
    933 
    934     buf->data    = NULL;
    935 
    936     switch (key->keyType) {
    937     case rsaKey:
    938 	hashItem.data = hash->u.raw;
    939 	hashItem.len = hash->len;
    940 	break;
    941     case dsaKey:
    942 	doDerEncode = isTLS;
    943 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
    944 	 * In that case, we use just the SHA1 part. */
    945 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
    946 	    hashItem.data = hash->u.s.sha;
    947 	    hashItem.len = sizeof(hash->u.s.sha);
    948 	} else {
    949 	    hashItem.data = hash->u.raw;
    950 	    hashItem.len = hash->len;
    951 	}
    952 	break;
    953 #ifdef NSS_ENABLE_ECC
    954     case ecKey:
    955 	doDerEncode = PR_TRUE;
    956 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
    957 	 * In that case, we use just the SHA1 part. */
    958 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
    959 	    hashItem.data = hash->u.s.sha;
    960 	    hashItem.len = sizeof(hash->u.s.sha);
    961 	} else {
    962 	    hashItem.data = hash->u.raw;
    963 	    hashItem.len = hash->len;
    964 	}
    965 	break;
    966 #endif /* NSS_ENABLE_ECC */
    967     default:
    968 	PORT_SetError(SEC_ERROR_INVALID_KEY);
    969 	goto done;
    970     }
    971     PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
    972 
    973     if (hash->hashAlg == SEC_OID_UNKNOWN) {
    974 	signatureLen = PK11_SignatureLen(key);
    975 	if (signatureLen <= 0) {
    976 	    PORT_SetError(SEC_ERROR_INVALID_KEY);
    977 	    goto done;
    978 	}
    979 
    980 	buf->len  = (unsigned)signatureLen;
    981 	buf->data = (unsigned char *)PORT_Alloc(signatureLen);
    982 	if (!buf->data)
    983 	    goto done;  /* error code was set. */
    984 
    985 	rv = PK11_Sign(key, buf, &hashItem);
    986     } else {
    987 	rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem);
    988     }
    989     if (rv != SECSuccess) {
    990 	ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
    991     } else if (doDerEncode) {
    992 	SECItem   derSig	= {siBuffer, NULL, 0};
    993 
    994 	/* This also works for an ECDSA signature */
    995 	rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
    996 	if (rv == SECSuccess) {
    997 	    PORT_Free(buf->data);	/* discard unencoded signature. */
    998 	    *buf = derSig;		/* give caller encoded signature. */
    999 	} else if (derSig.data) {
   1000 	    PORT_Free(derSig.data);
   1001 	}
   1002     }
   1003 
   1004     PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
   1005 done:
   1006     if (rv != SECSuccess && buf->data) {
   1007 	PORT_Free(buf->data);
   1008 	buf->data = NULL;
   1009     }
   1010     return rv;
   1011 }
   1012 
   1013 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
   1014 SECStatus
   1015 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
   1016                         SECItem *buf, PRBool isTLS, void *pwArg)
   1017 {
   1018     SECKEYPublicKey * key;
   1019     SECItem *         signature	= NULL;
   1020     SECStatus         rv;
   1021     SECItem           hashItem;
   1022     SECOidTag         encAlg;
   1023     SECOidTag         hashAlg;
   1024 
   1025 
   1026     PRINT_BUF(60, (NULL, "check signed hashes",
   1027                   buf->data, buf->len));
   1028 
   1029     key = CERT_ExtractPublicKey(cert);
   1030     if (key == NULL) {
   1031 	ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   1032     	return SECFailure;
   1033     }
   1034 
   1035     hashAlg = hash->hashAlg;
   1036     switch (key->keyType) {
   1037     case rsaKey:
   1038 	encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
   1039 	hashItem.data = hash->u.raw;
   1040 	hashItem.len = hash->len;
   1041 	break;
   1042     case dsaKey:
   1043 	encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
   1044 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
   1045 	 * In that case, we use just the SHA1 part. */
   1046 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
   1047 	    hashItem.data = hash->u.s.sha;
   1048 	    hashItem.len = sizeof(hash->u.s.sha);
   1049 	} else {
   1050 	    hashItem.data = hash->u.raw;
   1051 	    hashItem.len = hash->len;
   1052 	}
   1053 	/* Allow DER encoded DSA signatures in SSL 3.0 */
   1054 	if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
   1055 	    signature = DSAU_DecodeDerSig(buf);
   1056 	    if (!signature) {
   1057 	    	PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   1058 		return SECFailure;
   1059 	    }
   1060 	    buf = signature;
   1061 	}
   1062 	break;
   1063 
   1064 #ifdef NSS_ENABLE_ECC
   1065     case ecKey:
   1066 	encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
   1067 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
   1068 	 * In that case, we use just the SHA1 part.
   1069 	 * ECDSA signatures always encode the integers r and s using ASN.1
   1070 	 * (unlike DSA where ASN.1 encoding is used with TLS but not with
   1071 	 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
   1072 	 */
   1073 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
   1074 	    hashAlg = SEC_OID_SHA1;
   1075 	    hashItem.data = hash->u.s.sha;
   1076 	    hashItem.len = sizeof(hash->u.s.sha);
   1077 	} else {
   1078 	    hashItem.data = hash->u.raw;
   1079 	    hashItem.len = hash->len;
   1080 	}
   1081 	break;
   1082 #endif /* NSS_ENABLE_ECC */
   1083 
   1084     default:
   1085     	SECKEY_DestroyPublicKey(key);
   1086 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   1087 	return SECFailure;
   1088     }
   1089 
   1090     PRINT_BUF(60, (NULL, "hash(es) to be verified",
   1091                   hashItem.data, hashItem.len));
   1092 
   1093     if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
   1094 	/* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
   1095 	 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
   1096 	 * above always removes the DER encoding of DSA signatures when
   1097 	 * present. Thus DSA signatures are always verified with PK11_Verify.
   1098 	 */
   1099 	rv = PK11_Verify(key, buf, &hashItem, pwArg);
   1100     } else {
   1101 	rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
   1102 				    pwArg);
   1103     }
   1104     SECKEY_DestroyPublicKey(key);
   1105     if (signature) {
   1106     	SECITEM_FreeItem(signature, PR_TRUE);
   1107     }
   1108     if (rv != SECSuccess) {
   1109 	ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   1110     }
   1111     return rv;
   1112 }
   1113 
   1114 
   1115 /* Caller must set hiLevel error code. */
   1116 /* Called from ssl3_ComputeExportRSAKeyHash
   1117  *             ssl3_ComputeDHKeyHash
   1118  * which are called from ssl3_HandleServerKeyExchange.
   1119  *
   1120  * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
   1121  * the pre-1.2, MD5/SHA1 combination hash.
   1122  */
   1123 SECStatus
   1124 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
   1125 			  PRUint8 * hashBuf, unsigned int bufLen,
   1126 			  SSL3Hashes *hashes, PRBool bypassPKCS11)
   1127 {
   1128     SECStatus     rv 		= SECSuccess;
   1129 
   1130 #ifndef NO_PKCS11_BYPASS
   1131     if (bypassPKCS11) {
   1132 	if (hashAlg == SEC_OID_UNKNOWN) {
   1133 	    MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen);
   1134 	    SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
   1135 	    hashes->len = MD5_LENGTH + SHA1_LENGTH;
   1136 	} else if (hashAlg == SEC_OID_SHA1) {
   1137 	    SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1138 	    hashes->len = SHA1_LENGTH;
   1139 	} else if (hashAlg == SEC_OID_SHA256) {
   1140 	    SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1141 	    hashes->len = SHA256_LENGTH;
   1142 	} else if (hashAlg == SEC_OID_SHA384) {
   1143 	    SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1144 	    hashes->len = SHA384_LENGTH;
   1145 	} else if (hashAlg == SEC_OID_SHA512) {
   1146 	    SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1147 	    hashes->len = SHA512_LENGTH;
   1148 	} else {
   1149 	    PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   1150 	    return SECFailure;
   1151 	}
   1152     } else
   1153 #endif
   1154     {
   1155 	if (hashAlg == SEC_OID_UNKNOWN) {
   1156 	    rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
   1157 	    if (rv != SECSuccess) {
   1158 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   1159 		rv = SECFailure;
   1160 		goto done;
   1161 	    }
   1162 
   1163 	    rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
   1164 	    if (rv != SECSuccess) {
   1165 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   1166 		rv = SECFailure;
   1167 	    }
   1168 	    hashes->len = MD5_LENGTH + SHA1_LENGTH;
   1169 	} else {
   1170 	    hashes->len = HASH_ResultLenByOidTag(hashAlg);
   1171 	    if (hashes->len > sizeof(hashes->u.raw)) {
   1172 		ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   1173 		rv = SECFailure;
   1174 		goto done;
   1175 	    }
   1176 	    rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen);
   1177 	    if (rv != SECSuccess) {
   1178 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   1179 		rv = SECFailure;
   1180 	    }
   1181 	}
   1182     }
   1183     hashes->hashAlg = hashAlg;
   1184 
   1185 done:
   1186     return rv;
   1187 }
   1188 
   1189 /* Caller must set hiLevel error code.
   1190 ** Called from ssl3_SendServerKeyExchange and
   1191 **             ssl3_HandleServerKeyExchange.
   1192 */
   1193 static SECStatus
   1194 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg,
   1195 			     SECItem modulus, SECItem publicExponent,
   1196 			     SSL3Random *client_rand, SSL3Random *server_rand,
   1197 			     SSL3Hashes *hashes, PRBool bypassPKCS11)
   1198 {
   1199     PRUint8     * hashBuf;
   1200     PRUint8     * pBuf;
   1201     SECStatus     rv 		= SECSuccess;
   1202     unsigned int  bufLen;
   1203     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
   1204 
   1205     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
   1206     if (bufLen <= sizeof buf) {
   1207     	hashBuf = buf;
   1208     } else {
   1209     	hashBuf = PORT_Alloc(bufLen);
   1210 	if (!hashBuf) {
   1211 	    return SECFailure;
   1212 	}
   1213     }
   1214 
   1215     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
   1216     	pBuf = hashBuf + SSL3_RANDOM_LENGTH;
   1217     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
   1218     	pBuf += SSL3_RANDOM_LENGTH;
   1219     pBuf[0]  = (PRUint8)(modulus.len >> 8);
   1220     pBuf[1]  = (PRUint8)(modulus.len);
   1221     	pBuf += 2;
   1222     memcpy(pBuf, modulus.data, modulus.len);
   1223     	pBuf += modulus.len;
   1224     pBuf[0] = (PRUint8)(publicExponent.len >> 8);
   1225     pBuf[1] = (PRUint8)(publicExponent.len);
   1226     	pBuf += 2;
   1227     memcpy(pBuf, publicExponent.data, publicExponent.len);
   1228     	pBuf += publicExponent.len;
   1229     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
   1230 
   1231     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
   1232 				   bypassPKCS11);
   1233 
   1234     PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
   1235     if (hashAlg == SEC_OID_UNKNOWN) {
   1236 	PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
   1237 		  hashes->u.s.md5, MD5_LENGTH));
   1238 	PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
   1239 		  hashes->u.s.sha, SHA1_LENGTH));
   1240     } else {
   1241 	PRINT_BUF(95, (NULL, "RSAkey hash: result",
   1242 		  hashes->u.raw, hashes->len));
   1243     }
   1244 
   1245     if (hashBuf != buf && hashBuf != NULL)
   1246     	PORT_Free(hashBuf);
   1247     return rv;
   1248 }
   1249 
   1250 /* Caller must set hiLevel error code. */
   1251 /* Called from ssl3_HandleServerKeyExchange. */
   1252 static SECStatus
   1253 ssl3_ComputeDHKeyHash(SECOidTag hashAlg,
   1254 		      SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
   1255 		      SSL3Random *client_rand, SSL3Random *server_rand,
   1256 		      SSL3Hashes *hashes, PRBool bypassPKCS11)
   1257 {
   1258     PRUint8     * hashBuf;
   1259     PRUint8     * pBuf;
   1260     SECStatus     rv 		= SECSuccess;
   1261     unsigned int  bufLen;
   1262     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
   1263 
   1264     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
   1265     if (bufLen <= sizeof buf) {
   1266     	hashBuf = buf;
   1267     } else {
   1268     	hashBuf = PORT_Alloc(bufLen);
   1269 	if (!hashBuf) {
   1270 	    return SECFailure;
   1271 	}
   1272     }
   1273 
   1274     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
   1275     	pBuf = hashBuf + SSL3_RANDOM_LENGTH;
   1276     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
   1277     	pBuf += SSL3_RANDOM_LENGTH;
   1278     pBuf[0]  = (PRUint8)(dh_p.len >> 8);
   1279     pBuf[1]  = (PRUint8)(dh_p.len);
   1280     	pBuf += 2;
   1281     memcpy(pBuf, dh_p.data, dh_p.len);
   1282     	pBuf += dh_p.len;
   1283     pBuf[0] = (PRUint8)(dh_g.len >> 8);
   1284     pBuf[1] = (PRUint8)(dh_g.len);
   1285     	pBuf += 2;
   1286     memcpy(pBuf, dh_g.data, dh_g.len);
   1287     	pBuf += dh_g.len;
   1288     pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
   1289     pBuf[1] = (PRUint8)(dh_Ys.len);
   1290     	pBuf += 2;
   1291     memcpy(pBuf, dh_Ys.data, dh_Ys.len);
   1292     	pBuf += dh_Ys.len;
   1293     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
   1294 
   1295     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
   1296 				   bypassPKCS11);
   1297 
   1298     PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
   1299     if (hashAlg == SEC_OID_UNKNOWN) {
   1300 	PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
   1301 		  hashes->u.s.md5, MD5_LENGTH));
   1302 	PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
   1303 		  hashes->u.s.sha, SHA1_LENGTH));
   1304     } else {
   1305 	PRINT_BUF(95, (NULL, "DHkey hash: result",
   1306 		  hashes->u.raw, hashes->len));
   1307     }
   1308 
   1309     if (hashBuf != buf && hashBuf != NULL)
   1310     	PORT_Free(hashBuf);
   1311     return rv;
   1312 }
   1313 
   1314 static void
   1315 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
   1316 {
   1317     num->low++;
   1318     if (num->low == 0)
   1319 	num->high++;
   1320 }
   1321 
   1322 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
   1323 static void
   1324 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
   1325 {
   1326     if (mat->write_key != NULL) {
   1327 	PK11_FreeSymKey(mat->write_key);
   1328 	mat->write_key = NULL;
   1329     }
   1330     if (mat->write_mac_key != NULL) {
   1331 	PK11_FreeSymKey(mat->write_mac_key);
   1332 	mat->write_mac_key = NULL;
   1333     }
   1334     if (mat->write_mac_context != NULL) {
   1335 	PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
   1336 	mat->write_mac_context = NULL;
   1337     }
   1338 }
   1339 
   1340 /* Called from ssl3_SendChangeCipherSpecs() and
   1341 **	       ssl3_HandleChangeCipherSpecs()
   1342 **             ssl3_DestroySSL3Info
   1343 ** Caller must hold SpecWriteLock.
   1344 */
   1345 void
   1346 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
   1347 {
   1348     PRBool freeit = (PRBool)(!spec->bypassCiphers);
   1349 /*  PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
   1350     if (spec->destroy) {
   1351 	spec->destroy(spec->encodeContext, freeit);
   1352 	spec->destroy(spec->decodeContext, freeit);
   1353 	spec->encodeContext = NULL; /* paranoia */
   1354 	spec->decodeContext = NULL;
   1355     }
   1356     if (spec->destroyCompressContext && spec->compressContext) {
   1357 	spec->destroyCompressContext(spec->compressContext, 1);
   1358 	spec->compressContext = NULL;
   1359     }
   1360     if (spec->destroyDecompressContext && spec->decompressContext) {
   1361 	spec->destroyDecompressContext(spec->decompressContext, 1);
   1362 	spec->decompressContext = NULL;
   1363     }
   1364     if (freeSrvName && spec->srvVirtName.data) {
   1365         SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
   1366     }
   1367     if (spec->master_secret != NULL) {
   1368 	PK11_FreeSymKey(spec->master_secret);
   1369 	spec->master_secret = NULL;
   1370     }
   1371     spec->msItem.data = NULL;
   1372     spec->msItem.len  = 0;
   1373     ssl3_CleanupKeyMaterial(&spec->client);
   1374     ssl3_CleanupKeyMaterial(&spec->server);
   1375     spec->bypassCiphers = PR_FALSE;
   1376     spec->destroy=NULL;
   1377     spec->destroyCompressContext = NULL;
   1378     spec->destroyDecompressContext = NULL;
   1379 }
   1380 
   1381 /* Fill in the pending cipher spec with info from the selected ciphersuite.
   1382 ** This is as much initialization as we can do without having key material.
   1383 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
   1384 ** Caller must hold the ssl3 handshake lock.
   1385 ** Acquires & releases SpecWriteLock.
   1386 */
   1387 static SECStatus
   1388 ssl3_SetupPendingCipherSpec(sslSocket *ss)
   1389 {
   1390     ssl3CipherSpec *          pwSpec;
   1391     ssl3CipherSpec *          cwSpec;
   1392     ssl3CipherSuite           suite     = ss->ssl3.hs.cipher_suite;
   1393     SSL3MACAlgorithm          mac;
   1394     SSL3BulkCipher            cipher;
   1395     SSL3KeyExchangeAlgorithm  kea;
   1396     const ssl3CipherSuiteDef *suite_def;
   1397     PRBool                    isTLS;
   1398 
   1399     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1400 
   1401     ssl_GetSpecWriteLock(ss);  /*******************************/
   1402 
   1403     pwSpec = ss->ssl3.pwSpec;
   1404     PORT_Assert(pwSpec == ss->ssl3.prSpec);
   1405 
   1406     /* This hack provides maximal interoperability with SSL 3 servers. */
   1407     cwSpec = ss->ssl3.cwSpec;
   1408     if (cwSpec->mac_def->mac == mac_null) {
   1409 	/* SSL records are not being MACed. */
   1410 	cwSpec->version = ss->version;
   1411     }
   1412 
   1413     pwSpec->version  = ss->version;
   1414     isTLS  = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   1415 
   1416     SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
   1417 		SSL_GETPID(), ss->fd, suite));
   1418 
   1419     suite_def = ssl_LookupCipherSuiteDef(suite);
   1420     if (suite_def == NULL) {
   1421 	ssl_ReleaseSpecWriteLock(ss);
   1422 	return SECFailure;	/* error code set by ssl_LookupCipherSuiteDef */
   1423     }
   1424 
   1425     if (IS_DTLS(ss)) {
   1426 	/* Double-check that we did not pick an RC4 suite */
   1427 	PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
   1428 		    (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
   1429 		    (suite_def->bulk_cipher_alg != cipher_rc4_56));
   1430     }
   1431 
   1432     cipher = suite_def->bulk_cipher_alg;
   1433     kea    = suite_def->key_exchange_alg;
   1434     mac    = suite_def->mac_alg;
   1435     if (mac <= ssl_mac_sha && mac != ssl_mac_null && isTLS)
   1436 	mac += 2;
   1437 
   1438     ss->ssl3.hs.suite_def = suite_def;
   1439     ss->ssl3.hs.kea_def   = &kea_defs[kea];
   1440     PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
   1441 
   1442     pwSpec->cipher_def   = &bulk_cipher_defs[cipher];
   1443     PORT_Assert(pwSpec->cipher_def->cipher == cipher);
   1444 
   1445     pwSpec->mac_def = &mac_defs[mac];
   1446     PORT_Assert(pwSpec->mac_def->mac == mac);
   1447 
   1448     ss->sec.keyBits       = pwSpec->cipher_def->key_size        * BPB;
   1449     ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
   1450     ss->sec.cipherType    = cipher;
   1451 
   1452     pwSpec->encodeContext = NULL;
   1453     pwSpec->decodeContext = NULL;
   1454 
   1455     pwSpec->mac_size = pwSpec->mac_def->mac_size;
   1456 
   1457     pwSpec->compression_method = ss->ssl3.hs.compression;
   1458     pwSpec->compressContext = NULL;
   1459     pwSpec->decompressContext = NULL;
   1460 
   1461     ssl_ReleaseSpecWriteLock(ss);  /*******************************/
   1462     return SECSuccess;
   1463 }
   1464 
   1465 #ifdef NSS_ENABLE_ZLIB
   1466 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
   1467 
   1468 static SECStatus
   1469 ssl3_MapZlibError(int zlib_error)
   1470 {
   1471     switch (zlib_error) {
   1472     case Z_OK:
   1473         return SECSuccess;
   1474     default:
   1475         return SECFailure;
   1476     }
   1477 }
   1478 
   1479 static SECStatus
   1480 ssl3_DeflateInit(void *void_context)
   1481 {
   1482     z_stream *context = void_context;
   1483     context->zalloc = NULL;
   1484     context->zfree = NULL;
   1485     context->opaque = NULL;
   1486 
   1487     return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
   1488 }
   1489 
   1490 static SECStatus
   1491 ssl3_InflateInit(void *void_context)
   1492 {
   1493     z_stream *context = void_context;
   1494     context->zalloc = NULL;
   1495     context->zfree = NULL;
   1496     context->opaque = NULL;
   1497     context->next_in = NULL;
   1498     context->avail_in = 0;
   1499 
   1500     return ssl3_MapZlibError(inflateInit(context));
   1501 }
   1502 
   1503 static SECStatus
   1504 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
   1505                      int maxout, const unsigned char *in, int inlen)
   1506 {
   1507     z_stream *context = void_context;
   1508 
   1509     if (!inlen) {
   1510         *out_len = 0;
   1511         return SECSuccess;
   1512     }
   1513 
   1514     context->next_in = (unsigned char*) in;
   1515     context->avail_in = inlen;
   1516     context->next_out = out;
   1517     context->avail_out = maxout;
   1518     if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
   1519         return SECFailure;
   1520     }
   1521     if (context->avail_out == 0) {
   1522         /* We ran out of space! */
   1523         SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
   1524                     SSL_GETPID()));
   1525         return SECFailure;
   1526     }
   1527 
   1528     *out_len = maxout - context->avail_out;
   1529     return SECSuccess;
   1530 }
   1531 
   1532 static SECStatus
   1533 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
   1534                        int maxout, const unsigned char *in, int inlen)
   1535 {
   1536     z_stream *context = void_context;
   1537 
   1538     if (!inlen) {
   1539         *out_len = 0;
   1540         return SECSuccess;
   1541     }
   1542 
   1543     context->next_in = (unsigned char*) in;
   1544     context->avail_in = inlen;
   1545     context->next_out = out;
   1546     context->avail_out = maxout;
   1547     if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
   1548         PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
   1549         return SECFailure;
   1550     }
   1551 
   1552     *out_len = maxout - context->avail_out;
   1553     return SECSuccess;
   1554 }
   1555 
   1556 static SECStatus
   1557 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
   1558 {
   1559     deflateEnd(void_context);
   1560     PORT_Free(void_context);
   1561     return SECSuccess;
   1562 }
   1563 
   1564 static SECStatus
   1565 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
   1566 {
   1567     inflateEnd(void_context);
   1568     PORT_Free(void_context);
   1569     return SECSuccess;
   1570 }
   1571 
   1572 #endif /* NSS_ENABLE_ZLIB */
   1573 
   1574 /* Initialize the compression functions and contexts for the given
   1575  * CipherSpec.  */
   1576 static SECStatus
   1577 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
   1578 {
   1579     /* Setup the compression functions */
   1580     switch (pwSpec->compression_method) {
   1581     case ssl_compression_null:
   1582 	pwSpec->compressor = NULL;
   1583 	pwSpec->decompressor = NULL;
   1584 	pwSpec->compressContext = NULL;
   1585 	pwSpec->decompressContext = NULL;
   1586 	pwSpec->destroyCompressContext = NULL;
   1587 	pwSpec->destroyDecompressContext = NULL;
   1588 	break;
   1589 #ifdef NSS_ENABLE_ZLIB
   1590     case ssl_compression_deflate:
   1591 	pwSpec->compressor = ssl3_DeflateCompress;
   1592 	pwSpec->decompressor = ssl3_DeflateDecompress;
   1593 	pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
   1594 	pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
   1595 	pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
   1596 	pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
   1597 	ssl3_DeflateInit(pwSpec->compressContext);
   1598 	ssl3_InflateInit(pwSpec->decompressContext);
   1599 	break;
   1600 #endif /* NSS_ENABLE_ZLIB */
   1601     default:
   1602 	PORT_Assert(0);
   1603 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1604 	return SECFailure;
   1605     }
   1606 
   1607     return SECSuccess;
   1608 }
   1609 
   1610 #ifndef NO_PKCS11_BYPASS
   1611 /* Initialize encryption contexts for pending spec.
   1612  * MAC contexts are set up when computing the mac, not here.
   1613  * Master Secret already is derived in spec->msItem
   1614  * Caller holds Spec write lock.
   1615  */
   1616 static SECStatus
   1617 ssl3_InitPendingContextsBypass(sslSocket *ss)
   1618 {
   1619       ssl3CipherSpec  *  pwSpec;
   1620       const ssl3BulkCipherDef *cipher_def;
   1621       void *             serverContext = NULL;
   1622       void *             clientContext = NULL;
   1623       BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
   1624       int                mode     = 0;
   1625       unsigned int       optArg1  = 0;
   1626       unsigned int       optArg2  = 0;
   1627       PRBool             server_encrypts = ss->sec.isServer;
   1628       SSLCipherAlgorithm calg;
   1629       SECStatus          rv;
   1630 
   1631     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1632     PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   1633     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   1634 
   1635     pwSpec        = ss->ssl3.pwSpec;
   1636     cipher_def    = pwSpec->cipher_def;
   1637 
   1638     calg = cipher_def->calg;
   1639 
   1640     if (calg == calg_aes_gcm) {
   1641 	pwSpec->encode = NULL;
   1642 	pwSpec->decode = NULL;
   1643 	pwSpec->destroy = NULL;
   1644 	pwSpec->encodeContext = NULL;
   1645 	pwSpec->decodeContext = NULL;
   1646 	pwSpec->aead = ssl3_AESGCMBypass;
   1647 	ssl3_InitCompressionContext(pwSpec);
   1648 	return SECSuccess;
   1649     }
   1650 
   1651     serverContext = pwSpec->server.cipher_context;
   1652     clientContext = pwSpec->client.cipher_context;
   1653 
   1654     switch (calg) {
   1655     case ssl_calg_null:
   1656 	pwSpec->encode  = Null_Cipher;
   1657 	pwSpec->decode  = Null_Cipher;
   1658         pwSpec->destroy = NULL;
   1659 	goto success;
   1660 
   1661     case ssl_calg_rc4:
   1662       	initFn = (BLapiInitContextFunc)RC4_InitContext;
   1663 	pwSpec->encode  = (SSLCipher) RC4_Encrypt;
   1664 	pwSpec->decode  = (SSLCipher) RC4_Decrypt;
   1665 	pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
   1666 	break;
   1667     case ssl_calg_rc2:
   1668       	initFn = (BLapiInitContextFunc)RC2_InitContext;
   1669 	mode = NSS_RC2_CBC;
   1670 	optArg1 = cipher_def->key_size;
   1671 	pwSpec->encode  = (SSLCipher) RC2_Encrypt;
   1672 	pwSpec->decode  = (SSLCipher) RC2_Decrypt;
   1673 	pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
   1674 	break;
   1675     case ssl_calg_des:
   1676       	initFn = (BLapiInitContextFunc)DES_InitContext;
   1677 	mode = NSS_DES_CBC;
   1678 	optArg1 = server_encrypts;
   1679 	pwSpec->encode  = (SSLCipher) DES_Encrypt;
   1680 	pwSpec->decode  = (SSLCipher) DES_Decrypt;
   1681 	pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
   1682 	break;
   1683     case ssl_calg_3des:
   1684       	initFn = (BLapiInitContextFunc)DES_InitContext;
   1685 	mode = NSS_DES_EDE3_CBC;
   1686 	optArg1 = server_encrypts;
   1687 	pwSpec->encode  = (SSLCipher) DES_Encrypt;
   1688 	pwSpec->decode  = (SSLCipher) DES_Decrypt;
   1689 	pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
   1690 	break;
   1691     case ssl_calg_aes:
   1692       	initFn = (BLapiInitContextFunc)AES_InitContext;
   1693 	mode = NSS_AES_CBC;
   1694 	optArg1 = server_encrypts;
   1695 	optArg2 = AES_BLOCK_SIZE;
   1696 	pwSpec->encode  = (SSLCipher) AES_Encrypt;
   1697 	pwSpec->decode  = (SSLCipher) AES_Decrypt;
   1698 	pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
   1699 	break;
   1700 
   1701     case ssl_calg_camellia:
   1702       	initFn = (BLapiInitContextFunc)Camellia_InitContext;
   1703 	mode = NSS_CAMELLIA_CBC;
   1704 	optArg1 = server_encrypts;
   1705 	optArg2 = CAMELLIA_BLOCK_SIZE;
   1706 	pwSpec->encode  = (SSLCipher) Camellia_Encrypt;
   1707 	pwSpec->decode  = (SSLCipher) Camellia_Decrypt;
   1708 	pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
   1709 	break;
   1710 
   1711     case ssl_calg_seed:
   1712       	initFn = (BLapiInitContextFunc)SEED_InitContext;
   1713 	mode = NSS_SEED_CBC;
   1714 	optArg1 = server_encrypts;
   1715 	optArg2 = SEED_BLOCK_SIZE;
   1716 	pwSpec->encode  = (SSLCipher) SEED_Encrypt;
   1717 	pwSpec->decode  = (SSLCipher) SEED_Decrypt;
   1718 	pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
   1719 	break;
   1720 
   1721     case ssl_calg_idea:
   1722     case ssl_calg_fortezza :
   1723     default:
   1724 	PORT_Assert(0);
   1725 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1726 	goto bail_out;
   1727     }
   1728     rv = (*initFn)(serverContext,
   1729 		   pwSpec->server.write_key_item.data,
   1730 		   pwSpec->server.write_key_item.len,
   1731 		   pwSpec->server.write_iv_item.data,
   1732 		   mode, optArg1, optArg2);
   1733     if (rv != SECSuccess) {
   1734 	PORT_Assert(0);
   1735 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1736 	goto bail_out;
   1737     }
   1738 
   1739     switch (calg) {
   1740     case ssl_calg_des:
   1741     case ssl_calg_3des:
   1742     case ssl_calg_aes:
   1743     case ssl_calg_camellia:
   1744     case ssl_calg_seed:
   1745 	/* For block ciphers, if the server is encrypting, then the client
   1746 	* is decrypting, and vice versa.
   1747 	*/
   1748         optArg1 = !optArg1;
   1749         break;
   1750     /* kill warnings. */
   1751     case ssl_calg_null:
   1752     case ssl_calg_rc4:
   1753     case ssl_calg_rc2:
   1754     case ssl_calg_idea:
   1755     case ssl_calg_fortezza:
   1756         break;
   1757     }
   1758 
   1759     rv = (*initFn)(clientContext,
   1760 		   pwSpec->client.write_key_item.data,
   1761 		   pwSpec->client.write_key_item.len,
   1762 		   pwSpec->client.write_iv_item.data,
   1763 		   mode, optArg1, optArg2);
   1764     if (rv != SECSuccess) {
   1765 	PORT_Assert(0);
   1766 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1767 	goto bail_out;
   1768     }
   1769 
   1770     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
   1771     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
   1772 
   1773     ssl3_InitCompressionContext(pwSpec);
   1774 
   1775 success:
   1776     return SECSuccess;
   1777 
   1778 bail_out:
   1779     return SECFailure;
   1780 }
   1781 #endif
   1782 
   1783 /* This function should probably be moved to pk11wrap and be named
   1784  * PK11_ParamFromIVAndEffectiveKeyBits
   1785  */
   1786 static SECItem *
   1787 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
   1788 {
   1789     SECItem * param = PK11_ParamFromIV(mtype, iv);
   1790     if (param && param->data  && param->len >= sizeof(CK_RC2_PARAMS)) {
   1791 	switch (mtype) {
   1792 	case CKM_RC2_KEY_GEN:
   1793 	case CKM_RC2_ECB:
   1794 	case CKM_RC2_CBC:
   1795 	case CKM_RC2_MAC:
   1796 	case CKM_RC2_MAC_GENERAL:
   1797 	case CKM_RC2_CBC_PAD:
   1798 	    *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
   1799 	default: break;
   1800 	}
   1801     }
   1802     return param;
   1803 }
   1804 
   1805 /* ssl3_BuildRecordPseudoHeader writes the SSL/TLS pseudo-header (the data
   1806  * which is included in the MAC or AEAD additional data) to |out| and returns
   1807  * its length. See https://tools.ietf.org/html/rfc5246#section-6.2.3.3 for the
   1808  * definition of the AEAD additional data.
   1809  *
   1810  * TLS pseudo-header includes the record's version field, SSL's doesn't. Which
   1811  * pseudo-header defintiion to use should be decided based on the version of
   1812  * the protocol that was negotiated when the cipher spec became current, NOT
   1813  * based on the version value in the record itself, and the decision is passed
   1814  * to this function as the |includesVersion| argument. But, the |version|
   1815  * argument should be the record's version value.
   1816  */
   1817 static unsigned int
   1818 ssl3_BuildRecordPseudoHeader(unsigned char *out,
   1819 			     SSL3SequenceNumber seq_num,
   1820 			     SSL3ContentType type,
   1821 			     PRBool includesVersion,
   1822 			     SSL3ProtocolVersion version,
   1823 			     PRBool isDTLS,
   1824 			     int length)
   1825 {
   1826     out[0] = (unsigned char)(seq_num.high >> 24);
   1827     out[1] = (unsigned char)(seq_num.high >> 16);
   1828     out[2] = (unsigned char)(seq_num.high >>  8);
   1829     out[3] = (unsigned char)(seq_num.high >>  0);
   1830     out[4] = (unsigned char)(seq_num.low  >> 24);
   1831     out[5] = (unsigned char)(seq_num.low  >> 16);
   1832     out[6] = (unsigned char)(seq_num.low  >>  8);
   1833     out[7] = (unsigned char)(seq_num.low  >>  0);
   1834     out[8] = type;
   1835 
   1836     /* SSL3 MAC doesn't include the record's version field. */
   1837     if (!includesVersion) {
   1838 	out[9]  = MSB(length);
   1839 	out[10] = LSB(length);
   1840 	return 11;
   1841     }
   1842 
   1843     /* TLS MAC and AEAD additional data include version. */
   1844     if (isDTLS) {
   1845 	SSL3ProtocolVersion dtls_version;
   1846 
   1847 	dtls_version = dtls_TLSVersionToDTLSVersion(version);
   1848 	out[9]  = MSB(dtls_version);
   1849 	out[10] = LSB(dtls_version);
   1850     } else {
   1851 	out[9]  = MSB(version);
   1852 	out[10] = LSB(version);
   1853     }
   1854     out[11] = MSB(length);
   1855     out[12] = LSB(length);
   1856     return 13;
   1857 }
   1858 
   1859 typedef SECStatus (*PK11CryptFcn)(
   1860     PK11SymKey *symKey, CK_MECHANISM_TYPE mechanism, SECItem *param,
   1861     unsigned char *out, unsigned int *outLen, unsigned int maxLen,
   1862     const unsigned char *in, unsigned int inLen);
   1863 
   1864 static PK11CryptFcn pk11_encrypt = NULL;
   1865 static PK11CryptFcn pk11_decrypt = NULL;
   1866 
   1867 static PRCallOnceType resolvePK11CryptOnce;
   1868 
   1869 static PRStatus
   1870 ssl3_ResolvePK11CryptFunctions(void)
   1871 {
   1872 #ifdef LINUX
   1873     /* On Linux we use the system NSS libraries. Look up the PK11_Encrypt and
   1874      * PK11_Decrypt functions at run time. */
   1875     void *handle = dlopen(NULL, RTLD_LAZY);
   1876     if (!handle) {
   1877 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1878 	return PR_FAILURE;
   1879     }
   1880     pk11_encrypt = (PK11CryptFcn)dlsym(handle, "PK11_Encrypt");
   1881     pk11_decrypt = (PK11CryptFcn)dlsym(handle, "PK11_Decrypt");
   1882     dlclose(handle);
   1883     return PR_SUCCESS;
   1884 #else
   1885     /* On other platforms we use our own copy of NSS. PK11_Encrypt and
   1886      * PK11_Decrypt are known to be available. */
   1887     pk11_encrypt = PK11_Encrypt;
   1888     pk11_decrypt = PK11_Decrypt;
   1889     return PR_SUCCESS;
   1890 #endif
   1891 }
   1892 
   1893 /*
   1894  * In NSS 3.15, PK11_Encrypt and PK11_Decrypt were added to provide access
   1895  * to the AES GCM implementation in the NSS softoken. So the presence of
   1896  * these two functions implies the NSS version supports AES GCM.
   1897  */
   1898 static PRBool
   1899 ssl3_HasGCMSupport(void)
   1900 {
   1901     (void)PR_CallOnce(&resolvePK11CryptOnce, ssl3_ResolvePK11CryptFunctions);
   1902     return pk11_encrypt != NULL;
   1903 }
   1904 
   1905 /* On this socket, disable the GCM cipher suites */
   1906 SECStatus
   1907 ssl3_DisableGCMSuites(sslSocket * ss)
   1908 {
   1909     unsigned int i;
   1910 
   1911     for (i = 0; i < PR_ARRAY_SIZE(cipher_suite_defs); i++) {
   1912 	const ssl3CipherSuiteDef *cipher_def = &cipher_suite_defs[i];
   1913 	if (cipher_def->bulk_cipher_alg == cipher_aes_128_gcm) {
   1914 	    SECStatus rv = ssl3_CipherPrefSet(ss, cipher_def->cipher_suite,
   1915 					      PR_FALSE);
   1916 	    PORT_Assert(rv == SECSuccess); /* else is coding error */
   1917 	}
   1918     }
   1919     return SECSuccess;
   1920 }
   1921 
   1922 static SECStatus
   1923 ssl3_AESGCM(ssl3KeyMaterial *keys,
   1924 	    PRBool doDecrypt,
   1925 	    unsigned char *out,
   1926 	    int *outlen,
   1927 	    int maxout,
   1928 	    const unsigned char *in,
   1929 	    int inlen,
   1930 	    const unsigned char *additionalData,
   1931 	    int additionalDataLen)
   1932 {
   1933     SECItem            param;
   1934     SECStatus          rv = SECFailure;
   1935     unsigned char      nonce[12];
   1936     unsigned int       uOutLen;
   1937     CK_GCM_PARAMS      gcmParams;
   1938 
   1939     static const int   tagSize = 16;
   1940     static const int   explicitNonceLen = 8;
   1941 
   1942     /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
   1943      * nonce is formed. */
   1944     memcpy(nonce, keys->write_iv, 4);
   1945     if (doDecrypt) {
   1946 	memcpy(nonce + 4, in, explicitNonceLen);
   1947 	in += explicitNonceLen;
   1948 	inlen -= explicitNonceLen;
   1949 	*outlen = 0;
   1950     } else {
   1951 	if (maxout < explicitNonceLen) {
   1952 	    PORT_SetError(SEC_ERROR_INPUT_LEN);
   1953 	    return SECFailure;
   1954         }
   1955 	/* Use the 64-bit sequence number as the explicit nonce. */
   1956 	memcpy(nonce + 4, additionalData, explicitNonceLen);
   1957 	memcpy(out, additionalData, explicitNonceLen);
   1958 	out += explicitNonceLen;
   1959 	maxout -= explicitNonceLen;
   1960 	*outlen = explicitNonceLen;
   1961     }
   1962 
   1963     param.type = siBuffer;
   1964     param.data = (unsigned char *) &gcmParams;
   1965     param.len = sizeof(gcmParams);
   1966     gcmParams.pIv = nonce;
   1967     gcmParams.ulIvLen = sizeof(nonce);
   1968     gcmParams.pAAD = (unsigned char *)additionalData;  /* const cast */
   1969     gcmParams.ulAADLen = additionalDataLen;
   1970     gcmParams.ulTagBits = tagSize * 8;
   1971 
   1972     if (doDecrypt) {
   1973 	rv = pk11_decrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
   1974 			  maxout, in, inlen);
   1975     } else {
   1976 	rv = pk11_encrypt(keys->write_key, CKM_AES_GCM, &param, out, &uOutLen,
   1977 			  maxout, in, inlen);
   1978     }
   1979     *outlen += (int) uOutLen;
   1980 
   1981     return rv;
   1982 }
   1983 
   1984 #ifndef NO_PKCS11_BYPASS
   1985 static SECStatus
   1986 ssl3_AESGCMBypass(ssl3KeyMaterial *keys,
   1987 		  PRBool doDecrypt,
   1988 		  unsigned char *out,
   1989 		  int *outlen,
   1990 		  int maxout,
   1991 		  const unsigned char *in,
   1992 		  int inlen,
   1993 		  const unsigned char *additionalData,
   1994 		  int additionalDataLen)
   1995 {
   1996     SECStatus          rv = SECFailure;
   1997     unsigned char      nonce[12];
   1998     unsigned int       uOutLen;
   1999     AESContext        *cx;
   2000     CK_GCM_PARAMS      gcmParams;
   2001 
   2002     static const int   tagSize = 16;
   2003     static const int   explicitNonceLen = 8;
   2004 
   2005     /* See https://tools.ietf.org/html/rfc5288#section-3 for details of how the
   2006      * nonce is formed. */
   2007     PORT_Assert(keys->write_iv_item.len == 4);
   2008     if (keys->write_iv_item.len != 4) {
   2009 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2010 	return SECFailure;
   2011     }
   2012     memcpy(nonce, keys->write_iv_item.data, 4);
   2013     if (doDecrypt) {
   2014 	memcpy(nonce + 4, in, explicitNonceLen);
   2015 	in += explicitNonceLen;
   2016 	inlen -= explicitNonceLen;
   2017 	*outlen = 0;
   2018     } else {
   2019 	if (maxout < explicitNonceLen) {
   2020 	    PORT_SetError(SEC_ERROR_INPUT_LEN);
   2021 	    return SECFailure;
   2022         }
   2023 	/* Use the 64-bit sequence number as the explicit nonce. */
   2024 	memcpy(nonce + 4, additionalData, explicitNonceLen);
   2025 	memcpy(out, additionalData, explicitNonceLen);
   2026 	out += explicitNonceLen;
   2027 	maxout -= explicitNonceLen;
   2028 	*outlen = explicitNonceLen;
   2029     }
   2030 
   2031     gcmParams.pIv = nonce;
   2032     gcmParams.ulIvLen = sizeof(nonce);
   2033     gcmParams.pAAD = (unsigned char *)additionalData;  /* const cast */
   2034     gcmParams.ulAADLen = additionalDataLen;
   2035     gcmParams.ulTagBits = tagSize * 8;
   2036 
   2037     cx = (AESContext *)keys->cipher_context;
   2038     rv = AES_InitContext(cx, keys->write_key_item.data,
   2039 			 keys->write_key_item.len,
   2040 			 (unsigned char *)&gcmParams, NSS_AES_GCM, !doDecrypt,
   2041 			 AES_BLOCK_SIZE);
   2042     if (rv != SECSuccess) {
   2043 	return rv;
   2044     }
   2045     if (doDecrypt) {
   2046 	rv = AES_Decrypt(cx, out, &uOutLen, maxout, in, inlen);
   2047     } else {
   2048 	rv = AES_Encrypt(cx, out, &uOutLen, maxout, in, inlen);
   2049     }
   2050     AES_DestroyContext(cx, PR_FALSE);
   2051     *outlen += (int) uOutLen;
   2052 
   2053     return rv;
   2054 }
   2055 #endif
   2056 
   2057 static SECStatus
   2058 ssl3_ChaCha20Poly1305(
   2059 	ssl3KeyMaterial *keys,
   2060 	PRBool doDecrypt,
   2061 	unsigned char *out,
   2062 	int *outlen,
   2063 	int maxout,
   2064 	const unsigned char *in,
   2065 	int inlen,
   2066 	const unsigned char *additionalData,
   2067 	int additionalDataLen)
   2068 {
   2069     SECItem            param;
   2070     SECStatus          rv = SECFailure;
   2071     unsigned int       uOutLen;
   2072     CK_NSS_AEAD_PARAMS aeadParams;
   2073     static const int   tagSize = 16;
   2074 
   2075     param.type = siBuffer;
   2076     param.len = sizeof(aeadParams);
   2077     param.data = (unsigned char *) &aeadParams;
   2078     memset(&aeadParams, 0, sizeof(aeadParams));
   2079     aeadParams.pIv = (unsigned char *) additionalData;
   2080     aeadParams.ulIvLen = 8;
   2081     aeadParams.pAAD = (unsigned char *) additionalData;
   2082     aeadParams.ulAADLen = additionalDataLen;
   2083     aeadParams.ulTagLen = tagSize;
   2084 
   2085     if (doDecrypt) {
   2086 	rv = pk11_decrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param,
   2087 			  out, &uOutLen, maxout, in, inlen);
   2088     } else {
   2089 	rv = pk11_encrypt(keys->write_key, CKM_NSS_CHACHA20_POLY1305, &param,
   2090 			  out, &uOutLen, maxout, in, inlen);
   2091     }
   2092     *outlen = (int) uOutLen;
   2093 
   2094     return rv;
   2095 }
   2096 
   2097 /* Initialize encryption and MAC contexts for pending spec.
   2098  * Master Secret already is derived.
   2099  * Caller holds Spec write lock.
   2100  */
   2101 static SECStatus
   2102 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
   2103 {
   2104       ssl3CipherSpec  *  pwSpec;
   2105       const ssl3BulkCipherDef *cipher_def;
   2106       PK11Context *      serverContext = NULL;
   2107       PK11Context *      clientContext = NULL;
   2108       SECItem *          param;
   2109       CK_MECHANISM_TYPE  mechanism;
   2110       CK_MECHANISM_TYPE  mac_mech;
   2111       CK_ULONG           macLength;
   2112       CK_ULONG           effKeyBits;
   2113       SECItem            iv;
   2114       SECItem            mac_param;
   2115       SSLCipherAlgorithm calg;
   2116 
   2117     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   2118     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   2119     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   2120 
   2121     pwSpec        = ss->ssl3.pwSpec;
   2122     cipher_def    = pwSpec->cipher_def;
   2123     macLength     = pwSpec->mac_size;
   2124     calg          = cipher_def->calg;
   2125     PORT_Assert(alg2Mech[calg].calg == calg);
   2126 
   2127     pwSpec->client.write_mac_context = NULL;
   2128     pwSpec->server.write_mac_context = NULL;
   2129 
   2130     if (calg == calg_aes_gcm || calg == calg_chacha20) {
   2131 	pwSpec->encode = NULL;
   2132 	pwSpec->decode = NULL;
   2133 	pwSpec->destroy = NULL;
   2134 	pwSpec->encodeContext = NULL;
   2135 	pwSpec->decodeContext = NULL;
   2136 	if (calg == calg_aes_gcm) {
   2137 	    pwSpec->aead = ssl3_AESGCM;
   2138 	} else {
   2139 	    pwSpec->aead = ssl3_ChaCha20Poly1305;
   2140 	}
   2141 	return SECSuccess;
   2142     }
   2143 
   2144     /*
   2145     ** Now setup the MAC contexts,
   2146     **   crypto contexts are setup below.
   2147     */
   2148 
   2149     mac_mech       = pwSpec->mac_def->mmech;
   2150     mac_param.data = (unsigned char *)&macLength;
   2151     mac_param.len  = sizeof(macLength);
   2152     mac_param.type = 0;
   2153 
   2154     pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
   2155 	    mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
   2156     if (pwSpec->client.write_mac_context == NULL)  {
   2157 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   2158 	goto fail;
   2159     }
   2160     pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
   2161 	    mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
   2162     if (pwSpec->server.write_mac_context == NULL) {
   2163 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   2164 	goto fail;
   2165     }
   2166 
   2167     /*
   2168     ** Now setup the crypto contexts.
   2169     */
   2170 
   2171     if (calg == calg_null) {
   2172 	pwSpec->encode  = Null_Cipher;
   2173 	pwSpec->decode  = Null_Cipher;
   2174 	pwSpec->destroy = NULL;
   2175 	return SECSuccess;
   2176     }
   2177     mechanism = alg2Mech[calg].cmech;
   2178     effKeyBits = cipher_def->key_size * BPB;
   2179 
   2180     /*
   2181      * build the server context
   2182      */
   2183     iv.data = pwSpec->server.write_iv;
   2184     iv.len  = cipher_def->iv_size;
   2185     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
   2186     if (param == NULL) {
   2187 	ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
   2188     	goto fail;
   2189     }
   2190     serverContext = PK11_CreateContextBySymKey(mechanism,
   2191 				(ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
   2192 				pwSpec->server.write_key, param);
   2193     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
   2194     if (iv.data)
   2195     	PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
   2196     SECITEM_FreeItem(param, PR_TRUE);
   2197     if (serverContext == NULL) {
   2198 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   2199     	goto fail;
   2200     }
   2201 
   2202     /*
   2203      * build the client context
   2204      */
   2205     iv.data = pwSpec->client.write_iv;
   2206     iv.len  = cipher_def->iv_size;
   2207 
   2208     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
   2209     if (param == NULL) {
   2210 	ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
   2211     	goto fail;
   2212     }
   2213     clientContext = PK11_CreateContextBySymKey(mechanism,
   2214 				(ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
   2215 				pwSpec->client.write_key, param);
   2216     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
   2217     if (iv.data)
   2218     	PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
   2219     SECITEM_FreeItem(param,PR_TRUE);
   2220     if (clientContext == NULL) {
   2221 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   2222     	goto fail;
   2223     }
   2224     pwSpec->encode  = (SSLCipher) PK11_CipherOp;
   2225     pwSpec->decode  = (SSLCipher) PK11_CipherOp;
   2226     pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
   2227 
   2228     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
   2229     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
   2230 
   2231     serverContext = NULL;
   2232     clientContext = NULL;
   2233 
   2234     ssl3_InitCompressionContext(pwSpec);
   2235 
   2236     return SECSuccess;
   2237 
   2238 fail:
   2239     if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
   2240     if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
   2241     if (pwSpec->client.write_mac_context != NULL) {
   2242     	PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
   2243 	pwSpec->client.write_mac_context = NULL;
   2244     }
   2245     if (pwSpec->server.write_mac_context != NULL) {
   2246     	PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
   2247 	pwSpec->server.write_mac_context = NULL;
   2248     }
   2249 
   2250     return SECFailure;
   2251 }
   2252 
   2253 /* Complete the initialization of all keys, ciphers, MACs and their contexts
   2254  * for the pending Cipher Spec.
   2255  * Called from: ssl3_SendClientKeyExchange 	(for Full handshake)
   2256  *              ssl3_HandleRSAClientKeyExchange	(for Full handshake)
   2257  *              ssl3_HandleServerHello		(for session restart)
   2258  *              ssl3_HandleClientHello		(for session restart)
   2259  * Sets error code, but caller probably should override to disambiguate.
   2260  * NULL pms means re-use old master_secret.
   2261  *
   2262  * This code is common to the bypass and PKCS11 execution paths.
   2263  * For the bypass case,  pms is NULL.
   2264  */
   2265 SECStatus
   2266 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
   2267 {
   2268     ssl3CipherSpec  *  pwSpec;
   2269     ssl3CipherSpec  *  cwSpec;
   2270     SECStatus          rv;
   2271 
   2272     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   2273 
   2274     ssl_GetSpecWriteLock(ss);	/**************************************/
   2275 
   2276     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   2277 
   2278     pwSpec        = ss->ssl3.pwSpec;
   2279     cwSpec        = ss->ssl3.cwSpec;
   2280 
   2281     if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
   2282 	rv = ssl3_DeriveMasterSecret(ss, pms);
   2283 	if (rv != SECSuccess) {
   2284 	    goto done;  /* err code set by ssl3_DeriveMasterSecret */
   2285 	}
   2286     }
   2287 #ifndef NO_PKCS11_BYPASS
   2288     if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
   2289 	/* Double Bypass succeeded in extracting the master_secret */
   2290 	const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
   2291 	PRBool             isTLS   = (PRBool)(kea_def->tls_keygen ||
   2292                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
   2293 	pwSpec->bypassCiphers = PR_TRUE;
   2294 	rv = ssl3_KeyAndMacDeriveBypass( pwSpec,
   2295 			     (const unsigned char *)&ss->ssl3.hs.client_random,
   2296 			     (const unsigned char *)&ss->ssl3.hs.server_random,
   2297 			     isTLS,
   2298 			     (PRBool)(kea_def->is_limited));
   2299 	if (rv == SECSuccess) {
   2300 	    rv = ssl3_InitPendingContextsBypass(ss);
   2301 	}
   2302     } else
   2303 #endif
   2304     if (pwSpec->master_secret) {
   2305 	rv = ssl3_DeriveConnectionKeysPKCS11(ss);
   2306 	if (rv == SECSuccess) {
   2307 	    rv = ssl3_InitPendingContextsPKCS11(ss);
   2308 	}
   2309     } else {
   2310 	PORT_Assert(pwSpec->master_secret);
   2311 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2312 	rv = SECFailure;
   2313     }
   2314     if (rv != SECSuccess) {
   2315 	goto done;
   2316     }
   2317 
   2318     /* Generic behaviors -- common to all crypto methods */
   2319     if (!IS_DTLS(ss)) {
   2320 	pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
   2321     } else {
   2322 	if (cwSpec->epoch == PR_UINT16_MAX) {
   2323 	    /* The problem here is that we have rehandshaked too many
   2324 	     * times (you are not allowed to wrap the epoch). The
   2325 	     * spec says you should be discarding the connection
   2326 	     * and start over, so not much we can do here. */
   2327 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2328 	    rv = SECFailure;
   2329 	    goto done;
   2330 	}
   2331 	/* The sequence number has the high 16 bits as the epoch. */
   2332 	pwSpec->epoch = cwSpec->epoch + 1;
   2333 	pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
   2334 	    pwSpec->epoch << 16;
   2335 
   2336 	dtls_InitRecvdRecords(&pwSpec->recvdRecords);
   2337     }
   2338     pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
   2339 
   2340 done:
   2341     ssl_ReleaseSpecWriteLock(ss);	/******************************/
   2342     if (rv != SECSuccess)
   2343 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   2344     return rv;
   2345 }
   2346 
   2347 /*
   2348  * 60 bytes is 3 times the maximum length MAC size that is supported.
   2349  */
   2350 static const unsigned char mac_pad_1 [60] = {
   2351     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2352     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2353     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2354     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2355     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2356     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2357     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   2358     0x36, 0x36, 0x36, 0x36
   2359 };
   2360 static const unsigned char mac_pad_2 [60] = {
   2361     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2362     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2363     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2364     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2365     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2366     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2367     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   2368     0x5c, 0x5c, 0x5c, 0x5c
   2369 };
   2370 
   2371 /* Called from: ssl3_SendRecord()
   2372 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
   2373 */
   2374 static SECStatus
   2375 ssl3_ComputeRecordMAC(
   2376     ssl3CipherSpec *   spec,
   2377     PRBool             useServerMacKey,
   2378     const unsigned char *header,
   2379     unsigned int       headerLen,
   2380     const SSL3Opaque * input,
   2381     int                inputLength,
   2382     unsigned char *    outbuf,
   2383     unsigned int *     outLength)
   2384 {
   2385     const ssl3MACDef * mac_def;
   2386     SECStatus          rv;
   2387 
   2388     PRINT_BUF(95, (NULL, "frag hash1: header", header, headerLen));
   2389     PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
   2390 
   2391     mac_def = spec->mac_def;
   2392     if (mac_def->mac == mac_null) {
   2393 	*outLength = 0;
   2394 	return SECSuccess;
   2395     }
   2396 #ifndef NO_PKCS11_BYPASS
   2397     if (spec->bypassCiphers) {
   2398 	/* bypass version */
   2399 	const SECHashObject *hashObj = NULL;
   2400 	unsigned int       pad_bytes = 0;
   2401 	PRUint64           write_mac_context[MAX_MAC_CONTEXT_LLONGS];
   2402 
   2403 	switch (mac_def->mac) {
   2404 	case ssl_mac_null:
   2405 	    *outLength = 0;
   2406 	    return SECSuccess;
   2407 	case ssl_mac_md5:
   2408 	    pad_bytes = 48;
   2409 	    hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
   2410 	    break;
   2411 	case ssl_mac_sha:
   2412 	    pad_bytes = 40;
   2413 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
   2414 	    break;
   2415 	case ssl_hmac_md5: /* used with TLS */
   2416 	    hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
   2417 	    break;
   2418 	case ssl_hmac_sha: /* used with TLS */
   2419 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
   2420 	    break;
   2421 	case ssl_hmac_sha256: /* used with TLS */
   2422 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
   2423 	    break;
   2424 	default:
   2425 	    break;
   2426 	}
   2427 	if (!hashObj) {
   2428 	    PORT_Assert(0);
   2429 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2430 	    return SECFailure;
   2431 	}
   2432 
   2433 	if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
   2434 	    unsigned int tempLen;
   2435 	    unsigned char temp[MAX_MAC_LENGTH];
   2436 
   2437 	    /* compute "inner" part of SSL3 MAC */
   2438 	    hashObj->begin(write_mac_context);
   2439 	    if (useServerMacKey)
   2440 		hashObj->update(write_mac_context,
   2441 				spec->server.write_mac_key_item.data,
   2442 				spec->server.write_mac_key_item.len);
   2443 	    else
   2444 		hashObj->update(write_mac_context,
   2445 				spec->client.write_mac_key_item.data,
   2446 				spec->client.write_mac_key_item.len);
   2447 	    hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
   2448 	    hashObj->update(write_mac_context, header, headerLen);
   2449 	    hashObj->update(write_mac_context, input, inputLength);
   2450 	    hashObj->end(write_mac_context,    temp, &tempLen, sizeof temp);
   2451 
   2452 	    /* compute "outer" part of SSL3 MAC */
   2453 	    hashObj->begin(write_mac_context);
   2454 	    if (useServerMacKey)
   2455 		hashObj->update(write_mac_context,
   2456 				spec->server.write_mac_key_item.data,
   2457 				spec->server.write_mac_key_item.len);
   2458 	    else
   2459 		hashObj->update(write_mac_context,
   2460 				spec->client.write_mac_key_item.data,
   2461 				spec->client.write_mac_key_item.len);
   2462 	    hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
   2463 	    hashObj->update(write_mac_context, temp, tempLen);
   2464 	    hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
   2465 	    rv = SECSuccess;
   2466 	} else { /* is TLS */
   2467 #define cx ((HMACContext *)write_mac_context)
   2468 	    if (useServerMacKey) {
   2469 		rv = HMAC_Init(cx, hashObj,
   2470 			       spec->server.write_mac_key_item.data,
   2471 			       spec->server.write_mac_key_item.len, PR_FALSE);
   2472 	    } else {
   2473 		rv = HMAC_Init(cx, hashObj,
   2474 			       spec->client.write_mac_key_item.data,
   2475 			       spec->client.write_mac_key_item.len, PR_FALSE);
   2476 	    }
   2477 	    if (rv == SECSuccess) {
   2478 		HMAC_Begin(cx);
   2479 		HMAC_Update(cx, header, headerLen);
   2480 		HMAC_Update(cx, input, inputLength);
   2481 		rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
   2482 		HMAC_Destroy(cx, PR_FALSE);
   2483 	    }
   2484 #undef cx
   2485 	}
   2486     } else
   2487 #endif
   2488     {
   2489 	PK11Context *mac_context =
   2490 	    (useServerMacKey ? spec->server.write_mac_context
   2491 	                     : spec->client.write_mac_context);
   2492 	rv  = PK11_DigestBegin(mac_context);
   2493 	rv |= PK11_DigestOp(mac_context, header, headerLen);
   2494 	rv |= PK11_DigestOp(mac_context, input, inputLength);
   2495 	rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
   2496     }
   2497 
   2498     PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
   2499 
   2500     PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
   2501 
   2502     if (rv != SECSuccess) {
   2503     	rv = SECFailure;
   2504 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
   2505     }
   2506     return rv;
   2507 }
   2508 
   2509 /* This is a bodge to allow this code to be compiled against older NSS headers
   2510  * that don't contain the CBC constant-time changes. */
   2511 #ifndef CKM_NSS_HMAC_CONSTANT_TIME
   2512 #define CKM_NSS_HMAC_CONSTANT_TIME (CKM_NSS + 19)
   2513 #define CKM_NSS_SSL3_MAC_CONSTANT_TIME (CKM_NSS + 20)
   2514 
   2515 typedef struct CK_NSS_MAC_CONSTANT_TIME_PARAMS {
   2516     CK_MECHANISM_TYPE macAlg;   /* in */
   2517     CK_ULONG ulBodyTotalLen;    /* in */
   2518     CK_BYTE * pHeader;          /* in */
   2519     CK_ULONG ulHeaderLen;       /* in */
   2520 } CK_NSS_MAC_CONSTANT_TIME_PARAMS;
   2521 #endif
   2522 
   2523 /* Called from: ssl3_HandleRecord()
   2524  * Caller must already hold the SpecReadLock. (wish we could assert that!)
   2525  *
   2526  * On entry:
   2527  *   originalLen >= inputLen >= MAC size
   2528 */
   2529 static SECStatus
   2530 ssl3_ComputeRecordMACConstantTime(
   2531     ssl3CipherSpec *   spec,
   2532     PRBool             useServerMacKey,
   2533     const unsigned char *header,
   2534     unsigned int       headerLen,
   2535     const SSL3Opaque * input,
   2536     int                inputLen,
   2537     int                originalLen,
   2538     unsigned char *    outbuf,
   2539     unsigned int *     outLen)
   2540 {
   2541     CK_MECHANISM_TYPE            macType;
   2542     CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
   2543     PK11Context *                mac_context;
   2544     SECItem                      param;
   2545     SECStatus                    rv;
   2546     PK11SymKey *                 key;
   2547 
   2548     PORT_Assert(inputLen >= spec->mac_size);
   2549     PORT_Assert(originalLen >= inputLen);
   2550 
   2551     if (spec->bypassCiphers) {
   2552 	/* This function doesn't support PKCS#11 bypass. We fallback on the
   2553 	 * non-constant time version. */
   2554 	goto fallback;
   2555     }
   2556 
   2557     if (spec->mac_def->mac == mac_null) {
   2558 	*outLen = 0;
   2559 	return SECSuccess;
   2560     }
   2561 
   2562     macType = CKM_NSS_HMAC_CONSTANT_TIME;
   2563     if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
   2564 	macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
   2565     }
   2566 
   2567     params.macAlg = spec->mac_def->mmech;
   2568     params.ulBodyTotalLen = originalLen;
   2569     params.pHeader = (unsigned char *) header;  /* const cast */
   2570     params.ulHeaderLen = headerLen;
   2571 
   2572     param.data = (unsigned char*) &params;
   2573     param.len = sizeof(params);
   2574     param.type = 0;
   2575 
   2576     key = spec->server.write_mac_key;
   2577     if (!useServerMacKey) {
   2578 	key = spec->client.write_mac_key;
   2579     }
   2580     mac_context = PK11_CreateContextBySymKey(macType, CKA_SIGN, key, &param);
   2581     if (mac_context == NULL) {
   2582 	/* Older versions of NSS may not support constant-time MAC. */
   2583 	goto fallback;
   2584     }
   2585 
   2586     rv  = PK11_DigestBegin(mac_context);
   2587     rv |= PK11_DigestOp(mac_context, input, inputLen);
   2588     rv |= PK11_DigestFinal(mac_context, outbuf, outLen, spec->mac_size);
   2589     PK11_DestroyContext(mac_context, PR_TRUE);
   2590 
   2591     PORT_Assert(rv != SECSuccess || *outLen == (unsigned)spec->mac_size);
   2592 
   2593     if (rv != SECSuccess) {
   2594 	rv = SECFailure;
   2595 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
   2596     }
   2597     return rv;
   2598 
   2599 fallback:
   2600     /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
   2601      * length already. */
   2602     inputLen -= spec->mac_size;
   2603     return ssl3_ComputeRecordMAC(spec, useServerMacKey, header, headerLen,
   2604 				 input, inputLen, outbuf, outLen);
   2605 }
   2606 
   2607 static PRBool
   2608 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
   2609     PK11SlotInfo *slot = NULL;
   2610     PRBool isPresent = PR_TRUE;
   2611 
   2612     /* we only care if we are doing client auth */
   2613     /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being
   2614      * used, u.ssl3.clAuthValid will be false and this function will always
   2615      * return PR_TRUE. */
   2616     if (!sid || !sid->u.ssl3.clAuthValid) {
   2617 	return PR_TRUE;
   2618     }
   2619 
   2620     /* get the slot */
   2621     slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
   2622 	                     sid->u.ssl3.clAuthSlotID);
   2623     if (slot == NULL ||
   2624 	!PK11_IsPresent(slot) ||
   2625 	sid->u.ssl3.clAuthSeries     != PK11_GetSlotSeries(slot) ||
   2626 	sid->u.ssl3.clAuthSlotID     != PK11_GetSlotID(slot)     ||
   2627 	sid->u.ssl3.clAuthModuleID   != PK11_GetModuleID(slot)   ||
   2628 	(PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
   2629 	isPresent = PR_FALSE;
   2630     }
   2631     if (slot) {
   2632 	PK11_FreeSlot(slot);
   2633     }
   2634     return isPresent;
   2635 }
   2636 
   2637 /* Caller must hold the spec read lock. */
   2638 SECStatus
   2639 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *   cwSpec,
   2640 		              PRBool             isServer,
   2641 			      PRBool             isDTLS,
   2642 			      PRBool             capRecordVersion,
   2643                               SSL3ContentType    type,
   2644 		              const SSL3Opaque * pIn,
   2645 		              PRUint32           contentLen,
   2646 		              sslBuffer *        wrBuf)
   2647 {
   2648     const ssl3BulkCipherDef * cipher_def;
   2649     SECStatus                 rv;
   2650     PRUint32                  macLen = 0;
   2651     PRUint32                  fragLen;
   2652     PRUint32  p1Len, p2Len, oddLen = 0;
   2653     PRUint16                  headerLen;
   2654     int                       ivLen = 0;
   2655     int                       cipherBytes = 0;
   2656     unsigned char             pseudoHeader[13];
   2657     unsigned int              pseudoHeaderLen;
   2658 
   2659     cipher_def = cwSpec->cipher_def;
   2660     headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
   2661 
   2662     if (cipher_def->type == type_block &&
   2663 	cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   2664 	/* Prepend the per-record explicit IV using technique 2b from
   2665 	 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
   2666 	 * strong random number XORed with the CBC residue from the previous
   2667 	 * record.
   2668 	 */
   2669 	ivLen = cipher_def->iv_size;
   2670 	if (ivLen > wrBuf->space - headerLen) {
   2671 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2672 	    return SECFailure;
   2673 	}
   2674 	rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
   2675 	if (rv != SECSuccess) {
   2676 	    ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
   2677 	    return rv;
   2678 	}
   2679 	rv = cwSpec->encode( cwSpec->encodeContext,
   2680 	    wrBuf->buf + headerLen,
   2681 	    &cipherBytes,                       /* output and actual outLen */
   2682 	    ivLen,                              /* max outlen */
   2683 	    wrBuf->buf + headerLen,
   2684 	    ivLen);                             /* input and inputLen*/
   2685 	if (rv != SECSuccess || cipherBytes != ivLen) {
   2686 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2687 	    return SECFailure;
   2688 	}
   2689     }
   2690 
   2691     if (cwSpec->compressor) {
   2692 	int outlen;
   2693 	rv = cwSpec->compressor(
   2694 	    cwSpec->compressContext,
   2695 	    wrBuf->buf + headerLen + ivLen, &outlen,
   2696 	    wrBuf->space - headerLen - ivLen, pIn, contentLen);
   2697 	if (rv != SECSuccess)
   2698 	    return rv;
   2699 	pIn = wrBuf->buf + headerLen + ivLen;
   2700 	contentLen = outlen;
   2701     }
   2702 
   2703     pseudoHeaderLen = ssl3_BuildRecordPseudoHeader(
   2704 	pseudoHeader, cwSpec->write_seq_num, type,
   2705 	cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_0, cwSpec->version,
   2706 	isDTLS, contentLen);
   2707     PORT_Assert(pseudoHeaderLen <= sizeof(pseudoHeader));
   2708     if (cipher_def->type == type_aead) {
   2709 	const int nonceLen = cipher_def->explicit_nonce_size;
   2710 	const int tagLen = cipher_def->tag_size;
   2711 
   2712 	if (headerLen + nonceLen + contentLen + tagLen > wrBuf->space) {
   2713 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2714 	    return SECFailure;
   2715 	}
   2716 
   2717 	cipherBytes = contentLen;
   2718 	rv = cwSpec->aead(
   2719 		isServer ? &cwSpec->server : &cwSpec->client,
   2720 		PR_FALSE,                                   /* do encrypt */
   2721 		wrBuf->buf + headerLen,                     /* output  */
   2722 		&cipherBytes,                               /* out len */
   2723 		wrBuf->space - headerLen,                   /* max out */
   2724 		pIn, contentLen,                            /* input   */
   2725 		pseudoHeader, pseudoHeaderLen);
   2726 	if (rv != SECSuccess) {
   2727 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2728 	    return SECFailure;
   2729 	}
   2730     } else {
   2731 	/*
   2732 	 * Add the MAC
   2733 	 */
   2734 	rv = ssl3_ComputeRecordMAC(cwSpec, isServer,
   2735 	    pseudoHeader, pseudoHeaderLen, pIn, contentLen,
   2736 	    wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
   2737 	if (rv != SECSuccess) {
   2738 	    ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
   2739 	    return SECFailure;
   2740 	}
   2741 	p1Len   = contentLen;
   2742 	p2Len   = macLen;
   2743 	fragLen = contentLen + macLen;	/* needs to be encrypted */
   2744 	PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
   2745 
   2746 	/*
   2747 	 * Pad the text (if we're doing a block cipher)
   2748 	 * then Encrypt it
   2749 	 */
   2750 	if (cipher_def->type == type_block) {
   2751 	    unsigned char * pBuf;
   2752 	    int             padding_length;
   2753 	    int             i;
   2754 
   2755 	    oddLen = contentLen % cipher_def->block_size;
   2756 	    /* Assume blockSize is a power of two */
   2757 	    padding_length = cipher_def->block_size - 1 -
   2758 			    ((fragLen) & (cipher_def->block_size - 1));
   2759 	    fragLen += padding_length + 1;
   2760 	    PORT_Assert((fragLen % cipher_def->block_size) == 0);
   2761 
   2762 	    /* Pad according to TLS rules (also acceptable to SSL3). */
   2763 	    pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
   2764 	    for (i = padding_length + 1; i > 0; --i) {
   2765 		*pBuf-- = padding_length;
   2766 	    }
   2767 	    /* now, if contentLen is not a multiple of block size, fix it */
   2768 	    p2Len = fragLen - p1Len;
   2769 	}
   2770 	if (p1Len < 256) {
   2771 	    oddLen = p1Len;
   2772 	    p1Len = 0;
   2773 	} else {
   2774 	    p1Len -= oddLen;
   2775 	}
   2776 	if (oddLen) {
   2777 	    p2Len += oddLen;
   2778 	    PORT_Assert( (cipher_def->block_size < 2) || \
   2779 			 (p2Len % cipher_def->block_size) == 0);
   2780 	    memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len,
   2781 		    oddLen);
   2782 	}
   2783 	if (p1Len > 0) {
   2784 	    int cipherBytesPart1 = -1;
   2785 	    rv = cwSpec->encode( cwSpec->encodeContext,
   2786 		wrBuf->buf + headerLen + ivLen,         /* output */
   2787 		&cipherBytesPart1,                      /* actual outlen */
   2788 		p1Len,                                  /* max outlen */
   2789 		pIn, p1Len);                      /* input, and inputlen */
   2790 	    PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
   2791 	    if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
   2792 		PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2793 		return SECFailure;
   2794 	    }
   2795 	    cipherBytes += cipherBytesPart1;
   2796 	}
   2797 	if (p2Len > 0) {
   2798 	    int cipherBytesPart2 = -1;
   2799 	    rv = cwSpec->encode( cwSpec->encodeContext,
   2800 		wrBuf->buf + headerLen + ivLen + p1Len,
   2801 		&cipherBytesPart2,          /* output and actual outLen */
   2802 		p2Len,                             /* max outlen */
   2803 		wrBuf->buf + headerLen + ivLen + p1Len,
   2804 		p2Len);                            /* input and inputLen*/
   2805 	    PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
   2806 	    if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
   2807 		PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2808 		return SECFailure;
   2809 	    }
   2810 	    cipherBytes += cipherBytesPart2;
   2811 	}
   2812     }
   2813 
   2814     PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
   2815 
   2816     wrBuf->len    = cipherBytes + headerLen;
   2817     wrBuf->buf[0] = type;
   2818     if (isDTLS) {
   2819 	SSL3ProtocolVersion version;
   2820 
   2821 	version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
   2822 	wrBuf->buf[1] = MSB(version);
   2823 	wrBuf->buf[2] = LSB(version);
   2824 	wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
   2825 	wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
   2826 	wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >>  8);
   2827 	wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >>  0);
   2828 	wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low  >> 24);
   2829 	wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low  >> 16);
   2830 	wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low  >>  8);
   2831 	wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >>  0);
   2832 	wrBuf->buf[11] = MSB(cipherBytes);
   2833 	wrBuf->buf[12] = LSB(cipherBytes);
   2834     } else {
   2835 	SSL3ProtocolVersion version = cwSpec->version;
   2836 
   2837 	if (capRecordVersion) {
   2838 	    version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
   2839 	}
   2840 	wrBuf->buf[1] = MSB(version);
   2841 	wrBuf->buf[2] = LSB(version);
   2842 	wrBuf->buf[3] = MSB(cipherBytes);
   2843 	wrBuf->buf[4] = LSB(cipherBytes);
   2844     }
   2845 
   2846     ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
   2847 
   2848     return SECSuccess;
   2849 }
   2850 
   2851 /* Process the plain text before sending it.
   2852  * Returns the number of bytes of plaintext that were successfully sent
   2853  * 	plus the number of bytes of plaintext that were copied into the
   2854  *	output (write) buffer.
   2855  * Returns SECFailure on a hard IO error, memory error, or crypto error.
   2856  * Does NOT return SECWouldBlock.
   2857  *
   2858  * Notes on the use of the private ssl flags:
   2859  * (no private SSL flags)
   2860  *    Attempt to make and send SSL records for all plaintext
   2861  *    If non-blocking and a send gets WOULD_BLOCK,
   2862  *    or if the pending (ciphertext) buffer is not empty,
   2863  *    then buffer remaining bytes of ciphertext into pending buf,
   2864  *    and continue to do that for all succssive records until all
   2865  *    bytes are used.
   2866  * ssl_SEND_FLAG_FORCE_INTO_BUFFER
   2867  *    As above, except this suppresses all write attempts, and forces
   2868  *    all ciphertext into the pending ciphertext buffer.
   2869  * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
   2870  *    Forces the use of the provided epoch
   2871  * ssl_SEND_FLAG_CAP_RECORD_VERSION
   2872  *    Caps the record layer version number of TLS ClientHello to { 3, 1 }
   2873  *    (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
   2874  *    ClientHello.client_version and use the record layer version number
   2875  *    (TLSPlaintext.version) instead when negotiating protocol versions. In
   2876  *    addition, if the record layer version number of ClientHello is { 3, 2 }
   2877  *    (TLS 1.1) or higher, these servers reset the TCP connections. Lastly,
   2878  *    some F5 BIG-IP servers hang if a record containing a ClientHello has a
   2879  *    version greater than 0x0301 and a length greater than 255. Set this flag
   2880  *    to work around such servers.
   2881  */
   2882 PRInt32
   2883 ssl3_SendRecord(   sslSocket *        ss,
   2884                    DTLSEpoch          epoch, /* DTLS only */
   2885                    SSL3ContentType    type,
   2886 		   const SSL3Opaque * pIn,   /* input buffer */
   2887 		   PRInt32            nIn,   /* bytes of input */
   2888 		   PRInt32            flags)
   2889 {
   2890     sslBuffer      *          wrBuf 	  = &ss->sec.writeBuf;
   2891     SECStatus                 rv;
   2892     PRInt32                   totalSent   = 0;
   2893     PRBool                    capRecordVersion;
   2894 
   2895     SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
   2896 		SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
   2897 		nIn));
   2898     PRINT_BUF(50, (ss, "Send record (plain text)", pIn, nIn));
   2899 
   2900     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   2901 
   2902     capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
   2903 
   2904     if (capRecordVersion) {
   2905 	/* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
   2906 	 * TLS initial ClientHello. */
   2907 	PORT_Assert(!IS_DTLS(ss));
   2908 	PORT_Assert(!ss->firstHsDone);
   2909 	PORT_Assert(type == content_handshake);
   2910 	PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
   2911     }
   2912 
   2913     if (ss->ssl3.initialized == PR_FALSE) {
   2914 	/* This can happen on a server if the very first incoming record
   2915 	** looks like a defective ssl3 record (e.g. too long), and we're
   2916 	** trying to send an alert.
   2917 	*/
   2918 	PR_ASSERT(type == content_alert);
   2919 	rv = ssl3_InitState(ss);
   2920 	if (rv != SECSuccess) {
   2921 	    return SECFailure;	/* ssl3_InitState has set the error code. */
   2922     	}
   2923     }
   2924 
   2925     /* check for Token Presence */
   2926     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
   2927 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   2928 	return SECFailure;
   2929     }
   2930 
   2931     while (nIn > 0) {
   2932 	PRUint32  contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
   2933 	unsigned int spaceNeeded;
   2934 	unsigned int numRecords;
   2935 
   2936 	ssl_GetSpecReadLock(ss);    /********************************/
   2937 
   2938 	if (nIn > 1 && ss->opt.cbcRandomIV &&
   2939 	    ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
   2940 	    type == content_application_data &&
   2941 	    ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
   2942 	    /* We will split the first byte of the record into its own record,
   2943 	     * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
   2944 	     */
   2945 	    numRecords = 2;
   2946 	} else {
   2947 	    numRecords = 1;
   2948 	}
   2949 
   2950 	spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
   2951 	if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
   2952 	    ss->ssl3.cwSpec->cipher_def->type == type_block) {
   2953 	    spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
   2954 	}
   2955 	if (spaceNeeded > wrBuf->space) {
   2956 	    rv = sslBuffer_Grow(wrBuf, spaceNeeded);
   2957 	    if (rv != SECSuccess) {
   2958 		SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
   2959 			 SSL_GETPID(), ss->fd, spaceNeeded));
   2960 		goto spec_locked_loser; /* sslBuffer_Grow set error code. */
   2961 	    }
   2962 	}
   2963 
   2964 	if (numRecords == 2) {
   2965 	    sslBuffer secondRecord;
   2966 
   2967 	    rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
   2968 					       ss->sec.isServer, IS_DTLS(ss),
   2969 					       capRecordVersion, type, pIn,
   2970 					       1, wrBuf);
   2971 	    if (rv != SECSuccess)
   2972 	        goto spec_locked_loser;
   2973 
   2974 	    PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
   2975 	                   wrBuf->buf, wrBuf->len));
   2976 
   2977 	    secondRecord.buf = wrBuf->buf + wrBuf->len;
   2978 	    secondRecord.len = 0;
   2979 	    secondRecord.space = wrBuf->space - wrBuf->len;
   2980 
   2981 	    rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
   2982 	                                       ss->sec.isServer, IS_DTLS(ss),
   2983 					       capRecordVersion, type,
   2984 					       pIn + 1, contentLen - 1,
   2985 	                                       &secondRecord);
   2986 	    if (rv == SECSuccess) {
   2987 	        PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
   2988 	                       secondRecord.buf, secondRecord.len));
   2989 	        wrBuf->len += secondRecord.len;
   2990 	    }
   2991 	} else {
   2992 	    if (!IS_DTLS(ss)) {
   2993 		rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
   2994 						   ss->sec.isServer,
   2995 						   IS_DTLS(ss),
   2996 						   capRecordVersion,
   2997 						   type, pIn,
   2998 						   contentLen, wrBuf);
   2999 	    } else {
   3000 		rv = dtls_CompressMACEncryptRecord(ss, epoch,
   3001 						   !!(flags & ssl_SEND_FLAG_USE_EPOCH),
   3002 						   type, pIn,
   3003 						   contentLen, wrBuf);
   3004 	    }
   3005 
   3006 	    if (rv == SECSuccess) {
   3007 	        PRINT_BUF(50, (ss, "send (encrypted) record data:",
   3008 	                       wrBuf->buf, wrBuf->len));
   3009 	    }
   3010 	}
   3011 
   3012 spec_locked_loser:
   3013 	ssl_ReleaseSpecReadLock(ss); /************************************/
   3014 
   3015 	if (rv != SECSuccess)
   3016 	    return SECFailure;
   3017 
   3018 	pIn += contentLen;
   3019 	nIn -= contentLen;
   3020 	PORT_Assert( nIn >= 0 );
   3021 
   3022 	/* If there's still some previously saved ciphertext,
   3023 	 * or the caller doesn't want us to send the data yet,
   3024 	 * then add all our new ciphertext to the amount previously saved.
   3025 	 */
   3026 	if ((ss->pendingBuf.len > 0) ||
   3027 	    (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
   3028 
   3029 	    rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
   3030 	    if (rv != SECSuccess) {
   3031 		/* presumably a memory error, SEC_ERROR_NO_MEMORY */
   3032 		return SECFailure;
   3033 	    }
   3034 	    wrBuf->len = 0;	/* All cipher text is saved away. */
   3035 
   3036 	    if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
   3037 		PRInt32   sent;
   3038 		ss->handshakeBegun = 1;
   3039 		sent = ssl_SendSavedWriteData(ss);
   3040 		if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
   3041 		    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
   3042 		    return SECFailure;
   3043 		}
   3044 		if (ss->pendingBuf.len) {
   3045 		    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
   3046 		}
   3047 	    }
   3048 	} else if (wrBuf->len > 0) {
   3049 	    PRInt32   sent;
   3050 	    ss->handshakeBegun = 1;
   3051 	    sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
   3052 			       flags & ~ssl_SEND_FLAG_MASK);
   3053 	    if (sent < 0) {
   3054 		if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
   3055 		    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
   3056 		    return SECFailure;
   3057 		}
   3058 		/* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
   3059 		sent = 0;
   3060 	    }
   3061 	    wrBuf->len -= sent;
   3062 	    if (wrBuf->len) {
   3063 		if (IS_DTLS(ss)) {
   3064 		    /* DTLS just says no in this case. No buffering */
   3065 		    PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
   3066 		    return SECFailure;
   3067 		}
   3068 		/* now take all the remaining unsent new ciphertext and
   3069 		 * append it to the buffer of previously unsent ciphertext.
   3070 		 */
   3071 		rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
   3072 		if (rv != SECSuccess) {
   3073 		    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
   3074 		    return SECFailure;
   3075 		}
   3076 	    }
   3077 	}
   3078 	totalSent += contentLen;
   3079     }
   3080     return totalSent;
   3081 }
   3082 
   3083 #define SSL3_PENDING_HIGH_WATER 1024
   3084 
   3085 /* Attempt to send the content of "in" in an SSL application_data record.
   3086  * Returns "len" or SECFailure,   never SECWouldBlock, nor SECSuccess.
   3087  */
   3088 int
   3089 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
   3090 			 PRInt32 len, PRInt32 flags)
   3091 {
   3092     PRInt32   totalSent	= 0;
   3093     PRInt32   discarded = 0;
   3094 
   3095     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   3096     /* These flags for internal use only */
   3097     PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
   3098 			   ssl_SEND_FLAG_NO_RETRANSMIT)));
   3099     if (len < 0 || !in) {
   3100 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   3101 	return SECFailure;
   3102     }
   3103 
   3104     if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
   3105         !ssl_SocketIsBlocking(ss)) {
   3106 	PORT_Assert(!ssl_SocketIsBlocking(ss));
   3107 	PORT_SetError(PR_WOULD_BLOCK_ERROR);
   3108 	return SECFailure;
   3109     }
   3110 
   3111     if (ss->appDataBuffered && len) {
   3112 	PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
   3113 	if (in[0] != (unsigned char)(ss->appDataBuffered)) {
   3114 	    PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   3115 	    return SECFailure;
   3116 	}
   3117     	in++;
   3118 	len--;
   3119 	discarded = 1;
   3120     }
   3121     while (len > totalSent) {
   3122 	PRInt32   sent, toSend;
   3123 
   3124 	if (totalSent > 0) {
   3125 	    /*
   3126 	     * The thread yield is intended to give the reader thread a
   3127 	     * chance to get some cycles while the writer thread is in
   3128 	     * the middle of a large application data write.  (See
   3129 	     * Bugzilla bug 127740, comment #1.)
   3130 	     */
   3131 	    ssl_ReleaseXmitBufLock(ss);
   3132 	    PR_Sleep(PR_INTERVAL_NO_WAIT);	/* PR_Yield(); */
   3133 	    ssl_GetXmitBufLock(ss);
   3134 	}
   3135 	toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
   3136 	/*
   3137 	 * Note that the 0 epoch is OK because flags will never require
   3138 	 * its use, as guaranteed by the PORT_Assert above.
   3139 	 */
   3140 	sent = ssl3_SendRecord(ss, 0, content_application_data,
   3141 	                       in + totalSent, toSend, flags);
   3142 	if (sent < 0) {
   3143 	    if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
   3144 		PORT_Assert(ss->lastWriteBlocked);
   3145 	    	break;
   3146 	    }
   3147 	    return SECFailure; /* error code set by ssl3_SendRecord */
   3148 	}
   3149 	totalSent += sent;
   3150 	if (ss->pendingBuf.len) {
   3151 	    /* must be a non-blocking socket */
   3152 	    PORT_Assert(!ssl_SocketIsBlocking(ss));
   3153 	    PORT_Assert(ss->lastWriteBlocked);
   3154 	    break;
   3155 	}
   3156     }
   3157     if (ss->pendingBuf.len) {
   3158 	/* Must be non-blocking. */
   3159 	PORT_Assert(!ssl_SocketIsBlocking(ss));
   3160 	if (totalSent > 0) {
   3161 	    ss->appDataBuffered = 0x100 | in[totalSent - 1];
   3162 	}
   3163 
   3164 	totalSent = totalSent + discarded - 1;
   3165 	if (totalSent <= 0) {
   3166 	    PORT_SetError(PR_WOULD_BLOCK_ERROR);
   3167 	    totalSent = SECFailure;
   3168 	}
   3169 	return totalSent;
   3170     }
   3171     ss->appDataBuffered = 0;
   3172     return totalSent + discarded;
   3173 }
   3174 
   3175 /* Attempt to send buffered handshake messages.
   3176  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
   3177  * Always set sendBuf.len to 0, even when returning SECFailure.
   3178  *
   3179  * Depending on whether we are doing DTLS or not, this either calls
   3180  *
   3181  * - ssl3_FlushHandshakeMessages if non-DTLS
   3182  * - dtls_FlushHandshakeMessages if DTLS
   3183  *
   3184  * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
   3185  *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
   3186  *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
   3187  *             ssl3_SendFinished(),
   3188  */
   3189 static SECStatus
   3190 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
   3191 {
   3192     if (IS_DTLS(ss)) {
   3193         return dtls_FlushHandshakeMessages(ss, flags);
   3194     } else {
   3195         return ssl3_FlushHandshakeMessages(ss, flags);
   3196     }
   3197 }
   3198 
   3199 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
   3200  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
   3201  * Always set sendBuf.len to 0, even when returning SECFailure.
   3202  *
   3203  * Called from ssl3_FlushHandshake
   3204  */
   3205 static SECStatus
   3206 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
   3207 {
   3208     static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
   3209                                         ssl_SEND_FLAG_CAP_RECORD_VERSION;
   3210     PRInt32 rv = SECSuccess;
   3211 
   3212     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3213     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   3214 
   3215     if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
   3216 	return rv;
   3217 
   3218     /* only these flags are allowed */
   3219     PORT_Assert(!(flags & ~allowedFlags));
   3220     if ((flags & ~allowedFlags) != 0) {
   3221 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   3222 	rv = SECFailure;
   3223     } else {
   3224 	rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
   3225 			     ss->sec.ci.sendBuf.len, flags);
   3226     }
   3227     if (rv < 0) {
   3228     	int err = PORT_GetError();
   3229 	PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
   3230 	if (err == PR_WOULD_BLOCK_ERROR) {
   3231 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   3232 	}
   3233     } else if (rv < ss->sec.ci.sendBuf.len) {
   3234     	/* short write should never happen */
   3235 	PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
   3236 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   3237 	rv = SECFailure;
   3238     } else {
   3239 	rv = SECSuccess;
   3240     }
   3241 
   3242     /* Whether we succeeded or failed, toss the old handshake data. */
   3243     ss->sec.ci.sendBuf.len = 0;
   3244     return rv;
   3245 }
   3246 
   3247 /*
   3248  * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
   3249  * the remote client sends a negative response to our certificate request.
   3250  * Returns SECFailure if the application has required client auth.
   3251  *         SECSuccess otherwise.
   3252  */
   3253 static SECStatus
   3254 ssl3_HandleNoCertificate(sslSocket *ss)
   3255 {
   3256     if (ss->sec.peerCert != NULL) {
   3257 	if (ss->sec.peerKey != NULL) {
   3258 	    SECKEY_DestroyPublicKey(ss->sec.peerKey);
   3259 	    ss->sec.peerKey = NULL;
   3260 	}
   3261 	CERT_DestroyCertificate(ss->sec.peerCert);
   3262 	ss->sec.peerCert = NULL;
   3263     }
   3264     ssl3_CleanupPeerCerts(ss);
   3265 
   3266     /* If the server has required client-auth blindly but doesn't
   3267      * actually look at the certificate it won't know that no
   3268      * certificate was presented so we shutdown the socket to ensure
   3269      * an error.  We only do this if we haven't already completed the
   3270      * first handshake because if we're redoing the handshake we
   3271      * know the server is paying attention to the certificate.
   3272      */
   3273     if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
   3274 	(!ss->firstHsDone &&
   3275 	 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
   3276 	PRFileDesc * lower;
   3277 
   3278 	if (ss->sec.uncache)
   3279             ss->sec.uncache(ss->sec.ci.sid);
   3280 	SSL3_SendAlert(ss, alert_fatal, bad_certificate);
   3281 
   3282 	lower = ss->fd->lower;
   3283 #ifdef _WIN32
   3284 	lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
   3285 #else
   3286 	lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
   3287 #endif
   3288 	PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
   3289 	return SECFailure;
   3290     }
   3291     return SECSuccess;
   3292 }
   3293 
   3294 /************************************************************************
   3295  * Alerts
   3296  */
   3297 
   3298 /*
   3299 ** Acquires both handshake and XmitBuf locks.
   3300 ** Called from: ssl3_IllegalParameter	<-
   3301 **              ssl3_HandshakeFailure	<-
   3302 **              ssl3_HandleAlert	<- ssl3_HandleRecord.
   3303 **              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
   3304 **              ssl3_ConsumeHandshakeVariable <-
   3305 **              ssl3_HandleHelloRequest	<-
   3306 **              ssl3_HandleServerHello	<-
   3307 **              ssl3_HandleServerKeyExchange <-
   3308 **              ssl3_HandleCertificateRequest <-
   3309 **              ssl3_HandleServerHelloDone <-
   3310 **              ssl3_HandleClientHello	<-
   3311 **              ssl3_HandleV2ClientHello <-
   3312 **              ssl3_HandleCertificateVerify <-
   3313 **              ssl3_HandleClientKeyExchange <-
   3314 **              ssl3_HandleCertificate	<-
   3315 **              ssl3_HandleFinished	<-
   3316 **              ssl3_HandleHandshakeMessage <-
   3317 **              ssl3_HandleRecord	<-
   3318 **
   3319 */
   3320 SECStatus
   3321 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
   3322 {
   3323     PRUint8 	bytes[2];
   3324     SECStatus	rv;
   3325 
   3326     SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
   3327 		SSL_GETPID(), ss->fd, level, desc));
   3328 
   3329     bytes[0] = level;
   3330     bytes[1] = desc;
   3331 
   3332     ssl_GetSSL3HandshakeLock(ss);
   3333     if (level == alert_fatal) {
   3334 	if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
   3335 	    ss->sec.uncache(ss->sec.ci.sid);
   3336 	}
   3337     }
   3338     ssl_GetXmitBufLock(ss);
   3339     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   3340     if (rv == SECSuccess) {
   3341 	PRInt32 sent;
   3342 	sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2,
   3343 			       desc == no_certificate
   3344 			       ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
   3345 	rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
   3346     }
   3347     ssl_ReleaseXmitBufLock(ss);
   3348     ssl_ReleaseSSL3HandshakeLock(ss);
   3349     return rv;	/* error set by ssl3_FlushHandshake or ssl3_SendRecord */
   3350 }
   3351 
   3352 /*
   3353  * Send illegal_parameter alert.  Set generic error number.
   3354  */
   3355 static SECStatus
   3356 ssl3_IllegalParameter(sslSocket *ss)
   3357 {
   3358     (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
   3359     PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
   3360                                    : SSL_ERROR_BAD_SERVER );
   3361     return SECFailure;
   3362 }
   3363 
   3364 /*
   3365  * Send handshake_Failure alert.  Set generic error number.
   3366  */
   3367 static SECStatus
   3368 ssl3_HandshakeFailure(sslSocket *ss)
   3369 {
   3370     (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
   3371     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
   3372                                     : SSL_ERROR_BAD_SERVER );
   3373     return SECFailure;
   3374 }
   3375 
   3376 static void
   3377 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
   3378 {
   3379     SSL3AlertDescription desc	= bad_certificate;
   3380     PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
   3381 
   3382     switch (errCode) {
   3383     case SEC_ERROR_LIBRARY_FAILURE:     desc = unsupported_certificate; break;
   3384     case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired;     break;
   3385     case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked;     break;
   3386     case SEC_ERROR_INADEQUATE_KEY_USAGE:
   3387     case SEC_ERROR_INADEQUATE_CERT_TYPE:
   3388 		                        desc = certificate_unknown;     break;
   3389     case SEC_ERROR_UNTRUSTED_CERT:
   3390 		    desc = isTLS ? access_denied : certificate_unknown; break;
   3391     case SEC_ERROR_UNKNOWN_ISSUER:
   3392     case SEC_ERROR_UNTRUSTED_ISSUER:
   3393 		    desc = isTLS ? unknown_ca : certificate_unknown; break;
   3394     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
   3395 		    desc = isTLS ? unknown_ca : certificate_expired; break;
   3396 
   3397     case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
   3398     case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
   3399     case SEC_ERROR_CA_CERT_INVALID:
   3400     case SEC_ERROR_BAD_SIGNATURE:
   3401     default:                            desc = bad_certificate;     break;
   3402     }
   3403     SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
   3404 	     SSL_GETPID(), ss->fd, errCode));
   3405 
   3406     (void) SSL3_SendAlert(ss, alert_fatal, desc);
   3407 }
   3408 
   3409 
   3410 /*
   3411  * Send decode_error alert.  Set generic error number.
   3412  */
   3413 SECStatus
   3414 ssl3_DecodeError(sslSocket *ss)
   3415 {
   3416     (void)SSL3_SendAlert(ss, alert_fatal,
   3417 		  ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
   3418 							: illegal_parameter);
   3419     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
   3420                                     : SSL_ERROR_BAD_SERVER );
   3421     return SECFailure;
   3422 }
   3423 
   3424 /* Called from ssl3_HandleRecord.
   3425 ** Caller must hold both RecvBuf and Handshake locks.
   3426 */
   3427 static SECStatus
   3428 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
   3429 {
   3430     SSL3AlertLevel       level;
   3431     SSL3AlertDescription desc;
   3432     int                  error;
   3433 
   3434     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   3435     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   3436 
   3437     SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
   3438 
   3439     if (buf->len != 2) {
   3440 	(void)ssl3_DecodeError(ss);
   3441 	PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
   3442 	return SECFailure;
   3443     }
   3444     level = (SSL3AlertLevel)buf->buf[0];
   3445     desc  = (SSL3AlertDescription)buf->buf[1];
   3446     buf->len = 0;
   3447     SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
   3448         SSL_GETPID(), ss->fd, level, desc));
   3449 
   3450     switch (desc) {
   3451     case close_notify:		ss->recvdCloseNotify = 1;
   3452 		        	error = SSL_ERROR_CLOSE_NOTIFY_ALERT;     break;
   3453     case unexpected_message: 	error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
   3454 									  break;
   3455     case bad_record_mac: 	error = SSL_ERROR_BAD_MAC_ALERT; 	  break;
   3456     case decryption_failed_RESERVED:
   3457                                 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
   3458     									  break;
   3459     case record_overflow: 	error = SSL_ERROR_RECORD_OVERFLOW_ALERT;  break;
   3460     case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
   3461 									  break;
   3462     case handshake_failure: 	error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
   3463 			        					  break;
   3464     case no_certificate: 	error = SSL_ERROR_NO_CERTIFICATE;	  break;
   3465     case bad_certificate: 	error = SSL_ERROR_BAD_CERT_ALERT; 	  break;
   3466     case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
   3467     case certificate_revoked: 	error = SSL_ERROR_REVOKED_CERT_ALERT; 	  break;
   3468     case certificate_expired: 	error = SSL_ERROR_EXPIRED_CERT_ALERT; 	  break;
   3469     case certificate_unknown: 	error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
   3470 			        					  break;
   3471     case illegal_parameter: 	error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
   3472     case inappropriate_fallback:
   3473         error = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
   3474         break;
   3475 
   3476     /* All alerts below are TLS only. */
   3477     case unknown_ca: 		error = SSL_ERROR_UNKNOWN_CA_ALERT;       break;
   3478     case access_denied: 	error = SSL_ERROR_ACCESS_DENIED_ALERT;    break;
   3479     case decode_error: 		error = SSL_ERROR_DECODE_ERROR_ALERT;     break;
   3480     case decrypt_error: 	error = SSL_ERROR_DECRYPT_ERROR_ALERT;    break;
   3481     case export_restriction: 	error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
   3482     									  break;
   3483     case protocol_version: 	error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
   3484     case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
   3485     									  break;
   3486     case internal_error: 	error = SSL_ERROR_INTERNAL_ERROR_ALERT;   break;
   3487     case user_canceled: 	error = SSL_ERROR_USER_CANCELED_ALERT;    break;
   3488     case no_renegotiation: 	error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
   3489 
   3490     /* Alerts for TLS client hello extensions */
   3491     case unsupported_extension:
   3492 			error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;    break;
   3493     case certificate_unobtainable:
   3494 			error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
   3495     case unrecognized_name:
   3496 			error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;        break;
   3497     case bad_certificate_status_response:
   3498 			error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
   3499     case bad_certificate_hash_value:
   3500 			error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;      break;
   3501     default: 		error = SSL_ERROR_RX_UNKNOWN_ALERT;               break;
   3502     }
   3503     if (level == alert_fatal) {
   3504 	if (!ss->opt.noCache) {
   3505 	    if (ss->sec.uncache)
   3506                 ss->sec.uncache(ss->sec.ci.sid);
   3507 	}
   3508 	if ((ss->ssl3.hs.ws == wait_server_hello) &&
   3509 	    (desc == handshake_failure)) {
   3510 	    /* XXX This is a hack.  We're assuming that any handshake failure
   3511 	     * XXX on the client hello is a failure to match ciphers.
   3512 	     */
   3513 	    error = SSL_ERROR_NO_CYPHER_OVERLAP;
   3514 	}
   3515 	PORT_SetError(error);
   3516 	return SECFailure;
   3517     }
   3518     if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
   3519     	/* I'm a server. I've requested a client cert. He hasn't got one. */
   3520 	SECStatus rv;
   3521 
   3522 	PORT_Assert(ss->sec.isServer);
   3523 	ss->ssl3.hs.ws = wait_client_key;
   3524 	rv = ssl3_HandleNoCertificate(ss);
   3525 	return rv;
   3526     }
   3527     return SECSuccess;
   3528 }
   3529 
   3530 /*
   3531  * Change Cipher Specs
   3532  * Called from ssl3_HandleServerHelloDone,
   3533  *             ssl3_HandleClientHello,
   3534  * and         ssl3_HandleFinished
   3535  *
   3536  * Acquires and releases spec write lock, to protect switching the current
   3537  * and pending write spec pointers.
   3538  */
   3539 
   3540 static SECStatus
   3541 ssl3_SendChangeCipherSpecs(sslSocket *ss)
   3542 {
   3543     PRUint8           change = change_cipher_spec_choice;
   3544     ssl3CipherSpec *  pwSpec;
   3545     SECStatus         rv;
   3546     PRInt32           sent;
   3547 
   3548     SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
   3549 		SSL_GETPID(), ss->fd));
   3550 
   3551     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   3552     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3553 
   3554     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   3555     if (rv != SECSuccess) {
   3556 	return rv;	/* error code set by ssl3_FlushHandshake */
   3557     }
   3558     if (!IS_DTLS(ss)) {
   3559 	sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
   3560 			       ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   3561 	if (sent < 0) {
   3562 	    return (SECStatus)sent;	/* error code set by ssl3_SendRecord */
   3563 	}
   3564     } else {
   3565 	rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
   3566 	if (rv != SECSuccess) {
   3567 	    return rv;
   3568 	}
   3569     }
   3570 
   3571     /* swap the pending and current write specs. */
   3572     ssl_GetSpecWriteLock(ss);	/**************************************/
   3573     pwSpec                     = ss->ssl3.pwSpec;
   3574 
   3575     ss->ssl3.pwSpec = ss->ssl3.cwSpec;
   3576     ss->ssl3.cwSpec = pwSpec;
   3577 
   3578     SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
   3579 		SSL_GETPID(), ss->fd ));
   3580 
   3581     /* We need to free up the contexts, keys and certs ! */
   3582     /* If we are really through with the old cipher spec
   3583      * (Both the read and write sides have changed) destroy it.
   3584      */
   3585     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
   3586 	if (!IS_DTLS(ss)) {
   3587 	    ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
   3588 	} else {
   3589 	    /* With DTLS, we need to set a holddown timer in case the final
   3590 	     * message got lost */
   3591 	    ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
   3592 	    dtls_StartTimer(ss, dtls_FinishedTimerCb);
   3593 	}
   3594     }
   3595     ssl_ReleaseSpecWriteLock(ss); /**************************************/
   3596 
   3597     return SECSuccess;
   3598 }
   3599 
   3600 /* Called from ssl3_HandleRecord.
   3601 ** Caller must hold both RecvBuf and Handshake locks.
   3602  *
   3603  * Acquires and releases spec write lock, to protect switching the current
   3604  * and pending write spec pointers.
   3605 */
   3606 static SECStatus
   3607 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
   3608 {
   3609     ssl3CipherSpec *           prSpec;
   3610     SSL3WaitState              ws      = ss->ssl3.hs.ws;
   3611     SSL3ChangeCipherSpecChoice change;
   3612 
   3613     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   3614     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   3615 
   3616     SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
   3617 		SSL_GETPID(), ss->fd));
   3618 
   3619     if (ws != wait_change_cipher) {
   3620 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   3621 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
   3622 	return SECFailure;
   3623     }
   3624 
   3625     if(buf->len != 1) {
   3626 	(void)ssl3_DecodeError(ss);
   3627 	PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
   3628 	return SECFailure;
   3629     }
   3630     change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
   3631     if (change != change_cipher_spec_choice) {
   3632 	/* illegal_parameter is correct here for both SSL3 and TLS. */
   3633 	(void)ssl3_IllegalParameter(ss);
   3634 	PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
   3635 	return SECFailure;
   3636     }
   3637     buf->len = 0;
   3638 
   3639     /* Swap the pending and current read specs. */
   3640     ssl_GetSpecWriteLock(ss);   /*************************************/
   3641     prSpec                    = ss->ssl3.prSpec;
   3642 
   3643     ss->ssl3.prSpec  = ss->ssl3.crSpec;
   3644     ss->ssl3.crSpec  = prSpec;
   3645     ss->ssl3.hs.ws   = wait_finished;
   3646 
   3647     SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
   3648 		SSL_GETPID(), ss->fd ));
   3649 
   3650     /* If we are really through with the old cipher prSpec
   3651      * (Both the read and write sides have changed) destroy it.
   3652      */
   3653     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
   3654     	ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
   3655     }
   3656     ssl_ReleaseSpecWriteLock(ss);   /*************************************/
   3657     return SECSuccess;
   3658 }
   3659 
   3660 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
   3661 ** is a PKCS11 symkey. This is used in all cases except the
   3662 ** "triple bypass" with RSA key exchange.
   3663 ** Called from ssl3_InitPendingCipherSpec.   prSpec is pwSpec.
   3664 */
   3665 static SECStatus
   3666 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
   3667 {
   3668     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
   3669     const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
   3670     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
   3671     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
   3672     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
   3673                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
   3674     PRBool            isTLS12=
   3675 	    (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   3676     /*
   3677      * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
   3678      * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
   3679      * data into a 48-byte value.
   3680      */
   3681     PRBool    isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
   3682 	                       (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
   3683     SECStatus         rv = SECFailure;
   3684     CK_MECHANISM_TYPE master_derive;
   3685     CK_MECHANISM_TYPE key_derive;
   3686     SECItem           params;
   3687     CK_FLAGS          keyFlags;
   3688     CK_VERSION        pms_version;
   3689     CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
   3690 
   3691     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3692     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   3693     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   3694     if (isTLS12) {
   3695 	if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256;
   3696 	else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
   3697 	key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
   3698 	keyFlags      = CKF_SIGN | CKF_VERIFY;
   3699     } else if (isTLS) {
   3700 	if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
   3701 	else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
   3702 	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
   3703 	keyFlags      = CKF_SIGN | CKF_VERIFY;
   3704     } else {
   3705 	if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
   3706 	else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
   3707 	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
   3708 	keyFlags      = 0;
   3709     }
   3710 
   3711     if (pms || !pwSpec->master_secret) {
   3712 	if (isDH) {
   3713 	    master_params.pVersion                     = NULL;
   3714 	} else {
   3715 	    master_params.pVersion                     = &pms_version;
   3716 	}
   3717 	master_params.RandomInfo.pClientRandom     = cr;
   3718 	master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
   3719 	master_params.RandomInfo.pServerRandom     = sr;
   3720 	master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
   3721 
   3722 	params.data = (unsigned char *) &master_params;
   3723 	params.len  = sizeof master_params;
   3724     }
   3725 
   3726     if (pms != NULL) {
   3727 #if defined(TRACE)
   3728 	if (ssl_trace >= 100) {
   3729 	    SECStatus extractRV = PK11_ExtractKeyValue(pms);
   3730 	    if (extractRV == SECSuccess) {
   3731 		SECItem * keyData = PK11_GetKeyData(pms);
   3732 		if (keyData && keyData->data && keyData->len) {
   3733 		    ssl_PrintBuf(ss, "Pre-Master Secret",
   3734 				 keyData->data, keyData->len);
   3735 		}
   3736 	    }
   3737 	}
   3738 #endif
   3739 	pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive,
   3740 				&params, key_derive, CKA_DERIVE, 0, keyFlags);
   3741 	if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
   3742 	    SSL3ProtocolVersion client_version;
   3743 	    client_version = pms_version.major << 8 | pms_version.minor;
   3744 
   3745 	    if (IS_DTLS(ss)) {
   3746 		client_version = dtls_DTLSVersionToTLSVersion(client_version);
   3747 	    }
   3748 
   3749 	    if (client_version != ss->clientHelloVersion) {
   3750 		/* Destroy it.  Version roll-back detected. */
   3751 		PK11_FreeSymKey(pwSpec->master_secret);
   3752 	    	pwSpec->master_secret = NULL;
   3753 	    }
   3754 	}
   3755 	if (pwSpec->master_secret == NULL) {
   3756 	    /* Generate a faux master secret in the same slot as the old one. */
   3757 	    PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
   3758 	    PK11SymKey *   fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
   3759 
   3760 	    PK11_FreeSlot(slot);
   3761 	    if (fpms != NULL) {
   3762 		pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
   3763 					master_derive, &params, key_derive,
   3764 					CKA_DERIVE, 0, keyFlags);
   3765 		PK11_FreeSymKey(fpms);
   3766 	    }
   3767 	}
   3768     }
   3769     if (pwSpec->master_secret == NULL) {
   3770 	/* Generate a faux master secret from the internal slot. */
   3771 	PK11SlotInfo *  slot = PK11_GetInternalSlot();
   3772 	PK11SymKey *    fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
   3773 
   3774 	PK11_FreeSlot(slot);
   3775 	if (fpms != NULL) {
   3776 	    pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
   3777 					master_derive, &params, key_derive,
   3778 					CKA_DERIVE, 0, keyFlags);
   3779 	    if (pwSpec->master_secret == NULL) {
   3780 	    	pwSpec->master_secret = fpms; /* use the fpms as the master. */
   3781 		fpms = NULL;
   3782 	    }
   3783 	}
   3784 	if (fpms) {
   3785 	    PK11_FreeSymKey(fpms);
   3786     	}
   3787     }
   3788     if (pwSpec->master_secret == NULL) {
   3789 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3790 	return rv;
   3791     }
   3792 #ifndef NO_PKCS11_BYPASS
   3793     if (ss->opt.bypassPKCS11) {
   3794 	SECItem * keydata;
   3795 	/* In hope of doing a "double bypass",
   3796 	 * need to extract the master secret's value from the key object
   3797 	 * and store it raw in the sslSocket struct.
   3798 	 */
   3799 	rv = PK11_ExtractKeyValue(pwSpec->master_secret);
   3800 	if (rv != SECSuccess) {
   3801 	    return rv;
   3802 	}
   3803 	/* This returns the address of the secItem inside the key struct,
   3804 	 * not a copy or a reference.  So, there's no need to free it.
   3805 	 */
   3806 	keydata = PK11_GetKeyData(pwSpec->master_secret);
   3807 	if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
   3808 	    memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
   3809 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   3810 	    pwSpec->msItem.len  = keydata->len;
   3811 	} else {
   3812 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   3813 	    return SECFailure;
   3814 	}
   3815     }
   3816 #endif
   3817     return SECSuccess;
   3818 }
   3819 
   3820 
   3821 /*
   3822  * Derive encryption and MAC Keys (and IVs) from master secret
   3823  * Sets a useful error code when returning SECFailure.
   3824  *
   3825  * Called only from ssl3_InitPendingCipherSpec(),
   3826  * which in turn is called from
   3827  *              sendRSAClientKeyExchange        (for Full handshake)
   3828  *              sendDHClientKeyExchange         (for Full handshake)
   3829  *              ssl3_HandleClientKeyExchange    (for Full handshake)
   3830  *              ssl3_HandleServerHello          (for session restart)
   3831  *              ssl3_HandleClientHello          (for session restart)
   3832  * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
   3833  * ssl3_InitPendingCipherSpec does that.
   3834  *
   3835  */
   3836 static SECStatus
   3837 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
   3838 {
   3839     ssl3CipherSpec *         pwSpec     = ss->ssl3.pwSpec;
   3840     const ssl3KEADef *       kea_def    = ss->ssl3.hs.kea_def;
   3841     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
   3842     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
   3843     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
   3844                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
   3845     PRBool            isTLS12=
   3846 	    (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   3847     /* following variables used in PKCS11 path */
   3848     const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
   3849     PK11SlotInfo *         slot   = NULL;
   3850     PK11SymKey *           symKey = NULL;
   3851     void *                 pwArg  = ss->pkcs11PinArg;
   3852     int                    keySize;
   3853     CK_SSL3_KEY_MAT_PARAMS key_material_params;
   3854     CK_SSL3_KEY_MAT_OUT    returnedKeys;
   3855     CK_MECHANISM_TYPE      key_derive;
   3856     CK_MECHANISM_TYPE      bulk_mechanism;
   3857     SSLCipherAlgorithm     calg;
   3858     SECItem                params;
   3859     PRBool         skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
   3860 
   3861     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3862     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   3863     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   3864 
   3865     if (!pwSpec->master_secret) {
   3866 	PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3867 	return SECFailure;
   3868     }
   3869     /*
   3870      * generate the key material
   3871      */
   3872     key_material_params.ulMacSizeInBits = pwSpec->mac_size           * BPB;
   3873     key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
   3874     key_material_params.ulIVSizeInBits  = cipher_def->iv_size        * BPB;
   3875     if (cipher_def->type == type_block &&
   3876 	pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   3877 	/* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
   3878 	key_material_params.ulIVSizeInBits = 0;
   3879 	memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
   3880 	memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
   3881     }
   3882 
   3883     key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
   3884 
   3885     key_material_params.RandomInfo.pClientRandom     = cr;
   3886     key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
   3887     key_material_params.RandomInfo.pServerRandom     = sr;
   3888     key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
   3889     key_material_params.pReturnedKeyMaterial         = &returnedKeys;
   3890 
   3891     returnedKeys.pIVClient = pwSpec->client.write_iv;
   3892     returnedKeys.pIVServer = pwSpec->server.write_iv;
   3893     keySize                = cipher_def->key_size;
   3894 
   3895     if (skipKeysAndIVs) {
   3896 	keySize                             = 0;
   3897         key_material_params.ulKeySizeInBits = 0;
   3898         key_material_params.ulIVSizeInBits  = 0;
   3899     	returnedKeys.pIVClient              = NULL;
   3900     	returnedKeys.pIVServer              = NULL;
   3901     }
   3902 
   3903     calg = cipher_def->calg;
   3904     PORT_Assert(     alg2Mech[calg].calg == calg);
   3905     bulk_mechanism = alg2Mech[calg].cmech;
   3906 
   3907     params.data    = (unsigned char *)&key_material_params;
   3908     params.len     = sizeof(key_material_params);
   3909 
   3910     if (isTLS12) {
   3911 	key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
   3912     } else if (isTLS) {
   3913 	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
   3914     } else {
   3915 	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
   3916     }
   3917 
   3918     /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
   3919      * DERIVE by DEFAULT */
   3920     symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
   3921                          bulk_mechanism, CKA_ENCRYPT, keySize);
   3922     if (!symKey) {
   3923 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3924 	return SECFailure;
   3925     }
   3926     /* we really should use the actual mac'ing mechanism here, but we
   3927      * don't because these types are used to map keytype anyway and both
   3928      * mac's map to the same keytype.
   3929      */
   3930     slot  = PK11_GetSlotFromKey(symKey);
   3931 
   3932     PK11_FreeSlot(slot); /* slot is held until the key is freed */
   3933     pwSpec->client.write_mac_key =
   3934     	PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3935 	    CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
   3936     if (pwSpec->client.write_mac_key == NULL ) {
   3937 	goto loser;	/* loser sets err */
   3938     }
   3939     pwSpec->server.write_mac_key =
   3940     	PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3941 	    CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
   3942     if (pwSpec->server.write_mac_key == NULL ) {
   3943 	goto loser;	/* loser sets err */
   3944     }
   3945     if (!skipKeysAndIVs) {
   3946 	pwSpec->client.write_key =
   3947 		PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3948 		     bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
   3949 	if (pwSpec->client.write_key == NULL ) {
   3950 	    goto loser;	/* loser sets err */
   3951 	}
   3952 	pwSpec->server.write_key =
   3953 		PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3954 		     bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
   3955 	if (pwSpec->server.write_key == NULL ) {
   3956 	    goto loser;	/* loser sets err */
   3957 	}
   3958     }
   3959     PK11_FreeSymKey(symKey);
   3960     return SECSuccess;
   3961 
   3962 
   3963 loser:
   3964     if (symKey) PK11_FreeSymKey(symKey);
   3965     ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3966     return SECFailure;
   3967 }
   3968 
   3969 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
   3970  * buffered messages in ss->ssl3.hs.messages. */
   3971 static SECStatus
   3972 ssl3_InitHandshakeHashes(sslSocket *ss)
   3973 {
   3974     SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
   3975 
   3976     PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
   3977 #ifndef NO_PKCS11_BYPASS
   3978     if (ss->opt.bypassPKCS11) {
   3979 	PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
   3980 	if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   3981 	    /* If we ever support ciphersuites where the PRF hash isn't SHA-256
   3982 	     * then this will need to be updated. */
   3983 	    ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
   3984 	    if (!ss->ssl3.hs.sha_obj) {
   3985 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   3986 		return SECFailure;
   3987 	    }
   3988 	    ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
   3989 	    ss->ssl3.hs.hashType = handshake_hash_single;
   3990 	    ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
   3991 	} else {
   3992 	    ss->ssl3.hs.hashType = handshake_hash_combo;
   3993 	    MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
   3994 	    SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
   3995 	}
   3996     } else
   3997 #endif
   3998     {
   3999 	PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
   4000 	/*
   4001 	 * note: We should probably lookup an SSL3 slot for these
   4002 	 * handshake hashes in hopes that we wind up with the same slots
   4003 	 * that the master secret will wind up in ...
   4004 	 */
   4005 	if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   4006 	    /* If we ever support ciphersuites where the PRF hash isn't SHA-256
   4007 	     * then this will need to be updated. */
   4008 	    ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
   4009 	    if (ss->ssl3.hs.sha == NULL) {
   4010 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4011 		return SECFailure;
   4012 	    }
   4013 	    ss->ssl3.hs.hashType = handshake_hash_single;
   4014 
   4015 	    if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
   4016 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4017 		return SECFailure;
   4018 	    }
   4019 
   4020 	    /* A backup SHA-1 hash for a potential client auth signature. */
   4021 	    if (!ss->sec.isServer) {
   4022 		ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_SHA1);
   4023 		if (ss->ssl3.hs.md5 == NULL) {
   4024 		    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4025 		    return SECFailure;
   4026 		}
   4027 
   4028 		if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
   4029 		    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4030 		    return SECFailure;
   4031 		}
   4032 	    }
   4033 	} else {
   4034 	    /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
   4035 	     * created successfully. */
   4036 	    ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
   4037 	    if (ss->ssl3.hs.md5 == NULL) {
   4038 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4039 		return SECFailure;
   4040 	    }
   4041 	    ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
   4042 	    if (ss->ssl3.hs.sha == NULL) {
   4043 		PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   4044 		ss->ssl3.hs.md5 = NULL;
   4045 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4046 		return SECFailure;
   4047 	    }
   4048 	    ss->ssl3.hs.hashType = handshake_hash_combo;
   4049 
   4050 	    if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
   4051 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4052 		return SECFailure;
   4053 	    }
   4054 	    if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
   4055 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4056 		return SECFailure;
   4057 	    }
   4058 	}
   4059     }
   4060 
   4061     if (ss->ssl3.hs.messages.len > 0) {
   4062 	if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
   4063 				       ss->ssl3.hs.messages.len) !=
   4064 	    SECSuccess) {
   4065 	    return SECFailure;
   4066 	}
   4067 	PORT_Free(ss->ssl3.hs.messages.buf);
   4068 	ss->ssl3.hs.messages.buf = NULL;
   4069 	ss->ssl3.hs.messages.len = 0;
   4070 	ss->ssl3.hs.messages.space = 0;
   4071     }
   4072 
   4073     return SECSuccess;
   4074 }
   4075 
   4076 static SECStatus
   4077 ssl3_RestartHandshakeHashes(sslSocket *ss)
   4078 {
   4079     SECStatus rv = SECSuccess;
   4080 
   4081     SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
   4082 	    SSL_GETPID(), ss->fd ));
   4083     ss->ssl3.hs.hashType = handshake_hash_unknown;
   4084     ss->ssl3.hs.messages.len = 0;
   4085 #ifndef NO_PKCS11_BYPASS
   4086     ss->ssl3.hs.sha_obj = NULL;
   4087     ss->ssl3.hs.sha_clone = NULL;
   4088 #endif
   4089     if (ss->ssl3.hs.md5) {
   4090 	PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
   4091 	ss->ssl3.hs.md5 = NULL;
   4092     }
   4093     if (ss->ssl3.hs.sha) {
   4094 	PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
   4095 	ss->ssl3.hs.sha = NULL;
   4096     }
   4097     return rv;
   4098 }
   4099 
   4100 /*
   4101  * Handshake messages
   4102  */
   4103 /* Called from	ssl3_InitHandshakeHashes()
   4104 **		ssl3_AppendHandshake()
   4105 **		ssl3_StartHandshakeHash()
   4106 **		ssl3_HandleV2ClientHello()
   4107 **		ssl3_HandleHandshakeMessage()
   4108 ** Caller must hold the ssl3Handshake lock.
   4109 */
   4110 static SECStatus
   4111 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
   4112 			   unsigned int l)
   4113 {
   4114     SECStatus  rv = SECSuccess;
   4115 
   4116     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4117 
   4118     /* We need to buffer the handshake messages until we have established
   4119      * which handshake hash function to use. */
   4120     if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
   4121 	return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
   4122     }
   4123 
   4124     PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
   4125 
   4126 #ifndef NO_PKCS11_BYPASS
   4127     if (ss->opt.bypassPKCS11) {
   4128 	if (ss->ssl3.hs.hashType == handshake_hash_single) {
   4129 	    ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
   4130 	} else {
   4131 	    MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
   4132 	    SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
   4133 	}
   4134 	return rv;
   4135     }
   4136 #endif
   4137     if (ss->ssl3.hs.hashType == handshake_hash_single) {
   4138 	rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
   4139 	if (rv != SECSuccess) {
   4140 	    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4141 	    return rv;
   4142 	}
   4143 	if (ss->ssl3.hs.md5) {
   4144 	    rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
   4145 	    if (rv != SECSuccess) {
   4146 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4147 		return rv;
   4148 	    }
   4149 	}
   4150     } else {
   4151 	rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
   4152 	if (rv != SECSuccess) {
   4153 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4154 	    return rv;
   4155 	}
   4156 	rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
   4157 	if (rv != SECSuccess) {
   4158 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4159 	    return rv;
   4160 	}
   4161     }
   4162     return rv;
   4163 }
   4164 
   4165 /**************************************************************************
   4166  * Append Handshake functions.
   4167  * All these functions set appropriate error codes.
   4168  * Most rely on ssl3_AppendHandshake to set the error code.
   4169  **************************************************************************/
   4170 SECStatus
   4171 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
   4172 {
   4173     unsigned char *  src  = (unsigned char *)void_src;
   4174     int              room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
   4175     SECStatus        rv;
   4176 
   4177     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
   4178 
   4179     if (!bytes)
   4180     	return SECSuccess;
   4181     if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
   4182 	rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
   4183 		 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
   4184 	if (rv != SECSuccess)
   4185 	    return rv;	/* sslBuffer_Grow has set a memory error code. */
   4186 	room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
   4187     }
   4188 
   4189     PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
   4190     rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
   4191     if (rv != SECSuccess)
   4192 	return rv;	/* error code set by ssl3_UpdateHandshakeHashes */
   4193 
   4194     while (bytes > room) {
   4195 	if (room > 0)
   4196 	    PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
   4197 	                room);
   4198 	ss->sec.ci.sendBuf.len += room;
   4199 	rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   4200 	if (rv != SECSuccess) {
   4201 	    return rv;	/* error code set by ssl3_FlushHandshake */
   4202 	}
   4203 	bytes -= room;
   4204 	src += room;
   4205 	room = ss->sec.ci.sendBuf.space;
   4206 	PORT_Assert(ss->sec.ci.sendBuf.len == 0);
   4207     }
   4208     PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
   4209     ss->sec.ci.sendBuf.len += bytes;
   4210     return SECSuccess;
   4211 }
   4212 
   4213 SECStatus
   4214 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
   4215 {
   4216     SECStatus rv;
   4217     PRUint8   b[4];
   4218     PRUint8 * p = b;
   4219 
   4220     switch (lenSize) {
   4221       case 4:
   4222 	*p++ = (num >> 24) & 0xff;
   4223       case 3:
   4224 	*p++ = (num >> 16) & 0xff;
   4225       case 2:
   4226 	*p++ = (num >> 8) & 0xff;
   4227       case 1:
   4228 	*p = num & 0xff;
   4229     }
   4230     SSL_TRC(60, ("%d: number:", SSL_GETPID()));
   4231     rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
   4232     return rv;	/* error code set by AppendHandshake, if applicable. */
   4233 }
   4234 
   4235 SECStatus
   4236 ssl3_AppendHandshakeVariable(
   4237     sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
   4238 {
   4239     SECStatus rv;
   4240 
   4241     PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
   4242 	      (bytes < (1L<<16) && lenSize == 2) ||
   4243 	      (bytes < (1L<<24) && lenSize == 3));
   4244 
   4245     SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
   4246     rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
   4247     if (rv != SECSuccess) {
   4248 	return rv;	/* error code set by AppendHandshake, if applicable. */
   4249     }
   4250     SSL_TRC(60, ("data:"));
   4251     rv = ssl3_AppendHandshake(ss, src, bytes);
   4252     return rv;	/* error code set by AppendHandshake, if applicable. */
   4253 }
   4254 
   4255 SECStatus
   4256 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
   4257 {
   4258     SECStatus rv;
   4259 
   4260     /* If we already have a message in place, we need to enqueue it.
   4261      * This empties the buffer. This is a convenient place to call
   4262      * dtls_StageHandshakeMessage to mark the message boundary.
   4263      */
   4264     if (IS_DTLS(ss)) {
   4265 	rv = dtls_StageHandshakeMessage(ss);
   4266 	if (rv != SECSuccess) {
   4267 	    return rv;
   4268 	}
   4269     }
   4270 
   4271     SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
   4272     	SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
   4273 
   4274     rv = ssl3_AppendHandshakeNumber(ss, t, 1);
   4275     if (rv != SECSuccess) {
   4276     	return rv;	/* error code set by AppendHandshake, if applicable. */
   4277     }
   4278     rv = ssl3_AppendHandshakeNumber(ss, length, 3);
   4279     if (rv != SECSuccess) {
   4280     	return rv;	/* error code set by AppendHandshake, if applicable. */
   4281     }
   4282 
   4283     if (IS_DTLS(ss)) {
   4284 	/* Note that we make an unfragmented message here. We fragment in the
   4285 	 * transmission code, if necessary */
   4286 	rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
   4287 	if (rv != SECSuccess) {
   4288 	    return rv;	/* error code set by AppendHandshake, if applicable. */
   4289 	}
   4290 	ss->ssl3.hs.sendMessageSeq++;
   4291 
   4292 	/* 0 is the fragment offset, because it's not fragmented yet */
   4293 	rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
   4294 	if (rv != SECSuccess) {
   4295 	    return rv;	/* error code set by AppendHandshake, if applicable. */
   4296 	}
   4297 
   4298 	/* Fragment length -- set to the packet length because not fragmented */
   4299 	rv = ssl3_AppendHandshakeNumber(ss, length, 3);
   4300 	if (rv != SECSuccess) {
   4301 	    return rv;	/* error code set by AppendHandshake, if applicable. */
   4302 	}
   4303     }
   4304 
   4305     return rv;		/* error code set by AppendHandshake, if applicable. */
   4306 }
   4307 
   4308 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
   4309  * |sigAndHash| to the current handshake message. */
   4310 SECStatus
   4311 ssl3_AppendSignatureAndHashAlgorithm(
   4312 	sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash)
   4313 {
   4314     unsigned char serialized[2];
   4315 
   4316     serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg);
   4317     if (serialized[0] == 0) {
   4318 	PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   4319 	return SECFailure;
   4320     }
   4321 
   4322     serialized[1] = sigAndHash->sigAlg;
   4323 
   4324     return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
   4325 }
   4326 
   4327 /**************************************************************************
   4328  * Consume Handshake functions.
   4329  *
   4330  * All data used in these functions is protected by two locks,
   4331  * the RecvBufLock and the SSL3HandshakeLock
   4332  **************************************************************************/
   4333 
   4334 /* Read up the next "bytes" number of bytes from the (decrypted) input
   4335  * stream "b" (which is *length bytes long). Copy them into buffer "v".
   4336  * Reduces *length by bytes.  Advances *b by bytes.
   4337  *
   4338  * If this function returns SECFailure, it has already sent an alert,
   4339  * and has set a generic error code.  The caller should probably
   4340  * override the generic error code by setting another.
   4341  */
   4342 SECStatus
   4343 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
   4344 		      PRUint32 *length)
   4345 {
   4346     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   4347     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4348 
   4349     if ((PRUint32)bytes > *length) {
   4350 	return ssl3_DecodeError(ss);
   4351     }
   4352     PORT_Memcpy(v, *b, bytes);
   4353     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
   4354     *b      += bytes;
   4355     *length -= bytes;
   4356     return SECSuccess;
   4357 }
   4358 
   4359 /* Read up the next "bytes" number of bytes from the (decrypted) input
   4360  * stream "b" (which is *length bytes long), and interpret them as an
   4361  * integer in network byte order.  Returns the received value.
   4362  * Reduces *length by bytes.  Advances *b by bytes.
   4363  *
   4364  * Returns SECFailure (-1) on failure.
   4365  * This value is indistinguishable from the equivalent received value.
   4366  * Only positive numbers are to be received this way.
   4367  * Thus, the largest value that may be sent this way is 0x7fffffff.
   4368  * On error, an alert has been sent, and a generic error code has been set.
   4369  */
   4370 PRInt32
   4371 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
   4372 			    PRUint32 *length)
   4373 {
   4374     PRUint8  *buf = *b;
   4375     int       i;
   4376     PRInt32   num = 0;
   4377 
   4378     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   4379     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4380     PORT_Assert( bytes <= sizeof num);
   4381 
   4382     if ((PRUint32)bytes > *length) {
   4383 	return ssl3_DecodeError(ss);
   4384     }
   4385     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
   4386 
   4387     for (i = 0; i < bytes; i++)
   4388 	num = (num << 8) + buf[i];
   4389     *b      += bytes;
   4390     *length -= bytes;
   4391     return num;
   4392 }
   4393 
   4394 /* Read in two values from the incoming decrypted byte stream "b", which is
   4395  * *length bytes long.  The first value is a number whose size is "bytes"
   4396  * bytes long.  The second value is a byte-string whose size is the value
   4397  * of the first number received.  The latter byte-string, and its length,
   4398  * is returned in the SECItem i.
   4399  *
   4400  * Returns SECFailure (-1) on failure.
   4401  * On error, an alert has been sent, and a generic error code has been set.
   4402  *
   4403  * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
   4404  * of the data returned in the SECItem *i, so making a copy of it here
   4405  * is simply wasteful.  So, This function now just sets SECItem *i to
   4406  * point to the values in the buffer **b.
   4407  */
   4408 SECStatus
   4409 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
   4410 			      SSL3Opaque **b, PRUint32 *length)
   4411 {
   4412     PRInt32   count;
   4413 
   4414     PORT_Assert(bytes <= 3);
   4415     i->len  = 0;
   4416     i->data = NULL;
   4417     count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
   4418     if (count < 0) { 		/* Can't test for SECSuccess here. */
   4419     	return SECFailure;
   4420     }
   4421     if (count > 0) {
   4422 	if ((PRUint32)count > *length) {
   4423 	    return ssl3_DecodeError(ss);
   4424 	}
   4425 	i->data = *b;
   4426 	i->len  = count;
   4427 	*b      += count;
   4428 	*length -= count;
   4429     }
   4430     return SECSuccess;
   4431 }
   4432 
   4433 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
   4434  * SECOidTag used internally by NSS. */
   4435 static const struct {
   4436     int tlsHash;
   4437     SECOidTag oid;
   4438 } tlsHashOIDMap[] = {
   4439     { tls_hash_md5, SEC_OID_MD5 },
   4440     { tls_hash_sha1, SEC_OID_SHA1 },
   4441     { tls_hash_sha224, SEC_OID_SHA224 },
   4442     { tls_hash_sha256, SEC_OID_SHA256 },
   4443     { tls_hash_sha384, SEC_OID_SHA384 },
   4444     { tls_hash_sha512, SEC_OID_SHA512 }
   4445 };
   4446 
   4447 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
   4448  * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
   4449  *
   4450  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   4451 SECOidTag
   4452 ssl3_TLSHashAlgorithmToOID(int hashFunc)
   4453 {
   4454     unsigned int i;
   4455 
   4456     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
   4457 	if (hashFunc == tlsHashOIDMap[i].tlsHash) {
   4458 	    return tlsHashOIDMap[i].oid;
   4459 	}
   4460     }
   4461     return SEC_OID_UNKNOWN;
   4462 }
   4463 
   4464 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
   4465  * identifier. If the hash is not recognised, zero is returned.
   4466  *
   4467  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   4468 static int
   4469 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid)
   4470 {
   4471     unsigned int i;
   4472 
   4473     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
   4474 	if (oid == tlsHashOIDMap[i].oid) {
   4475 	    return tlsHashOIDMap[i].tlsHash;
   4476 	}
   4477     }
   4478     return 0;
   4479 }
   4480 
   4481 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
   4482  * identifier for a given KeyType. */
   4483 static SECStatus
   4484 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType,
   4485 				     TLSSignatureAlgorithm *out)
   4486 {
   4487     switch (keyType) {
   4488     case rsaKey:
   4489 	*out = tls_sig_rsa;
   4490 	return SECSuccess;
   4491     case dsaKey:
   4492 	*out = tls_sig_dsa;
   4493 	return SECSuccess;
   4494     case ecKey:
   4495 	*out = tls_sig_ecdsa;
   4496 	return SECSuccess;
   4497     default:
   4498 	PORT_SetError(SEC_ERROR_INVALID_KEY);
   4499 	return SECFailure;
   4500     }
   4501 }
   4502 
   4503 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
   4504  * algorithm identifier for the given certificate. */
   4505 static SECStatus
   4506 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
   4507 					 TLSSignatureAlgorithm *out)
   4508 {
   4509     SECKEYPublicKey *key;
   4510     KeyType keyType;
   4511 
   4512     key = CERT_ExtractPublicKey(cert);
   4513     if (key == NULL) {
   4514 	ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   4515     	return SECFailure;
   4516     }
   4517 
   4518     keyType = key->keyType;
   4519     SECKEY_DestroyPublicKey(key);
   4520     return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out);
   4521 }
   4522 
   4523 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
   4524  * algorithm identifier in |sigAndHash| is consistent with the public key in
   4525  * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
   4526  * and SECFailure is returned. */
   4527 SECStatus
   4528 ssl3_CheckSignatureAndHashAlgorithmConsistency(
   4529 	const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert)
   4530 {
   4531     SECStatus rv;
   4532     TLSSignatureAlgorithm sigAlg;
   4533 
   4534     rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
   4535     if (rv != SECSuccess) {
   4536 	return rv;
   4537     }
   4538     if (sigAlg != sigAndHash->sigAlg) {
   4539 	PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
   4540 	return SECFailure;
   4541     }
   4542     return SECSuccess;
   4543 }
   4544 
   4545 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
   4546  * structure from |b| and puts the resulting value into |out|. |b| and |length|
   4547  * are updated accordingly.
   4548  *
   4549  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   4550 SECStatus
   4551 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
   4552 				      SSL3Opaque **b,
   4553 				      PRUint32 *length,
   4554 				      SSL3SignatureAndHashAlgorithm *out)
   4555 {
   4556     unsigned char bytes[2];
   4557     SECStatus rv;
   4558 
   4559     rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length);
   4560     if (rv != SECSuccess) {
   4561 	return rv;
   4562     }
   4563 
   4564     out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]);
   4565     if (out->hashAlg == SEC_OID_UNKNOWN) {
   4566 	PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   4567 	return SECFailure;
   4568     }
   4569 
   4570     out->sigAlg = bytes[1];
   4571     return SECSuccess;
   4572 }
   4573 
   4574 /**************************************************************************
   4575  * end of Consume Handshake functions.
   4576  **************************************************************************/
   4577 
   4578 /* Extract the hashes of handshake messages to this point.
   4579  * Called from ssl3_SendCertificateVerify
   4580  *             ssl3_SendFinished
   4581  *             ssl3_HandleHandshakeMessage
   4582  *
   4583  * Caller must hold the SSL3HandshakeLock.
   4584  * Caller must hold a read or write lock on the Spec R/W lock.
   4585  *	(There is presently no way to assert on a Read lock.)
   4586  */
   4587 static SECStatus
   4588 ssl3_ComputeHandshakeHashes(sslSocket *     ss,
   4589                             ssl3CipherSpec *spec,   /* uses ->master_secret */
   4590 			    SSL3Hashes *    hashes, /* output goes here. */
   4591 			    PRUint32        sender)
   4592 {
   4593     SECStatus     rv        = SECSuccess;
   4594     PRBool        isTLS     = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
   4595     unsigned int  outLength;
   4596     SSL3Opaque    md5_inner[MAX_MAC_LENGTH];
   4597     SSL3Opaque    sha_inner[MAX_MAC_LENGTH];
   4598 
   4599     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4600     hashes->hashAlg = SEC_OID_UNKNOWN;
   4601 
   4602 #ifndef NO_PKCS11_BYPASS
   4603     if (ss->opt.bypassPKCS11 &&
   4604 	ss->ssl3.hs.hashType == handshake_hash_single) {
   4605 	/* compute them without PKCS11 */
   4606 	PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
   4607 
   4608 	if (!spec->msItem.data) {
   4609 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4610 	    return SECFailure;
   4611 	}
   4612 
   4613 	ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
   4614 	ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
   4615 				 sizeof(hashes->u.raw));
   4616 
   4617 	PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
   4618 
   4619 	/* If we ever support ciphersuites where the PRF hash isn't SHA-256
   4620 	 * then this will need to be updated. */
   4621 	hashes->hashAlg = SEC_OID_SHA256;
   4622 	rv = SECSuccess;
   4623     } else if (ss->opt.bypassPKCS11) {
   4624 	/* compute them without PKCS11 */
   4625 	PRUint64      md5_cx[MAX_MAC_CONTEXT_LLONGS];
   4626 	PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
   4627 
   4628 #define md5cx ((MD5Context *)md5_cx)
   4629 #define shacx ((SHA1Context *)sha_cx)
   4630 
   4631 	if (!spec->msItem.data) {
   4632 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4633 	    return SECFailure;
   4634 	}
   4635 
   4636 	MD5_Clone (md5cx,  (MD5Context *)ss->ssl3.hs.md5_cx);
   4637 	SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
   4638 
   4639 	if (!isTLS) {
   4640 	    /* compute hashes for SSL3. */
   4641 	    unsigned char s[4];
   4642 
   4643 	    s[0] = (unsigned char)(sender >> 24);
   4644 	    s[1] = (unsigned char)(sender >> 16);
   4645 	    s[2] = (unsigned char)(sender >> 8);
   4646 	    s[3] = (unsigned char)sender;
   4647 
   4648 	    if (sender != 0) {
   4649 		MD5_Update(md5cx, s, 4);
   4650 		PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
   4651 	    }
   4652 
   4653 	    PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
   4654 			    mac_defs[mac_md5].pad_size));
   4655 
   4656 	    MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
   4657 	    MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
   4658 	    MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
   4659 
   4660 	    PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
   4661 
   4662 	    if (sender != 0) {
   4663 		SHA1_Update(shacx, s, 4);
   4664 		PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
   4665 	    }
   4666 
   4667 	    PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
   4668 			    mac_defs[mac_sha].pad_size));
   4669 
   4670 	    SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
   4671 	    SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
   4672 	    SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
   4673 
   4674 	    PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
   4675 	    PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
   4676 			    mac_defs[mac_md5].pad_size));
   4677 	    PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
   4678 
   4679 	    MD5_Begin(md5cx);
   4680 	    MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
   4681 	    MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
   4682 	    MD5_Update(md5cx, md5_inner, MD5_LENGTH);
   4683 	}
   4684 	MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
   4685 
   4686 	PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
   4687 
   4688 	if (!isTLS) {
   4689 	    PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
   4690 			    mac_defs[mac_sha].pad_size));
   4691 	    PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
   4692 
   4693 	    SHA1_Begin(shacx);
   4694 	    SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
   4695 	    SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
   4696 	    SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
   4697 	}
   4698 	SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
   4699 
   4700 	PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
   4701 
   4702 	hashes->len = MD5_LENGTH + SHA1_LENGTH;
   4703 	rv = SECSuccess;
   4704 #undef md5cx
   4705 #undef shacx
   4706     } else
   4707 #endif
   4708     if (ss->ssl3.hs.hashType == handshake_hash_single) {
   4709 	/* compute hashes with PKCS11 */
   4710 	PK11Context *h;
   4711 	unsigned int  stateLen;
   4712 	unsigned char stackBuf[1024];
   4713 	unsigned char *stateBuf = NULL;
   4714 
   4715 	if (!spec->master_secret) {
   4716 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4717 	    return SECFailure;
   4718 	}
   4719 
   4720 	h = ss->ssl3.hs.sha;
   4721 	stateBuf = PK11_SaveContextAlloc(h, stackBuf,
   4722 					 sizeof(stackBuf), &stateLen);
   4723 	if (stateBuf == NULL) {
   4724 	    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4725 	    goto tls12_loser;
   4726 	}
   4727 	rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
   4728 			       sizeof(hashes->u.raw));
   4729 	if (rv != SECSuccess) {
   4730 	    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4731 	    rv = SECFailure;
   4732 	    goto tls12_loser;
   4733 	}
   4734 	/* If we ever support ciphersuites where the PRF hash isn't SHA-256
   4735 	 * then this will need to be updated. */
   4736 	hashes->hashAlg = SEC_OID_SHA256;
   4737 	rv = SECSuccess;
   4738 
   4739 tls12_loser:
   4740 	if (stateBuf) {
   4741 	    if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
   4742 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4743 		rv = SECFailure;
   4744 	    }
   4745 	    if (stateBuf != stackBuf) {
   4746 		PORT_ZFree(stateBuf, stateLen);
   4747 	    }
   4748 	}
   4749     } else {
   4750 	/* compute hashes with PKCS11 */
   4751 	PK11Context * md5;
   4752 	PK11Context * sha       = NULL;
   4753 	unsigned char *md5StateBuf = NULL;
   4754 	unsigned char *shaStateBuf = NULL;
   4755 	unsigned int  md5StateLen, shaStateLen;
   4756 	unsigned char md5StackBuf[256];
   4757 	unsigned char shaStackBuf[512];
   4758 
   4759 	if (!spec->master_secret) {
   4760 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4761 	    return SECFailure;
   4762 	}
   4763 
   4764 	md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
   4765 					    sizeof md5StackBuf, &md5StateLen);
   4766 	if (md5StateBuf == NULL) {
   4767 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4768 	    goto loser;
   4769 	}
   4770 	md5 = ss->ssl3.hs.md5;
   4771 
   4772 	shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
   4773 					    sizeof shaStackBuf, &shaStateLen);
   4774 	if (shaStateBuf == NULL) {
   4775 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4776 	    goto loser;
   4777 	}
   4778 	sha = ss->ssl3.hs.sha;
   4779 
   4780 	if (!isTLS) {
   4781 	    /* compute hashes for SSL3. */
   4782 	    unsigned char s[4];
   4783 
   4784 	    s[0] = (unsigned char)(sender >> 24);
   4785 	    s[1] = (unsigned char)(sender >> 16);
   4786 	    s[2] = (unsigned char)(sender >> 8);
   4787 	    s[3] = (unsigned char)sender;
   4788 
   4789 	    if (sender != 0) {
   4790 		rv |= PK11_DigestOp(md5, s, 4);
   4791 		PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
   4792 	    }
   4793 
   4794 	    PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
   4795 			  mac_defs[mac_md5].pad_size));
   4796 
   4797 	    rv |= PK11_DigestKey(md5,spec->master_secret);
   4798 	    rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
   4799 	    rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
   4800 	    PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
   4801 	    if (rv != SECSuccess) {
   4802 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4803 		rv = SECFailure;
   4804 		goto loser;
   4805 	    }
   4806 
   4807 	    PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
   4808 
   4809 	    if (sender != 0) {
   4810 		rv |= PK11_DigestOp(sha, s, 4);
   4811 		PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
   4812 	    }
   4813 
   4814 	    PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
   4815 			  mac_defs[mac_sha].pad_size));
   4816 
   4817 	    rv |= PK11_DigestKey(sha, spec->master_secret);
   4818 	    rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
   4819 	    rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
   4820 	    PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
   4821 	    if (rv != SECSuccess) {
   4822 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4823 		rv = SECFailure;
   4824 		goto loser;
   4825 	    }
   4826 
   4827 	    PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
   4828 
   4829 	    PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
   4830 			  mac_defs[mac_md5].pad_size));
   4831 	    PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
   4832 
   4833 	    rv |= PK11_DigestBegin(md5);
   4834 	    rv |= PK11_DigestKey(md5, spec->master_secret);
   4835 	    rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
   4836 	    rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
   4837 	}
   4838 	rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
   4839 	PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
   4840 	if (rv != SECSuccess) {
   4841 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4842 	    rv = SECFailure;
   4843 	    goto loser;
   4844 	}
   4845 
   4846 	PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
   4847 
   4848 	if (!isTLS) {
   4849 	    PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
   4850 			  mac_defs[mac_sha].pad_size));
   4851 	    PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
   4852 
   4853 	    rv |= PK11_DigestBegin(sha);
   4854 	    rv |= PK11_DigestKey(sha,spec->master_secret);
   4855 	    rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
   4856 	    rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
   4857 	}
   4858 	rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
   4859 	PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
   4860 	if (rv != SECSuccess) {
   4861 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4862 	    rv = SECFailure;
   4863 	    goto loser;
   4864 	}
   4865 
   4866 	PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
   4867 
   4868 	hashes->len = MD5_LENGTH + SHA1_LENGTH;
   4869 	rv = SECSuccess;
   4870 
   4871     loser:
   4872 	if (md5StateBuf) {
   4873 	    if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
   4874 		 != SECSuccess)
   4875 	    {
   4876 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4877 		rv = SECFailure;
   4878 	    }
   4879 	    if (md5StateBuf != md5StackBuf) {
   4880 		PORT_ZFree(md5StateBuf, md5StateLen);
   4881 	    }
   4882 	}
   4883 	if (shaStateBuf) {
   4884 	    if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
   4885 		 != SECSuccess)
   4886 	    {
   4887 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4888 		rv = SECFailure;
   4889 	    }
   4890 	    if (shaStateBuf != shaStackBuf) {
   4891 		PORT_ZFree(shaStateBuf, shaStateLen);
   4892 	    }
   4893 	}
   4894     }
   4895     return rv;
   4896 }
   4897 
   4898 static SECStatus
   4899 ssl3_ComputeBackupHandshakeHashes(sslSocket * ss,
   4900 				  SSL3Hashes * hashes) /* output goes here. */
   4901 {
   4902     SECStatus rv = SECSuccess;
   4903 
   4904     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4905     PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single );
   4906 
   4907     rv = PK11_DigestFinal(ss->ssl3.hs.md5, hashes->u.raw, &hashes->len,
   4908 			  sizeof(hashes->u.raw));
   4909     if (rv != SECSuccess) {
   4910 	ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4911 	rv = SECFailure;
   4912 	goto loser;
   4913     }
   4914     hashes->hashAlg = SEC_OID_SHA1;
   4915 
   4916 loser:
   4917     PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   4918     ss->ssl3.hs.md5 = NULL;
   4919     return rv;
   4920 }
   4921 
   4922 /*
   4923  * SSL 2 based implementations pass in the initial outbound buffer
   4924  * so that the handshake hash can contain the included information.
   4925  *
   4926  * Called from ssl2_BeginClientHandshake() in sslcon.c
   4927  */
   4928 SECStatus
   4929 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
   4930 {
   4931     SECStatus rv;
   4932 
   4933     ssl_GetSSL3HandshakeLock(ss);  /**************************************/
   4934 
   4935     rv = ssl3_InitState(ss);
   4936     if (rv != SECSuccess) {
   4937 	goto done;		/* ssl3_InitState has set the error code. */
   4938     }
   4939     rv = ssl3_RestartHandshakeHashes(ss);
   4940     if (rv != SECSuccess) {
   4941 	goto done;
   4942     }
   4943 
   4944     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
   4945     PORT_Memcpy(
   4946 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
   4947 	&ss->sec.ci.clientChallenge,
   4948 	SSL_CHALLENGE_BYTES);
   4949 
   4950     rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
   4951     /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
   4952 
   4953 done:
   4954     ssl_ReleaseSSL3HandshakeLock(ss);  /**************************************/
   4955     return rv;
   4956 }
   4957 
   4958 /**************************************************************************
   4959  * end of Handshake Hash functions.
   4960  * Begin Send and Handle functions for handshakes.
   4961  **************************************************************************/
   4962 
   4963 /* Called from ssl3_HandleHelloRequest(),
   4964  *             ssl3_RedoHandshake()
   4965  *             ssl2_BeginClientHandshake (when resuming ssl3 session)
   4966  *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
   4967  */
   4968 SECStatus
   4969 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
   4970 {
   4971     sslSessionID *   sid;
   4972     ssl3CipherSpec * cwSpec;
   4973     SECStatus        rv;
   4974     int              i;
   4975     int              length;
   4976     int              num_suites;
   4977     int              actual_count = 0;
   4978     PRBool           isTLS = PR_FALSE;
   4979     PRBool           requestingResume = PR_FALSE, fallbackSCSV = PR_FALSE;
   4980     PRInt32          total_exten_len = 0;
   4981     unsigned         paddingExtensionLen;
   4982     unsigned         numCompressionMethods;
   4983     PRInt32          flags;
   4984 
   4985     SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
   4986 		ss->fd));
   4987 
   4988     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4989     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   4990 
   4991     rv = ssl3_InitState(ss);
   4992     if (rv != SECSuccess) {
   4993 	return rv;		/* ssl3_InitState has set the error code. */
   4994     }
   4995     ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
   4996     PORT_Assert(IS_DTLS(ss) || !resending);
   4997 
   4998     /* We might be starting a session renegotiation in which case we should
   4999      * clear previous state.
   5000      */
   5001     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   5002 
   5003     rv = ssl3_RestartHandshakeHashes(ss);
   5004     if (rv != SECSuccess) {
   5005 	return rv;
   5006     }
   5007 
   5008     /*
   5009      * During a renegotiation, ss->clientHelloVersion will be used again to
   5010      * work around a Windows SChannel bug. Ensure that it is still enabled.
   5011      */
   5012     if (ss->firstHsDone) {
   5013 	if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
   5014 	    PORT_SetError(SSL_ERROR_SSL_DISABLED);
   5015 	    return SECFailure;
   5016 	}
   5017 
   5018 	if (ss->clientHelloVersion < ss->vrange.min ||
   5019 	    ss->clientHelloVersion > ss->vrange.max) {
   5020 	    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
   5021 	    return SECFailure;
   5022 	}
   5023     }
   5024 
   5025     /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
   5026      * handles expired entries and other details.
   5027      * XXX If we've been called from ssl2_BeginClientHandshake, then
   5028      * this lookup is duplicative and wasteful.
   5029      */
   5030     sid = (ss->opt.noCache) ? NULL
   5031 	    : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
   5032 
   5033     /* We can't resume based on a different token. If the sid exists,
   5034      * make sure the token that holds the master secret still exists ...
   5035      * If we previously did client-auth, make sure that the token that holds
   5036      * the private key still exists, is logged in, hasn't been removed, etc.
   5037      */
   5038     if (sid) {
   5039 	PRBool sidOK = PR_TRUE;
   5040 	if (sid->u.ssl3.keys.msIsWrapped) {
   5041 	    /* Session key was wrapped, which means it was using PKCS11, */
   5042 	    PK11SlotInfo *slot = NULL;
   5043 	    if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
   5044 		slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
   5045 					 sid->u.ssl3.masterSlotID);
   5046 	    }
   5047 	    if (slot == NULL) {
   5048 	       sidOK = PR_FALSE;
   5049 	    } else {
   5050 		PK11SymKey *wrapKey = NULL;
   5051 		if (!PK11_IsPresent(slot) ||
   5052 		    ((wrapKey = PK11_GetWrapKey(slot,
   5053 						sid->u.ssl3.masterWrapIndex,
   5054 						sid->u.ssl3.masterWrapMech,
   5055 						sid->u.ssl3.masterWrapSeries,
   5056 						ss->pkcs11PinArg)) == NULL) ) {
   5057 		    sidOK = PR_FALSE;
   5058 		}
   5059 		if (wrapKey) PK11_FreeSymKey(wrapKey);
   5060 		PK11_FreeSlot(slot);
   5061 		slot = NULL;
   5062 	    }
   5063 	}
   5064 	/* If we previously did client-auth, make sure that the token that
   5065 	** holds the private key still exists, is logged in, hasn't been
   5066 	** removed, etc.
   5067 	*/
   5068 	if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
   5069 	    sidOK = PR_FALSE;
   5070 	}
   5071 
   5072 	/* TLS 1.0 (RFC 2246) Appendix E says:
   5073 	 *   Whenever a client already knows the highest protocol known to
   5074 	 *   a server (for example, when resuming a session), it should
   5075 	 *   initiate the connection in that native protocol.
   5076 	 * So we pass sid->version to ssl3_NegotiateVersion() here, except
   5077 	 * when renegotiating.
   5078 	 *
   5079 	 * Windows SChannel compares the client_version inside the RSA
   5080 	 * EncryptedPreMasterSecret of a renegotiation with the
   5081 	 * client_version of the initial ClientHello rather than the
   5082 	 * ClientHello in the renegotiation. To work around this bug, we
   5083 	 * continue to use the client_version used in the initial
   5084 	 * ClientHello when renegotiating.
   5085 	 */
   5086 	if (sidOK) {
   5087 	    if (ss->firstHsDone) {
   5088 		/*
   5089 		 * The client_version of the initial ClientHello is still
   5090 		 * available in ss->clientHelloVersion. Ensure that
   5091 		 * sid->version is bounded within
   5092 		 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
   5093 		 * can't use sid.
   5094 		 */
   5095 		if (sid->version >= ss->vrange.min &&
   5096 		    sid->version <= ss->clientHelloVersion) {
   5097 		    ss->version = ss->clientHelloVersion;
   5098 		} else {
   5099 		    sidOK = PR_FALSE;
   5100 		}
   5101 	    } else {
   5102 		if (ssl3_NegotiateVersion(ss, sid->version,
   5103 					  PR_FALSE) != SECSuccess) {
   5104 		    sidOK = PR_FALSE;
   5105 		}
   5106 	    }
   5107 	}
   5108 
   5109 	if (!sidOK) {
   5110 	    SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
   5111 	    if (ss->sec.uncache)
   5112                 (*ss->sec.uncache)(sid);
   5113 	    ssl_FreeSID(sid);
   5114 	    sid = NULL;
   5115 	}
   5116     }
   5117 
   5118     if (sid) {
   5119 	requestingResume = PR_TRUE;
   5120 	SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
   5121 
   5122 	/* Are we attempting a stateless session resume? */
   5123 	if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
   5124 	    sid->u.ssl3.sessionTicket.ticket.data)
   5125 	    SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
   5126 
   5127 	PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
   5128 		      sid->u.ssl3.sessionIDLength));
   5129 
   5130 	ss->ssl3.policy = sid->u.ssl3.policy;
   5131     } else {
   5132 	SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
   5133 
   5134 	/*
   5135 	 * Windows SChannel compares the client_version inside the RSA
   5136 	 * EncryptedPreMasterSecret of a renegotiation with the
   5137 	 * client_version of the initial ClientHello rather than the
   5138 	 * ClientHello in the renegotiation. To work around this bug, we
   5139 	 * continue to use the client_version used in the initial
   5140 	 * ClientHello when renegotiating.
   5141 	 */
   5142 	if (ss->firstHsDone) {
   5143 	    ss->version = ss->clientHelloVersion;
   5144 	} else {
   5145 	    rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
   5146 				       PR_TRUE);
   5147 	    if (rv != SECSuccess)
   5148 		return rv;	/* error code was set */
   5149 	}
   5150 
   5151 	sid = ssl3_NewSessionID(ss, PR_FALSE);
   5152 	if (!sid) {
   5153 	    return SECFailure;	/* memory error is set */
   5154         }
   5155     }
   5156 
   5157     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
   5158     ssl_GetSpecWriteLock(ss);
   5159     cwSpec = ss->ssl3.cwSpec;
   5160     if (cwSpec->mac_def->mac == mac_null) {
   5161 	/* SSL records are not being MACed. */
   5162 	cwSpec->version = ss->version;
   5163     }
   5164     ssl_ReleaseSpecWriteLock(ss);
   5165 
   5166     if (ss->sec.ci.sid != NULL) {
   5167 	ssl_FreeSID(ss->sec.ci.sid);	/* decrement ref count, free if zero */
   5168     }
   5169     ss->sec.ci.sid = sid;
   5170 
   5171     ss->sec.send = ssl3_SendApplicationData;
   5172 
   5173     /* shouldn't get here if SSL3 is disabled, but ... */
   5174     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
   5175 	PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
   5176 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
   5177     	return SECFailure;
   5178     }
   5179 
   5180     /* how many suites does our PKCS11 support (regardless of policy)? */
   5181     num_suites = ssl3_config_match_init(ss);
   5182     if (!num_suites)
   5183     	return SECFailure;	/* ssl3_config_match_init has set error code. */
   5184 
   5185     /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
   5186      * only if TLS is disabled.
   5187      */
   5188     if (!ss->firstHsDone && !isTLS) {
   5189 	/* Must set this before calling Hello Extension Senders,
   5190 	 * to suppress sending of empty RI extension.
   5191 	 */
   5192 	ss->ssl3.hs.sendingSCSV = PR_TRUE;
   5193     }
   5194 
   5195     if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
   5196 	PRUint32 maxBytes = 65535; /* 2^16 - 1 */
   5197 	PRInt32  extLen;
   5198 
   5199 	extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
   5200 	if (extLen < 0) {
   5201 	    return SECFailure;
   5202 	}
   5203 	maxBytes        -= extLen;
   5204 	total_exten_len += extLen;
   5205 
   5206 	if (total_exten_len > 0)
   5207 	    total_exten_len += 2;
   5208     }
   5209 
   5210 #if defined(NSS_ENABLE_ECC)
   5211     if (!total_exten_len || !isTLS) {
   5212 	/* not sending the elliptic_curves and ec_point_formats extensions */
   5213     	ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
   5214     }
   5215 #endif
   5216 
   5217     if (IS_DTLS(ss)) {
   5218 	ssl3_DisableNonDTLSSuites(ss);
   5219     }
   5220 
   5221     if (!ssl3_HasGCMSupport()) {
   5222 	ssl3_DisableGCMSuites(ss);
   5223     }
   5224 
   5225     /* how many suites are permitted by policy and user preference? */
   5226     num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
   5227     if (!num_suites)
   5228     	return SECFailure;	/* count_cipher_suites has set error code. */
   5229 
   5230     fallbackSCSV = ss->opt.enableFallbackSCSV && (!requestingResume ||
   5231 						  ss->version < sid->version);
   5232     /* make room for SCSV */
   5233     if (ss->ssl3.hs.sendingSCSV) {
   5234 	++num_suites;
   5235     }
   5236     if (fallbackSCSV) {
   5237 	++num_suites;
   5238     }
   5239 
   5240     /* count compression methods */
   5241     numCompressionMethods = 0;
   5242     for (i = 0; i < compressionMethodsCount; i++) {
   5243 	if (compressionEnabled(ss, compressions[i]))
   5244 	    numCompressionMethods++;
   5245     }
   5246 
   5247     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
   5248 	1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
   5249 	2 + num_suites*sizeof(ssl3CipherSuite) +
   5250 	1 + numCompressionMethods + total_exten_len;
   5251     if (IS_DTLS(ss)) {
   5252 	length += 1 + ss->ssl3.hs.cookieLen;
   5253     }
   5254 
   5255     /* A padding extension may be included to ensure that the record containing
   5256      * the ClientHello doesn't have a length between 256 and 511 bytes
   5257      * (inclusive). Initial, ClientHello records with such lengths trigger bugs
   5258      * in F5 devices.
   5259      *
   5260      * This is not done for DTLS nor for renegotiation. */
   5261     if (!IS_DTLS(ss) && isTLS && !ss->firstHsDone) {
   5262         paddingExtensionLen = ssl3_CalculatePaddingExtensionLength(length);
   5263         total_exten_len += paddingExtensionLen;
   5264         length += paddingExtensionLen;
   5265     } else {
   5266         paddingExtensionLen = 0;
   5267     }
   5268 
   5269     rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
   5270     if (rv != SECSuccess) {
   5271 	return rv;	/* err set by ssl3_AppendHandshake* */
   5272     }
   5273 
   5274     if (ss->firstHsDone) {
   5275 	/* The client hello version must stay unchanged to work around
   5276 	 * the Windows SChannel bug described above. */
   5277 	PORT_Assert(ss->version == ss->clientHelloVersion);
   5278     }
   5279     ss->clientHelloVersion = ss->version;
   5280     if (IS_DTLS(ss)) {
   5281 	PRUint16 version;
   5282 
   5283 	version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
   5284 	rv = ssl3_AppendHandshakeNumber(ss, version, 2);
   5285     } else {
   5286 	rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
   5287     }
   5288     if (rv != SECSuccess) {
   5289 	return rv;	/* err set by ssl3_AppendHandshake* */
   5290     }
   5291 
   5292     if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
   5293 	rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
   5294 	if (rv != SECSuccess) {
   5295 	    return rv;	/* err set by GetNewRandom. */
   5296 	}
   5297     }
   5298     rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
   5299                               SSL3_RANDOM_LENGTH);
   5300     if (rv != SECSuccess) {
   5301 	return rv;	/* err set by ssl3_AppendHandshake* */
   5302     }
   5303 
   5304     if (sid)
   5305 	rv = ssl3_AppendHandshakeVariable(
   5306 	    ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
   5307     else
   5308 	rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
   5309     if (rv != SECSuccess) {
   5310 	return rv;	/* err set by ssl3_AppendHandshake* */
   5311     }
   5312 
   5313     if (IS_DTLS(ss)) {
   5314 	rv = ssl3_AppendHandshakeVariable(
   5315 	    ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
   5316 	if (rv != SECSuccess) {
   5317 	    return rv;	/* err set by ssl3_AppendHandshake* */
   5318 	}
   5319     }
   5320 
   5321     rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
   5322     if (rv != SECSuccess) {
   5323 	return rv;	/* err set by ssl3_AppendHandshake* */
   5324     }
   5325 
   5326     if (ss->ssl3.hs.sendingSCSV) {
   5327 	/* Add the actual SCSV */
   5328 	rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
   5329 					sizeof(ssl3CipherSuite));
   5330 	if (rv != SECSuccess) {
   5331 	    return rv;	/* err set by ssl3_AppendHandshake* */
   5332 	}
   5333 	actual_count++;
   5334     }
   5335     if (fallbackSCSV) {
   5336 	rv = ssl3_AppendHandshakeNumber(ss, TLS_FALLBACK_SCSV,
   5337 					sizeof(ssl3CipherSuite));
   5338 	if (rv != SECSuccess) {
   5339 	    return rv;	/* err set by ssl3_AppendHandshake* */
   5340 	}
   5341 	actual_count++;
   5342     }
   5343     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
   5344 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
   5345 	if (config_match(suite, ss->ssl3.policy, PR_TRUE, &ss->vrange)) {
   5346 	    actual_count++;
   5347 	    if (actual_count > num_suites) {
   5348 		/* set error card removal/insertion error */
   5349 		PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   5350 		return SECFailure;
   5351 	    }
   5352 	    rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
   5353 					    sizeof(ssl3CipherSuite));
   5354 	    if (rv != SECSuccess) {
   5355 		return rv;	/* err set by ssl3_AppendHandshake* */
   5356 	    }
   5357 	}
   5358     }
   5359 
   5360     /* if cards were removed or inserted between count_cipher_suites and
   5361      * generating our list, detect the error here rather than send it off to
   5362      * the server.. */
   5363     if (actual_count != num_suites) {
   5364 	/* Card removal/insertion error */
   5365 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   5366 	return SECFailure;
   5367     }
   5368 
   5369     rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
   5370     if (rv != SECSuccess) {
   5371 	return rv;	/* err set by ssl3_AppendHandshake* */
   5372     }
   5373     for (i = 0; i < compressionMethodsCount; i++) {
   5374 	if (!compressionEnabled(ss, compressions[i]))
   5375 	    continue;
   5376 	rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
   5377 	if (rv != SECSuccess) {
   5378 	    return rv;	/* err set by ssl3_AppendHandshake* */
   5379 	}
   5380     }
   5381 
   5382     if (total_exten_len) {
   5383 	PRUint32 maxBytes = total_exten_len - 2;
   5384 	PRInt32  extLen;
   5385 
   5386 	rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
   5387 	if (rv != SECSuccess) {
   5388 	    return rv;	/* err set by AppendHandshake. */
   5389 	}
   5390 
   5391 	extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
   5392 	if (extLen < 0) {
   5393 	    return SECFailure;
   5394 	}
   5395 	maxBytes -= extLen;
   5396 
   5397 	extLen = ssl3_AppendPaddingExtension(ss, paddingExtensionLen, maxBytes);
   5398 	if (extLen < 0) {
   5399 	    return SECFailure;
   5400 	}
   5401 	maxBytes -= extLen;
   5402 
   5403 	PORT_Assert(!maxBytes);
   5404     }
   5405     if (ss->ssl3.hs.sendingSCSV) {
   5406 	/* Since we sent the SCSV, pretend we sent empty RI extension. */
   5407 	TLSExtensionData *xtnData = &ss->xtnData;
   5408 	xtnData->advertised[xtnData->numAdvertised++] =
   5409 	    ssl_renegotiation_info_xtn;
   5410     }
   5411 
   5412     flags = 0;
   5413     if (!ss->firstHsDone && !IS_DTLS(ss)) {
   5414 	flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
   5415     }
   5416     rv = ssl3_FlushHandshake(ss, flags);
   5417     if (rv != SECSuccess) {
   5418 	return rv;	/* error code set by ssl3_FlushHandshake */
   5419     }
   5420 
   5421     ss->ssl3.hs.ws = wait_server_hello;
   5422     return rv;
   5423 }
   5424 
   5425 
   5426 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   5427  * ssl3 Hello Request.
   5428  * Caller must hold Handshake and RecvBuf locks.
   5429  */
   5430 static SECStatus
   5431 ssl3_HandleHelloRequest(sslSocket *ss)
   5432 {
   5433     sslSessionID *sid = ss->sec.ci.sid;
   5434     SECStatus     rv;
   5435 
   5436     SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
   5437 		SSL_GETPID(), ss->fd));
   5438 
   5439     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   5440     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   5441 
   5442     if (ss->ssl3.hs.ws == wait_server_hello)
   5443 	return SECSuccess;
   5444     if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
   5445 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   5446 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
   5447 	return SECFailure;
   5448     }
   5449     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
   5450 	ssl_GetXmitBufLock(ss);
   5451 	rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
   5452 	ssl_ReleaseXmitBufLock(ss);
   5453 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
   5454 	return SECFailure;
   5455     }
   5456 
   5457     if (sid) {
   5458 	if (ss->sec.uncache)
   5459             ss->sec.uncache(sid);
   5460 	ssl_FreeSID(sid);
   5461 	ss->sec.ci.sid = NULL;
   5462     }
   5463 
   5464     if (IS_DTLS(ss)) {
   5465 	dtls_RehandshakeCleanup(ss);
   5466     }
   5467 
   5468     ssl_GetXmitBufLock(ss);
   5469     rv = ssl3_SendClientHello(ss, PR_FALSE);
   5470     ssl_ReleaseXmitBufLock(ss);
   5471 
   5472     return rv;
   5473 }
   5474 
   5475 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
   5476 
   5477 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
   5478     CKM_DES3_ECB,
   5479     CKM_CAST5_ECB,
   5480     CKM_DES_ECB,
   5481     CKM_KEY_WRAP_LYNKS,
   5482     CKM_IDEA_ECB,
   5483     CKM_CAST3_ECB,
   5484     CKM_CAST_ECB,
   5485     CKM_RC5_ECB,
   5486     CKM_RC2_ECB,
   5487     CKM_CDMF_ECB,
   5488     CKM_SKIPJACK_WRAP,
   5489     CKM_SKIPJACK_CBC64,
   5490     CKM_AES_ECB,
   5491     CKM_CAMELLIA_ECB,
   5492     CKM_SEED_ECB,
   5493     UNKNOWN_WRAP_MECHANISM
   5494 };
   5495 
   5496 static int
   5497 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
   5498 {
   5499     const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
   5500 
   5501     while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
   5502     	++pMech;
   5503     }
   5504     return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
   5505                                               : (pMech - wrapMechanismList);
   5506 }
   5507 
   5508 static PK11SymKey *
   5509 ssl_UnwrapSymWrappingKey(
   5510 	SSLWrappedSymWrappingKey *pWswk,
   5511 	SECKEYPrivateKey *        svrPrivKey,
   5512 	SSL3KEAType               exchKeyType,
   5513 	CK_MECHANISM_TYPE         masterWrapMech,
   5514 	void *                    pwArg)
   5515 {
   5516     PK11SymKey *             unwrappedWrappingKey  = NULL;
   5517     SECItem                  wrappedKey;
   5518 #ifdef NSS_ENABLE_ECC
   5519     PK11SymKey *             Ks;
   5520     SECKEYPublicKey          pubWrapKey;
   5521     ECCWrappedKeyInfo        *ecWrapped;
   5522 #endif /* NSS_ENABLE_ECC */
   5523 
   5524     /* found the wrapping key on disk. */
   5525     PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
   5526     PORT_Assert(pWswk->exchKeyType      == exchKeyType);
   5527     if (pWswk->symWrapMechanism != masterWrapMech ||
   5528 	pWswk->exchKeyType      != exchKeyType) {
   5529 	goto loser;
   5530     }
   5531     wrappedKey.type = siBuffer;
   5532     wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
   5533     wrappedKey.len  = pWswk->wrappedSymKeyLen;
   5534     PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
   5535 
   5536     switch (exchKeyType) {
   5537 
   5538     case kt_rsa:
   5539 	unwrappedWrappingKey =
   5540 	    PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
   5541 				 masterWrapMech, CKA_UNWRAP, 0);
   5542 	break;
   5543 
   5544 #ifdef NSS_ENABLE_ECC
   5545     case kt_ecdh:
   5546         /*
   5547          * For kt_ecdh, we first create an EC public key based on
   5548          * data stored with the wrappedSymmetricWrappingkey. Next,
   5549          * we do an ECDH computation involving this public key and
   5550          * the SSL server's (long-term) EC private key. The resulting
   5551          * shared secret is treated the same way as Fortezza's Ks, i.e.,
   5552          * it is used to recover the symmetric wrapping key.
   5553          *
   5554          * The data in wrappedSymmetricWrappingkey is laid out as defined
   5555          * in the ECCWrappedKeyInfo structure.
   5556          */
   5557         ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
   5558 
   5559         PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
   5560             ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
   5561 
   5562         if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
   5563             ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
   5564             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   5565             goto loser;
   5566         }
   5567 
   5568         pubWrapKey.keyType = ecKey;
   5569         pubWrapKey.u.ec.size = ecWrapped->size;
   5570         pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
   5571         pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
   5572         pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
   5573         pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
   5574             ecWrapped->encodedParamLen;
   5575 
   5576         wrappedKey.len  = ecWrapped->wrappedKeyLen;
   5577         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
   5578             ecWrapped->pubValueLen;
   5579 
   5580         /* Derive Ks using ECDH */
   5581         Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
   5582 				   NULL, CKM_ECDH1_DERIVE, masterWrapMech,
   5583 				   CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
   5584         if (Ks == NULL) {
   5585             goto loser;
   5586         }
   5587 
   5588         /*  Use Ks to unwrap the wrapping key */
   5589         unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
   5590 						 &wrappedKey, masterWrapMech,
   5591 						 CKA_UNWRAP, 0);
   5592         PK11_FreeSymKey(Ks);
   5593 
   5594         break;
   5595 #endif
   5596 
   5597     default:
   5598 	/* Assert? */
   5599 	SET_ERROR_CODE
   5600 	goto loser;
   5601     }
   5602 loser:
   5603     return unwrappedWrappingKey;
   5604 }
   5605 
   5606 /* Each process sharing the server session ID cache has its own array of
   5607  * SymKey pointers for the symmetric wrapping keys that are used to wrap
   5608  * the master secrets.  There is one key for each KEA type.  These Symkeys
   5609  * correspond to the wrapped SymKeys kept in the server session cache.
   5610  */
   5611 
   5612 typedef struct {
   5613     PK11SymKey *      symWrapKey[kt_kea_size];
   5614 } ssl3SymWrapKey;
   5615 
   5616 static PZLock *          symWrapKeysLock = NULL;
   5617 static ssl3SymWrapKey    symWrapKeys[SSL_NUM_WRAP_MECHS];
   5618 
   5619 SECStatus ssl_FreeSymWrapKeysLock(void)
   5620 {
   5621     if (symWrapKeysLock) {
   5622         PZ_DestroyLock(symWrapKeysLock);
   5623         symWrapKeysLock = NULL;
   5624         return SECSuccess;
   5625     }
   5626     PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   5627     return SECFailure;
   5628 }
   5629 
   5630 SECStatus
   5631 SSL3_ShutdownServerCache(void)
   5632 {
   5633     int             i, j;
   5634 
   5635     if (!symWrapKeysLock)
   5636     	return SECSuccess;	/* lock was never initialized */
   5637     PZ_Lock(symWrapKeysLock);
   5638     /* get rid of all symWrapKeys */
   5639     for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
   5640     	for (j = 0; j < kt_kea_size; ++j) {
   5641 	    PK11SymKey **   pSymWrapKey;
   5642 	    pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
   5643 	    if (*pSymWrapKey) {
   5644 		PK11_FreeSymKey(*pSymWrapKey);
   5645 	    	*pSymWrapKey = NULL;
   5646 	    }
   5647 	}
   5648     }
   5649 
   5650     PZ_Unlock(symWrapKeysLock);
   5651     return SECSuccess;
   5652 }
   5653 
   5654 SECStatus ssl_InitSymWrapKeysLock(void)
   5655 {
   5656     symWrapKeysLock = PZ_NewLock(nssILockOther);
   5657     return symWrapKeysLock ? SECSuccess : SECFailure;
   5658 }
   5659 
   5660 /* Try to get wrapping key for mechanism from in-memory array.
   5661  * If that fails, look for one on disk.
   5662  * If that fails, generate a new one, put the new one on disk,
   5663  * Put the new key in the in-memory array.
   5664  */
   5665 static PK11SymKey *
   5666 getWrappingKey( sslSocket *       ss,
   5667 		PK11SlotInfo *    masterSecretSlot,
   5668 		SSL3KEAType       exchKeyType,
   5669                 CK_MECHANISM_TYPE masterWrapMech,
   5670 	        void *            pwArg)
   5671 {
   5672     SECKEYPrivateKey *       svrPrivKey;
   5673     SECKEYPublicKey *        svrPubKey             = NULL;
   5674     PK11SymKey *             unwrappedWrappingKey  = NULL;
   5675     PK11SymKey **            pSymWrapKey;
   5676     CK_MECHANISM_TYPE        asymWrapMechanism = CKM_INVALID_MECHANISM;
   5677     int                      length;
   5678     int                      symWrapMechIndex;
   5679     SECStatus                rv;
   5680     SECItem                  wrappedKey;
   5681     SSLWrappedSymWrappingKey wswk;
   5682 #ifdef NSS_ENABLE_ECC
   5683     PK11SymKey *      Ks = NULL;
   5684     SECKEYPublicKey   *pubWrapKey = NULL;
   5685     SECKEYPrivateKey  *privWrapKey = NULL;
   5686     ECCWrappedKeyInfo *ecWrapped;
   5687 #endif /* NSS_ENABLE_ECC */
   5688 
   5689     svrPrivKey  = ss->serverCerts[exchKeyType].SERVERKEY;
   5690     PORT_Assert(svrPrivKey != NULL);
   5691     if (!svrPrivKey) {
   5692     	return NULL;	/* why are we here?!? */
   5693     }
   5694 
   5695     symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
   5696     PORT_Assert(symWrapMechIndex >= 0);
   5697     if (symWrapMechIndex < 0)
   5698     	return NULL;	/* invalid masterWrapMech. */
   5699 
   5700     pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
   5701 
   5702     ssl_InitSessionCacheLocks();
   5703 
   5704     PZ_Lock(symWrapKeysLock);
   5705 
   5706     unwrappedWrappingKey = *pSymWrapKey;
   5707     if (unwrappedWrappingKey != NULL) {
   5708 	if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
   5709 	    unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
   5710 	    goto done;
   5711 	}
   5712 	/* slot series has changed, so this key is no good any more. */
   5713 	PK11_FreeSymKey(unwrappedWrappingKey);
   5714 	*pSymWrapKey = unwrappedWrappingKey = NULL;
   5715     }
   5716 
   5717     /* Try to get wrapped SymWrapping key out of the (disk) cache. */
   5718     /* Following call fills in wswk on success. */
   5719     if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
   5720     	/* found the wrapped sym wrapping key on disk. */
   5721 	unwrappedWrappingKey =
   5722 	    ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
   5723                                      masterWrapMech, pwArg);
   5724 	if (unwrappedWrappingKey) {
   5725 	    goto install;
   5726 	}
   5727     }
   5728 
   5729     if (!masterSecretSlot) 	/* caller doesn't want to create a new one. */
   5730     	goto loser;
   5731 
   5732     length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
   5733     /* Zero length means fixed key length algorithm, or error.
   5734      * It's ambiguous.
   5735      */
   5736     unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
   5737                                        length, pwArg);
   5738     if (!unwrappedWrappingKey) {
   5739     	goto loser;
   5740     }
   5741 
   5742     /* Prepare the buffer to receive the wrappedWrappingKey,
   5743      * the symmetric wrapping key wrapped using the server's pub key.
   5744      */
   5745     PORT_Memset(&wswk, 0, sizeof wswk);	/* eliminate UMRs. */
   5746 
   5747     if (ss->serverCerts[exchKeyType].serverKeyPair) {
   5748 	svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
   5749     }
   5750     if (svrPubKey == NULL) {
   5751 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   5752 	goto loser;
   5753     }
   5754     wrappedKey.type = siBuffer;
   5755     wrappedKey.len  = SECKEY_PublicKeyStrength(svrPubKey);
   5756     wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
   5757 
   5758     PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
   5759     if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
   5760     	goto loser;
   5761 
   5762     /* wrap symmetric wrapping key in server's public key. */
   5763     switch (exchKeyType) {
   5764     case kt_rsa:
   5765 	asymWrapMechanism = CKM_RSA_PKCS;
   5766 	rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
   5767 	                        unwrappedWrappingKey, &wrappedKey);
   5768 	break;
   5769 
   5770 #ifdef NSS_ENABLE_ECC
   5771     case kt_ecdh:
   5772 	/*
   5773 	 * We generate an ephemeral EC key pair. Perform an ECDH
   5774 	 * computation involving this ephemeral EC public key and
   5775 	 * the SSL server's (long-term) EC private key. The resulting
   5776 	 * shared secret is treated in the same way as Fortezza's Ks,
   5777 	 * i.e., it is used to wrap the wrapping key. To facilitate
   5778 	 * unwrapping in ssl_UnwrapWrappingKey, we also store all
   5779 	 * relevant info about the ephemeral EC public key in
   5780 	 * wswk.wrappedSymmetricWrappingkey and lay it out as
   5781 	 * described in the ECCWrappedKeyInfo structure.
   5782 	 */
   5783 	PORT_Assert(svrPubKey->keyType == ecKey);
   5784 	if (svrPubKey->keyType != ecKey) {
   5785 	    /* something is wrong in sslsecur.c if this isn't an ecKey */
   5786 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   5787 	    rv = SECFailure;
   5788 	    goto ec_cleanup;
   5789 	}
   5790 
   5791 	privWrapKey = SECKEY_CreateECPrivateKey(
   5792 	    &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
   5793 	if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
   5794 	    rv = SECFailure;
   5795 	    goto ec_cleanup;
   5796 	}
   5797 
   5798 	/* Set the key size in bits */
   5799 	if (pubWrapKey->u.ec.size == 0) {
   5800 	    pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
   5801 	}
   5802 
   5803 	PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
   5804 	    pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
   5805 	if (pubWrapKey->u.ec.DEREncodedParams.len +
   5806 	    pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
   5807 	    PORT_SetError(SEC_ERROR_INVALID_KEY);
   5808 	    rv = SECFailure;
   5809 	    goto ec_cleanup;
   5810 	}
   5811 
   5812 	/* Derive Ks using ECDH */
   5813 	Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
   5814 				   NULL, CKM_ECDH1_DERIVE, masterWrapMech,
   5815 				   CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
   5816 	if (Ks == NULL) {
   5817 	    rv = SECFailure;
   5818 	    goto ec_cleanup;
   5819 	}
   5820 
   5821 	ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
   5822 	ecWrapped->size = pubWrapKey->u.ec.size;
   5823 	ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
   5824 	PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
   5825 	    pubWrapKey->u.ec.DEREncodedParams.len);
   5826 
   5827 	ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
   5828 	PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
   5829 		    pubWrapKey->u.ec.publicValue.data,
   5830 		    pubWrapKey->u.ec.publicValue.len);
   5831 
   5832 	wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
   5833 	    (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
   5834 	wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
   5835 	    ecWrapped->pubValueLen;
   5836 
   5837 	/* wrap symmetricWrapping key with the local Ks */
   5838 	rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
   5839 			     unwrappedWrappingKey, &wrappedKey);
   5840 
   5841 	if (rv != SECSuccess) {
   5842 	    goto ec_cleanup;
   5843 	}
   5844 
   5845 	/* Write down the length of wrapped key in the buffer
   5846 	 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
   5847 	 */
   5848 	ecWrapped->wrappedKeyLen = wrappedKey.len;
   5849 
   5850 ec_cleanup:
   5851 	if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
   5852 	if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
   5853 	if (Ks) PK11_FreeSymKey(Ks);
   5854 	asymWrapMechanism = masterWrapMech;
   5855 	break;
   5856 #endif /* NSS_ENABLE_ECC */
   5857 
   5858     default:
   5859 	rv = SECFailure;
   5860 	break;
   5861     }
   5862 
   5863     if (rv != SECSuccess) {
   5864 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5865 	goto loser;
   5866     }
   5867 
   5868     PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
   5869 
   5870     wswk.symWrapMechanism  = masterWrapMech;
   5871     wswk.symWrapMechIndex  = symWrapMechIndex;
   5872     wswk.asymWrapMechanism = asymWrapMechanism;
   5873     wswk.exchKeyType       = exchKeyType;
   5874     wswk.wrappedSymKeyLen  = wrappedKey.len;
   5875 
   5876     /* put it on disk. */
   5877     /* If the wrapping key for this KEA type has already been set,
   5878      * then abandon the value we just computed and
   5879      * use the one we got from the disk.
   5880      */
   5881     if (ssl_SetWrappingKey(&wswk)) {
   5882     	/* somebody beat us to it.  The original contents of our wswk
   5883 	 * has been replaced with the content on disk.  Now, discard
   5884 	 * the key we just created and unwrap this new one.
   5885 	 */
   5886     	PK11_FreeSymKey(unwrappedWrappingKey);
   5887 
   5888 	unwrappedWrappingKey =
   5889 	    ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
   5890                                      masterWrapMech, pwArg);
   5891     }
   5892 
   5893 install:
   5894     if (unwrappedWrappingKey) {
   5895 	*pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
   5896     }
   5897 
   5898 loser:
   5899 done:
   5900     PZ_Unlock(symWrapKeysLock);
   5901     return unwrappedWrappingKey;
   5902 }
   5903 
   5904 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
   5905  * bytes to |out|. */
   5906 static void
   5907 hexEncode(char *out, const unsigned char *in, unsigned int length)
   5908 {
   5909     static const char hextable[] = "0123456789abcdef";
   5910     unsigned int i;
   5911 
   5912     for (i = 0; i < length; i++) {
   5913 	*(out++) = hextable[in[i] >> 4];
   5914 	*(out++) = hextable[in[i] & 15];
   5915     }
   5916 }
   5917 
   5918 /* Called from ssl3_SendClientKeyExchange(). */
   5919 /* Presently, this always uses PKCS11.  There is no bypass for this. */
   5920 static SECStatus
   5921 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
   5922 {
   5923     PK11SymKey *	pms 		= NULL;
   5924     SECStatus           rv    		= SECFailure;
   5925     SECItem 		enc_pms 	= {siBuffer, NULL, 0};
   5926     PRBool              isTLS;
   5927 
   5928     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   5929     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   5930 
   5931     /* Generate the pre-master secret ...  */
   5932     ssl_GetSpecWriteLock(ss);
   5933     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   5934 
   5935     pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
   5936     ssl_ReleaseSpecWriteLock(ss);
   5937     if (pms == NULL) {
   5938 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5939 	goto loser;
   5940     }
   5941 
   5942     /* Get the wrapped (encrypted) pre-master secret, enc_pms */
   5943     enc_pms.len  = SECKEY_PublicKeyStrength(svrPubKey);
   5944     enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
   5945     if (enc_pms.data == NULL) {
   5946 	goto loser;	/* err set by PORT_Alloc */
   5947     }
   5948 
   5949     /* wrap pre-master secret in server's public key. */
   5950     rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
   5951     if (rv != SECSuccess) {
   5952 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5953 	goto loser;
   5954     }
   5955 
   5956     if (ssl_keylog_iob) {
   5957 	SECStatus extractRV = PK11_ExtractKeyValue(pms);
   5958 	if (extractRV == SECSuccess) {
   5959 	    SECItem * keyData = PK11_GetKeyData(pms);
   5960 	    if (keyData && keyData->data && keyData->len) {
   5961 #ifdef TRACE
   5962 		if (ssl_trace >= 100) {
   5963 		    ssl_PrintBuf(ss, "Pre-Master Secret",
   5964 				 keyData->data, keyData->len);
   5965 		}
   5966 #endif
   5967 		if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
   5968 		    /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
   5969 
   5970 		    /* There could be multiple, concurrent writers to the
   5971 		     * keylog, so we have to do everything in a single call to
   5972 		     * fwrite. */
   5973 		    char buf[4 + 8*2 + 1 + 48*2 + 1];
   5974 
   5975 		    strcpy(buf, "RSA ");
   5976 		    hexEncode(buf + 4, enc_pms.data, 8);
   5977 		    buf[20] = ' ';
   5978 		    hexEncode(buf + 21, keyData->data, 48);
   5979 		    buf[sizeof(buf) - 1] = '\n';
   5980 
   5981 		    fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
   5982 		    fflush(ssl_keylog_iob);
   5983 		}
   5984 	    }
   5985 	}
   5986     }
   5987 
   5988     rv = ssl3_InitPendingCipherSpec(ss,  pms);
   5989     PK11_FreeSymKey(pms); pms = NULL;
   5990 
   5991     if (rv != SECSuccess) {
   5992 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5993 	goto loser;
   5994     }
   5995 
   5996     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
   5997 				    isTLS ? enc_pms.len + 2 : enc_pms.len);
   5998     if (rv != SECSuccess) {
   5999 	goto loser;	/* err set by ssl3_AppendHandshake* */
   6000     }
   6001     if (isTLS) {
   6002     	rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
   6003     } else {
   6004 	rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
   6005     }
   6006     if (rv != SECSuccess) {
   6007 	goto loser;	/* err set by ssl3_AppendHandshake* */
   6008     }
   6009 
   6010     rv = SECSuccess;
   6011 
   6012 loser:
   6013     if (enc_pms.data != NULL) {
   6014 	PORT_Free(enc_pms.data);
   6015     }
   6016     if (pms != NULL) {
   6017     	PK11_FreeSymKey(pms);
   6018     }
   6019     return rv;
   6020 }
   6021 
   6022 /* Called from ssl3_SendClientKeyExchange(). */
   6023 /* Presently, this always uses PKCS11.  There is no bypass for this. */
   6024 static SECStatus
   6025 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
   6026 {
   6027     PK11SymKey *	pms 		= NULL;
   6028     SECStatus           rv    		= SECFailure;
   6029     PRBool              isTLS;
   6030     CK_MECHANISM_TYPE	target;
   6031 
   6032     SECKEYDHParams	dhParam;		/* DH parameters */
   6033     SECKEYPublicKey	*pubKey = NULL;		/* Ephemeral DH key */
   6034     SECKEYPrivateKey	*privKey = NULL;	/* Ephemeral DH key */
   6035 
   6036     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   6037     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   6038 
   6039     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   6040 
   6041     /* Copy DH parameters from server key */
   6042 
   6043     if (svrPubKey->keyType != dhKey) {
   6044 	PORT_SetError(SEC_ERROR_BAD_KEY);
   6045 	goto loser;
   6046     }
   6047     dhParam.prime.data = svrPubKey->u.dh.prime.data;
   6048     dhParam.prime.len = svrPubKey->u.dh.prime.len;
   6049     dhParam.base.data = svrPubKey->u.dh.base.data;
   6050     dhParam.base.len = svrPubKey->u.dh.base.len;
   6051 
   6052     /* Generate ephemeral DH keypair */
   6053     privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
   6054     if (!privKey || !pubKey) {
   6055 	    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
   6056 	    rv = SECFailure;
   6057 	    goto loser;
   6058     }
   6059     PRINT_BUF(50, (ss, "DH public value:",
   6060 					pubKey->u.dh.publicValue.data,
   6061 					pubKey->u.dh.publicValue.len));
   6062 
   6063     if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
   6064     else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
   6065 
   6066     /* Determine the PMS */
   6067 
   6068     pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
   6069 			    CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
   6070 
   6071     if (pms == NULL) {
   6072 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   6073 	goto loser;
   6074     }
   6075 
   6076     SECKEY_DestroyPrivateKey(privKey);
   6077     privKey = NULL;
   6078 
   6079     rv = ssl3_InitPendingCipherSpec(ss,  pms);
   6080     PK11_FreeSymKey(pms); pms = NULL;
   6081 
   6082     if (rv != SECSuccess) {
   6083 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   6084 	goto loser;
   6085     }
   6086 
   6087     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
   6088 					pubKey->u.dh.publicValue.len + 2);
   6089     if (rv != SECSuccess) {
   6090 	goto loser;	/* err set by ssl3_AppendHandshake* */
   6091     }
   6092     rv = ssl3_AppendHandshakeVariable(ss,
   6093 					pubKey->u.dh.publicValue.data,
   6094 					pubKey->u.dh.publicValue.len, 2);
   6095     SECKEY_DestroyPublicKey(pubKey);
   6096     pubKey = NULL;
   6097 
   6098     if (rv != SECSuccess) {
   6099 	goto loser;	/* err set by ssl3_AppendHandshake* */
   6100     }
   6101 
   6102     rv = SECSuccess;
   6103 
   6104 
   6105 loser:
   6106 
   6107     if(pms) PK11_FreeSymKey(pms);
   6108     if(privKey) SECKEY_DestroyPrivateKey(privKey);
   6109     if(pubKey) SECKEY_DestroyPublicKey(pubKey);
   6110     return rv;
   6111 }
   6112 
   6113 
   6114 
   6115 
   6116 
   6117 /* Called from ssl3_HandleServerHelloDone(). */
   6118 static SECStatus
   6119 ssl3_SendClientKeyExchange(sslSocket *ss)
   6120 {
   6121     SECKEYPublicKey *	serverKey 	= NULL;
   6122     SECStatus 		rv 		= SECFailure;
   6123     PRBool              isTLS;
   6124 
   6125     SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
   6126 		SSL_GETPID(), ss->fd));
   6127 
   6128     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   6129     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   6130 
   6131     if (ss->sec.peerKey == NULL) {
   6132 	serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
   6133 	if (serverKey == NULL) {
   6134 	    ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   6135 	    return SECFailure;
   6136 	}
   6137     } else {
   6138 	serverKey = ss->sec.peerKey;
   6139 	ss->sec.peerKey = NULL; /* we're done with it now */
   6140     }
   6141 
   6142     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   6143     /* enforce limits on kea key sizes. */
   6144     if (ss->ssl3.hs.kea_def->is_limited) {
   6145 	int keyLen = SECKEY_PublicKeyStrength(serverKey);	/* bytes */
   6146 
   6147 	if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
   6148 	    if (isTLS)
   6149 		(void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
   6150 	    else
   6151 		(void)ssl3_HandshakeFailure(ss);
   6152 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
   6153 	    goto loser;
   6154 	}
   6155     }
   6156 
   6157     ss->sec.keaType    = ss->ssl3.hs.kea_def->exchKeyType;
   6158     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
   6159 
   6160     switch (ss->ssl3.hs.kea_def->exchKeyType) {
   6161     case kt_rsa:
   6162 	rv = sendRSAClientKeyExchange(ss, serverKey);
   6163 	break;
   6164 
   6165     case kt_dh:
   6166 	rv = sendDHClientKeyExchange(ss, serverKey);
   6167 	break;
   6168 
   6169 #ifdef NSS_ENABLE_ECC
   6170     case kt_ecdh:
   6171 	rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
   6172 	break;
   6173 #endif /* NSS_ENABLE_ECC */
   6174 
   6175     default:
   6176 	/* got an unknown or unsupported Key Exchange Algorithm.  */
   6177 	SEND_ALERT
   6178 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   6179 	break;
   6180     }
   6181 
   6182     SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
   6183 		SSL_GETPID(), ss->fd));
   6184 
   6185 loser:
   6186     if (serverKey)
   6187     	SECKEY_DestroyPublicKey(serverKey);
   6188     return rv;	/* err code already set. */
   6189 }
   6190 
   6191 /* Called from ssl3_HandleServerHelloDone(). */
   6192 static SECStatus
   6193 ssl3_SendCertificateVerify(sslSocket *ss)
   6194 {
   6195     SECStatus     rv		= SECFailure;
   6196     PRBool        isTLS;
   6197     PRBool        isTLS12;
   6198     SECItem       buf           = {siBuffer, NULL, 0};
   6199     SSL3Hashes    hashes;
   6200     KeyType       keyType;
   6201     unsigned int  len;
   6202     SSL3SignatureAndHashAlgorithm sigAndHash;
   6203 
   6204     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   6205     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   6206 
   6207     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
   6208 		SSL_GETPID(), ss->fd));
   6209 
   6210     ssl_GetSpecReadLock(ss);
   6211     /* In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the handshake hash
   6212      * function (SHA-256). If the server or the client does not support SHA-256
   6213      * as a signature hash, we can either maintain a backup SHA-1 handshake
   6214      * hash or buffer all handshake messages.
   6215      */
   6216     if (ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) {
   6217 	rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes);
   6218 	PORT_Assert(ss->ssl3.hs.md5 == NULL);
   6219     } else {
   6220 	rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
   6221     }
   6222     ssl_ReleaseSpecReadLock(ss);
   6223     if (rv != SECSuccess) {
   6224 	goto done;	/* err code was set by ssl3_ComputeHandshakeHashes */
   6225     }
   6226 
   6227     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   6228     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   6229     if (ss->ssl3.platformClientKey) {
   6230 #ifdef NSS_PLATFORM_CLIENT_AUTH
   6231 	keyType = CERT_GetCertKeyType(
   6232 	    &ss->ssl3.clientCertificate->subjectPublicKeyInfo);
   6233 	rv = ssl3_PlatformSignHashes(
   6234 	    &hashes, ss->ssl3.platformClientKey, &buf, isTLS, keyType);
   6235 	ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   6236 	ss->ssl3.platformClientKey = (PlatformKey)NULL;
   6237 #endif /* NSS_PLATFORM_CLIENT_AUTH */
   6238     } else {
   6239 	keyType = ss->ssl3.clientPrivateKey->keyType;
   6240 	rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
   6241 	if (rv == SECSuccess) {
   6242 	    PK11SlotInfo * slot;
   6243 	    sslSessionID * sid   = ss->sec.ci.sid;
   6244 
   6245 	    /* Remember the info about the slot that did the signing.
   6246 	    ** Later, when doing an SSL restart handshake, verify this.
   6247 	    ** These calls are mere accessors, and can't fail.
   6248 	    */
   6249 	    slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
   6250 	    sid->u.ssl3.clAuthSeries     = PK11_GetSlotSeries(slot);
   6251 	    sid->u.ssl3.clAuthSlotID     = PK11_GetSlotID(slot);
   6252 	    sid->u.ssl3.clAuthModuleID   = PK11_GetModuleID(slot);
   6253 	    sid->u.ssl3.clAuthValid      = PR_TRUE;
   6254 	    PK11_FreeSlot(slot);
   6255 	}
   6256 	SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   6257 	ss->ssl3.clientPrivateKey = NULL;
   6258     }
   6259     if (rv != SECSuccess) {
   6260 	goto done;	/* err code was set by ssl3_SignHashes */
   6261     }
   6262 
   6263     len = buf.len + 2 + (isTLS12 ? 2 : 0);
   6264 
   6265     rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
   6266     if (rv != SECSuccess) {
   6267 	goto done;	/* error code set by AppendHandshake */
   6268     }
   6269     if (isTLS12) {
   6270 	rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
   6271 						  &sigAndHash.sigAlg);
   6272 	if (rv != SECSuccess) {
   6273 	    goto done;
   6274 	}
   6275 	sigAndHash.hashAlg = hashes.hashAlg;
   6276 
   6277 	rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
   6278 	if (rv != SECSuccess) {
   6279 	    goto done; 	/* err set by AppendHandshake. */
   6280 	}
   6281     }
   6282     rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
   6283     if (rv != SECSuccess) {
   6284 	goto done;	/* error code set by AppendHandshake */
   6285     }
   6286 
   6287 done:
   6288     if (buf.data)
   6289 	PORT_Free(buf.data);
   6290     return rv;
   6291 }
   6292 
   6293 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   6294  * ssl3 ServerHello message.
   6295  * Caller must hold Handshake and RecvBuf locks.
   6296  */
   6297 static SECStatus
   6298 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   6299 {
   6300     sslSessionID *sid		= ss->sec.ci.sid;
   6301     PRInt32       temp;		/* allow for consume number failure */
   6302     PRBool        suite_found   = PR_FALSE;
   6303     int           i;
   6304     int           errCode	= SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
   6305     SECStatus     rv;
   6306     SECItem       sidBytes 	= {siBuffer, NULL, 0};
   6307     PRBool        sid_match;
   6308     PRBool        isTLS		= PR_FALSE;
   6309     SSL3AlertDescription desc   = illegal_parameter;
   6310     SSL3ProtocolVersion version;
   6311 
   6312     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
   6313     	SSL_GETPID(), ss->fd));
   6314     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   6315     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   6316     PORT_Assert( ss->ssl3.initialized );
   6317 
   6318     if (ss->ssl3.hs.ws != wait_server_hello) {
   6319         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
   6320 	desc    = unexpected_message;
   6321 	goto alert_loser;
   6322     }
   6323 
   6324     /* clean up anything left from previous handshake. */
   6325     if (ss->ssl3.clientCertChain != NULL) {
   6326        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
   6327        ss->ssl3.clientCertChain = NULL;
   6328     }
   6329     if (ss->ssl3.clientCertificate != NULL) {
   6330        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   6331        ss->ssl3.clientCertificate = NULL;
   6332     }
   6333     if (ss->ssl3.clientPrivateKey != NULL) {
   6334        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   6335        ss->ssl3.clientPrivateKey = NULL;
   6336     }
   6337 #ifdef NSS_PLATFORM_CLIENT_AUTH
   6338     if (ss->ssl3.platformClientKey) {
   6339        ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   6340        ss->ssl3.platformClientKey = (PlatformKey)NULL;
   6341     }
   6342 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
   6343 
   6344     if (ss->ssl3.channelID != NULL) {
   6345 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   6346 	ss->ssl3.channelID = NULL;
   6347     }
   6348     if (ss->ssl3.channelIDPub != NULL) {
   6349 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   6350 	ss->ssl3.channelIDPub = NULL;
   6351     }
   6352 
   6353     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   6354     if (temp < 0) {
   6355     	goto loser; 	/* alert has been sent */
   6356     }
   6357     version = (SSL3ProtocolVersion)temp;
   6358 
   6359     if (IS_DTLS(ss)) {
   6360 	/* RFC 4347 required that you verify that the server versions
   6361 	 * match (Section 4.2.1) in the HelloVerifyRequest and the
   6362 	 * ServerHello.
   6363 	 *
   6364 	 * RFC 6347 suggests (SHOULD) that servers always use 1.0
   6365 	 * in HelloVerifyRequest and allows the versions not to match,
   6366 	 * especially when 1.2 is being negotiated.
   6367 	 *
   6368 	 * Therefore we do not check for matching here.
   6369 	 */
   6370 	version = dtls_DTLSVersionToTLSVersion(version);
   6371 	if (version == 0) {  /* Insane version number */
   6372             goto alert_loser;
   6373 	}
   6374     }
   6375 
   6376     rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
   6377     if (rv != SECSuccess) {
   6378     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
   6379 						   : handshake_failure;
   6380 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   6381 	goto alert_loser;
   6382     }
   6383     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
   6384 
   6385     rv = ssl3_InitHandshakeHashes(ss);
   6386     if (rv != SECSuccess) {
   6387 	desc = internal_error;
   6388 	errCode = PORT_GetError();
   6389 	goto alert_loser;
   6390     }
   6391 
   6392     rv = ssl3_ConsumeHandshake(
   6393 	ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
   6394     if (rv != SECSuccess) {
   6395     	goto loser; 	/* alert has been sent */
   6396     }
   6397 
   6398     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
   6399     if (rv != SECSuccess) {
   6400     	goto loser; 	/* alert has been sent */
   6401     }
   6402     if (sidBytes.len > SSL3_SESSIONID_BYTES) {
   6403 	if (isTLS)
   6404 	    desc = decode_error;
   6405 	goto alert_loser;	/* malformed. */
   6406     }
   6407 
   6408     /* find selected cipher suite in our list. */
   6409     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   6410     if (temp < 0) {
   6411     	goto loser; 	/* alert has been sent */
   6412     }
   6413     ssl3_config_match_init(ss);
   6414     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
   6415 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
   6416 	if (temp == suite->cipher_suite) {
   6417 	    SSLVersionRange vrange = {ss->version, ss->version};
   6418 	    if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
   6419 		/* config_match already checks whether the cipher suite is
   6420 		 * acceptable for the version, but the check is repeated here
   6421 		 * in order to give a more precise error code. */
   6422 		if (!ssl3_CipherSuiteAllowedForVersionRange(temp, &vrange)) {
   6423 		    desc    = handshake_failure;
   6424 		    errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
   6425 		    goto alert_loser;
   6426 		}
   6427 
   6428 		break;	/* failure */
   6429 	    }
   6430 
   6431 	    suite_found = PR_TRUE;
   6432 	    break;	/* success */
   6433 	}
   6434     }
   6435     if (!suite_found) {
   6436     	desc    = handshake_failure;
   6437 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   6438 	goto alert_loser;
   6439     }
   6440     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
   6441     ss->ssl3.hs.suite_def    = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
   6442     PORT_Assert(ss->ssl3.hs.suite_def);
   6443     if (!ss->ssl3.hs.suite_def) {
   6444     	PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
   6445 	goto loser;	/* we don't send alerts for our screw-ups. */
   6446     }
   6447 
   6448     /* find selected compression method in our list. */
   6449     temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
   6450     if (temp < 0) {
   6451     	goto loser; 	/* alert has been sent */
   6452     }
   6453     suite_found = PR_FALSE;
   6454     for (i = 0; i < compressionMethodsCount; i++) {
   6455 	if (temp == compressions[i]) {
   6456 	    if (!compressionEnabled(ss, compressions[i])) {
   6457 		break;	/* failure */
   6458 	    }
   6459 	    suite_found = PR_TRUE;
   6460 	    break;	/* success */
   6461     	}
   6462     }
   6463     if (!suite_found) {
   6464     	desc    = handshake_failure;
   6465 	errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
   6466 	goto alert_loser;
   6467     }
   6468     ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
   6469 
   6470     /* Note that if !isTLS and the extra stuff is not extensions, we
   6471      * do NOT goto alert_loser.
   6472      * There are some old SSL 3.0 implementations that do send stuff
   6473      * after the end of the server hello, and we deliberately ignore
   6474      * such stuff in the interest of maximal interoperability (being
   6475      * "generous in what you accept").
   6476      * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
   6477      * extension in SSL 3.0.
   6478      */
   6479     if (length != 0) {
   6480 	SECItem extensions;
   6481 	rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
   6482 	if (rv != SECSuccess || length != 0) {
   6483 	    if (isTLS)
   6484 		goto alert_loser;
   6485 	} else {
   6486 	    rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
   6487 					    &extensions.len);
   6488 	    if (rv != SECSuccess)
   6489 		goto alert_loser;
   6490 	}
   6491     }
   6492     if ((ss->opt.requireSafeNegotiation ||
   6493          (ss->firstHsDone && (ss->peerRequestedProtection ||
   6494 	 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
   6495 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   6496 	desc = handshake_failure;
   6497 	errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
   6498 	                          : SSL_ERROR_UNSAFE_NEGOTIATION;
   6499 	goto alert_loser;
   6500     }
   6501 
   6502     /* Any errors after this point are not "malformed" errors. */
   6503     desc    = handshake_failure;
   6504 
   6505     /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
   6506      * key exchange algorithm. */
   6507     rv = ssl3_SetupPendingCipherSpec(ss);
   6508     if (rv != SECSuccess) {
   6509 	goto alert_loser;	/* error code is set. */
   6510     }
   6511 
   6512     /* We may or may not have sent a session id, we may get one back or
   6513      * not and if so it may match the one we sent.
   6514      * Attempt to restore the master secret to see if this is so...
   6515      * Don't consider failure to find a matching SID an error.
   6516      */
   6517     sid_match = (PRBool)(sidBytes.len > 0 &&
   6518 	sidBytes.len == sid->u.ssl3.sessionIDLength &&
   6519 	!PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
   6520 
   6521     if (sid_match &&
   6522 	sid->version == ss->version &&
   6523 	sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
   6524 	ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
   6525 
   6526 	SECItem       wrappedMS;   /* wrapped master secret. */
   6527 
   6528 	ss->sec.authAlgorithm = sid->authAlgorithm;
   6529 	ss->sec.authKeyBits   = sid->authKeyBits;
   6530 	ss->sec.keaType       = sid->keaType;
   6531 	ss->sec.keaKeyBits    = sid->keaKeyBits;
   6532 
   6533 	/* 3 cases here:
   6534 	 * a) key is wrapped (implies using PKCS11)
   6535 	 * b) key is unwrapped, but we're still using PKCS11
   6536 	 * c) key is unwrapped, and we're bypassing PKCS11.
   6537 	 */
   6538 	if (sid->u.ssl3.keys.msIsWrapped) {
   6539 	    PK11SlotInfo *slot;
   6540 	    PK11SymKey *  wrapKey;     /* wrapping key */
   6541 	    CK_FLAGS      keyFlags      = 0;
   6542 
   6543 #ifndef NO_PKCS11_BYPASS
   6544 	    if (ss->opt.bypassPKCS11) {
   6545 		/* we cannot restart a non-bypass session in a
   6546 		** bypass socket.
   6547 		*/
   6548 		break;
   6549 	    }
   6550 #endif
   6551 	    /* unwrap master secret with PKCS11 */
   6552 	    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
   6553 				     sid->u.ssl3.masterSlotID);
   6554 	    if (slot == NULL) {
   6555 		break;		/* not considered an error. */
   6556 	    }
   6557 	    if (!PK11_IsPresent(slot)) {
   6558 		PK11_FreeSlot(slot);
   6559 		break;		/* not considered an error. */
   6560 	    }
   6561 	    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
   6562 				      sid->u.ssl3.masterWrapMech,
   6563 				      sid->u.ssl3.masterWrapSeries,
   6564 				      ss->pkcs11PinArg);
   6565 	    PK11_FreeSlot(slot);
   6566 	    if (wrapKey == NULL) {
   6567 		break;		/* not considered an error. */
   6568 	    }
   6569 
   6570 	    if (ss->version > SSL_LIBRARY_VERSION_3_0) {	/* isTLS */
   6571 		keyFlags = CKF_SIGN | CKF_VERIFY;
   6572 	    }
   6573 
   6574 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   6575 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   6576 	    pwSpec->master_secret =
   6577 		PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
   6578 			    NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
   6579 			    CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
   6580 	    errCode = PORT_GetError();
   6581 	    PK11_FreeSymKey(wrapKey);
   6582 	    if (pwSpec->master_secret == NULL) {
   6583 		break;	/* errorCode set just after call to UnwrapSymKey. */
   6584 	    }
   6585 #ifndef NO_PKCS11_BYPASS
   6586 	} else if (ss->opt.bypassPKCS11) {
   6587 	    /* MS is not wrapped */
   6588 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   6589 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   6590 	    memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
   6591 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   6592 	    pwSpec->msItem.len  = wrappedMS.len;
   6593 #endif
   6594 	} else {
   6595 	    /* We CAN restart a bypass session in a non-bypass socket. */
   6596 	    /* need to import the raw master secret to session object */
   6597 	    PK11SlotInfo *slot = PK11_GetInternalSlot();
   6598 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   6599 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   6600 	    pwSpec->master_secret =
   6601 		PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
   6602 				  PK11_OriginUnwrap, CKA_ENCRYPT,
   6603 				  &wrappedMS, NULL);
   6604 	    PK11_FreeSlot(slot);
   6605 	    if (pwSpec->master_secret == NULL) {
   6606 		break;
   6607 	    }
   6608 	}
   6609 
   6610 	/* Got a Match */
   6611 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
   6612 
   6613 	/* If we sent a session ticket, then this is a stateless resume. */
   6614 	if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
   6615 	    sid->u.ssl3.sessionTicket.ticket.data != NULL)
   6616 	    SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
   6617 
   6618 	if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
   6619 	    ss->ssl3.hs.ws = wait_new_session_ticket;
   6620 	else
   6621 	    ss->ssl3.hs.ws = wait_change_cipher;
   6622 
   6623 	ss->ssl3.hs.isResuming = PR_TRUE;
   6624 
   6625 	/* copy the peer cert from the SID */
   6626 	if (sid->peerCert != NULL) {
   6627 	    ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
   6628 	    ssl3_CopyPeerCertsFromSID(ss, sid);
   6629 	}
   6630 
   6631 	/* NULL value for PMS signifies re-use of the old MS */
   6632 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
   6633 	if (rv != SECSuccess) {
   6634 	    goto alert_loser;	/* err code was set */
   6635 	}
   6636 	goto winner;
   6637     } while (0);
   6638 
   6639     if (sid_match)
   6640 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
   6641     else
   6642 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
   6643 
   6644     /* throw the old one away */
   6645     sid->u.ssl3.keys.resumable = PR_FALSE;
   6646     if (ss->sec.uncache)
   6647         (*ss->sec.uncache)(sid);
   6648     ssl_FreeSID(sid);
   6649 
   6650     /* get a new sid */
   6651     ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
   6652     if (sid == NULL) {
   6653 	goto alert_loser;	/* memory error is set. */
   6654     }
   6655 
   6656     sid->version = ss->version;
   6657     sid->u.ssl3.sessionIDLength = sidBytes.len;
   6658     PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
   6659 
   6660     /* Copy Signed Certificate Timestamps, if any. */
   6661     if (ss->xtnData.signedCertTimestamps.data) {
   6662 	rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.signedCertTimestamps,
   6663 			      &ss->xtnData.signedCertTimestamps);
   6664 	if (rv != SECSuccess)
   6665 	    goto loser;
   6666     }
   6667 
   6668     ss->ssl3.hs.isResuming = PR_FALSE;
   6669     ss->ssl3.hs.ws         = wait_server_cert;
   6670 
   6671 winner:
   6672     /* Clean up the temporary pointer to the handshake buffer. */
   6673     ss->xtnData.signedCertTimestamps.data = NULL;
   6674     ss->xtnData.signedCertTimestamps.len = 0;
   6675 
   6676     /* If we will need a ChannelID key then we make the callback now. This
   6677      * allows the handshake to be restarted cleanly if the callback returns
   6678      * SECWouldBlock. */
   6679     if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
   6680 	rv = ss->getChannelID(ss->getChannelIDArg, ss->fd,
   6681 			      &ss->ssl3.channelIDPub, &ss->ssl3.channelID);
   6682 	if (rv == SECWouldBlock) {
   6683 	    ssl3_SetAlwaysBlock(ss);
   6684 	    return rv;
   6685 	}
   6686 	if (rv != SECSuccess ||
   6687 	    ss->ssl3.channelIDPub == NULL ||
   6688 	    ss->ssl3.channelID == NULL) {
   6689 	    PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED);
   6690 	    desc = internal_error;
   6691 	    goto alert_loser;
   6692 	}
   6693     }
   6694 
   6695     return SECSuccess;
   6696 
   6697 alert_loser:
   6698     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   6699 
   6700 loser:
   6701     /* Clean up the temporary pointer to the handshake buffer. */
   6702     ss->xtnData.signedCertTimestamps.data = NULL;
   6703     ss->xtnData.signedCertTimestamps.len = 0;
   6704     errCode = ssl_MapLowLevelError(errCode);
   6705     return SECFailure;
   6706 }
   6707 
   6708 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
   6709  * big-endian integer is > 1 */
   6710 static PRBool
   6711 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
   6712     unsigned char firstNonZeroByte = 0;
   6713     unsigned int i;
   6714 
   6715     for (i = 0; i < mpint->len; i++) {
   6716 	if (mpint->data[i]) {
   6717 	    firstNonZeroByte = mpint->data[i];
   6718 	    break;
   6719 	}
   6720     }
   6721 
   6722     if (firstNonZeroByte == 0)
   6723 	return PR_FALSE;
   6724     if (firstNonZeroByte > 1)
   6725 	return PR_TRUE;
   6726 
   6727     /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
   6728      * is followed by another byte. */
   6729     return (i < mpint->len - 1);
   6730 }
   6731 
   6732 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   6733  * ssl3 ServerKeyExchange message.
   6734  * Caller must hold Handshake and RecvBuf locks.
   6735  */
   6736 static SECStatus
   6737 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   6738 {
   6739     PLArenaPool *    arena     = NULL;
   6740     SECKEYPublicKey *peerKey   = NULL;
   6741     PRBool           isTLS, isTLS12;
   6742     SECStatus        rv;
   6743     int              errCode   = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
   6744     SSL3AlertDescription desc  = illegal_parameter;
   6745     SSL3Hashes       hashes;
   6746     SECItem          signature = {siBuffer, NULL, 0};
   6747     SSL3SignatureAndHashAlgorithm sigAndHash;
   6748 
   6749     sigAndHash.hashAlg = SEC_OID_UNKNOWN;
   6750 
   6751     SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
   6752 		SSL_GETPID(), ss->fd));
   6753     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   6754     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   6755 
   6756     if (ss->ssl3.hs.ws != wait_server_key &&
   6757 	ss->ssl3.hs.ws != wait_server_cert) {
   6758 	errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
   6759 	desc    = unexpected_message;
   6760 	goto alert_loser;
   6761     }
   6762     if (ss->sec.peerCert == NULL) {
   6763 	errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
   6764 	desc    = unexpected_message;
   6765 	goto alert_loser;
   6766     }
   6767 
   6768     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   6769     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   6770 
   6771     switch (ss->ssl3.hs.kea_def->exchKeyType) {
   6772 
   6773     case kt_rsa: {
   6774 	SECItem          modulus   = {siBuffer, NULL, 0};
   6775 	SECItem          exponent  = {siBuffer, NULL, 0};
   6776 
   6777     	rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
   6778     	if (rv != SECSuccess) {
   6779 	    goto loser;		/* malformed. */
   6780 	}
   6781     	rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
   6782     	if (rv != SECSuccess) {
   6783 	    goto loser;		/* malformed. */
   6784 	}
   6785 	if (isTLS12) {
   6786 	    rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
   6787 						       &sigAndHash);
   6788 	    if (rv != SECSuccess) {
   6789 		goto loser;	/* malformed or unsupported. */
   6790 	    }
   6791 	    rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
   6792 		    &sigAndHash, ss->sec.peerCert);
   6793 	    if (rv != SECSuccess) {
   6794 		goto loser;
   6795 	    }
   6796 	}
   6797     	rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
   6798     	if (rv != SECSuccess) {
   6799 	    goto loser;		/* malformed. */
   6800 	}
   6801     	if (length != 0) {
   6802 	    if (isTLS)
   6803 		desc = decode_error;
   6804 	    goto alert_loser;		/* malformed. */
   6805 	}
   6806 
   6807 	/* failures after this point are not malformed handshakes. */
   6808 	/* TLS: send decrypt_error if signature failed. */
   6809     	desc = isTLS ? decrypt_error : handshake_failure;
   6810 
   6811     	/*
   6812      	 *  check to make sure the hash is signed by right guy
   6813      	 */
   6814 	rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent,
   6815 					  &ss->ssl3.hs.client_random,
   6816 					  &ss->ssl3.hs.server_random,
   6817 					  &hashes, ss->opt.bypassPKCS11);
   6818         if (rv != SECSuccess) {
   6819 	    errCode =
   6820 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6821 	    goto alert_loser;
   6822 	}
   6823         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
   6824 				    isTLS, ss->pkcs11PinArg);
   6825 	if (rv != SECSuccess)  {
   6826 	    errCode =
   6827 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6828 	    goto alert_loser;
   6829 	}
   6830 
   6831 	/*
   6832 	 * we really need to build a new key here because we can no longer
   6833 	 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
   6834 	 * pkcs11 slots and ID's.
   6835 	 */
   6836     	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   6837 	if (arena == NULL) {
   6838 	    goto no_memory;
   6839 	}
   6840 
   6841     	peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
   6842     	if (peerKey == NULL) {
   6843             PORT_FreeArena(arena, PR_FALSE);
   6844 	    goto no_memory;
   6845 	}
   6846 
   6847 	peerKey->arena              = arena;
   6848 	peerKey->keyType            = rsaKey;
   6849 	peerKey->pkcs11Slot         = NULL;
   6850 	peerKey->pkcs11ID           = CK_INVALID_HANDLE;
   6851 	if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus,        &modulus) ||
   6852 	    SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
   6853 	{
   6854             PORT_FreeArena(arena, PR_FALSE);
   6855 	    goto no_memory;
   6856         }
   6857     	ss->sec.peerKey = peerKey;
   6858     	ss->ssl3.hs.ws = wait_cert_request;
   6859     	return SECSuccess;
   6860     }
   6861 
   6862     case kt_dh: {
   6863 	SECItem          dh_p      = {siBuffer, NULL, 0};
   6864 	SECItem          dh_g      = {siBuffer, NULL, 0};
   6865 	SECItem          dh_Ys     = {siBuffer, NULL, 0};
   6866 
   6867     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
   6868     	if (rv != SECSuccess) {
   6869 	    goto loser;		/* malformed. */
   6870 	}
   6871 	if (dh_p.len < 512/8) {
   6872 	    errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
   6873 	    goto alert_loser;
   6874 	}
   6875     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
   6876     	if (rv != SECSuccess) {
   6877 	    goto loser;		/* malformed. */
   6878 	}
   6879 	if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
   6880 	    goto alert_loser;
   6881     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
   6882     	if (rv != SECSuccess) {
   6883 	    goto loser;		/* malformed. */
   6884 	}
   6885 	if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
   6886 	    goto alert_loser;
   6887 	if (isTLS12) {
   6888 	    rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
   6889 						       &sigAndHash);
   6890 	    if (rv != SECSuccess) {
   6891 		goto loser;	/* malformed or unsupported. */
   6892 	    }
   6893 	    rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
   6894 		    &sigAndHash, ss->sec.peerCert);
   6895 	    if (rv != SECSuccess) {
   6896 		goto loser;
   6897 	    }
   6898 	}
   6899     	rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
   6900     	if (rv != SECSuccess) {
   6901 	    goto loser;		/* malformed. */
   6902 	}
   6903     	if (length != 0) {
   6904 	    if (isTLS)
   6905 		desc = decode_error;
   6906 	    goto alert_loser;		/* malformed. */
   6907 	}
   6908 
   6909 	PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
   6910 	PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
   6911 	PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
   6912 
   6913 	/* failures after this point are not malformed handshakes. */
   6914 	/* TLS: send decrypt_error if signature failed. */
   6915     	desc = isTLS ? decrypt_error : handshake_failure;
   6916 
   6917     	/*
   6918      	 *  check to make sure the hash is signed by right guy
   6919      	 */
   6920 	rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
   6921 					  &ss->ssl3.hs.client_random,
   6922 					  &ss->ssl3.hs.server_random,
   6923 					  &hashes, ss->opt.bypassPKCS11);
   6924         if (rv != SECSuccess) {
   6925 	    errCode =
   6926 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6927 	    goto alert_loser;
   6928 	}
   6929         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
   6930 				    isTLS, ss->pkcs11PinArg);
   6931 	if (rv != SECSuccess)  {
   6932 	    errCode =
   6933 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6934 	    goto alert_loser;
   6935 	}
   6936 
   6937 	/*
   6938 	 * we really need to build a new key here because we can no longer
   6939 	 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
   6940 	 * pkcs11 slots and ID's.
   6941 	 */
   6942     	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   6943 	if (arena == NULL) {
   6944 	    goto no_memory;
   6945 	}
   6946 
   6947     	ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
   6948     	if (peerKey == NULL) {
   6949 	    goto no_memory;
   6950 	}
   6951 
   6952 	peerKey->arena              = arena;
   6953 	peerKey->keyType            = dhKey;
   6954 	peerKey->pkcs11Slot         = NULL;
   6955 	peerKey->pkcs11ID           = CK_INVALID_HANDLE;
   6956 
   6957 	if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime,        &dh_p) ||
   6958 	    SECITEM_CopyItem(arena, &peerKey->u.dh.base,         &dh_g) ||
   6959 	    SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue,  &dh_Ys))
   6960 	{
   6961             PORT_FreeArena(arena, PR_FALSE);
   6962 	    goto no_memory;
   6963         }
   6964     	ss->sec.peerKey = peerKey;
   6965     	ss->ssl3.hs.ws = wait_cert_request;
   6966     	return SECSuccess;
   6967     }
   6968 
   6969 #ifdef NSS_ENABLE_ECC
   6970     case kt_ecdh:
   6971 	rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
   6972 	return rv;
   6973 #endif /* NSS_ENABLE_ECC */
   6974 
   6975     default:
   6976     	desc    = handshake_failure;
   6977 	errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
   6978 	break;		/* goto alert_loser; */
   6979     }
   6980 
   6981 alert_loser:
   6982     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   6983 loser:
   6984     PORT_SetError( errCode );
   6985     return SECFailure;
   6986 
   6987 no_memory:	/* no-memory error has already been set. */
   6988     ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6989     return SECFailure;
   6990 }
   6991 
   6992 
   6993 /*
   6994  * Returns the TLS signature algorithm for the client authentication key and
   6995  * whether it is an RSA or DSA key that may be able to sign only SHA-1 hashes.
   6996  */
   6997 static SECStatus
   6998 ssl3_ExtractClientKeyInfo(sslSocket *ss,
   6999 			  TLSSignatureAlgorithm *sigAlg,
   7000 			  PRBool *preferSha1)
   7001 {
   7002     SECStatus rv = SECSuccess;
   7003     SECKEYPublicKey *pubk;
   7004 
   7005     pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
   7006     if (pubk == NULL) {
   7007 	rv = SECFailure;
   7008 	goto done;
   7009     }
   7010 
   7011     rv = ssl3_TLSSignatureAlgorithmForKeyType(pubk->keyType, sigAlg);
   7012     if (rv != SECSuccess) {
   7013 	goto done;
   7014     }
   7015 
   7016 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32)
   7017     /* If the key is in CAPI, assume conservatively that the CAPI service
   7018      * provider may be unable to sign SHA-256 hashes.
   7019      */
   7020     if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) {
   7021 	/* CAPI only supports RSA and DSA signatures, so we don't need to
   7022 	 * check the key type. */
   7023 	*preferSha1 = PR_TRUE;
   7024 	goto done;
   7025     }
   7026 #endif  /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */
   7027 
   7028     /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
   7029      * it may be unable to sign SHA-256 hashes. This is the case for older
   7030      * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
   7031      * older, DSA key size is at most 1024 bits and the hash function must
   7032      * be SHA-1.
   7033      */
   7034     if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) {
   7035 	*preferSha1 = SECKEY_PublicKeyStrength(pubk) <= 128;
   7036     } else {
   7037 	*preferSha1 = PR_FALSE;
   7038     }
   7039 
   7040   done:
   7041     if (pubk)
   7042 	SECKEY_DestroyPublicKey(pubk);
   7043     return rv;
   7044 }
   7045 
   7046 /* Destroys the backup handshake hash context if we don't need it. Note that
   7047  * this function selects the hash algorithm for client authentication
   7048  * signatures; ssl3_SendCertificateVerify uses the presence of the backup hash
   7049  * to determine whether to use SHA-1 or SHA-256. */
   7050 static void
   7051 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss,
   7052 					   const SECItem *algorithms)
   7053 {
   7054     SECStatus rv;
   7055     TLSSignatureAlgorithm sigAlg;
   7056     PRBool preferSha1;
   7057     PRBool supportsSha1 = PR_FALSE;
   7058     PRBool supportsSha256 = PR_FALSE;
   7059     PRBool needBackupHash = PR_FALSE;
   7060     unsigned int i;
   7061 
   7062     PORT_Assert(ss->ssl3.hs.md5);
   7063 
   7064     /* Determine the key's signature algorithm and whether it prefers SHA-1. */
   7065     rv = ssl3_ExtractClientKeyInfo(ss, &sigAlg, &preferSha1);
   7066     if (rv != SECSuccess) {
   7067 	goto done;
   7068     }
   7069 
   7070     /* Determine the server's hash support for that signature algorithm. */
   7071     for (i = 0; i < algorithms->len; i += 2) {
   7072 	if (algorithms->data[i+1] == sigAlg) {
   7073 	    if (algorithms->data[i] == tls_hash_sha1) {
   7074 		supportsSha1 = PR_TRUE;
   7075 	    } else if (algorithms->data[i] == tls_hash_sha256) {
   7076 		supportsSha256 = PR_TRUE;
   7077 	    }
   7078 	}
   7079     }
   7080 
   7081     /* If either the server does not support SHA-256 or the client key prefers
   7082      * SHA-1, leave the backup hash. */
   7083     if (supportsSha1 && (preferSha1 || !supportsSha256)) {
   7084 	needBackupHash = PR_TRUE;
   7085     }
   7086 
   7087 done:
   7088     if (!needBackupHash) {
   7089 	PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   7090 	ss->ssl3.hs.md5 = NULL;
   7091     }
   7092 }
   7093 
   7094 typedef struct dnameNode {
   7095     struct dnameNode *next;
   7096     SECItem           name;
   7097 } dnameNode;
   7098 
   7099 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   7100  * ssl3 Certificate Request message.
   7101  * Caller must hold Handshake and RecvBuf locks.
   7102  */
   7103 static SECStatus
   7104 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   7105 {
   7106     PLArenaPool *        arena       = NULL;
   7107     dnameNode *          node;
   7108     PRInt32              remaining;
   7109     PRBool               isTLS       = PR_FALSE;
   7110     PRBool               isTLS12     = PR_FALSE;
   7111     int                  i;
   7112     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
   7113     int                  nnames      = 0;
   7114     SECStatus            rv;
   7115     SSL3AlertDescription desc        = illegal_parameter;
   7116     SECItem              cert_types  = {siBuffer, NULL, 0};
   7117     SECItem              algorithms  = {siBuffer, NULL, 0};
   7118     CERTDistNames        ca_list;
   7119 #ifdef NSS_PLATFORM_CLIENT_AUTH
   7120     CERTCertList *       platform_cert_list = NULL;
   7121     CERTCertListNode *   certNode = NULL;
   7122 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
   7123 
   7124     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
   7125 		SSL_GETPID(), ss->fd));
   7126     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7127     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7128 
   7129     if (ss->ssl3.hs.ws != wait_cert_request &&
   7130     	ss->ssl3.hs.ws != wait_server_key) {
   7131 	desc    = unexpected_message;
   7132 	errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
   7133 	goto alert_loser;
   7134     }
   7135 
   7136     PORT_Assert(ss->ssl3.clientCertChain == NULL);
   7137     PORT_Assert(ss->ssl3.clientCertificate == NULL);
   7138     PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
   7139     PORT_Assert(ss->ssl3.platformClientKey == (PlatformKey)NULL);
   7140 
   7141     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   7142     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   7143     rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
   7144     if (rv != SECSuccess)
   7145     	goto loser;		/* malformed, alert has been sent */
   7146 
   7147     PORT_Assert(!ss->requestedCertTypes);
   7148     ss->requestedCertTypes = &cert_types;
   7149 
   7150     if (isTLS12) {
   7151 	rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
   7152 	if (rv != SECSuccess)
   7153 	    goto loser;		/* malformed, alert has been sent */
   7154 	/* An empty or odd-length value is invalid.
   7155 	 *    SignatureAndHashAlgorithm
   7156 	 *      supported_signature_algorithms<2..2^16-2>;
   7157 	 */
   7158 	if (algorithms.len == 0 || (algorithms.len & 1) != 0)
   7159 	    goto alert_loser;
   7160     }
   7161 
   7162     arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   7163     if (arena == NULL)
   7164     	goto no_mem;
   7165 
   7166     remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   7167     if (remaining < 0)
   7168     	goto loser;	 	/* malformed, alert has been sent */
   7169 
   7170     if ((PRUint32)remaining > length)
   7171 	goto alert_loser;
   7172 
   7173     ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
   7174     if (node == NULL)
   7175     	goto no_mem;
   7176 
   7177     while (remaining > 0) {
   7178 	PRInt32 len;
   7179 
   7180 	if (remaining < 2)
   7181 	    goto alert_loser;	/* malformed */
   7182 
   7183 	node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   7184 	if (len <= 0)
   7185 	    goto loser;		/* malformed, alert has been sent */
   7186 
   7187 	remaining -= 2;
   7188 	if (remaining < len)
   7189 	    goto alert_loser;	/* malformed */
   7190 
   7191 	node->name.data = b;
   7192 	b         += len;
   7193 	length    -= len;
   7194 	remaining -= len;
   7195 	nnames++;
   7196 	if (remaining <= 0)
   7197 	    break;		/* success */
   7198 
   7199 	node->next = PORT_ArenaZNew(arena, dnameNode);
   7200 	node = node->next;
   7201 	if (node == NULL)
   7202 	    goto no_mem;
   7203     }
   7204 
   7205     ca_list.nnames = nnames;
   7206     ca_list.names  = PORT_ArenaNewArray(arena, SECItem, nnames);
   7207     if (nnames > 0 && ca_list.names == NULL)
   7208         goto no_mem;
   7209 
   7210     for(i = 0, node = (dnameNode*)ca_list.head;
   7211 	i < nnames;
   7212 	i++, node = node->next) {
   7213 	ca_list.names[i] = node->name;
   7214     }
   7215 
   7216     if (length != 0)
   7217         goto alert_loser;   	/* malformed */
   7218 
   7219     desc = no_certificate;
   7220     ss->ssl3.hs.ws = wait_hello_done;
   7221 
   7222 #ifdef NSS_PLATFORM_CLIENT_AUTH
   7223     if (ss->getPlatformClientAuthData != NULL) {
   7224 	/* XXX Should pass cert_types and algorithms in this call!! */
   7225         rv = (SECStatus)(*ss->getPlatformClientAuthData)(
   7226                                         ss->getPlatformClientAuthDataArg,
   7227                                         ss->fd, &ca_list,
   7228                                         &platform_cert_list,
   7229                                         (void**)&ss->ssl3.platformClientKey,
   7230                                         &ss->ssl3.clientCertificate,
   7231                                         &ss->ssl3.clientPrivateKey);
   7232     } else
   7233 #endif
   7234     if (ss->getClientAuthData != NULL) {
   7235 	/* XXX Should pass cert_types and algorithms in this call!! */
   7236 	rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
   7237 						 ss->fd, &ca_list,
   7238 						 &ss->ssl3.clientCertificate,
   7239 						 &ss->ssl3.clientPrivateKey);
   7240     } else {
   7241 	rv = SECFailure; /* force it to send a no_certificate alert */
   7242     }
   7243 
   7244     switch (rv) {
   7245     case SECWouldBlock:	/* getClientAuthData has put up a dialog box. */
   7246 	ssl3_SetAlwaysBlock(ss);
   7247 	break;	/* not an error */
   7248 
   7249     case SECSuccess:
   7250 #ifdef NSS_PLATFORM_CLIENT_AUTH
   7251         if (!platform_cert_list || CERT_LIST_EMPTY(platform_cert_list) ||
   7252             !ss->ssl3.platformClientKey) {
   7253             if (platform_cert_list) {
   7254                 CERT_DestroyCertList(platform_cert_list);
   7255                 platform_cert_list = NULL;
   7256             }
   7257             if (ss->ssl3.platformClientKey) {
   7258                 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   7259                 ss->ssl3.platformClientKey = (PlatformKey)NULL;
   7260             }
   7261 	    /* Fall through to NSS client auth check */
   7262         } else {
   7263 	    certNode = CERT_LIST_HEAD(platform_cert_list);
   7264 	    ss->ssl3.clientCertificate = CERT_DupCertificate(certNode->cert);
   7265 
   7266 	    /* Setting ssl3.clientCertChain non-NULL will cause
   7267 	     * ssl3_HandleServerHelloDone to call SendCertificate.
   7268 	     * Note: clientCertChain should include the EE cert as
   7269 	     * clientCertificate is ignored during the actual sending
   7270 	     */
   7271 	    ss->ssl3.clientCertChain =
   7272 		    hack_NewCertificateListFromCertList(platform_cert_list);
   7273 	    CERT_DestroyCertList(platform_cert_list);
   7274 	    platform_cert_list = NULL;
   7275 	    if (ss->ssl3.clientCertChain == NULL) {
   7276 		if (ss->ssl3.clientCertificate != NULL) {
   7277 		    CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   7278 		    ss->ssl3.clientCertificate = NULL;
   7279 		}
   7280 		if (ss->ssl3.platformClientKey) {
   7281 		    ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   7282 		    ss->ssl3.platformClientKey = (PlatformKey)NULL;
   7283 		}
   7284 		goto send_no_certificate;
   7285 	    }
   7286 	    if (isTLS12) {
   7287 		ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
   7288 	    }
   7289 	    break;  /* not an error */
   7290 	}
   7291 #endif   /* NSS_PLATFORM_CLIENT_AUTH */
   7292         /* check what the callback function returned */
   7293         if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
   7294             /* we are missing either the key or cert */
   7295             if (ss->ssl3.clientCertificate) {
   7296                 /* got a cert, but no key - free it */
   7297                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   7298                 ss->ssl3.clientCertificate = NULL;
   7299             }
   7300             if (ss->ssl3.clientPrivateKey) {
   7301                 /* got a key, but no cert - free it */
   7302                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   7303                 ss->ssl3.clientPrivateKey = NULL;
   7304             }
   7305             goto send_no_certificate;
   7306         }
   7307 	/* Setting ssl3.clientCertChain non-NULL will cause
   7308 	 * ssl3_HandleServerHelloDone to call SendCertificate.
   7309 	 */
   7310 	ss->ssl3.clientCertChain = CERT_CertChainFromCert(
   7311 					ss->ssl3.clientCertificate,
   7312 					certUsageSSLClient, PR_FALSE);
   7313 	if (ss->ssl3.clientCertChain == NULL) {
   7314 	    if (ss->ssl3.clientCertificate != NULL) {
   7315 		CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   7316 		ss->ssl3.clientCertificate = NULL;
   7317 	    }
   7318 	    if (ss->ssl3.clientPrivateKey != NULL) {
   7319 		SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   7320 		ss->ssl3.clientPrivateKey = NULL;
   7321 	    }
   7322 	    goto send_no_certificate;
   7323 	}
   7324 	if (isTLS12) {
   7325 	    ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
   7326 	}
   7327 	break;	/* not an error */
   7328 
   7329     case SECFailure:
   7330     default:
   7331 send_no_certificate:
   7332 	if (isTLS) {
   7333 	    ss->ssl3.sendEmptyCert = PR_TRUE;
   7334 	} else {
   7335 	    (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
   7336 	}
   7337 	rv = SECSuccess;
   7338 	break;
   7339     }
   7340     goto done;
   7341 
   7342 no_mem:
   7343     rv = SECFailure;
   7344     PORT_SetError(SEC_ERROR_NO_MEMORY);
   7345     goto done;
   7346 
   7347 alert_loser:
   7348     if (isTLS && desc == illegal_parameter)
   7349     	desc = decode_error;
   7350     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   7351 loser:
   7352     PORT_SetError(errCode);
   7353     rv = SECFailure;
   7354 done:
   7355     ss->requestedCertTypes = NULL;
   7356     if (arena != NULL)
   7357     	PORT_FreeArena(arena, PR_FALSE);
   7358 #ifdef NSS_PLATFORM_CLIENT_AUTH
   7359     if (platform_cert_list)
   7360         CERT_DestroyCertList(platform_cert_list);
   7361 #endif
   7362     return rv;
   7363 }
   7364 
   7365 /*
   7366  * attempt to restart the handshake after asynchronously handling
   7367  * a request for the client's certificate.
   7368  *
   7369  * inputs:
   7370  *	cert	Client cert chosen by application.
   7371  *		Note: ssl takes this reference, and does not bump the
   7372  *		reference count.  The caller should drop its reference
   7373  *		without calling CERT_DestroyCert after calling this function.
   7374  *
   7375  *	key	Private key associated with cert.  This function takes
   7376  *		ownership of the private key, so the caller should drop its
   7377  *		reference without destroying the private key after this
   7378  *		function returns.
   7379  *
   7380  *	certChain  DER-encoded certs, client cert and its signers.
   7381  *		Note: ssl takes this reference, and does not copy the chain.
   7382  *		The caller should drop its reference without destroying the
   7383  *		chain.  SSL will free the chain when it is done with it.
   7384  *
   7385  * Return value: XXX
   7386  *
   7387  * XXX This code only works on the initial handshake on a connection, XXX
   7388  *     It does not work on a subsequent handshake (redo).
   7389  *
   7390  * Caller holds 1stHandshakeLock.
   7391  */
   7392 SECStatus
   7393 ssl3_RestartHandshakeAfterCertReq(sslSocket *         ss,
   7394 				CERTCertificate *    cert,
   7395 				SECKEYPrivateKey *   key,
   7396 				CERTCertificateList *certChain)
   7397 {
   7398     SECStatus        rv          = SECSuccess;
   7399 
   7400     /* XXX This code only works on the initial handshake on a connection,
   7401     ** XXX It does not work on a subsequent handshake (redo).
   7402     */
   7403     if (ss->handshake != 0) {
   7404 	ss->handshake              = ssl_GatherRecord1stHandshake;
   7405 	ss->ssl3.clientCertificate = cert;
   7406 	ss->ssl3.clientPrivateKey  = key;
   7407 	ss->ssl3.clientCertChain   = certChain;
   7408         if (!cert || !key || !certChain) {
   7409             /* we are missing the key, cert, or cert chain */
   7410             if (ss->ssl3.clientCertificate) {
   7411                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   7412                 ss->ssl3.clientCertificate = NULL;
   7413             }
   7414             if (ss->ssl3.clientPrivateKey) {
   7415                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   7416                 ss->ssl3.clientPrivateKey = NULL;
   7417             }
   7418             if (ss->ssl3.clientCertChain != NULL) {
   7419                 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
   7420                 ss->ssl3.clientCertChain = NULL;
   7421             }
   7422             if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) {
   7423                 ss->ssl3.sendEmptyCert = PR_TRUE;
   7424             } else {
   7425                 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
   7426             }
   7427 	}
   7428     } else {
   7429 	if (cert) {
   7430 	    CERT_DestroyCertificate(cert);
   7431 	}
   7432 	if (key) {
   7433 	    SECKEY_DestroyPrivateKey(key);
   7434 	}
   7435 	if (certChain) {
   7436 	    CERT_DestroyCertificateList(certChain);
   7437 	}
   7438 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   7439 	rv = SECFailure;
   7440     }
   7441     return rv;
   7442 }
   7443 
   7444 static SECStatus
   7445 ssl3_CheckFalseStart(sslSocket *ss)
   7446 {
   7447     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7448     PORT_Assert( !ss->ssl3.hs.authCertificatePending );
   7449     PORT_Assert( !ss->ssl3.hs.canFalseStart );
   7450 
   7451     if (!ss->canFalseStartCallback) {
   7452 	SSL_TRC(3, ("%d: SSL[%d]: no false start callback so no false start",
   7453 		    SSL_GETPID(), ss->fd));
   7454     } else {
   7455 	PRBool maybeFalseStart;
   7456 	SECStatus rv;
   7457 
   7458 	/* An attacker can control the selected ciphersuite so we only wish to
   7459 	 * do False Start in the case that the selected ciphersuite is
   7460 	 * sufficiently strong that the attack can gain no advantage.
   7461 	 * Therefore we always require an 80-bit cipher. */
   7462         ssl_GetSpecReadLock(ss);
   7463         maybeFalseStart = ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10;
   7464         ssl_ReleaseSpecReadLock(ss);
   7465 
   7466 	if (!maybeFalseStart) {
   7467 	    SSL_TRC(3, ("%d: SSL[%d]: no false start due to weak cipher",
   7468 			SSL_GETPID(), ss->fd));
   7469 	} else {
   7470 	    rv = (ss->canFalseStartCallback)(ss->fd,
   7471 					     ss->canFalseStartCallbackData,
   7472 					     &ss->ssl3.hs.canFalseStart);
   7473 	    if (rv == SECSuccess) {
   7474 		SSL_TRC(3, ("%d: SSL[%d]: false start callback returned %s",
   7475 			    SSL_GETPID(), ss->fd,
   7476 			    ss->ssl3.hs.canFalseStart ? "TRUE" : "FALSE"));
   7477 	    } else {
   7478 		SSL_TRC(3, ("%d: SSL[%d]: false start callback failed (%s)",
   7479 			    SSL_GETPID(), ss->fd,
   7480 			    PR_ErrorToName(PR_GetError())));
   7481 	    }
   7482 	    return rv;
   7483 	}
   7484     }
   7485 
   7486     ss->ssl3.hs.canFalseStart = PR_FALSE;
   7487     return SECSuccess;
   7488 }
   7489 
   7490 PRBool
   7491 ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss)
   7492 {
   7493     PRBool result;
   7494 
   7495     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7496 
   7497     switch (ss->ssl3.hs.ws) {
   7498     case wait_new_session_ticket:
   7499         result = PR_TRUE;
   7500         break;
   7501     case wait_change_cipher:
   7502         result = !ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn);
   7503         break;
   7504     default:
   7505         result = PR_FALSE;
   7506         break;
   7507     }
   7508 
   7509     return result;
   7510 }
   7511 
   7512 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
   7513 
   7514 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   7515  * ssl3 Server Hello Done message.
   7516  * Caller must hold Handshake and RecvBuf locks.
   7517  */
   7518 static SECStatus
   7519 ssl3_HandleServerHelloDone(sslSocket *ss)
   7520 {
   7521     SECStatus     rv;
   7522     SSL3WaitState ws          = ss->ssl3.hs.ws;
   7523 
   7524     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
   7525 		SSL_GETPID(), ss->fd));
   7526     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7527     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7528 
   7529     if (ws != wait_hello_done  &&
   7530         ws != wait_server_cert &&
   7531 	ws != wait_server_key  &&
   7532 	ws != wait_cert_request) {
   7533 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   7534 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
   7535 	return SECFailure;
   7536     }
   7537 
   7538     rv = ssl3_SendClientSecondRound(ss);
   7539 
   7540     return rv;
   7541 }
   7542 
   7543 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
   7544  *
   7545  * Caller must hold Handshake and RecvBuf locks.
   7546  */
   7547 static SECStatus
   7548 ssl3_SendClientSecondRound(sslSocket *ss)
   7549 {
   7550     SECStatus rv;
   7551     PRBool sendClientCert;
   7552 
   7553     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7554     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7555 
   7556     sendClientCert = !ss->ssl3.sendEmptyCert &&
   7557 		     ss->ssl3.clientCertChain  != NULL &&
   7558 		     (ss->ssl3.platformClientKey ||
   7559 		     ss->ssl3.clientPrivateKey != NULL);
   7560 
   7561     if (!sendClientCert &&
   7562 	ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) {
   7563 	/* Don't need the backup handshake hash. */
   7564 	PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   7565 	ss->ssl3.hs.md5 = NULL;
   7566     }
   7567 
   7568     /* We must wait for the server's certificate to be authenticated before
   7569      * sending the client certificate in order to disclosing the client
   7570      * certificate to an attacker that does not have a valid cert for the
   7571      * domain we are connecting to.
   7572      *
   7573      * XXX: We should do the same for the NPN extension, but for that we
   7574      * need an option to give the application the ability to leak the NPN
   7575      * information to get better performance.
   7576      *
   7577      * During the initial handshake on a connection, we never send/receive
   7578      * application data until we have authenticated the server's certificate;
   7579      * i.e. we have fully authenticated the handshake before using the cipher
   7580      * specs agreed upon for that handshake. During a renegotiation, we may
   7581      * continue sending and receiving application data during the handshake
   7582      * interleaved with the handshake records. If we were to send the client's
   7583      * second round for a renegotiation before the server's certificate was
   7584      * authenticated, then the application data sent/received after this point
   7585      * would be using cipher spec that hadn't been authenticated. By waiting
   7586      * until the server's certificate has been authenticated during
   7587      * renegotiations, we ensure that renegotiations have the same property
   7588      * as initial handshakes; i.e. we have fully authenticated the handshake
   7589      * before using the cipher specs agreed upon for that handshake for
   7590      * application data.
   7591      */
   7592     if (ss->ssl3.hs.restartTarget) {
   7593 	PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
   7594 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   7595 	return SECFailure;
   7596     }
   7597     if (ss->ssl3.hs.authCertificatePending &&
   7598 	(sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
   7599 	SSL_TRC(3, ("%d: SSL3[%p]: deferring ssl3_SendClientSecondRound because"
   7600 		    " certificate authentication is still pending.",
   7601 		    SSL_GETPID(), ss->fd));
   7602 	ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
   7603 	return SECWouldBlock;
   7604     }
   7605 
   7606     ssl_GetXmitBufLock(ss);		/*******************************/
   7607 
   7608     if (ss->ssl3.sendEmptyCert) {
   7609 	ss->ssl3.sendEmptyCert = PR_FALSE;
   7610 	rv = ssl3_SendEmptyCertificate(ss);
   7611 	/* Don't send verify */
   7612 	if (rv != SECSuccess) {
   7613 	    goto loser;	/* error code is set. */
   7614     	}
   7615     } else if (sendClientCert) {
   7616 	rv = ssl3_SendCertificate(ss);
   7617 	if (rv != SECSuccess) {
   7618 	    goto loser;	/* error code is set. */
   7619     	}
   7620     }
   7621 
   7622     rv = ssl3_SendClientKeyExchange(ss);
   7623     if (rv != SECSuccess) {
   7624     	goto loser;	/* err is set. */
   7625     }
   7626 
   7627     if (sendClientCert) {
   7628 	rv = ssl3_SendCertificateVerify(ss);
   7629 	if (rv != SECSuccess) {
   7630 	    goto loser;	/* err is set. */
   7631         }
   7632     }
   7633 
   7634     rv = ssl3_SendChangeCipherSpecs(ss);
   7635     if (rv != SECSuccess) {
   7636 	goto loser;	/* err code was set. */
   7637     }
   7638 
   7639     /* This must be done after we've set ss->ssl3.cwSpec in
   7640      * ssl3_SendChangeCipherSpecs because SSL_GetChannelInfo uses information
   7641      * from cwSpec. This must be done before we call ssl3_CheckFalseStart
   7642      * because the false start callback (if any) may need the information from
   7643      * the functions that depend on this being set.
   7644      */
   7645     ss->enoughFirstHsDone = PR_TRUE;
   7646 
   7647     if (!ss->firstHsDone) {
   7648 	/* XXX: If the server's certificate hasn't been authenticated by this
   7649 	 * point, then we may be leaking this NPN message to an attacker.
   7650 	 */
   7651 	rv = ssl3_SendNextProto(ss);
   7652 	if (rv != SECSuccess) {
   7653 	    goto loser;	/* err code was set. */
   7654 	}
   7655     }
   7656 
   7657     rv = ssl3_SendEncryptedExtensions(ss);
   7658     if (rv != SECSuccess) {
   7659 	goto loser; /* err code was set. */
   7660     }
   7661 
   7662     if (!ss->firstHsDone) {
   7663 	if (ss->opt.enableFalseStart) {
   7664 	    if (!ss->ssl3.hs.authCertificatePending) {
   7665 		/* When we fix bug 589047, we will need to know whether we are
   7666 		 * false starting before we try to flush the client second
   7667 		 * round to the network. With that in mind, we purposefully
   7668 		 * call ssl3_CheckFalseStart before calling ssl3_SendFinished,
   7669 		 * which includes a call to ssl3_FlushHandshake, so that
   7670 		 * no application develops a reliance on such flushing being
   7671 		 * done before its false start callback is called.
   7672 		 */
   7673 		ssl_ReleaseXmitBufLock(ss);
   7674 		rv = ssl3_CheckFalseStart(ss);
   7675 		ssl_GetXmitBufLock(ss);
   7676 		if (rv != SECSuccess) {
   7677 		    goto loser;
   7678 		}
   7679 	    } else {
   7680 		/* The certificate authentication and the server's Finished
   7681 		 * message are racing each other. If the certificate
   7682 		 * authentication wins, then we will try to false start in
   7683 		 * ssl3_AuthCertificateComplete.
   7684 		 */
   7685 		SSL_TRC(3, ("%d: SSL3[%p]: deferring false start check because"
   7686 			    " certificate authentication is still pending.",
   7687 			    SSL_GETPID(), ss->fd));
   7688 	    }
   7689 	}
   7690     }
   7691 
   7692     rv = ssl3_SendFinished(ss, 0);
   7693     if (rv != SECSuccess) {
   7694 	goto loser;	/* err code was set. */
   7695     }
   7696 
   7697     ssl_ReleaseXmitBufLock(ss);		/*******************************/
   7698 
   7699     if (!ss->ssl3.hs.isResuming &&
   7700         ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
   7701         /* If we are negotiating ChannelID on a full handshake then we record
   7702          * the handshake hashes in |sid| at this point. They will be needed in
   7703          * the event that we resume this session and use ChannelID on the
   7704          * resumption handshake. */
   7705         SSL3Hashes hashes;
   7706         SECItem *originalHandshakeHash =
   7707             &ss->sec.ci.sid->u.ssl3.originalHandshakeHash;
   7708         PORT_Assert(ss->sec.ci.sid->cached == never_cached);
   7709 
   7710         ssl_GetSpecReadLock(ss);
   7711         PORT_Assert(ss->version > SSL_LIBRARY_VERSION_3_0);
   7712         rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
   7713         ssl_ReleaseSpecReadLock(ss);
   7714         if (rv != SECSuccess) {
   7715             return rv;
   7716         }
   7717 
   7718         PORT_Assert(originalHandshakeHash->len == 0);
   7719         originalHandshakeHash->data = PORT_Alloc(hashes.len);
   7720         if (!originalHandshakeHash->data)
   7721             return SECFailure;
   7722         originalHandshakeHash->len = hashes.len;
   7723         memcpy(originalHandshakeHash->data, hashes.u.raw, hashes.len);
   7724     }
   7725 
   7726     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
   7727 	ss->ssl3.hs.ws = wait_new_session_ticket;
   7728     else
   7729 	ss->ssl3.hs.ws = wait_change_cipher;
   7730 
   7731     PORT_Assert(ssl3_WaitingForStartOfServerSecondRound(ss));
   7732 
   7733     return SECSuccess;
   7734 
   7735 loser:
   7736     ssl_ReleaseXmitBufLock(ss);
   7737     return rv;
   7738 }
   7739 
   7740 /*
   7741  * Routines used by servers
   7742  */
   7743 static SECStatus
   7744 ssl3_SendHelloRequest(sslSocket *ss)
   7745 {
   7746     SECStatus rv;
   7747 
   7748     SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
   7749 		ss->fd));
   7750 
   7751     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7752     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   7753 
   7754     rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
   7755     if (rv != SECSuccess) {
   7756 	return rv;	/* err set by AppendHandshake */
   7757     }
   7758     rv = ssl3_FlushHandshake(ss, 0);
   7759     if (rv != SECSuccess) {
   7760 	return rv;	/* error code set by ssl3_FlushHandshake */
   7761     }
   7762     ss->ssl3.hs.ws = wait_client_hello;
   7763     return SECSuccess;
   7764 }
   7765 
   7766 /*
   7767  * Called from:
   7768  *	ssl3_HandleClientHello()
   7769  */
   7770 static SECComparison
   7771 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
   7772 {
   7773     if (!name1 != !name2) {
   7774         return SECLessThan;
   7775     }
   7776     if (!name1) {
   7777         return SECEqual;
   7778     }
   7779     if (name1->type != name2->type) {
   7780         return SECLessThan;
   7781     }
   7782     return SECITEM_CompareItem(name1, name2);
   7783 }
   7784 
   7785 /* Sets memory error when returning NULL.
   7786  * Called from:
   7787  *	ssl3_SendClientHello()
   7788  *	ssl3_HandleServerHello()
   7789  *	ssl3_HandleClientHello()
   7790  *	ssl3_HandleV2ClientHello()
   7791  */
   7792 sslSessionID *
   7793 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
   7794 {
   7795     sslSessionID *sid;
   7796 
   7797     sid = PORT_ZNew(sslSessionID);
   7798     if (sid == NULL)
   7799     	return sid;
   7800 
   7801     if (is_server) {
   7802         const SECItem *  srvName;
   7803         SECStatus        rv = SECSuccess;
   7804 
   7805         ssl_GetSpecReadLock(ss);	/********************************/
   7806         srvName = &ss->ssl3.prSpec->srvVirtName;
   7807         if (srvName->len && srvName->data) {
   7808             rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
   7809         }
   7810         ssl_ReleaseSpecReadLock(ss); /************************************/
   7811         if (rv != SECSuccess) {
   7812             PORT_Free(sid);
   7813             return NULL;
   7814         }
   7815     }
   7816     sid->peerID		= (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
   7817     sid->urlSvrName	= (ss->url    == NULL) ? NULL : PORT_Strdup(ss->url);
   7818     sid->addr           = ss->sec.ci.peer;
   7819     sid->port           = ss->sec.ci.port;
   7820     sid->references     = 1;
   7821     sid->cached         = never_cached;
   7822     sid->version        = ss->version;
   7823 
   7824     sid->u.ssl3.keys.resumable = PR_TRUE;
   7825     sid->u.ssl3.policy         = SSL_ALLOWED;
   7826     sid->u.ssl3.clientWriteKey = NULL;
   7827     sid->u.ssl3.serverWriteKey = NULL;
   7828 
   7829     if (is_server) {
   7830 	SECStatus rv;
   7831 	int       pid = SSL_GETPID();
   7832 
   7833 	sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
   7834 	sid->u.ssl3.sessionID[0]    = (pid >> 8) & 0xff;
   7835 	sid->u.ssl3.sessionID[1]    =  pid       & 0xff;
   7836 	rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
   7837 	                         SSL3_SESSIONID_BYTES -2);
   7838 	if (rv != SECSuccess) {
   7839 	    ssl_FreeSID(sid);
   7840 	    ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
   7841 	    return NULL;
   7842     	}
   7843     }
   7844     return sid;
   7845 }
   7846 
   7847 /* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
   7848 static SECStatus
   7849 ssl3_SendServerHelloSequence(sslSocket *ss)
   7850 {
   7851     const ssl3KEADef *kea_def;
   7852     SECStatus         rv;
   7853 
   7854     SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
   7855 		SSL_GETPID(), ss->fd));
   7856 
   7857     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7858     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   7859 
   7860     rv = ssl3_SendServerHello(ss);
   7861     if (rv != SECSuccess) {
   7862 	return rv;	/* err code is set. */
   7863     }
   7864     rv = ssl3_SendCertificate(ss);
   7865     if (rv != SECSuccess) {
   7866 	return rv;	/* error code is set. */
   7867     }
   7868     rv = ssl3_SendCertificateStatus(ss);
   7869     if (rv != SECSuccess) {
   7870 	return rv;	/* error code is set. */
   7871     }
   7872     /* We have to do this after the call to ssl3_SendServerHello,
   7873      * because kea_def is set up by ssl3_SendServerHello().
   7874      */
   7875     kea_def = ss->ssl3.hs.kea_def;
   7876     ss->ssl3.hs.usedStepDownKey = PR_FALSE;
   7877 
   7878     if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
   7879 	/* see if we can legally use the key in the cert. */
   7880 	int keyLen;  /* bytes */
   7881 
   7882 	keyLen = PK11_GetPrivateModulusLen(
   7883 			    ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
   7884 
   7885 	if (keyLen > 0 &&
   7886 	    keyLen * BPB <= kea_def->key_size_limit ) {
   7887 	    /* XXX AND cert is not signing only!! */
   7888 	    /* just fall through and use it. */
   7889 	} else if (ss->stepDownKeyPair != NULL) {
   7890 	    ss->ssl3.hs.usedStepDownKey = PR_TRUE;
   7891 	    rv = ssl3_SendServerKeyExchange(ss);
   7892 	    if (rv != SECSuccess) {
   7893 		return rv;	/* err code was set. */
   7894 	    }
   7895 	} else {
   7896 #ifndef HACKED_EXPORT_SERVER
   7897 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
   7898 	    return rv;
   7899 #endif
   7900 	}
   7901 #ifdef NSS_ENABLE_ECC
   7902     } else if ((kea_def->kea == kea_ecdhe_rsa) ||
   7903 	       (kea_def->kea == kea_ecdhe_ecdsa)) {
   7904 	rv = ssl3_SendServerKeyExchange(ss);
   7905 	if (rv != SECSuccess) {
   7906 	    return rv;	/* err code was set. */
   7907 	}
   7908 #endif /* NSS_ENABLE_ECC */
   7909     }
   7910 
   7911     if (ss->opt.requestCertificate) {
   7912 	rv = ssl3_SendCertificateRequest(ss);
   7913 	if (rv != SECSuccess) {
   7914 	    return rv;		/* err code is set. */
   7915 	}
   7916     }
   7917     rv = ssl3_SendServerHelloDone(ss);
   7918     if (rv != SECSuccess) {
   7919 	return rv;		/* err code is set. */
   7920     }
   7921 
   7922     ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
   7923                                                : wait_client_key;
   7924     return SECSuccess;
   7925 }
   7926 
   7927 /* An empty TLS Renegotiation Info (RI) extension */
   7928 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
   7929 
   7930 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   7931  * ssl3 Client Hello message.
   7932  * Caller must hold Handshake and RecvBuf locks.
   7933  */
   7934 static SECStatus
   7935 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   7936 {
   7937     sslSessionID *      sid      = NULL;
   7938     PRInt32		tmp;
   7939     unsigned int        i;
   7940     int                 j;
   7941     SECStatus           rv;
   7942     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
   7943     SSL3AlertDescription desc    = illegal_parameter;
   7944     SSL3AlertLevel      level    = alert_fatal;
   7945     SSL3ProtocolVersion version;
   7946     SECItem             sidBytes = {siBuffer, NULL, 0};
   7947     SECItem             cookieBytes = {siBuffer, NULL, 0};
   7948     SECItem             suites   = {siBuffer, NULL, 0};
   7949     SECItem             comps    = {siBuffer, NULL, 0};
   7950     PRBool              haveSpecWriteLock = PR_FALSE;
   7951     PRBool              haveXmitBufLock   = PR_FALSE;
   7952 
   7953     SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
   7954     	SSL_GETPID(), ss->fd));
   7955 
   7956     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7957     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   7958     PORT_Assert( ss->ssl3.initialized );
   7959 
   7960     /* Get peer name of client */
   7961     rv = ssl_GetPeerInfo(ss);
   7962     if (rv != SECSuccess) {
   7963 	return rv;		/* error code is set. */
   7964     }
   7965 
   7966     /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
   7967      * call ssl2_HandleMessage.
   7968      *
   7969      * The issue here is that TLS ordinarily starts out in
   7970      * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
   7971      * code paths. That function zeroes these next pointers. But with DTLS,
   7972      * we don't even try to do the v2 ClientHello so we skip that function
   7973      * and need to reset these values here.
   7974      */
   7975     if (IS_DTLS(ss)) {
   7976 	ss->nextHandshake     = 0;
   7977 	ss->securityHandshake = 0;
   7978     }
   7979 
   7980     /* We might be starting session renegotiation in which case we should
   7981      * clear previous state.
   7982      */
   7983     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   7984     ss->statelessResume = PR_FALSE;
   7985 
   7986     if ((ss->ssl3.hs.ws != wait_client_hello) &&
   7987 	(ss->ssl3.hs.ws != idle_handshake)) {
   7988 	desc    = unexpected_message;
   7989 	errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
   7990 	goto alert_loser;
   7991     }
   7992     if (ss->ssl3.hs.ws == idle_handshake  &&
   7993         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
   7994 	desc    = no_renegotiation;
   7995 	level   = alert_warning;
   7996 	errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
   7997 	goto alert_loser;
   7998     }
   7999 
   8000     if (IS_DTLS(ss)) {
   8001 	dtls_RehandshakeCleanup(ss);
   8002     }
   8003 
   8004     tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   8005     if (tmp < 0)
   8006 	goto loser;		/* malformed, alert already sent */
   8007 
   8008     /* Translate the version */
   8009     if (IS_DTLS(ss)) {
   8010 	ss->clientHelloVersion = version =
   8011 	    dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
   8012     } else {
   8013 	ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
   8014     }
   8015 
   8016     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
   8017     if (rv != SECSuccess) {
   8018     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
   8019 	                                           : handshake_failure;
   8020 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   8021 	goto alert_loser;
   8022     }
   8023 
   8024     rv = ssl3_InitHandshakeHashes(ss);
   8025     if (rv != SECSuccess) {
   8026 	desc = internal_error;
   8027 	errCode = PORT_GetError();
   8028 	goto alert_loser;
   8029     }
   8030 
   8031     /* grab the client random data. */
   8032     rv = ssl3_ConsumeHandshake(
   8033 	ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
   8034     if (rv != SECSuccess) {
   8035 	goto loser;		/* malformed */
   8036     }
   8037 
   8038     /* grab the client's SID, if present. */
   8039     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
   8040     if (rv != SECSuccess) {
   8041 	goto loser;		/* malformed */
   8042     }
   8043 
   8044     /* grab the client's cookie, if present. */
   8045     if (IS_DTLS(ss)) {
   8046 	rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
   8047 	if (rv != SECSuccess) {
   8048 	    goto loser;		/* malformed */
   8049 	}
   8050     }
   8051 
   8052     /* grab the list of cipher suites. */
   8053     rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
   8054     if (rv != SECSuccess) {
   8055 	goto loser;		/* malformed */
   8056     }
   8057 
   8058     /* If the ClientHello version is less than our maximum version, check for a
   8059      * TLS_FALLBACK_SCSV and reject the connection if found. */
   8060     if (ss->vrange.max > ss->clientHelloVersion) {
   8061 	for (i = 0; i + 1 < suites.len; i += 2) {
   8062 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   8063 	    if (suite_i != TLS_FALLBACK_SCSV)
   8064 		continue;
   8065 	    desc = inappropriate_fallback;
   8066 	    errCode = SSL_ERROR_INAPPROPRIATE_FALLBACK_ALERT;
   8067 	    goto alert_loser;
   8068 	}
   8069     }
   8070 
   8071     /* grab the list of compression methods. */
   8072     rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
   8073     if (rv != SECSuccess) {
   8074 	goto loser;		/* malformed */
   8075     }
   8076 
   8077     desc = handshake_failure;
   8078 
   8079     /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
   8080      * we are restarting a previous session until extensions have been
   8081      * parsed, since we might have received a SessionTicket extension.
   8082      * Note: we allow extensions even when negotiating SSL3 for the sake
   8083      * of interoperability (and backwards compatibility).
   8084      */
   8085 
   8086     if (length) {
   8087 	/* Get length of hello extensions */
   8088 	PRInt32 extension_length;
   8089 	extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   8090 	if (extension_length < 0) {
   8091 	    goto loser;				/* alert already sent */
   8092 	}
   8093 	if (extension_length != length) {
   8094 	    ssl3_DecodeError(ss);		/* send alert */
   8095 	    goto loser;
   8096 	}
   8097 	rv = ssl3_HandleHelloExtensions(ss, &b, &length);
   8098 	if (rv != SECSuccess) {
   8099 	    goto loser;		/* malformed */
   8100 	}
   8101     }
   8102     if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   8103     	/* If we didn't receive an RI extension, look for the SCSV,
   8104 	 * and if found, treat it just like an empty RI extension
   8105 	 * by processing a local copy of an empty RI extension.
   8106 	 */
   8107 	for (i = 0; i + 1 < suites.len; i += 2) {
   8108 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   8109 	    if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
   8110 		SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
   8111 		PRUint32     L2 = sizeof emptyRIext;
   8112 		(void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
   8113 	    	break;
   8114 	    }
   8115 	}
   8116     }
   8117     if (ss->firstHsDone &&
   8118         (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
   8119         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
   8120 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   8121 	desc    = no_renegotiation;
   8122 	level   = alert_warning;
   8123 	errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
   8124 	goto alert_loser;
   8125     }
   8126     if ((ss->opt.requireSafeNegotiation ||
   8127          (ss->firstHsDone && ss->peerRequestedProtection)) &&
   8128 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   8129 	desc = handshake_failure;
   8130 	errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
   8131     	goto alert_loser;
   8132     }
   8133 
   8134     /* We do stateful resumes only if either of the following
   8135      * conditions are satisfied: (1) the client does not support the
   8136      * session ticket extension, or (2) the client support the session
   8137      * ticket extension, but sent an empty ticket.
   8138      */
   8139     if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
   8140 	ss->xtnData.emptySessionTicket) {
   8141 	if (sidBytes.len > 0 && !ss->opt.noCache) {
   8142 	    SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
   8143 			SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
   8144 			ss->sec.ci.peer.pr_s6_addr32[1],
   8145 			ss->sec.ci.peer.pr_s6_addr32[2],
   8146 			ss->sec.ci.peer.pr_s6_addr32[3]));
   8147 	    if (ssl_sid_lookup) {
   8148 		sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
   8149 					sidBytes.len, ss->dbHandle);
   8150 	    } else {
   8151 		errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
   8152 		goto loser;
   8153 	    }
   8154 	}
   8155     } else if (ss->statelessResume) {
   8156 	/* Fill in the client's session ID if doing a stateless resume.
   8157 	 * (When doing stateless resumes, server echos client's SessionID.)
   8158 	 */
   8159 	sid = ss->sec.ci.sid;
   8160 	PORT_Assert(sid != NULL);  /* Should have already been filled in.*/
   8161 
   8162 	if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
   8163 	    sid->u.ssl3.sessionIDLength = sidBytes.len;
   8164 	    PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
   8165 		sidBytes.len);
   8166 	    sid->u.ssl3.sessionIDLength = sidBytes.len;
   8167 	} else {
   8168 	    sid->u.ssl3.sessionIDLength = 0;
   8169 	}
   8170 	ss->sec.ci.sid = NULL;
   8171     }
   8172 
   8173     /* We only send a session ticket extension if the client supports
   8174      * the extension and we are unable to do either a stateful or
   8175      * stateless resume.
   8176      *
   8177      * TODO: send a session ticket if performing a stateful
   8178      * resumption.  (As per RFC4507, a server may issue a session
   8179      * ticket while doing a (stateless or stateful) session resume,
   8180      * but OpenSSL-0.9.8g does not accept session tickets while
   8181      * resuming.)
   8182      */
   8183     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
   8184 	ssl3_RegisterServerHelloExtensionSender(ss,
   8185 	    ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
   8186     }
   8187 
   8188     if (sid != NULL) {
   8189 	/* We've found a session cache entry for this client.
   8190 	 * Now, if we're going to require a client-auth cert,
   8191 	 * and we don't already have this client's cert in the session cache,
   8192 	 * and this is the first handshake on this connection (not a redo),
   8193 	 * then drop this old cache entry and start a new session.
   8194 	 */
   8195 	if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
   8196 	    ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
   8197 	     (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
   8198 	     ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE)
   8199 	      && !ss->firstHsDone))) {
   8200 
   8201 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
   8202 	    if (ss->sec.uncache)
   8203                 ss->sec.uncache(sid);
   8204 	    ssl_FreeSID(sid);
   8205 	    sid = NULL;
   8206 	}
   8207     }
   8208 
   8209 #ifdef NSS_ENABLE_ECC
   8210     /* Disable any ECC cipher suites for which we have no cert. */
   8211     ssl3_FilterECCipherSuitesByServerCerts(ss);
   8212 #endif
   8213 
   8214     if (IS_DTLS(ss)) {
   8215 	ssl3_DisableNonDTLSSuites(ss);
   8216     }
   8217 
   8218     if (!ssl3_HasGCMSupport()) {
   8219 	ssl3_DisableGCMSuites(ss);
   8220     }
   8221 
   8222 #ifdef PARANOID
   8223     /* Look for a matching cipher suite. */
   8224     j = ssl3_config_match_init(ss);
   8225     if (j <= 0) {		/* no ciphers are working/supported by PK11 */
   8226     	errCode = PORT_GetError();	/* error code is already set. */
   8227 	goto alert_loser;
   8228     }
   8229 #endif
   8230 
   8231     /* If we already have a session for this client, be sure to pick the
   8232     ** same cipher suite and compression method we picked before.
   8233     ** This is not a loop, despite appearances.
   8234     */
   8235     if (sid) do {
   8236 	ssl3CipherSuiteCfg *suite;
   8237 #ifdef PARANOID
   8238 	SSLVersionRange vrange = {ss->version, ss->version};
   8239 #endif
   8240 
   8241 	/* Check that the cached compression method is still enabled. */
   8242 	if (!compressionEnabled(ss, sid->u.ssl3.compression))
   8243 	    break;
   8244 
   8245 	/* Check that the cached compression method is in the client's list */
   8246 	for (i = 0; i < comps.len; i++) {
   8247 	    if (comps.data[i] == sid->u.ssl3.compression)
   8248 		break;
   8249 	}
   8250 	if (i == comps.len)
   8251 	    break;
   8252 
   8253 	suite = ss->cipherSuites;
   8254 	/* Find the entry for the cipher suite used in the cached session. */
   8255 	for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
   8256 	    if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
   8257 		break;
   8258 	}
   8259 	PORT_Assert(j > 0);
   8260 	if (j <= 0)
   8261 	    break;
   8262 #ifdef PARANOID
   8263 	/* Double check that the cached cipher suite is still enabled,
   8264 	 * implemented, and allowed by policy.  Might have been disabled.
   8265 	 * The product policy won't change during the process lifetime.
   8266 	 * Implemented ("isPresent") shouldn't change for servers.
   8267 	 */
   8268 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange))
   8269 	    break;
   8270 #else
   8271 	if (!suite->enabled)
   8272 	    break;
   8273 #endif
   8274 	/* Double check that the cached cipher suite is in the client's list */
   8275 	for (i = 0; i + 1 < suites.len; i += 2) {
   8276 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   8277 	    if (suite_i == suite->cipher_suite) {
   8278 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
   8279 		ss->ssl3.hs.suite_def =
   8280 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
   8281 
   8282 		/* Use the cached compression method. */
   8283 		ss->ssl3.hs.compression = sid->u.ssl3.compression;
   8284 		goto compression_found;
   8285 	    }
   8286 	}
   8287     } while (0);
   8288 
   8289     /* START A NEW SESSION */
   8290 
   8291 #ifndef PARANOID
   8292     /* Look for a matching cipher suite. */
   8293     j = ssl3_config_match_init(ss);
   8294     if (j <= 0) {		/* no ciphers are working/supported by PK11 */
   8295     	errCode = PORT_GetError();	/* error code is already set. */
   8296 	goto alert_loser;
   8297     }
   8298 #endif
   8299 
   8300     /* Select a cipher suite.
   8301     **
   8302     ** NOTE: This suite selection algorithm should be the same as the one in
   8303     ** ssl3_HandleV2ClientHello().
   8304     **
   8305     ** If TLS 1.0 is enabled, we could handle the case where the client
   8306     ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
   8307     ** 1.0 and selecting one of those export cipher suites. However, a secure
   8308     ** TLS 1.1 client should not have export cipher suites enabled at all,
   8309     ** and a TLS 1.1 client should definitely not be offering *only* export
   8310     ** cipher suites. Therefore, we refuse to negotiate export cipher suites
   8311     ** with any client that indicates support for TLS 1.1 or higher when we
   8312     ** (the server) have TLS 1.1 support enabled.
   8313     */
   8314     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
   8315 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
   8316 	SSLVersionRange vrange = {ss->version, ss->version};
   8317 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
   8318 	    continue;
   8319 	}
   8320 	for (i = 0; i + 1 < suites.len; i += 2) {
   8321 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   8322 	    if (suite_i == suite->cipher_suite) {
   8323 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
   8324 		ss->ssl3.hs.suite_def =
   8325 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
   8326 		goto suite_found;
   8327 	    }
   8328 	}
   8329     }
   8330     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   8331     goto alert_loser;
   8332 
   8333 suite_found:
   8334     /* Look for a matching compression algorithm. */
   8335     for (i = 0; i < comps.len; i++) {
   8336 	if (!compressionEnabled(ss, comps.data[i]))
   8337 	    continue;
   8338 	for (j = 0; j < compressionMethodsCount; j++) {
   8339 	    if (comps.data[i] == compressions[j]) {
   8340 		ss->ssl3.hs.compression =
   8341 					(SSLCompressionMethod)compressions[j];
   8342 		goto compression_found;
   8343 	    }
   8344 	}
   8345     }
   8346     errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
   8347     				/* null compression must be supported */
   8348     goto alert_loser;
   8349 
   8350 compression_found:
   8351     suites.data = NULL;
   8352     comps.data = NULL;
   8353 
   8354     ss->sec.send = ssl3_SendApplicationData;
   8355 
   8356     /* If there are any failures while processing the old sid,
   8357      * we don't consider them to be errors.  Instead, We just behave
   8358      * as if the client had sent us no sid to begin with, and make a new one.
   8359      */
   8360     if (sid != NULL) do {
   8361 	ssl3CipherSpec *pwSpec;
   8362 	SECItem         wrappedMS;  	/* wrapped key */
   8363 
   8364 	if (sid->version != ss->version  ||
   8365 	    sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
   8366 	    sid->u.ssl3.compression != ss->ssl3.hs.compression) {
   8367 	    break;	/* not an error */
   8368 	}
   8369 
   8370 	if (ss->sec.ci.sid) {
   8371 	    if (ss->sec.uncache)
   8372                 ss->sec.uncache(ss->sec.ci.sid);
   8373 	    PORT_Assert(ss->sec.ci.sid != sid);  /* should be impossible, but ... */
   8374 	    if (ss->sec.ci.sid != sid) {
   8375 		ssl_FreeSID(ss->sec.ci.sid);
   8376 	    }
   8377 	    ss->sec.ci.sid = NULL;
   8378 	}
   8379 	/* we need to resurrect the master secret.... */
   8380 
   8381 	ssl_GetSpecWriteLock(ss);  haveSpecWriteLock = PR_TRUE;
   8382 	pwSpec = ss->ssl3.pwSpec;
   8383 	if (sid->u.ssl3.keys.msIsWrapped) {
   8384 	    PK11SymKey *    wrapKey; 	/* wrapping key */
   8385 	    CK_FLAGS        keyFlags      = 0;
   8386 #ifndef NO_PKCS11_BYPASS
   8387 	    if (ss->opt.bypassPKCS11) {
   8388 		/* we cannot restart a non-bypass session in a
   8389 		** bypass socket.
   8390 		*/
   8391 		break;
   8392 	    }
   8393 #endif
   8394 
   8395 	    wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
   8396 				     sid->u.ssl3.masterWrapMech,
   8397 				     ss->pkcs11PinArg);
   8398 	    if (!wrapKey) {
   8399 		/* we have a SID cache entry, but no wrapping key for it??? */
   8400 		break;
   8401 	    }
   8402 
   8403 	    if (ss->version > SSL_LIBRARY_VERSION_3_0) {	/* isTLS */
   8404 		keyFlags = CKF_SIGN | CKF_VERIFY;
   8405 	    }
   8406 
   8407 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   8408 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   8409 
   8410 	    /* unwrap the master secret. */
   8411 	    pwSpec->master_secret =
   8412 		PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
   8413 			    NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
   8414 			    CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
   8415 	    PK11_FreeSymKey(wrapKey);
   8416 	    if (pwSpec->master_secret == NULL) {
   8417 		break;	/* not an error */
   8418 	    }
   8419 #ifndef NO_PKCS11_BYPASS
   8420 	} else if (ss->opt.bypassPKCS11) {
   8421 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   8422 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   8423 	    memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
   8424 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   8425 	    pwSpec->msItem.len  = wrappedMS.len;
   8426 #endif
   8427 	} else {
   8428 	    /* We CAN restart a bypass session in a non-bypass socket. */
   8429 	    /* need to import the raw master secret to session object */
   8430 	    PK11SlotInfo * slot;
   8431 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   8432 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   8433 	    slot = PK11_GetInternalSlot();
   8434 	    pwSpec->master_secret =
   8435 		PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
   8436 				  PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS,
   8437 				  NULL);
   8438 	    PK11_FreeSlot(slot);
   8439 	    if (pwSpec->master_secret == NULL) {
   8440 		break;	/* not an error */
   8441 	    }
   8442 	}
   8443 	ss->sec.ci.sid = sid;
   8444 	if (sid->peerCert != NULL) {
   8445 	    ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
   8446 	    ssl3_CopyPeerCertsFromSID(ss, sid);
   8447 	}
   8448 
   8449 	/*
   8450 	 * Old SID passed all tests, so resume this old session.
   8451 	 *
   8452 	 * XXX make sure compression still matches
   8453 	 */
   8454 	SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
   8455 	if (ss->statelessResume)
   8456 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
   8457 	ss->ssl3.hs.isResuming = PR_TRUE;
   8458 
   8459         ss->sec.authAlgorithm = sid->authAlgorithm;
   8460 	ss->sec.authKeyBits   = sid->authKeyBits;
   8461 	ss->sec.keaType       = sid->keaType;
   8462 	ss->sec.keaKeyBits    = sid->keaKeyBits;
   8463 
   8464 	/* server sids don't remember the server cert we previously sent,
   8465 	** but they do remember the kea type we originally used, so we
   8466 	** can locate it again, provided that the current ssl socket
   8467 	** has had its server certs configured the same as the previous one.
   8468 	*/
   8469 	ss->sec.localCert     =
   8470 		CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
   8471 
   8472         /* Copy cached name in to pending spec */
   8473         if (sid != NULL &&
   8474             sid->version > SSL_LIBRARY_VERSION_3_0 &&
   8475             sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
   8476             /* Set server name from sid */
   8477             SECItem *sidName = &sid->u.ssl3.srvName;
   8478             SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
   8479             if (pwsName->data) {
   8480                 SECITEM_FreeItem(pwsName, PR_FALSE);
   8481             }
   8482             rv = SECITEM_CopyItem(NULL, pwsName, sidName);
   8483             if (rv != SECSuccess) {
   8484                 errCode = PORT_GetError();
   8485                 desc = internal_error;
   8486                 goto alert_loser;
   8487             }
   8488         }
   8489 
   8490         /* Clean up sni name array */
   8491         if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
   8492             ss->xtnData.sniNameArr) {
   8493             PORT_Free(ss->xtnData.sniNameArr);
   8494             ss->xtnData.sniNameArr = NULL;
   8495             ss->xtnData.sniNameArrSize = 0;
   8496         }
   8497 
   8498 	ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
   8499 
   8500 	rv = ssl3_SendServerHello(ss);
   8501 	if (rv != SECSuccess) {
   8502 	    errCode = PORT_GetError();
   8503 	    goto loser;
   8504 	}
   8505 
   8506 	if (haveSpecWriteLock) {
   8507 	    ssl_ReleaseSpecWriteLock(ss);
   8508 	    haveSpecWriteLock = PR_FALSE;
   8509 	}
   8510 
   8511 	/* NULL value for PMS signifies re-use of the old MS */
   8512 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
   8513 	if (rv != SECSuccess) {
   8514 	    errCode = PORT_GetError();
   8515 	    goto loser;
   8516 	}
   8517 
   8518 	rv = ssl3_SendChangeCipherSpecs(ss);
   8519 	if (rv != SECSuccess) {
   8520 	    errCode = PORT_GetError();
   8521 	    goto loser;
   8522 	}
   8523 	rv = ssl3_SendFinished(ss, 0);
   8524 	ss->ssl3.hs.ws = wait_change_cipher;
   8525 	if (rv != SECSuccess) {
   8526 	    errCode = PORT_GetError();
   8527 	    goto loser;
   8528 	}
   8529 
   8530 	if (haveXmitBufLock) {
   8531 	    ssl_ReleaseXmitBufLock(ss);
   8532 	    haveXmitBufLock = PR_FALSE;
   8533 	}
   8534 
   8535         return SECSuccess;
   8536     } while (0);
   8537 
   8538     if (haveSpecWriteLock) {
   8539 	ssl_ReleaseSpecWriteLock(ss);
   8540 	haveSpecWriteLock = PR_FALSE;
   8541     }
   8542 
   8543     if (sid) { 	/* we had a sid, but it's no longer valid, free it */
   8544 	SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
   8545 	if (ss->sec.uncache)
   8546             ss->sec.uncache(sid);
   8547 	ssl_FreeSID(sid);
   8548 	sid = NULL;
   8549     }
   8550     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
   8551 
   8552     if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
   8553         int ret = 0;
   8554         if (ss->sniSocketConfig) do { /* not a loop */
   8555             ret = SSL_SNI_SEND_ALERT;
   8556             /* If extension is negotiated, the len of names should > 0. */
   8557             if (ss->xtnData.sniNameArrSize) {
   8558                 /* Calling client callback to reconfigure the socket. */
   8559                 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
   8560                                          ss->xtnData.sniNameArr,
   8561                                       ss->xtnData.sniNameArrSize,
   8562                                           ss->sniSocketConfigArg);
   8563             }
   8564             if (ret <= SSL_SNI_SEND_ALERT) {
   8565                 /* Application does not know the name or was not able to
   8566                  * properly reconfigure the socket. */
   8567                 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8568                 desc = unrecognized_name;
   8569                 break;
   8570             } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
   8571                 SECStatus       rv = SECSuccess;
   8572                 SECItem *       cwsName, *pwsName;
   8573 
   8574                 ssl_GetSpecWriteLock(ss);  /*******************************/
   8575                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
   8576                 cwsName = &ss->ssl3.cwSpec->srvVirtName;
   8577 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
   8578                 /* not allow name change on the 2d HS */
   8579                 if (ss->firstHsDone) {
   8580                     if (ssl3_ServerNameCompare(pwsName, cwsName)) {
   8581                         ssl_ReleaseSpecWriteLock(ss);  /******************/
   8582                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8583                         desc = handshake_failure;
   8584                         ret = SSL_SNI_SEND_ALERT;
   8585                         break;
   8586                     }
   8587                 }
   8588 #endif
   8589                 if (pwsName->data) {
   8590                     SECITEM_FreeItem(pwsName, PR_FALSE);
   8591                 }
   8592                 if (cwsName->data) {
   8593                     rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
   8594                 }
   8595                 ssl_ReleaseSpecWriteLock(ss);  /**************************/
   8596                 if (rv != SECSuccess) {
   8597                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
   8598                     desc = internal_error;
   8599                     ret = SSL_SNI_SEND_ALERT;
   8600                     break;
   8601                 }
   8602             } else if (ret < ss->xtnData.sniNameArrSize) {
   8603                 /* Application has configured new socket info. Lets check it
   8604                  * and save the name. */
   8605                 SECStatus       rv;
   8606                 SECItem *       name = &ss->xtnData.sniNameArr[ret];
   8607                 int             configedCiphers;
   8608                 SECItem *       pwsName;
   8609 
   8610                 /* get rid of the old name and save the newly picked. */
   8611                 /* This code is protected by ssl3HandshakeLock. */
   8612                 ssl_GetSpecWriteLock(ss);  /*******************************/
   8613 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
   8614                 /* not allow name change on the 2d HS */
   8615                 if (ss->firstHsDone) {
   8616                     SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
   8617                     if (ssl3_ServerNameCompare(name, cwsName)) {
   8618                         ssl_ReleaseSpecWriteLock(ss);  /******************/
   8619                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8620                         desc = handshake_failure;
   8621                         ret = SSL_SNI_SEND_ALERT;
   8622                         break;
   8623                     }
   8624                 }
   8625 #endif
   8626                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
   8627                 if (pwsName->data) {
   8628                     SECITEM_FreeItem(pwsName, PR_FALSE);
   8629                 }
   8630                 rv = SECITEM_CopyItem(NULL, pwsName, name);
   8631                 ssl_ReleaseSpecWriteLock(ss);  /***************************/
   8632                 if (rv != SECSuccess) {
   8633                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
   8634                     desc = internal_error;
   8635                     ret = SSL_SNI_SEND_ALERT;
   8636                     break;
   8637                 }
   8638                 configedCiphers = ssl3_config_match_init(ss);
   8639                 if (configedCiphers <= 0) {
   8640                     /* no ciphers are working/supported */
   8641                     errCode = PORT_GetError();
   8642                     desc = handshake_failure;
   8643                     ret = SSL_SNI_SEND_ALERT;
   8644                     break;
   8645                 }
   8646                 /* Need to tell the client that application has picked
   8647                  * the name from the offered list and reconfigured the socket.
   8648                  */
   8649                 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
   8650                                                         ssl3_SendServerNameXtn);
   8651             } else {
   8652                 /* Callback returned index outside of the boundary. */
   8653                 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
   8654                 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
   8655                 desc = internal_error;
   8656                 ret = SSL_SNI_SEND_ALERT;
   8657                 break;
   8658             }
   8659         } while (0);
   8660         /* Free sniNameArr. The data that each SECItem in the array
   8661          * points into is the data from the input buffer "b". It will
   8662          * not be available outside the scope of this or it's child
   8663          * functions.*/
   8664         if (ss->xtnData.sniNameArr) {
   8665             PORT_Free(ss->xtnData.sniNameArr);
   8666             ss->xtnData.sniNameArr = NULL;
   8667             ss->xtnData.sniNameArrSize = 0;
   8668         }
   8669         if (ret <= SSL_SNI_SEND_ALERT) {
   8670             /* desc and errCode should be set. */
   8671             goto alert_loser;
   8672         }
   8673     }
   8674 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
   8675     else if (ss->firstHsDone) {
   8676         /* Check that we don't have the name is current spec
   8677          * if this extension was not negotiated on the 2d hs. */
   8678         PRBool passed = PR_TRUE;
   8679         ssl_GetSpecReadLock(ss);  /*******************************/
   8680         if (ss->ssl3.cwSpec->srvVirtName.data) {
   8681             passed = PR_FALSE;
   8682         }
   8683         ssl_ReleaseSpecReadLock(ss);  /***************************/
   8684         if (!passed) {
   8685             errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8686             desc = handshake_failure;
   8687             goto alert_loser;
   8688         }
   8689     }
   8690 #endif
   8691 
   8692     sid = ssl3_NewSessionID(ss, PR_TRUE);
   8693     if (sid == NULL) {
   8694 	errCode = PORT_GetError();
   8695 	goto loser;	/* memory error is set. */
   8696     }
   8697     ss->sec.ci.sid = sid;
   8698 
   8699     ss->ssl3.hs.isResuming = PR_FALSE;
   8700     ssl_GetXmitBufLock(ss);
   8701     rv = ssl3_SendServerHelloSequence(ss);
   8702     ssl_ReleaseXmitBufLock(ss);
   8703     if (rv != SECSuccess) {
   8704 	errCode = PORT_GetError();
   8705 	goto loser;
   8706     }
   8707 
   8708     if (haveXmitBufLock) {
   8709 	ssl_ReleaseXmitBufLock(ss);
   8710 	haveXmitBufLock = PR_FALSE;
   8711     }
   8712 
   8713     return SECSuccess;
   8714 
   8715 alert_loser:
   8716     if (haveSpecWriteLock) {
   8717 	ssl_ReleaseSpecWriteLock(ss);
   8718 	haveSpecWriteLock = PR_FALSE;
   8719     }
   8720     (void)SSL3_SendAlert(ss, level, desc);
   8721     /* FALLTHRU */
   8722 loser:
   8723     if (haveSpecWriteLock) {
   8724 	ssl_ReleaseSpecWriteLock(ss);
   8725 	haveSpecWriteLock = PR_FALSE;
   8726     }
   8727 
   8728     if (haveXmitBufLock) {
   8729 	ssl_ReleaseXmitBufLock(ss);
   8730 	haveXmitBufLock = PR_FALSE;
   8731     }
   8732 
   8733     PORT_SetError(errCode);
   8734     return SECFailure;
   8735 }
   8736 
   8737 /*
   8738  * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
   8739  * in asking to use the V3 handshake.
   8740  * Called from ssl2_HandleClientHelloMessage() in sslcon.c
   8741  */
   8742 SECStatus
   8743 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
   8744 {
   8745     sslSessionID *      sid 		= NULL;
   8746     unsigned char *     suites;
   8747     unsigned char *     random;
   8748     SSL3ProtocolVersion version;
   8749     SECStatus           rv;
   8750     int                 i;
   8751     int                 j;
   8752     int                 sid_length;
   8753     int                 suite_length;
   8754     int                 rand_length;
   8755     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
   8756     SSL3AlertDescription desc    = handshake_failure;
   8757 
   8758     SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
   8759 
   8760     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   8761 
   8762     ssl_GetSSL3HandshakeLock(ss);
   8763 
   8764     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   8765 
   8766     rv = ssl3_InitState(ss);
   8767     if (rv != SECSuccess) {
   8768 	ssl_ReleaseSSL3HandshakeLock(ss);
   8769 	return rv;		/* ssl3_InitState has set the error code. */
   8770     }
   8771     rv = ssl3_RestartHandshakeHashes(ss);
   8772     if (rv != SECSuccess) {
   8773 	ssl_ReleaseSSL3HandshakeLock(ss);
   8774 	return rv;
   8775     }
   8776 
   8777     if (ss->ssl3.hs.ws != wait_client_hello) {
   8778 	desc    = unexpected_message;
   8779 	errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
   8780 	goto loser;	/* alert_loser */
   8781     }
   8782 
   8783     version      = (buffer[1] << 8) | buffer[2];
   8784     suite_length = (buffer[3] << 8) | buffer[4];
   8785     sid_length   = (buffer[5] << 8) | buffer[6];
   8786     rand_length  = (buffer[7] << 8) | buffer[8];
   8787     ss->clientHelloVersion = version;
   8788 
   8789     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
   8790     if (rv != SECSuccess) {
   8791 	/* send back which ever alert client will understand. */
   8792     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
   8793 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   8794 	goto alert_loser;
   8795     }
   8796 
   8797     rv = ssl3_InitHandshakeHashes(ss);
   8798     if (rv != SECSuccess) {
   8799 	desc = internal_error;
   8800 	errCode = PORT_GetError();
   8801 	goto alert_loser;
   8802     }
   8803 
   8804     /* if we get a non-zero SID, just ignore it. */
   8805     if (length !=
   8806         SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
   8807 	SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
   8808 		 SSL_GETPID(), ss->fd, length,
   8809 		 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
   8810 		 rand_length));
   8811 	goto loser;	/* malformed */	/* alert_loser */
   8812     }
   8813 
   8814     suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
   8815     random = suites + suite_length + sid_length;
   8816 
   8817     if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
   8818 	rand_length > SSL_MAX_CHALLENGE_BYTES) {
   8819 	goto loser;	/* malformed */	/* alert_loser */
   8820     }
   8821 
   8822     PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
   8823 
   8824     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
   8825     PORT_Memcpy(
   8826 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
   8827 	random, rand_length);
   8828 
   8829     PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
   8830 		   SSL3_RANDOM_LENGTH));
   8831 #ifdef NSS_ENABLE_ECC
   8832     /* Disable any ECC cipher suites for which we have no cert. */
   8833     ssl3_FilterECCipherSuitesByServerCerts(ss);
   8834 #endif
   8835     i = ssl3_config_match_init(ss);
   8836     if (i <= 0) {
   8837     	errCode = PORT_GetError();	/* error code is already set. */
   8838 	goto alert_loser;
   8839     }
   8840 
   8841     /* Select a cipher suite.
   8842     **
   8843     ** NOTE: This suite selection algorithm should be the same as the one in
   8844     ** ssl3_HandleClientHello().
   8845     **
   8846     ** See the comments about export cipher suites in ssl3_HandleClientHello().
   8847     */
   8848     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
   8849 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
   8850 	SSLVersionRange vrange = {ss->version, ss->version};
   8851 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE, &vrange)) {
   8852 	    continue;
   8853 	}
   8854 	for (i = 0; i+2 < suite_length; i += 3) {
   8855 	    PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
   8856 	    if (suite_i == suite->cipher_suite) {
   8857 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
   8858 		ss->ssl3.hs.suite_def =
   8859 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
   8860 		goto suite_found;
   8861 	    }
   8862 	}
   8863     }
   8864     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   8865     goto alert_loser;
   8866 
   8867 suite_found:
   8868 
   8869     /* Look for the SCSV, and if found, treat it just like an empty RI
   8870      * extension by processing a local copy of an empty RI extension.
   8871      */
   8872     for (i = 0; i+2 < suite_length; i += 3) {
   8873 	PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
   8874 	if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
   8875 	    SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
   8876 	    PRUint32     L2 = sizeof emptyRIext;
   8877 	    (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
   8878 	    break;
   8879 	}
   8880     }
   8881 
   8882     if (ss->opt.requireSafeNegotiation &&
   8883 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   8884 	desc = handshake_failure;
   8885 	errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
   8886     	goto alert_loser;
   8887     }
   8888 
   8889     ss->ssl3.hs.compression = ssl_compression_null;
   8890     ss->sec.send            = ssl3_SendApplicationData;
   8891 
   8892     /* we don't even search for a cache hit here.  It's just a miss. */
   8893     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
   8894     sid = ssl3_NewSessionID(ss, PR_TRUE);
   8895     if (sid == NULL) {
   8896     	errCode = PORT_GetError();
   8897 	goto loser;	/* memory error is set. */
   8898     }
   8899     ss->sec.ci.sid = sid;
   8900     /* do not worry about memory leak of sid since it now belongs to ci */
   8901 
   8902     /* We have to update the handshake hashes before we can send stuff */
   8903     rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
   8904     if (rv != SECSuccess) {
   8905     	errCode = PORT_GetError();
   8906 	goto loser;
   8907     }
   8908 
   8909     ssl_GetXmitBufLock(ss);
   8910     rv = ssl3_SendServerHelloSequence(ss);
   8911     ssl_ReleaseXmitBufLock(ss);
   8912     if (rv != SECSuccess) {
   8913     	errCode = PORT_GetError();
   8914 	goto loser;
   8915     }
   8916 
   8917     /* XXX_1 	The call stack to here is:
   8918      * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
   8919      * ssl2_HandleClientHelloMessage returns whatever we return here.
   8920      * ssl_Do1stHandshake will continue looping if it gets back either
   8921      *		SECSuccess or SECWouldBlock.
   8922      * SECSuccess is preferable here.  See XXX_1 in sslgathr.c.
   8923      */
   8924     ssl_ReleaseSSL3HandshakeLock(ss);
   8925     return SECSuccess;
   8926 
   8927 alert_loser:
   8928     SSL3_SendAlert(ss, alert_fatal, desc);
   8929 loser:
   8930     ssl_ReleaseSSL3HandshakeLock(ss);
   8931     PORT_SetError(errCode);
   8932     return SECFailure;
   8933 }
   8934 
   8935 /* The negotiated version number has been already placed in ss->version.
   8936 **
   8937 ** Called from:  ssl3_HandleClientHello                     (resuming session),
   8938 ** 	ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
   8939 ** 	ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
   8940 */
   8941 static SECStatus
   8942 ssl3_SendServerHello(sslSocket *ss)
   8943 {
   8944     sslSessionID *sid;
   8945     SECStatus     rv;
   8946     PRUint32      maxBytes = 65535;
   8947     PRUint32      length;
   8948     PRInt32       extensions_len = 0;
   8949     SSL3ProtocolVersion version;
   8950 
   8951     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
   8952 		ss->fd));
   8953 
   8954     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   8955     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   8956 
   8957     if (!IS_DTLS(ss)) {
   8958 	PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
   8959 
   8960 	if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
   8961 	    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
   8962 	    return SECFailure;
   8963 	}
   8964     } else {
   8965 	PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
   8966 
   8967 	if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
   8968 	    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
   8969 	    return SECFailure;
   8970 	}
   8971     }
   8972 
   8973     sid = ss->sec.ci.sid;
   8974 
   8975     extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
   8976 					       &ss->xtnData.serverSenders[0]);
   8977     if (extensions_len > 0)
   8978     	extensions_len += 2; /* Add sizeof total extension length */
   8979 
   8980     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
   8981              ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
   8982 	     sizeof(ssl3CipherSuite) + 1 + extensions_len;
   8983     rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
   8984     if (rv != SECSuccess) {
   8985 	return rv;	/* err set by AppendHandshake. */
   8986     }
   8987 
   8988     if (IS_DTLS(ss)) {
   8989 	version = dtls_TLSVersionToDTLSVersion(ss->version);
   8990     } else {
   8991 	version = ss->version;
   8992     }
   8993 
   8994     rv = ssl3_AppendHandshakeNumber(ss, version, 2);
   8995     if (rv != SECSuccess) {
   8996 	return rv;	/* err set by AppendHandshake. */
   8997     }
   8998     rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
   8999     if (rv != SECSuccess) {
   9000 	ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
   9001 	return rv;
   9002     }
   9003     rv = ssl3_AppendHandshake(
   9004 	ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
   9005     if (rv != SECSuccess) {
   9006 	return rv;	/* err set by AppendHandshake. */
   9007     }
   9008 
   9009     if (sid)
   9010 	rv = ssl3_AppendHandshakeVariable(
   9011 	    ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
   9012     else
   9013 	rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
   9014     if (rv != SECSuccess) {
   9015 	return rv;	/* err set by AppendHandshake. */
   9016     }
   9017 
   9018     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
   9019     if (rv != SECSuccess) {
   9020 	return rv;	/* err set by AppendHandshake. */
   9021     }
   9022     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
   9023     if (rv != SECSuccess) {
   9024 	return rv;	/* err set by AppendHandshake. */
   9025     }
   9026     if (extensions_len) {
   9027 	PRInt32 sent_len;
   9028 
   9029     	extensions_len -= 2;
   9030 	rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
   9031 	if (rv != SECSuccess)
   9032 	    return rv;	/* err set by ssl3_SetupPendingCipherSpec */
   9033 	sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
   9034 					   &ss->xtnData.serverSenders[0]);
   9035         PORT_Assert(sent_len == extensions_len);
   9036 	if (sent_len != extensions_len) {
   9037 	    if (sent_len >= 0)
   9038 	    	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   9039 	    return SECFailure;
   9040 	}
   9041     }
   9042     rv = ssl3_SetupPendingCipherSpec(ss);
   9043     if (rv != SECSuccess) {
   9044 	return rv;	/* err set by ssl3_SetupPendingCipherSpec */
   9045     }
   9046 
   9047     return SECSuccess;
   9048 }
   9049 
   9050 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
   9051  * elements of the handshake. (The negotiated cipher suite determines the
   9052  * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
   9053  * used. With TLS 1.2, a client may advertise its support for signature and
   9054  * hash combinations. */
   9055 static SECStatus
   9056 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
   9057 				SSL3SignatureAndHashAlgorithm* out)
   9058 {
   9059     TLSSignatureAlgorithm sigAlg;
   9060     unsigned int i, j;
   9061     /* hashPreference expresses our preferences for hash algorithms, most
   9062      * preferable first. */
   9063     static const PRUint8 hashPreference[] = {
   9064 	tls_hash_sha256,
   9065 	tls_hash_sha384,
   9066 	tls_hash_sha512,
   9067 	tls_hash_sha1,
   9068     };
   9069 
   9070     switch (ss->ssl3.hs.kea_def->kea) {
   9071     case kea_rsa:
   9072     case kea_rsa_export:
   9073     case kea_rsa_export_1024:
   9074     case kea_dh_rsa:
   9075     case kea_dh_rsa_export:
   9076     case kea_dhe_rsa:
   9077     case kea_dhe_rsa_export:
   9078     case kea_rsa_fips:
   9079     case kea_ecdh_rsa:
   9080     case kea_ecdhe_rsa:
   9081 	sigAlg = tls_sig_rsa;
   9082 	break;
   9083     case kea_dh_dss:
   9084     case kea_dh_dss_export:
   9085     case kea_dhe_dss:
   9086     case kea_dhe_dss_export:
   9087 	sigAlg = tls_sig_dsa;
   9088 	break;
   9089     case kea_ecdh_ecdsa:
   9090     case kea_ecdhe_ecdsa:
   9091 	sigAlg = tls_sig_ecdsa;
   9092 	break;
   9093     default:
   9094 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   9095 	return SECFailure;
   9096     }
   9097     out->sigAlg = sigAlg;
   9098 
   9099     if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
   9100 	/* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
   9101 	 * prior. */
   9102 	out->hashAlg = SEC_OID_UNKNOWN;
   9103 	return SECSuccess;
   9104     }
   9105 
   9106     if (ss->ssl3.hs.numClientSigAndHash == 0) {
   9107 	/* If the client didn't provide any signature_algorithms extension then
   9108 	 * we can assume that they support SHA-1:
   9109 	 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   9110 	out->hashAlg = SEC_OID_SHA1;
   9111 	return SECSuccess;
   9112     }
   9113 
   9114     for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) {
   9115 	for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
   9116 	    const SSL3SignatureAndHashAlgorithm* sh =
   9117 		&ss->ssl3.hs.clientSigAndHash[j];
   9118 	    if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) {
   9119 		out->hashAlg = sh->hashAlg;
   9120 		return SECSuccess;
   9121 	    }
   9122 	}
   9123     }
   9124 
   9125     PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   9126     return SECFailure;
   9127 }
   9128 
   9129 
   9130 static SECStatus
   9131 ssl3_SendServerKeyExchange(sslSocket *ss)
   9132 {
   9133     const ssl3KEADef * kea_def     = ss->ssl3.hs.kea_def;
   9134     SECStatus          rv          = SECFailure;
   9135     int                length;
   9136     PRBool             isTLS;
   9137     SECItem            signed_hash = {siBuffer, NULL, 0};
   9138     SSL3Hashes         hashes;
   9139     SECKEYPublicKey *  sdPub;	/* public key for step-down */
   9140     SSL3SignatureAndHashAlgorithm sigAndHash;
   9141 
   9142     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
   9143 		SSL_GETPID(), ss->fd));
   9144 
   9145     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9146     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9147 
   9148     if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
   9149 	return SECFailure;
   9150     }
   9151 
   9152     switch (kea_def->exchKeyType) {
   9153     case kt_rsa:
   9154 	/* Perform SSL Step-Down here. */
   9155 	sdPub = ss->stepDownKeyPair->pubKey;
   9156 	PORT_Assert(sdPub != NULL);
   9157 	if (!sdPub) {
   9158 	    PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   9159 	    return SECFailure;
   9160 	}
   9161 	rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
   9162 					  sdPub->u.rsa.modulus,
   9163 					  sdPub->u.rsa.publicExponent,
   9164 	                                  &ss->ssl3.hs.client_random,
   9165 	                                  &ss->ssl3.hs.server_random,
   9166 					  &hashes, ss->opt.bypassPKCS11);
   9167         if (rv != SECSuccess) {
   9168 	    ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   9169 	    return rv;
   9170 	}
   9171 
   9172 	isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   9173 	rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
   9174 	                     &signed_hash, isTLS);
   9175         if (rv != SECSuccess) {
   9176 	    goto loser;		/* ssl3_SignHashes has set err. */
   9177 	}
   9178 	if (signed_hash.data == NULL) {
   9179 	    /* how can this happen and rv == SECSuccess ?? */
   9180 	    PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   9181 	    goto loser;
   9182 	}
   9183 	length = 2 + sdPub->u.rsa.modulus.len +
   9184 	         2 + sdPub->u.rsa.publicExponent.len +
   9185 	         2 + signed_hash.len;
   9186 
   9187 	rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
   9188 	if (rv != SECSuccess) {
   9189 	    goto loser; 	/* err set by AppendHandshake. */
   9190 	}
   9191 
   9192 	rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
   9193 					  sdPub->u.rsa.modulus.len, 2);
   9194 	if (rv != SECSuccess) {
   9195 	    goto loser; 	/* err set by AppendHandshake. */
   9196 	}
   9197 
   9198 	rv = ssl3_AppendHandshakeVariable(
   9199 				ss, sdPub->u.rsa.publicExponent.data,
   9200 				sdPub->u.rsa.publicExponent.len, 2);
   9201 	if (rv != SECSuccess) {
   9202 	    goto loser; 	/* err set by AppendHandshake. */
   9203 	}
   9204 
   9205 	if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   9206 	    rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
   9207 	    if (rv != SECSuccess) {
   9208 		goto loser; 	/* err set by AppendHandshake. */
   9209 	    }
   9210 	}
   9211 
   9212 	rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
   9213 	                                  signed_hash.len, 2);
   9214 	if (rv != SECSuccess) {
   9215 	    goto loser; 	/* err set by AppendHandshake. */
   9216 	}
   9217 	PORT_Free(signed_hash.data);
   9218 	return SECSuccess;
   9219 
   9220 #ifdef NSS_ENABLE_ECC
   9221     case kt_ecdh: {
   9222 	rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
   9223 	return rv;
   9224     }
   9225 #endif /* NSS_ENABLE_ECC */
   9226 
   9227     case kt_dh:
   9228     case kt_null:
   9229     default:
   9230 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   9231 	break;
   9232     }
   9233 loser:
   9234     if (signed_hash.data != NULL)
   9235     	PORT_Free(signed_hash.data);
   9236     return SECFailure;
   9237 }
   9238 
   9239 
   9240 static SECStatus
   9241 ssl3_SendCertificateRequest(sslSocket *ss)
   9242 {
   9243     PRBool         isTLS12;
   9244     SECItem *      name;
   9245     CERTDistNames *ca_list;
   9246     const PRUint8 *certTypes;
   9247     const PRUint8 *sigAlgs;
   9248     SECItem *      names	= NULL;
   9249     SECStatus      rv;
   9250     int            length;
   9251     int            i;
   9252     int            calen	= 0;
   9253     int            nnames	= 0;
   9254     int            certTypesLength;
   9255     int            sigAlgsLength;
   9256 
   9257     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
   9258 		SSL_GETPID(), ss->fd));
   9259 
   9260     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9261     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9262 
   9263     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   9264 
   9265     /* ssl3.ca_list is initialized to NULL, and never changed. */
   9266     ca_list = ss->ssl3.ca_list;
   9267     if (!ca_list) {
   9268 	ca_list = ssl3_server_ca_list;
   9269     }
   9270 
   9271     if (ca_list != NULL) {
   9272 	names = ca_list->names;
   9273 	nnames = ca_list->nnames;
   9274     }
   9275 
   9276     for (i = 0, name = names; i < nnames; i++, name++) {
   9277 	calen += 2 + name->len;
   9278     }
   9279 
   9280     certTypes       = certificate_types;
   9281     certTypesLength = sizeof certificate_types;
   9282     sigAlgs         = supported_signature_algorithms;
   9283     sigAlgsLength   = sizeof supported_signature_algorithms;
   9284 
   9285     length = 1 + certTypesLength + 2 + calen;
   9286     if (isTLS12) {
   9287 	length += 2 + sigAlgsLength;
   9288     }
   9289 
   9290     rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
   9291     if (rv != SECSuccess) {
   9292 	return rv; 		/* err set by AppendHandshake. */
   9293     }
   9294     rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
   9295     if (rv != SECSuccess) {
   9296 	return rv; 		/* err set by AppendHandshake. */
   9297     }
   9298     if (isTLS12) {
   9299 	rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
   9300 	if (rv != SECSuccess) {
   9301 	    return rv; 		/* err set by AppendHandshake. */
   9302 	}
   9303     }
   9304     rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
   9305     if (rv != SECSuccess) {
   9306 	return rv; 		/* err set by AppendHandshake. */
   9307     }
   9308     for (i = 0, name = names; i < nnames; i++, name++) {
   9309 	rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
   9310 	if (rv != SECSuccess) {
   9311 	    return rv; 		/* err set by AppendHandshake. */
   9312 	}
   9313     }
   9314 
   9315     return SECSuccess;
   9316 }
   9317 
   9318 static SECStatus
   9319 ssl3_SendServerHelloDone(sslSocket *ss)
   9320 {
   9321     SECStatus rv;
   9322 
   9323     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
   9324 		SSL_GETPID(), ss->fd));
   9325 
   9326     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9327     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9328 
   9329     rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
   9330     if (rv != SECSuccess) {
   9331 	return rv; 		/* err set by AppendHandshake. */
   9332     }
   9333     rv = ssl3_FlushHandshake(ss, 0);
   9334     if (rv != SECSuccess) {
   9335 	return rv;	/* error code set by ssl3_FlushHandshake */
   9336     }
   9337     return SECSuccess;
   9338 }
   9339 
   9340 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   9341  * ssl3 Certificate Verify message
   9342  * Caller must hold Handshake and RecvBuf locks.
   9343  */
   9344 static SECStatus
   9345 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
   9346 			     SSL3Hashes *hashes)
   9347 {
   9348     SECItem              signed_hash = {siBuffer, NULL, 0};
   9349     SECStatus            rv;
   9350     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
   9351     SSL3AlertDescription desc        = handshake_failure;
   9352     PRBool               isTLS, isTLS12;
   9353     SSL3SignatureAndHashAlgorithm sigAndHash;
   9354 
   9355     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
   9356 		SSL_GETPID(), ss->fd));
   9357     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9358     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9359 
   9360     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   9361     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   9362 
   9363     if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
   9364 	desc    = unexpected_message;
   9365 	errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
   9366 	goto alert_loser;
   9367     }
   9368 
   9369     if (isTLS12) {
   9370 	rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
   9371 						   &sigAndHash);
   9372 	if (rv != SECSuccess) {
   9373 	    goto loser;	/* malformed or unsupported. */
   9374 	}
   9375 	rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
   9376 		&sigAndHash, ss->sec.peerCert);
   9377 	if (rv != SECSuccess) {
   9378 	    errCode = PORT_GetError();
   9379 	    desc = decrypt_error;
   9380 	    goto alert_loser;
   9381 	}
   9382 
   9383 	/* We only support CertificateVerify messages that use the handshake
   9384 	 * hash. */
   9385 	if (sigAndHash.hashAlg != hashes->hashAlg) {
   9386 	    errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
   9387 	    desc = decrypt_error;
   9388 	    goto alert_loser;
   9389 	}
   9390     }
   9391 
   9392     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
   9393     if (rv != SECSuccess) {
   9394 	goto loser;		/* malformed. */
   9395     }
   9396 
   9397     /* XXX verify that the key & kea match */
   9398     rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
   9399 				 isTLS, ss->pkcs11PinArg);
   9400     if (rv != SECSuccess) {
   9401     	errCode = PORT_GetError();
   9402 	desc = isTLS ? decrypt_error : handshake_failure;
   9403 	goto alert_loser;
   9404     }
   9405 
   9406     signed_hash.data = NULL;
   9407 
   9408     if (length != 0) {
   9409 	desc    = isTLS ? decode_error : illegal_parameter;
   9410 	goto alert_loser;	/* malformed */
   9411     }
   9412     ss->ssl3.hs.ws = wait_change_cipher;
   9413     return SECSuccess;
   9414 
   9415 alert_loser:
   9416     SSL3_SendAlert(ss, alert_fatal, desc);
   9417 loser:
   9418     PORT_SetError(errCode);
   9419     return SECFailure;
   9420 }
   9421 
   9422 
   9423 /* find a slot that is able to generate a PMS and wrap it with RSA.
   9424  * Then generate and return the PMS.
   9425  * If the serverKeySlot parameter is non-null, this function will use
   9426  * that slot to do the job, otherwise it will find a slot.
   9427  *
   9428  * Called from  ssl3_DeriveConnectionKeysPKCS11()  (above)
   9429  *		sendRSAClientKeyExchange()         (above)
   9430  *		ssl3_HandleRSAClientKeyExchange()  (below)
   9431  * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
   9432  */
   9433 static PK11SymKey *
   9434 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
   9435                     PK11SlotInfo * serverKeySlot)
   9436 {
   9437     PK11SymKey *      pms		= NULL;
   9438     PK11SlotInfo *    slot		= serverKeySlot;
   9439     void *	      pwArg 		= ss->pkcs11PinArg;
   9440     SECItem           param;
   9441     CK_VERSION 	      version;
   9442     CK_MECHANISM_TYPE mechanism_array[3];
   9443 
   9444     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9445 
   9446     if (slot == NULL) {
   9447 	SSLCipherAlgorithm calg;
   9448 	/* The specReadLock would suffice here, but we cannot assert on
   9449 	** read locks.  Also, all the callers who call with a non-null
   9450 	** slot already hold the SpecWriteLock.
   9451 	*/
   9452 	PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   9453 	PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   9454 
   9455         calg = spec->cipher_def->calg;
   9456 	PORT_Assert(alg2Mech[calg].calg == calg);
   9457 
   9458 	/* First get an appropriate slot.  */
   9459 	mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
   9460 	mechanism_array[1] = CKM_RSA_PKCS;
   9461 	mechanism_array[2] = alg2Mech[calg].cmech;
   9462 
   9463 	slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
   9464 	if (slot == NULL) {
   9465 	   /* can't find a slot with all three, find a slot with the minimum */
   9466 	    slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
   9467 	    if (slot == NULL) {
   9468 		PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
   9469 		return pms;	/* which is NULL */
   9470 	    }
   9471 	}
   9472     }
   9473 
   9474     /* Generate the pre-master secret ...  */
   9475     if (IS_DTLS(ss)) {
   9476 	SSL3ProtocolVersion temp;
   9477 
   9478 	temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
   9479 	version.major = MSB(temp);
   9480 	version.minor = LSB(temp);
   9481     } else {
   9482 	version.major = MSB(ss->clientHelloVersion);
   9483 	version.minor = LSB(ss->clientHelloVersion);
   9484     }
   9485 
   9486     param.data = (unsigned char *)&version;
   9487     param.len  = sizeof version;
   9488 
   9489     pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
   9490     if (!serverKeySlot)
   9491 	PK11_FreeSlot(slot);
   9492     if (pms == NULL) {
   9493 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   9494     }
   9495     return pms;
   9496 }
   9497 
   9498 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
   9499  * return any indication of failure of the Client Key Exchange message,
   9500  * where that failure is caused by the content of the client's message.
   9501  * This function must not return SECFailure for any reason that is directly
   9502  * or indirectly caused by the content of the client's encrypted PMS.
   9503  * We must not send an alert and also not drop the connection.
   9504  * Instead, we generate a random PMS.  This will cause a failure
   9505  * in the processing the finished message, which is exactly where
   9506  * the failure must occur.
   9507  *
   9508  * Called from ssl3_HandleClientKeyExchange
   9509  */
   9510 static SECStatus
   9511 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
   9512                                 SSL3Opaque *b,
   9513 				PRUint32 length,
   9514 				SECKEYPrivateKey *serverKey)
   9515 {
   9516     PK11SymKey *      pms;
   9517 #ifndef NO_PKCS11_BYPASS
   9518     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
   9519     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
   9520     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
   9521     unsigned int      outLen = 0;
   9522 #endif
   9523     PRBool            isTLS  = PR_FALSE;
   9524     SECStatus         rv;
   9525     SECItem           enc_pms;
   9526     unsigned char     rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
   9527     SECItem           pmsItem = {siBuffer, NULL, 0};
   9528 
   9529     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9530     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9531     PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec );
   9532 
   9533     enc_pms.data = b;
   9534     enc_pms.len  = length;
   9535     pmsItem.data = rsaPmsBuf;
   9536     pmsItem.len  = sizeof rsaPmsBuf;
   9537 
   9538     if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
   9539 	PRInt32 kLen;
   9540 	kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
   9541 	if (kLen < 0) {
   9542 	    PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   9543 	    return SECFailure;
   9544 	}
   9545 	if ((unsigned)kLen < enc_pms.len) {
   9546 	    enc_pms.len = kLen;
   9547 	}
   9548 	isTLS = PR_TRUE;
   9549     } else {
   9550 	isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
   9551     }
   9552 
   9553 #ifndef NO_PKCS11_BYPASS
   9554     if (ss->opt.bypassPKCS11) {
   9555 	/* TRIPLE BYPASS, get PMS directly from RSA decryption.
   9556 	 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
   9557 	 * then, check for version rollback attack, then
   9558 	 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
   9559 	 * pwSpec->msItem.  Finally call ssl3_InitPendingCipherSpec with
   9560 	 * ss and NULL, so that it will use the MS we've already derived here.
   9561 	 */
   9562 
   9563 	rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
   9564 				   sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
   9565 	if (rv != SECSuccess) {
   9566 	    /* triple bypass failed.  Let's try for a double bypass. */
   9567 	    goto double_bypass;
   9568 	} else if (ss->opt.detectRollBack) {
   9569 	    SSL3ProtocolVersion client_version =
   9570 					 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
   9571 
   9572 	    if (IS_DTLS(ss)) {
   9573 		client_version = dtls_DTLSVersionToTLSVersion(client_version);
   9574 	    }
   9575 
   9576 	    if (client_version != ss->clientHelloVersion) {
   9577 		/* Version roll-back detected. ensure failure.  */
   9578 		rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
   9579 	    }
   9580 	}
   9581 	/* have PMS, build MS without PKCS11 */
   9582 	rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
   9583 					PR_TRUE);
   9584 	if (rv != SECSuccess) {
   9585 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   9586 	    pwSpec->msItem.len  = SSL3_MASTER_SECRET_LENGTH;
   9587 	    PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
   9588 	}
   9589 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
   9590     } else
   9591 #endif
   9592     {
   9593 #ifndef NO_PKCS11_BYPASS
   9594 double_bypass:
   9595 #endif
   9596 	/*
   9597 	 * unwrap pms out of the incoming buffer
   9598 	 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
   9599 	 *	the unwrap.  Rather, it is the mechanism with which the
   9600 	 *      unwrapped pms will be used.
   9601 	 */
   9602 	pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
   9603 				   CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
   9604 	if (pms != NULL) {
   9605 	    PRINT_BUF(60, (ss, "decrypted premaster secret:",
   9606 			   PK11_GetKeyData(pms)->data,
   9607 			   PK11_GetKeyData(pms)->len));
   9608 	} else {
   9609 	    /* unwrap failed. Generate a bogus PMS and carry on. */
   9610 	    PK11SlotInfo *  slot   = PK11_GetSlotFromPrivateKey(serverKey);
   9611 
   9612 	    ssl_GetSpecWriteLock(ss);
   9613 	    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
   9614 	    ssl_ReleaseSpecWriteLock(ss);
   9615 	    PK11_FreeSlot(slot);
   9616 	}
   9617 
   9618 	if (pms == NULL) {
   9619 	    /* last gasp.  */
   9620 	    ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   9621 	    return SECFailure;
   9622 	}
   9623 
   9624 	/* This step will derive the MS from the PMS, among other things. */
   9625 	rv = ssl3_InitPendingCipherSpec(ss,  pms);
   9626 	PK11_FreeSymKey(pms);
   9627     }
   9628 
   9629     if (rv != SECSuccess) {
   9630 	SEND_ALERT
   9631 	return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
   9632     }
   9633     return SECSuccess;
   9634 }
   9635 
   9636 
   9637 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   9638  * ssl3 ClientKeyExchange message from the remote client
   9639  * Caller must hold Handshake and RecvBuf locks.
   9640  */
   9641 static SECStatus
   9642 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   9643 {
   9644     SECKEYPrivateKey *serverKey         = NULL;
   9645     SECStatus         rv;
   9646     const ssl3KEADef *kea_def;
   9647     ssl3KeyPair     *serverKeyPair      = NULL;
   9648 #ifdef NSS_ENABLE_ECC
   9649     SECKEYPublicKey *serverPubKey       = NULL;
   9650 #endif /* NSS_ENABLE_ECC */
   9651 
   9652     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
   9653 		SSL_GETPID(), ss->fd));
   9654 
   9655     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9656     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9657 
   9658     if (ss->ssl3.hs.ws != wait_client_key) {
   9659 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   9660     	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
   9661 	return SECFailure;
   9662     }
   9663 
   9664     kea_def   = ss->ssl3.hs.kea_def;
   9665 
   9666     if (ss->ssl3.hs.usedStepDownKey) {
   9667 	 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
   9668 		 && kea_def->exchKeyType == kt_rsa
   9669 		 && ss->stepDownKeyPair != NULL);
   9670 	 if (!kea_def->is_limited  ||
   9671 	      kea_def->exchKeyType != kt_rsa ||
   9672 	      ss->stepDownKeyPair == NULL) {
   9673 	 	/* shouldn't happen, don't use step down if it does */
   9674 		goto skip;
   9675 	 }
   9676     	serverKeyPair = ss->stepDownKeyPair;
   9677 	ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
   9678     } else
   9679 skip:
   9680 #ifdef NSS_ENABLE_ECC
   9681     /* XXX Using SSLKEAType to index server certifiates
   9682      * does not work for (EC)DHE ciphers. Until we have
   9683      * an indexing mechanism general enough for all key
   9684      * exchange algorithms, we'll need to deal with each
   9685      * one seprately.
   9686      */
   9687     if ((kea_def->kea == kea_ecdhe_rsa) ||
   9688                (kea_def->kea == kea_ecdhe_ecdsa)) {
   9689 	if (ss->ephemeralECDHKeyPair != NULL) {
   9690 	   serverKeyPair = ss->ephemeralECDHKeyPair;
   9691 	   if (serverKeyPair->pubKey) {
   9692 		ss->sec.keaKeyBits =
   9693 		    SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
   9694 	   }
   9695 	}
   9696     } else
   9697 #endif
   9698     {
   9699 	sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
   9700 	serverKeyPair = sc->serverKeyPair;
   9701 	ss->sec.keaKeyBits = sc->serverKeyBits;
   9702     }
   9703 
   9704     if (serverKeyPair) {
   9705 	serverKey = serverKeyPair->privKey;
   9706     }
   9707 
   9708     if (serverKey == NULL) {
   9709     	SEND_ALERT
   9710 	PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
   9711 	return SECFailure;
   9712     }
   9713 
   9714     ss->sec.keaType    = kea_def->exchKeyType;
   9715 
   9716     switch (kea_def->exchKeyType) {
   9717     case kt_rsa:
   9718 	rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
   9719 	if (rv != SECSuccess) {
   9720 	    SEND_ALERT
   9721 	    return SECFailure;	/* error code set */
   9722 	}
   9723 	break;
   9724 
   9725 
   9726 #ifdef NSS_ENABLE_ECC
   9727     case kt_ecdh:
   9728 	/* XXX We really ought to be able to store multiple
   9729 	 * EC certs (a requirement if we wish to support both
   9730 	 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
   9731 	 * When we make that change, we'll need an index other
   9732 	 * than kt_ecdh to pick the right EC certificate.
   9733 	 */
   9734 	if (serverKeyPair) {
   9735 	    serverPubKey = serverKeyPair->pubKey;
   9736         }
   9737 	if (serverPubKey == NULL) {
   9738 	    /* XXX Is this the right error code? */
   9739 	    PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   9740 	    return SECFailure;
   9741 	}
   9742 	rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
   9743 					      serverPubKey, serverKey);
   9744 	if (rv != SECSuccess) {
   9745 	    return SECFailure;	/* error code set */
   9746 	}
   9747 	break;
   9748 #endif /* NSS_ENABLE_ECC */
   9749 
   9750     default:
   9751 	(void) ssl3_HandshakeFailure(ss);
   9752 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   9753 	return SECFailure;
   9754     }
   9755     ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
   9756     return SECSuccess;
   9757 
   9758 }
   9759 
   9760 /* This is TLS's equivalent of sending a no_certificate alert. */
   9761 static SECStatus
   9762 ssl3_SendEmptyCertificate(sslSocket *ss)
   9763 {
   9764     SECStatus            rv;
   9765 
   9766     rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
   9767     if (rv == SECSuccess) {
   9768 	rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
   9769     }
   9770     return rv;	/* error, if any, set by functions called above. */
   9771 }
   9772 
   9773 SECStatus
   9774 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   9775 {
   9776     SECStatus         rv;
   9777     NewSessionTicket  session_ticket;
   9778 
   9779     SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
   9780 		SSL_GETPID(), ss->fd));
   9781 
   9782     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9783     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9784 
   9785     if (ss->ssl3.hs.ws != wait_new_session_ticket) {
   9786 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   9787 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
   9788 	return SECFailure;
   9789     }
   9790 
   9791     session_ticket.received_timestamp = ssl_Time();
   9792     if (length < 4) {
   9793 	(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
   9794 	PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
   9795 	return SECFailure;
   9796     }
   9797     session_ticket.ticket_lifetime_hint =
   9798 	(PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
   9799 
   9800     rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
   9801 	&b, &length);
   9802     if (length != 0 || rv != SECSuccess) {
   9803 	(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
   9804 	PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
   9805 	return SECFailure;  /* malformed */
   9806     }
   9807 
   9808     rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
   9809     if (rv != SECSuccess) {
   9810 	(void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
   9811 	PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
   9812 	return SECFailure;
   9813     }
   9814     ss->ssl3.hs.ws = wait_change_cipher;
   9815     return SECSuccess;
   9816 }
   9817 
   9818 #ifdef NISCC_TEST
   9819 static PRInt32 connNum = 0;
   9820 
   9821 static SECStatus
   9822 get_fake_cert(SECItem *pCertItem, int *pIndex)
   9823 {
   9824     PRFileDesc *cf;
   9825     char *      testdir;
   9826     char *      startat;
   9827     char *      stopat;
   9828     const char *extension;
   9829     int         fileNum;
   9830     PRInt32     numBytes   = 0;
   9831     PRStatus    prStatus;
   9832     PRFileInfo  info;
   9833     char        cfn[100];
   9834 
   9835     pCertItem->data = 0;
   9836     if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
   9837 	return SECSuccess;
   9838     }
   9839     *pIndex   = (NULL != strstr(testdir, "root"));
   9840     extension = (strstr(testdir, "simple") ? "" : ".der");
   9841     fileNum     = PR_ATOMIC_INCREMENT(&connNum) - 1;
   9842     if ((startat = PR_GetEnv("START_AT")) != NULL) {
   9843 	fileNum += atoi(startat);
   9844     }
   9845     if ((stopat = PR_GetEnv("STOP_AT")) != NULL &&
   9846 	fileNum >= atoi(stopat)) {
   9847 	*pIndex = -1;
   9848 	return SECSuccess;
   9849     }
   9850     sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
   9851     cf = PR_Open(cfn, PR_RDONLY, 0);
   9852     if (!cf) {
   9853 	goto loser;
   9854     }
   9855     prStatus = PR_GetOpenFileInfo(cf, &info);
   9856     if (prStatus != PR_SUCCESS) {
   9857 	PR_Close(cf);
   9858 	goto loser;
   9859     }
   9860     pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
   9861     if (pCertItem) {
   9862 	numBytes = PR_Read(cf, pCertItem->data, info.size);
   9863     }
   9864     PR_Close(cf);
   9865     if (numBytes != info.size) {
   9866 	SECITEM_FreeItem(pCertItem, PR_FALSE);
   9867 	PORT_SetError(SEC_ERROR_IO);
   9868 	goto loser;
   9869     }
   9870     fprintf(stderr, "using %s\n", cfn);
   9871     return SECSuccess;
   9872 
   9873 loser:
   9874     fprintf(stderr, "failed to use %s\n", cfn);
   9875     *pIndex = -1;
   9876     return SECFailure;
   9877 }
   9878 #endif
   9879 
   9880 /*
   9881  * Used by both client and server.
   9882  * Called from HandleServerHelloDone and from SendServerHelloSequence.
   9883  */
   9884 static SECStatus
   9885 ssl3_SendCertificate(sslSocket *ss)
   9886 {
   9887     SECStatus            rv;
   9888     CERTCertificateList *certChain;
   9889     int                  len 		= 0;
   9890     int                  i;
   9891     SSL3KEAType          certIndex;
   9892 #ifdef NISCC_TEST
   9893     SECItem              fakeCert;
   9894     int                  ndex           = -1;
   9895 #endif
   9896 
   9897     SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
   9898 		SSL_GETPID(), ss->fd));
   9899 
   9900     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9901     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9902 
   9903     if (ss->sec.localCert)
   9904     	CERT_DestroyCertificate(ss->sec.localCert);
   9905     if (ss->sec.isServer) {
   9906 	sslServerCerts * sc = NULL;
   9907 
   9908 	/* XXX SSLKEAType isn't really a good choice for
   9909 	 * indexing certificates (it breaks when we deal
   9910 	 * with (EC)DHE-* cipher suites. This hack ensures
   9911 	 * the RSA cert is picked for (EC)DHE-RSA.
   9912 	 * Revisit this when we add server side support
   9913 	 * for ECDHE-ECDSA or client-side authentication
   9914 	 * using EC certificates.
   9915 	 */
   9916 	if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
   9917 	    (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
   9918 	    certIndex = kt_rsa;
   9919 	} else {
   9920 	    certIndex = ss->ssl3.hs.kea_def->exchKeyType;
   9921 	}
   9922 	sc                    = ss->serverCerts + certIndex;
   9923 	certChain             = sc->serverCertChain;
   9924 	ss->sec.authKeyBits   = sc->serverKeyBits;
   9925 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
   9926 	ss->sec.localCert     = CERT_DupCertificate(sc->serverCert);
   9927     } else {
   9928 	certChain          = ss->ssl3.clientCertChain;
   9929 	ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
   9930     }
   9931 
   9932 #ifdef NISCC_TEST
   9933     rv = get_fake_cert(&fakeCert, &ndex);
   9934 #endif
   9935 
   9936     if (certChain) {
   9937 	for (i = 0; i < certChain->len; i++) {
   9938 #ifdef NISCC_TEST
   9939 	    if (fakeCert.len > 0 && i == ndex) {
   9940 		len += fakeCert.len + 3;
   9941 	    } else {
   9942 		len += certChain->certs[i].len + 3;
   9943 	    }
   9944 #else
   9945 	    len += certChain->certs[i].len + 3;
   9946 #endif
   9947 	}
   9948     }
   9949 
   9950     rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
   9951     if (rv != SECSuccess) {
   9952 	return rv; 		/* err set by AppendHandshake. */
   9953     }
   9954     rv = ssl3_AppendHandshakeNumber(ss, len, 3);
   9955     if (rv != SECSuccess) {
   9956 	return rv; 		/* err set by AppendHandshake. */
   9957     }
   9958     if (certChain) {
   9959         for (i = 0; i < certChain->len; i++) {
   9960 #ifdef NISCC_TEST
   9961             if (fakeCert.len > 0 && i == ndex) {
   9962                 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
   9963                                                   fakeCert.len, 3);
   9964                 SECITEM_FreeItem(&fakeCert, PR_FALSE);
   9965             } else {
   9966                 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
   9967                                                   certChain->certs[i].len, 3);
   9968             }
   9969 #else
   9970             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
   9971                                               certChain->certs[i].len, 3);
   9972 #endif
   9973             if (rv != SECSuccess) {
   9974                 return rv; 		/* err set by AppendHandshake. */
   9975             }
   9976         }
   9977     }
   9978 
   9979     return SECSuccess;
   9980 }
   9981 
   9982 /*
   9983  * Used by server only.
   9984  * single-stapling, send only a single cert status
   9985  */
   9986 static SECStatus
   9987 ssl3_SendCertificateStatus(sslSocket *ss)
   9988 {
   9989     SECStatus rv;
   9990     int len = 0;
   9991     SECItemArray *statusToSend = NULL;
   9992     SSL3KEAType certIndex;
   9993 
   9994     SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
   9995 		SSL_GETPID(), ss->fd));
   9996 
   9997     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9998     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9999     PORT_Assert( ss->sec.isServer);
   10000 
   10001     if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
   10002 	return SECSuccess;
   10003 
   10004     /* Use certStatus based on the cert being used. */
   10005     if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
   10006 	(ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
   10007 	certIndex = kt_rsa;
   10008     } else {
   10009 	certIndex = ss->ssl3.hs.kea_def->exchKeyType;
   10010     }
   10011     if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
   10012 	statusToSend = ss->certStatusArray[certIndex];
   10013     }
   10014     if (!statusToSend)
   10015 	return SECSuccess;
   10016 
   10017     /* Use the array's first item only (single stapling) */
   10018     len = 1 + statusToSend->items[0].len + 3;
   10019 
   10020     rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
   10021     if (rv != SECSuccess) {
   10022 	return rv; 		/* err set by AppendHandshake. */
   10023     }
   10024     rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
   10025     if (rv != SECSuccess)
   10026 	return rv; 		/* err set by AppendHandshake. */
   10027 
   10028     rv = ssl3_AppendHandshakeVariable(ss,
   10029 				      statusToSend->items[0].data,
   10030 				      statusToSend->items[0].len,
   10031 				      3);
   10032     if (rv != SECSuccess)
   10033 	return rv; 		/* err set by AppendHandshake. */
   10034 
   10035     return SECSuccess;
   10036 }
   10037 
   10038 /* This is used to delete the CA certificates in the peer certificate chain
   10039  * from the cert database after they've been validated.
   10040  */
   10041 static void
   10042 ssl3_CleanupPeerCerts(sslSocket *ss)
   10043 {
   10044     PLArenaPool * arena = ss->ssl3.peerCertArena;
   10045     ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
   10046 
   10047     for (; certs; certs = certs->next) {
   10048 	CERT_DestroyCertificate(certs->cert);
   10049     }
   10050     if (arena) PORT_FreeArena(arena, PR_FALSE);
   10051     ss->ssl3.peerCertArena = NULL;
   10052     ss->ssl3.peerCertChain = NULL;
   10053 }
   10054 
   10055 static void
   10056 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid)
   10057 {
   10058     PLArenaPool *arena;
   10059     ssl3CertNode *lastCert = NULL;
   10060     ssl3CertNode *certs = NULL;
   10061     int i;
   10062 
   10063     if (!sid->peerCertChain[0])
   10064 	return;
   10065     PORT_Assert(!ss->ssl3.peerCertArena);
   10066     PORT_Assert(!ss->ssl3.peerCertChain);
   10067     ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   10068     for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
   10069 	ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode);
   10070 	c->cert = CERT_DupCertificate(sid->peerCertChain[i]);
   10071 	c->next = NULL;
   10072 	if (lastCert) {
   10073 	    lastCert->next = c;
   10074 	} else {
   10075 	    certs = c;
   10076 	}
   10077 	lastCert = c;
   10078     }
   10079     ss->ssl3.peerCertChain = certs;
   10080 }
   10081 
   10082 static void
   10083 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid)
   10084 {
   10085     int i = 0;
   10086     ssl3CertNode *c = certs;
   10087     for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) {
   10088 	PORT_Assert(!sid->peerCertChain[i]);
   10089 	sid->peerCertChain[i] = CERT_DupCertificate(c->cert);
   10090     }
   10091 }
   10092 
   10093 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   10094  * ssl3 CertificateStatus message.
   10095  * Caller must hold Handshake and RecvBuf locks.
   10096  * This is always called before ssl3_HandleCertificate, even if the Certificate
   10097  * message is sent first.
   10098  */
   10099 static SECStatus
   10100 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   10101 {
   10102     PRInt32 status, len;
   10103 
   10104     if (ss->ssl3.hs.ws != wait_certificate_status) {
   10105         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10106         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
   10107         return SECFailure;
   10108     }
   10109 
   10110     PORT_Assert(!ss->sec.isServer);
   10111 
   10112     /* Consume the CertificateStatusType enum */
   10113     status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
   10114     if (status != 1 /* ocsp */) {
   10115        goto format_loser;
   10116     }
   10117 
   10118     len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   10119     if (len != length) {
   10120        goto format_loser;
   10121     }
   10122 
   10123 #define MAX_CERTSTATUS_LEN 0x1ffff   /* 128k - 1 */
   10124     if (length > MAX_CERTSTATUS_LEN)
   10125        goto format_loser;
   10126 #undef MAX_CERTSTATUS_LEN
   10127 
   10128     /* Array size 1, because we currently implement single-stapling only */
   10129     SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
   10130     if (!ss->sec.ci.sid->peerCertStatus.items)
   10131        return SECFailure;
   10132 
   10133     ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
   10134 
   10135     if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
   10136         SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
   10137         return SECFailure;
   10138     }
   10139 
   10140     PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
   10141     ss->sec.ci.sid->peerCertStatus.items[0].len = length;
   10142     ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
   10143 
   10144     return ssl3_AuthCertificate(ss);
   10145 
   10146 format_loser:
   10147     return ssl3_DecodeError(ss);
   10148 }
   10149 
   10150 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   10151  * ssl3 Certificate message.
   10152  * Caller must hold Handshake and RecvBuf locks.
   10153  */
   10154 static SECStatus
   10155 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   10156 {
   10157     ssl3CertNode *   c;
   10158     ssl3CertNode *   lastCert 	= NULL;
   10159     PRInt32          remaining  = 0;
   10160     PRInt32          size;
   10161     SECStatus        rv;
   10162     PRBool           isServer	= (PRBool)(!!ss->sec.isServer);
   10163     PRBool           isTLS;
   10164     SSL3AlertDescription desc;
   10165     int              errCode    = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
   10166     SECItem          certItem;
   10167 
   10168     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
   10169 		SSL_GETPID(), ss->fd));
   10170     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   10171     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   10172 
   10173     if ((ss->ssl3.hs.ws != wait_server_cert) &&
   10174 	(ss->ssl3.hs.ws != wait_client_cert)) {
   10175 	desc    = unexpected_message;
   10176 	errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
   10177 	goto alert_loser;
   10178     }
   10179 
   10180     if (ss->sec.peerCert != NULL) {
   10181 	if (ss->sec.peerKey) {
   10182 	    SECKEY_DestroyPublicKey(ss->sec.peerKey);
   10183 	    ss->sec.peerKey = NULL;
   10184 	}
   10185 	CERT_DestroyCertificate(ss->sec.peerCert);
   10186 	ss->sec.peerCert = NULL;
   10187     }
   10188 
   10189     ssl3_CleanupPeerCerts(ss);
   10190     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   10191 
   10192     /* It is reported that some TLS client sends a Certificate message
   10193     ** with a zero-length message body.  We'll treat that case like a
   10194     ** normal no_certificates message to maximize interoperability.
   10195     */
   10196     if (length) {
   10197 	remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   10198 	if (remaining < 0)
   10199 	    goto loser;	/* fatal alert already sent by ConsumeHandshake. */
   10200 	if ((PRUint32)remaining > length)
   10201 	    goto decode_loser;
   10202     }
   10203 
   10204     if (!remaining) {
   10205 	if (!(isTLS && isServer)) {
   10206 	    desc = bad_certificate;
   10207 	    goto alert_loser;
   10208 	}
   10209     	/* This is TLS's version of a no_certificate alert. */
   10210     	/* I'm a server. I've requested a client cert. He hasn't got one. */
   10211 	rv = ssl3_HandleNoCertificate(ss);
   10212 	if (rv != SECSuccess) {
   10213 	    errCode = PORT_GetError();
   10214 	    goto loser;
   10215 	}
   10216        ss->ssl3.hs.ws = wait_client_key;
   10217        return SECSuccess;
   10218     }
   10219 
   10220     ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   10221     if (ss->ssl3.peerCertArena == NULL) {
   10222 	goto loser;	/* don't send alerts on memory errors */
   10223     }
   10224 
   10225     /* First get the peer cert. */
   10226     remaining -= 3;
   10227     if (remaining < 0)
   10228 	goto decode_loser;
   10229 
   10230     size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   10231     if (size <= 0)
   10232 	goto loser;	/* fatal alert already sent by ConsumeHandshake. */
   10233 
   10234     if (remaining < size)
   10235 	goto decode_loser;
   10236 
   10237     certItem.data = b;
   10238     certItem.len = size;
   10239     b      += size;
   10240     length -= size;
   10241     remaining -= size;
   10242 
   10243     ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
   10244                                             PR_FALSE, PR_TRUE);
   10245     if (ss->sec.peerCert == NULL) {
   10246 	/* We should report an alert if the cert was bad, but not if the
   10247 	 * problem was just some local problem, like memory error.
   10248 	 */
   10249 	goto ambiguous_err;
   10250     }
   10251 
   10252     /* Now get all of the CA certs. */
   10253     while (remaining > 0) {
   10254 	remaining -= 3;
   10255 	if (remaining < 0)
   10256 	    goto decode_loser;
   10257 
   10258 	size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   10259 	if (size <= 0)
   10260 	    goto loser;	/* fatal alert already sent by ConsumeHandshake. */
   10261 
   10262 	if (remaining < size)
   10263 	    goto decode_loser;
   10264 
   10265 	certItem.data = b;
   10266 	certItem.len = size;
   10267 	b      += size;
   10268 	length -= size;
   10269 	remaining -= size;
   10270 
   10271 	c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
   10272 	if (c == NULL) {
   10273 	    goto loser;	/* don't send alerts on memory errors */
   10274 	}
   10275 
   10276 	c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
   10277 	                                  PR_FALSE, PR_TRUE);
   10278 	if (c->cert == NULL) {
   10279 	    goto ambiguous_err;
   10280 	}
   10281 
   10282 	c->next = NULL;
   10283 	if (lastCert) {
   10284 	    lastCert->next = c;
   10285 	} else {
   10286 	    ss->ssl3.peerCertChain = c;
   10287 	}
   10288 	lastCert = c;
   10289     }
   10290 
   10291     if (remaining != 0)
   10292         goto decode_loser;
   10293 
   10294     SECKEY_UpdateCertPQG(ss->sec.peerCert);
   10295 
   10296     if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
   10297        ss->ssl3.hs.ws = wait_certificate_status;
   10298        rv = SECSuccess;
   10299     } else {
   10300        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
   10301     }
   10302 
   10303     return rv;
   10304 
   10305 ambiguous_err:
   10306     errCode = PORT_GetError();
   10307     switch (errCode) {
   10308     case PR_OUT_OF_MEMORY_ERROR:
   10309     case SEC_ERROR_BAD_DATABASE:
   10310     case SEC_ERROR_NO_MEMORY:
   10311        if (isTLS) {
   10312            desc = internal_error;
   10313            goto alert_loser;
   10314        }
   10315        goto loser;
   10316     }
   10317     ssl3_SendAlertForCertError(ss, errCode);
   10318     goto loser;
   10319 
   10320 decode_loser:
   10321     desc = isTLS ? decode_error : bad_certificate;
   10322 
   10323 alert_loser:
   10324     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   10325 
   10326 loser:
   10327     (void)ssl_MapLowLevelError(errCode);
   10328     return SECFailure;
   10329 }
   10330 
   10331 static SECStatus
   10332 ssl3_AuthCertificate(sslSocket *ss)
   10333 {
   10334     SECStatus        rv;
   10335     PRBool           isServer   = (PRBool)(!!ss->sec.isServer);
   10336     int              errCode;
   10337 
   10338     ss->ssl3.hs.authCertificatePending = PR_FALSE;
   10339 
   10340     /*
   10341      * Ask caller-supplied callback function to validate cert chain.
   10342      */
   10343     rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
   10344 					   PR_TRUE, isServer);
   10345     if (rv) {
   10346 	errCode = PORT_GetError();
   10347 	if (rv != SECWouldBlock) {
   10348 	    if (ss->handleBadCert) {
   10349 		rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
   10350 	    }
   10351 	}
   10352 
   10353 	if (rv == SECWouldBlock) {
   10354 	    if (ss->sec.isServer) {
   10355 		errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
   10356 		rv = SECFailure;
   10357 		goto loser;
   10358 	    }
   10359 
   10360 	    ss->ssl3.hs.authCertificatePending = PR_TRUE;
   10361 	    rv = SECSuccess;
   10362 	}
   10363 
   10364 	if (rv != SECSuccess) {
   10365 	    ssl3_SendAlertForCertError(ss, errCode);
   10366 	    goto loser;
   10367 	}
   10368     }
   10369 
   10370     ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
   10371     ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid);
   10372 
   10373     if (!ss->sec.isServer) {
   10374         CERTCertificate *cert = ss->sec.peerCert;
   10375 
   10376 	/* set the server authentication and key exchange types and sizes
   10377 	** from the value in the cert.  If the key exchange key is different,
   10378 	** it will get fixed when we handle the server key exchange message.
   10379 	*/
   10380 	SECKEYPublicKey * pubKey  = CERT_ExtractPublicKey(cert);
   10381 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
   10382 	ss->sec.keaType       = ss->ssl3.hs.kea_def->exchKeyType;
   10383 	if (pubKey) {
   10384 	    ss->sec.keaKeyBits = ss->sec.authKeyBits =
   10385 		SECKEY_PublicKeyStrengthInBits(pubKey);
   10386 #ifdef NSS_ENABLE_ECC
   10387 	    if (ss->sec.keaType == kt_ecdh) {
   10388 		/* Get authKeyBits from signing key.
   10389 		 * XXX The code below uses a quick approximation of
   10390 		 * key size based on cert->signatureWrap.signature.data
   10391 		 * (which contains the DER encoded signature). The field
   10392 		 * cert->signatureWrap.signature.len contains the
   10393 		 * length of the encoded signature in bits.
   10394 		 */
   10395 		if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
   10396 		    ss->sec.authKeyBits =
   10397 			cert->signatureWrap.signature.data[3]*8;
   10398 		    if (cert->signatureWrap.signature.data[4] == 0x00)
   10399 			    ss->sec.authKeyBits -= 8;
   10400 		    /*
   10401 		     * XXX: if cert is not signed by ecdsa we should
   10402 		     * destroy pubKey and goto bad_cert
   10403 		     */
   10404 		} else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
   10405 		    ss->sec.authKeyBits = cert->signatureWrap.signature.len;
   10406 		    /*
   10407 		     * XXX: if cert is not signed by rsa we should
   10408 		     * destroy pubKey and goto bad_cert
   10409 		     */
   10410 		}
   10411 	    }
   10412 #endif /* NSS_ENABLE_ECC */
   10413 	    SECKEY_DestroyPublicKey(pubKey);
   10414 	    pubKey = NULL;
   10415     	}
   10416 
   10417 	ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
   10418 	if (ss->ssl3.hs.kea_def->is_limited ||
   10419 	    /* XXX OR server cert is signing only. */
   10420 #ifdef NSS_ENABLE_ECC
   10421 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
   10422 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
   10423 #endif /* NSS_ENABLE_ECC */
   10424 	    ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
   10425 	    ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
   10426 	}
   10427     } else {
   10428 	ss->ssl3.hs.ws = wait_client_key;
   10429     }
   10430 
   10431     PORT_Assert(rv == SECSuccess);
   10432     if (rv != SECSuccess) {
   10433 	errCode = SEC_ERROR_LIBRARY_FAILURE;
   10434 	rv = SECFailure;
   10435 	goto loser;
   10436     }
   10437 
   10438     return rv;
   10439 
   10440 loser:
   10441     (void)ssl_MapLowLevelError(errCode);
   10442     return SECFailure;
   10443 }
   10444 
   10445 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
   10446 
   10447 static SECStatus
   10448 ssl3_AlwaysFail(sslSocket * ss)
   10449 {
   10450     PORT_SetError(PR_INVALID_STATE_ERROR);
   10451     return SECFailure;
   10452 }
   10453 
   10454 /* Caller must hold 1stHandshakeLock.
   10455 */
   10456 SECStatus
   10457 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
   10458 {
   10459     SECStatus rv;
   10460 
   10461     PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
   10462 
   10463     if (ss->sec.isServer) {
   10464 	PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
   10465 	return SECFailure;
   10466     }
   10467 
   10468     ssl_GetRecvBufLock(ss);
   10469     ssl_GetSSL3HandshakeLock(ss);
   10470 
   10471     if (!ss->ssl3.hs.authCertificatePending) {
   10472 	PORT_SetError(PR_INVALID_STATE_ERROR);
   10473 	rv = SECFailure;
   10474 	goto done;
   10475     }
   10476 
   10477     ss->ssl3.hs.authCertificatePending = PR_FALSE;
   10478 
   10479     if (error != 0) {
   10480 	ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
   10481 	ssl3_SendAlertForCertError(ss, error);
   10482 	rv = SECSuccess;
   10483     } else if (ss->ssl3.hs.restartTarget != NULL) {
   10484 	sslRestartTarget target = ss->ssl3.hs.restartTarget;
   10485 	ss->ssl3.hs.restartTarget = NULL;
   10486 
   10487 	if (target == ssl3_FinishHandshake) {
   10488 	    SSL_TRC(3,("%d: SSL3[%p]: certificate authentication lost the race"
   10489 		       " with peer's finished message", SSL_GETPID(), ss->fd));
   10490 	}
   10491 
   10492 	rv = target(ss);
   10493 	/* Even if we blocked here, we have accomplished enough to claim
   10494 	 * success. Any remaining work will be taken care of by subsequent
   10495 	 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
   10496 	 */
   10497 	if (rv == SECWouldBlock) {
   10498 	    rv = SECSuccess;
   10499 	}
   10500     } else {
   10501 	SSL_TRC(3, ("%d: SSL3[%p]: certificate authentication won the race with"
   10502         	    " peer's finished message", SSL_GETPID(), ss->fd));
   10503 
   10504 	PORT_Assert(!ss->firstHsDone);
   10505 	PORT_Assert(!ss->sec.isServer);
   10506 	PORT_Assert(!ss->ssl3.hs.isResuming);
   10507 	PORT_Assert(ss->ssl3.hs.ws != idle_handshake);
   10508 
   10509 	if (ss->opt.enableFalseStart &&
   10510 	    !ss->firstHsDone &&
   10511 	    !ss->sec.isServer &&
   10512 	    !ss->ssl3.hs.isResuming &&
   10513 	    ssl3_WaitingForStartOfServerSecondRound(ss)) {
   10514 	    /* ssl3_SendClientSecondRound deferred the false start check because
   10515 	     * certificate authentication was pending, so we do it now if we still
   10516 	     * haven't received any of the server's second round yet.
   10517 	     */
   10518 	    rv = ssl3_CheckFalseStart(ss);
   10519 	} else {
   10520 	    rv = SECSuccess;
   10521 	}
   10522     }
   10523 
   10524 done:
   10525     ssl_ReleaseSSL3HandshakeLock(ss);
   10526     ssl_ReleaseRecvBufLock(ss);
   10527 
   10528     return rv;
   10529 }
   10530 
   10531 static SECStatus
   10532 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
   10533 			PRBool          isServer,
   10534                 const   SSL3Hashes   *  hashes,
   10535                         TLSFinished  *  tlsFinished)
   10536 {
   10537     const char * label;
   10538     unsigned int len;
   10539     SECStatus    rv;
   10540 
   10541     label = isServer ? "server finished" : "client finished";
   10542     len   = 15;
   10543 
   10544     rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
   10545 	hashes->len, tlsFinished->verify_data,
   10546 	sizeof tlsFinished->verify_data);
   10547 
   10548     return rv;
   10549 }
   10550 
   10551 /* The calling function must acquire and release the appropriate
   10552  * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
   10553  * ss->ssl3.crSpec).
   10554  */
   10555 SECStatus
   10556 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
   10557     unsigned int labelLen, const unsigned char *val, unsigned int valLen,
   10558     unsigned char *out, unsigned int outLen)
   10559 {
   10560     SECStatus rv = SECSuccess;
   10561 
   10562     if (spec->master_secret && !spec->bypassCiphers) {
   10563 	SECItem param = {siBuffer, NULL, 0};
   10564 	CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
   10565 	PK11Context *prf_context;
   10566 	unsigned int retLen;
   10567 
   10568 	if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   10569 	    mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
   10570 	}
   10571 	prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
   10572 						 spec->master_secret, &param);
   10573 	if (!prf_context)
   10574 	    return SECFailure;
   10575 
   10576 	rv  = PK11_DigestBegin(prf_context);
   10577 	rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
   10578 	rv |= PK11_DigestOp(prf_context, val, valLen);
   10579 	rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
   10580 	PORT_Assert(rv != SECSuccess || retLen == outLen);
   10581 
   10582 	PK11_DestroyContext(prf_context, PR_TRUE);
   10583     } else {
   10584 	/* bypass PKCS11 */
   10585 #ifdef NO_PKCS11_BYPASS
   10586 	PORT_Assert(spec->master_secret);
   10587 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   10588 	rv = SECFailure;
   10589 #else
   10590 	SECItem inData  = { siBuffer, };
   10591 	SECItem outData = { siBuffer, };
   10592 	PRBool isFIPS   = PR_FALSE;
   10593 
   10594 	inData.data  = (unsigned char *) val;
   10595 	inData.len   = valLen;
   10596 	outData.data = out;
   10597 	outData.len  = outLen;
   10598 	if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   10599 	    rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
   10600 			    &outData, isFIPS);
   10601 	} else {
   10602 	    rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
   10603 	}
   10604 	PORT_Assert(rv != SECSuccess || outData.len == outLen);
   10605 #endif
   10606     }
   10607     return rv;
   10608 }
   10609 
   10610 /* called from ssl3_HandleServerHelloDone
   10611  */
   10612 static SECStatus
   10613 ssl3_SendNextProto(sslSocket *ss)
   10614 {
   10615     SECStatus rv;
   10616     int padding_len;
   10617     static const unsigned char padding[32] = {0};
   10618 
   10619     if (ss->ssl3.nextProto.len == 0 ||
   10620         ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
   10621 	return SECSuccess;
   10622     }
   10623 
   10624     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   10625     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10626 
   10627     padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
   10628 
   10629     rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
   10630 						    2 + padding_len);
   10631     if (rv != SECSuccess) {
   10632 	return rv;	/* error code set by AppendHandshakeHeader */
   10633     }
   10634     rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
   10635 				      ss->ssl3.nextProto.len, 1);
   10636     if (rv != SECSuccess) {
   10637 	return rv;	/* error code set by AppendHandshake */
   10638     }
   10639     rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
   10640     if (rv != SECSuccess) {
   10641 	return rv;	/* error code set by AppendHandshake */
   10642     }
   10643     return rv;
   10644 }
   10645 
   10646 /* called from ssl3_SendFinished
   10647  *
   10648  * This function is simply a debugging aid and therefore does not return a
   10649  * SECStatus. */
   10650 static void
   10651 ssl3_RecordKeyLog(sslSocket *ss)
   10652 {
   10653     SECStatus rv;
   10654     SECItem *keyData;
   10655     char buf[14 /* "CLIENT_RANDOM " */ +
   10656 	     SSL3_RANDOM_LENGTH*2 /* client_random */ +
   10657 	     1 /* " " */ +
   10658 	     48*2 /* master secret */ +
   10659              1 /* new line */];
   10660     unsigned int j;
   10661 
   10662     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10663 
   10664     if (!ssl_keylog_iob)
   10665 	return;
   10666 
   10667     rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
   10668     if (rv != SECSuccess)
   10669 	return;
   10670 
   10671     ssl_GetSpecReadLock(ss);
   10672 
   10673     /* keyData does not need to be freed. */
   10674     keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
   10675     if (!keyData || !keyData->data || keyData->len != 48) {
   10676 	ssl_ReleaseSpecReadLock(ss);
   10677 	return;
   10678     }
   10679 
   10680     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
   10681 
   10682     /* There could be multiple, concurrent writers to the
   10683      * keylog, so we have to do everything in a single call to
   10684      * fwrite. */
   10685 
   10686     memcpy(buf, "CLIENT_RANDOM ", 14);
   10687     j = 14;
   10688     hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
   10689     j += SSL3_RANDOM_LENGTH*2;
   10690     buf[j++] = ' ';
   10691     hexEncode(buf + j, keyData->data, 48);
   10692     j += 48*2;
   10693     buf[j++] = '\n';
   10694 
   10695     PORT_Assert(j == sizeof(buf));
   10696 
   10697     ssl_ReleaseSpecReadLock(ss);
   10698 
   10699     if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
   10700         return;
   10701     fflush(ssl_keylog_iob);
   10702     return;
   10703 }
   10704 
   10705 /* called from ssl3_SendClientSecondRound
   10706  *	     ssl3_HandleFinished
   10707  */
   10708 static SECStatus
   10709 ssl3_SendEncryptedExtensions(sslSocket *ss)
   10710 {
   10711     static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature";
   10712     static const char CHANNEL_ID_RESUMPTION_MAGIC[] = "Resumption";
   10713     /* This is the ASN.1 prefix for a P-256 public key. Specifically it's:
   10714      * SEQUENCE
   10715      *   SEQUENCE
   10716      *     OID id-ecPublicKey
   10717      *     OID prime256v1
   10718      *   BIT STRING, length 66, 0 trailing bits: 0x04
   10719      *
   10720      * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
   10721      * public key. Following that are the two field elements as 32-byte,
   10722      * big-endian numbers, as required by the Channel ID. */
   10723     static const unsigned char P256_SPKI_PREFIX[] = {
   10724 	0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
   10725 	0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
   10726 	0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
   10727 	0x42, 0x00, 0x04
   10728     };
   10729     /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64
   10730      * bytes of ECDSA signature. */
   10731     static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64;
   10732     static const int CHANNEL_ID_LENGTH = 128;
   10733 
   10734     SECStatus rv = SECFailure;
   10735     SECItem *spki = NULL;
   10736     SSL3Hashes hashes;
   10737     const unsigned char *pub_bytes;
   10738     unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) +
   10739                               sizeof(CHANNEL_ID_RESUMPTION_MAGIC) +
   10740                               sizeof(SSL3Hashes)*2];
   10741     size_t signed_data_len;
   10742     unsigned char digest[SHA256_LENGTH];
   10743     SECItem digest_item;
   10744     unsigned char signature[64];
   10745     SECItem signature_item;
   10746 
   10747     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   10748     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10749 
   10750     if (ss->ssl3.channelID == NULL)
   10751 	return SECSuccess;
   10752 
   10753     PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn));
   10754 
   10755     if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey ||
   10756 	PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) {
   10757 	PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
   10758 	rv = SECFailure;
   10759 	goto loser;
   10760     }
   10761 
   10762     ssl_GetSpecReadLock(ss);
   10763     rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
   10764     ssl_ReleaseSpecReadLock(ss);
   10765 
   10766     if (rv != SECSuccess)
   10767 	goto loser;
   10768 
   10769     rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions,
   10770 				    2 + 2 + CHANNEL_ID_LENGTH);
   10771     if (rv != SECSuccess)
   10772 	goto loser;	/* error code set by AppendHandshakeHeader */
   10773     rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
   10774     if (rv != SECSuccess)
   10775 	goto loser;	/* error code set by AppendHandshake */
   10776     rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2);
   10777     if (rv != SECSuccess)
   10778 	goto loser;	/* error code set by AppendHandshake */
   10779 
   10780     spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub);
   10781 
   10782     if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH ||
   10783 	memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX)) != 0) {
   10784 	PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
   10785 	rv = SECFailure;
   10786 	goto loser;
   10787     }
   10788 
   10789     pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX);
   10790 
   10791     signed_data_len = 0;
   10792     memcpy(signed_data + signed_data_len, CHANNEL_ID_MAGIC,
   10793            sizeof(CHANNEL_ID_MAGIC));
   10794     signed_data_len += sizeof(CHANNEL_ID_MAGIC);
   10795     if (ss->ssl3.hs.isResuming) {
   10796         SECItem *originalHandshakeHash =
   10797             &ss->sec.ci.sid->u.ssl3.originalHandshakeHash;
   10798         PORT_Assert(originalHandshakeHash->len > 0);
   10799 
   10800         memcpy(signed_data + signed_data_len, CHANNEL_ID_RESUMPTION_MAGIC,
   10801                sizeof(CHANNEL_ID_RESUMPTION_MAGIC));
   10802         signed_data_len += sizeof(CHANNEL_ID_RESUMPTION_MAGIC);
   10803         memcpy(signed_data + signed_data_len, originalHandshakeHash->data,
   10804                originalHandshakeHash->len);
   10805         signed_data_len += originalHandshakeHash->len;
   10806     }
   10807     memcpy(signed_data + signed_data_len, hashes.u.raw, hashes.len);
   10808     signed_data_len += hashes.len;
   10809 
   10810     rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data, signed_data_len);
   10811     if (rv != SECSuccess)
   10812 	goto loser;
   10813 
   10814     digest_item.data = digest;
   10815     digest_item.len = sizeof(digest);
   10816 
   10817     signature_item.data = signature;
   10818     signature_item.len = sizeof(signature);
   10819 
   10820     rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item);
   10821     if (rv != SECSuccess)
   10822 	goto loser;
   10823 
   10824     rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH);
   10825     if (rv != SECSuccess)
   10826 	goto loser;
   10827     rv = ssl3_AppendHandshake(ss, signature, sizeof(signature));
   10828 
   10829 loser:
   10830     if (spki)
   10831 	SECITEM_FreeItem(spki, PR_TRUE);
   10832     if (ss->ssl3.channelID) {
   10833 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   10834 	ss->ssl3.channelID = NULL;
   10835     }
   10836     if (ss->ssl3.channelIDPub) {
   10837 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   10838 	ss->ssl3.channelIDPub = NULL;
   10839     }
   10840 
   10841     return rv;
   10842 }
   10843 
   10844 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake
   10845  * after a ChannelID callback returned SECWouldBlock. At this point we have
   10846  * processed the server's ServerHello but not yet any further messages. We will
   10847  * always get a message from the server after a ServerHello so either they are
   10848  * waiting in the buffer or we'll get network I/O. */
   10849 SECStatus
   10850 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss,
   10851 				       SECKEYPublicKey *channelIDPub,
   10852 				       SECKEYPrivateKey *channelID)
   10853 {
   10854     if (ss->handshake == 0) {
   10855 	SECKEY_DestroyPublicKey(channelIDPub);
   10856 	SECKEY_DestroyPrivateKey(channelID);
   10857 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   10858 	return SECFailure;
   10859     }
   10860 
   10861     if (channelIDPub == NULL ||
   10862 	channelID == NULL) {
   10863 	if (channelIDPub)
   10864 	    SECKEY_DestroyPublicKey(channelIDPub);
   10865 	if (channelID)
   10866 	    SECKEY_DestroyPrivateKey(channelID);
   10867 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   10868 	return SECFailure;
   10869     }
   10870 
   10871     if (ss->ssl3.channelID)
   10872 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   10873     if (ss->ssl3.channelIDPub)
   10874 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   10875 
   10876     ss->handshake = ssl_GatherRecord1stHandshake;
   10877     ss->ssl3.channelID = channelID;
   10878     ss->ssl3.channelIDPub = channelIDPub;
   10879 
   10880     return SECSuccess;
   10881 }
   10882 
   10883 /* called from ssl3_HandleServerHelloDone
   10884  *             ssl3_HandleClientHello
   10885  *             ssl3_HandleFinished
   10886  */
   10887 static SECStatus
   10888 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
   10889 {
   10890     ssl3CipherSpec *cwSpec;
   10891     PRBool          isTLS;
   10892     PRBool          isServer = ss->sec.isServer;
   10893     SECStatus       rv;
   10894     SSL3Sender      sender = isServer ? sender_server : sender_client;
   10895     SSL3Hashes      hashes;
   10896     TLSFinished     tlsFinished;
   10897 
   10898     SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
   10899 
   10900     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   10901     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10902 
   10903     ssl_GetSpecReadLock(ss);
   10904     cwSpec = ss->ssl3.cwSpec;
   10905     isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
   10906     rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
   10907     if (isTLS && rv == SECSuccess) {
   10908 	rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
   10909     }
   10910     ssl_ReleaseSpecReadLock(ss);
   10911     if (rv != SECSuccess) {
   10912 	goto fail;	/* err code was set by ssl3_ComputeHandshakeHashes */
   10913     }
   10914 
   10915     if (isTLS) {
   10916 	if (isServer)
   10917 	    ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
   10918 	else
   10919 	    ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
   10920 	ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
   10921 	rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
   10922 	if (rv != SECSuccess)
   10923 	    goto fail; 		/* err set by AppendHandshake. */
   10924 	rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
   10925 	if (rv != SECSuccess)
   10926 	    goto fail; 		/* err set by AppendHandshake. */
   10927     } else {
   10928 	if (isServer)
   10929 	    ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
   10930 	else
   10931 	    ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
   10932 	PORT_Assert(hashes.len == sizeof hashes.u.s);
   10933 	ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
   10934 	rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
   10935 	if (rv != SECSuccess)
   10936 	    goto fail; 		/* err set by AppendHandshake. */
   10937 	rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
   10938 	if (rv != SECSuccess)
   10939 	    goto fail; 		/* err set by AppendHandshake. */
   10940     }
   10941     rv = ssl3_FlushHandshake(ss, flags);
   10942     if (rv != SECSuccess) {
   10943 	goto fail;	/* error code set by ssl3_FlushHandshake */
   10944     }
   10945 
   10946     ssl3_RecordKeyLog(ss);
   10947 
   10948     return SECSuccess;
   10949 
   10950 fail:
   10951     return rv;
   10952 }
   10953 
   10954 /* wrap the master secret, and put it into the SID.
   10955  * Caller holds the Spec read lock.
   10956  */
   10957 SECStatus
   10958 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
   10959     ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
   10960 {
   10961     PK11SymKey *      wrappingKey  = NULL;
   10962     PK11SlotInfo *    symKeySlot;
   10963     void *            pwArg        = ss->pkcs11PinArg;
   10964     SECStatus         rv           = SECFailure;
   10965     PRBool            isServer     = ss->sec.isServer;
   10966     CK_MECHANISM_TYPE mechanism    = CKM_INVALID_MECHANISM;
   10967     symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
   10968     if (!isServer) {
   10969 	int  wrapKeyIndex;
   10970 	int  incarnation;
   10971 
   10972 	/* these next few functions are mere accessors and don't fail. */
   10973 	sid->u.ssl3.masterWrapIndex  = wrapKeyIndex =
   10974 				       PK11_GetCurrentWrapIndex(symKeySlot);
   10975 	PORT_Assert(wrapKeyIndex == 0);	/* array has only one entry! */
   10976 
   10977 	sid->u.ssl3.masterWrapSeries = incarnation =
   10978 				       PK11_GetSlotSeries(symKeySlot);
   10979 	sid->u.ssl3.masterSlotID   = PK11_GetSlotID(symKeySlot);
   10980 	sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
   10981 	sid->u.ssl3.masterValid    = PR_TRUE;
   10982 	/* Get the default wrapping key, for wrapping the master secret before
   10983 	 * placing it in the SID cache entry. */
   10984 	wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
   10985 				      CKM_INVALID_MECHANISM, incarnation,
   10986 				      pwArg);
   10987 	if (wrappingKey) {
   10988 	    mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
   10989 	} else {
   10990 	    int keyLength;
   10991 	    /* if the wrappingKey doesn't exist, attempt to create it.
   10992 	     * Note: we intentionally ignore errors here.  If we cannot
   10993 	     * generate a wrapping key, it is not fatal to this SSL connection,
   10994 	     * but we will not be able to restart this session.
   10995 	     */
   10996 	    mechanism = PK11_GetBestWrapMechanism(symKeySlot);
   10997 	    keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
   10998 	    /* Zero length means fixed key length algorithm, or error.
   10999 	     * It's ambiguous.
   11000 	     */
   11001 	    wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
   11002 				      keyLength, pwArg);
   11003 	    if (wrappingKey) {
   11004 		PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
   11005 	    }
   11006 	}
   11007     } else {
   11008 	/* server socket using session cache. */
   11009 	mechanism = PK11_GetBestWrapMechanism(symKeySlot);
   11010 	if (mechanism != CKM_INVALID_MECHANISM) {
   11011 	    wrappingKey =
   11012 		getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
   11013 			       mechanism, pwArg);
   11014 	    if (wrappingKey) {
   11015 		mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
   11016 	    }
   11017 	}
   11018     }
   11019 
   11020     sid->u.ssl3.masterWrapMech = mechanism;
   11021     PK11_FreeSlot(symKeySlot);
   11022 
   11023     if (wrappingKey) {
   11024 	SECItem wmsItem;
   11025 
   11026 	wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
   11027 	wmsItem.len  = sizeof sid->u.ssl3.keys.wrapped_master_secret;
   11028 	rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
   11029 			     spec->master_secret, &wmsItem);
   11030 	/* rv is examined below. */
   11031 	sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
   11032 	PK11_FreeSymKey(wrappingKey);
   11033     }
   11034     return rv;
   11035 }
   11036 
   11037 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   11038  * ssl3 Finished message from the peer.
   11039  * Caller must hold Handshake and RecvBuf locks.
   11040  */
   11041 static SECStatus
   11042 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
   11043 		    const SSL3Hashes *hashes)
   11044 {
   11045     sslSessionID *    sid	   = ss->sec.ci.sid;
   11046     SECStatus         rv           = SECSuccess;
   11047     PRBool            isServer     = ss->sec.isServer;
   11048     PRBool            isTLS;
   11049     SSL3KEAType       effectiveExchKeyType;
   11050 
   11051     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   11052     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   11053 
   11054     SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
   11055     	SSL_GETPID(), ss->fd));
   11056 
   11057     if (ss->ssl3.hs.ws != wait_finished) {
   11058 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11059     	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
   11060 	return SECFailure;
   11061     }
   11062 
   11063     isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
   11064     if (isTLS) {
   11065 	TLSFinished tlsFinished;
   11066 
   11067 	if (length != sizeof tlsFinished) {
   11068 	    (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
   11069 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
   11070 	    return SECFailure;
   11071 	}
   11072 	rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
   11073 	                             hashes, &tlsFinished);
   11074 	if (!isServer)
   11075 	    ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
   11076 	else
   11077 	    ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
   11078 	ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
   11079 	if (rv != SECSuccess ||
   11080 	    0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
   11081 	    (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
   11082 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   11083 	    return SECFailure;
   11084 	}
   11085     } else {
   11086 	if (length != sizeof(SSL3Finished)) {
   11087 	    (void)ssl3_IllegalParameter(ss);
   11088 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
   11089 	    return SECFailure;
   11090 	}
   11091 
   11092 	if (!isServer)
   11093 	    ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
   11094 	else
   11095 	    ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
   11096 	PORT_Assert(hashes->len == sizeof hashes->u.s);
   11097 	ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
   11098 	if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
   11099 	    (void)ssl3_HandshakeFailure(ss);
   11100 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   11101 	    return SECFailure;
   11102 	}
   11103     }
   11104 
   11105     ssl_GetXmitBufLock(ss);	/*************************************/
   11106 
   11107     if ((isServer && !ss->ssl3.hs.isResuming) ||
   11108 	(!isServer && ss->ssl3.hs.isResuming)) {
   11109 	PRInt32 flags = 0;
   11110 
   11111 	/* Send a NewSessionTicket message if the client sent us
   11112 	 * either an empty session ticket, or one that did not verify.
   11113 	 * (Note that if either of these conditions was met, then the
   11114 	 * server has sent a SessionTicket extension in the
   11115 	 * ServerHello message.)
   11116 	 */
   11117 	if (isServer && !ss->ssl3.hs.isResuming &&
   11118 	    ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
   11119 	    rv = ssl3_SendNewSessionTicket(ss);
   11120 	    if (rv != SECSuccess) {
   11121 		goto xmit_loser;
   11122 	    }
   11123 	}
   11124 
   11125 	rv = ssl3_SendChangeCipherSpecs(ss);
   11126 	if (rv != SECSuccess) {
   11127 	    goto xmit_loser;	/* err is set. */
   11128 	}
   11129 	/* If this thread is in SSL_SecureSend (trying to write some data)
   11130 	** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
   11131 	** last two handshake messages (change cipher spec and finished)
   11132 	** will be sent in the same send/write call as the application data.
   11133 	*/
   11134 	if (ss->writerThread == PR_GetCurrentThread()) {
   11135 	    flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
   11136 	}
   11137 
   11138 	if (!isServer) {
   11139 	    if (!ss->firstHsDone) {
   11140 		rv = ssl3_SendNextProto(ss);
   11141 		if (rv != SECSuccess) {
   11142 		    goto xmit_loser; /* err code was set. */
   11143 		}
   11144 	    }
   11145 	    rv = ssl3_SendEncryptedExtensions(ss);
   11146 	    if (rv != SECSuccess)
   11147 		goto xmit_loser; /* err code was set. */
   11148 	}
   11149 
   11150 	if (IS_DTLS(ss)) {
   11151 	    flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
   11152 	}
   11153 
   11154 	rv = ssl3_SendFinished(ss, flags);
   11155 	if (rv != SECSuccess) {
   11156 	    goto xmit_loser;	/* err is set. */
   11157 	}
   11158     }
   11159 
   11160 xmit_loser:
   11161     ssl_ReleaseXmitBufLock(ss);	/*************************************/
   11162     if (rv != SECSuccess) {
   11163         return rv;
   11164     }
   11165 
   11166     if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
   11167 	effectiveExchKeyType = kt_rsa;
   11168     } else {
   11169 	effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
   11170     }
   11171 
   11172     if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
   11173 	/* fill in the sid */
   11174 	sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
   11175 	sid->u.ssl3.compression = ss->ssl3.hs.compression;
   11176 	sid->u.ssl3.policy      = ss->ssl3.policy;
   11177 #ifdef NSS_ENABLE_ECC
   11178 	sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
   11179 #endif
   11180 	sid->u.ssl3.exchKeyType = effectiveExchKeyType;
   11181 	sid->version            = ss->version;
   11182 	sid->authAlgorithm      = ss->sec.authAlgorithm;
   11183 	sid->authKeyBits        = ss->sec.authKeyBits;
   11184 	sid->keaType            = ss->sec.keaType;
   11185 	sid->keaKeyBits         = ss->sec.keaKeyBits;
   11186 	sid->lastAccessTime     = sid->creationTime = ssl_Time();
   11187 	sid->expirationTime     = sid->creationTime + ssl3_sid_timeout;
   11188 	sid->localCert          = CERT_DupCertificate(ss->sec.localCert);
   11189 
   11190 	ssl_GetSpecReadLock(ss);	/*************************************/
   11191 
   11192 	/* Copy the master secret (wrapped or unwrapped) into the sid */
   11193 	if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
   11194 	    sid->u.ssl3.keys.wrapped_master_secret_len =
   11195 			    ss->ssl3.crSpec->msItem.len;
   11196 	    memcpy(sid->u.ssl3.keys.wrapped_master_secret,
   11197 		   ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
   11198 	    sid->u.ssl3.masterValid    = PR_TRUE;
   11199 	    sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
   11200 	    rv = SECSuccess;
   11201 	} else {
   11202 	    rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
   11203 					       ss->ssl3.crSpec,
   11204 					       effectiveExchKeyType);
   11205 	    sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
   11206 	}
   11207 	ssl_ReleaseSpecReadLock(ss);  /*************************************/
   11208 
   11209 	/* If the wrap failed, we don't cache the sid.
   11210 	 * The connection continues normally however.
   11211 	 */
   11212 	ss->ssl3.hs.cacheSID = rv == SECSuccess;
   11213     }
   11214 
   11215     if (ss->ssl3.hs.authCertificatePending) {
   11216 	if (ss->ssl3.hs.restartTarget) {
   11217 	    PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
   11218 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   11219 	    return SECFailure;
   11220 	}
   11221 
   11222 	ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
   11223 	return SECWouldBlock;
   11224     }
   11225 
   11226     rv = ssl3_FinishHandshake(ss);
   11227     return rv;
   11228 }
   11229 
   11230 /* The return type is SECStatus instead of void because this function needs
   11231  * to have type sslRestartTarget.
   11232  */
   11233 SECStatus
   11234 ssl3_FinishHandshake(sslSocket * ss)
   11235 {
   11236     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   11237     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   11238     PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
   11239 
   11240     /* The first handshake is now completed. */
   11241     ss->handshake           = NULL;
   11242 
   11243     if (ss->ssl3.hs.cacheSID && ss->sec.isServer) {
   11244 	(*ss->sec.cache)(ss->sec.ci.sid);
   11245 	ss->ssl3.hs.cacheSID = PR_FALSE;
   11246     }
   11247 
   11248     ss->ssl3.hs.canFalseStart = PR_FALSE; /* False Start phase is complete */
   11249     ss->ssl3.hs.ws = idle_handshake;
   11250 
   11251     ssl_FinishHandshake(ss);
   11252 
   11253     return SECSuccess;
   11254 }
   11255 
   11256 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
   11257  * hanshake message.
   11258  * Caller must hold Handshake and RecvBuf locks.
   11259  */
   11260 SECStatus
   11261 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   11262 {
   11263     SECStatus         rv 	= SECSuccess;
   11264     SSL3HandshakeType type 	= ss->ssl3.hs.msg_type;
   11265     SSL3Hashes        hashes;	/* computed hashes are put here. */
   11266     PRUint8           hdr[4];
   11267     PRUint8           dtlsData[8];
   11268 
   11269     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   11270     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   11271     /*
   11272      * We have to compute the hashes before we update them with the
   11273      * current message.
   11274      */
   11275     ssl_GetSpecReadLock(ss);	/************************************/
   11276     if((type == finished) || (type == certificate_verify)) {
   11277 	SSL3Sender      sender = (SSL3Sender)0;
   11278 	ssl3CipherSpec *rSpec  = ss->ssl3.prSpec;
   11279 
   11280 	if (type == finished) {
   11281 	    sender = ss->sec.isServer ? sender_client : sender_server;
   11282 	    rSpec  = ss->ssl3.crSpec;
   11283 	}
   11284 	rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
   11285     }
   11286     ssl_ReleaseSpecReadLock(ss); /************************************/
   11287     if (rv != SECSuccess) {
   11288 	return rv;	/* error code was set by ssl3_ComputeHandshakeHashes*/
   11289     }
   11290     SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
   11291 		ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
   11292 
   11293     hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
   11294     hdr[1] = (PRUint8)(length >> 16);
   11295     hdr[2] = (PRUint8)(length >>  8);
   11296     hdr[3] = (PRUint8)(length      );
   11297 
   11298     /* Start new handshake hashes when we start a new handshake */
   11299     if (ss->ssl3.hs.msg_type == client_hello) {
   11300 	rv = ssl3_RestartHandshakeHashes(ss);
   11301 	if (rv != SECSuccess) {
   11302 	    return rv;
   11303 	}
   11304     }
   11305     /* We should not include hello_request and hello_verify_request messages
   11306      * in the handshake hashes */
   11307     if ((ss->ssl3.hs.msg_type != hello_request) &&
   11308 	(ss->ssl3.hs.msg_type != hello_verify_request)) {
   11309 	rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
   11310 	if (rv != SECSuccess) return rv;	/* err code already set. */
   11311 
   11312 	/* Extra data to simulate a complete DTLS handshake fragment */
   11313 	if (IS_DTLS(ss)) {
   11314 	    /* Sequence number */
   11315 	    dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
   11316 	    dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
   11317 
   11318 	    /* Fragment offset */
   11319 	    dtlsData[2] = 0;
   11320 	    dtlsData[3] = 0;
   11321 	    dtlsData[4] = 0;
   11322 
   11323 	    /* Fragment length */
   11324 	    dtlsData[5] = (PRUint8)(length >> 16);
   11325 	    dtlsData[6] = (PRUint8)(length >>  8);
   11326 	    dtlsData[7] = (PRUint8)(length      );
   11327 
   11328 	    rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
   11329 					    sizeof(dtlsData));
   11330 	    if (rv != SECSuccess) return rv;	/* err code already set. */
   11331 	}
   11332 
   11333 	/* The message body */
   11334 	rv = ssl3_UpdateHandshakeHashes(ss, b, length);
   11335 	if (rv != SECSuccess) return rv;	/* err code already set. */
   11336     }
   11337 
   11338     PORT_SetError(0);	/* each message starts with no error. */
   11339 
   11340     if (ss->ssl3.hs.ws == wait_certificate_status &&
   11341         ss->ssl3.hs.msg_type != certificate_status) {
   11342         /* If we negotiated the certificate_status extension then we deferred
   11343          * certificate validation until we get the CertificateStatus messsage.
   11344          * But the CertificateStatus message is optional. If the server did
   11345          * not send it then we need to validate the certificate now. If the
   11346          * server does send the CertificateStatus message then we will
   11347          * authenticate the certificate in ssl3_HandleCertificateStatus.
   11348          */
   11349         rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
   11350         PORT_Assert(rv != SECWouldBlock);
   11351         if (rv != SECSuccess) {
   11352             return rv;
   11353         }
   11354     }
   11355 
   11356     switch (ss->ssl3.hs.msg_type) {
   11357     case hello_request:
   11358 	if (length != 0) {
   11359 	    (void)ssl3_DecodeError(ss);
   11360 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
   11361 	    return SECFailure;
   11362 	}
   11363 	if (ss->sec.isServer) {
   11364 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11365 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
   11366 	    return SECFailure;
   11367 	}
   11368 	rv = ssl3_HandleHelloRequest(ss);
   11369 	break;
   11370     case client_hello:
   11371 	if (!ss->sec.isServer) {
   11372 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11373 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
   11374 	    return SECFailure;
   11375 	}
   11376 	rv = ssl3_HandleClientHello(ss, b, length);
   11377 	break;
   11378     case server_hello:
   11379 	if (ss->sec.isServer) {
   11380 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11381 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
   11382 	    return SECFailure;
   11383 	}
   11384 	rv = ssl3_HandleServerHello(ss, b, length);
   11385 	break;
   11386     case hello_verify_request:
   11387 	if (!IS_DTLS(ss) || ss->sec.isServer) {
   11388 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11389 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
   11390 	    return SECFailure;
   11391 	}
   11392 	rv = dtls_HandleHelloVerifyRequest(ss, b, length);
   11393 	break;
   11394     case certificate:
   11395 	rv = ssl3_HandleCertificate(ss, b, length);
   11396 	break;
   11397     case certificate_status:
   11398 	rv = ssl3_HandleCertificateStatus(ss, b, length);
   11399 	break;
   11400     case server_key_exchange:
   11401 	if (ss->sec.isServer) {
   11402 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11403 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
   11404 	    return SECFailure;
   11405 	}
   11406 	rv = ssl3_HandleServerKeyExchange(ss, b, length);
   11407 	break;
   11408     case certificate_request:
   11409 	if (ss->sec.isServer) {
   11410 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11411 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
   11412 	    return SECFailure;
   11413 	}
   11414 	rv = ssl3_HandleCertificateRequest(ss, b, length);
   11415 	break;
   11416     case server_hello_done:
   11417 	if (length != 0) {
   11418 	    (void)ssl3_DecodeError(ss);
   11419 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
   11420 	    return SECFailure;
   11421 	}
   11422 	if (ss->sec.isServer) {
   11423 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11424 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
   11425 	    return SECFailure;
   11426 	}
   11427 	rv = ssl3_HandleServerHelloDone(ss);
   11428 	break;
   11429     case certificate_verify:
   11430 	if (!ss->sec.isServer) {
   11431 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11432 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
   11433 	    return SECFailure;
   11434 	}
   11435 	rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
   11436 	break;
   11437     case client_key_exchange:
   11438 	if (!ss->sec.isServer) {
   11439 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11440 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
   11441 	    return SECFailure;
   11442 	}
   11443 	rv = ssl3_HandleClientKeyExchange(ss, b, length);
   11444 	break;
   11445     case new_session_ticket:
   11446 	if (ss->sec.isServer) {
   11447 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11448 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
   11449 	    return SECFailure;
   11450 	}
   11451 	rv = ssl3_HandleNewSessionTicket(ss, b, length);
   11452 	break;
   11453     case finished:
   11454         rv = ssl3_HandleFinished(ss, b, length, &hashes);
   11455 	break;
   11456     default:
   11457 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11458 	PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
   11459 	rv = SECFailure;
   11460     }
   11461 
   11462     if (IS_DTLS(ss) && (rv != SECFailure)) {
   11463 	/* Increment the expected sequence number */
   11464 	ss->ssl3.hs.recvMessageSeq++;
   11465     }
   11466 
   11467     return rv;
   11468 }
   11469 
   11470 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
   11471  * origBuf is the decrypted ssl record content.
   11472  * Caller must hold the handshake and RecvBuf locks.
   11473  */
   11474 static SECStatus
   11475 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
   11476 {
   11477     /*
   11478      * There may be a partial handshake message already in the handshake
   11479      * state. The incoming buffer may contain another portion, or a
   11480      * complete message or several messages followed by another portion.
   11481      *
   11482      * Each message is made contiguous before being passed to the actual
   11483      * message parser.
   11484      */
   11485     sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
   11486     SECStatus rv;
   11487 
   11488     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   11489     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   11490 
   11491     if (buf->buf == NULL) {
   11492 	*buf = *origBuf;
   11493     }
   11494     while (buf->len > 0) {
   11495 	if (ss->ssl3.hs.header_bytes < 4) {
   11496 	    PRUint8 t;
   11497 	    t = *(buf->buf++);
   11498 	    buf->len--;
   11499 	    if (ss->ssl3.hs.header_bytes++ == 0)
   11500 		ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
   11501 	    else
   11502 		ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
   11503 	    if (ss->ssl3.hs.header_bytes < 4)
   11504 	    	continue;
   11505 
   11506 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff	/* 128k - 1 */
   11507 	    if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
   11508 		(void)ssl3_DecodeError(ss);
   11509 		PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
   11510 		return SECFailure;
   11511 	    }
   11512 #undef MAX_HANDSHAKE_MSG_LEN
   11513 
   11514 	    /* If msg_len is zero, be sure we fall through,
   11515 	    ** even if buf->len is zero.
   11516 	    */
   11517 	    if (ss->ssl3.hs.msg_len > 0)
   11518 	    	continue;
   11519 	}
   11520 
   11521 	/*
   11522 	 * Header has been gathered and there is at least one byte of new
   11523 	 * data available for this message. If it can be done right out
   11524 	 * of the original buffer, then use it from there.
   11525 	 */
   11526 	if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
   11527 	    /* handle it from input buffer */
   11528 	    rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
   11529 	    if (rv == SECFailure) {
   11530 		/* This test wants to fall through on either
   11531 		 * SECSuccess or SECWouldBlock.
   11532 		 * ssl3_HandleHandshakeMessage MUST set the error code.
   11533 		 */
   11534 		return rv;
   11535 	    }
   11536 	    buf->buf += ss->ssl3.hs.msg_len;
   11537 	    buf->len -= ss->ssl3.hs.msg_len;
   11538 	    ss->ssl3.hs.msg_len = 0;
   11539 	    ss->ssl3.hs.header_bytes = 0;
   11540 	    if (rv != SECSuccess) { /* return if SECWouldBlock. */
   11541 		return rv;
   11542 	    }
   11543 	} else {
   11544 	    /* must be copied to msg_body and dealt with from there */
   11545 	    unsigned int bytes;
   11546 
   11547 	    PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
   11548 	    bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
   11549 
   11550 	    /* Grow the buffer if needed */
   11551 	    rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
   11552 	    if (rv != SECSuccess) {
   11553 		/* sslBuffer_Grow has set a memory error code. */
   11554 		return SECFailure;
   11555 	    }
   11556 
   11557 	    PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
   11558 		        buf->buf, bytes);
   11559 	    ss->ssl3.hs.msg_body.len += bytes;
   11560 	    buf->buf += bytes;
   11561 	    buf->len -= bytes;
   11562 
   11563 	    PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
   11564 
   11565 	    /* if we have a whole message, do it */
   11566 	    if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
   11567 		rv = ssl3_HandleHandshakeMessage(
   11568 		    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
   11569 		if (rv == SECFailure) {
   11570 		    /* This test wants to fall through on either
   11571 		     * SECSuccess or SECWouldBlock.
   11572 		     * ssl3_HandleHandshakeMessage MUST set error code.
   11573 		     */
   11574 		    return rv;
   11575 		}
   11576 		ss->ssl3.hs.msg_body.len = 0;
   11577 		ss->ssl3.hs.msg_len = 0;
   11578 		ss->ssl3.hs.header_bytes = 0;
   11579 		if (rv != SECSuccess) { /* return if SECWouldBlock. */
   11580 		    return rv;
   11581 		}
   11582 	    } else {
   11583 		PORT_Assert(buf->len == 0);
   11584 		break;
   11585 	    }
   11586 	}
   11587     }	/* end loop */
   11588 
   11589     origBuf->len = 0;	/* So ssl3_GatherAppDataRecord will keep looping. */
   11590     buf->buf = NULL;	/* not a leak. */
   11591     return SECSuccess;
   11592 }
   11593 
   11594 /* These macros return the given value with the MSB copied to all the other
   11595  * bits. They use the fact that arithmetic shift shifts-in the sign bit.
   11596  * However, this is not ensured by the C standard so you may need to replace
   11597  * them with something else for odd compilers. */
   11598 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
   11599 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
   11600 
   11601 /* SECStatusToMask returns, in constant time, a mask value of all ones if
   11602  * rv == SECSuccess.  Otherwise it returns zero. */
   11603 static unsigned int
   11604 SECStatusToMask(SECStatus rv)
   11605 {
   11606     unsigned int good;
   11607     /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
   11608      * in the MSB being set to one iff it was zero before. */
   11609     good = rv ^ SECSuccess;
   11610     good--;
   11611     return DUPLICATE_MSB_TO_ALL(good);
   11612 }
   11613 
   11614 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
   11615 static unsigned char
   11616 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
   11617 {
   11618     a -= b;
   11619     return DUPLICATE_MSB_TO_ALL(~a);
   11620 }
   11621 
   11622 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
   11623 static unsigned char
   11624 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
   11625 {
   11626     unsigned int c = a ^ b;
   11627     c--;
   11628     return DUPLICATE_MSB_TO_ALL_8(c);
   11629 }
   11630 
   11631 static SECStatus
   11632 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
   11633 			  unsigned int blockSize,
   11634 			  unsigned int macSize)
   11635 {
   11636     unsigned int paddingLength, good, t;
   11637     const unsigned int overhead = 1 /* padding length byte */ + macSize;
   11638 
   11639     /* These lengths are all public so we can test them in non-constant
   11640      * time. */
   11641     if (overhead > plaintext->len) {
   11642 	return SECFailure;
   11643     }
   11644 
   11645     paddingLength = plaintext->buf[plaintext->len-1];
   11646     /* SSLv3 padding bytes are random and cannot be checked. */
   11647     t = plaintext->len;
   11648     t -= paddingLength+overhead;
   11649     /* If len >= paddingLength+overhead then the MSB of t is zero. */
   11650     good = DUPLICATE_MSB_TO_ALL(~t);
   11651     /* SSLv3 requires that the padding is minimal. */
   11652     t = blockSize - (paddingLength+1);
   11653     good &= DUPLICATE_MSB_TO_ALL(~t);
   11654     plaintext->len -= good & (paddingLength+1);
   11655     return (good & SECSuccess) | (~good & SECFailure);
   11656 }
   11657 
   11658 static SECStatus
   11659 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
   11660 {
   11661     unsigned int paddingLength, good, t, toCheck, i;
   11662     const unsigned int overhead = 1 /* padding length byte */ + macSize;
   11663 
   11664     /* These lengths are all public so we can test them in non-constant
   11665      * time. */
   11666     if (overhead > plaintext->len) {
   11667 	return SECFailure;
   11668     }
   11669 
   11670     paddingLength = plaintext->buf[plaintext->len-1];
   11671     t = plaintext->len;
   11672     t -= paddingLength+overhead;
   11673     /* If len >= paddingLength+overhead then the MSB of t is zero. */
   11674     good = DUPLICATE_MSB_TO_ALL(~t);
   11675 
   11676     /* The padding consists of a length byte at the end of the record and then
   11677      * that many bytes of padding, all with the same value as the length byte.
   11678      * Thus, with the length byte included, there are paddingLength+1 bytes of
   11679      * padding.
   11680      *
   11681      * We can't check just |paddingLength+1| bytes because that leaks
   11682      * decrypted information. Therefore we always have to check the maximum
   11683      * amount of padding possible. (Again, the length of the record is
   11684      * public information so we can use it.) */
   11685     toCheck = 255; /* maximum amount of padding. */
   11686     if (toCheck > plaintext->len-1) {
   11687 	toCheck = plaintext->len-1;
   11688     }
   11689 
   11690     for (i = 0; i < toCheck; i++) {
   11691 	unsigned int t = paddingLength - i;
   11692 	/* If i <= paddingLength then the MSB of t is zero and mask is
   11693 	 * 0xff.  Otherwise, mask is 0. */
   11694 	unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
   11695 	unsigned char b = plaintext->buf[plaintext->len-1-i];
   11696 	/* The final |paddingLength+1| bytes should all have the value
   11697 	 * |paddingLength|. Therefore the XOR should be zero. */
   11698 	good &= ~(mask&(paddingLength ^ b));
   11699     }
   11700 
   11701     /* If any of the final |paddingLength+1| bytes had the wrong value,
   11702      * one or more of the lower eight bits of |good| will be cleared. We
   11703      * AND the bottom 8 bits together and duplicate the result to all the
   11704      * bits. */
   11705     good &= good >> 4;
   11706     good &= good >> 2;
   11707     good &= good >> 1;
   11708     good <<= sizeof(good)*8-1;
   11709     good = DUPLICATE_MSB_TO_ALL(good);
   11710 
   11711     plaintext->len -= good & (paddingLength+1);
   11712     return (good & SECSuccess) | (~good & SECFailure);
   11713 }
   11714 
   11715 /* On entry:
   11716  *   originalLength >= macSize
   11717  *   macSize <= MAX_MAC_LENGTH
   11718  *   plaintext->len >= macSize
   11719  */
   11720 static void
   11721 ssl_CBCExtractMAC(sslBuffer *plaintext,
   11722 		  unsigned int originalLength,
   11723 		  SSL3Opaque* out,
   11724 		  unsigned int macSize)
   11725 {
   11726     unsigned char rotatedMac[MAX_MAC_LENGTH];
   11727     /* macEnd is the index of |plaintext->buf| just after the end of the
   11728      * MAC. */
   11729     unsigned macEnd = plaintext->len;
   11730     unsigned macStart = macEnd - macSize;
   11731     /* scanStart contains the number of bytes that we can ignore because
   11732      * the MAC's position can only vary by 255 bytes. */
   11733     unsigned scanStart = 0;
   11734     unsigned i, j, divSpoiler;
   11735     unsigned char rotateOffset;
   11736 
   11737     if (originalLength > macSize + 255 + 1)
   11738 	scanStart = originalLength - (macSize + 255 + 1);
   11739 
   11740     /* divSpoiler contains a multiple of macSize that is used to cause the
   11741      * modulo operation to be constant time. Without this, the time varies
   11742      * based on the amount of padding when running on Intel chips at least.
   11743      *
   11744      * The aim of right-shifting macSize is so that the compiler doesn't
   11745      * figure out that it can remove divSpoiler as that would require it
   11746      * to prove that macSize is always even, which I hope is beyond it. */
   11747     divSpoiler = macSize >> 1;
   11748     divSpoiler <<= (sizeof(divSpoiler)-1)*8;
   11749     rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
   11750 
   11751     memset(rotatedMac, 0, macSize);
   11752     for (i = scanStart; i < originalLength;) {
   11753 	for (j = 0; j < macSize && i < originalLength; i++, j++) {
   11754 	    unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
   11755 	    unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
   11756 	    unsigned char b = 0;
   11757 	    b = plaintext->buf[i];
   11758 	    rotatedMac[j] |= b & macStarted & ~macEnded;
   11759 	}
   11760     }
   11761 
   11762     /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
   11763      * we could line-align |rotatedMac| and rotate in place. */
   11764     memset(out, 0, macSize);
   11765     for (i = 0; i < macSize; i++) {
   11766 	unsigned char offset =
   11767 	    (divSpoiler + macSize - rotateOffset + i) % macSize;
   11768 	for (j = 0; j < macSize; j++) {
   11769 	    out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
   11770 	}
   11771     }
   11772 }
   11773 
   11774 /* if cText is non-null, then decipher, check MAC, and decompress the
   11775  * SSL record from cText->buf (typically gs->inbuf)
   11776  * into databuf (typically gs->buf), and any previous contents of databuf
   11777  * is lost.  Then handle databuf according to its SSL record type,
   11778  * unless it's an application record.
   11779  *
   11780  * If cText is NULL, then the ciphertext has previously been deciphered and
   11781  * checked, and is already sitting in databuf.  It is processed as an SSL
   11782  * Handshake message.
   11783  *
   11784  * DOES NOT process the decrypted/decompressed application data.
   11785  * On return, databuf contains the decrypted/decompressed record.
   11786  *
   11787  * Called from ssl3_GatherCompleteHandshake
   11788  *             ssl3_RestartHandshakeAfterCertReq
   11789  *
   11790  * Caller must hold the RecvBufLock.
   11791  *
   11792  * This function aquires and releases the SSL3Handshake Lock, holding the
   11793  * lock around any calls to functions that handle records other than
   11794  * Application Data records.
   11795  */
   11796 SECStatus
   11797 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
   11798 {
   11799     const ssl3BulkCipherDef *cipher_def;
   11800     ssl3CipherSpec *     crSpec;
   11801     SECStatus            rv;
   11802     unsigned int         hashBytes = MAX_MAC_LENGTH + 1;
   11803     PRBool               isTLS;
   11804     SSL3ContentType      rType;
   11805     SSL3Opaque           hash[MAX_MAC_LENGTH];
   11806     SSL3Opaque           givenHashBuf[MAX_MAC_LENGTH];
   11807     SSL3Opaque          *givenHash;
   11808     sslBuffer           *plaintext;
   11809     sslBuffer            temp_buf;
   11810     PRUint64             dtls_seq_num;
   11811     unsigned int         ivLen = 0;
   11812     unsigned int         originalLen = 0;
   11813     unsigned int         good;
   11814     unsigned int         minLength;
   11815     unsigned char        header[13];
   11816     unsigned int         headerLen;
   11817 
   11818     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   11819 
   11820     if (!ss->ssl3.initialized) {
   11821 	ssl_GetSSL3HandshakeLock(ss);
   11822 	rv = ssl3_InitState(ss);
   11823 	ssl_ReleaseSSL3HandshakeLock(ss);
   11824 	if (rv != SECSuccess) {
   11825 	    return rv;		/* ssl3_InitState has set the error code. */
   11826     	}
   11827     }
   11828 
   11829     /* check for Token Presence */
   11830     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
   11831 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   11832 	return SECFailure;
   11833     }
   11834 
   11835     /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
   11836      * This implies that databuf holds a previously deciphered SSL Handshake
   11837      * message.
   11838      */
   11839     if (cText == NULL) {
   11840 	SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
   11841 		 SSL_GETPID(), ss->fd));
   11842 	rType = content_handshake;
   11843 	goto process_it;
   11844     }
   11845 
   11846     ssl_GetSpecReadLock(ss); /******************************************/
   11847 
   11848     crSpec = ss->ssl3.crSpec;
   11849     cipher_def = crSpec->cipher_def;
   11850 
   11851     /*
   11852      * DTLS relevance checks:
   11853      * Note that this code currently ignores all out-of-epoch packets,
   11854      * which means we lose some in the case of rehandshake +
   11855      * loss/reordering. Since DTLS is explicitly unreliable, this
   11856      * seems like a good tradeoff for implementation effort and is
   11857      * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
   11858      */
   11859     if (IS_DTLS(ss)) {
   11860 	DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
   11861 
   11862 	if (crSpec->epoch != epoch) {
   11863 	    ssl_ReleaseSpecReadLock(ss);
   11864 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
   11865 		     "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
   11866 	    /* Silently drop the packet */
   11867             databuf->len = 0; /* Needed to ensure data not left around */
   11868 	    return SECSuccess;
   11869 	}
   11870 
   11871 	dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
   11872 			((PRUint64)cText->seq_num.low);
   11873 
   11874 	if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
   11875 	    ssl_ReleaseSpecReadLock(ss);
   11876 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
   11877 		     "potentially replayed packet", SSL_GETPID(), ss->fd));
   11878 	    /* Silently drop the packet */
   11879             databuf->len = 0; /* Needed to ensure data not left around */
   11880 	    return SECSuccess;
   11881 	}
   11882     }
   11883 
   11884     good = ~0U;
   11885     minLength = crSpec->mac_size;
   11886     if (cipher_def->type == type_block) {
   11887 	/* CBC records have a padding length byte at the end. */
   11888 	minLength++;
   11889 	if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   11890 	    /* With >= TLS 1.1, CBC records have an explicit IV. */
   11891 	    minLength += cipher_def->iv_size;
   11892 	}
   11893     } else if (cipher_def->type == type_aead) {
   11894 	minLength = cipher_def->explicit_nonce_size + cipher_def->tag_size;
   11895     }
   11896 
   11897     /* We can perform this test in variable time because the record's total
   11898      * length and the ciphersuite are both public knowledge. */
   11899     if (cText->buf->len < minLength) {
   11900 	goto decrypt_loser;
   11901     }
   11902 
   11903     if (cipher_def->type == type_block &&
   11904 	crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   11905 	/* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
   11906 	 * "The receiver decrypts the entire GenericBlockCipher structure and
   11907 	 * then discards the first cipher block corresponding to the IV
   11908 	 * component." Instead, we decrypt the first cipher block and then
   11909 	 * discard it before decrypting the rest.
   11910 	 */
   11911 	SSL3Opaque iv[MAX_IV_LENGTH];
   11912 	int decoded;
   11913 
   11914 	ivLen = cipher_def->iv_size;
   11915 	if (ivLen < 8 || ivLen > sizeof(iv)) {
   11916 	    ssl_ReleaseSpecReadLock(ss);
   11917 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   11918 	    return SECFailure;
   11919 	}
   11920 
   11921 	PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
   11922 
   11923 	/* The decryption result is garbage, but since we just throw away
   11924 	 * the block it doesn't matter.  The decryption of the next block
   11925 	 * depends only on the ciphertext of the IV block.
   11926 	 */
   11927 	rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
   11928 			    sizeof(iv), cText->buf->buf, ivLen);
   11929 
   11930 	good &= SECStatusToMask(rv);
   11931     }
   11932 
   11933     /* If we will be decompressing the buffer we need to decrypt somewhere
   11934      * other than into databuf */
   11935     if (crSpec->decompressor) {
   11936 	temp_buf.buf = NULL;
   11937 	temp_buf.space = 0;
   11938 	plaintext = &temp_buf;
   11939     } else {
   11940 	plaintext = databuf;
   11941     }
   11942 
   11943     plaintext->len = 0; /* filled in by decode call below. */
   11944     if (plaintext->space < MAX_FRAGMENT_LENGTH) {
   11945 	rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
   11946 	if (rv != SECSuccess) {
   11947 	    ssl_ReleaseSpecReadLock(ss);
   11948 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
   11949 		     SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
   11950 	    /* sslBuffer_Grow has set a memory error code. */
   11951 	    /* Perhaps we should send an alert. (but we have no memory!) */
   11952 	    return SECFailure;
   11953 	}
   11954     }
   11955 
   11956     PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
   11957 				      cText->buf->len - ivLen));
   11958 
   11959     isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
   11960 
   11961     if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
   11962 	ssl_ReleaseSpecReadLock(ss);
   11963 	SSL3_SendAlert(ss, alert_fatal, record_overflow);
   11964 	PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
   11965 	return SECFailure;
   11966     }
   11967 
   11968     rType = cText->type;
   11969     if (cipher_def->type == type_aead) {
   11970 	/* XXX For many AEAD ciphers, the plaintext is shorter than the
   11971 	 * ciphertext by a fixed byte count, but it is not true in general.
   11972 	 * Each AEAD cipher should provide a function that returns the
   11973 	 * plaintext length for a given ciphertext. */
   11974 	unsigned int decryptedLen =
   11975 	    cText->buf->len - cipher_def->explicit_nonce_size -
   11976 	    cipher_def->tag_size;
   11977 	headerLen = ssl3_BuildRecordPseudoHeader(
   11978 	    header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
   11979 	    rType, isTLS, cText->version, IS_DTLS(ss), decryptedLen);
   11980 	PORT_Assert(headerLen <= sizeof(header));
   11981 	rv = crSpec->aead(
   11982 		ss->sec.isServer ? &crSpec->client : &crSpec->server,
   11983 		PR_TRUE,                          /* do decrypt */
   11984 		plaintext->buf,                   /* out */
   11985 		(int*) &plaintext->len,           /* outlen */
   11986 		plaintext->space,                 /* maxout */
   11987 		cText->buf->buf,                  /* in */
   11988 		cText->buf->len,                  /* inlen */
   11989 		header, headerLen);
   11990 	if (rv != SECSuccess) {
   11991 	    good = 0;
   11992 	}
   11993     } else {
   11994 	if (cipher_def->type == type_block &&
   11995 	    ((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
   11996 	    goto decrypt_loser;
   11997 	}
   11998 
   11999 	/* decrypt from cText buf to plaintext. */
   12000 	rv = crSpec->decode(
   12001 	    crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
   12002 	    plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
   12003 	if (rv != SECSuccess) {
   12004 	    goto decrypt_loser;
   12005 	}
   12006 
   12007 	PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
   12008 
   12009 	originalLen = plaintext->len;
   12010 
   12011 	/* If it's a block cipher, check and strip the padding. */
   12012 	if (cipher_def->type == type_block) {
   12013 	    const unsigned int blockSize = cipher_def->block_size;
   12014 	    const unsigned int macSize = crSpec->mac_size;
   12015 
   12016 	    if (!isTLS) {
   12017 		good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
   12018 			    plaintext, blockSize, macSize));
   12019 	    } else {
   12020 		good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
   12021 			    plaintext, macSize));
   12022 	    }
   12023 	}
   12024 
   12025 	/* compute the MAC */
   12026 	headerLen = ssl3_BuildRecordPseudoHeader(
   12027 	    header, IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
   12028 	    rType, isTLS, cText->version, IS_DTLS(ss),
   12029 	    plaintext->len - crSpec->mac_size);
   12030 	PORT_Assert(headerLen <= sizeof(header));
   12031 	if (cipher_def->type == type_block) {
   12032 	    rv = ssl3_ComputeRecordMACConstantTime(
   12033 		crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
   12034 		plaintext->buf, plaintext->len, originalLen,
   12035 		hash, &hashBytes);
   12036 
   12037 	    ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
   12038 			      crSpec->mac_size);
   12039 	    givenHash = givenHashBuf;
   12040 
   12041 	    /* plaintext->len will always have enough space to remove the MAC
   12042 	     * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
   12043 	     * plaintext->len if the result has enough space for the MAC and we
   12044 	     * tested the unadjusted size against minLength, above. */
   12045 	    plaintext->len -= crSpec->mac_size;
   12046 	} else {
   12047 	    /* This is safe because we checked the minLength above. */
   12048 	    plaintext->len -= crSpec->mac_size;
   12049 
   12050 	    rv = ssl3_ComputeRecordMAC(
   12051 		crSpec, (PRBool)(!ss->sec.isServer), header, headerLen,
   12052 		plaintext->buf, plaintext->len, hash, &hashBytes);
   12053 
   12054 	    /* We can read the MAC directly from the record because its location
   12055 	     * is public when a stream cipher is used. */
   12056 	    givenHash = plaintext->buf + plaintext->len;
   12057 	}
   12058 
   12059 	good &= SECStatusToMask(rv);
   12060 
   12061 	if (hashBytes != (unsigned)crSpec->mac_size ||
   12062 	    NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
   12063 	    /* We're allowed to leak whether or not the MAC check was correct */
   12064 	    good = 0;
   12065 	}
   12066     }
   12067 
   12068     if (good == 0) {
   12069 decrypt_loser:
   12070 	/* must not hold spec lock when calling SSL3_SendAlert. */
   12071 	ssl_ReleaseSpecReadLock(ss);
   12072 
   12073 	SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
   12074 
   12075 	if (!IS_DTLS(ss)) {
   12076 	    SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
   12077 	    /* always log mac error, in case attacker can read server logs. */
   12078 	    PORT_SetError(SSL_ERROR_BAD_MAC_READ);
   12079 	    return SECFailure;
   12080 	} else {
   12081 	    /* Silently drop the packet */
   12082             databuf->len = 0; /* Needed to ensure data not left around */
   12083 	    return SECSuccess;
   12084 	}
   12085     }
   12086 
   12087     if (!IS_DTLS(ss)) {
   12088 	ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
   12089     } else {
   12090 	dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
   12091     }
   12092 
   12093     ssl_ReleaseSpecReadLock(ss); /*****************************************/
   12094 
   12095     /*
   12096      * The decrypted data is now in plaintext.
   12097      */
   12098 
   12099     /* possibly decompress the record. If we aren't using compression then
   12100      * plaintext == databuf and so the uncompressed data is already in
   12101      * databuf. */
   12102     if (crSpec->decompressor) {
   12103 	if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
   12104 	    rv = sslBuffer_Grow(
   12105 	        databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
   12106 	    if (rv != SECSuccess) {
   12107 		SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
   12108 			 SSL_GETPID(), ss->fd,
   12109 			 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
   12110 		/* sslBuffer_Grow has set a memory error code. */
   12111 		/* Perhaps we should send an alert. (but we have no memory!) */
   12112 		PORT_Free(plaintext->buf);
   12113 		return SECFailure;
   12114 	    }
   12115 	}
   12116 
   12117 	rv = crSpec->decompressor(crSpec->decompressContext,
   12118 				  databuf->buf,
   12119 				  (int*) &databuf->len,
   12120 				  databuf->space,
   12121 				  plaintext->buf,
   12122 				  plaintext->len);
   12123 
   12124 	if (rv != SECSuccess) {
   12125 	    int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
   12126 	    SSL3_SendAlert(ss, alert_fatal,
   12127 			   isTLS ? decompression_failure : bad_record_mac);
   12128 
   12129 	    /* There appears to be a bug with (at least) Apache + OpenSSL where
   12130 	     * resumed SSLv3 connections don't actually use compression. See
   12131 	     * comments 93-95 of
   12132 	     * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
   12133 	     *
   12134 	     * So, if we get a decompression error, and the record appears to
   12135 	     * be already uncompressed, then we return a more specific error
   12136 	     * code to hopefully save somebody some debugging time in the
   12137 	     * future.
   12138 	     */
   12139 	    if (plaintext->len >= 4) {
   12140 		unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
   12141 		                   ((unsigned int) plaintext->buf[2] << 8) |
   12142 		                   (unsigned int) plaintext->buf[3];
   12143 		if (len == plaintext->len - 4) {
   12144 		    /* This appears to be uncompressed already */
   12145 		    err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
   12146 		}
   12147 	    }
   12148 
   12149 	    PORT_Free(plaintext->buf);
   12150 	    PORT_SetError(err);
   12151 	    return SECFailure;
   12152 	}
   12153 
   12154 	PORT_Free(plaintext->buf);
   12155     }
   12156 
   12157     /*
   12158     ** Having completed the decompression, check the length again.
   12159     */
   12160     if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
   12161 	SSL3_SendAlert(ss, alert_fatal, record_overflow);
   12162 	PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
   12163 	return SECFailure;
   12164     }
   12165 
   12166     /* Application data records are processed by the caller of this
   12167     ** function, not by this function.
   12168     */
   12169     if (rType == content_application_data) {
   12170 	if (ss->firstHsDone)
   12171 	    return SECSuccess;
   12172 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   12173 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
   12174 	return SECFailure;
   12175     }
   12176 
   12177     /* It's a record that must be handled by ssl itself, not the application.
   12178     */
   12179 process_it:
   12180     /* XXX  Get the xmit lock here.  Odds are very high that we'll be xmiting
   12181      * data ang getting the xmit lock here prevents deadlocks.
   12182      */
   12183     ssl_GetSSL3HandshakeLock(ss);
   12184 
   12185     /* All the functions called in this switch MUST set error code if
   12186     ** they return SECFailure or SECWouldBlock.
   12187     */
   12188     switch (rType) {
   12189     case content_change_cipher_spec:
   12190 	rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
   12191 	break;
   12192     case content_alert:
   12193 	rv = ssl3_HandleAlert(ss, databuf);
   12194 	break;
   12195     case content_handshake:
   12196 	if (!IS_DTLS(ss)) {
   12197 	    rv = ssl3_HandleHandshake(ss, databuf);
   12198 	} else {
   12199 	    rv = dtls_HandleHandshake(ss, databuf);
   12200 	}
   12201 	break;
   12202     /*
   12203     case content_application_data is handled before this switch
   12204     */
   12205     default:
   12206 	SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
   12207 		 SSL_GETPID(), ss->fd, cText->type));
   12208 	/* XXX Send an alert ???  */
   12209 	PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
   12210 	rv = SECFailure;
   12211 	break;
   12212     }
   12213 
   12214     ssl_ReleaseSSL3HandshakeLock(ss);
   12215     return rv;
   12216 }
   12217 
   12218 /*
   12219  * Initialization functions
   12220  */
   12221 
   12222 /* Called from ssl3_InitState, immediately below. */
   12223 /* Caller must hold the SpecWriteLock. */
   12224 static void
   12225 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
   12226 {
   12227     spec->cipher_def               = &bulk_cipher_defs[cipher_null];
   12228     PORT_Assert(spec->cipher_def->cipher == cipher_null);
   12229     spec->mac_def                  = &mac_defs[mac_null];
   12230     PORT_Assert(spec->mac_def->mac == mac_null);
   12231     spec->encode                   = Null_Cipher;
   12232     spec->decode                   = Null_Cipher;
   12233     spec->destroy                  = NULL;
   12234     spec->compressor               = NULL;
   12235     spec->decompressor             = NULL;
   12236     spec->destroyCompressContext   = NULL;
   12237     spec->destroyDecompressContext = NULL;
   12238     spec->mac_size                 = 0;
   12239     spec->master_secret            = NULL;
   12240     spec->bypassCiphers            = PR_FALSE;
   12241 
   12242     spec->msItem.data              = NULL;
   12243     spec->msItem.len               = 0;
   12244 
   12245     spec->client.write_key         = NULL;
   12246     spec->client.write_mac_key     = NULL;
   12247     spec->client.write_mac_context = NULL;
   12248 
   12249     spec->server.write_key         = NULL;
   12250     spec->server.write_mac_key     = NULL;
   12251     spec->server.write_mac_context = NULL;
   12252 
   12253     spec->write_seq_num.high       = 0;
   12254     spec->write_seq_num.low        = 0;
   12255 
   12256     spec->read_seq_num.high        = 0;
   12257     spec->read_seq_num.low         = 0;
   12258 
   12259     spec->epoch                    = 0;
   12260     dtls_InitRecvdRecords(&spec->recvdRecords);
   12261 
   12262     spec->version                  = ss->vrange.max;
   12263 }
   12264 
   12265 /* Called from:	ssl3_SendRecord
   12266 **		ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
   12267 **		ssl3_SendClientHello()
   12268 **		ssl3_HandleV2ClientHello()
   12269 **		ssl3_HandleRecord()
   12270 **
   12271 ** This function should perhaps acquire and release the SpecWriteLock.
   12272 **
   12273 **
   12274 */
   12275 static SECStatus
   12276 ssl3_InitState(sslSocket *ss)
   12277 {
   12278     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   12279 
   12280     if (ss->ssl3.initialized)
   12281     	return SECSuccess;	/* Function should be idempotent */
   12282 
   12283     ss->ssl3.policy = SSL_ALLOWED;
   12284 
   12285     ssl_GetSpecWriteLock(ss);
   12286     ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
   12287     ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
   12288     ss->ssl3.hs.sendingSCSV = PR_FALSE;
   12289     ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
   12290     ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
   12291 
   12292     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
   12293 #ifdef NSS_ENABLE_ECC
   12294     ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
   12295 #endif
   12296     ssl_ReleaseSpecWriteLock(ss);
   12297 
   12298     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   12299 
   12300     if (IS_DTLS(ss)) {
   12301 	ss->ssl3.hs.sendMessageSeq = 0;
   12302 	ss->ssl3.hs.recvMessageSeq = 0;
   12303 	ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
   12304 	ss->ssl3.hs.rtRetries = 0;
   12305 	ss->ssl3.hs.recvdHighWater = -1;
   12306 	PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
   12307 	dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
   12308     }
   12309 
   12310     PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
   12311     ss->ssl3.hs.messages.buf = NULL;
   12312     ss->ssl3.hs.messages.space = 0;
   12313 
   12314     ss->ssl3.initialized = PR_TRUE;
   12315     return SECSuccess;
   12316 }
   12317 
   12318 /* Returns a reference counted object that contains a key pair.
   12319  * Or NULL on failure.  Initial ref count is 1.
   12320  * Uses the keys in the pair as input.
   12321  */
   12322 ssl3KeyPair *
   12323 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
   12324 {
   12325     ssl3KeyPair * pair;
   12326 
   12327     if (!privKey || !pubKey) {
   12328 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   12329     	return NULL;
   12330     }
   12331     pair = PORT_ZNew(ssl3KeyPair);
   12332     if (!pair)
   12333     	return NULL;			/* error code is set. */
   12334     pair->refCount = 1;
   12335     pair->privKey  = privKey;
   12336     pair->pubKey   = pubKey;
   12337     return pair;			/* success */
   12338 }
   12339 
   12340 ssl3KeyPair *
   12341 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
   12342 {
   12343     PR_ATOMIC_INCREMENT(&keyPair->refCount);
   12344     return keyPair;
   12345 }
   12346 
   12347 void
   12348 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
   12349 {
   12350     PRInt32 newCount =  PR_ATOMIC_DECREMENT(&keyPair->refCount);
   12351     if (!newCount) {
   12352 	if (keyPair->privKey)
   12353 	    SECKEY_DestroyPrivateKey(keyPair->privKey);
   12354 	if (keyPair->pubKey)
   12355 	    SECKEY_DestroyPublicKey( keyPair->pubKey);
   12356     	PORT_Free(keyPair);
   12357     }
   12358 }
   12359 
   12360 
   12361 
   12362 /*
   12363  * Creates the public and private RSA keys for SSL Step down.
   12364  * Called from SSL_ConfigSecureServer in sslsecur.c
   12365  */
   12366 SECStatus
   12367 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
   12368 {
   12369     SECStatus             rv  	 = SECSuccess;
   12370     SECKEYPrivateKey *    privKey;		/* RSA step down key */
   12371     SECKEYPublicKey *     pubKey;		/* RSA step down key */
   12372 
   12373     if (ss->stepDownKeyPair)
   12374 	ssl3_FreeKeyPair(ss->stepDownKeyPair);
   12375     ss->stepDownKeyPair = NULL;
   12376 #ifndef HACKED_EXPORT_SERVER
   12377     /* Sigh, should have a get key strength call for private keys */
   12378     if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
   12379                                                      EXPORT_RSA_KEY_LENGTH) {
   12380 	/* need to ask for the key size in bits */
   12381 	privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
   12382 					     &pubKey, NULL);
   12383     	if (!privKey || !pubKey ||
   12384 	    !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
   12385 	    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
   12386 	    rv = SECFailure;
   12387 	}
   12388     }
   12389 #endif
   12390     return rv;
   12391 }
   12392 
   12393 
   12394 /* record the export policy for this cipher suite */
   12395 SECStatus
   12396 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
   12397 {
   12398     ssl3CipherSuiteCfg *suite;
   12399 
   12400     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   12401     if (suite == NULL) {
   12402 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
   12403     }
   12404     suite->policy = policy;
   12405 
   12406     return SECSuccess;
   12407 }
   12408 
   12409 SECStatus
   12410 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
   12411 {
   12412     ssl3CipherSuiteCfg *suite;
   12413     PRInt32             policy;
   12414     SECStatus           rv;
   12415 
   12416     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   12417     if (suite) {
   12418     	policy = suite->policy;
   12419 	rv     = SECSuccess;
   12420     } else {
   12421     	policy = SSL_NOT_ALLOWED;
   12422 	rv     = SECFailure;	/* err code was set by Lookup. */
   12423     }
   12424     *oPolicy = policy;
   12425     return rv;
   12426 }
   12427 
   12428 /* record the user preference for this suite */
   12429 SECStatus
   12430 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
   12431 {
   12432     ssl3CipherSuiteCfg *suite;
   12433 
   12434     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   12435     if (suite == NULL) {
   12436 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
   12437     }
   12438     suite->enabled = enabled;
   12439     return SECSuccess;
   12440 }
   12441 
   12442 /* return the user preference for this suite */
   12443 SECStatus
   12444 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
   12445 {
   12446     ssl3CipherSuiteCfg *suite;
   12447     PRBool              pref;
   12448     SECStatus           rv;
   12449 
   12450     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   12451     if (suite) {
   12452     	pref   = suite->enabled;
   12453 	rv     = SECSuccess;
   12454     } else {
   12455     	pref   = SSL_NOT_ALLOWED;
   12456 	rv     = SECFailure;	/* err code was set by Lookup. */
   12457     }
   12458     *enabled = pref;
   12459     return rv;
   12460 }
   12461 
   12462 SECStatus
   12463 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
   12464 {
   12465     ssl3CipherSuiteCfg *suite;
   12466 
   12467     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
   12468     if (suite == NULL) {
   12469 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
   12470     }
   12471     suite->enabled = enabled;
   12472     return SECSuccess;
   12473 }
   12474 
   12475 SECStatus
   12476 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
   12477 {
   12478     ssl3CipherSuiteCfg *suite;
   12479     PRBool              pref;
   12480     SECStatus           rv;
   12481 
   12482     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
   12483     if (suite) {
   12484     	pref   = suite->enabled;
   12485 	rv     = SECSuccess;
   12486     } else {
   12487     	pref   = SSL_NOT_ALLOWED;
   12488 	rv     = SECFailure;	/* err code was set by Lookup. */
   12489     }
   12490     *enabled = pref;
   12491     return rv;
   12492 }
   12493 
   12494 SECStatus
   12495 ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *ciphers, unsigned int len)
   12496 {
   12497     /* |i| iterates over |ciphers| while |done| and |j| iterate over
   12498      * |ss->cipherSuites|. */
   12499     unsigned int i, done;
   12500 
   12501     for (i = done = 0; i < len; i++) {
   12502 	PRUint16 id = ciphers[i];
   12503 	unsigned int existingIndex, j;
   12504 	PRBool found = PR_FALSE;
   12505 
   12506 	for (j = done; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
   12507 	    if (ss->cipherSuites[j].cipher_suite == id) {
   12508 		existingIndex = j;
   12509 		found = PR_TRUE;
   12510 		break;
   12511 	    }
   12512 	}
   12513 
   12514 	if (!found) {
   12515 	    continue;
   12516 	}
   12517 
   12518 	if (existingIndex != done) {
   12519 	    const ssl3CipherSuiteCfg temp = ss->cipherSuites[done];
   12520 	    ss->cipherSuites[done] = ss->cipherSuites[existingIndex];
   12521 	    ss->cipherSuites[existingIndex] = temp;
   12522 	}
   12523 	done++;
   12524     }
   12525 
   12526     /* Disable all cipher suites that weren't included. */
   12527     for (; done < ssl_V3_SUITES_IMPLEMENTED; done++) {
   12528 	ss->cipherSuites[done].enabled = 0;
   12529     }
   12530 
   12531     return SECSuccess;
   12532 }
   12533 
   12534 /* copy global default policy into socket. */
   12535 void
   12536 ssl3_InitSocketPolicy(sslSocket *ss)
   12537 {
   12538     PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
   12539 }
   12540 
   12541 SECStatus
   12542 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss,
   12543 				unsigned char *out,
   12544 				unsigned int *outLen,
   12545 				unsigned int outLenMax) {
   12546     PRBool       isTLS;
   12547     int          index = 0;
   12548     unsigned int len;
   12549     SECStatus    rv = SECFailure;
   12550 
   12551     *outLen = 0;
   12552 
   12553     ssl_GetSSL3HandshakeLock(ss);
   12554 
   12555     ssl_GetSpecReadLock(ss);
   12556     isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0);
   12557     ssl_ReleaseSpecReadLock(ss);
   12558 
   12559     /* The tls-unique channel binding is the first Finished structure in the
   12560      * handshake. In the case of a resumption, that's the server's Finished.
   12561      * Otherwise, it's the client's Finished. */
   12562     len = ss->ssl3.hs.finishedBytes;
   12563 
   12564     /* Sending or receiving a Finished message will set finishedBytes to a
   12565      * non-zero value. */
   12566     if (len == 0) {
   12567 	PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
   12568 	goto loser;
   12569     }
   12570 
   12571     /* If we are in the middle of a renegotiation then the channel binding
   12572      * value is poorly defined and depends on the direction that it will be
   12573      * used on. Therefore we simply return an error in this case. */
   12574     if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) {
   12575 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
   12576 	goto loser;
   12577     }
   12578 
   12579     /* If resuming, then we want the second Finished value in the array, which
   12580      * is the server's */
   12581     if (ss->ssl3.hs.isResuming)
   12582 	index = 1;
   12583 
   12584     *outLen = len;
   12585     if (outLenMax < len) {
   12586 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   12587 	goto loser;
   12588     }
   12589 
   12590     if (isTLS) {
   12591 	memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len);
   12592     } else {
   12593 	memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len);
   12594     }
   12595 
   12596     rv = SECSuccess;
   12597 
   12598 loser:
   12599     ssl_ReleaseSSL3HandshakeLock(ss);
   12600     return rv;
   12601 }
   12602 
   12603 /* ssl3_config_match_init must have already been called by
   12604  * the caller of this function.
   12605  */
   12606 SECStatus
   12607 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
   12608 {
   12609     int i, count = 0;
   12610 
   12611     PORT_Assert(ss != 0);
   12612     if (!ss) {
   12613 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   12614 	return SECFailure;
   12615     }
   12616     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
   12617     	*size = 0;
   12618 	return SECSuccess;
   12619     }
   12620     if (cs == NULL) {
   12621 	*size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
   12622 	return SECSuccess;
   12623     }
   12624 
   12625     /* ssl3_config_match_init was called by the caller of this function. */
   12626     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
   12627 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
   12628 	if (config_match(suite, SSL_ALLOWED, PR_TRUE, &ss->vrange)) {
   12629 	    if (cs != NULL) {
   12630 		*cs++ = 0x00;
   12631 		*cs++ = (suite->cipher_suite >> 8) & 0xFF;
   12632 		*cs++ =  suite->cipher_suite       & 0xFF;
   12633 	    }
   12634 	    count++;
   12635 	}
   12636     }
   12637     *size = count;
   12638     return SECSuccess;
   12639 }
   12640 
   12641 /*
   12642 ** If ssl3 socket has completed the first handshake, and is in idle state,
   12643 ** then start a new handshake.
   12644 ** If flushCache is true, the SID cache will be flushed first, forcing a
   12645 ** "Full" handshake (not a session restart handshake), to be done.
   12646 **
   12647 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
   12648 */
   12649 SECStatus
   12650 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
   12651 {
   12652     sslSessionID *   sid = ss->sec.ci.sid;
   12653     SECStatus        rv;
   12654 
   12655     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   12656 
   12657     if (!ss->firstHsDone ||
   12658         ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
   12659 	 ss->ssl3.initialized &&
   12660 	 (ss->ssl3.hs.ws != idle_handshake))) {
   12661 	PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
   12662 	return SECFailure;
   12663     }
   12664 
   12665     if (IS_DTLS(ss)) {
   12666 	dtls_RehandshakeCleanup(ss);
   12667     }
   12668 
   12669     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
   12670 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
   12671 	return SECFailure;
   12672     }
   12673     if (sid && flushCache) {
   12674         if (ss->sec.uncache)
   12675             ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
   12676 	ssl_FreeSID(sid);	/* dec ref count and free if zero. */
   12677 	ss->sec.ci.sid = NULL;
   12678     }
   12679 
   12680     ssl_GetXmitBufLock(ss);	/**************************************/
   12681 
   12682     /* start off a new handshake. */
   12683     rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
   12684                             : ssl3_SendClientHello(ss, PR_FALSE);
   12685 
   12686     ssl_ReleaseXmitBufLock(ss);	/**************************************/
   12687     return rv;
   12688 }
   12689 
   12690 /* Called from ssl_DestroySocketContents() in sslsock.c */
   12691 void
   12692 ssl3_DestroySSL3Info(sslSocket *ss)
   12693 {
   12694 
   12695     if (ss->ssl3.clientCertificate != NULL)
   12696 	CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   12697 
   12698     if (ss->ssl3.clientPrivateKey != NULL)
   12699 	SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   12700 #ifdef NSS_PLATFORM_CLIENT_AUTH
   12701     if (ss->ssl3.platformClientKey)
   12702 	ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   12703 #endif /* NSS_PLATFORM_CLIENT_AUTH */
   12704 
   12705     if (ss->ssl3.channelID)
   12706 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   12707     if (ss->ssl3.channelIDPub)
   12708 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   12709 
   12710     if (ss->ssl3.peerCertArena != NULL)
   12711 	ssl3_CleanupPeerCerts(ss);
   12712 
   12713     if (ss->ssl3.clientCertChain != NULL) {
   12714        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
   12715        ss->ssl3.clientCertChain = NULL;
   12716     }
   12717 
   12718     /* clean up handshake */
   12719 #ifndef NO_PKCS11_BYPASS
   12720     if (ss->opt.bypassPKCS11) {
   12721 	if (ss->ssl3.hs.hashType == handshake_hash_combo) {
   12722 	    SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
   12723 	    MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
   12724 	} else if (ss->ssl3.hs.hashType == handshake_hash_single) {
   12725 	    ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
   12726 	}
   12727     }
   12728 #endif
   12729     if (ss->ssl3.hs.md5) {
   12730 	PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
   12731     }
   12732     if (ss->ssl3.hs.sha) {
   12733 	PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
   12734     }
   12735     if (ss->ssl3.hs.clientSigAndHash) {
   12736 	PORT_Free(ss->ssl3.hs.clientSigAndHash);
   12737     }
   12738     if (ss->ssl3.hs.messages.buf) {
   12739     	PORT_Free(ss->ssl3.hs.messages.buf);
   12740 	ss->ssl3.hs.messages.buf = NULL;
   12741 	ss->ssl3.hs.messages.len = 0;
   12742 	ss->ssl3.hs.messages.space = 0;
   12743     }
   12744 
   12745     /* free the SSL3Buffer (msg_body) */
   12746     PORT_Free(ss->ssl3.hs.msg_body.buf);
   12747 
   12748     /* free up the CipherSpecs */
   12749     ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
   12750     ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
   12751 
   12752     /* Destroy the DTLS data */
   12753     if (IS_DTLS(ss)) {
   12754 	dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
   12755 	if (ss->ssl3.hs.recvdFragments.buf) {
   12756 	    PORT_Free(ss->ssl3.hs.recvdFragments.buf);
   12757 	}
   12758     }
   12759 
   12760     ss->ssl3.initialized = PR_FALSE;
   12761 
   12762     SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
   12763 }
   12764 
   12765 /* End of ssl3con.c */
   12766