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 #include <stdio.h>
     44 #ifdef NSS_ENABLE_ZLIB
     45 #include "zlib.h"
     46 #endif
     47 
     48 #ifndef PK11_SETATTRS
     49 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
     50 		(x)->pValue=(v); (x)->ulValueLen = (l);
     51 #endif
     52 
     53 static SECStatus ssl3_AuthCertificate(sslSocket *ss);
     54 static void      ssl3_CleanupPeerCerts(sslSocket *ss);
     55 static void      ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid);
     56 static PK11SymKey *ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
     57                                        PK11SlotInfo * serverKeySlot);
     58 static SECStatus ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms);
     59 static SECStatus ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss);
     60 static SECStatus ssl3_HandshakeFailure(      sslSocket *ss);
     61 static SECStatus ssl3_InitState(             sslSocket *ss);
     62 static SECStatus ssl3_SendCertificate(       sslSocket *ss);
     63 static SECStatus ssl3_SendCertificateStatus( sslSocket *ss);
     64 static SECStatus ssl3_SendEmptyCertificate(  sslSocket *ss);
     65 static SECStatus ssl3_SendCertificateRequest(sslSocket *ss);
     66 static SECStatus ssl3_SendNextProto(         sslSocket *ss);
     67 static SECStatus ssl3_SendEncryptedExtensions(sslSocket *ss);
     68 static SECStatus ssl3_SendFinished(          sslSocket *ss, PRInt32 flags);
     69 static SECStatus ssl3_SendServerHello(       sslSocket *ss);
     70 static SECStatus ssl3_SendServerHelloDone(   sslSocket *ss);
     71 static SECStatus ssl3_SendServerKeyExchange( sslSocket *ss);
     72 static SECStatus ssl3_UpdateHandshakeHashes( sslSocket *ss,
     73                                              const unsigned char *b,
     74                                              unsigned int l);
     75 static SECStatus ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
     76 static int       ssl3_OIDToTLSHashAlgorithm(SECOidTag oid);
     77 
     78 static SECStatus Null_Cipher(void *ctx, unsigned char *output, int *outputLen,
     79 			     int maxOutputLen, const unsigned char *input,
     80 			     int inputLen);
     81 
     82 #define MAX_SEND_BUF_LENGTH 32000 /* watch for 16-bit integer overflow */
     83 #define MIN_SEND_BUF_LENGTH  4000
     84 
     85 /* This list of SSL3 cipher suites is sorted in descending order of
     86  * precedence (desirability).  It only includes cipher suites we implement.
     87  * This table is modified by SSL3_SetPolicy(). The ordering of cipher suites
     88  * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
     89  */
     90 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
     91    /*      cipher_suite                         policy      enabled is_present*/
     92 #ifdef NSS_ENABLE_ECC
     93  { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
     94  { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
     95 #endif /* NSS_ENABLE_ECC */
     96  { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
     97  { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
     98  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
     99  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,    SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    100  { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    101 #ifdef NSS_ENABLE_ECC
    102  { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    103  { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    104 #endif /* NSS_ENABLE_ECC */
    105  { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    106  { TLS_RSA_WITH_AES_256_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    107  { TLS_RSA_WITH_AES_256_CBC_SHA256,	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    108 
    109 #ifdef NSS_ENABLE_ECC
    110  { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,       SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    111  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    112  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    113  { TLS_ECDHE_RSA_WITH_RC4_128_SHA,         SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    114  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    115  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    116 #endif /* NSS_ENABLE_ECC */
    117  { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    118  { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    119  { TLS_DHE_DSS_WITH_RC4_128_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    120  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,       SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    121  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,    SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    122  { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    123 #ifdef NSS_ENABLE_ECC
    124  { TLS_ECDH_RSA_WITH_RC4_128_SHA,          SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    125  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,      SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    126  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,        SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    127  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    128 #endif /* NSS_ENABLE_ECC */
    129  { TLS_RSA_WITH_SEED_CBC_SHA,              SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    130  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,  	   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    131  { SSL_RSA_WITH_RC4_128_SHA,               SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    132  { SSL_RSA_WITH_RC4_128_MD5,               SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
    133  { TLS_RSA_WITH_AES_128_CBC_SHA,     	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    134  { TLS_RSA_WITH_AES_128_CBC_SHA256,	   SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    135 
    136 #ifdef NSS_ENABLE_ECC
    137  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    138  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    139 #endif /* NSS_ENABLE_ECC */
    140  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    141  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,      SSL_NOT_ALLOWED, PR_TRUE,PR_FALSE},
    142 #ifdef NSS_ENABLE_ECC
    143  { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    144  { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    145 #endif /* NSS_ENABLE_ECC */
    146  { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA,     SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    147  { SSL_RSA_WITH_3DES_EDE_CBC_SHA,          SSL_NOT_ALLOWED, PR_TRUE, PR_FALSE},
    148 
    149 
    150  { SSL_DHE_RSA_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    151  { SSL_DHE_DSS_WITH_DES_CBC_SHA,           SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    152  { SSL_RSA_FIPS_WITH_DES_CBC_SHA,          SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    153  { SSL_RSA_WITH_DES_CBC_SHA,               SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    154  { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,     SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    155  { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,    SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    156 
    157  { SSL_RSA_EXPORT_WITH_RC4_40_MD5,         SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    158  { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,     SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    159 
    160 #ifdef NSS_ENABLE_ECC
    161  { TLS_ECDHE_ECDSA_WITH_NULL_SHA,          SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    162  { TLS_ECDHE_RSA_WITH_NULL_SHA,            SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    163  { TLS_ECDH_RSA_WITH_NULL_SHA,             SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    164  { TLS_ECDH_ECDSA_WITH_NULL_SHA,           SSL_NOT_ALLOWED, PR_FALSE, PR_FALSE},
    165 #endif /* NSS_ENABLE_ECC */
    166  { SSL_RSA_WITH_NULL_SHA,                  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    167  { TLS_RSA_WITH_NULL_SHA256,               SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    168  { SSL_RSA_WITH_NULL_MD5,                  SSL_NOT_ALLOWED, PR_FALSE,PR_FALSE},
    169 
    170 };
    171 
    172 /* This list of SSL3 compression methods is sorted in descending order of
    173  * precedence (desirability).  It only includes compression methods we
    174  * implement.
    175  */
    176 static const /*SSLCompressionMethod*/ PRUint8 compressions [] = {
    177 #ifdef NSS_ENABLE_ZLIB
    178     ssl_compression_deflate,
    179 #endif
    180     ssl_compression_null
    181 };
    182 
    183 static const int compressionMethodsCount =
    184     sizeof(compressions) / sizeof(compressions[0]);
    185 
    186 /* compressionEnabled returns true iff the compression algorithm is enabled
    187  * for the given SSL socket. */
    188 static PRBool
    189 compressionEnabled(sslSocket *ss, SSLCompressionMethod compression)
    190 {
    191     switch (compression) {
    192     case ssl_compression_null:
    193 	return PR_TRUE;  /* Always enabled */
    194 #ifdef NSS_ENABLE_ZLIB
    195     case ssl_compression_deflate:
    196 	return ss->opt.enableDeflate;
    197 #endif
    198     default:
    199 	return PR_FALSE;
    200     }
    201 }
    202 
    203 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
    204     ct_RSA_sign,
    205 #ifdef NSS_ENABLE_ECC
    206     ct_ECDSA_sign,
    207 #endif /* NSS_ENABLE_ECC */
    208     ct_DSS_sign,
    209 };
    210 
    211 /* This block is the contents of the supported_signature_algorithms field of
    212  * our TLS 1.2 CertificateRequest message, in wire format. See
    213  * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
    214  *
    215  * This block contains only sha256 entries because we only support TLS 1.2
    216  * CertificateVerify messages that use the handshake hash. */
    217 static const PRUint8 supported_signature_algorithms[] = {
    218     tls_hash_sha256, tls_sig_rsa,
    219 #ifdef NSS_ENABLE_ECC
    220     tls_hash_sha256, tls_sig_ecdsa,
    221 #endif
    222     tls_hash_sha256, tls_sig_dsa,
    223 };
    224 
    225 #define EXPORT_RSA_KEY_LENGTH 64	/* bytes */
    226 
    227 
    228 /* This global item is used only in servers.  It is is initialized by
    229 ** SSL_ConfigSecureServer(), and is used in ssl3_SendCertificateRequest().
    230 */
    231 CERTDistNames *ssl3_server_ca_list = NULL;
    232 static SSL3Statistics ssl3stats;
    233 
    234 /* indexed by SSL3BulkCipher */
    235 static const ssl3BulkCipherDef bulk_cipher_defs[] = {
    236     /* cipher          calg        keySz secretSz  type  ivSz BlkSz keygen */
    237     {cipher_null,      calg_null,      0,  0, type_stream,  0, 0, kg_null},
    238     {cipher_rc4,       calg_rc4,      16, 16, type_stream,  0, 0, kg_strong},
    239     {cipher_rc4_40,    calg_rc4,      16,  5, type_stream,  0, 0, kg_export},
    240     {cipher_rc4_56,    calg_rc4,      16,  7, type_stream,  0, 0, kg_export},
    241     {cipher_rc2,       calg_rc2,      16, 16, type_block,   8, 8, kg_strong},
    242     {cipher_rc2_40,    calg_rc2,      16,  5, type_block,   8, 8, kg_export},
    243     {cipher_des,       calg_des,       8,  8, type_block,   8, 8, kg_strong},
    244     {cipher_3des,      calg_3des,     24, 24, type_block,   8, 8, kg_strong},
    245     {cipher_des40,     calg_des,       8,  5, type_block,   8, 8, kg_export},
    246     {cipher_idea,      calg_idea,     16, 16, type_block,   8, 8, kg_strong},
    247     {cipher_aes_128,   calg_aes,      16, 16, type_block,  16,16, kg_strong},
    248     {cipher_aes_256,   calg_aes,      32, 32, type_block,  16,16, kg_strong},
    249     {cipher_camellia_128, calg_camellia,16, 16, type_block,  16,16, kg_strong},
    250     {cipher_camellia_256, calg_camellia,32, 32, type_block,  16,16, kg_strong},
    251     {cipher_seed,      calg_seed,     16, 16, type_block,  16,16, kg_strong},
    252     {cipher_missing,   calg_null,      0,  0, type_stream,  0, 0, kg_null},
    253 };
    254 
    255 static const ssl3KEADef kea_defs[] =
    256 { /* indexed by SSL3KeyExchangeAlgorithm */
    257     /* kea              exchKeyType signKeyType is_limited limit  tls_keygen */
    258     {kea_null,           kt_null,     sign_null, PR_FALSE,   0, PR_FALSE},
    259     {kea_rsa,            kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_FALSE},
    260     {kea_rsa_export,     kt_rsa,      sign_rsa,  PR_TRUE,  512, PR_FALSE},
    261     {kea_rsa_export_1024,kt_rsa,      sign_rsa,  PR_TRUE, 1024, PR_FALSE},
    262     {kea_dh_dss,         kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
    263     {kea_dh_dss_export,  kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
    264     {kea_dh_rsa,         kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
    265     {kea_dh_rsa_export,  kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
    266     {kea_dhe_dss,        kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
    267     {kea_dhe_dss_export, kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
    268     {kea_dhe_rsa,        kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
    269     {kea_dhe_rsa_export, kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
    270     {kea_dh_anon,        kt_dh,       sign_null, PR_FALSE,   0, PR_FALSE},
    271     {kea_dh_anon_export, kt_dh,       sign_null, PR_TRUE,  512, PR_FALSE},
    272     {kea_rsa_fips,       kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_TRUE },
    273 #ifdef NSS_ENABLE_ECC
    274     {kea_ecdh_ecdsa,     kt_ecdh,     sign_ecdsa,  PR_FALSE, 0, PR_FALSE},
    275     {kea_ecdhe_ecdsa,    kt_ecdh,     sign_ecdsa,  PR_FALSE,   0, PR_FALSE},
    276     {kea_ecdh_rsa,       kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
    277     {kea_ecdhe_rsa,      kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
    278     {kea_ecdh_anon,      kt_ecdh,     sign_null,  PR_FALSE,   0, PR_FALSE},
    279 #endif /* NSS_ENABLE_ECC */
    280 };
    281 
    282 /* must use ssl_LookupCipherSuiteDef to access */
    283 static const ssl3CipherSuiteDef cipher_suite_defs[] =
    284 {
    285 /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg */
    286 
    287     {SSL_NULL_WITH_NULL_NULL,       cipher_null,   mac_null, kea_null},
    288     {SSL_RSA_WITH_NULL_MD5,         cipher_null,   mac_md5, kea_rsa},
    289     {SSL_RSA_WITH_NULL_SHA,         cipher_null,   mac_sha, kea_rsa},
    290     {TLS_RSA_WITH_NULL_SHA256,      cipher_null,   hmac_sha256, kea_rsa},
    291     {SSL_RSA_EXPORT_WITH_RC4_40_MD5,cipher_rc4_40, mac_md5, kea_rsa_export},
    292     {SSL_RSA_WITH_RC4_128_MD5,      cipher_rc4,    mac_md5, kea_rsa},
    293     {SSL_RSA_WITH_RC4_128_SHA,      cipher_rc4,    mac_sha, kea_rsa},
    294     {SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
    295                                     cipher_rc2_40, mac_md5, kea_rsa_export},
    296 #if 0 /* not implemented */
    297     {SSL_RSA_WITH_IDEA_CBC_SHA,     cipher_idea,   mac_sha, kea_rsa},
    298     {SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
    299                                     cipher_des40,  mac_sha, kea_rsa_export},
    300 #endif
    301     {SSL_RSA_WITH_DES_CBC_SHA,      cipher_des,    mac_sha, kea_rsa},
    302     {SSL_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,   mac_sha, kea_rsa},
    303     {SSL_DHE_DSS_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_dss},
    304     {SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
    305                                     cipher_3des,   mac_sha, kea_dhe_dss},
    306     {TLS_DHE_DSS_WITH_RC4_128_SHA,  cipher_rc4,    mac_sha, kea_dhe_dss},
    307 #if 0 /* not implemented */
    308     {SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
    309                                     cipher_des40,  mac_sha, kea_dh_dss_export},
    310     {SSL_DH_DSS_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_dss},
    311     {SSL_DH_DSS_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_dss},
    312     {SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
    313                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
    314     {SSL_DH_RSA_DES_CBC_SHA,        cipher_des,    mac_sha, kea_dh_rsa},
    315     {SSL_DH_RSA_3DES_CBC_SHA,       cipher_3des,   mac_sha, kea_dh_rsa},
    316     {SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
    317                                     cipher_des40,  mac_sha, kea_dh_dss_export},
    318     {SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
    319                                     cipher_des40,  mac_sha, kea_dh_rsa_export},
    320 #endif
    321     {SSL_DHE_RSA_WITH_DES_CBC_SHA,  cipher_des,    mac_sha, kea_dhe_rsa},
    322     {SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
    323                                     cipher_3des,   mac_sha, kea_dhe_rsa},
    324 #if 0
    325     {SSL_DH_ANON_EXPORT_RC4_40_MD5, cipher_rc4_40, mac_md5, kea_dh_anon_export},
    326     {SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA,
    327                                     cipher_des40,  mac_sha, kea_dh_anon_export},
    328     {SSL_DH_ANON_DES_CBC_SHA,       cipher_des,    mac_sha, kea_dh_anon},
    329     {SSL_DH_ANON_3DES_CBC_SHA,      cipher_3des,   mac_sha, kea_dh_anon},
    330 #endif
    331 
    332 
    333 /* New TLS cipher suites */
    334     {TLS_RSA_WITH_AES_128_CBC_SHA,     	cipher_aes_128, mac_sha, kea_rsa},
    335     {TLS_RSA_WITH_AES_128_CBC_SHA256,	cipher_aes_128, hmac_sha256, kea_rsa},
    336     {TLS_DHE_DSS_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dhe_dss},
    337     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dhe_rsa},
    338     {TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_dhe_rsa},
    339     {TLS_RSA_WITH_AES_256_CBC_SHA,     	cipher_aes_256, mac_sha, kea_rsa},
    340     {TLS_RSA_WITH_AES_256_CBC_SHA256,	cipher_aes_256, hmac_sha256, kea_rsa},
    341     {TLS_DHE_DSS_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dhe_dss},
    342     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dhe_rsa},
    343     {TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, cipher_aes_256, hmac_sha256, kea_dhe_rsa},
    344 #if 0
    345     {TLS_DH_DSS_WITH_AES_128_CBC_SHA,  	cipher_aes_128, mac_sha, kea_dh_dss},
    346     {TLS_DH_RSA_WITH_AES_128_CBC_SHA,  	cipher_aes_128, mac_sha, kea_dh_rsa},
    347     {TLS_DH_ANON_WITH_AES_128_CBC_SHA, 	cipher_aes_128, mac_sha, kea_dh_anon},
    348     {TLS_DH_DSS_WITH_AES_256_CBC_SHA,  	cipher_aes_256, mac_sha, kea_dh_dss},
    349     {TLS_DH_RSA_WITH_AES_256_CBC_SHA,  	cipher_aes_256, mac_sha, kea_dh_rsa},
    350     {TLS_DH_ANON_WITH_AES_256_CBC_SHA, 	cipher_aes_256, mac_sha, kea_dh_anon},
    351 #endif
    352 
    353     {TLS_RSA_WITH_SEED_CBC_SHA,	    cipher_seed,   mac_sha, kea_rsa},
    354 
    355     {TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, cipher_camellia_128, mac_sha, kea_rsa},
    356     {TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
    357      cipher_camellia_128, mac_sha, kea_dhe_dss},
    358     {TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
    359      cipher_camellia_128, mac_sha, kea_dhe_rsa},
    360     {TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,	cipher_camellia_256, mac_sha, kea_rsa},
    361     {TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
    362      cipher_camellia_256, mac_sha, kea_dhe_dss},
    363     {TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
    364      cipher_camellia_256, mac_sha, kea_dhe_rsa},
    365 
    366     {TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
    367                                     cipher_des,    mac_sha,kea_rsa_export_1024},
    368     {TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
    369                                     cipher_rc4_56, mac_sha,kea_rsa_export_1024},
    370 
    371     {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
    372     {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des,    mac_sha, kea_rsa_fips},
    373 
    374 #ifdef NSS_ENABLE_ECC
    375     {TLS_ECDH_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdh_ecdsa},
    376     {TLS_ECDH_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdh_ecdsa},
    377     {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
    378     {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
    379     {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
    380 
    381     {TLS_ECDHE_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdhe_ecdsa},
    382     {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
    383     {TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdhe_ecdsa},
    384     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdhe_ecdsa},
    385     {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_ecdsa},
    386     {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdhe_ecdsa},
    387 
    388     {TLS_ECDH_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_rsa},
    389     {TLS_ECDH_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_rsa},
    390     {TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_rsa},
    391     {TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_rsa},
    392     {TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_rsa},
    393 
    394     {TLS_ECDHE_RSA_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdhe_rsa},
    395     {TLS_ECDHE_RSA_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdhe_rsa},
    396     {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdhe_rsa},
    397     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdhe_rsa},
    398     {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, cipher_aes_128, hmac_sha256, kea_ecdhe_rsa},
    399     {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdhe_rsa},
    400 
    401 #if 0
    402     {TLS_ECDH_anon_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_anon},
    403     {TLS_ECDH_anon_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_anon},
    404     {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_anon},
    405     {TLS_ECDH_anon_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_anon},
    406     {TLS_ECDH_anon_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_anon},
    407 #endif
    408 #endif /* NSS_ENABLE_ECC */
    409 };
    410 
    411 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
    412     0x80000000L,
    413     CKM_RSA_PKCS,
    414     CKM_DH_PKCS_DERIVE,
    415     CKM_KEA_KEY_DERIVE,
    416     CKM_ECDH1_DERIVE
    417 };
    418 
    419 typedef struct SSLCipher2MechStr {
    420     SSLCipherAlgorithm  calg;
    421     CK_MECHANISM_TYPE   cmech;
    422 } SSLCipher2Mech;
    423 
    424 /* indexed by type SSLCipherAlgorithm */
    425 static const SSLCipher2Mech alg2Mech[] = {
    426     /* calg,          cmech  */
    427     { calg_null     , (CK_MECHANISM_TYPE)0x80000000L	},
    428     { calg_rc4      , CKM_RC4				},
    429     { calg_rc2      , CKM_RC2_CBC			},
    430     { calg_des      , CKM_DES_CBC			},
    431     { calg_3des     , CKM_DES3_CBC			},
    432     { calg_idea     , CKM_IDEA_CBC			},
    433     { calg_fortezza , CKM_SKIPJACK_CBC64                },
    434     { calg_aes      , CKM_AES_CBC			},
    435     { calg_camellia , CKM_CAMELLIA_CBC			},
    436     { calg_seed     , CKM_SEED_CBC			},
    437 /*  { calg_init     , (CK_MECHANISM_TYPE)0x7fffffffL    }  */
    438 };
    439 
    440 #define mmech_null     (CK_MECHANISM_TYPE)0x80000000L
    441 #define mmech_md5      CKM_SSL3_MD5_MAC
    442 #define mmech_sha      CKM_SSL3_SHA1_MAC
    443 #define mmech_md5_hmac CKM_MD5_HMAC
    444 #define mmech_sha_hmac CKM_SHA_1_HMAC
    445 #define mmech_sha256_hmac CKM_SHA256_HMAC
    446 
    447 static const ssl3MACDef mac_defs[] = { /* indexed by SSL3MACAlgorithm */
    448     /* pad_size is only used for SSL 3.0 MAC. See RFC 6101 Sec. 5.2.3.1. */
    449     /* mac      mmech       pad_size  mac_size                       */
    450     { mac_null, mmech_null,       0,  0          },
    451     { mac_md5,  mmech_md5,       48,  MD5_LENGTH },
    452     { mac_sha,  mmech_sha,       40,  SHA1_LENGTH},
    453     {hmac_md5,  mmech_md5_hmac,   0,  MD5_LENGTH },
    454     {hmac_sha,  mmech_sha_hmac,   0,  SHA1_LENGTH},
    455     {hmac_sha256, mmech_sha256_hmac, 0, SHA256_LENGTH},
    456 };
    457 
    458 /* indexed by SSL3BulkCipher */
    459 const char * const ssl3_cipherName[] = {
    460     "NULL",
    461     "RC4",
    462     "RC4-40",
    463     "RC4-56",
    464     "RC2-CBC",
    465     "RC2-CBC-40",
    466     "DES-CBC",
    467     "3DES-EDE-CBC",
    468     "DES-CBC-40",
    469     "IDEA-CBC",
    470     "AES-128",
    471     "AES-256",
    472     "Camellia-128",
    473     "Camellia-256",
    474     "SEED-CBC",
    475     "missing"
    476 };
    477 
    478 #ifdef NSS_ENABLE_ECC
    479 /* The ECCWrappedKeyInfo structure defines how various pieces of
    480  * information are laid out within wrappedSymmetricWrappingkey
    481  * for ECDH key exchange. Since wrappedSymmetricWrappingkey is
    482  * a 512-byte buffer (see sslimpl.h), the variable length field
    483  * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
    484  *
    485  * XXX For now, NSS only supports named elliptic curves of size 571 bits
    486  * or smaller. The public value will fit within 145 bytes and EC params
    487  * will fit within 12 bytes. We'll need to revisit this when NSS
    488  * supports arbitrary curves.
    489  */
    490 #define MAX_EC_WRAPPED_KEY_BUFLEN  504
    491 
    492 typedef struct ECCWrappedKeyInfoStr {
    493     PRUint16 size;            /* EC public key size in bits */
    494     PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
    495     PRUint16 pubValueLen;     /* length (in bytes) of EC public value */
    496     PRUint16 wrappedKeyLen;   /* length (in bytes) of the wrapped key */
    497     PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
    498     /* EC public-key params, the EC public value and the wrapped key  */
    499 } ECCWrappedKeyInfo;
    500 #endif /* NSS_ENABLE_ECC */
    501 
    502 #if defined(TRACE)
    503 
    504 static char *
    505 ssl3_DecodeHandshakeType(int msgType)
    506 {
    507     char * rv;
    508     static char line[40];
    509 
    510     switch(msgType) {
    511     case hello_request:	        rv = "hello_request (0)";               break;
    512     case client_hello:	        rv = "client_hello  (1)";               break;
    513     case server_hello:	        rv = "server_hello  (2)";               break;
    514     case hello_verify_request:  rv = "hello_verify_request (3)";        break;
    515     case certificate:	        rv = "certificate  (11)";               break;
    516     case server_key_exchange:	rv = "server_key_exchange (12)";        break;
    517     case certificate_request:	rv = "certificate_request (13)";        break;
    518     case server_hello_done:	rv = "server_hello_done   (14)";        break;
    519     case certificate_verify:	rv = "certificate_verify  (15)";        break;
    520     case client_key_exchange:	rv = "client_key_exchange (16)";        break;
    521     case finished:	        rv = "finished     (20)";               break;
    522     default:
    523         sprintf(line, "*UNKNOWN* handshake type! (%d)", msgType);
    524 	rv = line;
    525     }
    526     return rv;
    527 }
    528 
    529 static char *
    530 ssl3_DecodeContentType(int msgType)
    531 {
    532     char * rv;
    533     static char line[40];
    534 
    535     switch(msgType) {
    536     case content_change_cipher_spec:
    537                                 rv = "change_cipher_spec (20)";         break;
    538     case content_alert:	        rv = "alert      (21)";                 break;
    539     case content_handshake:	rv = "handshake  (22)";                 break;
    540     case content_application_data:
    541                                 rv = "application_data (23)";           break;
    542     default:
    543         sprintf(line, "*UNKNOWN* record type! (%d)", msgType);
    544 	rv = line;
    545     }
    546     return rv;
    547 }
    548 
    549 #endif
    550 
    551 SSL3Statistics *
    552 SSL_GetStatistics(void)
    553 {
    554     return &ssl3stats;
    555 }
    556 
    557 typedef struct tooLongStr {
    558 #if defined(IS_LITTLE_ENDIAN)
    559     PRInt32 low;
    560     PRInt32 high;
    561 #else
    562     PRInt32 high;
    563     PRInt32 low;
    564 #endif
    565 } tooLong;
    566 
    567 void SSL_AtomicIncrementLong(long * x)
    568 {
    569     if ((sizeof *x) == sizeof(PRInt32)) {
    570         PR_ATOMIC_INCREMENT((PRInt32 *)x);
    571     } else {
    572     	tooLong * tl = (tooLong *)x;
    573 	if (PR_ATOMIC_INCREMENT(&tl->low) == 0)
    574 	    PR_ATOMIC_INCREMENT(&tl->high);
    575     }
    576 }
    577 
    578 static PRBool
    579 ssl3_CipherSuiteAllowedForVersion(ssl3CipherSuite cipherSuite,
    580 				  SSL3ProtocolVersion version)
    581 {
    582     switch (cipherSuite) {
    583     /* See RFC 4346 A.5. Export cipher suites must not be used in TLS 1.1 or
    584      * later. This set of cipher suites is similar to, but different from, the
    585      * set of cipher suites considered exportable by SSL_IsExportCipherSuite.
    586      */
    587     case SSL_RSA_EXPORT_WITH_RC4_40_MD5:
    588     case SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5:
    589     /*   SSL_RSA_EXPORT_WITH_DES40_CBC_SHA:      never implemented
    590      *   SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA:   never implemented
    591      *   SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA:   never implemented
    592      *   SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA:  never implemented
    593      *   SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA:  never implemented
    594      *   SSL_DH_ANON_EXPORT_WITH_RC4_40_MD5:     never implemented
    595      *   SSL_DH_ANON_EXPORT_WITH_DES40_CBC_SHA:  never implemented
    596      */
    597 	return version <= SSL_LIBRARY_VERSION_TLS_1_0;
    598     case TLS_DHE_RSA_WITH_AES_256_CBC_SHA256:
    599     case TLS_RSA_WITH_AES_256_CBC_SHA256:
    600     case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
    601     case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
    602     case TLS_DHE_RSA_WITH_AES_128_CBC_SHA256:
    603     case TLS_RSA_WITH_AES_128_CBC_SHA256:
    604     case TLS_RSA_WITH_NULL_SHA256:
    605 	return version >= SSL_LIBRARY_VERSION_TLS_1_2;
    606     default:
    607 	return PR_TRUE;
    608     }
    609 }
    610 
    611 /* return pointer to ssl3CipherSuiteDef for suite, or NULL */
    612 /* XXX This does a linear search.  A binary search would be better. */
    613 static const ssl3CipherSuiteDef *
    614 ssl_LookupCipherSuiteDef(ssl3CipherSuite suite)
    615 {
    616     int cipher_suite_def_len =
    617 	sizeof(cipher_suite_defs) / sizeof(cipher_suite_defs[0]);
    618     int i;
    619 
    620     for (i = 0; i < cipher_suite_def_len; i++) {
    621 	if (cipher_suite_defs[i].cipher_suite == suite)
    622 	    return &cipher_suite_defs[i];
    623     }
    624     PORT_Assert(PR_FALSE);  /* We should never get here. */
    625     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
    626     return NULL;
    627 }
    628 
    629 /* Find the cipher configuration struct associate with suite */
    630 /* XXX This does a linear search.  A binary search would be better. */
    631 static ssl3CipherSuiteCfg *
    632 ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite, ssl3CipherSuiteCfg *suites)
    633 {
    634     int i;
    635 
    636     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
    637 	if (suites[i].cipher_suite == suite)
    638 	    return &suites[i];
    639     }
    640     /* return NULL and let the caller handle it.  */
    641     PORT_SetError(SSL_ERROR_UNKNOWN_CIPHER_SUITE);
    642     return NULL;
    643 }
    644 
    645 
    646 /* Initialize the suite->isPresent value for config_match
    647  * Returns count of enabled ciphers supported by extant tokens,
    648  * regardless of policy or user preference.
    649  * If this returns zero, the user cannot do SSL v3.
    650  */
    651 int
    652 ssl3_config_match_init(sslSocket *ss)
    653 {
    654     ssl3CipherSuiteCfg *      suite;
    655     const ssl3CipherSuiteDef *cipher_def;
    656     SSLCipherAlgorithm        cipher_alg;
    657     CK_MECHANISM_TYPE         cipher_mech;
    658     SSL3KEAType               exchKeyType;
    659     int                       i;
    660     int                       numPresent		= 0;
    661     int                       numEnabled		= 0;
    662     PRBool                    isServer;
    663     sslServerCerts           *svrAuth;
    664 
    665     PORT_Assert(ss);
    666     if (!ss) {
    667     	PORT_SetError(SEC_ERROR_INVALID_ARGS);
    668 	return 0;
    669     }
    670     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
    671     	return 0;
    672     }
    673     isServer = (PRBool)(ss->sec.isServer != 0);
    674 
    675     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
    676 	suite = &ss->cipherSuites[i];
    677 	if (suite->enabled) {
    678 	    ++numEnabled;
    679 	    /* We need the cipher defs to see if we have a token that can handle
    680 	     * this cipher.  It isn't part of the static definition.
    681 	     */
    682 	    cipher_def = ssl_LookupCipherSuiteDef(suite->cipher_suite);
    683 	    if (!cipher_def) {
    684 	    	suite->isPresent = PR_FALSE;
    685 		continue;
    686 	    }
    687 	    cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
    688 	    PORT_Assert(  alg2Mech[cipher_alg].calg == cipher_alg);
    689 	    cipher_mech = alg2Mech[cipher_alg].cmech;
    690 	    exchKeyType =
    691 	    	    kea_defs[cipher_def->key_exchange_alg].exchKeyType;
    692 #ifndef NSS_ENABLE_ECC
    693 	    svrAuth = ss->serverCerts + exchKeyType;
    694 #else
    695 	    /* XXX SSLKEAType isn't really a good choice for
    696 	     * indexing certificates. It doesn't work for
    697 	     * (EC)DHE-* ciphers. Here we use a hack to ensure
    698 	     * that the server uses an RSA cert for (EC)DHE-RSA.
    699 	     */
    700 	    switch (cipher_def->key_exchange_alg) {
    701 	    case kea_ecdhe_rsa:
    702 #if NSS_SERVER_DHE_IMPLEMENTED
    703 	    /* XXX NSS does not yet implement the server side of _DHE_
    704 	     * cipher suites.  Correcting the computation for svrAuth,
    705 	     * as the case below does, causes NSS SSL servers to begin to
    706 	     * negotiate cipher suites they do not implement.  So, until
    707 	     * server side _DHE_ is implemented, keep this disabled.
    708 	     */
    709 	    case kea_dhe_rsa:
    710 #endif
    711 		svrAuth = ss->serverCerts + kt_rsa;
    712 		break;
    713 	    case kea_ecdh_ecdsa:
    714 	    case kea_ecdh_rsa:
    715 	        /*
    716 		 * XXX We ought to have different indices for
    717 		 * ECDSA- and RSA-signed EC certificates so
    718 		 * we could support both key exchange mechanisms
    719 		 * simultaneously. For now, both of them use
    720 		 * whatever is in the certificate slot for kt_ecdh
    721 		 */
    722 	    default:
    723 		svrAuth = ss->serverCerts + exchKeyType;
    724 		break;
    725 	    }
    726 #endif /* NSS_ENABLE_ECC */
    727 
    728 	    /* Mark the suites that are backed by real tokens, certs and keys */
    729 	    suite->isPresent = (PRBool)
    730 		(((exchKeyType == kt_null) ||
    731 		   ((!isServer || (svrAuth->serverKeyPair &&
    732 		                   svrAuth->SERVERKEY &&
    733 				   svrAuth->serverCertChain)) &&
    734 		    PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
    735 		((cipher_alg == calg_null) || PK11_TokenExists(cipher_mech)));
    736 	    if (suite->isPresent)
    737 	    	++numPresent;
    738 	}
    739     }
    740     PORT_Assert(numPresent > 0 || numEnabled == 0);
    741     if (numPresent <= 0) {
    742 	PORT_SetError(SSL_ERROR_NO_CIPHERS_SUPPORTED);
    743     }
    744     return numPresent;
    745 }
    746 
    747 
    748 /* return PR_TRUE if suite matches policy and enabled state */
    749 /* It would be a REALLY BAD THING (tm) if we ever permitted the use
    750 ** of a cipher that was NOT_ALLOWED.  So, if this is ever called with
    751 ** policy == SSL_NOT_ALLOWED, report no match.
    752 */
    753 /* adjust suite enabled to the availability of a token that can do the
    754  * cipher suite. */
    755 static PRBool
    756 config_match(ssl3CipherSuiteCfg *suite, int policy, PRBool enabled)
    757 {
    758     PORT_Assert(policy != SSL_NOT_ALLOWED && enabled != PR_FALSE);
    759     if (policy == SSL_NOT_ALLOWED || !enabled)
    760     	return PR_FALSE;
    761     return (PRBool)(suite->enabled &&
    762                     suite->isPresent &&
    763 	            suite->policy != SSL_NOT_ALLOWED &&
    764 		    suite->policy <= policy);
    765 }
    766 
    767 /* return number of cipher suites that match policy and enabled state */
    768 /* called from ssl3_SendClientHello and ssl3_ConstructV2CipherSpecsHack */
    769 static int
    770 count_cipher_suites(sslSocket *ss, int policy, PRBool enabled)
    771 {
    772     int i, count = 0;
    773 
    774     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
    775     	return 0;
    776     }
    777     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
    778 	if (config_match(&ss->cipherSuites[i], policy, enabled))
    779 	    count++;
    780     }
    781     if (count <= 0) {
    782 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
    783     }
    784     return count;
    785 }
    786 
    787 /*
    788  * Null compression, mac and encryption functions
    789  */
    790 
    791 static SECStatus
    792 Null_Cipher(void *ctx, unsigned char *output, int *outputLen, int maxOutputLen,
    793 	    const unsigned char *input, int inputLen)
    794 {
    795     *outputLen = inputLen;
    796     if (input != output)
    797 	PORT_Memcpy(output, input, inputLen);
    798     return SECSuccess;
    799 }
    800 
    801 /*
    802  * SSL3 Utility functions
    803  */
    804 
    805 /* allowLargerPeerVersion controls whether the function will select the
    806  * highest enabled SSL version or fail when peerVersion is greater than the
    807  * highest enabled version.
    808  *
    809  * If allowLargerPeerVersion is true, peerVersion is the peer's highest
    810  * enabled version rather than the peer's selected version.
    811  */
    812 SECStatus
    813 ssl3_NegotiateVersion(sslSocket *ss, SSL3ProtocolVersion peerVersion,
    814 		      PRBool allowLargerPeerVersion)
    815 {
    816     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
    817 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
    818 	return SECFailure;
    819     }
    820 
    821     if (peerVersion < ss->vrange.min ||
    822 	(peerVersion > ss->vrange.max && !allowLargerPeerVersion)) {
    823 	PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
    824 	return SECFailure;
    825     }
    826 
    827     ss->version = PR_MIN(peerVersion, ss->vrange.max);
    828     PORT_Assert(ssl3_VersionIsSupported(ss->protocolVariant, ss->version));
    829 
    830     return SECSuccess;
    831 }
    832 
    833 static SECStatus
    834 ssl3_GetNewRandom(SSL3Random *random)
    835 {
    836     PRUint32 gmt = ssl_Time();
    837     SECStatus rv;
    838 
    839     random->rand[0] = (unsigned char)(gmt >> 24);
    840     random->rand[1] = (unsigned char)(gmt >> 16);
    841     random->rand[2] = (unsigned char)(gmt >>  8);
    842     random->rand[3] = (unsigned char)(gmt);
    843 
    844     /* first 4 bytes are reserverd for time */
    845     rv = PK11_GenerateRandom(&random->rand[4], SSL3_RANDOM_LENGTH - 4);
    846     if (rv != SECSuccess) {
    847 	ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
    848     }
    849     return rv;
    850 }
    851 
    852 /* Called by ssl3_SendServerKeyExchange and ssl3_SendCertificateVerify */
    853 SECStatus
    854 ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, SECItem *buf,
    855                 PRBool isTLS)
    856 {
    857     SECStatus rv		= SECFailure;
    858     PRBool    doDerEncode       = PR_FALSE;
    859     int       signatureLen;
    860     SECItem   hashItem;
    861 
    862     buf->data    = NULL;
    863 
    864     switch (key->keyType) {
    865     case rsaKey:
    866 	hashItem.data = hash->u.raw;
    867 	hashItem.len = hash->len;
    868 	break;
    869     case dsaKey:
    870 	doDerEncode = isTLS;
    871 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
    872 	 * In that case, we use just the SHA1 part. */
    873 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
    874 	    hashItem.data = hash->u.s.sha;
    875 	    hashItem.len = sizeof(hash->u.s.sha);
    876 	} else {
    877 	    hashItem.data = hash->u.raw;
    878 	    hashItem.len = hash->len;
    879 	}
    880 	break;
    881 #ifdef NSS_ENABLE_ECC
    882     case ecKey:
    883 	doDerEncode = PR_TRUE;
    884 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
    885 	 * In that case, we use just the SHA1 part. */
    886 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
    887 	    hashItem.data = hash->u.s.sha;
    888 	    hashItem.len = sizeof(hash->u.s.sha);
    889 	} else {
    890 	    hashItem.data = hash->u.raw;
    891 	    hashItem.len = hash->len;
    892 	}
    893 	break;
    894 #endif /* NSS_ENABLE_ECC */
    895     default:
    896 	PORT_SetError(SEC_ERROR_INVALID_KEY);
    897 	goto done;
    898     }
    899     PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
    900 
    901     if (hash->hashAlg == SEC_OID_UNKNOWN) {
    902 	signatureLen = PK11_SignatureLen(key);
    903 	if (signatureLen <= 0) {
    904 	    PORT_SetError(SEC_ERROR_INVALID_KEY);
    905 	    goto done;
    906 	}
    907 
    908 	buf->len  = (unsigned)signatureLen;
    909 	buf->data = (unsigned char *)PORT_Alloc(signatureLen);
    910 	if (!buf->data)
    911 	    goto done;  /* error code was set. */
    912 
    913 	rv = PK11_Sign(key, buf, &hashItem);
    914     } else {
    915 	rv = SGN_Digest(key, hash->hashAlg, buf, &hashItem);
    916     }
    917     if (rv != SECSuccess) {
    918 	ssl_MapLowLevelError(SSL_ERROR_SIGN_HASHES_FAILURE);
    919     } else if (doDerEncode) {
    920 	SECItem   derSig	= {siBuffer, NULL, 0};
    921 
    922 	/* This also works for an ECDSA signature */
    923 	rv = DSAU_EncodeDerSigWithLen(&derSig, buf, buf->len);
    924 	if (rv == SECSuccess) {
    925 	    PORT_Free(buf->data);	/* discard unencoded signature. */
    926 	    *buf = derSig;		/* give caller encoded signature. */
    927 	} else if (derSig.data) {
    928 	    PORT_Free(derSig.data);
    929 	}
    930     }
    931 
    932     PRINT_BUF(60, (NULL, "signed hashes", (unsigned char*)buf->data, buf->len));
    933 done:
    934     if (rv != SECSuccess && buf->data) {
    935 	PORT_Free(buf->data);
    936 	buf->data = NULL;
    937     }
    938     return rv;
    939 }
    940 
    941 /* Called from ssl3_HandleServerKeyExchange, ssl3_HandleCertificateVerify */
    942 SECStatus
    943 ssl3_VerifySignedHashes(SSL3Hashes *hash, CERTCertificate *cert,
    944                         SECItem *buf, PRBool isTLS, void *pwArg)
    945 {
    946     SECKEYPublicKey * key;
    947     SECItem *         signature	= NULL;
    948     SECStatus         rv;
    949     SECItem           hashItem;
    950     SECOidTag         encAlg;
    951     SECOidTag         hashAlg;
    952 
    953 
    954     PRINT_BUF(60, (NULL, "check signed hashes",
    955                   buf->data, buf->len));
    956 
    957     key = CERT_ExtractPublicKey(cert);
    958     if (key == NULL) {
    959 	ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
    960     	return SECFailure;
    961     }
    962 
    963     hashAlg = hash->hashAlg;
    964     switch (key->keyType) {
    965     case rsaKey:
    966 	encAlg = SEC_OID_PKCS1_RSA_ENCRYPTION;
    967 	hashItem.data = hash->u.raw;
    968 	hashItem.len = hash->len;
    969 	break;
    970     case dsaKey:
    971 	encAlg = SEC_OID_ANSIX9_DSA_SIGNATURE;
    972 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
    973 	 * In that case, we use just the SHA1 part. */
    974 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
    975 	    hashItem.data = hash->u.s.sha;
    976 	    hashItem.len = sizeof(hash->u.s.sha);
    977 	} else {
    978 	    hashItem.data = hash->u.raw;
    979 	    hashItem.len = hash->len;
    980 	}
    981 	/* Allow DER encoded DSA signatures in SSL 3.0 */
    982 	if (isTLS || buf->len != SECKEY_SignatureLen(key)) {
    983 	    signature = DSAU_DecodeDerSig(buf);
    984 	    if (!signature) {
    985 	    	PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
    986 		return SECFailure;
    987 	    }
    988 	    buf = signature;
    989 	}
    990 	break;
    991 
    992 #ifdef NSS_ENABLE_ECC
    993     case ecKey:
    994 	encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
    995 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
    996 	 * In that case, we use just the SHA1 part.
    997 	 * ECDSA signatures always encode the integers r and s using ASN.1
    998 	 * (unlike DSA where ASN.1 encoding is used with TLS but not with
    999 	 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
   1000 	 */
   1001 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
   1002 	    hashAlg = SEC_OID_SHA1;
   1003 	    hashItem.data = hash->u.s.sha;
   1004 	    hashItem.len = sizeof(hash->u.s.sha);
   1005 	} else {
   1006 	    hashItem.data = hash->u.raw;
   1007 	    hashItem.len = hash->len;
   1008 	}
   1009 	break;
   1010 #endif /* NSS_ENABLE_ECC */
   1011 
   1012     default:
   1013     	SECKEY_DestroyPublicKey(key);
   1014 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   1015 	return SECFailure;
   1016     }
   1017 
   1018     PRINT_BUF(60, (NULL, "hash(es) to be verified",
   1019                   hashItem.data, hashItem.len));
   1020 
   1021     if (hashAlg == SEC_OID_UNKNOWN || key->keyType == dsaKey) {
   1022 	/* VFY_VerifyDigestDirect requires DSA signatures to be DER-encoded.
   1023 	 * DSA signatures are DER-encoded in TLS but not in SSL3 and the code
   1024 	 * above always removes the DER encoding of DSA signatures when
   1025 	 * present. Thus DSA signatures are always verified with PK11_Verify.
   1026 	 */
   1027 	rv = PK11_Verify(key, buf, &hashItem, pwArg);
   1028     } else {
   1029 	rv = VFY_VerifyDigestDirect(&hashItem, key, buf, encAlg, hashAlg,
   1030 				    pwArg);
   1031     }
   1032     SECKEY_DestroyPublicKey(key);
   1033     if (signature) {
   1034     	SECITEM_FreeItem(signature, PR_TRUE);
   1035     }
   1036     if (rv != SECSuccess) {
   1037 	ssl_MapLowLevelError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   1038     }
   1039     return rv;
   1040 }
   1041 
   1042 
   1043 /* Caller must set hiLevel error code. */
   1044 /* Called from ssl3_ComputeExportRSAKeyHash
   1045  *             ssl3_ComputeDHKeyHash
   1046  * which are called from ssl3_HandleServerKeyExchange.
   1047  *
   1048  * hashAlg: either the OID for a hash algorithm or SEC_OID_UNKNOWN to specify
   1049  * the pre-1.2, MD5/SHA1 combination hash.
   1050  */
   1051 SECStatus
   1052 ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
   1053 			  PRUint8 * hashBuf, unsigned int bufLen,
   1054 			  SSL3Hashes *hashes, PRBool bypassPKCS11)
   1055 {
   1056     SECStatus     rv 		= SECSuccess;
   1057 
   1058 #ifndef NO_PKCS11_BYPASS
   1059     if (bypassPKCS11) {
   1060 	if (hashAlg == SEC_OID_UNKNOWN) {
   1061 	    MD5_HashBuf (hashes->u.s.md5, hashBuf, bufLen);
   1062 	    SHA1_HashBuf(hashes->u.s.sha, hashBuf, bufLen);
   1063 	    hashes->len = MD5_LENGTH + SHA1_LENGTH;
   1064 	} else if (hashAlg == SEC_OID_SHA1) {
   1065 	    SHA1_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1066 	    hashes->len = SHA1_LENGTH;
   1067 	} else if (hashAlg == SEC_OID_SHA256) {
   1068 	    SHA256_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1069 	    hashes->len = SHA256_LENGTH;
   1070 	} else if (hashAlg == SEC_OID_SHA384) {
   1071 	    SHA384_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1072 	    hashes->len = SHA384_LENGTH;
   1073 	} else if (hashAlg == SEC_OID_SHA512) {
   1074 	    SHA512_HashBuf(hashes->u.raw, hashBuf, bufLen);
   1075 	    hashes->len = SHA512_LENGTH;
   1076 	} else {
   1077 	    PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   1078 	    return SECFailure;
   1079 	}
   1080     } else
   1081 #endif
   1082     {
   1083 	if (hashAlg == SEC_OID_UNKNOWN) {
   1084 	    rv = PK11_HashBuf(SEC_OID_MD5, hashes->u.s.md5, hashBuf, bufLen);
   1085 	    if (rv != SECSuccess) {
   1086 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   1087 		rv = SECFailure;
   1088 		goto done;
   1089 	    }
   1090 
   1091 	    rv = PK11_HashBuf(SEC_OID_SHA1, hashes->u.s.sha, hashBuf, bufLen);
   1092 	    if (rv != SECSuccess) {
   1093 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   1094 		rv = SECFailure;
   1095 	    }
   1096 	    hashes->len = MD5_LENGTH + SHA1_LENGTH;
   1097 	} else {
   1098 	    hashes->len = HASH_ResultLenByOidTag(hashAlg);
   1099 	    if (hashes->len > sizeof(hashes->u.raw)) {
   1100 		ssl_MapLowLevelError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   1101 		rv = SECFailure;
   1102 		goto done;
   1103 	    }
   1104 	    rv = PK11_HashBuf(hashAlg, hashes->u.raw, hashBuf, bufLen);
   1105 	    if (rv != SECSuccess) {
   1106 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   1107 		rv = SECFailure;
   1108 	    }
   1109 	}
   1110     }
   1111     hashes->hashAlg = hashAlg;
   1112 
   1113 done:
   1114     return rv;
   1115 }
   1116 
   1117 /* Caller must set hiLevel error code.
   1118 ** Called from ssl3_SendServerKeyExchange and
   1119 **             ssl3_HandleServerKeyExchange.
   1120 */
   1121 static SECStatus
   1122 ssl3_ComputeExportRSAKeyHash(SECOidTag hashAlg,
   1123 			     SECItem modulus, SECItem publicExponent,
   1124 			     SSL3Random *client_rand, SSL3Random *server_rand,
   1125 			     SSL3Hashes *hashes, PRBool bypassPKCS11)
   1126 {
   1127     PRUint8     * hashBuf;
   1128     PRUint8     * pBuf;
   1129     SECStatus     rv 		= SECSuccess;
   1130     unsigned int  bufLen;
   1131     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
   1132 
   1133     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + modulus.len + 2 + publicExponent.len;
   1134     if (bufLen <= sizeof buf) {
   1135     	hashBuf = buf;
   1136     } else {
   1137     	hashBuf = PORT_Alloc(bufLen);
   1138 	if (!hashBuf) {
   1139 	    return SECFailure;
   1140 	}
   1141     }
   1142 
   1143     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
   1144     	pBuf = hashBuf + SSL3_RANDOM_LENGTH;
   1145     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
   1146     	pBuf += SSL3_RANDOM_LENGTH;
   1147     pBuf[0]  = (PRUint8)(modulus.len >> 8);
   1148     pBuf[1]  = (PRUint8)(modulus.len);
   1149     	pBuf += 2;
   1150     memcpy(pBuf, modulus.data, modulus.len);
   1151     	pBuf += modulus.len;
   1152     pBuf[0] = (PRUint8)(publicExponent.len >> 8);
   1153     pBuf[1] = (PRUint8)(publicExponent.len);
   1154     	pBuf += 2;
   1155     memcpy(pBuf, publicExponent.data, publicExponent.len);
   1156     	pBuf += publicExponent.len;
   1157     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
   1158 
   1159     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
   1160 				   bypassPKCS11);
   1161 
   1162     PRINT_BUF(95, (NULL, "RSAkey hash: ", hashBuf, bufLen));
   1163     if (hashAlg == SEC_OID_UNKNOWN) {
   1164 	PRINT_BUF(95, (NULL, "RSAkey hash: MD5 result",
   1165 		  hashes->u.s.md5, MD5_LENGTH));
   1166 	PRINT_BUF(95, (NULL, "RSAkey hash: SHA1 result",
   1167 		  hashes->u.s.sha, SHA1_LENGTH));
   1168     } else {
   1169 	PRINT_BUF(95, (NULL, "RSAkey hash: result",
   1170 		  hashes->u.raw, hashes->len));
   1171     }
   1172 
   1173     if (hashBuf != buf && hashBuf != NULL)
   1174     	PORT_Free(hashBuf);
   1175     return rv;
   1176 }
   1177 
   1178 /* Caller must set hiLevel error code. */
   1179 /* Called from ssl3_HandleServerKeyExchange. */
   1180 static SECStatus
   1181 ssl3_ComputeDHKeyHash(SECOidTag hashAlg,
   1182 		      SECItem dh_p, SECItem dh_g, SECItem dh_Ys,
   1183 		      SSL3Random *client_rand, SSL3Random *server_rand,
   1184 		      SSL3Hashes *hashes, PRBool bypassPKCS11)
   1185 {
   1186     PRUint8     * hashBuf;
   1187     PRUint8     * pBuf;
   1188     SECStatus     rv 		= SECSuccess;
   1189     unsigned int  bufLen;
   1190     PRUint8       buf[2*SSL3_RANDOM_LENGTH + 2 + 4096/8 + 2 + 4096/8];
   1191 
   1192     bufLen = 2*SSL3_RANDOM_LENGTH + 2 + dh_p.len + 2 + dh_g.len + 2 + dh_Ys.len;
   1193     if (bufLen <= sizeof buf) {
   1194     	hashBuf = buf;
   1195     } else {
   1196     	hashBuf = PORT_Alloc(bufLen);
   1197 	if (!hashBuf) {
   1198 	    return SECFailure;
   1199 	}
   1200     }
   1201 
   1202     memcpy(hashBuf, client_rand, SSL3_RANDOM_LENGTH);
   1203     	pBuf = hashBuf + SSL3_RANDOM_LENGTH;
   1204     memcpy(pBuf, server_rand, SSL3_RANDOM_LENGTH);
   1205     	pBuf += SSL3_RANDOM_LENGTH;
   1206     pBuf[0]  = (PRUint8)(dh_p.len >> 8);
   1207     pBuf[1]  = (PRUint8)(dh_p.len);
   1208     	pBuf += 2;
   1209     memcpy(pBuf, dh_p.data, dh_p.len);
   1210     	pBuf += dh_p.len;
   1211     pBuf[0] = (PRUint8)(dh_g.len >> 8);
   1212     pBuf[1] = (PRUint8)(dh_g.len);
   1213     	pBuf += 2;
   1214     memcpy(pBuf, dh_g.data, dh_g.len);
   1215     	pBuf += dh_g.len;
   1216     pBuf[0] = (PRUint8)(dh_Ys.len >> 8);
   1217     pBuf[1] = (PRUint8)(dh_Ys.len);
   1218     	pBuf += 2;
   1219     memcpy(pBuf, dh_Ys.data, dh_Ys.len);
   1220     	pBuf += dh_Ys.len;
   1221     PORT_Assert((unsigned int)(pBuf - hashBuf) == bufLen);
   1222 
   1223     rv = ssl3_ComputeCommonKeyHash(hashAlg, hashBuf, bufLen, hashes,
   1224 				   bypassPKCS11);
   1225 
   1226     PRINT_BUF(95, (NULL, "DHkey hash: ", hashBuf, bufLen));
   1227     if (hashAlg == SEC_OID_UNKNOWN) {
   1228 	PRINT_BUF(95, (NULL, "DHkey hash: MD5 result",
   1229 		  hashes->u.s.md5, MD5_LENGTH));
   1230 	PRINT_BUF(95, (NULL, "DHkey hash: SHA1 result",
   1231 		  hashes->u.s.sha, SHA1_LENGTH));
   1232     } else {
   1233 	PRINT_BUF(95, (NULL, "DHkey hash: result",
   1234 		  hashes->u.raw, hashes->len));
   1235     }
   1236 
   1237     if (hashBuf != buf && hashBuf != NULL)
   1238     	PORT_Free(hashBuf);
   1239     return rv;
   1240 }
   1241 
   1242 static void
   1243 ssl3_BumpSequenceNumber(SSL3SequenceNumber *num)
   1244 {
   1245     num->low++;
   1246     if (num->low == 0)
   1247 	num->high++;
   1248 }
   1249 
   1250 /* Called twice, only from ssl3_DestroyCipherSpec (immediately below). */
   1251 static void
   1252 ssl3_CleanupKeyMaterial(ssl3KeyMaterial *mat)
   1253 {
   1254     if (mat->write_key != NULL) {
   1255 	PK11_FreeSymKey(mat->write_key);
   1256 	mat->write_key = NULL;
   1257     }
   1258     if (mat->write_mac_key != NULL) {
   1259 	PK11_FreeSymKey(mat->write_mac_key);
   1260 	mat->write_mac_key = NULL;
   1261     }
   1262     if (mat->write_mac_context != NULL) {
   1263 	PK11_DestroyContext(mat->write_mac_context, PR_TRUE);
   1264 	mat->write_mac_context = NULL;
   1265     }
   1266 }
   1267 
   1268 /* Called from ssl3_SendChangeCipherSpecs() and
   1269 **	       ssl3_HandleChangeCipherSpecs()
   1270 **             ssl3_DestroySSL3Info
   1271 ** Caller must hold SpecWriteLock.
   1272 */
   1273 void
   1274 ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName)
   1275 {
   1276     PRBool freeit = (PRBool)(!spec->bypassCiphers);
   1277 /*  PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss)); Don't have ss! */
   1278     if (spec->destroy) {
   1279 	spec->destroy(spec->encodeContext, freeit);
   1280 	spec->destroy(spec->decodeContext, freeit);
   1281 	spec->encodeContext = NULL; /* paranoia */
   1282 	spec->decodeContext = NULL;
   1283     }
   1284     if (spec->destroyCompressContext && spec->compressContext) {
   1285 	spec->destroyCompressContext(spec->compressContext, 1);
   1286 	spec->compressContext = NULL;
   1287     }
   1288     if (spec->destroyDecompressContext && spec->decompressContext) {
   1289 	spec->destroyDecompressContext(spec->decompressContext, 1);
   1290 	spec->decompressContext = NULL;
   1291     }
   1292     if (freeSrvName && spec->srvVirtName.data) {
   1293         SECITEM_FreeItem(&spec->srvVirtName, PR_FALSE);
   1294     }
   1295     if (spec->master_secret != NULL) {
   1296 	PK11_FreeSymKey(spec->master_secret);
   1297 	spec->master_secret = NULL;
   1298     }
   1299     spec->msItem.data = NULL;
   1300     spec->msItem.len  = 0;
   1301     ssl3_CleanupKeyMaterial(&spec->client);
   1302     ssl3_CleanupKeyMaterial(&spec->server);
   1303     spec->bypassCiphers = PR_FALSE;
   1304     spec->destroy=NULL;
   1305     spec->destroyCompressContext = NULL;
   1306     spec->destroyDecompressContext = NULL;
   1307 }
   1308 
   1309 /* Fill in the pending cipher spec with info from the selected ciphersuite.
   1310 ** This is as much initialization as we can do without having key material.
   1311 ** Called from ssl3_HandleServerHello(), ssl3_SendServerHello()
   1312 ** Caller must hold the ssl3 handshake lock.
   1313 ** Acquires & releases SpecWriteLock.
   1314 */
   1315 static SECStatus
   1316 ssl3_SetupPendingCipherSpec(sslSocket *ss)
   1317 {
   1318     ssl3CipherSpec *          pwSpec;
   1319     ssl3CipherSpec *          cwSpec;
   1320     ssl3CipherSuite           suite     = ss->ssl3.hs.cipher_suite;
   1321     SSL3MACAlgorithm          mac;
   1322     SSL3BulkCipher            cipher;
   1323     SSL3KeyExchangeAlgorithm  kea;
   1324     const ssl3CipherSuiteDef *suite_def;
   1325     PRBool                    isTLS;
   1326 
   1327     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1328 
   1329     ssl_GetSpecWriteLock(ss);  /*******************************/
   1330 
   1331     pwSpec = ss->ssl3.pwSpec;
   1332     PORT_Assert(pwSpec == ss->ssl3.prSpec);
   1333 
   1334     /* This hack provides maximal interoperability with SSL 3 servers. */
   1335     cwSpec = ss->ssl3.cwSpec;
   1336     if (cwSpec->mac_def->mac == mac_null) {
   1337 	/* SSL records are not being MACed. */
   1338 	cwSpec->version = ss->version;
   1339     }
   1340 
   1341     pwSpec->version  = ss->version;
   1342     isTLS  = (PRBool)(pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   1343 
   1344     SSL_TRC(3, ("%d: SSL3[%d]: Set XXX Pending Cipher Suite to 0x%04x",
   1345 		SSL_GETPID(), ss->fd, suite));
   1346 
   1347     suite_def = ssl_LookupCipherSuiteDef(suite);
   1348     if (suite_def == NULL) {
   1349 	ssl_ReleaseSpecWriteLock(ss);
   1350 	return SECFailure;	/* error code set by ssl_LookupCipherSuiteDef */
   1351     }
   1352 
   1353     if (IS_DTLS(ss)) {
   1354 	/* Double-check that we did not pick an RC4 suite */
   1355 	PORT_Assert((suite_def->bulk_cipher_alg != cipher_rc4) &&
   1356 		    (suite_def->bulk_cipher_alg != cipher_rc4_40) &&
   1357 		    (suite_def->bulk_cipher_alg != cipher_rc4_56));
   1358     }
   1359 
   1360     cipher = suite_def->bulk_cipher_alg;
   1361     kea    = suite_def->key_exchange_alg;
   1362     mac    = suite_def->mac_alg;
   1363     if (mac <= ssl_mac_sha && isTLS)
   1364 	mac += 2;
   1365 
   1366     ss->ssl3.hs.suite_def = suite_def;
   1367     ss->ssl3.hs.kea_def   = &kea_defs[kea];
   1368     PORT_Assert(ss->ssl3.hs.kea_def->kea == kea);
   1369 
   1370     pwSpec->cipher_def   = &bulk_cipher_defs[cipher];
   1371     PORT_Assert(pwSpec->cipher_def->cipher == cipher);
   1372 
   1373     pwSpec->mac_def = &mac_defs[mac];
   1374     PORT_Assert(pwSpec->mac_def->mac == mac);
   1375 
   1376     ss->sec.keyBits       = pwSpec->cipher_def->key_size        * BPB;
   1377     ss->sec.secretKeyBits = pwSpec->cipher_def->secret_key_size * BPB;
   1378     ss->sec.cipherType    = cipher;
   1379 
   1380     pwSpec->encodeContext = NULL;
   1381     pwSpec->decodeContext = NULL;
   1382 
   1383     pwSpec->mac_size = pwSpec->mac_def->mac_size;
   1384 
   1385     pwSpec->compression_method = ss->ssl3.hs.compression;
   1386     pwSpec->compressContext = NULL;
   1387     pwSpec->decompressContext = NULL;
   1388 
   1389     ssl_ReleaseSpecWriteLock(ss);  /*******************************/
   1390     return SECSuccess;
   1391 }
   1392 
   1393 #ifdef NSS_ENABLE_ZLIB
   1394 #define SSL3_DEFLATE_CONTEXT_SIZE sizeof(z_stream)
   1395 
   1396 static SECStatus
   1397 ssl3_MapZlibError(int zlib_error)
   1398 {
   1399     switch (zlib_error) {
   1400     case Z_OK:
   1401         return SECSuccess;
   1402     default:
   1403         return SECFailure;
   1404     }
   1405 }
   1406 
   1407 static SECStatus
   1408 ssl3_DeflateInit(void *void_context)
   1409 {
   1410     z_stream *context = void_context;
   1411     context->zalloc = NULL;
   1412     context->zfree = NULL;
   1413     context->opaque = NULL;
   1414 
   1415     return ssl3_MapZlibError(deflateInit(context, Z_DEFAULT_COMPRESSION));
   1416 }
   1417 
   1418 static SECStatus
   1419 ssl3_InflateInit(void *void_context)
   1420 {
   1421     z_stream *context = void_context;
   1422     context->zalloc = NULL;
   1423     context->zfree = NULL;
   1424     context->opaque = NULL;
   1425     context->next_in = NULL;
   1426     context->avail_in = 0;
   1427 
   1428     return ssl3_MapZlibError(inflateInit(context));
   1429 }
   1430 
   1431 static SECStatus
   1432 ssl3_DeflateCompress(void *void_context, unsigned char *out, int *out_len,
   1433                      int maxout, const unsigned char *in, int inlen)
   1434 {
   1435     z_stream *context = void_context;
   1436 
   1437     if (!inlen) {
   1438         *out_len = 0;
   1439         return SECSuccess;
   1440     }
   1441 
   1442     context->next_in = (unsigned char*) in;
   1443     context->avail_in = inlen;
   1444     context->next_out = out;
   1445     context->avail_out = maxout;
   1446     if (deflate(context, Z_SYNC_FLUSH) != Z_OK) {
   1447         return SECFailure;
   1448     }
   1449     if (context->avail_out == 0) {
   1450         /* We ran out of space! */
   1451         SSL_TRC(3, ("%d: SSL3[%d] Ran out of buffer while compressing",
   1452                     SSL_GETPID()));
   1453         return SECFailure;
   1454     }
   1455 
   1456     *out_len = maxout - context->avail_out;
   1457     return SECSuccess;
   1458 }
   1459 
   1460 static SECStatus
   1461 ssl3_DeflateDecompress(void *void_context, unsigned char *out, int *out_len,
   1462                        int maxout, const unsigned char *in, int inlen)
   1463 {
   1464     z_stream *context = void_context;
   1465 
   1466     if (!inlen) {
   1467         *out_len = 0;
   1468         return SECSuccess;
   1469     }
   1470 
   1471     context->next_in = (unsigned char*) in;
   1472     context->avail_in = inlen;
   1473     context->next_out = out;
   1474     context->avail_out = maxout;
   1475     if (inflate(context, Z_SYNC_FLUSH) != Z_OK) {
   1476         PORT_SetError(SSL_ERROR_DECOMPRESSION_FAILURE);
   1477         return SECFailure;
   1478     }
   1479 
   1480     *out_len = maxout - context->avail_out;
   1481     return SECSuccess;
   1482 }
   1483 
   1484 static SECStatus
   1485 ssl3_DestroyCompressContext(void *void_context, PRBool unused)
   1486 {
   1487     deflateEnd(void_context);
   1488     PORT_Free(void_context);
   1489     return SECSuccess;
   1490 }
   1491 
   1492 static SECStatus
   1493 ssl3_DestroyDecompressContext(void *void_context, PRBool unused)
   1494 {
   1495     inflateEnd(void_context);
   1496     PORT_Free(void_context);
   1497     return SECSuccess;
   1498 }
   1499 
   1500 #endif /* NSS_ENABLE_ZLIB */
   1501 
   1502 /* Initialize the compression functions and contexts for the given
   1503  * CipherSpec.  */
   1504 static SECStatus
   1505 ssl3_InitCompressionContext(ssl3CipherSpec *pwSpec)
   1506 {
   1507     /* Setup the compression functions */
   1508     switch (pwSpec->compression_method) {
   1509     case ssl_compression_null:
   1510 	pwSpec->compressor = NULL;
   1511 	pwSpec->decompressor = NULL;
   1512 	pwSpec->compressContext = NULL;
   1513 	pwSpec->decompressContext = NULL;
   1514 	pwSpec->destroyCompressContext = NULL;
   1515 	pwSpec->destroyDecompressContext = NULL;
   1516 	break;
   1517 #ifdef NSS_ENABLE_ZLIB
   1518     case ssl_compression_deflate:
   1519 	pwSpec->compressor = ssl3_DeflateCompress;
   1520 	pwSpec->decompressor = ssl3_DeflateDecompress;
   1521 	pwSpec->compressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
   1522 	pwSpec->decompressContext = PORT_Alloc(SSL3_DEFLATE_CONTEXT_SIZE);
   1523 	pwSpec->destroyCompressContext = ssl3_DestroyCompressContext;
   1524 	pwSpec->destroyDecompressContext = ssl3_DestroyDecompressContext;
   1525 	ssl3_DeflateInit(pwSpec->compressContext);
   1526 	ssl3_InflateInit(pwSpec->decompressContext);
   1527 	break;
   1528 #endif /* NSS_ENABLE_ZLIB */
   1529     default:
   1530 	PORT_Assert(0);
   1531 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1532 	return SECFailure;
   1533     }
   1534 
   1535     return SECSuccess;
   1536 }
   1537 
   1538 #ifndef NO_PKCS11_BYPASS
   1539 /* Initialize encryption contexts for pending spec.
   1540  * MAC contexts are set up when computing the mac, not here.
   1541  * Master Secret already is derived in spec->msItem
   1542  * Caller holds Spec write lock.
   1543  */
   1544 static SECStatus
   1545 ssl3_InitPendingContextsBypass(sslSocket *ss)
   1546 {
   1547       ssl3CipherSpec  *  pwSpec;
   1548       const ssl3BulkCipherDef *cipher_def;
   1549       void *             serverContext = NULL;
   1550       void *             clientContext = NULL;
   1551       BLapiInitContextFunc initFn = (BLapiInitContextFunc)NULL;
   1552       int                mode     = 0;
   1553       unsigned int       optArg1  = 0;
   1554       unsigned int       optArg2  = 0;
   1555       PRBool             server_encrypts = ss->sec.isServer;
   1556       SSLCipherAlgorithm calg;
   1557       SSLCompressionMethod compression_method;
   1558       SECStatus          rv;
   1559 
   1560     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1561     PORT_Assert(ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   1562     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   1563 
   1564     pwSpec        = ss->ssl3.pwSpec;
   1565     cipher_def    = pwSpec->cipher_def;
   1566 
   1567     calg = cipher_def->calg;
   1568     compression_method = pwSpec->compression_method;
   1569 
   1570     serverContext = pwSpec->server.cipher_context;
   1571     clientContext = pwSpec->client.cipher_context;
   1572 
   1573     switch (calg) {
   1574     case ssl_calg_null:
   1575 	pwSpec->encode  = Null_Cipher;
   1576 	pwSpec->decode  = Null_Cipher;
   1577         pwSpec->destroy = NULL;
   1578 	goto success;
   1579 
   1580     case ssl_calg_rc4:
   1581       	initFn = (BLapiInitContextFunc)RC4_InitContext;
   1582 	pwSpec->encode  = (SSLCipher) RC4_Encrypt;
   1583 	pwSpec->decode  = (SSLCipher) RC4_Decrypt;
   1584 	pwSpec->destroy = (SSLDestroy) RC4_DestroyContext;
   1585 	break;
   1586     case ssl_calg_rc2:
   1587       	initFn = (BLapiInitContextFunc)RC2_InitContext;
   1588 	mode = NSS_RC2_CBC;
   1589 	optArg1 = cipher_def->key_size;
   1590 	pwSpec->encode  = (SSLCipher) RC2_Encrypt;
   1591 	pwSpec->decode  = (SSLCipher) RC2_Decrypt;
   1592 	pwSpec->destroy = (SSLDestroy) RC2_DestroyContext;
   1593 	break;
   1594     case ssl_calg_des:
   1595       	initFn = (BLapiInitContextFunc)DES_InitContext;
   1596 	mode = NSS_DES_CBC;
   1597 	optArg1 = server_encrypts;
   1598 	pwSpec->encode  = (SSLCipher) DES_Encrypt;
   1599 	pwSpec->decode  = (SSLCipher) DES_Decrypt;
   1600 	pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
   1601 	break;
   1602     case ssl_calg_3des:
   1603       	initFn = (BLapiInitContextFunc)DES_InitContext;
   1604 	mode = NSS_DES_EDE3_CBC;
   1605 	optArg1 = server_encrypts;
   1606 	pwSpec->encode  = (SSLCipher) DES_Encrypt;
   1607 	pwSpec->decode  = (SSLCipher) DES_Decrypt;
   1608 	pwSpec->destroy = (SSLDestroy) DES_DestroyContext;
   1609 	break;
   1610     case ssl_calg_aes:
   1611       	initFn = (BLapiInitContextFunc)AES_InitContext;
   1612 	mode = NSS_AES_CBC;
   1613 	optArg1 = server_encrypts;
   1614 	optArg2 = AES_BLOCK_SIZE;
   1615 	pwSpec->encode  = (SSLCipher) AES_Encrypt;
   1616 	pwSpec->decode  = (SSLCipher) AES_Decrypt;
   1617 	pwSpec->destroy = (SSLDestroy) AES_DestroyContext;
   1618 	break;
   1619 
   1620     case ssl_calg_camellia:
   1621       	initFn = (BLapiInitContextFunc)Camellia_InitContext;
   1622 	mode = NSS_CAMELLIA_CBC;
   1623 	optArg1 = server_encrypts;
   1624 	optArg2 = CAMELLIA_BLOCK_SIZE;
   1625 	pwSpec->encode  = (SSLCipher) Camellia_Encrypt;
   1626 	pwSpec->decode  = (SSLCipher) Camellia_Decrypt;
   1627 	pwSpec->destroy = (SSLDestroy) Camellia_DestroyContext;
   1628 	break;
   1629 
   1630     case ssl_calg_seed:
   1631       	initFn = (BLapiInitContextFunc)SEED_InitContext;
   1632 	mode = NSS_SEED_CBC;
   1633 	optArg1 = server_encrypts;
   1634 	optArg2 = SEED_BLOCK_SIZE;
   1635 	pwSpec->encode  = (SSLCipher) SEED_Encrypt;
   1636 	pwSpec->decode  = (SSLCipher) SEED_Decrypt;
   1637 	pwSpec->destroy = (SSLDestroy) SEED_DestroyContext;
   1638 	break;
   1639 
   1640     case ssl_calg_idea:
   1641     case ssl_calg_fortezza :
   1642     default:
   1643 	PORT_Assert(0);
   1644 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1645 	goto bail_out;
   1646     }
   1647     rv = (*initFn)(serverContext,
   1648 		   pwSpec->server.write_key_item.data,
   1649 		   pwSpec->server.write_key_item.len,
   1650 		   pwSpec->server.write_iv_item.data,
   1651 		   mode, optArg1, optArg2);
   1652     if (rv != SECSuccess) {
   1653 	PORT_Assert(0);
   1654 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1655 	goto bail_out;
   1656     }
   1657 
   1658     switch (calg) {
   1659     case ssl_calg_des:
   1660     case ssl_calg_3des:
   1661     case ssl_calg_aes:
   1662     case ssl_calg_camellia:
   1663     case ssl_calg_seed:
   1664 	/* For block ciphers, if the server is encrypting, then the client
   1665 	* is decrypting, and vice versa.
   1666 	*/
   1667         optArg1 = !optArg1;
   1668         break;
   1669     /* kill warnings. */
   1670     case ssl_calg_null:
   1671     case ssl_calg_rc4:
   1672     case ssl_calg_rc2:
   1673     case ssl_calg_idea:
   1674     case ssl_calg_fortezza:
   1675         break;
   1676     }
   1677 
   1678     rv = (*initFn)(clientContext,
   1679 		   pwSpec->client.write_key_item.data,
   1680 		   pwSpec->client.write_key_item.len,
   1681 		   pwSpec->client.write_iv_item.data,
   1682 		   mode, optArg1, optArg2);
   1683     if (rv != SECSuccess) {
   1684 	PORT_Assert(0);
   1685 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1686 	goto bail_out;
   1687     }
   1688 
   1689     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
   1690     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
   1691 
   1692     ssl3_InitCompressionContext(pwSpec);
   1693 
   1694 success:
   1695     return SECSuccess;
   1696 
   1697 bail_out:
   1698     return SECFailure;
   1699 }
   1700 #endif
   1701 
   1702 /* This function should probably be moved to pk11wrap and be named
   1703  * PK11_ParamFromIVAndEffectiveKeyBits
   1704  */
   1705 static SECItem *
   1706 ssl3_ParamFromIV(CK_MECHANISM_TYPE mtype, SECItem *iv, CK_ULONG ulEffectiveBits)
   1707 {
   1708     SECItem * param = PK11_ParamFromIV(mtype, iv);
   1709     if (param && param->data  && param->len >= sizeof(CK_RC2_PARAMS)) {
   1710 	switch (mtype) {
   1711 	case CKM_RC2_KEY_GEN:
   1712 	case CKM_RC2_ECB:
   1713 	case CKM_RC2_CBC:
   1714 	case CKM_RC2_MAC:
   1715 	case CKM_RC2_MAC_GENERAL:
   1716 	case CKM_RC2_CBC_PAD:
   1717 	    *(CK_RC2_PARAMS *)param->data = ulEffectiveBits;
   1718 	default: break;
   1719 	}
   1720     }
   1721     return param;
   1722 }
   1723 
   1724 /* Initialize encryption and MAC contexts for pending spec.
   1725  * Master Secret already is derived.
   1726  * Caller holds Spec write lock.
   1727  */
   1728 static SECStatus
   1729 ssl3_InitPendingContextsPKCS11(sslSocket *ss)
   1730 {
   1731       ssl3CipherSpec  *  pwSpec;
   1732       const ssl3BulkCipherDef *cipher_def;
   1733       PK11Context *      serverContext = NULL;
   1734       PK11Context *      clientContext = NULL;
   1735       SECItem *          param;
   1736       CK_MECHANISM_TYPE  mechanism;
   1737       CK_MECHANISM_TYPE  mac_mech;
   1738       CK_ULONG           macLength;
   1739       CK_ULONG           effKeyBits;
   1740       SECItem            iv;
   1741       SECItem            mac_param;
   1742       SSLCipherAlgorithm calg;
   1743 
   1744     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1745     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   1746     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   1747 
   1748     pwSpec        = ss->ssl3.pwSpec;
   1749     cipher_def    = pwSpec->cipher_def;
   1750     macLength     = pwSpec->mac_size;
   1751 
   1752     /*
   1753     ** Now setup the MAC contexts,
   1754     **   crypto contexts are setup below.
   1755     */
   1756 
   1757     pwSpec->client.write_mac_context = NULL;
   1758     pwSpec->server.write_mac_context = NULL;
   1759     mac_mech       = pwSpec->mac_def->mmech;
   1760     mac_param.data = (unsigned char *)&macLength;
   1761     mac_param.len  = sizeof(macLength);
   1762     mac_param.type = 0;
   1763 
   1764     pwSpec->client.write_mac_context = PK11_CreateContextBySymKey(
   1765 	    mac_mech, CKA_SIGN, pwSpec->client.write_mac_key, &mac_param);
   1766     if (pwSpec->client.write_mac_context == NULL)  {
   1767 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   1768 	goto fail;
   1769     }
   1770     pwSpec->server.write_mac_context = PK11_CreateContextBySymKey(
   1771 	    mac_mech, CKA_SIGN, pwSpec->server.write_mac_key, &mac_param);
   1772     if (pwSpec->server.write_mac_context == NULL) {
   1773 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   1774 	goto fail;
   1775     }
   1776 
   1777     /*
   1778     ** Now setup the crypto contexts.
   1779     */
   1780 
   1781     calg = cipher_def->calg;
   1782     PORT_Assert(alg2Mech[calg].calg == calg);
   1783 
   1784     if (calg == calg_null) {
   1785 	pwSpec->encode  = Null_Cipher;
   1786 	pwSpec->decode  = Null_Cipher;
   1787 	pwSpec->destroy = NULL;
   1788 	return SECSuccess;
   1789     }
   1790     mechanism = alg2Mech[calg].cmech;
   1791     effKeyBits = cipher_def->key_size * BPB;
   1792 
   1793     /*
   1794      * build the server context
   1795      */
   1796     iv.data = pwSpec->server.write_iv;
   1797     iv.len  = cipher_def->iv_size;
   1798     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
   1799     if (param == NULL) {
   1800 	ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
   1801     	goto fail;
   1802     }
   1803     serverContext = PK11_CreateContextBySymKey(mechanism,
   1804 				(ss->sec.isServer ? CKA_ENCRYPT : CKA_DECRYPT),
   1805 				pwSpec->server.write_key, param);
   1806     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
   1807     if (iv.data)
   1808     	PORT_Memcpy(pwSpec->server.write_iv, iv.data, iv.len);
   1809     SECITEM_FreeItem(param, PR_TRUE);
   1810     if (serverContext == NULL) {
   1811 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   1812     	goto fail;
   1813     }
   1814 
   1815     /*
   1816      * build the client context
   1817      */
   1818     iv.data = pwSpec->client.write_iv;
   1819     iv.len  = cipher_def->iv_size;
   1820 
   1821     param = ssl3_ParamFromIV(mechanism, &iv, effKeyBits);
   1822     if (param == NULL) {
   1823 	ssl_MapLowLevelError(SSL_ERROR_IV_PARAM_FAILURE);
   1824     	goto fail;
   1825     }
   1826     clientContext = PK11_CreateContextBySymKey(mechanism,
   1827 				(ss->sec.isServer ? CKA_DECRYPT : CKA_ENCRYPT),
   1828 				pwSpec->client.write_key, param);
   1829     iv.data = PK11_IVFromParam(mechanism, param, (int *)&iv.len);
   1830     if (iv.data)
   1831     	PORT_Memcpy(pwSpec->client.write_iv, iv.data, iv.len);
   1832     SECITEM_FreeItem(param,PR_TRUE);
   1833     if (clientContext == NULL) {
   1834 	ssl_MapLowLevelError(SSL_ERROR_SYM_KEY_CONTEXT_FAILURE);
   1835     	goto fail;
   1836     }
   1837     pwSpec->encode  = (SSLCipher) PK11_CipherOp;
   1838     pwSpec->decode  = (SSLCipher) PK11_CipherOp;
   1839     pwSpec->destroy = (SSLDestroy) PK11_DestroyContext;
   1840 
   1841     pwSpec->encodeContext = (ss->sec.isServer) ? serverContext : clientContext;
   1842     pwSpec->decodeContext = (ss->sec.isServer) ? clientContext : serverContext;
   1843 
   1844     serverContext = NULL;
   1845     clientContext = NULL;
   1846 
   1847     ssl3_InitCompressionContext(pwSpec);
   1848 
   1849     return SECSuccess;
   1850 
   1851 fail:
   1852     if (serverContext != NULL) PK11_DestroyContext(serverContext, PR_TRUE);
   1853     if (clientContext != NULL) PK11_DestroyContext(clientContext, PR_TRUE);
   1854     if (pwSpec->client.write_mac_context != NULL) {
   1855     	PK11_DestroyContext(pwSpec->client.write_mac_context,PR_TRUE);
   1856 	pwSpec->client.write_mac_context = NULL;
   1857     }
   1858     if (pwSpec->server.write_mac_context != NULL) {
   1859     	PK11_DestroyContext(pwSpec->server.write_mac_context,PR_TRUE);
   1860 	pwSpec->server.write_mac_context = NULL;
   1861     }
   1862 
   1863     return SECFailure;
   1864 }
   1865 
   1866 /* Complete the initialization of all keys, ciphers, MACs and their contexts
   1867  * for the pending Cipher Spec.
   1868  * Called from: ssl3_SendClientKeyExchange 	(for Full handshake)
   1869  *              ssl3_HandleRSAClientKeyExchange	(for Full handshake)
   1870  *              ssl3_HandleServerHello		(for session restart)
   1871  *              ssl3_HandleClientHello		(for session restart)
   1872  * Sets error code, but caller probably should override to disambiguate.
   1873  * NULL pms means re-use old master_secret.
   1874  *
   1875  * This code is common to the bypass and PKCS11 execution paths.
   1876  * For the bypass case,  pms is NULL.
   1877  */
   1878 SECStatus
   1879 ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms)
   1880 {
   1881     ssl3CipherSpec  *  pwSpec;
   1882     ssl3CipherSpec  *  cwSpec;
   1883     SECStatus          rv;
   1884 
   1885     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   1886 
   1887     ssl_GetSpecWriteLock(ss);	/**************************************/
   1888 
   1889     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   1890 
   1891     pwSpec        = ss->ssl3.pwSpec;
   1892     cwSpec        = ss->ssl3.cwSpec;
   1893 
   1894     if (pms || (!pwSpec->msItem.len && !pwSpec->master_secret)) {
   1895 	rv = ssl3_DeriveMasterSecret(ss, pms);
   1896 	if (rv != SECSuccess) {
   1897 	    goto done;  /* err code set by ssl3_DeriveMasterSecret */
   1898 	}
   1899     }
   1900 #ifndef NO_PKCS11_BYPASS
   1901     if (ss->opt.bypassPKCS11 && pwSpec->msItem.len && pwSpec->msItem.data) {
   1902 	/* Double Bypass succeeded in extracting the master_secret */
   1903 	const ssl3KEADef * kea_def = ss->ssl3.hs.kea_def;
   1904 	PRBool             isTLS   = (PRBool)(kea_def->tls_keygen ||
   1905                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
   1906 	pwSpec->bypassCiphers = PR_TRUE;
   1907 	rv = ssl3_KeyAndMacDeriveBypass( pwSpec,
   1908 			     (const unsigned char *)&ss->ssl3.hs.client_random,
   1909 			     (const unsigned char *)&ss->ssl3.hs.server_random,
   1910 			     isTLS,
   1911 			     (PRBool)(kea_def->is_limited));
   1912 	if (rv == SECSuccess) {
   1913 	    rv = ssl3_InitPendingContextsBypass(ss);
   1914 	}
   1915     } else
   1916 #endif
   1917     if (pwSpec->master_secret) {
   1918 	rv = ssl3_DeriveConnectionKeysPKCS11(ss);
   1919 	if (rv == SECSuccess) {
   1920 	    rv = ssl3_InitPendingContextsPKCS11(ss);
   1921 	}
   1922     } else {
   1923 	PORT_Assert(pwSpec->master_secret);
   1924 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1925 	rv = SECFailure;
   1926     }
   1927     if (rv != SECSuccess) {
   1928 	goto done;
   1929     }
   1930 
   1931     /* Generic behaviors -- common to all crypto methods */
   1932     if (!IS_DTLS(ss)) {
   1933 	pwSpec->read_seq_num.high = pwSpec->write_seq_num.high = 0;
   1934     } else {
   1935 	if (cwSpec->epoch == PR_UINT16_MAX) {
   1936 	    /* The problem here is that we have rehandshaked too many
   1937 	     * times (you are not allowed to wrap the epoch). The
   1938 	     * spec says you should be discarding the connection
   1939 	     * and start over, so not much we can do here. */
   1940 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   1941 	    rv = SECFailure;
   1942 	    goto done;
   1943 	}
   1944 	/* The sequence number has the high 16 bits as the epoch. */
   1945 	pwSpec->epoch = cwSpec->epoch + 1;
   1946 	pwSpec->read_seq_num.high = pwSpec->write_seq_num.high =
   1947 	    pwSpec->epoch << 16;
   1948 
   1949 	dtls_InitRecvdRecords(&pwSpec->recvdRecords);
   1950     }
   1951     pwSpec->read_seq_num.low = pwSpec->write_seq_num.low = 0;
   1952 
   1953 done:
   1954     ssl_ReleaseSpecWriteLock(ss);	/******************************/
   1955     if (rv != SECSuccess)
   1956 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   1957     return rv;
   1958 }
   1959 
   1960 /*
   1961  * 60 bytes is 3 times the maximum length MAC size that is supported.
   1962  */
   1963 static const unsigned char mac_pad_1 [60] = {
   1964     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1965     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1966     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1967     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1968     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1969     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1970     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
   1971     0x36, 0x36, 0x36, 0x36
   1972 };
   1973 static const unsigned char mac_pad_2 [60] = {
   1974     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1975     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1976     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1977     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1978     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1979     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1980     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
   1981     0x5c, 0x5c, 0x5c, 0x5c
   1982 };
   1983 
   1984 /* Called from: ssl3_SendRecord()
   1985 ** Caller must already hold the SpecReadLock. (wish we could assert that!)
   1986 */
   1987 static SECStatus
   1988 ssl3_ComputeRecordMAC(
   1989     ssl3CipherSpec *   spec,
   1990     PRBool             useServerMacKey,
   1991     PRBool             isDTLS,
   1992     SSL3ContentType    type,
   1993     SSL3ProtocolVersion version,
   1994     SSL3SequenceNumber seq_num,
   1995     const SSL3Opaque * input,
   1996     int                inputLength,
   1997     unsigned char *    outbuf,
   1998     unsigned int *     outLength)
   1999 {
   2000     const ssl3MACDef * mac_def;
   2001     SECStatus          rv;
   2002 #ifndef NO_PKCS11_BYPASS
   2003     PRBool             isTLS;
   2004 #endif
   2005     unsigned int       tempLen;
   2006     unsigned char      temp[MAX_MAC_LENGTH];
   2007 
   2008     temp[0] = (unsigned char)(seq_num.high >> 24);
   2009     temp[1] = (unsigned char)(seq_num.high >> 16);
   2010     temp[2] = (unsigned char)(seq_num.high >>  8);
   2011     temp[3] = (unsigned char)(seq_num.high >>  0);
   2012     temp[4] = (unsigned char)(seq_num.low  >> 24);
   2013     temp[5] = (unsigned char)(seq_num.low  >> 16);
   2014     temp[6] = (unsigned char)(seq_num.low  >>  8);
   2015     temp[7] = (unsigned char)(seq_num.low  >>  0);
   2016     temp[8] = type;
   2017 
   2018     /* TLS MAC includes the record's version field, SSL's doesn't.
   2019     ** We decide which MAC defintiion to use based on the version of
   2020     ** the protocol that was negotiated when the spec became current,
   2021     ** NOT based on the version value in the record itself.
   2022     ** But, we use the record'v version value in the computation.
   2023     */
   2024     if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
   2025 	temp[9]  = MSB(inputLength);
   2026 	temp[10] = LSB(inputLength);
   2027 	tempLen  = 11;
   2028 #ifndef NO_PKCS11_BYPASS
   2029 	isTLS    = PR_FALSE;
   2030 #endif
   2031     } else {
   2032     	/* New TLS hash includes version. */
   2033 	if (isDTLS) {
   2034 	    SSL3ProtocolVersion dtls_version;
   2035 
   2036 	    dtls_version = dtls_TLSVersionToDTLSVersion(version);
   2037 	    temp[9]  = MSB(dtls_version);
   2038 	    temp[10] = LSB(dtls_version);
   2039         } else {
   2040 	    temp[9]  = MSB(version);
   2041 	    temp[10] = LSB(version);
   2042         }
   2043 	temp[11] = MSB(inputLength);
   2044 	temp[12] = LSB(inputLength);
   2045 	tempLen  = 13;
   2046 #ifndef NO_PKCS11_BYPASS
   2047 	isTLS    = PR_TRUE;
   2048 #endif
   2049     }
   2050 
   2051     PRINT_BUF(95, (NULL, "frag hash1: temp", temp, tempLen));
   2052     PRINT_BUF(95, (NULL, "frag hash1: input", input, inputLength));
   2053 
   2054     mac_def = spec->mac_def;
   2055     if (mac_def->mac == mac_null) {
   2056 	*outLength = 0;
   2057 	return SECSuccess;
   2058     }
   2059 #ifndef NO_PKCS11_BYPASS
   2060     if (spec->bypassCiphers) {
   2061 	/* bypass version */
   2062 	const SECHashObject *hashObj = NULL;
   2063 	unsigned int       pad_bytes = 0;
   2064 	PRUint64           write_mac_context[MAX_MAC_CONTEXT_LLONGS];
   2065 
   2066 	switch (mac_def->mac) {
   2067 	case ssl_mac_null:
   2068 	    *outLength = 0;
   2069 	    return SECSuccess;
   2070 	case ssl_mac_md5:
   2071 	    pad_bytes = 48;
   2072 	    hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
   2073 	    break;
   2074 	case ssl_mac_sha:
   2075 	    pad_bytes = 40;
   2076 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
   2077 	    break;
   2078 	case ssl_hmac_md5: /* used with TLS */
   2079 	    hashObj = HASH_GetRawHashObject(HASH_AlgMD5);
   2080 	    break;
   2081 	case ssl_hmac_sha: /* used with TLS */
   2082 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA1);
   2083 	    break;
   2084 	case ssl_hmac_sha256: /* used with TLS */
   2085 	    hashObj = HASH_GetRawHashObject(HASH_AlgSHA256);
   2086 	    break;
   2087 	default:
   2088 	    break;
   2089 	}
   2090 	if (!hashObj) {
   2091 	    PORT_Assert(0);
   2092 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2093 	    return SECFailure;
   2094 	}
   2095 
   2096 	if (!isTLS) {
   2097 	    /* compute "inner" part of SSL3 MAC */
   2098 	    hashObj->begin(write_mac_context);
   2099 	    if (useServerMacKey)
   2100 		hashObj->update(write_mac_context,
   2101 				spec->server.write_mac_key_item.data,
   2102 				spec->server.write_mac_key_item.len);
   2103 	    else
   2104 		hashObj->update(write_mac_context,
   2105 				spec->client.write_mac_key_item.data,
   2106 				spec->client.write_mac_key_item.len);
   2107 	    hashObj->update(write_mac_context, mac_pad_1, pad_bytes);
   2108 	    hashObj->update(write_mac_context, temp,  tempLen);
   2109 	    hashObj->update(write_mac_context, input, inputLength);
   2110 	    hashObj->end(write_mac_context,    temp, &tempLen, sizeof temp);
   2111 
   2112 	    /* compute "outer" part of SSL3 MAC */
   2113 	    hashObj->begin(write_mac_context);
   2114 	    if (useServerMacKey)
   2115 		hashObj->update(write_mac_context,
   2116 				spec->server.write_mac_key_item.data,
   2117 				spec->server.write_mac_key_item.len);
   2118 	    else
   2119 		hashObj->update(write_mac_context,
   2120 				spec->client.write_mac_key_item.data,
   2121 				spec->client.write_mac_key_item.len);
   2122 	    hashObj->update(write_mac_context, mac_pad_2, pad_bytes);
   2123 	    hashObj->update(write_mac_context, temp, tempLen);
   2124 	    hashObj->end(write_mac_context, outbuf, outLength, spec->mac_size);
   2125 	    rv = SECSuccess;
   2126 	} else { /* is TLS */
   2127 #define cx ((HMACContext *)write_mac_context)
   2128 	    if (useServerMacKey) {
   2129 		rv = HMAC_Init(cx, hashObj,
   2130 			       spec->server.write_mac_key_item.data,
   2131 			       spec->server.write_mac_key_item.len, PR_FALSE);
   2132 	    } else {
   2133 		rv = HMAC_Init(cx, hashObj,
   2134 			       spec->client.write_mac_key_item.data,
   2135 			       spec->client.write_mac_key_item.len, PR_FALSE);
   2136 	    }
   2137 	    if (rv == SECSuccess) {
   2138 		HMAC_Begin(cx);
   2139 		HMAC_Update(cx, temp, tempLen);
   2140 		HMAC_Update(cx, input, inputLength);
   2141 		rv = HMAC_Finish(cx, outbuf, outLength, spec->mac_size);
   2142 		HMAC_Destroy(cx, PR_FALSE);
   2143 	    }
   2144 #undef cx
   2145 	}
   2146     } else
   2147 #endif
   2148     {
   2149 	PK11Context *mac_context =
   2150 	    (useServerMacKey ? spec->server.write_mac_context
   2151 	                     : spec->client.write_mac_context);
   2152 	rv  = PK11_DigestBegin(mac_context);
   2153 	rv |= PK11_DigestOp(mac_context, temp, tempLen);
   2154 	rv |= PK11_DigestOp(mac_context, input, inputLength);
   2155 	rv |= PK11_DigestFinal(mac_context, outbuf, outLength, spec->mac_size);
   2156     }
   2157 
   2158     PORT_Assert(rv != SECSuccess || *outLength == (unsigned)spec->mac_size);
   2159 
   2160     PRINT_BUF(95, (NULL, "frag hash2: result", outbuf, *outLength));
   2161 
   2162     if (rv != SECSuccess) {
   2163     	rv = SECFailure;
   2164 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
   2165     }
   2166     return rv;
   2167 }
   2168 
   2169 /* This is a bodge to allow this code to be compiled against older NSS headers
   2170  * that don't contain the CBC constant-time changes. */
   2171 #ifndef CKM_NSS_HMAC_CONSTANT_TIME
   2172 #define CKM_NSS_HMAC_CONSTANT_TIME (CKM_NSS + 19)
   2173 #define CKM_NSS_SSL3_MAC_CONSTANT_TIME (CKM_NSS + 20)
   2174 
   2175 typedef struct CK_NSS_MAC_CONSTANT_TIME_PARAMS {
   2176     CK_MECHANISM_TYPE macAlg;   /* in */
   2177     CK_ULONG ulBodyTotalLen;    /* in */
   2178     CK_BYTE * pHeader;          /* in */
   2179     CK_ULONG ulHeaderLen;       /* in */
   2180 } CK_NSS_MAC_CONSTANT_TIME_PARAMS;
   2181 #endif
   2182 
   2183 /* Called from: ssl3_HandleRecord()
   2184  * Caller must already hold the SpecReadLock. (wish we could assert that!)
   2185  *
   2186  * On entry:
   2187  *   originalLen >= inputLen >= MAC size
   2188 */
   2189 static SECStatus
   2190 ssl3_ComputeRecordMACConstantTime(
   2191     ssl3CipherSpec *   spec,
   2192     PRBool             useServerMacKey,
   2193     PRBool             isDTLS,
   2194     SSL3ContentType    type,
   2195     SSL3ProtocolVersion version,
   2196     SSL3SequenceNumber seq_num,
   2197     const SSL3Opaque * input,
   2198     int                inputLen,
   2199     int                originalLen,
   2200     unsigned char *    outbuf,
   2201     unsigned int *     outLen)
   2202 {
   2203     CK_MECHANISM_TYPE            macType;
   2204     CK_NSS_MAC_CONSTANT_TIME_PARAMS params;
   2205     PK11Context *                mac_context;
   2206     SECItem                      param;
   2207     SECStatus                    rv;
   2208     unsigned char                header[13];
   2209     PK11SymKey *                 key;
   2210     int                          recordLength;
   2211 
   2212     PORT_Assert(inputLen >= spec->mac_size);
   2213     PORT_Assert(originalLen >= inputLen);
   2214 
   2215     if (spec->bypassCiphers) {
   2216 	/* This function doesn't support PKCS#11 bypass. We fallback on the
   2217 	 * non-constant time version. */
   2218 	goto fallback;
   2219     }
   2220 
   2221     if (spec->mac_def->mac == mac_null) {
   2222 	*outLen = 0;
   2223 	return SECSuccess;
   2224     }
   2225 
   2226     header[0] = (unsigned char)(seq_num.high >> 24);
   2227     header[1] = (unsigned char)(seq_num.high >> 16);
   2228     header[2] = (unsigned char)(seq_num.high >>  8);
   2229     header[3] = (unsigned char)(seq_num.high >>  0);
   2230     header[4] = (unsigned char)(seq_num.low  >> 24);
   2231     header[5] = (unsigned char)(seq_num.low  >> 16);
   2232     header[6] = (unsigned char)(seq_num.low  >>  8);
   2233     header[7] = (unsigned char)(seq_num.low  >>  0);
   2234     header[8] = type;
   2235 
   2236     macType = CKM_NSS_HMAC_CONSTANT_TIME;
   2237     recordLength = inputLen - spec->mac_size;
   2238     if (spec->version <= SSL_LIBRARY_VERSION_3_0) {
   2239 	macType = CKM_NSS_SSL3_MAC_CONSTANT_TIME;
   2240 	header[9] = recordLength >> 8;
   2241 	header[10] = recordLength;
   2242 	params.ulHeaderLen = 11;
   2243     } else {
   2244 	if (isDTLS) {
   2245 	    SSL3ProtocolVersion dtls_version;
   2246 
   2247 	    dtls_version = dtls_TLSVersionToDTLSVersion(version);
   2248 	    header[9] = dtls_version >> 8;
   2249 	    header[10] = dtls_version;
   2250 	} else {
   2251 	    header[9] = version >> 8;
   2252 	    header[10] = version;
   2253 	}
   2254 	header[11] = recordLength >> 8;
   2255 	header[12] = recordLength;
   2256 	params.ulHeaderLen = 13;
   2257     }
   2258 
   2259     params.macAlg = spec->mac_def->mmech;
   2260     params.ulBodyTotalLen = originalLen;
   2261     params.pHeader = header;
   2262 
   2263     param.data = (unsigned char*) &params;
   2264     param.len = sizeof(params);
   2265     param.type = 0;
   2266 
   2267     key = spec->server.write_mac_key;
   2268     if (!useServerMacKey) {
   2269 	key = spec->client.write_mac_key;
   2270     }
   2271     mac_context = PK11_CreateContextBySymKey(macType, CKA_SIGN, key, &param);
   2272     if (mac_context == NULL) {
   2273 	/* Older versions of NSS may not support constant-time MAC. */
   2274 	goto fallback;
   2275     }
   2276 
   2277     rv  = PK11_DigestBegin(mac_context);
   2278     rv |= PK11_DigestOp(mac_context, input, inputLen);
   2279     rv |= PK11_DigestFinal(mac_context, outbuf, outLen, spec->mac_size);
   2280     PK11_DestroyContext(mac_context, PR_TRUE);
   2281 
   2282     PORT_Assert(rv != SECSuccess || *outLen == (unsigned)spec->mac_size);
   2283 
   2284     if (rv != SECSuccess) {
   2285 	rv = SECFailure;
   2286 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
   2287     }
   2288     return rv;
   2289 
   2290 fallback:
   2291     /* ssl3_ComputeRecordMAC expects the MAC to have been removed from the
   2292      * length already. */
   2293     inputLen -= spec->mac_size;
   2294     return ssl3_ComputeRecordMAC(spec, useServerMacKey, isDTLS, type,
   2295 				 version, seq_num, input, inputLen,
   2296 				 outbuf, outLen);
   2297 }
   2298 
   2299 static PRBool
   2300 ssl3_ClientAuthTokenPresent(sslSessionID *sid) {
   2301     PK11SlotInfo *slot = NULL;
   2302     PRBool isPresent = PR_TRUE;
   2303 
   2304     /* we only care if we are doing client auth */
   2305     /* If NSS_PLATFORM_CLIENT_AUTH is defined and a platformClientKey is being
   2306      * used, u.ssl3.clAuthValid will be false and this function will always
   2307      * return PR_TRUE. */
   2308     if (!sid || !sid->u.ssl3.clAuthValid) {
   2309 	return PR_TRUE;
   2310     }
   2311 
   2312     /* get the slot */
   2313     slot = SECMOD_LookupSlot(sid->u.ssl3.clAuthModuleID,
   2314 	                     sid->u.ssl3.clAuthSlotID);
   2315     if (slot == NULL ||
   2316 	!PK11_IsPresent(slot) ||
   2317 	sid->u.ssl3.clAuthSeries     != PK11_GetSlotSeries(slot) ||
   2318 	sid->u.ssl3.clAuthSlotID     != PK11_GetSlotID(slot)     ||
   2319 	sid->u.ssl3.clAuthModuleID   != PK11_GetModuleID(slot)   ||
   2320 	(PK11_NeedLogin(slot) && !PK11_IsLoggedIn(slot, NULL))) {
   2321 	isPresent = PR_FALSE;
   2322     }
   2323     if (slot) {
   2324 	PK11_FreeSlot(slot);
   2325     }
   2326     return isPresent;
   2327 }
   2328 
   2329 /* Caller must hold the spec read lock. */
   2330 SECStatus
   2331 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *   cwSpec,
   2332 		              PRBool             isServer,
   2333 			      PRBool             isDTLS,
   2334 			      PRBool             capRecordVersion,
   2335                               SSL3ContentType    type,
   2336 		              const SSL3Opaque * pIn,
   2337 		              PRUint32           contentLen,
   2338 		              sslBuffer *        wrBuf)
   2339 {
   2340     const ssl3BulkCipherDef * cipher_def;
   2341     SECStatus                 rv;
   2342     PRUint32                  macLen = 0;
   2343     PRUint32                  fragLen;
   2344     PRUint32  p1Len, p2Len, oddLen = 0;
   2345     PRUint16                  headerLen;
   2346     int                       ivLen = 0;
   2347     int                       cipherBytes = 0;
   2348 
   2349     cipher_def = cwSpec->cipher_def;
   2350     headerLen = isDTLS ? DTLS_RECORD_HEADER_LENGTH : SSL3_RECORD_HEADER_LENGTH;
   2351 
   2352     if (cipher_def->type == type_block &&
   2353 	cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   2354 	/* Prepend the per-record explicit IV using technique 2b from
   2355 	 * RFC 4346 section 6.2.3.2: The IV is a cryptographically
   2356 	 * strong random number XORed with the CBC residue from the previous
   2357 	 * record.
   2358 	 */
   2359 	ivLen = cipher_def->iv_size;
   2360 	if (ivLen > wrBuf->space - headerLen) {
   2361 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2362 	    return SECFailure;
   2363 	}
   2364 	rv = PK11_GenerateRandom(wrBuf->buf + headerLen, ivLen);
   2365 	if (rv != SECSuccess) {
   2366 	    ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
   2367 	    return rv;
   2368 	}
   2369 	rv = cwSpec->encode( cwSpec->encodeContext,
   2370 	    wrBuf->buf + headerLen,
   2371 	    &cipherBytes,                       /* output and actual outLen */
   2372 	    ivLen,                              /* max outlen */
   2373 	    wrBuf->buf + headerLen,
   2374 	    ivLen);                             /* input and inputLen*/
   2375 	if (rv != SECSuccess || cipherBytes != ivLen) {
   2376 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2377 	    return SECFailure;
   2378 	}
   2379     }
   2380 
   2381     if (cwSpec->compressor) {
   2382 	int outlen;
   2383 	rv = cwSpec->compressor(
   2384 	    cwSpec->compressContext,
   2385 	    wrBuf->buf + headerLen + ivLen, &outlen,
   2386 	    wrBuf->space - headerLen - ivLen, pIn, contentLen);
   2387 	if (rv != SECSuccess)
   2388 	    return rv;
   2389 	pIn = wrBuf->buf + headerLen + ivLen;
   2390 	contentLen = outlen;
   2391     }
   2392 
   2393     /*
   2394      * Add the MAC
   2395      */
   2396     rv = ssl3_ComputeRecordMAC( cwSpec, isServer, isDTLS,
   2397 	type, cwSpec->version, cwSpec->write_seq_num, pIn, contentLen,
   2398 	wrBuf->buf + headerLen + ivLen + contentLen, &macLen);
   2399     if (rv != SECSuccess) {
   2400 	ssl_MapLowLevelError(SSL_ERROR_MAC_COMPUTATION_FAILURE);
   2401 	return SECFailure;
   2402     }
   2403     p1Len   = contentLen;
   2404     p2Len   = macLen;
   2405     fragLen = contentLen + macLen;	/* needs to be encrypted */
   2406     PORT_Assert(fragLen <= MAX_FRAGMENT_LENGTH + 1024);
   2407 
   2408     /*
   2409      * Pad the text (if we're doing a block cipher)
   2410      * then Encrypt it
   2411      */
   2412     if (cipher_def->type == type_block) {
   2413 	unsigned char * pBuf;
   2414 	int             padding_length;
   2415 	int             i;
   2416 
   2417 	oddLen = contentLen % cipher_def->block_size;
   2418 	/* Assume blockSize is a power of two */
   2419 	padding_length = cipher_def->block_size - 1 -
   2420 			((fragLen) & (cipher_def->block_size - 1));
   2421 	fragLen += padding_length + 1;
   2422 	PORT_Assert((fragLen % cipher_def->block_size) == 0);
   2423 
   2424 	/* Pad according to TLS rules (also acceptable to SSL3). */
   2425 	pBuf = &wrBuf->buf[headerLen + ivLen + fragLen - 1];
   2426 	for (i = padding_length + 1; i > 0; --i) {
   2427 	    *pBuf-- = padding_length;
   2428 	}
   2429 	/* now, if contentLen is not a multiple of block size, fix it */
   2430 	p2Len = fragLen - p1Len;
   2431     }
   2432     if (p1Len < 256) {
   2433 	oddLen = p1Len;
   2434 	p1Len = 0;
   2435     } else {
   2436 	p1Len -= oddLen;
   2437     }
   2438     if (oddLen) {
   2439 	p2Len += oddLen;
   2440 	PORT_Assert( (cipher_def->block_size < 2) || \
   2441 		     (p2Len % cipher_def->block_size) == 0);
   2442 	memmove(wrBuf->buf + headerLen + ivLen + p1Len, pIn + p1Len, oddLen);
   2443     }
   2444     if (p1Len > 0) {
   2445 	int cipherBytesPart1 = -1;
   2446 	rv = cwSpec->encode( cwSpec->encodeContext,
   2447 	    wrBuf->buf + headerLen + ivLen,         /* output */
   2448 	    &cipherBytesPart1,                      /* actual outlen */
   2449 	    p1Len,                                  /* max outlen */
   2450 	    pIn, p1Len);                      /* input, and inputlen */
   2451 	PORT_Assert(rv == SECSuccess && cipherBytesPart1 == (int) p1Len);
   2452 	if (rv != SECSuccess || cipherBytesPart1 != (int) p1Len) {
   2453 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2454 	    return SECFailure;
   2455 	}
   2456 	cipherBytes += cipherBytesPart1;
   2457     }
   2458     if (p2Len > 0) {
   2459 	int cipherBytesPart2 = -1;
   2460 	rv = cwSpec->encode( cwSpec->encodeContext,
   2461 	    wrBuf->buf + headerLen + ivLen + p1Len,
   2462 	    &cipherBytesPart2,          /* output and actual outLen */
   2463 	    p2Len,                             /* max outlen */
   2464 	    wrBuf->buf + headerLen + ivLen + p1Len,
   2465 	    p2Len);                            /* input and inputLen*/
   2466 	PORT_Assert(rv == SECSuccess && cipherBytesPart2 == (int) p2Len);
   2467 	if (rv != SECSuccess || cipherBytesPart2 != (int) p2Len) {
   2468 	    PORT_SetError(SSL_ERROR_ENCRYPTION_FAILURE);
   2469 	    return SECFailure;
   2470 	}
   2471 	cipherBytes += cipherBytesPart2;
   2472     }
   2473     PORT_Assert(cipherBytes <= MAX_FRAGMENT_LENGTH + 1024);
   2474 
   2475     wrBuf->len    = cipherBytes + headerLen;
   2476     wrBuf->buf[0] = type;
   2477     if (isDTLS) {
   2478 	SSL3ProtocolVersion version;
   2479 
   2480 	version = dtls_TLSVersionToDTLSVersion(cwSpec->version);
   2481 	wrBuf->buf[1] = MSB(version);
   2482 	wrBuf->buf[2] = LSB(version);
   2483 	wrBuf->buf[3] = (unsigned char)(cwSpec->write_seq_num.high >> 24);
   2484 	wrBuf->buf[4] = (unsigned char)(cwSpec->write_seq_num.high >> 16);
   2485 	wrBuf->buf[5] = (unsigned char)(cwSpec->write_seq_num.high >>  8);
   2486 	wrBuf->buf[6] = (unsigned char)(cwSpec->write_seq_num.high >>  0);
   2487 	wrBuf->buf[7] = (unsigned char)(cwSpec->write_seq_num.low  >> 24);
   2488 	wrBuf->buf[8] = (unsigned char)(cwSpec->write_seq_num.low  >> 16);
   2489 	wrBuf->buf[9] = (unsigned char)(cwSpec->write_seq_num.low  >>  8);
   2490 	wrBuf->buf[10] = (unsigned char)(cwSpec->write_seq_num.low >>  0);
   2491 	wrBuf->buf[11] = MSB(cipherBytes);
   2492 	wrBuf->buf[12] = LSB(cipherBytes);
   2493     } else {
   2494 	SSL3ProtocolVersion version = cwSpec->version;
   2495 
   2496 	if (capRecordVersion) {
   2497 	    version = PR_MIN(SSL_LIBRARY_VERSION_TLS_1_0, version);
   2498 	}
   2499 	wrBuf->buf[1] = MSB(version);
   2500 	wrBuf->buf[2] = LSB(version);
   2501 	wrBuf->buf[3] = MSB(cipherBytes);
   2502 	wrBuf->buf[4] = LSB(cipherBytes);
   2503     }
   2504 
   2505     ssl3_BumpSequenceNumber(&cwSpec->write_seq_num);
   2506 
   2507     return SECSuccess;
   2508 }
   2509 
   2510 /* Process the plain text before sending it.
   2511  * Returns the number of bytes of plaintext that were successfully sent
   2512  * 	plus the number of bytes of plaintext that were copied into the
   2513  *	output (write) buffer.
   2514  * Returns SECFailure on a hard IO error, memory error, or crypto error.
   2515  * Does NOT return SECWouldBlock.
   2516  *
   2517  * Notes on the use of the private ssl flags:
   2518  * (no private SSL flags)
   2519  *    Attempt to make and send SSL records for all plaintext
   2520  *    If non-blocking and a send gets WOULD_BLOCK,
   2521  *    or if the pending (ciphertext) buffer is not empty,
   2522  *    then buffer remaining bytes of ciphertext into pending buf,
   2523  *    and continue to do that for all succssive records until all
   2524  *    bytes are used.
   2525  * ssl_SEND_FLAG_FORCE_INTO_BUFFER
   2526  *    As above, except this suppresses all write attempts, and forces
   2527  *    all ciphertext into the pending ciphertext buffer.
   2528  * ssl_SEND_FLAG_USE_EPOCH (for DTLS)
   2529  *    Forces the use of the provided epoch
   2530  * ssl_SEND_FLAG_CAP_RECORD_VERSION
   2531  *    Caps the record layer version number of TLS ClientHello to { 3, 1 }
   2532  *    (TLS 1.0). Some TLS 1.0 servers (which seem to use F5 BIG-IP) ignore
   2533  *    ClientHello.client_version and use the record layer version number
   2534  *    (TLSPlaintext.version) instead when negotiating protocol versions. In
   2535  *    addition, if the record layer version number of ClientHello is { 3, 2 }
   2536  *    (TLS 1.1) or higher, these servers reset the TCP connections. Set this
   2537  *    flag to work around such servers.
   2538  */
   2539 PRInt32
   2540 ssl3_SendRecord(   sslSocket *        ss,
   2541                    DTLSEpoch          epoch, /* DTLS only */
   2542                    SSL3ContentType    type,
   2543 		   const SSL3Opaque * pIn,   /* input buffer */
   2544 		   PRInt32            nIn,   /* bytes of input */
   2545 		   PRInt32            flags)
   2546 {
   2547     sslBuffer      *          wrBuf 	  = &ss->sec.writeBuf;
   2548     SECStatus                 rv;
   2549     PRInt32                   totalSent   = 0;
   2550     PRBool                    capRecordVersion;
   2551 
   2552     SSL_TRC(3, ("%d: SSL3[%d] SendRecord type: %s nIn=%d",
   2553 		SSL_GETPID(), ss->fd, ssl3_DecodeContentType(type),
   2554 		nIn));
   2555     PRINT_BUF(3, (ss, "Send record (plain text)", pIn, nIn));
   2556 
   2557     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   2558 
   2559     capRecordVersion = ((flags & ssl_SEND_FLAG_CAP_RECORD_VERSION) != 0);
   2560 
   2561     if (capRecordVersion) {
   2562 	/* ssl_SEND_FLAG_CAP_RECORD_VERSION can only be used with the
   2563 	 * TLS initial ClientHello. */
   2564 	PORT_Assert(!IS_DTLS(ss));
   2565 	PORT_Assert(!ss->firstHsDone);
   2566 	PORT_Assert(type == content_handshake);
   2567 	PORT_Assert(ss->ssl3.hs.ws == wait_server_hello);
   2568     }
   2569 
   2570     if (ss->ssl3.initialized == PR_FALSE) {
   2571 	/* This can happen on a server if the very first incoming record
   2572 	** looks like a defective ssl3 record (e.g. too long), and we're
   2573 	** trying to send an alert.
   2574 	*/
   2575 	PR_ASSERT(type == content_alert);
   2576 	rv = ssl3_InitState(ss);
   2577 	if (rv != SECSuccess) {
   2578 	    return SECFailure;	/* ssl3_InitState has set the error code. */
   2579     	}
   2580     }
   2581 
   2582     /* check for Token Presence */
   2583     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
   2584 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   2585 	return SECFailure;
   2586     }
   2587 
   2588     while (nIn > 0) {
   2589 	PRUint32  contentLen = PR_MIN(nIn, MAX_FRAGMENT_LENGTH);
   2590 	unsigned int spaceNeeded;
   2591 	unsigned int numRecords;
   2592 
   2593 	ssl_GetSpecReadLock(ss);    /********************************/
   2594 
   2595 	if (nIn > 1 && ss->opt.cbcRandomIV &&
   2596 	    ss->ssl3.cwSpec->version < SSL_LIBRARY_VERSION_TLS_1_1 &&
   2597 	    type == content_application_data &&
   2598 	    ss->ssl3.cwSpec->cipher_def->type == type_block /* CBC mode */) {
   2599 	    /* We will split the first byte of the record into its own record,
   2600 	     * as explained in the documentation for SSL_CBC_RANDOM_IV in ssl.h
   2601 	     */
   2602 	    numRecords = 2;
   2603 	} else {
   2604 	    numRecords = 1;
   2605 	}
   2606 
   2607 	spaceNeeded = contentLen + (numRecords * SSL3_BUFFER_FUDGE);
   2608 	if (ss->ssl3.cwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
   2609 	    ss->ssl3.cwSpec->cipher_def->type == type_block) {
   2610 	    spaceNeeded += ss->ssl3.cwSpec->cipher_def->iv_size;
   2611 	}
   2612 	if (spaceNeeded > wrBuf->space) {
   2613 	    rv = sslBuffer_Grow(wrBuf, spaceNeeded);
   2614 	    if (rv != SECSuccess) {
   2615 		SSL_DBG(("%d: SSL3[%d]: SendRecord, tried to get %d bytes",
   2616 			 SSL_GETPID(), ss->fd, spaceNeeded));
   2617 		goto spec_locked_loser; /* sslBuffer_Grow set error code. */
   2618 	    }
   2619 	}
   2620 
   2621 	if (numRecords == 2) {
   2622 	    sslBuffer secondRecord;
   2623 
   2624 	    rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
   2625 					       ss->sec.isServer, IS_DTLS(ss),
   2626 					       capRecordVersion, type, pIn,
   2627 					       1, wrBuf);
   2628 	    if (rv != SECSuccess)
   2629 	        goto spec_locked_loser;
   2630 
   2631 	    PRINT_BUF(50, (ss, "send (encrypted) record data [1/2]:",
   2632 	                   wrBuf->buf, wrBuf->len));
   2633 
   2634 	    secondRecord.buf = wrBuf->buf + wrBuf->len;
   2635 	    secondRecord.len = 0;
   2636 	    secondRecord.space = wrBuf->space - wrBuf->len;
   2637 
   2638 	    rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
   2639 	                                       ss->sec.isServer, IS_DTLS(ss),
   2640 					       capRecordVersion, type,
   2641 					       pIn + 1, contentLen - 1,
   2642 	                                       &secondRecord);
   2643 	    if (rv == SECSuccess) {
   2644 	        PRINT_BUF(50, (ss, "send (encrypted) record data [2/2]:",
   2645 	                       secondRecord.buf, secondRecord.len));
   2646 	        wrBuf->len += secondRecord.len;
   2647 	    }
   2648 	} else {
   2649 	    if (!IS_DTLS(ss)) {
   2650 		rv = ssl3_CompressMACEncryptRecord(ss->ssl3.cwSpec,
   2651 						   ss->sec.isServer,
   2652 						   IS_DTLS(ss),
   2653 						   capRecordVersion,
   2654 						   type, pIn,
   2655 						   contentLen, wrBuf);
   2656 	    } else {
   2657 		rv = dtls_CompressMACEncryptRecord(ss, epoch,
   2658 						   !!(flags & ssl_SEND_FLAG_USE_EPOCH),
   2659 						   type, pIn,
   2660 						   contentLen, wrBuf);
   2661 	    }
   2662 
   2663 	    if (rv == SECSuccess) {
   2664 	        PRINT_BUF(50, (ss, "send (encrypted) record data:",
   2665 	                       wrBuf->buf, wrBuf->len));
   2666 	    }
   2667 	}
   2668 
   2669 spec_locked_loser:
   2670 	ssl_ReleaseSpecReadLock(ss); /************************************/
   2671 
   2672 	if (rv != SECSuccess)
   2673 	    return SECFailure;
   2674 
   2675 	pIn += contentLen;
   2676 	nIn -= contentLen;
   2677 	PORT_Assert( nIn >= 0 );
   2678 
   2679 	/* If there's still some previously saved ciphertext,
   2680 	 * or the caller doesn't want us to send the data yet,
   2681 	 * then add all our new ciphertext to the amount previously saved.
   2682 	 */
   2683 	if ((ss->pendingBuf.len > 0) ||
   2684 	    (flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
   2685 
   2686 	    rv = ssl_SaveWriteData(ss, wrBuf->buf, wrBuf->len);
   2687 	    if (rv != SECSuccess) {
   2688 		/* presumably a memory error, SEC_ERROR_NO_MEMORY */
   2689 		return SECFailure;
   2690 	    }
   2691 	    wrBuf->len = 0;	/* All cipher text is saved away. */
   2692 
   2693 	    if (!(flags & ssl_SEND_FLAG_FORCE_INTO_BUFFER)) {
   2694 		PRInt32   sent;
   2695 		ss->handshakeBegun = 1;
   2696 		sent = ssl_SendSavedWriteData(ss);
   2697 		if (sent < 0 && PR_GetError() != PR_WOULD_BLOCK_ERROR) {
   2698 		    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
   2699 		    return SECFailure;
   2700 		}
   2701 		if (ss->pendingBuf.len) {
   2702 		    flags |= ssl_SEND_FLAG_FORCE_INTO_BUFFER;
   2703 		}
   2704 	    }
   2705 	} else if (wrBuf->len > 0) {
   2706 	    PRInt32   sent;
   2707 	    ss->handshakeBegun = 1;
   2708 	    sent = ssl_DefSend(ss, wrBuf->buf, wrBuf->len,
   2709 			       flags & ~ssl_SEND_FLAG_MASK);
   2710 	    if (sent < 0) {
   2711 		if (PR_GetError() != PR_WOULD_BLOCK_ERROR) {
   2712 		    ssl_MapLowLevelError(SSL_ERROR_SOCKET_WRITE_FAILURE);
   2713 		    return SECFailure;
   2714 		}
   2715 		/* we got PR_WOULD_BLOCK_ERROR, which means none was sent. */
   2716 		sent = 0;
   2717 	    }
   2718 	    wrBuf->len -= sent;
   2719 	    if (wrBuf->len) {
   2720 		if (IS_DTLS(ss)) {
   2721 		    /* DTLS just says no in this case. No buffering */
   2722 		    PR_SetError(PR_WOULD_BLOCK_ERROR, 0);
   2723 		    return SECFailure;
   2724 		}
   2725 		/* now take all the remaining unsent new ciphertext and
   2726 		 * append it to the buffer of previously unsent ciphertext.
   2727 		 */
   2728 		rv = ssl_SaveWriteData(ss, wrBuf->buf + sent, wrBuf->len);
   2729 		if (rv != SECSuccess) {
   2730 		    /* presumably a memory error, SEC_ERROR_NO_MEMORY */
   2731 		    return SECFailure;
   2732 		}
   2733 	    }
   2734 	}
   2735 	totalSent += contentLen;
   2736     }
   2737     return totalSent;
   2738 }
   2739 
   2740 #define SSL3_PENDING_HIGH_WATER 1024
   2741 
   2742 /* Attempt to send the content of "in" in an SSL application_data record.
   2743  * Returns "len" or SECFailure,   never SECWouldBlock, nor SECSuccess.
   2744  */
   2745 int
   2746 ssl3_SendApplicationData(sslSocket *ss, const unsigned char *in,
   2747 			 PRInt32 len, PRInt32 flags)
   2748 {
   2749     PRInt32   totalSent	= 0;
   2750     PRInt32   discarded = 0;
   2751 
   2752     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   2753     /* These flags for internal use only */
   2754     PORT_Assert(!(flags & (ssl_SEND_FLAG_USE_EPOCH |
   2755 			   ssl_SEND_FLAG_NO_RETRANSMIT)));
   2756     if (len < 0 || !in) {
   2757 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   2758 	return SECFailure;
   2759     }
   2760 
   2761     if (ss->pendingBuf.len > SSL3_PENDING_HIGH_WATER &&
   2762         !ssl_SocketIsBlocking(ss)) {
   2763 	PORT_Assert(!ssl_SocketIsBlocking(ss));
   2764 	PORT_SetError(PR_WOULD_BLOCK_ERROR);
   2765 	return SECFailure;
   2766     }
   2767 
   2768     if (ss->appDataBuffered && len) {
   2769 	PORT_Assert (in[0] == (unsigned char)(ss->appDataBuffered));
   2770 	if (in[0] != (unsigned char)(ss->appDataBuffered)) {
   2771 	    PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   2772 	    return SECFailure;
   2773 	}
   2774     	in++;
   2775 	len--;
   2776 	discarded = 1;
   2777     }
   2778     while (len > totalSent) {
   2779 	PRInt32   sent, toSend;
   2780 
   2781 	if (totalSent > 0) {
   2782 	    /*
   2783 	     * The thread yield is intended to give the reader thread a
   2784 	     * chance to get some cycles while the writer thread is in
   2785 	     * the middle of a large application data write.  (See
   2786 	     * Bugzilla bug 127740, comment #1.)
   2787 	     */
   2788 	    ssl_ReleaseXmitBufLock(ss);
   2789 	    PR_Sleep(PR_INTERVAL_NO_WAIT);	/* PR_Yield(); */
   2790 	    ssl_GetXmitBufLock(ss);
   2791 	}
   2792 	toSend = PR_MIN(len - totalSent, MAX_FRAGMENT_LENGTH);
   2793 	/*
   2794 	 * Note that the 0 epoch is OK because flags will never require
   2795 	 * its use, as guaranteed by the PORT_Assert above.
   2796 	 */
   2797 	sent = ssl3_SendRecord(ss, 0, content_application_data,
   2798 	                       in + totalSent, toSend, flags);
   2799 	if (sent < 0) {
   2800 	    if (totalSent > 0 && PR_GetError() == PR_WOULD_BLOCK_ERROR) {
   2801 		PORT_Assert(ss->lastWriteBlocked);
   2802 	    	break;
   2803 	    }
   2804 	    return SECFailure; /* error code set by ssl3_SendRecord */
   2805 	}
   2806 	totalSent += sent;
   2807 	if (ss->pendingBuf.len) {
   2808 	    /* must be a non-blocking socket */
   2809 	    PORT_Assert(!ssl_SocketIsBlocking(ss));
   2810 	    PORT_Assert(ss->lastWriteBlocked);
   2811 	    break;
   2812 	}
   2813     }
   2814     if (ss->pendingBuf.len) {
   2815 	/* Must be non-blocking. */
   2816 	PORT_Assert(!ssl_SocketIsBlocking(ss));
   2817 	if (totalSent > 0) {
   2818 	    ss->appDataBuffered = 0x100 | in[totalSent - 1];
   2819 	}
   2820 
   2821 	totalSent = totalSent + discarded - 1;
   2822 	if (totalSent <= 0) {
   2823 	    PORT_SetError(PR_WOULD_BLOCK_ERROR);
   2824 	    totalSent = SECFailure;
   2825 	}
   2826 	return totalSent;
   2827     }
   2828     ss->appDataBuffered = 0;
   2829     return totalSent + discarded;
   2830 }
   2831 
   2832 /* Attempt to send buffered handshake messages.
   2833  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
   2834  * Always set sendBuf.len to 0, even when returning SECFailure.
   2835  *
   2836  * Depending on whether we are doing DTLS or not, this either calls
   2837  *
   2838  * - ssl3_FlushHandshakeMessages if non-DTLS
   2839  * - dtls_FlushHandshakeMessages if DTLS
   2840  *
   2841  * Called from SSL3_SendAlert(), ssl3_SendChangeCipherSpecs(),
   2842  *             ssl3_AppendHandshake(), ssl3_SendClientHello(),
   2843  *             ssl3_SendHelloRequest(), ssl3_SendServerHelloDone(),
   2844  *             ssl3_SendFinished(),
   2845  */
   2846 static SECStatus
   2847 ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags)
   2848 {
   2849     if (IS_DTLS(ss)) {
   2850         return dtls_FlushHandshakeMessages(ss, flags);
   2851     } else {
   2852         return ssl3_FlushHandshakeMessages(ss, flags);
   2853     }
   2854 }
   2855 
   2856 /* Attempt to send the content of sendBuf buffer in an SSL handshake record.
   2857  * This function returns SECSuccess or SECFailure, never SECWouldBlock.
   2858  * Always set sendBuf.len to 0, even when returning SECFailure.
   2859  *
   2860  * Called from ssl3_FlushHandshake
   2861  */
   2862 static SECStatus
   2863 ssl3_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags)
   2864 {
   2865     static const PRInt32 allowedFlags = ssl_SEND_FLAG_FORCE_INTO_BUFFER |
   2866                                         ssl_SEND_FLAG_CAP_RECORD_VERSION;
   2867     PRInt32 rv = SECSuccess;
   2868 
   2869     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   2870     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   2871 
   2872     if (!ss->sec.ci.sendBuf.buf || !ss->sec.ci.sendBuf.len)
   2873 	return rv;
   2874 
   2875     /* only these flags are allowed */
   2876     PORT_Assert(!(flags & ~allowedFlags));
   2877     if ((flags & ~allowedFlags) != 0) {
   2878 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
   2879 	rv = SECFailure;
   2880     } else {
   2881 	rv = ssl3_SendRecord(ss, 0, content_handshake, ss->sec.ci.sendBuf.buf,
   2882 			     ss->sec.ci.sendBuf.len, flags);
   2883     }
   2884     if (rv < 0) {
   2885     	int err = PORT_GetError();
   2886 	PORT_Assert(err != PR_WOULD_BLOCK_ERROR);
   2887 	if (err == PR_WOULD_BLOCK_ERROR) {
   2888 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2889 	}
   2890     } else if (rv < ss->sec.ci.sendBuf.len) {
   2891     	/* short write should never happen */
   2892 	PORT_Assert(rv >= ss->sec.ci.sendBuf.len);
   2893 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   2894 	rv = SECFailure;
   2895     } else {
   2896 	rv = SECSuccess;
   2897     }
   2898 
   2899     /* Whether we succeeded or failed, toss the old handshake data. */
   2900     ss->sec.ci.sendBuf.len = 0;
   2901     return rv;
   2902 }
   2903 
   2904 /*
   2905  * Called from ssl3_HandleAlert and from ssl3_HandleCertificate when
   2906  * the remote client sends a negative response to our certificate request.
   2907  * Returns SECFailure if the application has required client auth.
   2908  *         SECSuccess otherwise.
   2909  */
   2910 static SECStatus
   2911 ssl3_HandleNoCertificate(sslSocket *ss)
   2912 {
   2913     if (ss->sec.peerCert != NULL) {
   2914 	if (ss->sec.peerKey != NULL) {
   2915 	    SECKEY_DestroyPublicKey(ss->sec.peerKey);
   2916 	    ss->sec.peerKey = NULL;
   2917 	}
   2918 	CERT_DestroyCertificate(ss->sec.peerCert);
   2919 	ss->sec.peerCert = NULL;
   2920     }
   2921     ssl3_CleanupPeerCerts(ss);
   2922 
   2923     /* If the server has required client-auth blindly but doesn't
   2924      * actually look at the certificate it won't know that no
   2925      * certificate was presented so we shutdown the socket to ensure
   2926      * an error.  We only do this if we haven't already completed the
   2927      * first handshake because if we're redoing the handshake we
   2928      * know the server is paying attention to the certificate.
   2929      */
   2930     if ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
   2931 	(!ss->firstHsDone &&
   2932 	 (ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE))) {
   2933 	PRFileDesc * lower;
   2934 
   2935 	if (ss->sec.uncache)
   2936             ss->sec.uncache(ss->sec.ci.sid);
   2937 	SSL3_SendAlert(ss, alert_fatal, bad_certificate);
   2938 
   2939 	lower = ss->fd->lower;
   2940 #ifdef _WIN32
   2941 	lower->methods->shutdown(lower, PR_SHUTDOWN_SEND);
   2942 #else
   2943 	lower->methods->shutdown(lower, PR_SHUTDOWN_BOTH);
   2944 #endif
   2945 	PORT_SetError(SSL_ERROR_NO_CERTIFICATE);
   2946 	return SECFailure;
   2947     }
   2948     return SECSuccess;
   2949 }
   2950 
   2951 /************************************************************************
   2952  * Alerts
   2953  */
   2954 
   2955 /*
   2956 ** Acquires both handshake and XmitBuf locks.
   2957 ** Called from: ssl3_IllegalParameter	<-
   2958 **              ssl3_HandshakeFailure	<-
   2959 **              ssl3_HandleAlert	<- ssl3_HandleRecord.
   2960 **              ssl3_HandleChangeCipherSpecs <- ssl3_HandleRecord
   2961 **              ssl3_ConsumeHandshakeVariable <-
   2962 **              ssl3_HandleHelloRequest	<-
   2963 **              ssl3_HandleServerHello	<-
   2964 **              ssl3_HandleServerKeyExchange <-
   2965 **              ssl3_HandleCertificateRequest <-
   2966 **              ssl3_HandleServerHelloDone <-
   2967 **              ssl3_HandleClientHello	<-
   2968 **              ssl3_HandleV2ClientHello <-
   2969 **              ssl3_HandleCertificateVerify <-
   2970 **              ssl3_HandleClientKeyExchange <-
   2971 **              ssl3_HandleCertificate	<-
   2972 **              ssl3_HandleFinished	<-
   2973 **              ssl3_HandleHandshakeMessage <-
   2974 **              ssl3_HandleRecord	<-
   2975 **
   2976 */
   2977 SECStatus
   2978 SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level, SSL3AlertDescription desc)
   2979 {
   2980     PRUint8 	bytes[2];
   2981     SECStatus	rv;
   2982 
   2983     SSL_TRC(3, ("%d: SSL3[%d]: send alert record, level=%d desc=%d",
   2984 		SSL_GETPID(), ss->fd, level, desc));
   2985 
   2986     bytes[0] = level;
   2987     bytes[1] = desc;
   2988 
   2989     ssl_GetSSL3HandshakeLock(ss);
   2990     if (level == alert_fatal) {
   2991 	if (!ss->opt.noCache && ss->sec.ci.sid && ss->sec.uncache) {
   2992 	    ss->sec.uncache(ss->sec.ci.sid);
   2993 	}
   2994     }
   2995     ssl_GetXmitBufLock(ss);
   2996     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   2997     if (rv == SECSuccess) {
   2998 	PRInt32 sent;
   2999 	sent = ssl3_SendRecord(ss, 0, content_alert, bytes, 2,
   3000 			       desc == no_certificate
   3001 			       ? ssl_SEND_FLAG_FORCE_INTO_BUFFER : 0);
   3002 	rv = (sent >= 0) ? SECSuccess : (SECStatus)sent;
   3003     }
   3004     ssl_ReleaseXmitBufLock(ss);
   3005     ssl_ReleaseSSL3HandshakeLock(ss);
   3006     return rv;	/* error set by ssl3_FlushHandshake or ssl3_SendRecord */
   3007 }
   3008 
   3009 /*
   3010  * Send illegal_parameter alert.  Set generic error number.
   3011  */
   3012 static SECStatus
   3013 ssl3_IllegalParameter(sslSocket *ss)
   3014 {
   3015     PRBool isTLS;
   3016 
   3017     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   3018     (void)SSL3_SendAlert(ss, alert_fatal, illegal_parameter);
   3019     PORT_SetError(ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
   3020                                    : SSL_ERROR_BAD_SERVER );
   3021     return SECFailure;
   3022 }
   3023 
   3024 /*
   3025  * Send handshake_Failure alert.  Set generic error number.
   3026  */
   3027 static SECStatus
   3028 ssl3_HandshakeFailure(sslSocket *ss)
   3029 {
   3030     (void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
   3031     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
   3032                                     : SSL_ERROR_BAD_SERVER );
   3033     return SECFailure;
   3034 }
   3035 
   3036 static void
   3037 ssl3_SendAlertForCertError(sslSocket * ss, PRErrorCode errCode)
   3038 {
   3039     SSL3AlertDescription desc	= bad_certificate;
   3040     PRBool isTLS = ss->version >= SSL_LIBRARY_VERSION_3_1_TLS;
   3041 
   3042     switch (errCode) {
   3043     case SEC_ERROR_LIBRARY_FAILURE:     desc = unsupported_certificate; break;
   3044     case SEC_ERROR_EXPIRED_CERTIFICATE: desc = certificate_expired;     break;
   3045     case SEC_ERROR_REVOKED_CERTIFICATE: desc = certificate_revoked;     break;
   3046     case SEC_ERROR_INADEQUATE_KEY_USAGE:
   3047     case SEC_ERROR_INADEQUATE_CERT_TYPE:
   3048 		                        desc = certificate_unknown;     break;
   3049     case SEC_ERROR_UNTRUSTED_CERT:
   3050 		    desc = isTLS ? access_denied : certificate_unknown; break;
   3051     case SEC_ERROR_UNKNOWN_ISSUER:
   3052     case SEC_ERROR_UNTRUSTED_ISSUER:
   3053 		    desc = isTLS ? unknown_ca : certificate_unknown; break;
   3054     case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
   3055 		    desc = isTLS ? unknown_ca : certificate_expired; break;
   3056 
   3057     case SEC_ERROR_CERT_NOT_IN_NAME_SPACE:
   3058     case SEC_ERROR_PATH_LEN_CONSTRAINT_INVALID:
   3059     case SEC_ERROR_CA_CERT_INVALID:
   3060     case SEC_ERROR_BAD_SIGNATURE:
   3061     default:                            desc = bad_certificate;     break;
   3062     }
   3063     SSL_DBG(("%d: SSL3[%d]: peer certificate is no good: error=%d",
   3064 	     SSL_GETPID(), ss->fd, errCode));
   3065 
   3066     (void) SSL3_SendAlert(ss, alert_fatal, desc);
   3067 }
   3068 
   3069 
   3070 /*
   3071  * Send decode_error alert.  Set generic error number.
   3072  */
   3073 SECStatus
   3074 ssl3_DecodeError(sslSocket *ss)
   3075 {
   3076     (void)SSL3_SendAlert(ss, alert_fatal,
   3077 		  ss->version > SSL_LIBRARY_VERSION_3_0 ? decode_error
   3078 							: illegal_parameter);
   3079     PORT_SetError( ss->sec.isServer ? SSL_ERROR_BAD_CLIENT
   3080                                     : SSL_ERROR_BAD_SERVER );
   3081     return SECFailure;
   3082 }
   3083 
   3084 /* Called from ssl3_HandleRecord.
   3085 ** Caller must hold both RecvBuf and Handshake locks.
   3086 */
   3087 static SECStatus
   3088 ssl3_HandleAlert(sslSocket *ss, sslBuffer *buf)
   3089 {
   3090     SSL3AlertLevel       level;
   3091     SSL3AlertDescription desc;
   3092     int                  error;
   3093 
   3094     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   3095     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   3096 
   3097     SSL_TRC(3, ("%d: SSL3[%d]: handle alert record", SSL_GETPID(), ss->fd));
   3098 
   3099     if (buf->len != 2) {
   3100 	(void)ssl3_DecodeError(ss);
   3101 	PORT_SetError(SSL_ERROR_RX_MALFORMED_ALERT);
   3102 	return SECFailure;
   3103     }
   3104     level = (SSL3AlertLevel)buf->buf[0];
   3105     desc  = (SSL3AlertDescription)buf->buf[1];
   3106     buf->len = 0;
   3107     SSL_TRC(5, ("%d: SSL3[%d] received alert, level = %d, description = %d",
   3108         SSL_GETPID(), ss->fd, level, desc));
   3109 
   3110     switch (desc) {
   3111     case close_notify:		ss->recvdCloseNotify = 1;
   3112 		        	error = SSL_ERROR_CLOSE_NOTIFY_ALERT;     break;
   3113     case unexpected_message: 	error = SSL_ERROR_HANDSHAKE_UNEXPECTED_ALERT;
   3114 									  break;
   3115     case bad_record_mac: 	error = SSL_ERROR_BAD_MAC_ALERT; 	  break;
   3116     case decryption_failed_RESERVED:
   3117                                 error = SSL_ERROR_DECRYPTION_FAILED_ALERT;
   3118     									  break;
   3119     case record_overflow: 	error = SSL_ERROR_RECORD_OVERFLOW_ALERT;  break;
   3120     case decompression_failure: error = SSL_ERROR_DECOMPRESSION_FAILURE_ALERT;
   3121 									  break;
   3122     case handshake_failure: 	error = SSL_ERROR_HANDSHAKE_FAILURE_ALERT;
   3123 			        					  break;
   3124     case no_certificate: 	error = SSL_ERROR_NO_CERTIFICATE;	  break;
   3125     case bad_certificate: 	error = SSL_ERROR_BAD_CERT_ALERT; 	  break;
   3126     case unsupported_certificate:error = SSL_ERROR_UNSUPPORTED_CERT_ALERT;break;
   3127     case certificate_revoked: 	error = SSL_ERROR_REVOKED_CERT_ALERT; 	  break;
   3128     case certificate_expired: 	error = SSL_ERROR_EXPIRED_CERT_ALERT; 	  break;
   3129     case certificate_unknown: 	error = SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT;
   3130 			        					  break;
   3131     case illegal_parameter: 	error = SSL_ERROR_ILLEGAL_PARAMETER_ALERT;break;
   3132 
   3133     /* All alerts below are TLS only. */
   3134     case unknown_ca: 		error = SSL_ERROR_UNKNOWN_CA_ALERT;       break;
   3135     case access_denied: 	error = SSL_ERROR_ACCESS_DENIED_ALERT;    break;
   3136     case decode_error: 		error = SSL_ERROR_DECODE_ERROR_ALERT;     break;
   3137     case decrypt_error: 	error = SSL_ERROR_DECRYPT_ERROR_ALERT;    break;
   3138     case export_restriction: 	error = SSL_ERROR_EXPORT_RESTRICTION_ALERT;
   3139     									  break;
   3140     case protocol_version: 	error = SSL_ERROR_PROTOCOL_VERSION_ALERT; break;
   3141     case insufficient_security: error = SSL_ERROR_INSUFFICIENT_SECURITY_ALERT;
   3142     									  break;
   3143     case internal_error: 	error = SSL_ERROR_INTERNAL_ERROR_ALERT;   break;
   3144     case user_canceled: 	error = SSL_ERROR_USER_CANCELED_ALERT;    break;
   3145     case no_renegotiation: 	error = SSL_ERROR_NO_RENEGOTIATION_ALERT; break;
   3146 
   3147     /* Alerts for TLS client hello extensions */
   3148     case unsupported_extension:
   3149 			error = SSL_ERROR_UNSUPPORTED_EXTENSION_ALERT;    break;
   3150     case certificate_unobtainable:
   3151 			error = SSL_ERROR_CERTIFICATE_UNOBTAINABLE_ALERT; break;
   3152     case unrecognized_name:
   3153 			error = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;        break;
   3154     case bad_certificate_status_response:
   3155 			error = SSL_ERROR_BAD_CERT_STATUS_RESPONSE_ALERT; break;
   3156     case bad_certificate_hash_value:
   3157 			error = SSL_ERROR_BAD_CERT_HASH_VALUE_ALERT;      break;
   3158     default: 		error = SSL_ERROR_RX_UNKNOWN_ALERT;               break;
   3159     }
   3160     if (level == alert_fatal) {
   3161 	if (!ss->opt.noCache) {
   3162 	    if (ss->sec.uncache)
   3163                 ss->sec.uncache(ss->sec.ci.sid);
   3164 	}
   3165 	if ((ss->ssl3.hs.ws == wait_server_hello) &&
   3166 	    (desc == handshake_failure)) {
   3167 	    /* XXX This is a hack.  We're assuming that any handshake failure
   3168 	     * XXX on the client hello is a failure to match ciphers.
   3169 	     */
   3170 	    error = SSL_ERROR_NO_CYPHER_OVERLAP;
   3171 	}
   3172 	PORT_SetError(error);
   3173 	return SECFailure;
   3174     }
   3175     if ((desc == no_certificate) && (ss->ssl3.hs.ws == wait_client_cert)) {
   3176     	/* I'm a server. I've requested a client cert. He hasn't got one. */
   3177 	SECStatus rv;
   3178 
   3179 	PORT_Assert(ss->sec.isServer);
   3180 	ss->ssl3.hs.ws = wait_client_key;
   3181 	rv = ssl3_HandleNoCertificate(ss);
   3182 	return rv;
   3183     }
   3184     return SECSuccess;
   3185 }
   3186 
   3187 /*
   3188  * Change Cipher Specs
   3189  * Called from ssl3_HandleServerHelloDone,
   3190  *             ssl3_HandleClientHello,
   3191  * and         ssl3_HandleFinished
   3192  *
   3193  * Acquires and releases spec write lock, to protect switching the current
   3194  * and pending write spec pointers.
   3195  */
   3196 
   3197 static SECStatus
   3198 ssl3_SendChangeCipherSpecs(sslSocket *ss)
   3199 {
   3200     PRUint8           change = change_cipher_spec_choice;
   3201     ssl3CipherSpec *  pwSpec;
   3202     SECStatus         rv;
   3203     PRInt32           sent;
   3204 
   3205     SSL_TRC(3, ("%d: SSL3[%d]: send change_cipher_spec record",
   3206 		SSL_GETPID(), ss->fd));
   3207 
   3208     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   3209     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3210 
   3211     rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   3212     if (rv != SECSuccess) {
   3213 	return rv;	/* error code set by ssl3_FlushHandshake */
   3214     }
   3215     if (!IS_DTLS(ss)) {
   3216 	sent = ssl3_SendRecord(ss, 0, content_change_cipher_spec, &change, 1,
   3217 			       ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   3218 	if (sent < 0) {
   3219 	    return (SECStatus)sent;	/* error code set by ssl3_SendRecord */
   3220 	}
   3221     } else {
   3222 	rv = dtls_QueueMessage(ss, content_change_cipher_spec, &change, 1);
   3223 	if (rv != SECSuccess) {
   3224 	    return rv;
   3225 	}
   3226     }
   3227 
   3228     /* swap the pending and current write specs. */
   3229     ssl_GetSpecWriteLock(ss);	/**************************************/
   3230     pwSpec                     = ss->ssl3.pwSpec;
   3231 
   3232     ss->ssl3.pwSpec = ss->ssl3.cwSpec;
   3233     ss->ssl3.cwSpec = pwSpec;
   3234 
   3235     SSL_TRC(3, ("%d: SSL3[%d] Set Current Write Cipher Suite to Pending",
   3236 		SSL_GETPID(), ss->fd ));
   3237 
   3238     /* We need to free up the contexts, keys and certs ! */
   3239     /* If we are really through with the old cipher spec
   3240      * (Both the read and write sides have changed) destroy it.
   3241      */
   3242     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
   3243 	if (!IS_DTLS(ss)) {
   3244 	    ssl3_DestroyCipherSpec(ss->ssl3.pwSpec, PR_FALSE/*freeSrvName*/);
   3245 	} else {
   3246 	    /* With DTLS, we need to set a holddown timer in case the final
   3247 	     * message got lost */
   3248 	    ss->ssl3.hs.rtTimeoutMs = DTLS_FINISHED_TIMER_MS;
   3249 	    dtls_StartTimer(ss, dtls_FinishedTimerCb);
   3250 	}
   3251     }
   3252     ssl_ReleaseSpecWriteLock(ss); /**************************************/
   3253 
   3254     return SECSuccess;
   3255 }
   3256 
   3257 /* Called from ssl3_HandleRecord.
   3258 ** Caller must hold both RecvBuf and Handshake locks.
   3259  *
   3260  * Acquires and releases spec write lock, to protect switching the current
   3261  * and pending write spec pointers.
   3262 */
   3263 static SECStatus
   3264 ssl3_HandleChangeCipherSpecs(sslSocket *ss, sslBuffer *buf)
   3265 {
   3266     ssl3CipherSpec *           prSpec;
   3267     SSL3WaitState              ws      = ss->ssl3.hs.ws;
   3268     SSL3ChangeCipherSpecChoice change;
   3269 
   3270     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   3271     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   3272 
   3273     SSL_TRC(3, ("%d: SSL3[%d]: handle change_cipher_spec record",
   3274 		SSL_GETPID(), ss->fd));
   3275 
   3276     if (ws != wait_change_cipher) {
   3277 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   3278 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CHANGE_CIPHER);
   3279 	return SECFailure;
   3280     }
   3281 
   3282     if(buf->len != 1) {
   3283 	(void)ssl3_DecodeError(ss);
   3284 	PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
   3285 	return SECFailure;
   3286     }
   3287     change = (SSL3ChangeCipherSpecChoice)buf->buf[0];
   3288     if (change != change_cipher_spec_choice) {
   3289 	/* illegal_parameter is correct here for both SSL3 and TLS. */
   3290 	(void)ssl3_IllegalParameter(ss);
   3291 	PORT_SetError(SSL_ERROR_RX_MALFORMED_CHANGE_CIPHER);
   3292 	return SECFailure;
   3293     }
   3294     buf->len = 0;
   3295 
   3296     /* Swap the pending and current read specs. */
   3297     ssl_GetSpecWriteLock(ss);   /*************************************/
   3298     prSpec                    = ss->ssl3.prSpec;
   3299 
   3300     ss->ssl3.prSpec  = ss->ssl3.crSpec;
   3301     ss->ssl3.crSpec  = prSpec;
   3302     ss->ssl3.hs.ws   = wait_finished;
   3303 
   3304     SSL_TRC(3, ("%d: SSL3[%d] Set Current Read Cipher Suite to Pending",
   3305 		SSL_GETPID(), ss->fd ));
   3306 
   3307     /* If we are really through with the old cipher prSpec
   3308      * (Both the read and write sides have changed) destroy it.
   3309      */
   3310     if (ss->ssl3.prSpec == ss->ssl3.pwSpec) {
   3311     	ssl3_DestroyCipherSpec(ss->ssl3.prSpec, PR_FALSE/*freeSrvName*/);
   3312     }
   3313     ssl_ReleaseSpecWriteLock(ss);   /*************************************/
   3314     return SECSuccess;
   3315 }
   3316 
   3317 /* This method uses PKCS11 to derive the MS from the PMS, where PMS
   3318 ** is a PKCS11 symkey. This is used in all cases except the
   3319 ** "triple bypass" with RSA key exchange.
   3320 ** Called from ssl3_InitPendingCipherSpec.   prSpec is pwSpec.
   3321 */
   3322 static SECStatus
   3323 ssl3_DeriveMasterSecret(sslSocket *ss, PK11SymKey *pms)
   3324 {
   3325     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
   3326     const ssl3KEADef *kea_def= ss->ssl3.hs.kea_def;
   3327     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
   3328     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
   3329     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
   3330                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
   3331     PRBool            isTLS12=
   3332 	    (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   3333     /*
   3334      * Whenever isDH is true, we need to use CKM_TLS_MASTER_KEY_DERIVE_DH
   3335      * which, unlike CKM_TLS_MASTER_KEY_DERIVE, converts arbitrary size
   3336      * data into a 48-byte value.
   3337      */
   3338     PRBool    isDH = (PRBool) ((ss->ssl3.hs.kea_def->exchKeyType == kt_dh) ||
   3339 	                       (ss->ssl3.hs.kea_def->exchKeyType == kt_ecdh));
   3340     SECStatus         rv = SECFailure;
   3341     CK_MECHANISM_TYPE master_derive;
   3342     CK_MECHANISM_TYPE key_derive;
   3343     SECItem           params;
   3344     CK_FLAGS          keyFlags;
   3345     CK_VERSION        pms_version;
   3346     CK_SSL3_MASTER_KEY_DERIVE_PARAMS master_params;
   3347 
   3348     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3349     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   3350     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   3351     if (isTLS12) {
   3352 	if(isDH) master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256;
   3353 	else master_derive = CKM_NSS_TLS_MASTER_KEY_DERIVE_SHA256;
   3354 	key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
   3355 	keyFlags      = CKF_SIGN | CKF_VERIFY;
   3356     } else if (isTLS) {
   3357 	if(isDH) master_derive = CKM_TLS_MASTER_KEY_DERIVE_DH;
   3358 	else master_derive = CKM_TLS_MASTER_KEY_DERIVE;
   3359 	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
   3360 	keyFlags      = CKF_SIGN | CKF_VERIFY;
   3361     } else {
   3362 	if (isDH) master_derive = CKM_SSL3_MASTER_KEY_DERIVE_DH;
   3363 	else master_derive = CKM_SSL3_MASTER_KEY_DERIVE;
   3364 	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
   3365 	keyFlags      = 0;
   3366     }
   3367 
   3368     if (pms || !pwSpec->master_secret) {
   3369 	if (isDH) {
   3370 	    master_params.pVersion                     = NULL;
   3371 	} else {
   3372 	    master_params.pVersion                     = &pms_version;
   3373 	}
   3374 	master_params.RandomInfo.pClientRandom     = cr;
   3375 	master_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
   3376 	master_params.RandomInfo.pServerRandom     = sr;
   3377 	master_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
   3378 
   3379 	params.data = (unsigned char *) &master_params;
   3380 	params.len  = sizeof master_params;
   3381     }
   3382 
   3383     if (pms != NULL) {
   3384 #if defined(TRACE)
   3385 	if (ssl_trace >= 100) {
   3386 	    SECStatus extractRV = PK11_ExtractKeyValue(pms);
   3387 	    if (extractRV == SECSuccess) {
   3388 		SECItem * keyData = PK11_GetKeyData(pms);
   3389 		if (keyData && keyData->data && keyData->len) {
   3390 		    ssl_PrintBuf(ss, "Pre-Master Secret",
   3391 				 keyData->data, keyData->len);
   3392 		}
   3393 	    }
   3394 	}
   3395 #endif
   3396 	pwSpec->master_secret = PK11_DeriveWithFlags(pms, master_derive,
   3397 				&params, key_derive, CKA_DERIVE, 0, keyFlags);
   3398 	if (!isDH && pwSpec->master_secret && ss->opt.detectRollBack) {
   3399 	    SSL3ProtocolVersion client_version;
   3400 	    client_version = pms_version.major << 8 | pms_version.minor;
   3401 
   3402 	    if (IS_DTLS(ss)) {
   3403 		client_version = dtls_DTLSVersionToTLSVersion(client_version);
   3404 	    }
   3405 
   3406 	    if (client_version != ss->clientHelloVersion) {
   3407 		/* Destroy it.  Version roll-back detected. */
   3408 		PK11_FreeSymKey(pwSpec->master_secret);
   3409 	    	pwSpec->master_secret = NULL;
   3410 	    }
   3411 	}
   3412 	if (pwSpec->master_secret == NULL) {
   3413 	    /* Generate a faux master secret in the same slot as the old one. */
   3414 	    PK11SlotInfo * slot = PK11_GetSlotFromKey((PK11SymKey *)pms);
   3415 	    PK11SymKey *   fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
   3416 
   3417 	    PK11_FreeSlot(slot);
   3418 	    if (fpms != NULL) {
   3419 		pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
   3420 					master_derive, &params, key_derive,
   3421 					CKA_DERIVE, 0, keyFlags);
   3422 		PK11_FreeSymKey(fpms);
   3423 	    }
   3424 	}
   3425     }
   3426     if (pwSpec->master_secret == NULL) {
   3427 	/* Generate a faux master secret from the internal slot. */
   3428 	PK11SlotInfo *  slot = PK11_GetInternalSlot();
   3429 	PK11SymKey *    fpms = ssl3_GenerateRSAPMS(ss, pwSpec, slot);
   3430 
   3431 	PK11_FreeSlot(slot);
   3432 	if (fpms != NULL) {
   3433 	    pwSpec->master_secret = PK11_DeriveWithFlags(fpms,
   3434 					master_derive, &params, key_derive,
   3435 					CKA_DERIVE, 0, keyFlags);
   3436 	    if (pwSpec->master_secret == NULL) {
   3437 	    	pwSpec->master_secret = fpms; /* use the fpms as the master. */
   3438 		fpms = NULL;
   3439 	    }
   3440 	}
   3441 	if (fpms) {
   3442 	    PK11_FreeSymKey(fpms);
   3443     	}
   3444     }
   3445     if (pwSpec->master_secret == NULL) {
   3446 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3447 	return rv;
   3448     }
   3449 #ifndef NO_PKCS11_BYPASS
   3450     if (ss->opt.bypassPKCS11) {
   3451 	SECItem * keydata;
   3452 	/* In hope of doing a "double bypass",
   3453 	 * need to extract the master secret's value from the key object
   3454 	 * and store it raw in the sslSocket struct.
   3455 	 */
   3456 	rv = PK11_ExtractKeyValue(pwSpec->master_secret);
   3457 	if (rv != SECSuccess) {
   3458 	    return rv;
   3459 	}
   3460 	/* This returns the address of the secItem inside the key struct,
   3461 	 * not a copy or a reference.  So, there's no need to free it.
   3462 	 */
   3463 	keydata = PK11_GetKeyData(pwSpec->master_secret);
   3464 	if (keydata && keydata->len <= sizeof pwSpec->raw_master_secret) {
   3465 	    memcpy(pwSpec->raw_master_secret, keydata->data, keydata->len);
   3466 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   3467 	    pwSpec->msItem.len  = keydata->len;
   3468 	} else {
   3469 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   3470 	    return SECFailure;
   3471 	}
   3472     }
   3473 #endif
   3474     return SECSuccess;
   3475 }
   3476 
   3477 
   3478 /*
   3479  * Derive encryption and MAC Keys (and IVs) from master secret
   3480  * Sets a useful error code when returning SECFailure.
   3481  *
   3482  * Called only from ssl3_InitPendingCipherSpec(),
   3483  * which in turn is called from
   3484  *              sendRSAClientKeyExchange        (for Full handshake)
   3485  *              sendDHClientKeyExchange         (for Full handshake)
   3486  *              ssl3_HandleClientKeyExchange    (for Full handshake)
   3487  *              ssl3_HandleServerHello          (for session restart)
   3488  *              ssl3_HandleClientHello          (for session restart)
   3489  * Caller MUST hold the specWriteLock, and SSL3HandshakeLock.
   3490  * ssl3_InitPendingCipherSpec does that.
   3491  *
   3492  */
   3493 static SECStatus
   3494 ssl3_DeriveConnectionKeysPKCS11(sslSocket *ss)
   3495 {
   3496     ssl3CipherSpec *         pwSpec     = ss->ssl3.pwSpec;
   3497     const ssl3KEADef *       kea_def    = ss->ssl3.hs.kea_def;
   3498     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
   3499     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
   3500     PRBool            isTLS  = (PRBool)(kea_def->tls_keygen ||
   3501                                 (pwSpec->version > SSL_LIBRARY_VERSION_3_0));
   3502     PRBool            isTLS12=
   3503 	    (PRBool)(isTLS && pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   3504     /* following variables used in PKCS11 path */
   3505     const ssl3BulkCipherDef *cipher_def = pwSpec->cipher_def;
   3506     PK11SlotInfo *         slot   = NULL;
   3507     PK11SymKey *           symKey = NULL;
   3508     void *                 pwArg  = ss->pkcs11PinArg;
   3509     int                    keySize;
   3510     CK_SSL3_KEY_MAT_PARAMS key_material_params;
   3511     CK_SSL3_KEY_MAT_OUT    returnedKeys;
   3512     CK_MECHANISM_TYPE      key_derive;
   3513     CK_MECHANISM_TYPE      bulk_mechanism;
   3514     SSLCipherAlgorithm     calg;
   3515     SECItem                params;
   3516     PRBool         skipKeysAndIVs = (PRBool)(cipher_def->calg == calg_null);
   3517 
   3518     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   3519     PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   3520     PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   3521 
   3522     if (!pwSpec->master_secret) {
   3523 	PORT_SetError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3524 	return SECFailure;
   3525     }
   3526     /*
   3527      * generate the key material
   3528      */
   3529     key_material_params.ulMacSizeInBits = pwSpec->mac_size           * BPB;
   3530     key_material_params.ulKeySizeInBits = cipher_def->secret_key_size* BPB;
   3531     key_material_params.ulIVSizeInBits  = cipher_def->iv_size        * BPB;
   3532     if (cipher_def->type == type_block &&
   3533 	pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   3534 	/* Block ciphers in >= TLS 1.1 use a per-record, explicit IV. */
   3535 	key_material_params.ulIVSizeInBits = 0;
   3536 	memset(pwSpec->client.write_iv, 0, cipher_def->iv_size);
   3537 	memset(pwSpec->server.write_iv, 0, cipher_def->iv_size);
   3538     }
   3539 
   3540     key_material_params.bIsExport = (CK_BBOOL)(kea_def->is_limited);
   3541     /* was:	(CK_BBOOL)(cipher_def->keygen_mode != kg_strong); */
   3542 
   3543     key_material_params.RandomInfo.pClientRandom     = cr;
   3544     key_material_params.RandomInfo.ulClientRandomLen = SSL3_RANDOM_LENGTH;
   3545     key_material_params.RandomInfo.pServerRandom     = sr;
   3546     key_material_params.RandomInfo.ulServerRandomLen = SSL3_RANDOM_LENGTH;
   3547     key_material_params.pReturnedKeyMaterial         = &returnedKeys;
   3548 
   3549     returnedKeys.pIVClient = pwSpec->client.write_iv;
   3550     returnedKeys.pIVServer = pwSpec->server.write_iv;
   3551     keySize                = cipher_def->key_size;
   3552 
   3553     if (skipKeysAndIVs) {
   3554 	keySize                             = 0;
   3555         key_material_params.ulKeySizeInBits = 0;
   3556         key_material_params.ulIVSizeInBits  = 0;
   3557     	returnedKeys.pIVClient              = NULL;
   3558     	returnedKeys.pIVServer              = NULL;
   3559     }
   3560 
   3561     calg = cipher_def->calg;
   3562     PORT_Assert(     alg2Mech[calg].calg == calg);
   3563     bulk_mechanism = alg2Mech[calg].cmech;
   3564 
   3565     params.data    = (unsigned char *)&key_material_params;
   3566     params.len     = sizeof(key_material_params);
   3567 
   3568     if (isTLS12) {
   3569 	key_derive    = CKM_NSS_TLS_KEY_AND_MAC_DERIVE_SHA256;
   3570     } else if (isTLS) {
   3571 	key_derive    = CKM_TLS_KEY_AND_MAC_DERIVE;
   3572     } else {
   3573 	key_derive    = CKM_SSL3_KEY_AND_MAC_DERIVE;
   3574     }
   3575 
   3576     /* CKM_SSL3_KEY_AND_MAC_DERIVE is defined to set ENCRYPT, DECRYPT, and
   3577      * DERIVE by DEFAULT */
   3578     symKey = PK11_Derive(pwSpec->master_secret, key_derive, &params,
   3579                          bulk_mechanism, CKA_ENCRYPT, keySize);
   3580     if (!symKey) {
   3581 	ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3582 	return SECFailure;
   3583     }
   3584     /* we really should use the actual mac'ing mechanism here, but we
   3585      * don't because these types are used to map keytype anyway and both
   3586      * mac's map to the same keytype.
   3587      */
   3588     slot  = PK11_GetSlotFromKey(symKey);
   3589 
   3590     PK11_FreeSlot(slot); /* slot is held until the key is freed */
   3591     pwSpec->client.write_mac_key =
   3592     	PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3593 	    CKM_SSL3_SHA1_MAC, returnedKeys.hClientMacSecret, PR_TRUE, pwArg);
   3594     if (pwSpec->client.write_mac_key == NULL ) {
   3595 	goto loser;	/* loser sets err */
   3596     }
   3597     pwSpec->server.write_mac_key =
   3598     	PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3599 	    CKM_SSL3_SHA1_MAC, returnedKeys.hServerMacSecret, PR_TRUE, pwArg);
   3600     if (pwSpec->server.write_mac_key == NULL ) {
   3601 	goto loser;	/* loser sets err */
   3602     }
   3603     if (!skipKeysAndIVs) {
   3604 	pwSpec->client.write_key =
   3605 		PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3606 		     bulk_mechanism, returnedKeys.hClientKey, PR_TRUE, pwArg);
   3607 	if (pwSpec->client.write_key == NULL ) {
   3608 	    goto loser;	/* loser sets err */
   3609 	}
   3610 	pwSpec->server.write_key =
   3611 		PK11_SymKeyFromHandle(slot, symKey, PK11_OriginDerive,
   3612 		     bulk_mechanism, returnedKeys.hServerKey, PR_TRUE, pwArg);
   3613 	if (pwSpec->server.write_key == NULL ) {
   3614 	    goto loser;	/* loser sets err */
   3615 	}
   3616     }
   3617     PK11_FreeSymKey(symKey);
   3618     return SECSuccess;
   3619 
   3620 
   3621 loser:
   3622     if (symKey) PK11_FreeSymKey(symKey);
   3623     ssl_MapLowLevelError(SSL_ERROR_SESSION_KEY_GEN_FAILURE);
   3624     return SECFailure;
   3625 }
   3626 
   3627 /* ssl3_InitHandshakeHashes creates handshake hash contexts and hashes in
   3628  * buffered messages in ss->ssl3.hs.messages. */
   3629 static SECStatus
   3630 ssl3_InitHandshakeHashes(sslSocket *ss)
   3631 {
   3632     SSL_TRC(30,("%d: SSL3[%d]: start handshake hashes", SSL_GETPID(), ss->fd));
   3633 
   3634     PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown);
   3635 #ifndef NO_PKCS11_BYPASS
   3636     if (ss->opt.bypassPKCS11) {
   3637 	PORT_Assert(!ss->ssl3.hs.sha_obj && !ss->ssl3.hs.sha_clone);
   3638 	if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   3639 	    /* If we ever support ciphersuites where the PRF hash isn't SHA-256
   3640 	     * then this will need to be updated. */
   3641 	    ss->ssl3.hs.sha_obj = HASH_GetRawHashObject(HASH_AlgSHA256);
   3642 	    if (!ss->ssl3.hs.sha_obj) {
   3643 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   3644 		return SECFailure;
   3645 	    }
   3646 	    ss->ssl3.hs.sha_clone = (void (*)(void *, void *))SHA256_Clone;
   3647 	    ss->ssl3.hs.hashType = handshake_hash_single;
   3648 	    ss->ssl3.hs.sha_obj->begin(ss->ssl3.hs.sha_cx);
   3649 	} else {
   3650 	    ss->ssl3.hs.hashType = handshake_hash_combo;
   3651 	    MD5_Begin((MD5Context *)ss->ssl3.hs.md5_cx);
   3652 	    SHA1_Begin((SHA1Context *)ss->ssl3.hs.sha_cx);
   3653 	}
   3654     } else
   3655 #endif
   3656     {
   3657 	PORT_Assert(!ss->ssl3.hs.md5 && !ss->ssl3.hs.sha);
   3658 	/*
   3659 	 * note: We should probably lookup an SSL3 slot for these
   3660 	 * handshake hashes in hopes that we wind up with the same slots
   3661 	 * that the master secret will wind up in ...
   3662 	 */
   3663 	if (ss->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   3664 	    /* If we ever support ciphersuites where the PRF hash isn't SHA-256
   3665 	     * then this will need to be updated. */
   3666 	    ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA256);
   3667 	    if (ss->ssl3.hs.sha == NULL) {
   3668 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3669 		return SECFailure;
   3670 	    }
   3671 	    ss->ssl3.hs.hashType = handshake_hash_single;
   3672 
   3673 	    if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
   3674 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   3675 		return SECFailure;
   3676 	    }
   3677 
   3678 	    /* A backup SHA-1 hash for a potential client auth signature. */
   3679 	    if (!ss->sec.isServer) {
   3680 		ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_SHA1);
   3681 		if (ss->ssl3.hs.md5 == NULL) {
   3682 		    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3683 		    return SECFailure;
   3684 		}
   3685 
   3686 		if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
   3687 		    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3688 		    return SECFailure;
   3689 		}
   3690 	    }
   3691 	} else {
   3692 	    /* Both ss->ssl3.hs.md5 and ss->ssl3.hs.sha should be NULL or
   3693 	     * created successfully. */
   3694 	    ss->ssl3.hs.md5 = PK11_CreateDigestContext(SEC_OID_MD5);
   3695 	    if (ss->ssl3.hs.md5 == NULL) {
   3696 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   3697 		return SECFailure;
   3698 	    }
   3699 	    ss->ssl3.hs.sha = PK11_CreateDigestContext(SEC_OID_SHA1);
   3700 	    if (ss->ssl3.hs.sha == NULL) {
   3701 		PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   3702 		ss->ssl3.hs.md5 = NULL;
   3703 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3704 		return SECFailure;
   3705 	    }
   3706 	    ss->ssl3.hs.hashType = handshake_hash_combo;
   3707 
   3708 	    if (PK11_DigestBegin(ss->ssl3.hs.md5) != SECSuccess) {
   3709 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   3710 		return SECFailure;
   3711 	    }
   3712 	    if (PK11_DigestBegin(ss->ssl3.hs.sha) != SECSuccess) {
   3713 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3714 		return SECFailure;
   3715 	    }
   3716 	}
   3717     }
   3718 
   3719     if (ss->ssl3.hs.messages.len > 0) {
   3720 	if (ssl3_UpdateHandshakeHashes(ss, ss->ssl3.hs.messages.buf,
   3721 				       ss->ssl3.hs.messages.len) !=
   3722 	    SECSuccess) {
   3723 	    return SECFailure;
   3724 	}
   3725 	PORT_Free(ss->ssl3.hs.messages.buf);
   3726 	ss->ssl3.hs.messages.buf = NULL;
   3727 	ss->ssl3.hs.messages.len = 0;
   3728 	ss->ssl3.hs.messages.space = 0;
   3729     }
   3730 
   3731     return SECSuccess;
   3732 }
   3733 
   3734 static SECStatus
   3735 ssl3_RestartHandshakeHashes(sslSocket *ss)
   3736 {
   3737     SECStatus rv = SECSuccess;
   3738 
   3739     SSL_TRC(30,("%d: SSL3[%d]: reset handshake hashes",
   3740 	    SSL_GETPID(), ss->fd ));
   3741     ss->ssl3.hs.hashType = handshake_hash_unknown;
   3742     ss->ssl3.hs.messages.len = 0;
   3743 #ifndef NO_PKCS11_BYPASS
   3744     ss->ssl3.hs.sha_obj = NULL;
   3745     ss->ssl3.hs.sha_clone = NULL;
   3746 #endif
   3747     if (ss->ssl3.hs.md5) {
   3748 	PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
   3749 	ss->ssl3.hs.md5 = NULL;
   3750     }
   3751     if (ss->ssl3.hs.sha) {
   3752 	PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
   3753 	ss->ssl3.hs.sha = NULL;
   3754     }
   3755     return rv;
   3756 }
   3757 
   3758 /*
   3759  * Handshake messages
   3760  */
   3761 /* Called from	ssl3_InitHandshakeHashes()
   3762 **		ssl3_AppendHandshake()
   3763 **		ssl3_StartHandshakeHash()
   3764 **		ssl3_HandleV2ClientHello()
   3765 **		ssl3_HandleHandshakeMessage()
   3766 ** Caller must hold the ssl3Handshake lock.
   3767 */
   3768 static SECStatus
   3769 ssl3_UpdateHandshakeHashes(sslSocket *ss, const unsigned char *b,
   3770 			   unsigned int l)
   3771 {
   3772     SECStatus  rv = SECSuccess;
   3773 
   3774     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   3775 
   3776     /* We need to buffer the handshake messages until we have established
   3777      * which handshake hash function to use. */
   3778     if (ss->ssl3.hs.hashType == handshake_hash_unknown) {
   3779 	return sslBuffer_Append(&ss->ssl3.hs.messages, b, l);
   3780     }
   3781 
   3782     PRINT_BUF(90, (NULL, "handshake hash input:", b, l));
   3783 
   3784 #ifndef NO_PKCS11_BYPASS
   3785     if (ss->opt.bypassPKCS11) {
   3786 	if (ss->ssl3.hs.hashType == handshake_hash_single) {
   3787 	    ss->ssl3.hs.sha_obj->update(ss->ssl3.hs.sha_cx, b, l);
   3788 	} else {
   3789 	    MD5_Update((MD5Context *)ss->ssl3.hs.md5_cx, b, l);
   3790 	    SHA1_Update((SHA1Context *)ss->ssl3.hs.sha_cx, b, l);
   3791 	}
   3792 	return rv;
   3793     }
   3794 #endif
   3795     if (ss->ssl3.hs.hashType == handshake_hash_single) {
   3796 	rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
   3797 	if (rv != SECSuccess) {
   3798 	    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   3799 	    return rv;
   3800 	}
   3801 	if (ss->ssl3.hs.md5) {
   3802 	    rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
   3803 	    if (rv != SECSuccess) {
   3804 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3805 		return rv;
   3806 	    }
   3807 	}
   3808     } else {
   3809 	rv = PK11_DigestOp(ss->ssl3.hs.md5, b, l);
   3810 	if (rv != SECSuccess) {
   3811 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   3812 	    return rv;
   3813 	}
   3814 	rv = PK11_DigestOp(ss->ssl3.hs.sha, b, l);
   3815 	if (rv != SECSuccess) {
   3816 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   3817 	    return rv;
   3818 	}
   3819     }
   3820     return rv;
   3821 }
   3822 
   3823 /**************************************************************************
   3824  * Append Handshake functions.
   3825  * All these functions set appropriate error codes.
   3826  * Most rely on ssl3_AppendHandshake to set the error code.
   3827  **************************************************************************/
   3828 SECStatus
   3829 ssl3_AppendHandshake(sslSocket *ss, const void *void_src, PRInt32 bytes)
   3830 {
   3831     unsigned char *  src  = (unsigned char *)void_src;
   3832     int              room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
   3833     SECStatus        rv;
   3834 
   3835     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) ); /* protects sendBuf. */
   3836 
   3837     if (!bytes)
   3838     	return SECSuccess;
   3839     if (ss->sec.ci.sendBuf.space < MAX_SEND_BUF_LENGTH && room < bytes) {
   3840 	rv = sslBuffer_Grow(&ss->sec.ci.sendBuf, PR_MAX(MIN_SEND_BUF_LENGTH,
   3841 		 PR_MIN(MAX_SEND_BUF_LENGTH, ss->sec.ci.sendBuf.len + bytes)));
   3842 	if (rv != SECSuccess)
   3843 	    return rv;	/* sslBuffer_Grow has set a memory error code. */
   3844 	room = ss->sec.ci.sendBuf.space - ss->sec.ci.sendBuf.len;
   3845     }
   3846 
   3847     PRINT_BUF(60, (ss, "Append to Handshake", (unsigned char*)void_src, bytes));
   3848     rv = ssl3_UpdateHandshakeHashes(ss, src, bytes);
   3849     if (rv != SECSuccess)
   3850 	return rv;	/* error code set by ssl3_UpdateHandshakeHashes */
   3851 
   3852     while (bytes > room) {
   3853 	if (room > 0)
   3854 	    PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src,
   3855 	                room);
   3856 	ss->sec.ci.sendBuf.len += room;
   3857 	rv = ssl3_FlushHandshake(ss, ssl_SEND_FLAG_FORCE_INTO_BUFFER);
   3858 	if (rv != SECSuccess) {
   3859 	    return rv;	/* error code set by ssl3_FlushHandshake */
   3860 	}
   3861 	bytes -= room;
   3862 	src += room;
   3863 	room = ss->sec.ci.sendBuf.space;
   3864 	PORT_Assert(ss->sec.ci.sendBuf.len == 0);
   3865     }
   3866     PORT_Memcpy(ss->sec.ci.sendBuf.buf + ss->sec.ci.sendBuf.len, src, bytes);
   3867     ss->sec.ci.sendBuf.len += bytes;
   3868     return SECSuccess;
   3869 }
   3870 
   3871 SECStatus
   3872 ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, PRInt32 lenSize)
   3873 {
   3874     SECStatus rv;
   3875     PRUint8   b[4];
   3876     PRUint8 * p = b;
   3877 
   3878     switch (lenSize) {
   3879       case 4:
   3880 	*p++ = (num >> 24) & 0xff;
   3881       case 3:
   3882 	*p++ = (num >> 16) & 0xff;
   3883       case 2:
   3884 	*p++ = (num >> 8) & 0xff;
   3885       case 1:
   3886 	*p = num & 0xff;
   3887     }
   3888     SSL_TRC(60, ("%d: number:", SSL_GETPID()));
   3889     rv = ssl3_AppendHandshake(ss, &b[0], lenSize);
   3890     return rv;	/* error code set by AppendHandshake, if applicable. */
   3891 }
   3892 
   3893 SECStatus
   3894 ssl3_AppendHandshakeVariable(
   3895     sslSocket *ss, const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize)
   3896 {
   3897     SECStatus rv;
   3898 
   3899     PORT_Assert((bytes < (1<<8) && lenSize == 1) ||
   3900 	      (bytes < (1L<<16) && lenSize == 2) ||
   3901 	      (bytes < (1L<<24) && lenSize == 3));
   3902 
   3903     SSL_TRC(60,("%d: append variable:", SSL_GETPID()));
   3904     rv = ssl3_AppendHandshakeNumber(ss, bytes, lenSize);
   3905     if (rv != SECSuccess) {
   3906 	return rv;	/* error code set by AppendHandshake, if applicable. */
   3907     }
   3908     SSL_TRC(60, ("data:"));
   3909     rv = ssl3_AppendHandshake(ss, src, bytes);
   3910     return rv;	/* error code set by AppendHandshake, if applicable. */
   3911 }
   3912 
   3913 SECStatus
   3914 ssl3_AppendHandshakeHeader(sslSocket *ss, SSL3HandshakeType t, PRUint32 length)
   3915 {
   3916     SECStatus rv;
   3917 
   3918     /* If we already have a message in place, we need to enqueue it.
   3919      * This empties the buffer. This is a convenient place to call
   3920      * dtls_StageHandshakeMessage to mark the message boundary.
   3921      */
   3922     if (IS_DTLS(ss)) {
   3923 	rv = dtls_StageHandshakeMessage(ss);
   3924 	if (rv != SECSuccess) {
   3925 	    return rv;
   3926 	}
   3927     }
   3928 
   3929     SSL_TRC(30,("%d: SSL3[%d]: append handshake header: type %s",
   3930     	SSL_GETPID(), ss->fd, ssl3_DecodeHandshakeType(t)));
   3931 
   3932     rv = ssl3_AppendHandshakeNumber(ss, t, 1);
   3933     if (rv != SECSuccess) {
   3934     	return rv;	/* error code set by AppendHandshake, if applicable. */
   3935     }
   3936     rv = ssl3_AppendHandshakeNumber(ss, length, 3);
   3937     if (rv != SECSuccess) {
   3938     	return rv;	/* error code set by AppendHandshake, if applicable. */
   3939     }
   3940 
   3941     if (IS_DTLS(ss)) {
   3942 	/* Note that we make an unfragmented message here. We fragment in the
   3943 	 * transmission code, if necessary */
   3944 	rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.sendMessageSeq, 2);
   3945 	if (rv != SECSuccess) {
   3946 	    return rv;	/* error code set by AppendHandshake, if applicable. */
   3947 	}
   3948 	ss->ssl3.hs.sendMessageSeq++;
   3949 
   3950 	/* 0 is the fragment offset, because it's not fragmented yet */
   3951 	rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
   3952 	if (rv != SECSuccess) {
   3953 	    return rv;	/* error code set by AppendHandshake, if applicable. */
   3954 	}
   3955 
   3956 	/* Fragment length -- set to the packet length because not fragmented */
   3957 	rv = ssl3_AppendHandshakeNumber(ss, length, 3);
   3958 	if (rv != SECSuccess) {
   3959 	    return rv;	/* error code set by AppendHandshake, if applicable. */
   3960 	}
   3961     }
   3962 
   3963     return rv;		/* error code set by AppendHandshake, if applicable. */
   3964 }
   3965 
   3966 /* ssl3_AppendSignatureAndHashAlgorithm appends the serialisation of
   3967  * |sigAndHash| to the current handshake message. */
   3968 SECStatus
   3969 ssl3_AppendSignatureAndHashAlgorithm(
   3970 	sslSocket *ss, const SSL3SignatureAndHashAlgorithm* sigAndHash)
   3971 {
   3972     unsigned char serialized[2];
   3973 
   3974     serialized[0] = ssl3_OIDToTLSHashAlgorithm(sigAndHash->hashAlg);
   3975     if (serialized[0] == 0) {
   3976 	PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   3977 	return SECFailure;
   3978     }
   3979 
   3980     serialized[1] = sigAndHash->sigAlg;
   3981 
   3982     return ssl3_AppendHandshake(ss, serialized, sizeof(serialized));
   3983 }
   3984 
   3985 /**************************************************************************
   3986  * Consume Handshake functions.
   3987  *
   3988  * All data used in these functions is protected by two locks,
   3989  * the RecvBufLock and the SSL3HandshakeLock
   3990  **************************************************************************/
   3991 
   3992 /* Read up the next "bytes" number of bytes from the (decrypted) input
   3993  * stream "b" (which is *length bytes long). Copy them into buffer "v".
   3994  * Reduces *length by bytes.  Advances *b by bytes.
   3995  *
   3996  * If this function returns SECFailure, it has already sent an alert,
   3997  * and has set a generic error code.  The caller should probably
   3998  * override the generic error code by setting another.
   3999  */
   4000 SECStatus
   4001 ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, SSL3Opaque **b,
   4002 		      PRUint32 *length)
   4003 {
   4004     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   4005     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4006 
   4007     if ((PRUint32)bytes > *length) {
   4008 	return ssl3_DecodeError(ss);
   4009     }
   4010     PORT_Memcpy(v, *b, bytes);
   4011     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
   4012     *b      += bytes;
   4013     *length -= bytes;
   4014     return SECSuccess;
   4015 }
   4016 
   4017 /* Read up the next "bytes" number of bytes from the (decrypted) input
   4018  * stream "b" (which is *length bytes long), and interpret them as an
   4019  * integer in network byte order.  Returns the received value.
   4020  * Reduces *length by bytes.  Advances *b by bytes.
   4021  *
   4022  * Returns SECFailure (-1) on failure.
   4023  * This value is indistinguishable from the equivalent received value.
   4024  * Only positive numbers are to be received this way.
   4025  * Thus, the largest value that may be sent this way is 0x7fffffff.
   4026  * On error, an alert has been sent, and a generic error code has been set.
   4027  */
   4028 PRInt32
   4029 ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, SSL3Opaque **b,
   4030 			    PRUint32 *length)
   4031 {
   4032     PRUint8  *buf = *b;
   4033     int       i;
   4034     PRInt32   num = 0;
   4035 
   4036     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   4037     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4038     PORT_Assert( bytes <= sizeof num);
   4039 
   4040     if ((PRUint32)bytes > *length) {
   4041 	return ssl3_DecodeError(ss);
   4042     }
   4043     PRINT_BUF(60, (ss, "consume bytes:", *b, bytes));
   4044 
   4045     for (i = 0; i < bytes; i++)
   4046 	num = (num << 8) + buf[i];
   4047     *b      += bytes;
   4048     *length -= bytes;
   4049     return num;
   4050 }
   4051 
   4052 /* Read in two values from the incoming decrypted byte stream "b", which is
   4053  * *length bytes long.  The first value is a number whose size is "bytes"
   4054  * bytes long.  The second value is a byte-string whose size is the value
   4055  * of the first number received.  The latter byte-string, and its length,
   4056  * is returned in the SECItem i.
   4057  *
   4058  * Returns SECFailure (-1) on failure.
   4059  * On error, an alert has been sent, and a generic error code has been set.
   4060  *
   4061  * RADICAL CHANGE for NSS 3.11.  All callers of this function make copies
   4062  * of the data returned in the SECItem *i, so making a copy of it here
   4063  * is simply wasteful.  So, This function now just sets SECItem *i to
   4064  * point to the values in the buffer **b.
   4065  */
   4066 SECStatus
   4067 ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, PRInt32 bytes,
   4068 			      SSL3Opaque **b, PRUint32 *length)
   4069 {
   4070     PRInt32   count;
   4071 
   4072     PORT_Assert(bytes <= 3);
   4073     i->len  = 0;
   4074     i->data = NULL;
   4075     count = ssl3_ConsumeHandshakeNumber(ss, bytes, b, length);
   4076     if (count < 0) { 		/* Can't test for SECSuccess here. */
   4077     	return SECFailure;
   4078     }
   4079     if (count > 0) {
   4080 	if ((PRUint32)count > *length) {
   4081 	    return ssl3_DecodeError(ss);
   4082 	}
   4083 	i->data = *b;
   4084 	i->len  = count;
   4085 	*b      += count;
   4086 	*length -= count;
   4087     }
   4088     return SECSuccess;
   4089 }
   4090 
   4091 /* tlsHashOIDMap contains the mapping between TLS hash identifiers and the
   4092  * SECOidTag used internally by NSS. */
   4093 static const struct {
   4094     int tlsHash;
   4095     SECOidTag oid;
   4096 } tlsHashOIDMap[] = {
   4097     { tls_hash_md5, SEC_OID_MD5 },
   4098     { tls_hash_sha1, SEC_OID_SHA1 },
   4099     { tls_hash_sha224, SEC_OID_SHA224 },
   4100     { tls_hash_sha256, SEC_OID_SHA256 },
   4101     { tls_hash_sha384, SEC_OID_SHA384 },
   4102     { tls_hash_sha512, SEC_OID_SHA512 }
   4103 };
   4104 
   4105 /* ssl3_TLSHashAlgorithmToOID converts a TLS hash identifier into an OID value.
   4106  * If the hash is not recognised, SEC_OID_UNKNOWN is returned.
   4107  *
   4108  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   4109 SECOidTag
   4110 ssl3_TLSHashAlgorithmToOID(int hashFunc)
   4111 {
   4112     unsigned int i;
   4113 
   4114     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
   4115 	if (hashFunc == tlsHashOIDMap[i].tlsHash) {
   4116 	    return tlsHashOIDMap[i].oid;
   4117 	}
   4118     }
   4119     return SEC_OID_UNKNOWN;
   4120 }
   4121 
   4122 /* ssl3_OIDToTLSHashAlgorithm converts an OID to a TLS hash algorithm
   4123  * identifier. If the hash is not recognised, zero is returned.
   4124  *
   4125  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   4126 static int
   4127 ssl3_OIDToTLSHashAlgorithm(SECOidTag oid)
   4128 {
   4129     unsigned int i;
   4130 
   4131     for (i = 0; i < PR_ARRAY_SIZE(tlsHashOIDMap); i++) {
   4132 	if (oid == tlsHashOIDMap[i].oid) {
   4133 	    return tlsHashOIDMap[i].tlsHash;
   4134 	}
   4135     }
   4136     return 0;
   4137 }
   4138 
   4139 /* ssl3_TLSSignatureAlgorithmForKeyType returns the TLS 1.2 signature algorithm
   4140  * identifier for a given KeyType. */
   4141 static SECStatus
   4142 ssl3_TLSSignatureAlgorithmForKeyType(KeyType keyType,
   4143 				     TLSSignatureAlgorithm *out)
   4144 {
   4145     switch (keyType) {
   4146     case rsaKey:
   4147 	*out = tls_sig_rsa;
   4148 	return SECSuccess;
   4149     case dsaKey:
   4150 	*out = tls_sig_dsa;
   4151 	return SECSuccess;
   4152     case ecKey:
   4153 	*out = tls_sig_ecdsa;
   4154 	return SECSuccess;
   4155     default:
   4156 	PORT_SetError(SEC_ERROR_INVALID_KEY);
   4157 	return SECFailure;
   4158     }
   4159 }
   4160 
   4161 /* ssl3_TLSSignatureAlgorithmForCertificate returns the TLS 1.2 signature
   4162  * algorithm identifier for the given certificate. */
   4163 static SECStatus
   4164 ssl3_TLSSignatureAlgorithmForCertificate(CERTCertificate *cert,
   4165 					 TLSSignatureAlgorithm *out)
   4166 {
   4167     SECKEYPublicKey *key;
   4168     KeyType keyType;
   4169 
   4170     key = CERT_ExtractPublicKey(cert);
   4171     if (key == NULL) {
   4172 	ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   4173     	return SECFailure;
   4174     }
   4175 
   4176     keyType = key->keyType;
   4177     SECKEY_DestroyPublicKey(key);
   4178     return ssl3_TLSSignatureAlgorithmForKeyType(keyType, out);
   4179 }
   4180 
   4181 /* ssl3_CheckSignatureAndHashAlgorithmConsistency checks that the signature
   4182  * algorithm identifier in |sigAndHash| is consistent with the public key in
   4183  * |cert|. If so, SECSuccess is returned. Otherwise, PORT_SetError is called
   4184  * and SECFailure is returned. */
   4185 SECStatus
   4186 ssl3_CheckSignatureAndHashAlgorithmConsistency(
   4187 	const SSL3SignatureAndHashAlgorithm *sigAndHash, CERTCertificate* cert)
   4188 {
   4189     SECStatus rv;
   4190     TLSSignatureAlgorithm sigAlg;
   4191 
   4192     rv = ssl3_TLSSignatureAlgorithmForCertificate(cert, &sigAlg);
   4193     if (rv != SECSuccess) {
   4194 	return rv;
   4195     }
   4196     if (sigAlg != sigAndHash->sigAlg) {
   4197 	PORT_SetError(SSL_ERROR_INCORRECT_SIGNATURE_ALGORITHM);
   4198 	return SECFailure;
   4199     }
   4200     return SECSuccess;
   4201 }
   4202 
   4203 /* ssl3_ConsumeSignatureAndHashAlgorithm reads a SignatureAndHashAlgorithm
   4204  * structure from |b| and puts the resulting value into |out|. |b| and |length|
   4205  * are updated accordingly.
   4206  *
   4207  * See https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   4208 SECStatus
   4209 ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
   4210 				      SSL3Opaque **b,
   4211 				      PRUint32 *length,
   4212 				      SSL3SignatureAndHashAlgorithm *out)
   4213 {
   4214     unsigned char bytes[2];
   4215     SECStatus rv;
   4216 
   4217     rv = ssl3_ConsumeHandshake(ss, bytes, sizeof(bytes), b, length);
   4218     if (rv != SECSuccess) {
   4219 	return rv;
   4220     }
   4221 
   4222     out->hashAlg = ssl3_TLSHashAlgorithmToOID(bytes[0]);
   4223     if (out->hashAlg == SEC_OID_UNKNOWN) {
   4224 	PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   4225 	return SECFailure;
   4226     }
   4227 
   4228     out->sigAlg = bytes[1];
   4229     return SECSuccess;
   4230 }
   4231 
   4232 /**************************************************************************
   4233  * end of Consume Handshake functions.
   4234  **************************************************************************/
   4235 
   4236 /* Extract the hashes of handshake messages to this point.
   4237  * Called from ssl3_SendCertificateVerify
   4238  *             ssl3_SendFinished
   4239  *             ssl3_HandleHandshakeMessage
   4240  *
   4241  * Caller must hold the SSL3HandshakeLock.
   4242  * Caller must hold a read or write lock on the Spec R/W lock.
   4243  *	(There is presently no way to assert on a Read lock.)
   4244  */
   4245 static SECStatus
   4246 ssl3_ComputeHandshakeHashes(sslSocket *     ss,
   4247                             ssl3CipherSpec *spec,   /* uses ->master_secret */
   4248 			    SSL3Hashes *    hashes, /* output goes here. */
   4249 			    PRUint32        sender)
   4250 {
   4251     SECStatus     rv        = SECSuccess;
   4252     PRBool        isTLS     = (PRBool)(spec->version > SSL_LIBRARY_VERSION_3_0);
   4253     unsigned int  outLength;
   4254     SSL3Opaque    md5_inner[MAX_MAC_LENGTH];
   4255     SSL3Opaque    sha_inner[MAX_MAC_LENGTH];
   4256 
   4257     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4258     hashes->hashAlg = SEC_OID_UNKNOWN;
   4259 
   4260 #ifndef NO_PKCS11_BYPASS
   4261     if (ss->opt.bypassPKCS11 &&
   4262 	ss->ssl3.hs.hashType == handshake_hash_single) {
   4263 	/* compute them without PKCS11 */
   4264 	PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
   4265 
   4266 	if (!spec->msItem.data) {
   4267 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4268 	    return SECFailure;
   4269 	}
   4270 
   4271 	ss->ssl3.hs.sha_clone(sha_cx, ss->ssl3.hs.sha_cx);
   4272 	ss->ssl3.hs.sha_obj->end(sha_cx, hashes->u.raw, &hashes->len,
   4273 				 sizeof(hashes->u.raw));
   4274 
   4275 	PRINT_BUF(60, (NULL, "SHA-256: result", hashes->u.raw, hashes->len));
   4276 
   4277 	/* If we ever support ciphersuites where the PRF hash isn't SHA-256
   4278 	 * then this will need to be updated. */
   4279 	hashes->hashAlg = SEC_OID_SHA256;
   4280 	rv = SECSuccess;
   4281     } else if (ss->opt.bypassPKCS11) {
   4282 	/* compute them without PKCS11 */
   4283 	PRUint64      md5_cx[MAX_MAC_CONTEXT_LLONGS];
   4284 	PRUint64      sha_cx[MAX_MAC_CONTEXT_LLONGS];
   4285 
   4286 #define md5cx ((MD5Context *)md5_cx)
   4287 #define shacx ((SHA1Context *)sha_cx)
   4288 
   4289 	if (!spec->msItem.data) {
   4290 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4291 	    return SECFailure;
   4292 	}
   4293 
   4294 	MD5_Clone (md5cx,  (MD5Context *)ss->ssl3.hs.md5_cx);
   4295 	SHA1_Clone(shacx, (SHA1Context *)ss->ssl3.hs.sha_cx);
   4296 
   4297 	if (!isTLS) {
   4298 	    /* compute hashes for SSL3. */
   4299 	    unsigned char s[4];
   4300 
   4301 	    s[0] = (unsigned char)(sender >> 24);
   4302 	    s[1] = (unsigned char)(sender >> 16);
   4303 	    s[2] = (unsigned char)(sender >> 8);
   4304 	    s[3] = (unsigned char)sender;
   4305 
   4306 	    if (sender != 0) {
   4307 		MD5_Update(md5cx, s, 4);
   4308 		PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
   4309 	    }
   4310 
   4311 	    PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
   4312 			    mac_defs[mac_md5].pad_size));
   4313 
   4314 	    MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
   4315 	    MD5_Update(md5cx, mac_pad_1, mac_defs[mac_md5].pad_size);
   4316 	    MD5_End(md5cx, md5_inner, &outLength, MD5_LENGTH);
   4317 
   4318 	    PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
   4319 
   4320 	    if (sender != 0) {
   4321 		SHA1_Update(shacx, s, 4);
   4322 		PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
   4323 	    }
   4324 
   4325 	    PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
   4326 			    mac_defs[mac_sha].pad_size));
   4327 
   4328 	    SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
   4329 	    SHA1_Update(shacx, mac_pad_1, mac_defs[mac_sha].pad_size);
   4330 	    SHA1_End(shacx, sha_inner, &outLength, SHA1_LENGTH);
   4331 
   4332 	    PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
   4333 	    PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
   4334 			    mac_defs[mac_md5].pad_size));
   4335 	    PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
   4336 
   4337 	    MD5_Begin(md5cx);
   4338 	    MD5_Update(md5cx, spec->msItem.data, spec->msItem.len);
   4339 	    MD5_Update(md5cx, mac_pad_2, mac_defs[mac_md5].pad_size);
   4340 	    MD5_Update(md5cx, md5_inner, MD5_LENGTH);
   4341 	}
   4342 	MD5_End(md5cx, hashes->u.s.md5, &outLength, MD5_LENGTH);
   4343 
   4344 	PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
   4345 
   4346 	if (!isTLS) {
   4347 	    PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
   4348 			    mac_defs[mac_sha].pad_size));
   4349 	    PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
   4350 
   4351 	    SHA1_Begin(shacx);
   4352 	    SHA1_Update(shacx, spec->msItem.data, spec->msItem.len);
   4353 	    SHA1_Update(shacx, mac_pad_2, mac_defs[mac_sha].pad_size);
   4354 	    SHA1_Update(shacx, sha_inner, SHA1_LENGTH);
   4355 	}
   4356 	SHA1_End(shacx, hashes->u.s.sha, &outLength, SHA1_LENGTH);
   4357 
   4358 	PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
   4359 
   4360 	hashes->len = MD5_LENGTH + SHA1_LENGTH;
   4361 	rv = SECSuccess;
   4362 #undef md5cx
   4363 #undef shacx
   4364     } else
   4365 #endif
   4366     if (ss->ssl3.hs.hashType == handshake_hash_single) {
   4367 	/* compute hashes with PKCS11 */
   4368 	PK11Context *h;
   4369 	unsigned int  stateLen;
   4370 	unsigned char stackBuf[1024];
   4371 	unsigned char *stateBuf = NULL;
   4372 
   4373 	if (!spec->master_secret) {
   4374 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4375 	    return SECFailure;
   4376 	}
   4377 
   4378 	h = ss->ssl3.hs.sha;
   4379 	stateBuf = PK11_SaveContextAlloc(h, stackBuf,
   4380 					 sizeof(stackBuf), &stateLen);
   4381 	if (stateBuf == NULL) {
   4382 	    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4383 	    goto tls12_loser;
   4384 	}
   4385 	rv |= PK11_DigestFinal(h, hashes->u.raw, &hashes->len,
   4386 			       sizeof(hashes->u.raw));
   4387 	if (rv != SECSuccess) {
   4388 	    ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4389 	    rv = SECFailure;
   4390 	    goto tls12_loser;
   4391 	}
   4392 	/* If we ever support ciphersuites where the PRF hash isn't SHA-256
   4393 	 * then this will need to be updated. */
   4394 	hashes->hashAlg = SEC_OID_SHA256;
   4395 	rv = SECSuccess;
   4396 
   4397 tls12_loser:
   4398 	if (stateBuf) {
   4399 	    if (PK11_RestoreContext(h, stateBuf, stateLen) != SECSuccess) {
   4400 		ssl_MapLowLevelError(SSL_ERROR_DIGEST_FAILURE);
   4401 		rv = SECFailure;
   4402 	    }
   4403 	    if (stateBuf != stackBuf) {
   4404 		PORT_ZFree(stateBuf, stateLen);
   4405 	    }
   4406 	}
   4407     } else {
   4408 	/* compute hashes with PKCS11 */
   4409 	PK11Context * md5;
   4410 	PK11Context * sha       = NULL;
   4411 	unsigned char *md5StateBuf = NULL;
   4412 	unsigned char *shaStateBuf = NULL;
   4413 	unsigned int  md5StateLen, shaStateLen;
   4414 	unsigned char md5StackBuf[256];
   4415 	unsigned char shaStackBuf[512];
   4416 
   4417 	if (!spec->master_secret) {
   4418 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HANDSHAKE);
   4419 	    return SECFailure;
   4420 	}
   4421 
   4422 	md5StateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.md5, md5StackBuf,
   4423 					    sizeof md5StackBuf, &md5StateLen);
   4424 	if (md5StateBuf == NULL) {
   4425 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4426 	    goto loser;
   4427 	}
   4428 	md5 = ss->ssl3.hs.md5;
   4429 
   4430 	shaStateBuf = PK11_SaveContextAlloc(ss->ssl3.hs.sha, shaStackBuf,
   4431 					    sizeof shaStackBuf, &shaStateLen);
   4432 	if (shaStateBuf == NULL) {
   4433 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4434 	    goto loser;
   4435 	}
   4436 	sha = ss->ssl3.hs.sha;
   4437 
   4438 	if (!isTLS) {
   4439 	    /* compute hashes for SSL3. */
   4440 	    unsigned char s[4];
   4441 
   4442 	    s[0] = (unsigned char)(sender >> 24);
   4443 	    s[1] = (unsigned char)(sender >> 16);
   4444 	    s[2] = (unsigned char)(sender >> 8);
   4445 	    s[3] = (unsigned char)sender;
   4446 
   4447 	    if (sender != 0) {
   4448 		rv |= PK11_DigestOp(md5, s, 4);
   4449 		PRINT_BUF(95, (NULL, "MD5 inner: sender", s, 4));
   4450 	    }
   4451 
   4452 	    PRINT_BUF(95, (NULL, "MD5 inner: MAC Pad 1", mac_pad_1,
   4453 			  mac_defs[mac_md5].pad_size));
   4454 
   4455 	    rv |= PK11_DigestKey(md5,spec->master_secret);
   4456 	    rv |= PK11_DigestOp(md5, mac_pad_1, mac_defs[mac_md5].pad_size);
   4457 	    rv |= PK11_DigestFinal(md5, md5_inner, &outLength, MD5_LENGTH);
   4458 	    PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
   4459 	    if (rv != SECSuccess) {
   4460 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4461 		rv = SECFailure;
   4462 		goto loser;
   4463 	    }
   4464 
   4465 	    PRINT_BUF(95, (NULL, "MD5 inner: result", md5_inner, outLength));
   4466 
   4467 	    if (sender != 0) {
   4468 		rv |= PK11_DigestOp(sha, s, 4);
   4469 		PRINT_BUF(95, (NULL, "SHA inner: sender", s, 4));
   4470 	    }
   4471 
   4472 	    PRINT_BUF(95, (NULL, "SHA inner: MAC Pad 1", mac_pad_1,
   4473 			  mac_defs[mac_sha].pad_size));
   4474 
   4475 	    rv |= PK11_DigestKey(sha, spec->master_secret);
   4476 	    rv |= PK11_DigestOp(sha, mac_pad_1, mac_defs[mac_sha].pad_size);
   4477 	    rv |= PK11_DigestFinal(sha, sha_inner, &outLength, SHA1_LENGTH);
   4478 	    PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
   4479 	    if (rv != SECSuccess) {
   4480 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4481 		rv = SECFailure;
   4482 		goto loser;
   4483 	    }
   4484 
   4485 	    PRINT_BUF(95, (NULL, "SHA inner: result", sha_inner, outLength));
   4486 
   4487 	    PRINT_BUF(95, (NULL, "MD5 outer: MAC Pad 2", mac_pad_2,
   4488 			  mac_defs[mac_md5].pad_size));
   4489 	    PRINT_BUF(95, (NULL, "MD5 outer: MD5 inner", md5_inner, MD5_LENGTH));
   4490 
   4491 	    rv |= PK11_DigestBegin(md5);
   4492 	    rv |= PK11_DigestKey(md5, spec->master_secret);
   4493 	    rv |= PK11_DigestOp(md5, mac_pad_2, mac_defs[mac_md5].pad_size);
   4494 	    rv |= PK11_DigestOp(md5, md5_inner, MD5_LENGTH);
   4495 	}
   4496 	rv |= PK11_DigestFinal(md5, hashes->u.s.md5, &outLength, MD5_LENGTH);
   4497 	PORT_Assert(rv != SECSuccess || outLength == MD5_LENGTH);
   4498 	if (rv != SECSuccess) {
   4499 	    ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4500 	    rv = SECFailure;
   4501 	    goto loser;
   4502 	}
   4503 
   4504 	PRINT_BUF(60, (NULL, "MD5 outer: result", hashes->u.s.md5, MD5_LENGTH));
   4505 
   4506 	if (!isTLS) {
   4507 	    PRINT_BUF(95, (NULL, "SHA outer: MAC Pad 2", mac_pad_2,
   4508 			  mac_defs[mac_sha].pad_size));
   4509 	    PRINT_BUF(95, (NULL, "SHA outer: SHA inner", sha_inner, SHA1_LENGTH));
   4510 
   4511 	    rv |= PK11_DigestBegin(sha);
   4512 	    rv |= PK11_DigestKey(sha,spec->master_secret);
   4513 	    rv |= PK11_DigestOp(sha, mac_pad_2, mac_defs[mac_sha].pad_size);
   4514 	    rv |= PK11_DigestOp(sha, sha_inner, SHA1_LENGTH);
   4515 	}
   4516 	rv |= PK11_DigestFinal(sha, hashes->u.s.sha, &outLength, SHA1_LENGTH);
   4517 	PORT_Assert(rv != SECSuccess || outLength == SHA1_LENGTH);
   4518 	if (rv != SECSuccess) {
   4519 	    ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4520 	    rv = SECFailure;
   4521 	    goto loser;
   4522 	}
   4523 
   4524 	PRINT_BUF(60, (NULL, "SHA outer: result", hashes->u.s.sha, SHA1_LENGTH));
   4525 
   4526 	hashes->len = MD5_LENGTH + SHA1_LENGTH;
   4527 	rv = SECSuccess;
   4528 
   4529     loser:
   4530 	if (md5StateBuf) {
   4531 	    if (PK11_RestoreContext(ss->ssl3.hs.md5, md5StateBuf, md5StateLen)
   4532 		 != SECSuccess)
   4533 	    {
   4534 		ssl_MapLowLevelError(SSL_ERROR_MD5_DIGEST_FAILURE);
   4535 		rv = SECFailure;
   4536 	    }
   4537 	    if (md5StateBuf != md5StackBuf) {
   4538 		PORT_ZFree(md5StateBuf, md5StateLen);
   4539 	    }
   4540 	}
   4541 	if (shaStateBuf) {
   4542 	    if (PK11_RestoreContext(ss->ssl3.hs.sha, shaStateBuf, shaStateLen)
   4543 		 != SECSuccess)
   4544 	    {
   4545 		ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4546 		rv = SECFailure;
   4547 	    }
   4548 	    if (shaStateBuf != shaStackBuf) {
   4549 		PORT_ZFree(shaStateBuf, shaStateLen);
   4550 	    }
   4551 	}
   4552     }
   4553     return rv;
   4554 }
   4555 
   4556 static SECStatus
   4557 ssl3_ComputeBackupHandshakeHashes(sslSocket * ss,
   4558 				  SSL3Hashes * hashes) /* output goes here. */
   4559 {
   4560     SECStatus rv = SECSuccess;
   4561 
   4562     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4563     PORT_Assert( ss->ssl3.hs.hashType == handshake_hash_single );
   4564 
   4565     rv = PK11_DigestFinal(ss->ssl3.hs.md5, hashes->u.raw, &hashes->len,
   4566 			  sizeof(hashes->u.raw));
   4567     if (rv != SECSuccess) {
   4568 	ssl_MapLowLevelError(SSL_ERROR_SHA_DIGEST_FAILURE);
   4569 	rv = SECFailure;
   4570 	goto loser;
   4571     }
   4572     hashes->hashAlg = SEC_OID_SHA1;
   4573 
   4574 loser:
   4575     PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   4576     ss->ssl3.hs.md5 = NULL;
   4577     return rv;
   4578 }
   4579 
   4580 /*
   4581  * SSL 2 based implementations pass in the initial outbound buffer
   4582  * so that the handshake hash can contain the included information.
   4583  *
   4584  * Called from ssl2_BeginClientHandshake() in sslcon.c
   4585  */
   4586 SECStatus
   4587 ssl3_StartHandshakeHash(sslSocket *ss, unsigned char * buf, int length)
   4588 {
   4589     SECStatus rv;
   4590 
   4591     ssl_GetSSL3HandshakeLock(ss);  /**************************************/
   4592 
   4593     rv = ssl3_InitState(ss);
   4594     if (rv != SECSuccess) {
   4595 	goto done;		/* ssl3_InitState has set the error code. */
   4596     }
   4597     rv = ssl3_RestartHandshakeHashes(ss);
   4598     if (rv != SECSuccess) {
   4599 	goto done;
   4600     }
   4601 
   4602     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
   4603     PORT_Memcpy(
   4604 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - SSL_CHALLENGE_BYTES],
   4605 	&ss->sec.ci.clientChallenge,
   4606 	SSL_CHALLENGE_BYTES);
   4607 
   4608     rv = ssl3_UpdateHandshakeHashes(ss, buf, length);
   4609     /* if it failed, ssl3_UpdateHandshakeHashes has set the error code. */
   4610 
   4611 done:
   4612     ssl_ReleaseSSL3HandshakeLock(ss);  /**************************************/
   4613     return rv;
   4614 }
   4615 
   4616 /**************************************************************************
   4617  * end of Handshake Hash functions.
   4618  * Begin Send and Handle functions for handshakes.
   4619  **************************************************************************/
   4620 
   4621 /* Called from ssl3_HandleHelloRequest(),
   4622  *             ssl3_RedoHandshake()
   4623  *             ssl2_BeginClientHandshake (when resuming ssl3 session)
   4624  *             dtls_HandleHelloVerifyRequest(with resending=PR_TRUE)
   4625  */
   4626 SECStatus
   4627 ssl3_SendClientHello(sslSocket *ss, PRBool resending)
   4628 {
   4629     sslSessionID *   sid;
   4630     ssl3CipherSpec * cwSpec;
   4631     SECStatus        rv;
   4632     int              i;
   4633     int              length;
   4634     int              num_suites;
   4635     int              actual_count = 0;
   4636     PRBool           isTLS = PR_FALSE;
   4637     PRBool           requestingResume = PR_FALSE;
   4638     PRInt32          total_exten_len = 0;
   4639     unsigned         numCompressionMethods;
   4640     PRInt32          flags;
   4641 
   4642     SSL_TRC(3, ("%d: SSL3[%d]: send client_hello handshake", SSL_GETPID(),
   4643 		ss->fd));
   4644 
   4645     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   4646     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   4647 
   4648     rv = ssl3_InitState(ss);
   4649     if (rv != SECSuccess) {
   4650 	return rv;		/* ssl3_InitState has set the error code. */
   4651     }
   4652     ss->ssl3.hs.sendingSCSV = PR_FALSE; /* Must be reset every handshake */
   4653     PORT_Assert(IS_DTLS(ss) || !resending);
   4654 
   4655     /* We might be starting a session renegotiation in which case we should
   4656      * clear previous state.
   4657      */
   4658     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   4659 
   4660     rv = ssl3_RestartHandshakeHashes(ss);
   4661     if (rv != SECSuccess) {
   4662 	return rv;
   4663     }
   4664 
   4665     /*
   4666      * During a renegotiation, ss->clientHelloVersion will be used again to
   4667      * work around a Windows SChannel bug. Ensure that it is still enabled.
   4668      */
   4669     if (ss->firstHsDone) {
   4670 	if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
   4671 	    PORT_SetError(SSL_ERROR_SSL_DISABLED);
   4672 	    return SECFailure;
   4673 	}
   4674 
   4675 	if (ss->clientHelloVersion < ss->vrange.min ||
   4676 	    ss->clientHelloVersion > ss->vrange.max) {
   4677 	    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
   4678 	    return SECFailure;
   4679 	}
   4680     }
   4681 
   4682     /* We ignore ss->sec.ci.sid here, and use ssl_Lookup because Lookup
   4683      * handles expired entries and other details.
   4684      * XXX If we've been called from ssl2_BeginClientHandshake, then
   4685      * this lookup is duplicative and wasteful.
   4686      */
   4687     sid = (ss->opt.noCache) ? NULL
   4688 	    : ssl_LookupSID(&ss->sec.ci.peer, ss->sec.ci.port, ss->peerID, ss->url);
   4689 
   4690     /* We can't resume based on a different token. If the sid exists,
   4691      * make sure the token that holds the master secret still exists ...
   4692      * If we previously did client-auth, make sure that the token that holds
   4693      * the private key still exists, is logged in, hasn't been removed, etc.
   4694      */
   4695     if (sid) {
   4696 	PRBool sidOK = PR_TRUE;
   4697 	if (sid->u.ssl3.keys.msIsWrapped) {
   4698 	    /* Session key was wrapped, which means it was using PKCS11, */
   4699 	    PK11SlotInfo *slot = NULL;
   4700 	    if (sid->u.ssl3.masterValid && !ss->opt.bypassPKCS11) {
   4701 		slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
   4702 					 sid->u.ssl3.masterSlotID);
   4703 	    }
   4704 	    if (slot == NULL) {
   4705 	       sidOK = PR_FALSE;
   4706 	    } else {
   4707 		PK11SymKey *wrapKey = NULL;
   4708 		if (!PK11_IsPresent(slot) ||
   4709 		    ((wrapKey = PK11_GetWrapKey(slot,
   4710 						sid->u.ssl3.masterWrapIndex,
   4711 						sid->u.ssl3.masterWrapMech,
   4712 						sid->u.ssl3.masterWrapSeries,
   4713 						ss->pkcs11PinArg)) == NULL) ) {
   4714 		    sidOK = PR_FALSE;
   4715 		}
   4716 		if (wrapKey) PK11_FreeSymKey(wrapKey);
   4717 		PK11_FreeSlot(slot);
   4718 		slot = NULL;
   4719 	    }
   4720 	}
   4721 	/* If we previously did client-auth, make sure that the token that
   4722 	** holds the private key still exists, is logged in, hasn't been
   4723 	** removed, etc.
   4724 	*/
   4725 	if (sidOK && !ssl3_ClientAuthTokenPresent(sid)) {
   4726 	    sidOK = PR_FALSE;
   4727 	}
   4728 
   4729 	/* TLS 1.0 (RFC 2246) Appendix E says:
   4730 	 *   Whenever a client already knows the highest protocol known to
   4731 	 *   a server (for example, when resuming a session), it should
   4732 	 *   initiate the connection in that native protocol.
   4733 	 * So we pass sid->version to ssl3_NegotiateVersion() here, except
   4734 	 * when renegotiating.
   4735 	 *
   4736 	 * Windows SChannel compares the client_version inside the RSA
   4737 	 * EncryptedPreMasterSecret of a renegotiation with the
   4738 	 * client_version of the initial ClientHello rather than the
   4739 	 * ClientHello in the renegotiation. To work around this bug, we
   4740 	 * continue to use the client_version used in the initial
   4741 	 * ClientHello when renegotiating.
   4742 	 */
   4743 	if (sidOK) {
   4744 	    if (ss->firstHsDone) {
   4745 		/*
   4746 		 * The client_version of the initial ClientHello is still
   4747 		 * available in ss->clientHelloVersion. Ensure that
   4748 		 * sid->version is bounded within
   4749 		 * [ss->vrange.min, ss->clientHelloVersion], otherwise we
   4750 		 * can't use sid.
   4751 		 */
   4752 		if (sid->version >= ss->vrange.min &&
   4753 		    sid->version <= ss->clientHelloVersion) {
   4754 		    ss->version = ss->clientHelloVersion;
   4755 		} else {
   4756 		    sidOK = PR_FALSE;
   4757 		}
   4758 	    } else {
   4759 		if (ssl3_NegotiateVersion(ss, sid->version,
   4760 					  PR_FALSE) != SECSuccess) {
   4761 		    sidOK = PR_FALSE;
   4762 		}
   4763 	    }
   4764 	}
   4765 
   4766 	if (!sidOK) {
   4767 	    SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_not_ok );
   4768 	    if (ss->sec.uncache)
   4769                 (*ss->sec.uncache)(sid);
   4770 	    ssl_FreeSID(sid);
   4771 	    sid = NULL;
   4772 	}
   4773     }
   4774 
   4775     if (sid) {
   4776 	requestingResume = PR_TRUE;
   4777 	SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_hits );
   4778 
   4779 	/* Are we attempting a stateless session resume? */
   4780 	if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
   4781 	    sid->u.ssl3.sessionTicket.ticket.data)
   4782 	    SSL_AtomicIncrementLong(& ssl3stats.sch_sid_stateless_resumes );
   4783 
   4784 	PRINT_BUF(4, (ss, "client, found session-id:", sid->u.ssl3.sessionID,
   4785 		      sid->u.ssl3.sessionIDLength));
   4786 
   4787 	ss->ssl3.policy = sid->u.ssl3.policy;
   4788     } else {
   4789 	SSL_AtomicIncrementLong(& ssl3stats.sch_sid_cache_misses );
   4790 
   4791 	/*
   4792 	 * Windows SChannel compares the client_version inside the RSA
   4793 	 * EncryptedPreMasterSecret of a renegotiation with the
   4794 	 * client_version of the initial ClientHello rather than the
   4795 	 * ClientHello in the renegotiation. To work around this bug, we
   4796 	 * continue to use the client_version used in the initial
   4797 	 * ClientHello when renegotiating.
   4798 	 */
   4799 	if (ss->firstHsDone) {
   4800 	    ss->version = ss->clientHelloVersion;
   4801 	} else {
   4802 	    rv = ssl3_NegotiateVersion(ss, SSL_LIBRARY_VERSION_MAX_SUPPORTED,
   4803 				       PR_TRUE);
   4804 	    if (rv != SECSuccess)
   4805 		return rv;	/* error code was set */
   4806 	}
   4807 
   4808 	sid = ssl3_NewSessionID(ss, PR_FALSE);
   4809 	if (!sid) {
   4810 	    return SECFailure;	/* memory error is set */
   4811         }
   4812     }
   4813 
   4814     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
   4815     ssl_GetSpecWriteLock(ss);
   4816     cwSpec = ss->ssl3.cwSpec;
   4817     if (cwSpec->mac_def->mac == mac_null) {
   4818 	/* SSL records are not being MACed. */
   4819 	cwSpec->version = ss->version;
   4820     }
   4821     ssl_ReleaseSpecWriteLock(ss);
   4822 
   4823     if (ss->sec.ci.sid != NULL) {
   4824 	ssl_FreeSID(ss->sec.ci.sid);	/* decrement ref count, free if zero */
   4825     }
   4826     ss->sec.ci.sid = sid;
   4827 
   4828     ss->sec.send = ssl3_SendApplicationData;
   4829 
   4830     /* shouldn't get here if SSL3 is disabled, but ... */
   4831     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
   4832 	PR_NOT_REACHED("No versions of SSL 3.0 or later are enabled");
   4833 	PORT_SetError(SSL_ERROR_SSL_DISABLED);
   4834     	return SECFailure;
   4835     }
   4836 
   4837     /* how many suites does our PKCS11 support (regardless of policy)? */
   4838     num_suites = ssl3_config_match_init(ss);
   4839     if (!num_suites)
   4840     	return SECFailure;	/* ssl3_config_match_init has set error code. */
   4841 
   4842     /* HACK for SCSV in SSL 3.0.  On initial handshake, prepend SCSV,
   4843      * only if TLS is disabled.
   4844      */
   4845     if (!ss->firstHsDone && !isTLS) {
   4846 	/* Must set this before calling Hello Extension Senders,
   4847 	 * to suppress sending of empty RI extension.
   4848 	 */
   4849 	ss->ssl3.hs.sendingSCSV = PR_TRUE;
   4850     }
   4851 
   4852     if (isTLS || (ss->firstHsDone && ss->peerRequestedProtection)) {
   4853 	PRUint32 maxBytes = 65535; /* 2^16 - 1 */
   4854 	PRInt32  extLen;
   4855 
   4856 	extLen = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes, NULL);
   4857 	if (extLen < 0) {
   4858 	    return SECFailure;
   4859 	}
   4860 	maxBytes        -= extLen;
   4861 	total_exten_len += extLen;
   4862 
   4863 	if (total_exten_len > 0)
   4864 	    total_exten_len += 2;
   4865     }
   4866 
   4867 #if defined(NSS_ENABLE_ECC)
   4868     if (!total_exten_len || !isTLS) {
   4869 	/* not sending the elliptic_curves and ec_point_formats extensions */
   4870     	ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
   4871     }
   4872 #endif
   4873 
   4874     if (IS_DTLS(ss)) {
   4875 	ssl3_DisableNonDTLSSuites(ss);
   4876     }
   4877 
   4878     /* how many suites are permitted by policy and user preference? */
   4879     num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
   4880     if (!num_suites)
   4881     	return SECFailure;	/* count_cipher_suites has set error code. */
   4882     if (ss->ssl3.hs.sendingSCSV) {
   4883 	++num_suites;   /* make room for SCSV */
   4884     }
   4885 
   4886     /* count compression methods */
   4887     numCompressionMethods = 0;
   4888     for (i = 0; i < compressionMethodsCount; i++) {
   4889 	if (compressionEnabled(ss, compressions[i]))
   4890 	    numCompressionMethods++;
   4891     }
   4892 
   4893     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH +
   4894 	1 + ((sid == NULL) ? 0 : sid->u.ssl3.sessionIDLength) +
   4895 	2 + num_suites*sizeof(ssl3CipherSuite) +
   4896 	1 + numCompressionMethods + total_exten_len;
   4897     if (IS_DTLS(ss)) {
   4898 	length += 1 + ss->ssl3.hs.cookieLen;
   4899     }
   4900 
   4901     rv = ssl3_AppendHandshakeHeader(ss, client_hello, length);
   4902     if (rv != SECSuccess) {
   4903 	return rv;	/* err set by ssl3_AppendHandshake* */
   4904     }
   4905 
   4906     if (ss->firstHsDone) {
   4907 	/* The client hello version must stay unchanged to work around
   4908 	 * the Windows SChannel bug described above. */
   4909 	PORT_Assert(ss->version == ss->clientHelloVersion);
   4910     }
   4911     ss->clientHelloVersion = ss->version;
   4912     if (IS_DTLS(ss)) {
   4913 	PRUint16 version;
   4914 
   4915 	version = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
   4916 	rv = ssl3_AppendHandshakeNumber(ss, version, 2);
   4917     } else {
   4918 	rv = ssl3_AppendHandshakeNumber(ss, ss->clientHelloVersion, 2);
   4919     }
   4920     if (rv != SECSuccess) {
   4921 	return rv;	/* err set by ssl3_AppendHandshake* */
   4922     }
   4923 
   4924     if (!resending) { /* Don't re-generate if we are in DTLS re-sending mode */
   4925 	rv = ssl3_GetNewRandom(&ss->ssl3.hs.client_random);
   4926 	if (rv != SECSuccess) {
   4927 	    return rv;	/* err set by GetNewRandom. */
   4928 	}
   4929     }
   4930     rv = ssl3_AppendHandshake(ss, &ss->ssl3.hs.client_random,
   4931                               SSL3_RANDOM_LENGTH);
   4932     if (rv != SECSuccess) {
   4933 	return rv;	/* err set by ssl3_AppendHandshake* */
   4934     }
   4935 
   4936     if (sid)
   4937 	rv = ssl3_AppendHandshakeVariable(
   4938 	    ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
   4939     else
   4940 	rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
   4941     if (rv != SECSuccess) {
   4942 	return rv;	/* err set by ssl3_AppendHandshake* */
   4943     }
   4944 
   4945     if (IS_DTLS(ss)) {
   4946 	rv = ssl3_AppendHandshakeVariable(
   4947 	    ss, ss->ssl3.hs.cookie, ss->ssl3.hs.cookieLen, 1);
   4948 	if (rv != SECSuccess) {
   4949 	    return rv;	/* err set by ssl3_AppendHandshake* */
   4950 	}
   4951     }
   4952 
   4953     rv = ssl3_AppendHandshakeNumber(ss, num_suites*sizeof(ssl3CipherSuite), 2);
   4954     if (rv != SECSuccess) {
   4955 	return rv;	/* err set by ssl3_AppendHandshake* */
   4956     }
   4957 
   4958     if (ss->ssl3.hs.sendingSCSV) {
   4959 	/* Add the actual SCSV */
   4960 	rv = ssl3_AppendHandshakeNumber(ss, TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
   4961 					sizeof(ssl3CipherSuite));
   4962 	if (rv != SECSuccess) {
   4963 	    return rv;	/* err set by ssl3_AppendHandshake* */
   4964 	}
   4965 	actual_count++;
   4966     }
   4967     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
   4968 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
   4969 	if (config_match(suite, ss->ssl3.policy, PR_TRUE)) {
   4970 	    actual_count++;
   4971 	    if (actual_count > num_suites) {
   4972 		/* set error card removal/insertion error */
   4973 		PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   4974 		return SECFailure;
   4975 	    }
   4976 	    rv = ssl3_AppendHandshakeNumber(ss, suite->cipher_suite,
   4977 					    sizeof(ssl3CipherSuite));
   4978 	    if (rv != SECSuccess) {
   4979 		return rv;	/* err set by ssl3_AppendHandshake* */
   4980 	    }
   4981 	}
   4982     }
   4983 
   4984     /* if cards were removed or inserted between count_cipher_suites and
   4985      * generating our list, detect the error here rather than send it off to
   4986      * the server.. */
   4987     if (actual_count != num_suites) {
   4988 	/* Card removal/insertion error */
   4989 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   4990 	return SECFailure;
   4991     }
   4992 
   4993     rv = ssl3_AppendHandshakeNumber(ss, numCompressionMethods, 1);
   4994     if (rv != SECSuccess) {
   4995 	return rv;	/* err set by ssl3_AppendHandshake* */
   4996     }
   4997     for (i = 0; i < compressionMethodsCount; i++) {
   4998 	if (!compressionEnabled(ss, compressions[i]))
   4999 	    continue;
   5000 	rv = ssl3_AppendHandshakeNumber(ss, compressions[i], 1);
   5001 	if (rv != SECSuccess) {
   5002 	    return rv;	/* err set by ssl3_AppendHandshake* */
   5003 	}
   5004     }
   5005 
   5006     if (total_exten_len) {
   5007 	PRUint32 maxBytes = total_exten_len - 2;
   5008 	PRInt32  extLen;
   5009 
   5010 	rv = ssl3_AppendHandshakeNumber(ss, maxBytes, 2);
   5011 	if (rv != SECSuccess) {
   5012 	    return rv;	/* err set by AppendHandshake. */
   5013 	}
   5014 
   5015 	extLen = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, maxBytes, NULL);
   5016 	if (extLen < 0) {
   5017 	    return SECFailure;
   5018 	}
   5019 	maxBytes -= extLen;
   5020 	PORT_Assert(!maxBytes);
   5021     }
   5022     if (ss->ssl3.hs.sendingSCSV) {
   5023 	/* Since we sent the SCSV, pretend we sent empty RI extension. */
   5024 	TLSExtensionData *xtnData = &ss->xtnData;
   5025 	xtnData->advertised[xtnData->numAdvertised++] =
   5026 	    ssl_renegotiation_info_xtn;
   5027     }
   5028 
   5029     flags = 0;
   5030     if (!ss->firstHsDone && !requestingResume && !IS_DTLS(ss)) {
   5031 	flags |= ssl_SEND_FLAG_CAP_RECORD_VERSION;
   5032     }
   5033     rv = ssl3_FlushHandshake(ss, flags);
   5034     if (rv != SECSuccess) {
   5035 	return rv;	/* error code set by ssl3_FlushHandshake */
   5036     }
   5037 
   5038     ss->ssl3.hs.ws = wait_server_hello;
   5039     return rv;
   5040 }
   5041 
   5042 
   5043 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   5044  * ssl3 Hello Request.
   5045  * Caller must hold Handshake and RecvBuf locks.
   5046  */
   5047 static SECStatus
   5048 ssl3_HandleHelloRequest(sslSocket *ss)
   5049 {
   5050     sslSessionID *sid = ss->sec.ci.sid;
   5051     SECStatus     rv;
   5052 
   5053     SSL_TRC(3, ("%d: SSL3[%d]: handle hello_request handshake",
   5054 		SSL_GETPID(), ss->fd));
   5055 
   5056     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   5057     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   5058 
   5059     if (ss->ssl3.hs.ws == wait_server_hello)
   5060 	return SECSuccess;
   5061     if (ss->ssl3.hs.ws != idle_handshake || ss->sec.isServer) {
   5062 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   5063 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
   5064 	return SECFailure;
   5065     }
   5066     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
   5067 	ssl_GetXmitBufLock(ss);
   5068 	rv = SSL3_SendAlert(ss, alert_warning, no_renegotiation);
   5069 	ssl_ReleaseXmitBufLock(ss);
   5070 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
   5071 	return SECFailure;
   5072     }
   5073 
   5074     if (sid) {
   5075 	if (ss->sec.uncache)
   5076             ss->sec.uncache(sid);
   5077 	ssl_FreeSID(sid);
   5078 	ss->sec.ci.sid = NULL;
   5079     }
   5080 
   5081     if (IS_DTLS(ss)) {
   5082 	dtls_RehandshakeCleanup(ss);
   5083     }
   5084 
   5085     ssl_GetXmitBufLock(ss);
   5086     rv = ssl3_SendClientHello(ss, PR_FALSE);
   5087     ssl_ReleaseXmitBufLock(ss);
   5088 
   5089     return rv;
   5090 }
   5091 
   5092 #define UNKNOWN_WRAP_MECHANISM 0x7fffffff
   5093 
   5094 static const CK_MECHANISM_TYPE wrapMechanismList[SSL_NUM_WRAP_MECHS] = {
   5095     CKM_DES3_ECB,
   5096     CKM_CAST5_ECB,
   5097     CKM_DES_ECB,
   5098     CKM_KEY_WRAP_LYNKS,
   5099     CKM_IDEA_ECB,
   5100     CKM_CAST3_ECB,
   5101     CKM_CAST_ECB,
   5102     CKM_RC5_ECB,
   5103     CKM_RC2_ECB,
   5104     CKM_CDMF_ECB,
   5105     CKM_SKIPJACK_WRAP,
   5106     CKM_SKIPJACK_CBC64,
   5107     CKM_AES_ECB,
   5108     CKM_CAMELLIA_ECB,
   5109     CKM_SEED_ECB,
   5110     UNKNOWN_WRAP_MECHANISM
   5111 };
   5112 
   5113 static int
   5114 ssl_FindIndexByWrapMechanism(CK_MECHANISM_TYPE mech)
   5115 {
   5116     const CK_MECHANISM_TYPE *pMech = wrapMechanismList;
   5117 
   5118     while (mech != *pMech && *pMech != UNKNOWN_WRAP_MECHANISM) {
   5119     	++pMech;
   5120     }
   5121     return (*pMech == UNKNOWN_WRAP_MECHANISM) ? -1
   5122                                               : (pMech - wrapMechanismList);
   5123 }
   5124 
   5125 static PK11SymKey *
   5126 ssl_UnwrapSymWrappingKey(
   5127 	SSLWrappedSymWrappingKey *pWswk,
   5128 	SECKEYPrivateKey *        svrPrivKey,
   5129 	SSL3KEAType               exchKeyType,
   5130 	CK_MECHANISM_TYPE         masterWrapMech,
   5131 	void *                    pwArg)
   5132 {
   5133     PK11SymKey *             unwrappedWrappingKey  = NULL;
   5134     SECItem                  wrappedKey;
   5135 #ifdef NSS_ENABLE_ECC
   5136     PK11SymKey *             Ks;
   5137     SECKEYPublicKey          pubWrapKey;
   5138     ECCWrappedKeyInfo        *ecWrapped;
   5139 #endif /* NSS_ENABLE_ECC */
   5140 
   5141     /* found the wrapping key on disk. */
   5142     PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
   5143     PORT_Assert(pWswk->exchKeyType      == exchKeyType);
   5144     if (pWswk->symWrapMechanism != masterWrapMech ||
   5145 	pWswk->exchKeyType      != exchKeyType) {
   5146 	goto loser;
   5147     }
   5148     wrappedKey.type = siBuffer;
   5149     wrappedKey.data = pWswk->wrappedSymmetricWrappingkey;
   5150     wrappedKey.len  = pWswk->wrappedSymKeyLen;
   5151     PORT_Assert(wrappedKey.len <= sizeof pWswk->wrappedSymmetricWrappingkey);
   5152 
   5153     switch (exchKeyType) {
   5154 
   5155     case kt_rsa:
   5156 	unwrappedWrappingKey =
   5157 	    PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
   5158 				 masterWrapMech, CKA_UNWRAP, 0);
   5159 	break;
   5160 
   5161 #ifdef NSS_ENABLE_ECC
   5162     case kt_ecdh:
   5163         /*
   5164          * For kt_ecdh, we first create an EC public key based on
   5165          * data stored with the wrappedSymmetricWrappingkey. Next,
   5166          * we do an ECDH computation involving this public key and
   5167          * the SSL server's (long-term) EC private key. The resulting
   5168          * shared secret is treated the same way as Fortezza's Ks, i.e.,
   5169          * it is used to recover the symmetric wrapping key.
   5170          *
   5171          * The data in wrappedSymmetricWrappingkey is laid out as defined
   5172          * in the ECCWrappedKeyInfo structure.
   5173          */
   5174         ecWrapped = (ECCWrappedKeyInfo *) pWswk->wrappedSymmetricWrappingkey;
   5175 
   5176         PORT_Assert(ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
   5177             ecWrapped->wrappedKeyLen <= MAX_EC_WRAPPED_KEY_BUFLEN);
   5178 
   5179         if (ecWrapped->encodedParamLen + ecWrapped->pubValueLen +
   5180             ecWrapped->wrappedKeyLen > MAX_EC_WRAPPED_KEY_BUFLEN) {
   5181             PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   5182             goto loser;
   5183         }
   5184 
   5185         pubWrapKey.keyType = ecKey;
   5186         pubWrapKey.u.ec.size = ecWrapped->size;
   5187         pubWrapKey.u.ec.DEREncodedParams.len = ecWrapped->encodedParamLen;
   5188         pubWrapKey.u.ec.DEREncodedParams.data = ecWrapped->var;
   5189         pubWrapKey.u.ec.publicValue.len = ecWrapped->pubValueLen;
   5190         pubWrapKey.u.ec.publicValue.data = ecWrapped->var +
   5191             ecWrapped->encodedParamLen;
   5192 
   5193         wrappedKey.len  = ecWrapped->wrappedKeyLen;
   5194         wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
   5195             ecWrapped->pubValueLen;
   5196 
   5197         /* Derive Ks using ECDH */
   5198         Ks = PK11_PubDeriveWithKDF(svrPrivKey, &pubWrapKey, PR_FALSE, NULL,
   5199 				   NULL, CKM_ECDH1_DERIVE, masterWrapMech,
   5200 				   CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
   5201         if (Ks == NULL) {
   5202             goto loser;
   5203         }
   5204 
   5205         /*  Use Ks to unwrap the wrapping key */
   5206         unwrappedWrappingKey = PK11_UnwrapSymKey(Ks, masterWrapMech, NULL,
   5207 						 &wrappedKey, masterWrapMech,
   5208 						 CKA_UNWRAP, 0);
   5209         PK11_FreeSymKey(Ks);
   5210 
   5211         break;
   5212 #endif
   5213 
   5214     default:
   5215 	/* Assert? */
   5216 	SET_ERROR_CODE
   5217 	goto loser;
   5218     }
   5219 loser:
   5220     return unwrappedWrappingKey;
   5221 }
   5222 
   5223 /* Each process sharing the server session ID cache has its own array of
   5224  * SymKey pointers for the symmetric wrapping keys that are used to wrap
   5225  * the master secrets.  There is one key for each KEA type.  These Symkeys
   5226  * correspond to the wrapped SymKeys kept in the server session cache.
   5227  */
   5228 
   5229 typedef struct {
   5230     PK11SymKey *      symWrapKey[kt_kea_size];
   5231 } ssl3SymWrapKey;
   5232 
   5233 static PZLock *          symWrapKeysLock = NULL;
   5234 static ssl3SymWrapKey    symWrapKeys[SSL_NUM_WRAP_MECHS];
   5235 
   5236 SECStatus ssl_FreeSymWrapKeysLock(void)
   5237 {
   5238     if (symWrapKeysLock) {
   5239         PZ_DestroyLock(symWrapKeysLock);
   5240         symWrapKeysLock = NULL;
   5241         return SECSuccess;
   5242     }
   5243     PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
   5244     return SECFailure;
   5245 }
   5246 
   5247 SECStatus
   5248 SSL3_ShutdownServerCache(void)
   5249 {
   5250     int             i, j;
   5251 
   5252     if (!symWrapKeysLock)
   5253     	return SECSuccess;	/* lock was never initialized */
   5254     PZ_Lock(symWrapKeysLock);
   5255     /* get rid of all symWrapKeys */
   5256     for (i = 0; i < SSL_NUM_WRAP_MECHS; ++i) {
   5257     	for (j = 0; j < kt_kea_size; ++j) {
   5258 	    PK11SymKey **   pSymWrapKey;
   5259 	    pSymWrapKey = &symWrapKeys[i].symWrapKey[j];
   5260 	    if (*pSymWrapKey) {
   5261 		PK11_FreeSymKey(*pSymWrapKey);
   5262 	    	*pSymWrapKey = NULL;
   5263 	    }
   5264 	}
   5265     }
   5266 
   5267     PZ_Unlock(symWrapKeysLock);
   5268     ssl_FreeSessionCacheLocks();
   5269     return SECSuccess;
   5270 }
   5271 
   5272 SECStatus ssl_InitSymWrapKeysLock(void)
   5273 {
   5274     symWrapKeysLock = PZ_NewLock(nssILockOther);
   5275     return symWrapKeysLock ? SECSuccess : SECFailure;
   5276 }
   5277 
   5278 /* Try to get wrapping key for mechanism from in-memory array.
   5279  * If that fails, look for one on disk.
   5280  * If that fails, generate a new one, put the new one on disk,
   5281  * Put the new key in the in-memory array.
   5282  */
   5283 static PK11SymKey *
   5284 getWrappingKey( sslSocket *       ss,
   5285 		PK11SlotInfo *    masterSecretSlot,
   5286 		SSL3KEAType       exchKeyType,
   5287                 CK_MECHANISM_TYPE masterWrapMech,
   5288 	        void *            pwArg)
   5289 {
   5290     SECKEYPrivateKey *       svrPrivKey;
   5291     SECKEYPublicKey *        svrPubKey             = NULL;
   5292     PK11SymKey *             unwrappedWrappingKey  = NULL;
   5293     PK11SymKey **            pSymWrapKey;
   5294     CK_MECHANISM_TYPE        asymWrapMechanism = CKM_INVALID_MECHANISM;
   5295     int                      length;
   5296     int                      symWrapMechIndex;
   5297     SECStatus                rv;
   5298     SECItem                  wrappedKey;
   5299     SSLWrappedSymWrappingKey wswk;
   5300 #ifdef NSS_ENABLE_ECC
   5301     PK11SymKey *      Ks = NULL;
   5302     SECKEYPublicKey   *pubWrapKey = NULL;
   5303     SECKEYPrivateKey  *privWrapKey = NULL;
   5304     ECCWrappedKeyInfo *ecWrapped;
   5305 #endif /* NSS_ENABLE_ECC */
   5306 
   5307     svrPrivKey  = ss->serverCerts[exchKeyType].SERVERKEY;
   5308     PORT_Assert(svrPrivKey != NULL);
   5309     if (!svrPrivKey) {
   5310     	return NULL;	/* why are we here?!? */
   5311     }
   5312 
   5313     symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
   5314     PORT_Assert(symWrapMechIndex >= 0);
   5315     if (symWrapMechIndex < 0)
   5316     	return NULL;	/* invalid masterWrapMech. */
   5317 
   5318     pSymWrapKey = &symWrapKeys[symWrapMechIndex].symWrapKey[exchKeyType];
   5319 
   5320     ssl_InitSessionCacheLocks(PR_TRUE);
   5321 
   5322     PZ_Lock(symWrapKeysLock);
   5323 
   5324     unwrappedWrappingKey = *pSymWrapKey;
   5325     if (unwrappedWrappingKey != NULL) {
   5326 	if (PK11_VerifyKeyOK(unwrappedWrappingKey)) {
   5327 	    unwrappedWrappingKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
   5328 	    goto done;
   5329 	}
   5330 	/* slot series has changed, so this key is no good any more. */
   5331 	PK11_FreeSymKey(unwrappedWrappingKey);
   5332 	*pSymWrapKey = unwrappedWrappingKey = NULL;
   5333     }
   5334 
   5335     /* Try to get wrapped SymWrapping key out of the (disk) cache. */
   5336     /* Following call fills in wswk on success. */
   5337     if (ssl_GetWrappingKey(symWrapMechIndex, exchKeyType, &wswk)) {
   5338     	/* found the wrapped sym wrapping key on disk. */
   5339 	unwrappedWrappingKey =
   5340 	    ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
   5341                                      masterWrapMech, pwArg);
   5342 	if (unwrappedWrappingKey) {
   5343 	    goto install;
   5344 	}
   5345     }
   5346 
   5347     if (!masterSecretSlot) 	/* caller doesn't want to create a new one. */
   5348     	goto loser;
   5349 
   5350     length = PK11_GetBestKeyLength(masterSecretSlot, masterWrapMech);
   5351     /* Zero length means fixed key length algorithm, or error.
   5352      * It's ambiguous.
   5353      */
   5354     unwrappedWrappingKey = PK11_KeyGen(masterSecretSlot, masterWrapMech, NULL,
   5355                                        length, pwArg);
   5356     if (!unwrappedWrappingKey) {
   5357     	goto loser;
   5358     }
   5359 
   5360     /* Prepare the buffer to receive the wrappedWrappingKey,
   5361      * the symmetric wrapping key wrapped using the server's pub key.
   5362      */
   5363     PORT_Memset(&wswk, 0, sizeof wswk);	/* eliminate UMRs. */
   5364 
   5365     if (ss->serverCerts[exchKeyType].serverKeyPair) {
   5366 	svrPubKey = ss->serverCerts[exchKeyType].serverKeyPair->pubKey;
   5367     }
   5368     if (svrPubKey == NULL) {
   5369 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   5370 	goto loser;
   5371     }
   5372     wrappedKey.type = siBuffer;
   5373     wrappedKey.len  = SECKEY_PublicKeyStrength(svrPubKey);
   5374     wrappedKey.data = wswk.wrappedSymmetricWrappingkey;
   5375 
   5376     PORT_Assert(wrappedKey.len <= sizeof wswk.wrappedSymmetricWrappingkey);
   5377     if (wrappedKey.len > sizeof wswk.wrappedSymmetricWrappingkey)
   5378     	goto loser;
   5379 
   5380     /* wrap symmetric wrapping key in server's public key. */
   5381     switch (exchKeyType) {
   5382     case kt_rsa:
   5383 	asymWrapMechanism = CKM_RSA_PKCS;
   5384 	rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
   5385 	                        unwrappedWrappingKey, &wrappedKey);
   5386 	break;
   5387 
   5388 #ifdef NSS_ENABLE_ECC
   5389     case kt_ecdh:
   5390 	/*
   5391 	 * We generate an ephemeral EC key pair. Perform an ECDH
   5392 	 * computation involving this ephemeral EC public key and
   5393 	 * the SSL server's (long-term) EC private key. The resulting
   5394 	 * shared secret is treated in the same way as Fortezza's Ks,
   5395 	 * i.e., it is used to wrap the wrapping key. To facilitate
   5396 	 * unwrapping in ssl_UnwrapWrappingKey, we also store all
   5397 	 * relevant info about the ephemeral EC public key in
   5398 	 * wswk.wrappedSymmetricWrappingkey and lay it out as
   5399 	 * described in the ECCWrappedKeyInfo structure.
   5400 	 */
   5401 	PORT_Assert(svrPubKey->keyType == ecKey);
   5402 	if (svrPubKey->keyType != ecKey) {
   5403 	    /* something is wrong in sslsecur.c if this isn't an ecKey */
   5404 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   5405 	    rv = SECFailure;
   5406 	    goto ec_cleanup;
   5407 	}
   5408 
   5409 	privWrapKey = SECKEY_CreateECPrivateKey(
   5410 	    &svrPubKey->u.ec.DEREncodedParams, &pubWrapKey, NULL);
   5411 	if ((privWrapKey == NULL) || (pubWrapKey == NULL)) {
   5412 	    rv = SECFailure;
   5413 	    goto ec_cleanup;
   5414 	}
   5415 
   5416 	/* Set the key size in bits */
   5417 	if (pubWrapKey->u.ec.size == 0) {
   5418 	    pubWrapKey->u.ec.size = SECKEY_PublicKeyStrengthInBits(svrPubKey);
   5419 	}
   5420 
   5421 	PORT_Assert(pubWrapKey->u.ec.DEREncodedParams.len +
   5422 	    pubWrapKey->u.ec.publicValue.len < MAX_EC_WRAPPED_KEY_BUFLEN);
   5423 	if (pubWrapKey->u.ec.DEREncodedParams.len +
   5424 	    pubWrapKey->u.ec.publicValue.len >= MAX_EC_WRAPPED_KEY_BUFLEN) {
   5425 	    PORT_SetError(SEC_ERROR_INVALID_KEY);
   5426 	    rv = SECFailure;
   5427 	    goto ec_cleanup;
   5428 	}
   5429 
   5430 	/* Derive Ks using ECDH */
   5431 	Ks = PK11_PubDeriveWithKDF(svrPrivKey, pubWrapKey, PR_FALSE, NULL,
   5432 				   NULL, CKM_ECDH1_DERIVE, masterWrapMech,
   5433 				   CKA_DERIVE, 0, CKD_NULL, NULL, NULL);
   5434 	if (Ks == NULL) {
   5435 	    rv = SECFailure;
   5436 	    goto ec_cleanup;
   5437 	}
   5438 
   5439 	ecWrapped = (ECCWrappedKeyInfo *) (wswk.wrappedSymmetricWrappingkey);
   5440 	ecWrapped->size = pubWrapKey->u.ec.size;
   5441 	ecWrapped->encodedParamLen = pubWrapKey->u.ec.DEREncodedParams.len;
   5442 	PORT_Memcpy(ecWrapped->var, pubWrapKey->u.ec.DEREncodedParams.data,
   5443 	    pubWrapKey->u.ec.DEREncodedParams.len);
   5444 
   5445 	ecWrapped->pubValueLen = pubWrapKey->u.ec.publicValue.len;
   5446 	PORT_Memcpy(ecWrapped->var + ecWrapped->encodedParamLen,
   5447 		    pubWrapKey->u.ec.publicValue.data,
   5448 		    pubWrapKey->u.ec.publicValue.len);
   5449 
   5450 	wrappedKey.len = MAX_EC_WRAPPED_KEY_BUFLEN -
   5451 	    (ecWrapped->encodedParamLen + ecWrapped->pubValueLen);
   5452 	wrappedKey.data = ecWrapped->var + ecWrapped->encodedParamLen +
   5453 	    ecWrapped->pubValueLen;
   5454 
   5455 	/* wrap symmetricWrapping key with the local Ks */
   5456 	rv = PK11_WrapSymKey(masterWrapMech, NULL, Ks,
   5457 			     unwrappedWrappingKey, &wrappedKey);
   5458 
   5459 	if (rv != SECSuccess) {
   5460 	    goto ec_cleanup;
   5461 	}
   5462 
   5463 	/* Write down the length of wrapped key in the buffer
   5464 	 * wswk.wrappedSymmetricWrappingkey at the appropriate offset
   5465 	 */
   5466 	ecWrapped->wrappedKeyLen = wrappedKey.len;
   5467 
   5468 ec_cleanup:
   5469 	if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
   5470 	if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
   5471 	if (Ks) PK11_FreeSymKey(Ks);
   5472 	asymWrapMechanism = masterWrapMech;
   5473 	break;
   5474 #endif /* NSS_ENABLE_ECC */
   5475 
   5476     default:
   5477 	rv = SECFailure;
   5478 	break;
   5479     }
   5480 
   5481     if (rv != SECSuccess) {
   5482 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5483 	goto loser;
   5484     }
   5485 
   5486     PORT_Assert(asymWrapMechanism != CKM_INVALID_MECHANISM);
   5487 
   5488     wswk.symWrapMechanism  = masterWrapMech;
   5489     wswk.symWrapMechIndex  = symWrapMechIndex;
   5490     wswk.asymWrapMechanism = asymWrapMechanism;
   5491     wswk.exchKeyType       = exchKeyType;
   5492     wswk.wrappedSymKeyLen  = wrappedKey.len;
   5493 
   5494     /* put it on disk. */
   5495     /* If the wrapping key for this KEA type has already been set,
   5496      * then abandon the value we just computed and
   5497      * use the one we got from the disk.
   5498      */
   5499     if (ssl_SetWrappingKey(&wswk)) {
   5500     	/* somebody beat us to it.  The original contents of our wswk
   5501 	 * has been replaced with the content on disk.  Now, discard
   5502 	 * the key we just created and unwrap this new one.
   5503 	 */
   5504     	PK11_FreeSymKey(unwrappedWrappingKey);
   5505 
   5506 	unwrappedWrappingKey =
   5507 	    ssl_UnwrapSymWrappingKey(&wswk, svrPrivKey, exchKeyType,
   5508                                      masterWrapMech, pwArg);
   5509     }
   5510 
   5511 install:
   5512     if (unwrappedWrappingKey) {
   5513 	*pSymWrapKey = PK11_ReferenceSymKey(unwrappedWrappingKey);
   5514     }
   5515 
   5516 loser:
   5517 done:
   5518     PZ_Unlock(symWrapKeysLock);
   5519     return unwrappedWrappingKey;
   5520 }
   5521 
   5522 /* hexEncode hex encodes |length| bytes from |in| and writes it as |length*2|
   5523  * bytes to |out|. */
   5524 static void
   5525 hexEncode(char *out, const unsigned char *in, unsigned int length)
   5526 {
   5527     static const char hextable[] = "0123456789abcdef";
   5528     unsigned int i;
   5529 
   5530     for (i = 0; i < length; i++) {
   5531 	*(out++) = hextable[in[i] >> 4];
   5532 	*(out++) = hextable[in[i] & 15];
   5533     }
   5534 }
   5535 
   5536 /* Called from ssl3_SendClientKeyExchange(). */
   5537 /* Presently, this always uses PKCS11.  There is no bypass for this. */
   5538 static SECStatus
   5539 sendRSAClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
   5540 {
   5541     PK11SymKey *	pms 		= NULL;
   5542     SECStatus           rv    		= SECFailure;
   5543     SECItem 		enc_pms 	= {siBuffer, NULL, 0};
   5544     PRBool              isTLS;
   5545 
   5546     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   5547     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   5548 
   5549     /* Generate the pre-master secret ...  */
   5550     ssl_GetSpecWriteLock(ss);
   5551     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   5552 
   5553     pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.pwSpec, NULL);
   5554     ssl_ReleaseSpecWriteLock(ss);
   5555     if (pms == NULL) {
   5556 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5557 	goto loser;
   5558     }
   5559 
   5560     /* Get the wrapped (encrypted) pre-master secret, enc_pms */
   5561     enc_pms.len  = SECKEY_PublicKeyStrength(svrPubKey);
   5562     enc_pms.data = (unsigned char*)PORT_Alloc(enc_pms.len);
   5563     if (enc_pms.data == NULL) {
   5564 	goto loser;	/* err set by PORT_Alloc */
   5565     }
   5566 
   5567     /* wrap pre-master secret in server's public key. */
   5568     rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, svrPubKey, pms, &enc_pms);
   5569     if (rv != SECSuccess) {
   5570 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5571 	goto loser;
   5572     }
   5573 
   5574     if (ssl_keylog_iob) {
   5575 	SECStatus extractRV = PK11_ExtractKeyValue(pms);
   5576 	if (extractRV == SECSuccess) {
   5577 	    SECItem * keyData = PK11_GetKeyData(pms);
   5578 	    if (keyData && keyData->data && keyData->len) {
   5579 #ifdef TRACE
   5580 		if (ssl_trace >= 100) {
   5581 		    ssl_PrintBuf(ss, "Pre-Master Secret",
   5582 				 keyData->data, keyData->len);
   5583 		}
   5584 #endif
   5585 		if (ssl_keylog_iob && enc_pms.len >= 8 && keyData->len == 48) {
   5586 		    /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
   5587 
   5588 		    /* There could be multiple, concurrent writers to the
   5589 		     * keylog, so we have to do everything in a single call to
   5590 		     * fwrite. */
   5591 		    char buf[4 + 8*2 + 1 + 48*2 + 1];
   5592 
   5593 		    strcpy(buf, "RSA ");
   5594 		    hexEncode(buf + 4, enc_pms.data, 8);
   5595 		    buf[20] = ' ';
   5596 		    hexEncode(buf + 21, keyData->data, 48);
   5597 		    buf[sizeof(buf) - 1] = '\n';
   5598 
   5599 		    fwrite(buf, sizeof(buf), 1, ssl_keylog_iob);
   5600 		    fflush(ssl_keylog_iob);
   5601 		}
   5602 	    }
   5603 	}
   5604     }
   5605 
   5606     rv = ssl3_InitPendingCipherSpec(ss,  pms);
   5607     PK11_FreeSymKey(pms); pms = NULL;
   5608 
   5609     if (rv != SECSuccess) {
   5610 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5611 	goto loser;
   5612     }
   5613 
   5614     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
   5615 				    isTLS ? enc_pms.len + 2 : enc_pms.len);
   5616     if (rv != SECSuccess) {
   5617 	goto loser;	/* err set by ssl3_AppendHandshake* */
   5618     }
   5619     if (isTLS) {
   5620     	rv = ssl3_AppendHandshakeVariable(ss, enc_pms.data, enc_pms.len, 2);
   5621     } else {
   5622 	rv = ssl3_AppendHandshake(ss, enc_pms.data, enc_pms.len);
   5623     }
   5624     if (rv != SECSuccess) {
   5625 	goto loser;	/* err set by ssl3_AppendHandshake* */
   5626     }
   5627 
   5628     rv = SECSuccess;
   5629 
   5630 loser:
   5631     if (enc_pms.data != NULL) {
   5632 	PORT_Free(enc_pms.data);
   5633     }
   5634     if (pms != NULL) {
   5635     	PK11_FreeSymKey(pms);
   5636     }
   5637     return rv;
   5638 }
   5639 
   5640 /* Called from ssl3_SendClientKeyExchange(). */
   5641 /* Presently, this always uses PKCS11.  There is no bypass for this. */
   5642 static SECStatus
   5643 sendDHClientKeyExchange(sslSocket * ss, SECKEYPublicKey * svrPubKey)
   5644 {
   5645     PK11SymKey *	pms 		= NULL;
   5646     SECStatus           rv    		= SECFailure;
   5647     PRBool              isTLS;
   5648     CK_MECHANISM_TYPE	target;
   5649 
   5650     SECKEYDHParams	dhParam;		/* DH parameters */
   5651     SECKEYPublicKey	*pubKey = NULL;		/* Ephemeral DH key */
   5652     SECKEYPrivateKey	*privKey = NULL;	/* Ephemeral DH key */
   5653 
   5654     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   5655     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   5656 
   5657     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   5658 
   5659     /* Copy DH parameters from server key */
   5660 
   5661     if (svrPubKey->keyType != dhKey) {
   5662 	PORT_SetError(SEC_ERROR_BAD_KEY);
   5663 	goto loser;
   5664     }
   5665     dhParam.prime.data = svrPubKey->u.dh.prime.data;
   5666     dhParam.prime.len = svrPubKey->u.dh.prime.len;
   5667     dhParam.base.data = svrPubKey->u.dh.base.data;
   5668     dhParam.base.len = svrPubKey->u.dh.base.len;
   5669 
   5670     /* Generate ephemeral DH keypair */
   5671     privKey = SECKEY_CreateDHPrivateKey(&dhParam, &pubKey, NULL);
   5672     if (!privKey || !pubKey) {
   5673 	    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
   5674 	    rv = SECFailure;
   5675 	    goto loser;
   5676     }
   5677     PRINT_BUF(50, (ss, "DH public value:",
   5678 					pubKey->u.dh.publicValue.data,
   5679 					pubKey->u.dh.publicValue.len));
   5680 
   5681     if (isTLS) target = CKM_TLS_MASTER_KEY_DERIVE_DH;
   5682     else target = CKM_SSL3_MASTER_KEY_DERIVE_DH;
   5683 
   5684     /* Determine the PMS */
   5685 
   5686     pms = PK11_PubDerive(privKey, svrPubKey, PR_FALSE, NULL, NULL,
   5687 			    CKM_DH_PKCS_DERIVE, target, CKA_DERIVE, 0, NULL);
   5688 
   5689     if (pms == NULL) {
   5690 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5691 	goto loser;
   5692     }
   5693 
   5694     SECKEY_DestroyPrivateKey(privKey);
   5695     privKey = NULL;
   5696 
   5697     rv = ssl3_InitPendingCipherSpec(ss,  pms);
   5698     PK11_FreeSymKey(pms); pms = NULL;
   5699 
   5700     if (rv != SECSuccess) {
   5701 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   5702 	goto loser;
   5703     }
   5704 
   5705     rv = ssl3_AppendHandshakeHeader(ss, client_key_exchange,
   5706 					pubKey->u.dh.publicValue.len + 2);
   5707     if (rv != SECSuccess) {
   5708 	goto loser;	/* err set by ssl3_AppendHandshake* */
   5709     }
   5710     rv = ssl3_AppendHandshakeVariable(ss,
   5711 					pubKey->u.dh.publicValue.data,
   5712 					pubKey->u.dh.publicValue.len, 2);
   5713     SECKEY_DestroyPublicKey(pubKey);
   5714     pubKey = NULL;
   5715 
   5716     if (rv != SECSuccess) {
   5717 	goto loser;	/* err set by ssl3_AppendHandshake* */
   5718     }
   5719 
   5720     rv = SECSuccess;
   5721 
   5722 
   5723 loser:
   5724 
   5725     if(pms) PK11_FreeSymKey(pms);
   5726     if(privKey) SECKEY_DestroyPrivateKey(privKey);
   5727     if(pubKey) SECKEY_DestroyPublicKey(pubKey);
   5728     return rv;
   5729 }
   5730 
   5731 
   5732 
   5733 
   5734 
   5735 /* Called from ssl3_HandleServerHelloDone(). */
   5736 static SECStatus
   5737 ssl3_SendClientKeyExchange(sslSocket *ss)
   5738 {
   5739     SECKEYPublicKey *	serverKey 	= NULL;
   5740     SECStatus 		rv 		= SECFailure;
   5741     PRBool              isTLS;
   5742 
   5743     SSL_TRC(3, ("%d: SSL3[%d]: send client_key_exchange handshake",
   5744 		SSL_GETPID(), ss->fd));
   5745 
   5746     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   5747     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   5748 
   5749     if (ss->sec.peerKey == NULL) {
   5750 	serverKey = CERT_ExtractPublicKey(ss->sec.peerCert);
   5751 	if (serverKey == NULL) {
   5752 	    ssl_MapLowLevelError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   5753 	    return SECFailure;
   5754 	}
   5755     } else {
   5756 	serverKey = ss->sec.peerKey;
   5757 	ss->sec.peerKey = NULL; /* we're done with it now */
   5758     }
   5759 
   5760     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   5761     /* enforce limits on kea key sizes. */
   5762     if (ss->ssl3.hs.kea_def->is_limited) {
   5763 	int keyLen = SECKEY_PublicKeyStrength(serverKey);	/* bytes */
   5764 
   5765 	if (keyLen * BPB > ss->ssl3.hs.kea_def->key_size_limit) {
   5766 	    if (isTLS)
   5767 		(void)SSL3_SendAlert(ss, alert_fatal, export_restriction);
   5768 	    else
   5769 		(void)ssl3_HandshakeFailure(ss);
   5770 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
   5771 	    goto loser;
   5772 	}
   5773     }
   5774 
   5775     ss->sec.keaType    = ss->ssl3.hs.kea_def->exchKeyType;
   5776     ss->sec.keaKeyBits = SECKEY_PublicKeyStrengthInBits(serverKey);
   5777 
   5778     switch (ss->ssl3.hs.kea_def->exchKeyType) {
   5779     case kt_rsa:
   5780 	rv = sendRSAClientKeyExchange(ss, serverKey);
   5781 	break;
   5782 
   5783     case kt_dh:
   5784 	rv = sendDHClientKeyExchange(ss, serverKey);
   5785 	break;
   5786 
   5787 #ifdef NSS_ENABLE_ECC
   5788     case kt_ecdh:
   5789 	rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
   5790 	break;
   5791 #endif /* NSS_ENABLE_ECC */
   5792 
   5793     default:
   5794 	/* got an unknown or unsupported Key Exchange Algorithm.  */
   5795 	SEND_ALERT
   5796 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   5797 	break;
   5798     }
   5799 
   5800     SSL_TRC(3, ("%d: SSL3[%d]: DONE sending client_key_exchange",
   5801 		SSL_GETPID(), ss->fd));
   5802 
   5803 loser:
   5804     if (serverKey)
   5805     	SECKEY_DestroyPublicKey(serverKey);
   5806     return rv;	/* err code already set. */
   5807 }
   5808 
   5809 /* Called from ssl3_HandleServerHelloDone(). */
   5810 static SECStatus
   5811 ssl3_SendCertificateVerify(sslSocket *ss)
   5812 {
   5813     SECStatus     rv		= SECFailure;
   5814     PRBool        isTLS;
   5815     PRBool        isTLS12;
   5816     SECItem       buf           = {siBuffer, NULL, 0};
   5817     SSL3Hashes    hashes;
   5818     KeyType       keyType;
   5819     unsigned int  len;
   5820     SSL3SignatureAndHashAlgorithm sigAndHash;
   5821 
   5822     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   5823     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   5824 
   5825     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_verify handshake",
   5826 		SSL_GETPID(), ss->fd));
   5827 
   5828     ssl_GetSpecReadLock(ss);
   5829     /* In TLS 1.2, ssl3_ComputeHandshakeHashes always uses the handshake hash
   5830      * function (SHA-256). If the server or the client does not support SHA-256
   5831      * as a signature hash, we can either maintain a backup SHA-1 handshake
   5832      * hash or buffer all handshake messages.
   5833      */
   5834     if (ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) {
   5835 	rv = ssl3_ComputeBackupHandshakeHashes(ss, &hashes);
   5836 	PORT_Assert(ss->ssl3.hs.md5 == NULL);
   5837     } else {
   5838 	rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.pwSpec, &hashes, 0);
   5839     }
   5840     ssl_ReleaseSpecReadLock(ss);
   5841     if (rv != SECSuccess) {
   5842 	goto done;	/* err code was set by ssl3_ComputeHandshakeHashes */
   5843     }
   5844 
   5845     isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   5846     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   5847     if (ss->ssl3.platformClientKey) {
   5848 #ifdef NSS_PLATFORM_CLIENT_AUTH
   5849 	keyType = CERT_GetCertKeyType(
   5850 	    &ss->ssl3.clientCertificate->subjectPublicKeyInfo);
   5851 	rv = ssl3_PlatformSignHashes(
   5852 	    &hashes, ss->ssl3.platformClientKey, &buf, isTLS, keyType);
   5853 	ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   5854 	ss->ssl3.platformClientKey = (PlatformKey)NULL;
   5855 #endif /* NSS_PLATFORM_CLIENT_AUTH */
   5856     } else {
   5857 	keyType = ss->ssl3.clientPrivateKey->keyType;
   5858 	rv = ssl3_SignHashes(&hashes, ss->ssl3.clientPrivateKey, &buf, isTLS);
   5859 	if (rv == SECSuccess) {
   5860 	    PK11SlotInfo * slot;
   5861 	    sslSessionID * sid   = ss->sec.ci.sid;
   5862 
   5863 	    /* Remember the info about the slot that did the signing.
   5864 	    ** Later, when doing an SSL restart handshake, verify this.
   5865 	    ** These calls are mere accessors, and can't fail.
   5866 	    */
   5867 	    slot = PK11_GetSlotFromPrivateKey(ss->ssl3.clientPrivateKey);
   5868 	    sid->u.ssl3.clAuthSeries     = PK11_GetSlotSeries(slot);
   5869 	    sid->u.ssl3.clAuthSlotID     = PK11_GetSlotID(slot);
   5870 	    sid->u.ssl3.clAuthModuleID   = PK11_GetModuleID(slot);
   5871 	    sid->u.ssl3.clAuthValid      = PR_TRUE;
   5872 	    PK11_FreeSlot(slot);
   5873 	}
   5874 	SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   5875 	ss->ssl3.clientPrivateKey = NULL;
   5876     }
   5877     if (rv != SECSuccess) {
   5878 	goto done;	/* err code was set by ssl3_SignHashes */
   5879     }
   5880 
   5881     len = buf.len + 2 + (isTLS12 ? 2 : 0);
   5882 
   5883     rv = ssl3_AppendHandshakeHeader(ss, certificate_verify, len);
   5884     if (rv != SECSuccess) {
   5885 	goto done;	/* error code set by AppendHandshake */
   5886     }
   5887     if (isTLS12) {
   5888 	rv = ssl3_TLSSignatureAlgorithmForKeyType(keyType,
   5889 						  &sigAndHash.sigAlg);
   5890 	if (rv != SECSuccess) {
   5891 	    goto done;
   5892 	}
   5893 	sigAndHash.hashAlg = hashes.hashAlg;
   5894 
   5895 	rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
   5896 	if (rv != SECSuccess) {
   5897 	    goto done; 	/* err set by AppendHandshake. */
   5898 	}
   5899     }
   5900     rv = ssl3_AppendHandshakeVariable(ss, buf.data, buf.len, 2);
   5901     if (rv != SECSuccess) {
   5902 	goto done;	/* error code set by AppendHandshake */
   5903     }
   5904 
   5905 done:
   5906     if (buf.data)
   5907 	PORT_Free(buf.data);
   5908     return rv;
   5909 }
   5910 
   5911 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   5912  * ssl3 ServerHello message.
   5913  * Caller must hold Handshake and RecvBuf locks.
   5914  */
   5915 static SECStatus
   5916 ssl3_HandleServerHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   5917 {
   5918     sslSessionID *sid		= ss->sec.ci.sid;
   5919     PRInt32       temp;		/* allow for consume number failure */
   5920     PRBool        suite_found   = PR_FALSE;
   5921     int           i;
   5922     int           errCode	= SSL_ERROR_RX_MALFORMED_SERVER_HELLO;
   5923     SECStatus     rv;
   5924     SECItem       sidBytes 	= {siBuffer, NULL, 0};
   5925     PRBool        sid_match;
   5926     PRBool        isTLS		= PR_FALSE;
   5927     SSL3AlertDescription desc   = illegal_parameter;
   5928     SSL3ProtocolVersion version;
   5929 
   5930     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello handshake",
   5931     	SSL_GETPID(), ss->fd));
   5932     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   5933     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   5934     PORT_Assert( ss->ssl3.initialized );
   5935 
   5936     if (ss->ssl3.hs.ws != wait_server_hello) {
   5937         errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO;
   5938 	desc    = unexpected_message;
   5939 	goto alert_loser;
   5940     }
   5941 
   5942     /* clean up anything left from previous handshake. */
   5943     if (ss->ssl3.clientCertChain != NULL) {
   5944        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
   5945        ss->ssl3.clientCertChain = NULL;
   5946     }
   5947     if (ss->ssl3.clientCertificate != NULL) {
   5948        CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   5949        ss->ssl3.clientCertificate = NULL;
   5950     }
   5951     if (ss->ssl3.clientPrivateKey != NULL) {
   5952        SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   5953        ss->ssl3.clientPrivateKey = NULL;
   5954     }
   5955 #ifdef NSS_PLATFORM_CLIENT_AUTH
   5956     if (ss->ssl3.platformClientKey) {
   5957        ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   5958        ss->ssl3.platformClientKey = (PlatformKey)NULL;
   5959     }
   5960 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
   5961 
   5962     if (ss->ssl3.channelID != NULL) {
   5963 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   5964 	ss->ssl3.channelID = NULL;
   5965     }
   5966     if (ss->ssl3.channelIDPub != NULL) {
   5967 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   5968 	ss->ssl3.channelIDPub = NULL;
   5969     }
   5970 
   5971     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   5972     if (temp < 0) {
   5973     	goto loser; 	/* alert has been sent */
   5974     }
   5975     version = (SSL3ProtocolVersion)temp;
   5976 
   5977     if (IS_DTLS(ss)) {
   5978 	/* RFC 4347 required that you verify that the server versions
   5979 	 * match (Section 4.2.1) in the HelloVerifyRequest and the
   5980 	 * ServerHello.
   5981 	 *
   5982 	 * RFC 6347 suggests (SHOULD) that servers always use 1.0
   5983 	 * in HelloVerifyRequest and allows the versions not to match,
   5984 	 * especially when 1.2 is being negotiated.
   5985 	 *
   5986 	 * Therefore we do not check for matching here.
   5987 	 */
   5988 	version = dtls_DTLSVersionToTLSVersion(version);
   5989 	if (version == 0) {  /* Insane version number */
   5990             goto alert_loser;
   5991 	}
   5992     }
   5993 
   5994     rv = ssl3_NegotiateVersion(ss, version, PR_FALSE);
   5995     if (rv != SECSuccess) {
   5996     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
   5997 						   : handshake_failure;
   5998 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   5999 	goto alert_loser;
   6000     }
   6001     isTLS = (ss->version > SSL_LIBRARY_VERSION_3_0);
   6002 
   6003     rv = ssl3_InitHandshakeHashes(ss);
   6004     if (rv != SECSuccess) {
   6005 	desc = internal_error;
   6006 	errCode = PORT_GetError();
   6007 	goto alert_loser;
   6008     }
   6009 
   6010     rv = ssl3_ConsumeHandshake(
   6011 	ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH, &b, &length);
   6012     if (rv != SECSuccess) {
   6013     	goto loser; 	/* alert has been sent */
   6014     }
   6015 
   6016     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
   6017     if (rv != SECSuccess) {
   6018     	goto loser; 	/* alert has been sent */
   6019     }
   6020     if (sidBytes.len > SSL3_SESSIONID_BYTES) {
   6021 	if (isTLS)
   6022 	    desc = decode_error;
   6023 	goto alert_loser;	/* malformed. */
   6024     }
   6025 
   6026     /* find selected cipher suite in our list. */
   6027     temp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   6028     if (temp < 0) {
   6029     	goto loser; 	/* alert has been sent */
   6030     }
   6031     ssl3_config_match_init(ss);
   6032     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
   6033 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
   6034 	if (temp == suite->cipher_suite) {
   6035 	    if (!config_match(suite, ss->ssl3.policy, PR_TRUE)) {
   6036 		break;	/* failure */
   6037 	    }
   6038 	    if (!ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
   6039 						   ss->version)) {
   6040 		desc    = handshake_failure;
   6041 		errCode = SSL_ERROR_CIPHER_DISALLOWED_FOR_VERSION;
   6042 		goto alert_loser;
   6043 	    }
   6044 
   6045 	    suite_found = PR_TRUE;
   6046 	    break;	/* success */
   6047 	}
   6048     }
   6049     if (!suite_found) {
   6050     	desc    = handshake_failure;
   6051 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   6052 	goto alert_loser;
   6053     }
   6054     ss->ssl3.hs.cipher_suite = (ssl3CipherSuite)temp;
   6055     ss->ssl3.hs.suite_def    = ssl_LookupCipherSuiteDef((ssl3CipherSuite)temp);
   6056     PORT_Assert(ss->ssl3.hs.suite_def);
   6057     if (!ss->ssl3.hs.suite_def) {
   6058     	PORT_SetError(errCode = SEC_ERROR_LIBRARY_FAILURE);
   6059 	goto loser;	/* we don't send alerts for our screw-ups. */
   6060     }
   6061 
   6062     /* find selected compression method in our list. */
   6063     temp = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
   6064     if (temp < 0) {
   6065     	goto loser; 	/* alert has been sent */
   6066     }
   6067     suite_found = PR_FALSE;
   6068     for (i = 0; i < compressionMethodsCount; i++) {
   6069 	if (temp == compressions[i]) {
   6070 	    if (!compressionEnabled(ss, compressions[i])) {
   6071 		break;	/* failure */
   6072 	    }
   6073 	    suite_found = PR_TRUE;
   6074 	    break;	/* success */
   6075     	}
   6076     }
   6077     if (!suite_found) {
   6078     	desc    = handshake_failure;
   6079 	errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
   6080 	goto alert_loser;
   6081     }
   6082     ss->ssl3.hs.compression = (SSLCompressionMethod)temp;
   6083 
   6084     /* Note that if !isTLS and the extra stuff is not extensions, we
   6085      * do NOT goto alert_loser.
   6086      * There are some old SSL 3.0 implementations that do send stuff
   6087      * after the end of the server hello, and we deliberately ignore
   6088      * such stuff in the interest of maximal interoperability (being
   6089      * "generous in what you accept").
   6090      * Update: Starting in NSS 3.12.6, we handle the renegotiation_info
   6091      * extension in SSL 3.0.
   6092      */
   6093     if (length != 0) {
   6094 	SECItem extensions;
   6095 	rv = ssl3_ConsumeHandshakeVariable(ss, &extensions, 2, &b, &length);
   6096 	if (rv != SECSuccess || length != 0) {
   6097 	    if (isTLS)
   6098 		goto alert_loser;
   6099 	} else {
   6100 	    rv = ssl3_HandleHelloExtensions(ss, &extensions.data,
   6101 					    &extensions.len);
   6102 	    if (rv != SECSuccess)
   6103 		goto alert_loser;
   6104 	}
   6105     }
   6106     if ((ss->opt.requireSafeNegotiation ||
   6107          (ss->firstHsDone && (ss->peerRequestedProtection ||
   6108 	 ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN))) &&
   6109 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   6110 	desc = handshake_failure;
   6111 	errCode = ss->firstHsDone ? SSL_ERROR_RENEGOTIATION_NOT_ALLOWED
   6112 	                          : SSL_ERROR_UNSAFE_NEGOTIATION;
   6113 	goto alert_loser;
   6114     }
   6115 
   6116     /* Any errors after this point are not "malformed" errors. */
   6117     desc    = handshake_failure;
   6118 
   6119     /* we need to call ssl3_SetupPendingCipherSpec here so we can check the
   6120      * key exchange algorithm. */
   6121     rv = ssl3_SetupPendingCipherSpec(ss);
   6122     if (rv != SECSuccess) {
   6123 	goto alert_loser;	/* error code is set. */
   6124     }
   6125 
   6126     /* We may or may not have sent a session id, we may get one back or
   6127      * not and if so it may match the one we sent.
   6128      * Attempt to restore the master secret to see if this is so...
   6129      * Don't consider failure to find a matching SID an error.
   6130      */
   6131     sid_match = (PRBool)(sidBytes.len > 0 &&
   6132 	sidBytes.len == sid->u.ssl3.sessionIDLength &&
   6133 	!PORT_Memcmp(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len));
   6134 
   6135     if (sid_match &&
   6136 	sid->version == ss->version &&
   6137 	sid->u.ssl3.cipherSuite == ss->ssl3.hs.cipher_suite) do {
   6138 	ssl3CipherSpec *pwSpec = ss->ssl3.pwSpec;
   6139 
   6140 	SECItem       wrappedMS;   /* wrapped master secret. */
   6141 
   6142 	ss->sec.authAlgorithm = sid->authAlgorithm;
   6143 	ss->sec.authKeyBits   = sid->authKeyBits;
   6144 	ss->sec.keaType       = sid->keaType;
   6145 	ss->sec.keaKeyBits    = sid->keaKeyBits;
   6146 
   6147 	/* 3 cases here:
   6148 	 * a) key is wrapped (implies using PKCS11)
   6149 	 * b) key is unwrapped, but we're still using PKCS11
   6150 	 * c) key is unwrapped, and we're bypassing PKCS11.
   6151 	 */
   6152 	if (sid->u.ssl3.keys.msIsWrapped) {
   6153 	    PK11SlotInfo *slot;
   6154 	    PK11SymKey *  wrapKey;     /* wrapping key */
   6155 	    CK_FLAGS      keyFlags      = 0;
   6156 
   6157 #ifndef NO_PKCS11_BYPASS
   6158 	    if (ss->opt.bypassPKCS11) {
   6159 		/* we cannot restart a non-bypass session in a
   6160 		** bypass socket.
   6161 		*/
   6162 		break;
   6163 	    }
   6164 #endif
   6165 	    /* unwrap master secret with PKCS11 */
   6166 	    slot = SECMOD_LookupSlot(sid->u.ssl3.masterModuleID,
   6167 				     sid->u.ssl3.masterSlotID);
   6168 	    if (slot == NULL) {
   6169 		break;		/* not considered an error. */
   6170 	    }
   6171 	    if (!PK11_IsPresent(slot)) {
   6172 		PK11_FreeSlot(slot);
   6173 		break;		/* not considered an error. */
   6174 	    }
   6175 	    wrapKey = PK11_GetWrapKey(slot, sid->u.ssl3.masterWrapIndex,
   6176 				      sid->u.ssl3.masterWrapMech,
   6177 				      sid->u.ssl3.masterWrapSeries,
   6178 				      ss->pkcs11PinArg);
   6179 	    PK11_FreeSlot(slot);
   6180 	    if (wrapKey == NULL) {
   6181 		break;		/* not considered an error. */
   6182 	    }
   6183 
   6184 	    if (ss->version > SSL_LIBRARY_VERSION_3_0) {	/* isTLS */
   6185 		keyFlags = CKF_SIGN | CKF_VERIFY;
   6186 	    }
   6187 
   6188 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   6189 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   6190 	    pwSpec->master_secret =
   6191 		PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
   6192 			    NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
   6193 			    CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
   6194 	    errCode = PORT_GetError();
   6195 	    PK11_FreeSymKey(wrapKey);
   6196 	    if (pwSpec->master_secret == NULL) {
   6197 		break;	/* errorCode set just after call to UnwrapSymKey. */
   6198 	    }
   6199 #ifndef NO_PKCS11_BYPASS
   6200 	} else if (ss->opt.bypassPKCS11) {
   6201 	    /* MS is not wrapped */
   6202 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   6203 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   6204 	    memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
   6205 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   6206 	    pwSpec->msItem.len  = wrappedMS.len;
   6207 #endif
   6208 	} else {
   6209 	    /* We CAN restart a bypass session in a non-bypass socket. */
   6210 	    /* need to import the raw master secret to session object */
   6211 	    PK11SlotInfo *slot = PK11_GetInternalSlot();
   6212 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   6213 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   6214 	    pwSpec->master_secret =
   6215 		PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
   6216 				  PK11_OriginUnwrap, CKA_ENCRYPT,
   6217 				  &wrappedMS, NULL);
   6218 	    PK11_FreeSlot(slot);
   6219 	    if (pwSpec->master_secret == NULL) {
   6220 		break;
   6221 	    }
   6222 	}
   6223 
   6224 	/* Got a Match */
   6225 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_hits );
   6226 
   6227 	/* If we sent a session ticket, then this is a stateless resume. */
   6228 	if (sid->version > SSL_LIBRARY_VERSION_3_0 &&
   6229 	    sid->u.ssl3.sessionTicket.ticket.data != NULL)
   6230 	    SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_stateless_resumes );
   6231 
   6232 	if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
   6233 	    ss->ssl3.hs.ws = wait_new_session_ticket;
   6234 	else
   6235 	    ss->ssl3.hs.ws = wait_change_cipher;
   6236 
   6237 	ss->ssl3.hs.isResuming = PR_TRUE;
   6238 
   6239 	/* copy the peer cert from the SID */
   6240 	if (sid->peerCert != NULL) {
   6241 	    ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
   6242 	    ssl3_CopyPeerCertsFromSID(ss, sid);
   6243 	}
   6244 
   6245 	/* NULL value for PMS signifies re-use of the old MS */
   6246 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
   6247 	if (rv != SECSuccess) {
   6248 	    goto alert_loser;	/* err code was set */
   6249 	}
   6250 	goto winner;
   6251     } while (0);
   6252 
   6253     if (sid_match)
   6254 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_not_ok );
   6255     else
   6256 	SSL_AtomicIncrementLong(& ssl3stats.hsh_sid_cache_misses );
   6257 
   6258     /* throw the old one away */
   6259     sid->u.ssl3.keys.resumable = PR_FALSE;
   6260     if (ss->sec.uncache)
   6261         (*ss->sec.uncache)(sid);
   6262     ssl_FreeSID(sid);
   6263 
   6264     /* get a new sid */
   6265     ss->sec.ci.sid = sid = ssl3_NewSessionID(ss, PR_FALSE);
   6266     if (sid == NULL) {
   6267 	goto alert_loser;	/* memory error is set. */
   6268     }
   6269 
   6270     sid->version = ss->version;
   6271     sid->u.ssl3.sessionIDLength = sidBytes.len;
   6272     PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data, sidBytes.len);
   6273 
   6274     ss->ssl3.hs.isResuming = PR_FALSE;
   6275     ss->ssl3.hs.ws         = wait_server_cert;
   6276 
   6277 winner:
   6278     /* If we will need a ChannelID key then we make the callback now. This
   6279      * allows the handshake to be restarted cleanly if the callback returns
   6280      * SECWouldBlock. */
   6281     if (ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn)) {
   6282 	rv = ss->getChannelID(ss->getChannelIDArg, ss->fd,
   6283 			      &ss->ssl3.channelIDPub, &ss->ssl3.channelID);
   6284 	if (rv == SECWouldBlock) {
   6285 	    ssl3_SetAlwaysBlock(ss);
   6286 	    return rv;
   6287 	}
   6288 	if (rv != SECSuccess ||
   6289 	    ss->ssl3.channelIDPub == NULL ||
   6290 	    ss->ssl3.channelID == NULL) {
   6291 	    PORT_SetError(SSL_ERROR_GET_CHANNEL_ID_FAILED);
   6292 	    desc = internal_error;
   6293 	    goto alert_loser;
   6294 	}
   6295     }
   6296 
   6297     return SECSuccess;
   6298 
   6299 alert_loser:
   6300     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   6301 
   6302 loser:
   6303     errCode = ssl_MapLowLevelError(errCode);
   6304     return SECFailure;
   6305 }
   6306 
   6307 /* ssl3_BigIntGreaterThanOne returns true iff |mpint|, taken as an unsigned,
   6308  * big-endian integer is > 1 */
   6309 static PRBool
   6310 ssl3_BigIntGreaterThanOne(const SECItem* mpint) {
   6311     unsigned char firstNonZeroByte = 0;
   6312     unsigned int i;
   6313 
   6314     for (i = 0; i < mpint->len; i++) {
   6315 	if (mpint->data[i]) {
   6316 	    firstNonZeroByte = mpint->data[i];
   6317 	    break;
   6318 	}
   6319     }
   6320 
   6321     if (firstNonZeroByte == 0)
   6322 	return PR_FALSE;
   6323     if (firstNonZeroByte > 1)
   6324 	return PR_TRUE;
   6325 
   6326     /* firstNonZeroByte == 1, therefore mpint > 1 iff the first non-zero byte
   6327      * is followed by another byte. */
   6328     return (i < mpint->len - 1);
   6329 }
   6330 
   6331 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   6332  * ssl3 ServerKeyExchange message.
   6333  * Caller must hold Handshake and RecvBuf locks.
   6334  */
   6335 static SECStatus
   6336 ssl3_HandleServerKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   6337 {
   6338     PLArenaPool *    arena     = NULL;
   6339     SECKEYPublicKey *peerKey   = NULL;
   6340     PRBool           isTLS, isTLS12;
   6341     SECStatus        rv;
   6342     int              errCode   = SSL_ERROR_RX_MALFORMED_SERVER_KEY_EXCH;
   6343     SSL3AlertDescription desc  = illegal_parameter;
   6344     SSL3Hashes       hashes;
   6345     SECItem          signature = {siBuffer, NULL, 0};
   6346     SSL3SignatureAndHashAlgorithm sigAndHash;
   6347 
   6348     sigAndHash.hashAlg = SEC_OID_UNKNOWN;
   6349 
   6350     SSL_TRC(3, ("%d: SSL3[%d]: handle server_key_exchange handshake",
   6351 		SSL_GETPID(), ss->fd));
   6352     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   6353     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   6354 
   6355     if (ss->ssl3.hs.ws != wait_server_key &&
   6356 	ss->ssl3.hs.ws != wait_server_cert) {
   6357 	errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
   6358 	desc    = unexpected_message;
   6359 	goto alert_loser;
   6360     }
   6361     if (ss->sec.peerCert == NULL) {
   6362 	errCode = SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH;
   6363 	desc    = unexpected_message;
   6364 	goto alert_loser;
   6365     }
   6366 
   6367     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   6368     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   6369 
   6370     switch (ss->ssl3.hs.kea_def->exchKeyType) {
   6371 
   6372     case kt_rsa: {
   6373 	SECItem          modulus   = {siBuffer, NULL, 0};
   6374 	SECItem          exponent  = {siBuffer, NULL, 0};
   6375 
   6376     	rv = ssl3_ConsumeHandshakeVariable(ss, &modulus, 2, &b, &length);
   6377     	if (rv != SECSuccess) {
   6378 	    goto loser;		/* malformed. */
   6379 	}
   6380     	rv = ssl3_ConsumeHandshakeVariable(ss, &exponent, 2, &b, &length);
   6381     	if (rv != SECSuccess) {
   6382 	    goto loser;		/* malformed. */
   6383 	}
   6384 	if (isTLS12) {
   6385 	    rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
   6386 						       &sigAndHash);
   6387 	    if (rv != SECSuccess) {
   6388 		goto loser;	/* malformed or unsupported. */
   6389 	    }
   6390 	    rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
   6391 		    &sigAndHash, ss->sec.peerCert);
   6392 	    if (rv != SECSuccess) {
   6393 		goto loser;
   6394 	    }
   6395 	}
   6396     	rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
   6397     	if (rv != SECSuccess) {
   6398 	    goto loser;		/* malformed. */
   6399 	}
   6400     	if (length != 0) {
   6401 	    if (isTLS)
   6402 		desc = decode_error;
   6403 	    goto alert_loser;		/* malformed. */
   6404 	}
   6405 
   6406 	/* failures after this point are not malformed handshakes. */
   6407 	/* TLS: send decrypt_error if signature failed. */
   6408     	desc = isTLS ? decrypt_error : handshake_failure;
   6409 
   6410     	/*
   6411      	 *  check to make sure the hash is signed by right guy
   6412      	 */
   6413 	rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg, modulus, exponent,
   6414 					  &ss->ssl3.hs.client_random,
   6415 					  &ss->ssl3.hs.server_random,
   6416 					  &hashes, ss->opt.bypassPKCS11);
   6417         if (rv != SECSuccess) {
   6418 	    errCode =
   6419 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6420 	    goto alert_loser;
   6421 	}
   6422         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
   6423 				    isTLS, ss->pkcs11PinArg);
   6424 	if (rv != SECSuccess)  {
   6425 	    errCode =
   6426 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6427 	    goto alert_loser;
   6428 	}
   6429 
   6430 	/*
   6431 	 * we really need to build a new key here because we can no longer
   6432 	 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
   6433 	 * pkcs11 slots and ID's.
   6434 	 */
   6435     	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   6436 	if (arena == NULL) {
   6437 	    goto no_memory;
   6438 	}
   6439 
   6440     	peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
   6441     	if (peerKey == NULL) {
   6442             PORT_FreeArena(arena, PR_FALSE);
   6443 	    goto no_memory;
   6444 	}
   6445 
   6446 	peerKey->arena              = arena;
   6447 	peerKey->keyType            = rsaKey;
   6448 	peerKey->pkcs11Slot         = NULL;
   6449 	peerKey->pkcs11ID           = CK_INVALID_HANDLE;
   6450 	if (SECITEM_CopyItem(arena, &peerKey->u.rsa.modulus,        &modulus) ||
   6451 	    SECITEM_CopyItem(arena, &peerKey->u.rsa.publicExponent, &exponent))
   6452 	{
   6453             PORT_FreeArena(arena, PR_FALSE);
   6454 	    goto no_memory;
   6455         }
   6456     	ss->sec.peerKey = peerKey;
   6457     	ss->ssl3.hs.ws = wait_cert_request;
   6458     	return SECSuccess;
   6459     }
   6460 
   6461     case kt_dh: {
   6462 	SECItem          dh_p      = {siBuffer, NULL, 0};
   6463 	SECItem          dh_g      = {siBuffer, NULL, 0};
   6464 	SECItem          dh_Ys     = {siBuffer, NULL, 0};
   6465 
   6466     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_p, 2, &b, &length);
   6467     	if (rv != SECSuccess) {
   6468 	    goto loser;		/* malformed. */
   6469 	}
   6470 	if (dh_p.len < 512/8) {
   6471 	    errCode = SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY;
   6472 	    goto alert_loser;
   6473 	}
   6474     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_g, 2, &b, &length);
   6475     	if (rv != SECSuccess) {
   6476 	    goto loser;		/* malformed. */
   6477 	}
   6478 	if (dh_g.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_g))
   6479 	    goto alert_loser;
   6480     	rv = ssl3_ConsumeHandshakeVariable(ss, &dh_Ys, 2, &b, &length);
   6481     	if (rv != SECSuccess) {
   6482 	    goto loser;		/* malformed. */
   6483 	}
   6484 	if (dh_Ys.len > dh_p.len || !ssl3_BigIntGreaterThanOne(&dh_Ys))
   6485 	    goto alert_loser;
   6486 	if (isTLS12) {
   6487 	    rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
   6488 						       &sigAndHash);
   6489 	    if (rv != SECSuccess) {
   6490 		goto loser;	/* malformed or unsupported. */
   6491 	    }
   6492 	    rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
   6493 		    &sigAndHash, ss->sec.peerCert);
   6494 	    if (rv != SECSuccess) {
   6495 		goto loser;
   6496 	    }
   6497 	}
   6498     	rv = ssl3_ConsumeHandshakeVariable(ss, &signature, 2, &b, &length);
   6499     	if (rv != SECSuccess) {
   6500 	    goto loser;		/* malformed. */
   6501 	}
   6502     	if (length != 0) {
   6503 	    if (isTLS)
   6504 		desc = decode_error;
   6505 	    goto alert_loser;		/* malformed. */
   6506 	}
   6507 
   6508 	PRINT_BUF(60, (NULL, "Server DH p", dh_p.data, dh_p.len));
   6509 	PRINT_BUF(60, (NULL, "Server DH g", dh_g.data, dh_g.len));
   6510 	PRINT_BUF(60, (NULL, "Server DH Ys", dh_Ys.data, dh_Ys.len));
   6511 
   6512 	/* failures after this point are not malformed handshakes. */
   6513 	/* TLS: send decrypt_error if signature failed. */
   6514     	desc = isTLS ? decrypt_error : handshake_failure;
   6515 
   6516     	/*
   6517      	 *  check to make sure the hash is signed by right guy
   6518      	 */
   6519 	rv = ssl3_ComputeDHKeyHash(sigAndHash.hashAlg, dh_p, dh_g, dh_Ys,
   6520 					  &ss->ssl3.hs.client_random,
   6521 					  &ss->ssl3.hs.server_random,
   6522 					  &hashes, ss->opt.bypassPKCS11);
   6523         if (rv != SECSuccess) {
   6524 	    errCode =
   6525 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6526 	    goto alert_loser;
   6527 	}
   6528         rv = ssl3_VerifySignedHashes(&hashes, ss->sec.peerCert, &signature,
   6529 				    isTLS, ss->pkcs11PinArg);
   6530 	if (rv != SECSuccess)  {
   6531 	    errCode =
   6532 	    	ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6533 	    goto alert_loser;
   6534 	}
   6535 
   6536 	/*
   6537 	 * we really need to build a new key here because we can no longer
   6538 	 * ignore calling SECKEY_DestroyPublicKey. Using the key may allocate
   6539 	 * pkcs11 slots and ID's.
   6540 	 */
   6541     	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   6542 	if (arena == NULL) {
   6543 	    goto no_memory;
   6544 	}
   6545 
   6546     	ss->sec.peerKey = peerKey = PORT_ArenaZNew(arena, SECKEYPublicKey);
   6547     	if (peerKey == NULL) {
   6548 	    goto no_memory;
   6549 	}
   6550 
   6551 	peerKey->arena              = arena;
   6552 	peerKey->keyType            = dhKey;
   6553 	peerKey->pkcs11Slot         = NULL;
   6554 	peerKey->pkcs11ID           = CK_INVALID_HANDLE;
   6555 
   6556 	if (SECITEM_CopyItem(arena, &peerKey->u.dh.prime,        &dh_p) ||
   6557 	    SECITEM_CopyItem(arena, &peerKey->u.dh.base,         &dh_g) ||
   6558 	    SECITEM_CopyItem(arena, &peerKey->u.dh.publicValue,  &dh_Ys))
   6559 	{
   6560             PORT_FreeArena(arena, PR_FALSE);
   6561 	    goto no_memory;
   6562         }
   6563     	ss->sec.peerKey = peerKey;
   6564     	ss->ssl3.hs.ws = wait_cert_request;
   6565     	return SECSuccess;
   6566     }
   6567 
   6568 #ifdef NSS_ENABLE_ECC
   6569     case kt_ecdh:
   6570 	rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
   6571 	return rv;
   6572 #endif /* NSS_ENABLE_ECC */
   6573 
   6574     default:
   6575     	desc    = handshake_failure;
   6576 	errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
   6577 	break;		/* goto alert_loser; */
   6578     }
   6579 
   6580 alert_loser:
   6581     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   6582 loser:
   6583     PORT_SetError( errCode );
   6584     return SECFailure;
   6585 
   6586 no_memory:	/* no-memory error has already been set. */
   6587     ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   6588     return SECFailure;
   6589 }
   6590 
   6591 
   6592 /*
   6593  * Returns true if the client authentication key is an RSA or DSA key that
   6594  * may be able to sign only SHA-1 hashes.
   6595  */
   6596 static PRBool
   6597 ssl3_ClientKeyPrefersSHA1(sslSocket *ss)
   6598 {
   6599     SECKEYPublicKey *pubk;
   6600     PRBool prefer_sha1 = PR_FALSE;
   6601 
   6602 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(_WIN32)
   6603     /* If the key is in CAPI, assume conservatively that the CAPI service
   6604      * provider may be unable to sign SHA-256 hashes.
   6605      */
   6606     if (ss->ssl3.platformClientKey->dwKeySpec != CERT_NCRYPT_KEY_SPEC) {
   6607 	/* CAPI only supports RSA and DSA signatures, so we don't need to
   6608 	 * check the key type. */
   6609 	return PR_TRUE;
   6610     }
   6611 #endif  /* NSS_PLATFORM_CLIENT_AUTH && _WIN32 */
   6612 
   6613     /* If the key is a 1024-bit RSA or DSA key, assume conservatively that
   6614      * it may be unable to sign SHA-256 hashes. This is the case for older
   6615      * Estonian ID cards that have 1024-bit RSA keys. In FIPS 186-2 and
   6616      * older, DSA key size is at most 1024 bits and the hash function must
   6617      * be SHA-1.
   6618      */
   6619     pubk = CERT_ExtractPublicKey(ss->ssl3.clientCertificate);
   6620     if (pubk == NULL) {
   6621 	return PR_FALSE;
   6622     }
   6623     if (pubk->keyType == rsaKey || pubk->keyType == dsaKey) {
   6624 	prefer_sha1 = SECKEY_PublicKeyStrength(pubk) <= 128;
   6625     }
   6626     SECKEY_DestroyPublicKey(pubk);
   6627     return prefer_sha1;
   6628 }
   6629 
   6630 /* Destroys the backup handshake hash context if we don't need it. */
   6631 static void
   6632 ssl3_DestroyBackupHandshakeHashIfNotNeeded(sslSocket *ss,
   6633 					   const SECItem *algorithms)
   6634 {
   6635     PRBool need_backup_hash = PR_FALSE;
   6636     unsigned int i;
   6637 
   6638     PORT_Assert(ss->ssl3.hs.md5);
   6639     if (ssl3_ClientKeyPrefersSHA1(ss)) {
   6640 	/* Use SHA-1 if the server supports it. */
   6641 	for (i = 0; i < algorithms->len; i += 2) {
   6642 	    if (algorithms->data[i] == tls_hash_sha1 &&
   6643 		(algorithms->data[i+1] == tls_sig_rsa ||
   6644 		 algorithms->data[i+1] == tls_sig_dsa)) {
   6645 		need_backup_hash = PR_TRUE;
   6646 		break;
   6647 	    }
   6648 	}
   6649     }
   6650     if (!need_backup_hash) {
   6651 	PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   6652 	ss->ssl3.hs.md5 = NULL;
   6653     }
   6654 }
   6655 
   6656 typedef struct dnameNode {
   6657     struct dnameNode *next;
   6658     SECItem           name;
   6659 } dnameNode;
   6660 
   6661 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   6662  * ssl3 Certificate Request message.
   6663  * Caller must hold Handshake and RecvBuf locks.
   6664  */
   6665 static SECStatus
   6666 ssl3_HandleCertificateRequest(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   6667 {
   6668     PLArenaPool *        arena       = NULL;
   6669     dnameNode *          node;
   6670     PRInt32              remaining;
   6671     PRBool               isTLS       = PR_FALSE;
   6672     PRBool               isTLS12     = PR_FALSE;
   6673     int                  i;
   6674     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_REQUEST;
   6675     int                  nnames      = 0;
   6676     SECStatus            rv;
   6677     SSL3AlertDescription desc        = illegal_parameter;
   6678     SECItem              cert_types  = {siBuffer, NULL, 0};
   6679     SECItem              algorithms  = {siBuffer, NULL, 0};
   6680     CERTDistNames        ca_list;
   6681 #ifdef NSS_PLATFORM_CLIENT_AUTH
   6682     CERTCertList *       platform_cert_list = NULL;
   6683     CERTCertListNode *   certNode = NULL;
   6684 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
   6685 
   6686     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_request handshake",
   6687 		SSL_GETPID(), ss->fd));
   6688     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   6689     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   6690 
   6691     if (ss->ssl3.hs.ws != wait_cert_request &&
   6692     	ss->ssl3.hs.ws != wait_server_key) {
   6693 	desc    = unexpected_message;
   6694 	errCode = SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST;
   6695 	goto alert_loser;
   6696     }
   6697 
   6698     PORT_Assert(ss->ssl3.clientCertChain == NULL);
   6699     PORT_Assert(ss->ssl3.clientCertificate == NULL);
   6700     PORT_Assert(ss->ssl3.clientPrivateKey == NULL);
   6701     PORT_Assert(ss->ssl3.platformClientKey == (PlatformKey)NULL);
   6702 
   6703     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   6704     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   6705     rv = ssl3_ConsumeHandshakeVariable(ss, &cert_types, 1, &b, &length);
   6706     if (rv != SECSuccess)
   6707     	goto loser;		/* malformed, alert has been sent */
   6708 
   6709     PORT_Assert(!ss->requestedCertTypes);
   6710     ss->requestedCertTypes = &cert_types;
   6711 
   6712     if (isTLS12) {
   6713 	rv = ssl3_ConsumeHandshakeVariable(ss, &algorithms, 2, &b, &length);
   6714 	if (rv != SECSuccess)
   6715 	    goto loser;		/* malformed, alert has been sent */
   6716 	/* An empty or odd-length value is invalid.
   6717 	 *    SignatureAndHashAlgorithm
   6718 	 *      supported_signature_algorithms<2..2^16-2>;
   6719 	 */
   6720 	if (algorithms.len == 0 || (algorithms.len & 1) != 0)
   6721 	    goto alert_loser;
   6722     }
   6723 
   6724     arena = ca_list.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   6725     if (arena == NULL)
   6726     	goto no_mem;
   6727 
   6728     remaining = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   6729     if (remaining < 0)
   6730     	goto loser;	 	/* malformed, alert has been sent */
   6731 
   6732     if ((PRUint32)remaining > length)
   6733 	goto alert_loser;
   6734 
   6735     ca_list.head = node = PORT_ArenaZNew(arena, dnameNode);
   6736     if (node == NULL)
   6737     	goto no_mem;
   6738 
   6739     while (remaining > 0) {
   6740 	PRInt32 len;
   6741 
   6742 	if (remaining < 2)
   6743 	    goto alert_loser;	/* malformed */
   6744 
   6745 	node->name.len = len = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   6746 	if (len <= 0)
   6747 	    goto loser;		/* malformed, alert has been sent */
   6748 
   6749 	remaining -= 2;
   6750 	if (remaining < len)
   6751 	    goto alert_loser;	/* malformed */
   6752 
   6753 	node->name.data = b;
   6754 	b         += len;
   6755 	length    -= len;
   6756 	remaining -= len;
   6757 	nnames++;
   6758 	if (remaining <= 0)
   6759 	    break;		/* success */
   6760 
   6761 	node->next = PORT_ArenaZNew(arena, dnameNode);
   6762 	node = node->next;
   6763 	if (node == NULL)
   6764 	    goto no_mem;
   6765     }
   6766 
   6767     ca_list.nnames = nnames;
   6768     ca_list.names  = PORT_ArenaNewArray(arena, SECItem, nnames);
   6769     if (nnames > 0 && ca_list.names == NULL)
   6770         goto no_mem;
   6771 
   6772     for(i = 0, node = (dnameNode*)ca_list.head;
   6773 	i < nnames;
   6774 	i++, node = node->next) {
   6775 	ca_list.names[i] = node->name;
   6776     }
   6777 
   6778     if (length != 0)
   6779         goto alert_loser;   	/* malformed */
   6780 
   6781     desc = no_certificate;
   6782     ss->ssl3.hs.ws = wait_hello_done;
   6783 
   6784 #ifdef NSS_PLATFORM_CLIENT_AUTH
   6785     if (ss->getPlatformClientAuthData != NULL) {
   6786 	/* XXX Should pass cert_types and algorithms in this call!! */
   6787         rv = (SECStatus)(*ss->getPlatformClientAuthData)(
   6788                                         ss->getPlatformClientAuthDataArg,
   6789                                         ss->fd, &ca_list,
   6790                                         &platform_cert_list,
   6791                                         (void**)&ss->ssl3.platformClientKey,
   6792                                         &ss->ssl3.clientCertificate,
   6793                                         &ss->ssl3.clientPrivateKey);
   6794     } else
   6795 #endif
   6796     if (ss->getClientAuthData != NULL) {
   6797 	/* XXX Should pass cert_types and algorithms in this call!! */
   6798 	rv = (SECStatus)(*ss->getClientAuthData)(ss->getClientAuthDataArg,
   6799 						 ss->fd, &ca_list,
   6800 						 &ss->ssl3.clientCertificate,
   6801 						 &ss->ssl3.clientPrivateKey);
   6802     } else {
   6803 	rv = SECFailure; /* force it to send a no_certificate alert */
   6804     }
   6805 
   6806     switch (rv) {
   6807     case SECWouldBlock:	/* getClientAuthData has put up a dialog box. */
   6808 	ssl3_SetAlwaysBlock(ss);
   6809 	break;	/* not an error */
   6810 
   6811     case SECSuccess:
   6812 #ifdef NSS_PLATFORM_CLIENT_AUTH
   6813         if (!platform_cert_list || CERT_LIST_EMPTY(platform_cert_list) ||
   6814             !ss->ssl3.platformClientKey) {
   6815             if (platform_cert_list) {
   6816                 CERT_DestroyCertList(platform_cert_list);
   6817                 platform_cert_list = NULL;
   6818             }
   6819             if (ss->ssl3.platformClientKey) {
   6820                 ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   6821                 ss->ssl3.platformClientKey = (PlatformKey)NULL;
   6822             }
   6823 	    /* Fall through to NSS client auth check */
   6824         } else {
   6825 	    certNode = CERT_LIST_HEAD(platform_cert_list);
   6826 	    ss->ssl3.clientCertificate = CERT_DupCertificate(certNode->cert);
   6827 
   6828 	    /* Setting ssl3.clientCertChain non-NULL will cause
   6829 	     * ssl3_HandleServerHelloDone to call SendCertificate.
   6830 	     * Note: clientCertChain should include the EE cert as
   6831 	     * clientCertificate is ignored during the actual sending
   6832 	     */
   6833 	    ss->ssl3.clientCertChain =
   6834 		    hack_NewCertificateListFromCertList(platform_cert_list);
   6835 	    CERT_DestroyCertList(platform_cert_list);
   6836 	    platform_cert_list = NULL;
   6837 	    if (ss->ssl3.clientCertChain == NULL) {
   6838 		if (ss->ssl3.clientCertificate != NULL) {
   6839 		    CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   6840 		    ss->ssl3.clientCertificate = NULL;
   6841 		}
   6842 		if (ss->ssl3.platformClientKey) {
   6843 		    ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   6844 		    ss->ssl3.platformClientKey = (PlatformKey)NULL;
   6845 		}
   6846 		goto send_no_certificate;
   6847 	    }
   6848 	    if (isTLS12) {
   6849 		ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
   6850 	    }
   6851 	    break;  /* not an error */
   6852 	}
   6853 #endif   /* NSS_PLATFORM_CLIENT_AUTH */
   6854         /* check what the callback function returned */
   6855         if ((!ss->ssl3.clientCertificate) || (!ss->ssl3.clientPrivateKey)) {
   6856             /* we are missing either the key or cert */
   6857             if (ss->ssl3.clientCertificate) {
   6858                 /* got a cert, but no key - free it */
   6859                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   6860                 ss->ssl3.clientCertificate = NULL;
   6861             }
   6862             if (ss->ssl3.clientPrivateKey) {
   6863                 /* got a key, but no cert - free it */
   6864                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   6865                 ss->ssl3.clientPrivateKey = NULL;
   6866             }
   6867             goto send_no_certificate;
   6868         }
   6869 	/* Setting ssl3.clientCertChain non-NULL will cause
   6870 	 * ssl3_HandleServerHelloDone to call SendCertificate.
   6871 	 */
   6872 	ss->ssl3.clientCertChain = CERT_CertChainFromCert(
   6873 					ss->ssl3.clientCertificate,
   6874 					certUsageSSLClient, PR_FALSE);
   6875 	if (ss->ssl3.clientCertChain == NULL) {
   6876 	    if (ss->ssl3.clientCertificate != NULL) {
   6877 		CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   6878 		ss->ssl3.clientCertificate = NULL;
   6879 	    }
   6880 	    if (ss->ssl3.clientPrivateKey != NULL) {
   6881 		SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   6882 		ss->ssl3.clientPrivateKey = NULL;
   6883 	    }
   6884 	    goto send_no_certificate;
   6885 	}
   6886 	if (isTLS12) {
   6887 	    ssl3_DestroyBackupHandshakeHashIfNotNeeded(ss, &algorithms);
   6888 	}
   6889 	break;	/* not an error */
   6890 
   6891     case SECFailure:
   6892     default:
   6893 send_no_certificate:
   6894 	if (isTLS) {
   6895 	    ss->ssl3.sendEmptyCert = PR_TRUE;
   6896 	} else {
   6897 	    (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
   6898 	}
   6899 	rv = SECSuccess;
   6900 	break;
   6901     }
   6902     goto done;
   6903 
   6904 no_mem:
   6905     rv = SECFailure;
   6906     PORT_SetError(SEC_ERROR_NO_MEMORY);
   6907     goto done;
   6908 
   6909 alert_loser:
   6910     if (isTLS && desc == illegal_parameter)
   6911     	desc = decode_error;
   6912     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   6913 loser:
   6914     PORT_SetError(errCode);
   6915     rv = SECFailure;
   6916 done:
   6917     ss->requestedCertTypes = NULL;
   6918     if (arena != NULL)
   6919     	PORT_FreeArena(arena, PR_FALSE);
   6920 #ifdef NSS_PLATFORM_CLIENT_AUTH
   6921     if (platform_cert_list)
   6922         CERT_DestroyCertList(platform_cert_list);
   6923 #endif
   6924     return rv;
   6925 }
   6926 
   6927 /*
   6928  * attempt to restart the handshake after asynchronously handling
   6929  * a request for the client's certificate.
   6930  *
   6931  * inputs:
   6932  *	cert	Client cert chosen by application.
   6933  *		Note: ssl takes this reference, and does not bump the
   6934  *		reference count.  The caller should drop its reference
   6935  *		without calling CERT_DestroyCert after calling this function.
   6936  *
   6937  *	key	Private key associated with cert.  This function takes
   6938  *		ownership of the private key, so the caller should drop its
   6939  *		reference without destroying the private key after this
   6940  *		function returns.
   6941  *
   6942  *	certChain  DER-encoded certs, client cert and its signers.
   6943  *		Note: ssl takes this reference, and does not copy the chain.
   6944  *		The caller should drop its reference without destroying the
   6945  *		chain.  SSL will free the chain when it is done with it.
   6946  *
   6947  * Return value: XXX
   6948  *
   6949  * XXX This code only works on the initial handshake on a connection, XXX
   6950  *     It does not work on a subsequent handshake (redo).
   6951  *
   6952  * Caller holds 1stHandshakeLock.
   6953  */
   6954 SECStatus
   6955 ssl3_RestartHandshakeAfterCertReq(sslSocket *         ss,
   6956 				CERTCertificate *    cert,
   6957 				SECKEYPrivateKey *   key,
   6958 				CERTCertificateList *certChain)
   6959 {
   6960     SECStatus        rv          = SECSuccess;
   6961 
   6962     /* XXX This code only works on the initial handshake on a connection,
   6963     ** XXX It does not work on a subsequent handshake (redo).
   6964     */
   6965     if (ss->handshake != 0) {
   6966 	ss->handshake              = ssl_GatherRecord1stHandshake;
   6967 	ss->ssl3.clientCertificate = cert;
   6968 	ss->ssl3.clientPrivateKey  = key;
   6969 	ss->ssl3.clientCertChain   = certChain;
   6970         if (!cert || !key || !certChain) {
   6971             /* we are missing the key, cert, or cert chain */
   6972             if (ss->ssl3.clientCertificate) {
   6973                 CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   6974                 ss->ssl3.clientCertificate = NULL;
   6975             }
   6976             if (ss->ssl3.clientPrivateKey) {
   6977                 SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   6978                 ss->ssl3.clientPrivateKey = NULL;
   6979             }
   6980             if (ss->ssl3.clientCertChain != NULL) {
   6981                 CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
   6982                 ss->ssl3.clientCertChain = NULL;
   6983             }
   6984             if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) {
   6985                 ss->ssl3.sendEmptyCert = PR_TRUE;
   6986             } else {
   6987                 (void)SSL3_SendAlert(ss, alert_warning, no_certificate);
   6988             }
   6989 	}
   6990     } else {
   6991 	if (cert) {
   6992 	    CERT_DestroyCertificate(cert);
   6993 	}
   6994 	if (key) {
   6995 	    SECKEY_DestroyPrivateKey(key);
   6996 	}
   6997 	if (certChain) {
   6998 	    CERT_DestroyCertificateList(certChain);
   6999 	}
   7000 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   7001 	rv = SECFailure;
   7002     }
   7003     return rv;
   7004 }
   7005 
   7006 PRBool
   7007 ssl3_CanFalseStart(sslSocket *ss) {
   7008     PRBool rv;
   7009 
   7010     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7011 
   7012     /* XXX: does not take into account whether we are waiting for
   7013      * SSL_AuthCertificateComplete or SSL_RestartHandshakeAfterCertReq. If/when
   7014      * that is done, this function could return different results each time it
   7015      * would be called.
   7016      */
   7017 
   7018     ssl_GetSpecReadLock(ss);
   7019     rv = ss->opt.enableFalseStart &&
   7020 	 !ss->sec.isServer &&
   7021 	 !ss->ssl3.hs.isResuming &&
   7022 	 ss->ssl3.cwSpec &&
   7023 
   7024 	 /* An attacker can control the selected ciphersuite so we only wish to
   7025 	  * do False Start in the case that the selected ciphersuite is
   7026 	  * sufficiently strong that the attack can gain no advantage.
   7027 	  * Therefore we require an 80-bit cipher and a forward-secret key
   7028 	  * exchange. */
   7029 	 ss->ssl3.cwSpec->cipher_def->secret_key_size >= 10 &&
   7030 	(ss->ssl3.hs.kea_def->kea == kea_dhe_dss ||
   7031 	 ss->ssl3.hs.kea_def->kea == kea_dhe_rsa ||
   7032 	 ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
   7033 	 ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa);
   7034     ssl_ReleaseSpecReadLock(ss);
   7035     return rv;
   7036 }
   7037 
   7038 static SECStatus ssl3_SendClientSecondRound(sslSocket *ss);
   7039 
   7040 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   7041  * ssl3 Server Hello Done message.
   7042  * Caller must hold Handshake and RecvBuf locks.
   7043  */
   7044 static SECStatus
   7045 ssl3_HandleServerHelloDone(sslSocket *ss)
   7046 {
   7047     SECStatus     rv;
   7048     SSL3WaitState ws          = ss->ssl3.hs.ws;
   7049 
   7050     SSL_TRC(3, ("%d: SSL3[%d]: handle server_hello_done handshake",
   7051 		SSL_GETPID(), ss->fd));
   7052     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7053     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7054 
   7055     if (ws != wait_hello_done  &&
   7056         ws != wait_server_cert &&
   7057 	ws != wait_server_key  &&
   7058 	ws != wait_cert_request) {
   7059 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   7060 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
   7061 	return SECFailure;
   7062     }
   7063 
   7064     rv = ssl3_SendClientSecondRound(ss);
   7065 
   7066     return rv;
   7067 }
   7068 
   7069 /* Called from ssl3_HandleServerHelloDone and ssl3_AuthCertificateComplete.
   7070  *
   7071  * Caller must hold Handshake and RecvBuf locks.
   7072  */
   7073 static SECStatus
   7074 ssl3_SendClientSecondRound(sslSocket *ss)
   7075 {
   7076     SECStatus rv;
   7077     PRBool sendClientCert;
   7078 
   7079     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7080     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7081 
   7082     sendClientCert = !ss->ssl3.sendEmptyCert &&
   7083 		     ss->ssl3.clientCertChain  != NULL &&
   7084 		     (ss->ssl3.platformClientKey ||
   7085 		     ss->ssl3.clientPrivateKey != NULL);
   7086 
   7087     if (!sendClientCert &&
   7088 	ss->ssl3.hs.hashType == handshake_hash_single && ss->ssl3.hs.md5) {
   7089 	/* Don't need the backup handshake hash. */
   7090 	PK11_DestroyContext(ss->ssl3.hs.md5, PR_TRUE);
   7091 	ss->ssl3.hs.md5 = NULL;
   7092     }
   7093 
   7094     /* We must wait for the server's certificate to be authenticated before
   7095      * sending the client certificate in order to disclosing the client
   7096      * certificate to an attacker that does not have a valid cert for the
   7097      * domain we are connecting to.
   7098      *
   7099      * XXX: We should do the same for the NPN extension, but for that we
   7100      * need an option to give the application the ability to leak the NPN
   7101      * information to get better performance.
   7102      *
   7103      * During the initial handshake on a connection, we never send/receive
   7104      * application data until we have authenticated the server's certificate;
   7105      * i.e. we have fully authenticated the handshake before using the cipher
   7106      * specs agreed upon for that handshake. During a renegotiation, we may
   7107      * continue sending and receiving application data during the handshake
   7108      * interleaved with the handshake records. If we were to send the client's
   7109      * second round for a renegotiation before the server's certificate was
   7110      * authenticated, then the application data sent/received after this point
   7111      * would be using cipher spec that hadn't been authenticated. By waiting
   7112      * until the server's certificate has been authenticated during
   7113      * renegotiations, we ensure that renegotiations have the same property
   7114      * as initial handshakes; i.e. we have fully authenticated the handshake
   7115      * before using the cipher specs agreed upon for that handshake for
   7116      * application data.
   7117      */
   7118     if (ss->ssl3.hs.restartTarget) {
   7119 	PR_NOT_REACHED("unexpected ss->ssl3.hs.restartTarget");
   7120 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   7121 	return SECFailure;
   7122     }
   7123     if (ss->ssl3.hs.authCertificatePending &&
   7124 	(sendClientCert || ss->ssl3.sendEmptyCert || ss->firstHsDone)) {
   7125 	ss->ssl3.hs.restartTarget = ssl3_SendClientSecondRound;
   7126 	return SECWouldBlock;
   7127     }
   7128 
   7129     ssl_GetXmitBufLock(ss);		/*******************************/
   7130 
   7131     if (ss->ssl3.sendEmptyCert) {
   7132 	ss->ssl3.sendEmptyCert = PR_FALSE;
   7133 	rv = ssl3_SendEmptyCertificate(ss);
   7134 	/* Don't send verify */
   7135 	if (rv != SECSuccess) {
   7136 	    goto loser;	/* error code is set. */
   7137     	}
   7138     } else if (sendClientCert) {
   7139 	rv = ssl3_SendCertificate(ss);
   7140 	if (rv != SECSuccess) {
   7141 	    goto loser;	/* error code is set. */
   7142     	}
   7143     }
   7144 
   7145     rv = ssl3_SendClientKeyExchange(ss);
   7146     if (rv != SECSuccess) {
   7147     	goto loser;	/* err is set. */
   7148     }
   7149 
   7150     if (sendClientCert) {
   7151 	rv = ssl3_SendCertificateVerify(ss);
   7152 	if (rv != SECSuccess) {
   7153 	    goto loser;	/* err is set. */
   7154         }
   7155     }
   7156 
   7157     rv = ssl3_SendChangeCipherSpecs(ss);
   7158     if (rv != SECSuccess) {
   7159 	goto loser;	/* err code was set. */
   7160     }
   7161 
   7162     /* XXX: If the server's certificate hasn't been authenticated by this
   7163      * point, then we may be leaking this NPN message to an attacker.
   7164      */
   7165     if (!ss->firstHsDone) {
   7166 	rv = ssl3_SendNextProto(ss);
   7167 	if (rv != SECSuccess) {
   7168 	    goto loser;	/* err code was set. */
   7169 	}
   7170     }
   7171     rv = ssl3_SendEncryptedExtensions(ss);
   7172     if (rv != SECSuccess) {
   7173 	goto loser; /* err code was set. */
   7174     }
   7175 
   7176     rv = ssl3_SendFinished(ss, 0);
   7177     if (rv != SECSuccess) {
   7178 	goto loser;	/* err code was set. */
   7179     }
   7180 
   7181     ssl_ReleaseXmitBufLock(ss);		/*******************************/
   7182 
   7183     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn))
   7184 	ss->ssl3.hs.ws = wait_new_session_ticket;
   7185     else
   7186 	ss->ssl3.hs.ws = wait_change_cipher;
   7187 
   7188     /* Do the handshake callback for sslv3 here, if we can false start. */
   7189     if (ss->handshakeCallback != NULL && ssl3_CanFalseStart(ss)) {
   7190 	(ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
   7191     }
   7192 
   7193     return SECSuccess;
   7194 
   7195 loser:
   7196     ssl_ReleaseXmitBufLock(ss);
   7197     return rv;
   7198 }
   7199 
   7200 /*
   7201  * Routines used by servers
   7202  */
   7203 static SECStatus
   7204 ssl3_SendHelloRequest(sslSocket *ss)
   7205 {
   7206     SECStatus rv;
   7207 
   7208     SSL_TRC(3, ("%d: SSL3[%d]: send hello_request handshake", SSL_GETPID(),
   7209 		ss->fd));
   7210 
   7211     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7212     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   7213 
   7214     rv = ssl3_AppendHandshakeHeader(ss, hello_request, 0);
   7215     if (rv != SECSuccess) {
   7216 	return rv;	/* err set by AppendHandshake */
   7217     }
   7218     rv = ssl3_FlushHandshake(ss, 0);
   7219     if (rv != SECSuccess) {
   7220 	return rv;	/* error code set by ssl3_FlushHandshake */
   7221     }
   7222     ss->ssl3.hs.ws = wait_client_hello;
   7223     return SECSuccess;
   7224 }
   7225 
   7226 /*
   7227  * Called from:
   7228  *	ssl3_HandleClientHello()
   7229  */
   7230 static SECComparison
   7231 ssl3_ServerNameCompare(const SECItem *name1, const SECItem *name2)
   7232 {
   7233     if (!name1 != !name2) {
   7234         return SECLessThan;
   7235     }
   7236     if (!name1) {
   7237         return SECEqual;
   7238     }
   7239     if (name1->type != name2->type) {
   7240         return SECLessThan;
   7241     }
   7242     return SECITEM_CompareItem(name1, name2);
   7243 }
   7244 
   7245 /* Sets memory error when returning NULL.
   7246  * Called from:
   7247  *	ssl3_SendClientHello()
   7248  *	ssl3_HandleServerHello()
   7249  *	ssl3_HandleClientHello()
   7250  *	ssl3_HandleV2ClientHello()
   7251  */
   7252 sslSessionID *
   7253 ssl3_NewSessionID(sslSocket *ss, PRBool is_server)
   7254 {
   7255     sslSessionID *sid;
   7256 
   7257     sid = PORT_ZNew(sslSessionID);
   7258     if (sid == NULL)
   7259     	return sid;
   7260 
   7261     if (is_server) {
   7262         const SECItem *  srvName;
   7263         SECStatus        rv = SECSuccess;
   7264 
   7265         ssl_GetSpecReadLock(ss);	/********************************/
   7266         srvName = &ss->ssl3.prSpec->srvVirtName;
   7267         if (srvName->len && srvName->data) {
   7268             rv = SECITEM_CopyItem(NULL, &sid->u.ssl3.srvName, srvName);
   7269         }
   7270         ssl_ReleaseSpecReadLock(ss); /************************************/
   7271         if (rv != SECSuccess) {
   7272             PORT_Free(sid);
   7273             return NULL;
   7274         }
   7275     }
   7276     sid->peerID		= (ss->peerID == NULL) ? NULL : PORT_Strdup(ss->peerID);
   7277     sid->urlSvrName	= (ss->url    == NULL) ? NULL : PORT_Strdup(ss->url);
   7278     sid->addr           = ss->sec.ci.peer;
   7279     sid->port           = ss->sec.ci.port;
   7280     sid->references     = 1;
   7281     sid->cached         = never_cached;
   7282     sid->version        = ss->version;
   7283 
   7284     sid->u.ssl3.keys.resumable = PR_TRUE;
   7285     sid->u.ssl3.policy         = SSL_ALLOWED;
   7286     sid->u.ssl3.clientWriteKey = NULL;
   7287     sid->u.ssl3.serverWriteKey = NULL;
   7288 
   7289     if (is_server) {
   7290 	SECStatus rv;
   7291 	int       pid = SSL_GETPID();
   7292 
   7293 	sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
   7294 	sid->u.ssl3.sessionID[0]    = (pid >> 8) & 0xff;
   7295 	sid->u.ssl3.sessionID[1]    =  pid       & 0xff;
   7296 	rv = PK11_GenerateRandom(sid->u.ssl3.sessionID + 2,
   7297 	                         SSL3_SESSIONID_BYTES -2);
   7298 	if (rv != SECSuccess) {
   7299 	    ssl_FreeSID(sid);
   7300 	    ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
   7301 	    return NULL;
   7302     	}
   7303     }
   7304     return sid;
   7305 }
   7306 
   7307 /* Called from:  ssl3_HandleClientHello, ssl3_HandleV2ClientHello */
   7308 static SECStatus
   7309 ssl3_SendServerHelloSequence(sslSocket *ss)
   7310 {
   7311     const ssl3KEADef *kea_def;
   7312     SECStatus         rv;
   7313 
   7314     SSL_TRC(3, ("%d: SSL3[%d]: begin send server_hello sequence",
   7315 		SSL_GETPID(), ss->fd));
   7316 
   7317     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   7318     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss) );
   7319 
   7320     rv = ssl3_SendServerHello(ss);
   7321     if (rv != SECSuccess) {
   7322 	return rv;	/* err code is set. */
   7323     }
   7324     rv = ssl3_SendCertificate(ss);
   7325     if (rv != SECSuccess) {
   7326 	return rv;	/* error code is set. */
   7327     }
   7328     rv = ssl3_SendCertificateStatus(ss);
   7329     if (rv != SECSuccess) {
   7330 	return rv;	/* error code is set. */
   7331     }
   7332     /* We have to do this after the call to ssl3_SendServerHello,
   7333      * because kea_def is set up by ssl3_SendServerHello().
   7334      */
   7335     kea_def = ss->ssl3.hs.kea_def;
   7336     ss->ssl3.hs.usedStepDownKey = PR_FALSE;
   7337 
   7338     if (kea_def->is_limited && kea_def->exchKeyType == kt_rsa) {
   7339 	/* see if we can legally use the key in the cert. */
   7340 	int keyLen;  /* bytes */
   7341 
   7342 	keyLen = PK11_GetPrivateModulusLen(
   7343 			    ss->serverCerts[kea_def->exchKeyType].SERVERKEY);
   7344 
   7345 	if (keyLen > 0 &&
   7346 	    keyLen * BPB <= kea_def->key_size_limit ) {
   7347 	    /* XXX AND cert is not signing only!! */
   7348 	    /* just fall through and use it. */
   7349 	} else if (ss->stepDownKeyPair != NULL) {
   7350 	    ss->ssl3.hs.usedStepDownKey = PR_TRUE;
   7351 	    rv = ssl3_SendServerKeyExchange(ss);
   7352 	    if (rv != SECSuccess) {
   7353 		return rv;	/* err code was set. */
   7354 	    }
   7355 	} else {
   7356 #ifndef HACKED_EXPORT_SERVER
   7357 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
   7358 	    return rv;
   7359 #endif
   7360 	}
   7361 #ifdef NSS_ENABLE_ECC
   7362     } else if ((kea_def->kea == kea_ecdhe_rsa) ||
   7363 	       (kea_def->kea == kea_ecdhe_ecdsa)) {
   7364 	rv = ssl3_SendServerKeyExchange(ss);
   7365 	if (rv != SECSuccess) {
   7366 	    return rv;	/* err code was set. */
   7367 	}
   7368 #endif /* NSS_ENABLE_ECC */
   7369     }
   7370 
   7371     if (ss->opt.requestCertificate) {
   7372 	rv = ssl3_SendCertificateRequest(ss);
   7373 	if (rv != SECSuccess) {
   7374 	    return rv;		/* err code is set. */
   7375 	}
   7376     }
   7377     rv = ssl3_SendServerHelloDone(ss);
   7378     if (rv != SECSuccess) {
   7379 	return rv;		/* err code is set. */
   7380     }
   7381 
   7382     ss->ssl3.hs.ws = (ss->opt.requestCertificate) ? wait_client_cert
   7383                                                : wait_client_key;
   7384     return SECSuccess;
   7385 }
   7386 
   7387 /* An empty TLS Renegotiation Info (RI) extension */
   7388 static const PRUint8 emptyRIext[5] = {0xff, 0x01, 0x00, 0x01, 0x00};
   7389 
   7390 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   7391  * ssl3 Client Hello message.
   7392  * Caller must hold Handshake and RecvBuf locks.
   7393  */
   7394 static SECStatus
   7395 ssl3_HandleClientHello(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   7396 {
   7397     sslSessionID *      sid      = NULL;
   7398     PRInt32		tmp;
   7399     unsigned int        i;
   7400     int                 j;
   7401     SECStatus           rv;
   7402     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
   7403     SSL3AlertDescription desc    = illegal_parameter;
   7404     SSL3AlertLevel      level    = alert_fatal;
   7405     SSL3ProtocolVersion version;
   7406     SECItem             sidBytes = {siBuffer, NULL, 0};
   7407     SECItem             cookieBytes = {siBuffer, NULL, 0};
   7408     SECItem             suites   = {siBuffer, NULL, 0};
   7409     SECItem             comps    = {siBuffer, NULL, 0};
   7410     PRBool              haveSpecWriteLock = PR_FALSE;
   7411     PRBool              haveXmitBufLock   = PR_FALSE;
   7412 
   7413     SSL_TRC(3, ("%d: SSL3[%d]: handle client_hello handshake",
   7414     	SSL_GETPID(), ss->fd));
   7415 
   7416     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   7417     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   7418     PORT_Assert( ss->ssl3.initialized );
   7419 
   7420     /* Get peer name of client */
   7421     rv = ssl_GetPeerInfo(ss);
   7422     if (rv != SECSuccess) {
   7423 	return rv;		/* error code is set. */
   7424     }
   7425 
   7426     /* Clearing the handshake pointers so that ssl_Do1stHandshake won't
   7427      * call ssl2_HandleMessage.
   7428      *
   7429      * The issue here is that TLS ordinarily starts out in
   7430      * ssl2_HandleV3HandshakeRecord() because of the backward-compatibility
   7431      * code paths. That function zeroes these next pointers. But with DTLS,
   7432      * we don't even try to do the v2 ClientHello so we skip that function
   7433      * and need to reset these values here.
   7434      */
   7435     if (IS_DTLS(ss)) {
   7436 	ss->nextHandshake     = 0;
   7437 	ss->securityHandshake = 0;
   7438     }
   7439 
   7440     /* We might be starting session renegotiation in which case we should
   7441      * clear previous state.
   7442      */
   7443     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   7444     ss->statelessResume = PR_FALSE;
   7445 
   7446     if ((ss->ssl3.hs.ws != wait_client_hello) &&
   7447 	(ss->ssl3.hs.ws != idle_handshake)) {
   7448 	desc    = unexpected_message;
   7449 	errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
   7450 	goto alert_loser;
   7451     }
   7452     if (ss->ssl3.hs.ws == idle_handshake  &&
   7453         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
   7454 	desc    = no_renegotiation;
   7455 	level   = alert_warning;
   7456 	errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
   7457 	goto alert_loser;
   7458     }
   7459 
   7460     if (IS_DTLS(ss)) {
   7461 	dtls_RehandshakeCleanup(ss);
   7462     }
   7463 
   7464     tmp = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   7465     if (tmp < 0)
   7466 	goto loser;		/* malformed, alert already sent */
   7467 
   7468     /* Translate the version */
   7469     if (IS_DTLS(ss)) {
   7470 	ss->clientHelloVersion = version =
   7471 	    dtls_DTLSVersionToTLSVersion((SSL3ProtocolVersion)tmp);
   7472     } else {
   7473 	ss->clientHelloVersion = version = (SSL3ProtocolVersion)tmp;
   7474     }
   7475 
   7476     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
   7477     if (rv != SECSuccess) {
   7478     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version
   7479 	                                           : handshake_failure;
   7480 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   7481 	goto alert_loser;
   7482     }
   7483 
   7484     rv = ssl3_InitHandshakeHashes(ss);
   7485     if (rv != SECSuccess) {
   7486 	desc = internal_error;
   7487 	errCode = PORT_GetError();
   7488 	goto alert_loser;
   7489     }
   7490 
   7491     /* grab the client random data. */
   7492     rv = ssl3_ConsumeHandshake(
   7493 	ss, &ss->ssl3.hs.client_random, SSL3_RANDOM_LENGTH, &b, &length);
   7494     if (rv != SECSuccess) {
   7495 	goto loser;		/* malformed */
   7496     }
   7497 
   7498     /* grab the client's SID, if present. */
   7499     rv = ssl3_ConsumeHandshakeVariable(ss, &sidBytes, 1, &b, &length);
   7500     if (rv != SECSuccess) {
   7501 	goto loser;		/* malformed */
   7502     }
   7503 
   7504     /* grab the client's cookie, if present. */
   7505     if (IS_DTLS(ss)) {
   7506 	rv = ssl3_ConsumeHandshakeVariable(ss, &cookieBytes, 1, &b, &length);
   7507 	if (rv != SECSuccess) {
   7508 	    goto loser;		/* malformed */
   7509 	}
   7510     }
   7511 
   7512     /* grab the list of cipher suites. */
   7513     rv = ssl3_ConsumeHandshakeVariable(ss, &suites, 2, &b, &length);
   7514     if (rv != SECSuccess) {
   7515 	goto loser;		/* malformed */
   7516     }
   7517 
   7518     /* grab the list of compression methods. */
   7519     rv = ssl3_ConsumeHandshakeVariable(ss, &comps, 1, &b, &length);
   7520     if (rv != SECSuccess) {
   7521 	goto loser;		/* malformed */
   7522     }
   7523 
   7524     desc = handshake_failure;
   7525 
   7526     /* Handle TLS hello extensions for SSL3 & TLS. We do not know if
   7527      * we are restarting a previous session until extensions have been
   7528      * parsed, since we might have received a SessionTicket extension.
   7529      * Note: we allow extensions even when negotiating SSL3 for the sake
   7530      * of interoperability (and backwards compatibility).
   7531      */
   7532 
   7533     if (length) {
   7534 	/* Get length of hello extensions */
   7535 	PRInt32 extension_length;
   7536 	extension_length = ssl3_ConsumeHandshakeNumber(ss, 2, &b, &length);
   7537 	if (extension_length < 0) {
   7538 	    goto loser;				/* alert already sent */
   7539 	}
   7540 	if (extension_length != length) {
   7541 	    ssl3_DecodeError(ss);		/* send alert */
   7542 	    goto loser;
   7543 	}
   7544 	rv = ssl3_HandleHelloExtensions(ss, &b, &length);
   7545 	if (rv != SECSuccess) {
   7546 	    goto loser;		/* malformed */
   7547 	}
   7548     }
   7549     if (!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   7550     	/* If we didn't receive an RI extension, look for the SCSV,
   7551 	 * and if found, treat it just like an empty RI extension
   7552 	 * by processing a local copy of an empty RI extension.
   7553 	 */
   7554 	for (i = 0; i + 1 < suites.len; i += 2) {
   7555 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   7556 	    if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
   7557 		SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
   7558 		PRUint32     L2 = sizeof emptyRIext;
   7559 		(void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
   7560 	    	break;
   7561 	    }
   7562 	}
   7563     }
   7564     if (ss->firstHsDone &&
   7565         (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_REQUIRES_XTN ||
   7566         ss->opt.enableRenegotiation == SSL_RENEGOTIATE_TRANSITIONAL) &&
   7567 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   7568 	desc    = no_renegotiation;
   7569 	level   = alert_warning;
   7570 	errCode = SSL_ERROR_RENEGOTIATION_NOT_ALLOWED;
   7571 	goto alert_loser;
   7572     }
   7573     if ((ss->opt.requireSafeNegotiation ||
   7574          (ss->firstHsDone && ss->peerRequestedProtection)) &&
   7575 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   7576 	desc = handshake_failure;
   7577 	errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
   7578     	goto alert_loser;
   7579     }
   7580 
   7581     /* We do stateful resumes only if either of the following
   7582      * conditions are satisfied: (1) the client does not support the
   7583      * session ticket extension, or (2) the client support the session
   7584      * ticket extension, but sent an empty ticket.
   7585      */
   7586     if (!ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) ||
   7587 	ss->xtnData.emptySessionTicket) {
   7588 	if (sidBytes.len > 0 && !ss->opt.noCache) {
   7589 	    SSL_TRC(7, ("%d: SSL3[%d]: server, lookup client session-id for 0x%08x%08x%08x%08x",
   7590 			SSL_GETPID(), ss->fd, ss->sec.ci.peer.pr_s6_addr32[0],
   7591 			ss->sec.ci.peer.pr_s6_addr32[1],
   7592 			ss->sec.ci.peer.pr_s6_addr32[2],
   7593 			ss->sec.ci.peer.pr_s6_addr32[3]));
   7594 	    if (ssl_sid_lookup) {
   7595 		sid = (*ssl_sid_lookup)(&ss->sec.ci.peer, sidBytes.data,
   7596 					sidBytes.len, ss->dbHandle);
   7597 	    } else {
   7598 		errCode = SSL_ERROR_SERVER_CACHE_NOT_CONFIGURED;
   7599 		goto loser;
   7600 	    }
   7601 	}
   7602     } else if (ss->statelessResume) {
   7603 	/* Fill in the client's session ID if doing a stateless resume.
   7604 	 * (When doing stateless resumes, server echos client's SessionID.)
   7605 	 */
   7606 	sid = ss->sec.ci.sid;
   7607 	PORT_Assert(sid != NULL);  /* Should have already been filled in.*/
   7608 
   7609 	if (sidBytes.len > 0 && sidBytes.len <= SSL3_SESSIONID_BYTES) {
   7610 	    sid->u.ssl3.sessionIDLength = sidBytes.len;
   7611 	    PORT_Memcpy(sid->u.ssl3.sessionID, sidBytes.data,
   7612 		sidBytes.len);
   7613 	    sid->u.ssl3.sessionIDLength = sidBytes.len;
   7614 	} else {
   7615 	    sid->u.ssl3.sessionIDLength = 0;
   7616 	}
   7617 	ss->sec.ci.sid = NULL;
   7618     }
   7619 
   7620     /* We only send a session ticket extension if the client supports
   7621      * the extension and we are unable to do either a stateful or
   7622      * stateless resume.
   7623      *
   7624      * TODO: send a session ticket if performing a stateful
   7625      * resumption.  (As per RFC4507, a server may issue a session
   7626      * ticket while doing a (stateless or stateful) session resume,
   7627      * but OpenSSL-0.9.8g does not accept session tickets while
   7628      * resuming.)
   7629      */
   7630     if (ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn) && sid == NULL) {
   7631 	ssl3_RegisterServerHelloExtensionSender(ss,
   7632 	    ssl_session_ticket_xtn, ssl3_SendSessionTicketXtn);
   7633     }
   7634 
   7635     if (sid != NULL) {
   7636 	/* We've found a session cache entry for this client.
   7637 	 * Now, if we're going to require a client-auth cert,
   7638 	 * and we don't already have this client's cert in the session cache,
   7639 	 * and this is the first handshake on this connection (not a redo),
   7640 	 * then drop this old cache entry and start a new session.
   7641 	 */
   7642 	if ((sid->peerCert == NULL) && ss->opt.requestCertificate &&
   7643 	    ((ss->opt.requireCertificate == SSL_REQUIRE_ALWAYS) ||
   7644 	     (ss->opt.requireCertificate == SSL_REQUIRE_NO_ERROR) ||
   7645 	     ((ss->opt.requireCertificate == SSL_REQUIRE_FIRST_HANDSHAKE)
   7646 	      && !ss->firstHsDone))) {
   7647 
   7648 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
   7649 	    if (ss->sec.uncache)
   7650                 ss->sec.uncache(sid);
   7651 	    ssl_FreeSID(sid);
   7652 	    sid = NULL;
   7653 	}
   7654     }
   7655 
   7656 #ifdef NSS_ENABLE_ECC
   7657     /* Disable any ECC cipher suites for which we have no cert. */
   7658     ssl3_FilterECCipherSuitesByServerCerts(ss);
   7659 #endif
   7660 
   7661     if (IS_DTLS(ss)) {
   7662 	ssl3_DisableNonDTLSSuites(ss);
   7663     }
   7664 
   7665 #ifdef PARANOID
   7666     /* Look for a matching cipher suite. */
   7667     j = ssl3_config_match_init(ss);
   7668     if (j <= 0) {		/* no ciphers are working/supported by PK11 */
   7669     	errCode = PORT_GetError();	/* error code is already set. */
   7670 	goto alert_loser;
   7671     }
   7672 #endif
   7673 
   7674     /* If we already have a session for this client, be sure to pick the
   7675     ** same cipher suite and compression method we picked before.
   7676     ** This is not a loop, despite appearances.
   7677     */
   7678     if (sid) do {
   7679 	ssl3CipherSuiteCfg *suite;
   7680 
   7681 	/* Check that the cached compression method is still enabled. */
   7682 	if (!compressionEnabled(ss, sid->u.ssl3.compression))
   7683 	    break;
   7684 
   7685 	/* Check that the cached compression method is in the client's list */
   7686 	for (i = 0; i < comps.len; i++) {
   7687 	    if (comps.data[i] == sid->u.ssl3.compression)
   7688 		break;
   7689 	}
   7690 	if (i == comps.len)
   7691 	    break;
   7692 
   7693 	suite = ss->cipherSuites;
   7694 	/* Find the entry for the cipher suite used in the cached session. */
   7695 	for (j = ssl_V3_SUITES_IMPLEMENTED; j > 0; --j, ++suite) {
   7696 	    if (suite->cipher_suite == sid->u.ssl3.cipherSuite)
   7697 		break;
   7698 	}
   7699 	PORT_Assert(j > 0);
   7700 	if (j <= 0)
   7701 	    break;
   7702 #ifdef PARANOID
   7703 	/* Double check that the cached cipher suite is still enabled,
   7704 	 * implemented, and allowed by policy.  Might have been disabled.
   7705 	 * The product policy won't change during the process lifetime.
   7706 	 * Implemented ("isPresent") shouldn't change for servers.
   7707 	 */
   7708 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE))
   7709 	    break;
   7710 #else
   7711 	if (!suite->enabled)
   7712 	    break;
   7713 #endif
   7714 	/* Double check that the cached cipher suite is in the client's list */
   7715 	for (i = 0; i + 1 < suites.len; i += 2) {
   7716 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   7717 	    if (suite_i == suite->cipher_suite) {
   7718 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
   7719 		ss->ssl3.hs.suite_def =
   7720 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
   7721 
   7722 		/* Use the cached compression method. */
   7723 		ss->ssl3.hs.compression = sid->u.ssl3.compression;
   7724 		goto compression_found;
   7725 	    }
   7726 	}
   7727     } while (0);
   7728 
   7729     /* START A NEW SESSION */
   7730 
   7731 #ifndef PARANOID
   7732     /* Look for a matching cipher suite. */
   7733     j = ssl3_config_match_init(ss);
   7734     if (j <= 0) {		/* no ciphers are working/supported by PK11 */
   7735     	errCode = PORT_GetError();	/* error code is already set. */
   7736 	goto alert_loser;
   7737     }
   7738 #endif
   7739 
   7740     /* Select a cipher suite.
   7741     **
   7742     ** NOTE: This suite selection algorithm should be the same as the one in
   7743     ** ssl3_HandleV2ClientHello().
   7744     **
   7745     ** If TLS 1.0 is enabled, we could handle the case where the client
   7746     ** offered TLS 1.1 but offered only export cipher suites by choosing TLS
   7747     ** 1.0 and selecting one of those export cipher suites. However, a secure
   7748     ** TLS 1.1 client should not have export cipher suites enabled at all,
   7749     ** and a TLS 1.1 client should definitely not be offering *only* export
   7750     ** cipher suites. Therefore, we refuse to negotiate export cipher suites
   7751     ** with any client that indicates support for TLS 1.1 or higher when we
   7752     ** (the server) have TLS 1.1 support enabled.
   7753     */
   7754     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
   7755 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
   7756 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE) ||
   7757 	    !ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
   7758 					       ss->version)) {
   7759 	    continue;
   7760 	}
   7761 	for (i = 0; i + 1 < suites.len; i += 2) {
   7762 	    PRUint16 suite_i = (suites.data[i] << 8) | suites.data[i + 1];
   7763 	    if (suite_i == suite->cipher_suite) {
   7764 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
   7765 		ss->ssl3.hs.suite_def =
   7766 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
   7767 		goto suite_found;
   7768 	    }
   7769 	}
   7770     }
   7771     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   7772     goto alert_loser;
   7773 
   7774 suite_found:
   7775     /* Look for a matching compression algorithm. */
   7776     for (i = 0; i < comps.len; i++) {
   7777 	if (!compressionEnabled(ss, comps.data[i]))
   7778 	    continue;
   7779 	for (j = 0; j < compressionMethodsCount; j++) {
   7780 	    if (comps.data[i] == compressions[j]) {
   7781 		ss->ssl3.hs.compression =
   7782 					(SSLCompressionMethod)compressions[j];
   7783 		goto compression_found;
   7784 	    }
   7785 	}
   7786     }
   7787     errCode = SSL_ERROR_NO_COMPRESSION_OVERLAP;
   7788     				/* null compression must be supported */
   7789     goto alert_loser;
   7790 
   7791 compression_found:
   7792     suites.data = NULL;
   7793     comps.data = NULL;
   7794 
   7795     ss->sec.send = ssl3_SendApplicationData;
   7796 
   7797     /* If there are any failures while processing the old sid,
   7798      * we don't consider them to be errors.  Instead, We just behave
   7799      * as if the client had sent us no sid to begin with, and make a new one.
   7800      */
   7801     if (sid != NULL) do {
   7802 	ssl3CipherSpec *pwSpec;
   7803 	SECItem         wrappedMS;  	/* wrapped key */
   7804 
   7805 	if (sid->version != ss->version  ||
   7806 	    sid->u.ssl3.cipherSuite != ss->ssl3.hs.cipher_suite ||
   7807 	    sid->u.ssl3.compression != ss->ssl3.hs.compression) {
   7808 	    break;	/* not an error */
   7809 	}
   7810 
   7811 	if (ss->sec.ci.sid) {
   7812 	    if (ss->sec.uncache)
   7813                 ss->sec.uncache(ss->sec.ci.sid);
   7814 	    PORT_Assert(ss->sec.ci.sid != sid);  /* should be impossible, but ... */
   7815 	    if (ss->sec.ci.sid != sid) {
   7816 		ssl_FreeSID(ss->sec.ci.sid);
   7817 	    }
   7818 	    ss->sec.ci.sid = NULL;
   7819 	}
   7820 	/* we need to resurrect the master secret.... */
   7821 
   7822 	ssl_GetSpecWriteLock(ss);  haveSpecWriteLock = PR_TRUE;
   7823 	pwSpec = ss->ssl3.pwSpec;
   7824 	if (sid->u.ssl3.keys.msIsWrapped) {
   7825 	    PK11SymKey *    wrapKey; 	/* wrapping key */
   7826 	    CK_FLAGS        keyFlags      = 0;
   7827 #ifndef NO_PKCS11_BYPASS
   7828 	    if (ss->opt.bypassPKCS11) {
   7829 		/* we cannot restart a non-bypass session in a
   7830 		** bypass socket.
   7831 		*/
   7832 		break;
   7833 	    }
   7834 #endif
   7835 
   7836 	    wrapKey = getWrappingKey(ss, NULL, sid->u.ssl3.exchKeyType,
   7837 				     sid->u.ssl3.masterWrapMech,
   7838 				     ss->pkcs11PinArg);
   7839 	    if (!wrapKey) {
   7840 		/* we have a SID cache entry, but no wrapping key for it??? */
   7841 		break;
   7842 	    }
   7843 
   7844 	    if (ss->version > SSL_LIBRARY_VERSION_3_0) {	/* isTLS */
   7845 		keyFlags = CKF_SIGN | CKF_VERIFY;
   7846 	    }
   7847 
   7848 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   7849 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   7850 
   7851 	    /* unwrap the master secret. */
   7852 	    pwSpec->master_secret =
   7853 		PK11_UnwrapSymKeyWithFlags(wrapKey, sid->u.ssl3.masterWrapMech,
   7854 			    NULL, &wrappedMS, CKM_SSL3_MASTER_KEY_DERIVE,
   7855 			    CKA_DERIVE, sizeof(SSL3MasterSecret), keyFlags);
   7856 	    PK11_FreeSymKey(wrapKey);
   7857 	    if (pwSpec->master_secret == NULL) {
   7858 		break;	/* not an error */
   7859 	    }
   7860 #ifndef NO_PKCS11_BYPASS
   7861 	} else if (ss->opt.bypassPKCS11) {
   7862 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   7863 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   7864 	    memcpy(pwSpec->raw_master_secret, wrappedMS.data, wrappedMS.len);
   7865 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   7866 	    pwSpec->msItem.len  = wrappedMS.len;
   7867 #endif
   7868 	} else {
   7869 	    /* We CAN restart a bypass session in a non-bypass socket. */
   7870 	    /* need to import the raw master secret to session object */
   7871 	    PK11SlotInfo * slot;
   7872 	    wrappedMS.data = sid->u.ssl3.keys.wrapped_master_secret;
   7873 	    wrappedMS.len  = sid->u.ssl3.keys.wrapped_master_secret_len;
   7874 	    slot = PK11_GetInternalSlot();
   7875 	    pwSpec->master_secret =
   7876 		PK11_ImportSymKey(slot, CKM_SSL3_MASTER_KEY_DERIVE,
   7877 				  PK11_OriginUnwrap, CKA_ENCRYPT, &wrappedMS,
   7878 				  NULL);
   7879 	    PK11_FreeSlot(slot);
   7880 	    if (pwSpec->master_secret == NULL) {
   7881 		break;	/* not an error */
   7882 	    }
   7883 	}
   7884 	ss->sec.ci.sid = sid;
   7885 	if (sid->peerCert != NULL) {
   7886 	    ss->sec.peerCert = CERT_DupCertificate(sid->peerCert);
   7887 	    ssl3_CopyPeerCertsFromSID(ss, sid);
   7888 	}
   7889 
   7890 	/*
   7891 	 * Old SID passed all tests, so resume this old session.
   7892 	 *
   7893 	 * XXX make sure compression still matches
   7894 	 */
   7895 	SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_hits );
   7896 	if (ss->statelessResume)
   7897 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_stateless_resumes );
   7898 	ss->ssl3.hs.isResuming = PR_TRUE;
   7899 
   7900         ss->sec.authAlgorithm = sid->authAlgorithm;
   7901 	ss->sec.authKeyBits   = sid->authKeyBits;
   7902 	ss->sec.keaType       = sid->keaType;
   7903 	ss->sec.keaKeyBits    = sid->keaKeyBits;
   7904 
   7905 	/* server sids don't remember the server cert we previously sent,
   7906 	** but they do remember the kea type we originally used, so we
   7907 	** can locate it again, provided that the current ssl socket
   7908 	** has had its server certs configured the same as the previous one.
   7909 	*/
   7910 	ss->sec.localCert     =
   7911 		CERT_DupCertificate(ss->serverCerts[sid->keaType].serverCert);
   7912 
   7913         /* Copy cached name in to pending spec */
   7914         if (sid != NULL &&
   7915             sid->version > SSL_LIBRARY_VERSION_3_0 &&
   7916             sid->u.ssl3.srvName.len && sid->u.ssl3.srvName.data) {
   7917             /* Set server name from sid */
   7918             SECItem *sidName = &sid->u.ssl3.srvName;
   7919             SECItem *pwsName = &ss->ssl3.pwSpec->srvVirtName;
   7920             if (pwsName->data) {
   7921                 SECITEM_FreeItem(pwsName, PR_FALSE);
   7922             }
   7923             rv = SECITEM_CopyItem(NULL, pwsName, sidName);
   7924             if (rv != SECSuccess) {
   7925                 errCode = PORT_GetError();
   7926                 desc = internal_error;
   7927                 goto alert_loser;
   7928             }
   7929         }
   7930 
   7931         /* Clean up sni name array */
   7932         if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn) &&
   7933             ss->xtnData.sniNameArr) {
   7934             PORT_Free(ss->xtnData.sniNameArr);
   7935             ss->xtnData.sniNameArr = NULL;
   7936             ss->xtnData.sniNameArrSize = 0;
   7937         }
   7938 
   7939 	ssl_GetXmitBufLock(ss); haveXmitBufLock = PR_TRUE;
   7940 
   7941 	rv = ssl3_SendServerHello(ss);
   7942 	if (rv != SECSuccess) {
   7943 	    errCode = PORT_GetError();
   7944 	    goto loser;
   7945 	}
   7946 
   7947 	if (haveSpecWriteLock) {
   7948 	    ssl_ReleaseSpecWriteLock(ss);
   7949 	    haveSpecWriteLock = PR_FALSE;
   7950 	}
   7951 
   7952 	/* NULL value for PMS signifies re-use of the old MS */
   7953 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
   7954 	if (rv != SECSuccess) {
   7955 	    errCode = PORT_GetError();
   7956 	    goto loser;
   7957 	}
   7958 
   7959 	rv = ssl3_SendChangeCipherSpecs(ss);
   7960 	if (rv != SECSuccess) {
   7961 	    errCode = PORT_GetError();
   7962 	    goto loser;
   7963 	}
   7964 	rv = ssl3_SendFinished(ss, 0);
   7965 	ss->ssl3.hs.ws = wait_change_cipher;
   7966 	if (rv != SECSuccess) {
   7967 	    errCode = PORT_GetError();
   7968 	    goto loser;
   7969 	}
   7970 
   7971 	if (haveXmitBufLock) {
   7972 	    ssl_ReleaseXmitBufLock(ss);
   7973 	    haveXmitBufLock = PR_FALSE;
   7974 	}
   7975 
   7976         return SECSuccess;
   7977     } while (0);
   7978 
   7979     if (haveSpecWriteLock) {
   7980 	ssl_ReleaseSpecWriteLock(ss);
   7981 	haveSpecWriteLock = PR_FALSE;
   7982     }
   7983 
   7984     if (sid) { 	/* we had a sid, but it's no longer valid, free it */
   7985 	SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
   7986 	if (ss->sec.uncache)
   7987             ss->sec.uncache(sid);
   7988 	ssl_FreeSID(sid);
   7989 	sid = NULL;
   7990     }
   7991     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
   7992 
   7993     if (ssl3_ExtensionNegotiated(ss, ssl_server_name_xtn)) {
   7994         int ret = 0;
   7995         if (ss->sniSocketConfig) do { /* not a loop */
   7996             ret = SSL_SNI_SEND_ALERT;
   7997             /* If extension is negotiated, the len of names should > 0. */
   7998             if (ss->xtnData.sniNameArrSize) {
   7999                 /* Calling client callback to reconfigure the socket. */
   8000                 ret = (SECStatus)(*ss->sniSocketConfig)(ss->fd,
   8001                                          ss->xtnData.sniNameArr,
   8002                                       ss->xtnData.sniNameArrSize,
   8003                                           ss->sniSocketConfigArg);
   8004             }
   8005             if (ret <= SSL_SNI_SEND_ALERT) {
   8006                 /* Application does not know the name or was not able to
   8007                  * properly reconfigure the socket. */
   8008                 errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8009                 desc = unrecognized_name;
   8010                 break;
   8011             } else if (ret == SSL_SNI_CURRENT_CONFIG_IS_USED) {
   8012                 SECStatus       rv = SECSuccess;
   8013                 SECItem *       cwsName, *pwsName;
   8014 
   8015                 ssl_GetSpecWriteLock(ss);  /*******************************/
   8016                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
   8017                 cwsName = &ss->ssl3.cwSpec->srvVirtName;
   8018 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
   8019                 /* not allow name change on the 2d HS */
   8020                 if (ss->firstHsDone) {
   8021                     if (ssl3_ServerNameCompare(pwsName, cwsName)) {
   8022                         ssl_ReleaseSpecWriteLock(ss);  /******************/
   8023                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8024                         desc = handshake_failure;
   8025                         ret = SSL_SNI_SEND_ALERT;
   8026                         break;
   8027                     }
   8028                 }
   8029 #endif
   8030                 if (pwsName->data) {
   8031                     SECITEM_FreeItem(pwsName, PR_FALSE);
   8032                 }
   8033                 if (cwsName->data) {
   8034                     rv = SECITEM_CopyItem(NULL, pwsName, cwsName);
   8035                 }
   8036                 ssl_ReleaseSpecWriteLock(ss);  /**************************/
   8037                 if (rv != SECSuccess) {
   8038                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
   8039                     desc = internal_error;
   8040                     ret = SSL_SNI_SEND_ALERT;
   8041                     break;
   8042                 }
   8043             } else if (ret < ss->xtnData.sniNameArrSize) {
   8044                 /* Application has configured new socket info. Lets check it
   8045                  * and save the name. */
   8046                 SECStatus       rv;
   8047                 SECItem *       name = &ss->xtnData.sniNameArr[ret];
   8048                 int             configedCiphers;
   8049                 SECItem *       pwsName;
   8050 
   8051                 /* get rid of the old name and save the newly picked. */
   8052                 /* This code is protected by ssl3HandshakeLock. */
   8053                 ssl_GetSpecWriteLock(ss);  /*******************************/
   8054 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
   8055                 /* not allow name change on the 2d HS */
   8056                 if (ss->firstHsDone) {
   8057                     SECItem *cwsName = &ss->ssl3.cwSpec->srvVirtName;
   8058                     if (ssl3_ServerNameCompare(name, cwsName)) {
   8059                         ssl_ReleaseSpecWriteLock(ss);  /******************/
   8060                         errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8061                         desc = handshake_failure;
   8062                         ret = SSL_SNI_SEND_ALERT;
   8063                         break;
   8064                     }
   8065                 }
   8066 #endif
   8067                 pwsName = &ss->ssl3.pwSpec->srvVirtName;
   8068                 if (pwsName->data) {
   8069                     SECITEM_FreeItem(pwsName, PR_FALSE);
   8070                 }
   8071                 rv = SECITEM_CopyItem(NULL, pwsName, name);
   8072                 ssl_ReleaseSpecWriteLock(ss);  /***************************/
   8073                 if (rv != SECSuccess) {
   8074                     errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
   8075                     desc = internal_error;
   8076                     ret = SSL_SNI_SEND_ALERT;
   8077                     break;
   8078                 }
   8079                 configedCiphers = ssl3_config_match_init(ss);
   8080                 if (configedCiphers <= 0) {
   8081                     /* no ciphers are working/supported */
   8082                     errCode = PORT_GetError();
   8083                     desc = handshake_failure;
   8084                     ret = SSL_SNI_SEND_ALERT;
   8085                     break;
   8086                 }
   8087                 /* Need to tell the client that application has picked
   8088                  * the name from the offered list and reconfigured the socket.
   8089                  */
   8090                 ssl3_RegisterServerHelloExtensionSender(ss, ssl_server_name_xtn,
   8091                                                         ssl3_SendServerNameXtn);
   8092             } else {
   8093                 /* Callback returned index outside of the boundary. */
   8094                 PORT_Assert(ret < ss->xtnData.sniNameArrSize);
   8095                 errCode = SSL_ERROR_INTERNAL_ERROR_ALERT;
   8096                 desc = internal_error;
   8097                 ret = SSL_SNI_SEND_ALERT;
   8098                 break;
   8099             }
   8100         } while (0);
   8101         /* Free sniNameArr. The data that each SECItem in the array
   8102          * points into is the data from the input buffer "b". It will
   8103          * not be available outside the scope of this or it's child
   8104          * functions.*/
   8105         if (ss->xtnData.sniNameArr) {
   8106             PORT_Free(ss->xtnData.sniNameArr);
   8107             ss->xtnData.sniNameArr = NULL;
   8108             ss->xtnData.sniNameArrSize = 0;
   8109         }
   8110         if (ret <= SSL_SNI_SEND_ALERT) {
   8111             /* desc and errCode should be set. */
   8112             goto alert_loser;
   8113         }
   8114     }
   8115 #ifndef SSL_SNI_ALLOW_NAME_CHANGE_2HS
   8116     else if (ss->firstHsDone) {
   8117         /* Check that we don't have the name is current spec
   8118          * if this extension was not negotiated on the 2d hs. */
   8119         PRBool passed = PR_TRUE;
   8120         ssl_GetSpecReadLock(ss);  /*******************************/
   8121         if (ss->ssl3.cwSpec->srvVirtName.data) {
   8122             passed = PR_FALSE;
   8123         }
   8124         ssl_ReleaseSpecReadLock(ss);  /***************************/
   8125         if (!passed) {
   8126             errCode = SSL_ERROR_UNRECOGNIZED_NAME_ALERT;
   8127             desc = handshake_failure;
   8128             goto alert_loser;
   8129         }
   8130     }
   8131 #endif
   8132 
   8133     sid = ssl3_NewSessionID(ss, PR_TRUE);
   8134     if (sid == NULL) {
   8135 	errCode = PORT_GetError();
   8136 	goto loser;	/* memory error is set. */
   8137     }
   8138     ss->sec.ci.sid = sid;
   8139 
   8140     ss->ssl3.hs.isResuming = PR_FALSE;
   8141     ssl_GetXmitBufLock(ss);
   8142     rv = ssl3_SendServerHelloSequence(ss);
   8143     ssl_ReleaseXmitBufLock(ss);
   8144     if (rv != SECSuccess) {
   8145 	errCode = PORT_GetError();
   8146 	goto loser;
   8147     }
   8148 
   8149     if (haveXmitBufLock) {
   8150 	ssl_ReleaseXmitBufLock(ss);
   8151 	haveXmitBufLock = PR_FALSE;
   8152     }
   8153 
   8154     return SECSuccess;
   8155 
   8156 alert_loser:
   8157     if (haveSpecWriteLock) {
   8158 	ssl_ReleaseSpecWriteLock(ss);
   8159 	haveSpecWriteLock = PR_FALSE;
   8160     }
   8161     (void)SSL3_SendAlert(ss, level, desc);
   8162     /* FALLTHRU */
   8163 loser:
   8164     if (haveSpecWriteLock) {
   8165 	ssl_ReleaseSpecWriteLock(ss);
   8166 	haveSpecWriteLock = PR_FALSE;
   8167     }
   8168 
   8169     if (haveXmitBufLock) {
   8170 	ssl_ReleaseXmitBufLock(ss);
   8171 	haveXmitBufLock = PR_FALSE;
   8172     }
   8173 
   8174     PORT_SetError(errCode);
   8175     return SECFailure;
   8176 }
   8177 
   8178 /*
   8179  * ssl3_HandleV2ClientHello is used when a V2 formatted hello comes
   8180  * in asking to use the V3 handshake.
   8181  * Called from ssl2_HandleClientHelloMessage() in sslcon.c
   8182  */
   8183 SECStatus
   8184 ssl3_HandleV2ClientHello(sslSocket *ss, unsigned char *buffer, int length)
   8185 {
   8186     sslSessionID *      sid 		= NULL;
   8187     unsigned char *     suites;
   8188     unsigned char *     random;
   8189     SSL3ProtocolVersion version;
   8190     SECStatus           rv;
   8191     int                 i;
   8192     int                 j;
   8193     int                 sid_length;
   8194     int                 suite_length;
   8195     int                 rand_length;
   8196     int                 errCode  = SSL_ERROR_RX_MALFORMED_CLIENT_HELLO;
   8197     SSL3AlertDescription desc    = handshake_failure;
   8198 
   8199     SSL_TRC(3, ("%d: SSL3[%d]: handle v2 client_hello", SSL_GETPID(), ss->fd));
   8200 
   8201     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   8202 
   8203     ssl_GetSSL3HandshakeLock(ss);
   8204 
   8205     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   8206 
   8207     rv = ssl3_InitState(ss);
   8208     if (rv != SECSuccess) {
   8209 	ssl_ReleaseSSL3HandshakeLock(ss);
   8210 	return rv;		/* ssl3_InitState has set the error code. */
   8211     }
   8212     rv = ssl3_RestartHandshakeHashes(ss);
   8213     if (rv != SECSuccess) {
   8214 	ssl_ReleaseSSL3HandshakeLock(ss);
   8215 	return rv;
   8216     }
   8217 
   8218     if (ss->ssl3.hs.ws != wait_client_hello) {
   8219 	desc    = unexpected_message;
   8220 	errCode = SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO;
   8221 	goto loser;	/* alert_loser */
   8222     }
   8223 
   8224     version      = (buffer[1] << 8) | buffer[2];
   8225     suite_length = (buffer[3] << 8) | buffer[4];
   8226     sid_length   = (buffer[5] << 8) | buffer[6];
   8227     rand_length  = (buffer[7] << 8) | buffer[8];
   8228     ss->clientHelloVersion = version;
   8229 
   8230     rv = ssl3_NegotiateVersion(ss, version, PR_TRUE);
   8231     if (rv != SECSuccess) {
   8232 	/* send back which ever alert client will understand. */
   8233     	desc = (version > SSL_LIBRARY_VERSION_3_0) ? protocol_version : handshake_failure;
   8234 	errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   8235 	goto alert_loser;
   8236     }
   8237 
   8238     rv = ssl3_InitHandshakeHashes(ss);
   8239     if (rv != SECSuccess) {
   8240 	desc = internal_error;
   8241 	errCode = PORT_GetError();
   8242 	goto alert_loser;
   8243     }
   8244 
   8245     /* if we get a non-zero SID, just ignore it. */
   8246     if (length !=
   8247         SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length + rand_length) {
   8248 	SSL_DBG(("%d: SSL3[%d]: bad v2 client hello message, len=%d should=%d",
   8249 		 SSL_GETPID(), ss->fd, length,
   8250 		 SSL_HL_CLIENT_HELLO_HBYTES + suite_length + sid_length +
   8251 		 rand_length));
   8252 	goto loser;	/* malformed */	/* alert_loser */
   8253     }
   8254 
   8255     suites = buffer + SSL_HL_CLIENT_HELLO_HBYTES;
   8256     random = suites + suite_length + sid_length;
   8257 
   8258     if (rand_length < SSL_MIN_CHALLENGE_BYTES ||
   8259 	rand_length > SSL_MAX_CHALLENGE_BYTES) {
   8260 	goto loser;	/* malformed */	/* alert_loser */
   8261     }
   8262 
   8263     PORT_Assert(SSL_MAX_CHALLENGE_BYTES == SSL3_RANDOM_LENGTH);
   8264 
   8265     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
   8266     PORT_Memcpy(
   8267 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
   8268 	random, rand_length);
   8269 
   8270     PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
   8271 		   SSL3_RANDOM_LENGTH));
   8272 #ifdef NSS_ENABLE_ECC
   8273     /* Disable any ECC cipher suites for which we have no cert. */
   8274     ssl3_FilterECCipherSuitesByServerCerts(ss);
   8275 #endif
   8276     i = ssl3_config_match_init(ss);
   8277     if (i <= 0) {
   8278     	errCode = PORT_GetError();	/* error code is already set. */
   8279 	goto alert_loser;
   8280     }
   8281 
   8282     /* Select a cipher suite.
   8283     **
   8284     ** NOTE: This suite selection algorithm should be the same as the one in
   8285     ** ssl3_HandleClientHello().
   8286     **
   8287     ** See the comments about export cipher suites in ssl3_HandleClientHello().
   8288     */
   8289     for (j = 0; j < ssl_V3_SUITES_IMPLEMENTED; j++) {
   8290 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[j];
   8291 	if (!config_match(suite, ss->ssl3.policy, PR_TRUE) ||
   8292 	    !ssl3_CipherSuiteAllowedForVersion(suite->cipher_suite,
   8293 					       ss->version)) {
   8294 	    continue;
   8295 	}
   8296 	for (i = 0; i+2 < suite_length; i += 3) {
   8297 	    PRUint32 suite_i = (suites[i] << 16)|(suites[i+1] << 8)|suites[i+2];
   8298 	    if (suite_i == suite->cipher_suite) {
   8299 		ss->ssl3.hs.cipher_suite = suite->cipher_suite;
   8300 		ss->ssl3.hs.suite_def =
   8301 		    ssl_LookupCipherSuiteDef(ss->ssl3.hs.cipher_suite);
   8302 		goto suite_found;
   8303 	    }
   8304 	}
   8305     }
   8306     errCode = SSL_ERROR_NO_CYPHER_OVERLAP;
   8307     goto alert_loser;
   8308 
   8309 suite_found:
   8310 
   8311     /* Look for the SCSV, and if found, treat it just like an empty RI
   8312      * extension by processing a local copy of an empty RI extension.
   8313      */
   8314     for (i = 0; i+2 < suite_length; i += 3) {
   8315 	PRUint32 suite_i = (suites[i] << 16) | (suites[i+1] << 8) | suites[i+2];
   8316 	if (suite_i == TLS_EMPTY_RENEGOTIATION_INFO_SCSV) {
   8317 	    SSL3Opaque * b2 = (SSL3Opaque *)emptyRIext;
   8318 	    PRUint32     L2 = sizeof emptyRIext;
   8319 	    (void)ssl3_HandleHelloExtensions(ss, &b2, &L2);
   8320 	    break;
   8321 	}
   8322     }
   8323 
   8324     if (ss->opt.requireSafeNegotiation &&
   8325 	!ssl3_ExtensionNegotiated(ss, ssl_renegotiation_info_xtn)) {
   8326 	desc = handshake_failure;
   8327 	errCode = SSL_ERROR_UNSAFE_NEGOTIATION;
   8328     	goto alert_loser;
   8329     }
   8330 
   8331     ss->ssl3.hs.compression = ssl_compression_null;
   8332     ss->sec.send            = ssl3_SendApplicationData;
   8333 
   8334     /* we don't even search for a cache hit here.  It's just a miss. */
   8335     SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_misses );
   8336     sid = ssl3_NewSessionID(ss, PR_TRUE);
   8337     if (sid == NULL) {
   8338     	errCode = PORT_GetError();
   8339 	goto loser;	/* memory error is set. */
   8340     }
   8341     ss->sec.ci.sid = sid;
   8342     /* do not worry about memory leak of sid since it now belongs to ci */
   8343 
   8344     /* We have to update the handshake hashes before we can send stuff */
   8345     rv = ssl3_UpdateHandshakeHashes(ss, buffer, length);
   8346     if (rv != SECSuccess) {
   8347     	errCode = PORT_GetError();
   8348 	goto loser;
   8349     }
   8350 
   8351     ssl_GetXmitBufLock(ss);
   8352     rv = ssl3_SendServerHelloSequence(ss);
   8353     ssl_ReleaseXmitBufLock(ss);
   8354     if (rv != SECSuccess) {
   8355     	errCode = PORT_GetError();
   8356 	goto loser;
   8357     }
   8358 
   8359     /* XXX_1 	The call stack to here is:
   8360      * ssl_Do1stHandshake -> ssl2_HandleClientHelloMessage -> here.
   8361      * ssl2_HandleClientHelloMessage returns whatever we return here.
   8362      * ssl_Do1stHandshake will continue looping if it gets back either
   8363      *		SECSuccess or SECWouldBlock.
   8364      * SECSuccess is preferable here.  See XXX_1 in sslgathr.c.
   8365      */
   8366     ssl_ReleaseSSL3HandshakeLock(ss);
   8367     return SECSuccess;
   8368 
   8369 alert_loser:
   8370     SSL3_SendAlert(ss, alert_fatal, desc);
   8371 loser:
   8372     ssl_ReleaseSSL3HandshakeLock(ss);
   8373     PORT_SetError(errCode);
   8374     return SECFailure;
   8375 }
   8376 
   8377 /* The negotiated version number has been already placed in ss->version.
   8378 **
   8379 ** Called from:  ssl3_HandleClientHello                     (resuming session),
   8380 ** 	ssl3_SendServerHelloSequence <- ssl3_HandleClientHello   (new session),
   8381 ** 	ssl3_SendServerHelloSequence <- ssl3_HandleV2ClientHello (new session)
   8382 */
   8383 static SECStatus
   8384 ssl3_SendServerHello(sslSocket *ss)
   8385 {
   8386     sslSessionID *sid;
   8387     SECStatus     rv;
   8388     PRUint32      maxBytes = 65535;
   8389     PRUint32      length;
   8390     PRInt32       extensions_len = 0;
   8391     SSL3ProtocolVersion version;
   8392 
   8393     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello handshake", SSL_GETPID(),
   8394 		ss->fd));
   8395 
   8396     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   8397     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   8398 
   8399     if (!IS_DTLS(ss)) {
   8400 	PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_3_0));
   8401 
   8402 	if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_3_0)) {
   8403 	    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
   8404 	    return SECFailure;
   8405 	}
   8406     } else {
   8407 	PORT_Assert(MSB(ss->version) == MSB(SSL_LIBRARY_VERSION_DTLS_1_0));
   8408 
   8409 	if (MSB(ss->version) != MSB(SSL_LIBRARY_VERSION_DTLS_1_0)) {
   8410 	    PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
   8411 	    return SECFailure;
   8412 	}
   8413     }
   8414 
   8415     sid = ss->sec.ci.sid;
   8416 
   8417     extensions_len = ssl3_CallHelloExtensionSenders(ss, PR_FALSE, maxBytes,
   8418 					       &ss->xtnData.serverSenders[0]);
   8419     if (extensions_len > 0)
   8420     	extensions_len += 2; /* Add sizeof total extension length */
   8421 
   8422     length = sizeof(SSL3ProtocolVersion) + SSL3_RANDOM_LENGTH + 1 +
   8423              ((sid == NULL) ? 0: sid->u.ssl3.sessionIDLength) +
   8424 	     sizeof(ssl3CipherSuite) + 1 + extensions_len;
   8425     rv = ssl3_AppendHandshakeHeader(ss, server_hello, length);
   8426     if (rv != SECSuccess) {
   8427 	return rv;	/* err set by AppendHandshake. */
   8428     }
   8429 
   8430     if (IS_DTLS(ss)) {
   8431 	version = dtls_TLSVersionToDTLSVersion(ss->version);
   8432     } else {
   8433 	version = ss->version;
   8434     }
   8435 
   8436     rv = ssl3_AppendHandshakeNumber(ss, version, 2);
   8437     if (rv != SECSuccess) {
   8438 	return rv;	/* err set by AppendHandshake. */
   8439     }
   8440     rv = ssl3_GetNewRandom(&ss->ssl3.hs.server_random);
   8441     if (rv != SECSuccess) {
   8442 	ssl_MapLowLevelError(SSL_ERROR_GENERATE_RANDOM_FAILURE);
   8443 	return rv;
   8444     }
   8445     rv = ssl3_AppendHandshake(
   8446 	ss, &ss->ssl3.hs.server_random, SSL3_RANDOM_LENGTH);
   8447     if (rv != SECSuccess) {
   8448 	return rv;	/* err set by AppendHandshake. */
   8449     }
   8450 
   8451     if (sid)
   8452 	rv = ssl3_AppendHandshakeVariable(
   8453 	    ss, sid->u.ssl3.sessionID, sid->u.ssl3.sessionIDLength, 1);
   8454     else
   8455 	rv = ssl3_AppendHandshakeVariable(ss, NULL, 0, 1);
   8456     if (rv != SECSuccess) {
   8457 	return rv;	/* err set by AppendHandshake. */
   8458     }
   8459 
   8460     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.cipher_suite, 2);
   8461     if (rv != SECSuccess) {
   8462 	return rv;	/* err set by AppendHandshake. */
   8463     }
   8464     rv = ssl3_AppendHandshakeNumber(ss, ss->ssl3.hs.compression, 1);
   8465     if (rv != SECSuccess) {
   8466 	return rv;	/* err set by AppendHandshake. */
   8467     }
   8468     if (extensions_len) {
   8469 	PRInt32 sent_len;
   8470 
   8471     	extensions_len -= 2;
   8472 	rv = ssl3_AppendHandshakeNumber(ss, extensions_len, 2);
   8473 	if (rv != SECSuccess)
   8474 	    return rv;	/* err set by ssl3_SetupPendingCipherSpec */
   8475 	sent_len = ssl3_CallHelloExtensionSenders(ss, PR_TRUE, extensions_len,
   8476 					   &ss->xtnData.serverSenders[0]);
   8477         PORT_Assert(sent_len == extensions_len);
   8478 	if (sent_len != extensions_len) {
   8479 	    if (sent_len >= 0)
   8480 	    	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   8481 	    return SECFailure;
   8482 	}
   8483     }
   8484     rv = ssl3_SetupPendingCipherSpec(ss);
   8485     if (rv != SECSuccess) {
   8486 	return rv;	/* err set by ssl3_SetupPendingCipherSpec */
   8487     }
   8488 
   8489     return SECSuccess;
   8490 }
   8491 
   8492 /* ssl3_PickSignatureHashAlgorithm selects a hash algorithm to use when signing
   8493  * elements of the handshake. (The negotiated cipher suite determines the
   8494  * signature algorithm.) Prior to TLS 1.2, the MD5/SHA1 combination is always
   8495  * used. With TLS 1.2, a client may advertise its support for signature and
   8496  * hash combinations. */
   8497 static SECStatus
   8498 ssl3_PickSignatureHashAlgorithm(sslSocket *ss,
   8499 				SSL3SignatureAndHashAlgorithm* out)
   8500 {
   8501     TLSSignatureAlgorithm sigAlg;
   8502     unsigned int i, j;
   8503     /* hashPreference expresses our preferences for hash algorithms, most
   8504      * preferable first. */
   8505     static const PRUint8 hashPreference[] = {
   8506 	tls_hash_sha256,
   8507 	tls_hash_sha384,
   8508 	tls_hash_sha512,
   8509 	tls_hash_sha1,
   8510     };
   8511 
   8512     switch (ss->ssl3.hs.kea_def->kea) {
   8513     case kea_rsa:
   8514     case kea_rsa_export:
   8515     case kea_rsa_export_1024:
   8516     case kea_dh_rsa:
   8517     case kea_dh_rsa_export:
   8518     case kea_dhe_rsa:
   8519     case kea_dhe_rsa_export:
   8520     case kea_rsa_fips:
   8521     case kea_ecdh_rsa:
   8522     case kea_ecdhe_rsa:
   8523 	sigAlg = tls_sig_rsa;
   8524 	break;
   8525     case kea_dh_dss:
   8526     case kea_dh_dss_export:
   8527     case kea_dhe_dss:
   8528     case kea_dhe_dss_export:
   8529 	sigAlg = tls_sig_dsa;
   8530 	break;
   8531     case kea_ecdh_ecdsa:
   8532     case kea_ecdhe_ecdsa:
   8533 	sigAlg = tls_sig_ecdsa;
   8534 	break;
   8535     default:
   8536 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   8537 	return SECFailure;
   8538     }
   8539     out->sigAlg = sigAlg;
   8540 
   8541     if (ss->version <= SSL_LIBRARY_VERSION_TLS_1_1) {
   8542 	/* SEC_OID_UNKNOWN means the MD5/SHA1 combo hash used in TLS 1.1 and
   8543 	 * prior. */
   8544 	out->hashAlg = SEC_OID_UNKNOWN;
   8545 	return SECSuccess;
   8546     }
   8547 
   8548     if (ss->ssl3.hs.numClientSigAndHash == 0) {
   8549 	/* If the client didn't provide any signature_algorithms extension then
   8550 	 * we can assume that they support SHA-1:
   8551 	 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
   8552 	out->hashAlg = SEC_OID_SHA1;
   8553 	return SECSuccess;
   8554     }
   8555 
   8556     for (i = 0; i < PR_ARRAY_SIZE(hashPreference); i++) {
   8557 	for (j = 0; j < ss->ssl3.hs.numClientSigAndHash; j++) {
   8558 	    const SSL3SignatureAndHashAlgorithm* sh =
   8559 		&ss->ssl3.hs.clientSigAndHash[j];
   8560 	    if (sh->sigAlg == sigAlg && sh->hashAlg == hashPreference[i]) {
   8561 		out->hashAlg = sh->hashAlg;
   8562 		return SECSuccess;
   8563 	    }
   8564 	}
   8565     }
   8566 
   8567     PORT_SetError(SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM);
   8568     return SECFailure;
   8569 }
   8570 
   8571 
   8572 static SECStatus
   8573 ssl3_SendServerKeyExchange(sslSocket *ss)
   8574 {
   8575     const ssl3KEADef * kea_def     = ss->ssl3.hs.kea_def;
   8576     SECStatus          rv          = SECFailure;
   8577     int                length;
   8578     PRBool             isTLS;
   8579     SECItem            signed_hash = {siBuffer, NULL, 0};
   8580     SSL3Hashes         hashes;
   8581     SECKEYPublicKey *  sdPub;	/* public key for step-down */
   8582     SSL3SignatureAndHashAlgorithm sigAndHash;
   8583 
   8584     SSL_TRC(3, ("%d: SSL3[%d]: send server_key_exchange handshake",
   8585 		SSL_GETPID(), ss->fd));
   8586 
   8587     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   8588     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   8589 
   8590     if (ssl3_PickSignatureHashAlgorithm(ss, &sigAndHash) != SECSuccess) {
   8591 	return SECFailure;
   8592     }
   8593 
   8594     switch (kea_def->exchKeyType) {
   8595     case kt_rsa:
   8596 	/* Perform SSL Step-Down here. */
   8597 	sdPub = ss->stepDownKeyPair->pubKey;
   8598 	PORT_Assert(sdPub != NULL);
   8599 	if (!sdPub) {
   8600 	    PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   8601 	    return SECFailure;
   8602 	}
   8603 	rv = ssl3_ComputeExportRSAKeyHash(sigAndHash.hashAlg,
   8604 					  sdPub->u.rsa.modulus,
   8605 					  sdPub->u.rsa.publicExponent,
   8606 	                                  &ss->ssl3.hs.client_random,
   8607 	                                  &ss->ssl3.hs.server_random,
   8608 					  &hashes, ss->opt.bypassPKCS11);
   8609         if (rv != SECSuccess) {
   8610 	    ssl_MapLowLevelError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   8611 	    return rv;
   8612 	}
   8613 
   8614 	isTLS = (PRBool)(ss->ssl3.pwSpec->version > SSL_LIBRARY_VERSION_3_0);
   8615 	rv = ssl3_SignHashes(&hashes, ss->serverCerts[kt_rsa].SERVERKEY,
   8616 	                     &signed_hash, isTLS);
   8617         if (rv != SECSuccess) {
   8618 	    goto loser;		/* ssl3_SignHashes has set err. */
   8619 	}
   8620 	if (signed_hash.data == NULL) {
   8621 	    /* how can this happen and rv == SECSuccess ?? */
   8622 	    PORT_SetError(SSL_ERROR_SERVER_KEY_EXCHANGE_FAILURE);
   8623 	    goto loser;
   8624 	}
   8625 	length = 2 + sdPub->u.rsa.modulus.len +
   8626 	         2 + sdPub->u.rsa.publicExponent.len +
   8627 	         2 + signed_hash.len;
   8628 
   8629 	rv = ssl3_AppendHandshakeHeader(ss, server_key_exchange, length);
   8630 	if (rv != SECSuccess) {
   8631 	    goto loser; 	/* err set by AppendHandshake. */
   8632 	}
   8633 
   8634 	rv = ssl3_AppendHandshakeVariable(ss, sdPub->u.rsa.modulus.data,
   8635 					  sdPub->u.rsa.modulus.len, 2);
   8636 	if (rv != SECSuccess) {
   8637 	    goto loser; 	/* err set by AppendHandshake. */
   8638 	}
   8639 
   8640 	rv = ssl3_AppendHandshakeVariable(
   8641 				ss, sdPub->u.rsa.publicExponent.data,
   8642 				sdPub->u.rsa.publicExponent.len, 2);
   8643 	if (rv != SECSuccess) {
   8644 	    goto loser; 	/* err set by AppendHandshake. */
   8645 	}
   8646 
   8647 	if (ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   8648 	    rv = ssl3_AppendSignatureAndHashAlgorithm(ss, &sigAndHash);
   8649 	    if (rv != SECSuccess) {
   8650 		goto loser; 	/* err set by AppendHandshake. */
   8651 	    }
   8652 	}
   8653 
   8654 	rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
   8655 	                                  signed_hash.len, 2);
   8656 	if (rv != SECSuccess) {
   8657 	    goto loser; 	/* err set by AppendHandshake. */
   8658 	}
   8659 	PORT_Free(signed_hash.data);
   8660 	return SECSuccess;
   8661 
   8662 #ifdef NSS_ENABLE_ECC
   8663     case kt_ecdh: {
   8664 	rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
   8665 	return rv;
   8666     }
   8667 #endif /* NSS_ENABLE_ECC */
   8668 
   8669     case kt_dh:
   8670     case kt_null:
   8671     default:
   8672 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   8673 	break;
   8674     }
   8675 loser:
   8676     if (signed_hash.data != NULL)
   8677     	PORT_Free(signed_hash.data);
   8678     return SECFailure;
   8679 }
   8680 
   8681 
   8682 static SECStatus
   8683 ssl3_SendCertificateRequest(sslSocket *ss)
   8684 {
   8685     PRBool         isTLS12;
   8686     SECItem *      name;
   8687     CERTDistNames *ca_list;
   8688     const PRUint8 *certTypes;
   8689     const PRUint8 *sigAlgs;
   8690     SECItem *      names	= NULL;
   8691     SECStatus      rv;
   8692     int            length;
   8693     int            i;
   8694     int            calen	= 0;
   8695     int            nnames	= 0;
   8696     int            certTypesLength;
   8697     int            sigAlgsLength;
   8698 
   8699     SSL_TRC(3, ("%d: SSL3[%d]: send certificate_request handshake",
   8700 		SSL_GETPID(), ss->fd));
   8701 
   8702     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   8703     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   8704 
   8705     isTLS12 = (PRBool)(ss->ssl3.pwSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   8706 
   8707     /* ssl3.ca_list is initialized to NULL, and never changed. */
   8708     ca_list = ss->ssl3.ca_list;
   8709     if (!ca_list) {
   8710 	ca_list = ssl3_server_ca_list;
   8711     }
   8712 
   8713     if (ca_list != NULL) {
   8714 	names = ca_list->names;
   8715 	nnames = ca_list->nnames;
   8716     }
   8717 
   8718     for (i = 0, name = names; i < nnames; i++, name++) {
   8719 	calen += 2 + name->len;
   8720     }
   8721 
   8722     certTypes       = certificate_types;
   8723     certTypesLength = sizeof certificate_types;
   8724     sigAlgs         = supported_signature_algorithms;
   8725     sigAlgsLength   = sizeof supported_signature_algorithms;
   8726 
   8727     length = 1 + certTypesLength + 2 + calen;
   8728     if (isTLS12) {
   8729 	length += 2 + sigAlgsLength;
   8730     }
   8731 
   8732     rv = ssl3_AppendHandshakeHeader(ss, certificate_request, length);
   8733     if (rv != SECSuccess) {
   8734 	return rv; 		/* err set by AppendHandshake. */
   8735     }
   8736     rv = ssl3_AppendHandshakeVariable(ss, certTypes, certTypesLength, 1);
   8737     if (rv != SECSuccess) {
   8738 	return rv; 		/* err set by AppendHandshake. */
   8739     }
   8740     if (isTLS12) {
   8741 	rv = ssl3_AppendHandshakeVariable(ss, sigAlgs, sigAlgsLength, 2);
   8742 	if (rv != SECSuccess) {
   8743 	    return rv; 		/* err set by AppendHandshake. */
   8744 	}
   8745     }
   8746     rv = ssl3_AppendHandshakeNumber(ss, calen, 2);
   8747     if (rv != SECSuccess) {
   8748 	return rv; 		/* err set by AppendHandshake. */
   8749     }
   8750     for (i = 0, name = names; i < nnames; i++, name++) {
   8751 	rv = ssl3_AppendHandshakeVariable(ss, name->data, name->len, 2);
   8752 	if (rv != SECSuccess) {
   8753 	    return rv; 		/* err set by AppendHandshake. */
   8754 	}
   8755     }
   8756 
   8757     return SECSuccess;
   8758 }
   8759 
   8760 static SECStatus
   8761 ssl3_SendServerHelloDone(sslSocket *ss)
   8762 {
   8763     SECStatus rv;
   8764 
   8765     SSL_TRC(3, ("%d: SSL3[%d]: send server_hello_done handshake",
   8766 		SSL_GETPID(), ss->fd));
   8767 
   8768     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   8769     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   8770 
   8771     rv = ssl3_AppendHandshakeHeader(ss, server_hello_done, 0);
   8772     if (rv != SECSuccess) {
   8773 	return rv; 		/* err set by AppendHandshake. */
   8774     }
   8775     rv = ssl3_FlushHandshake(ss, 0);
   8776     if (rv != SECSuccess) {
   8777 	return rv;	/* error code set by ssl3_FlushHandshake */
   8778     }
   8779     return SECSuccess;
   8780 }
   8781 
   8782 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   8783  * ssl3 Certificate Verify message
   8784  * Caller must hold Handshake and RecvBuf locks.
   8785  */
   8786 static SECStatus
   8787 ssl3_HandleCertificateVerify(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
   8788 			     SSL3Hashes *hashes)
   8789 {
   8790     SECItem              signed_hash = {siBuffer, NULL, 0};
   8791     SECStatus            rv;
   8792     int                  errCode     = SSL_ERROR_RX_MALFORMED_CERT_VERIFY;
   8793     SSL3AlertDescription desc        = handshake_failure;
   8794     PRBool               isTLS, isTLS12;
   8795     SSL3SignatureAndHashAlgorithm sigAndHash;
   8796 
   8797     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate_verify handshake",
   8798 		SSL_GETPID(), ss->fd));
   8799     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   8800     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   8801 
   8802     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   8803     isTLS12 = (PRBool)(ss->ssl3.prSpec->version >= SSL_LIBRARY_VERSION_TLS_1_2);
   8804 
   8805     if (ss->ssl3.hs.ws != wait_cert_verify || ss->sec.peerCert == NULL) {
   8806 	desc    = unexpected_message;
   8807 	errCode = SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY;
   8808 	goto alert_loser;
   8809     }
   8810 
   8811     if (isTLS12) {
   8812 	rv = ssl3_ConsumeSignatureAndHashAlgorithm(ss, &b, &length,
   8813 						   &sigAndHash);
   8814 	if (rv != SECSuccess) {
   8815 	    goto loser;	/* malformed or unsupported. */
   8816 	}
   8817 	rv = ssl3_CheckSignatureAndHashAlgorithmConsistency(
   8818 		&sigAndHash, ss->sec.peerCert);
   8819 	if (rv != SECSuccess) {
   8820 	    errCode = PORT_GetError();
   8821 	    desc = decrypt_error;
   8822 	    goto alert_loser;
   8823 	}
   8824 
   8825 	/* We only support CertificateVerify messages that use the handshake
   8826 	 * hash. */
   8827 	if (sigAndHash.hashAlg != hashes->hashAlg) {
   8828 	    errCode = SSL_ERROR_UNSUPPORTED_HASH_ALGORITHM;
   8829 	    desc = decrypt_error;
   8830 	    goto alert_loser;
   8831 	}
   8832     }
   8833 
   8834     rv = ssl3_ConsumeHandshakeVariable(ss, &signed_hash, 2, &b, &length);
   8835     if (rv != SECSuccess) {
   8836 	goto loser;		/* malformed. */
   8837     }
   8838 
   8839     /* XXX verify that the key & kea match */
   8840     rv = ssl3_VerifySignedHashes(hashes, ss->sec.peerCert, &signed_hash,
   8841 				 isTLS, ss->pkcs11PinArg);
   8842     if (rv != SECSuccess) {
   8843     	errCode = PORT_GetError();
   8844 	desc = isTLS ? decrypt_error : handshake_failure;
   8845 	goto alert_loser;
   8846     }
   8847 
   8848     signed_hash.data = NULL;
   8849 
   8850     if (length != 0) {
   8851 	desc    = isTLS ? decode_error : illegal_parameter;
   8852 	goto alert_loser;	/* malformed */
   8853     }
   8854     ss->ssl3.hs.ws = wait_change_cipher;
   8855     return SECSuccess;
   8856 
   8857 alert_loser:
   8858     SSL3_SendAlert(ss, alert_fatal, desc);
   8859 loser:
   8860     PORT_SetError(errCode);
   8861     return SECFailure;
   8862 }
   8863 
   8864 
   8865 /* find a slot that is able to generate a PMS and wrap it with RSA.
   8866  * Then generate and return the PMS.
   8867  * If the serverKeySlot parameter is non-null, this function will use
   8868  * that slot to do the job, otherwise it will find a slot.
   8869  *
   8870  * Called from  ssl3_DeriveConnectionKeysPKCS11()  (above)
   8871  *		sendRSAClientKeyExchange()         (above)
   8872  *		ssl3_HandleRSAClientKeyExchange()  (below)
   8873  * Caller must hold the SpecWriteLock, the SSL3HandshakeLock
   8874  */
   8875 static PK11SymKey *
   8876 ssl3_GenerateRSAPMS(sslSocket *ss, ssl3CipherSpec *spec,
   8877                     PK11SlotInfo * serverKeySlot)
   8878 {
   8879     PK11SymKey *      pms		= NULL;
   8880     PK11SlotInfo *    slot		= serverKeySlot;
   8881     void *	      pwArg 		= ss->pkcs11PinArg;
   8882     SECItem           param;
   8883     CK_VERSION 	      version;
   8884     CK_MECHANISM_TYPE mechanism_array[3];
   8885 
   8886     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   8887 
   8888     if (slot == NULL) {
   8889 	SSLCipherAlgorithm calg;
   8890 	/* The specReadLock would suffice here, but we cannot assert on
   8891 	** read locks.  Also, all the callers who call with a non-null
   8892 	** slot already hold the SpecWriteLock.
   8893 	*/
   8894 	PORT_Assert( ss->opt.noLocks || ssl_HaveSpecWriteLock(ss));
   8895 	PORT_Assert(ss->ssl3.prSpec == ss->ssl3.pwSpec);
   8896 
   8897         calg = spec->cipher_def->calg;
   8898 	PORT_Assert(alg2Mech[calg].calg == calg);
   8899 
   8900 	/* First get an appropriate slot.  */
   8901 	mechanism_array[0] = CKM_SSL3_PRE_MASTER_KEY_GEN;
   8902 	mechanism_array[1] = CKM_RSA_PKCS;
   8903 	mechanism_array[2] = alg2Mech[calg].cmech;
   8904 
   8905 	slot = PK11_GetBestSlotMultiple(mechanism_array, 3, pwArg);
   8906 	if (slot == NULL) {
   8907 	   /* can't find a slot with all three, find a slot with the minimum */
   8908 	    slot = PK11_GetBestSlotMultiple(mechanism_array, 2, pwArg);
   8909 	    if (slot == NULL) {
   8910 		PORT_SetError(SSL_ERROR_TOKEN_SLOT_NOT_FOUND);
   8911 		return pms;	/* which is NULL */
   8912 	    }
   8913 	}
   8914     }
   8915 
   8916     /* Generate the pre-master secret ...  */
   8917     if (IS_DTLS(ss)) {
   8918 	SSL3ProtocolVersion temp;
   8919 
   8920 	temp = dtls_TLSVersionToDTLSVersion(ss->clientHelloVersion);
   8921 	version.major = MSB(temp);
   8922 	version.minor = LSB(temp);
   8923     } else {
   8924 	version.major = MSB(ss->clientHelloVersion);
   8925 	version.minor = LSB(ss->clientHelloVersion);
   8926     }
   8927 
   8928     param.data = (unsigned char *)&version;
   8929     param.len  = sizeof version;
   8930 
   8931     pms = PK11_KeyGen(slot, CKM_SSL3_PRE_MASTER_KEY_GEN, &param, 0, pwArg);
   8932     if (!serverKeySlot)
   8933 	PK11_FreeSlot(slot);
   8934     if (pms == NULL) {
   8935 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   8936     }
   8937     return pms;
   8938 }
   8939 
   8940 /* Note: The Bleichenbacher attack on PKCS#1 necessitates that we NEVER
   8941  * return any indication of failure of the Client Key Exchange message,
   8942  * where that failure is caused by the content of the client's message.
   8943  * This function must not return SECFailure for any reason that is directly
   8944  * or indirectly caused by the content of the client's encrypted PMS.
   8945  * We must not send an alert and also not drop the connection.
   8946  * Instead, we generate a random PMS.  This will cause a failure
   8947  * in the processing the finished message, which is exactly where
   8948  * the failure must occur.
   8949  *
   8950  * Called from ssl3_HandleClientKeyExchange
   8951  */
   8952 static SECStatus
   8953 ssl3_HandleRSAClientKeyExchange(sslSocket *ss,
   8954                                 SSL3Opaque *b,
   8955 				PRUint32 length,
   8956 				SECKEYPrivateKey *serverKey)
   8957 {
   8958     PK11SymKey *      pms;
   8959 #ifndef NO_PKCS11_BYPASS
   8960     unsigned char *   cr     = (unsigned char *)&ss->ssl3.hs.client_random;
   8961     unsigned char *   sr     = (unsigned char *)&ss->ssl3.hs.server_random;
   8962     ssl3CipherSpec *  pwSpec = ss->ssl3.pwSpec;
   8963     unsigned int      outLen = 0;
   8964 #endif
   8965     PRBool            isTLS  = PR_FALSE;
   8966     SECStatus         rv;
   8967     SECItem           enc_pms;
   8968     unsigned char     rsaPmsBuf[SSL3_RSA_PMS_LENGTH];
   8969     SECItem           pmsItem = {siBuffer, NULL, 0};
   8970 
   8971     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   8972     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   8973     PORT_Assert( ss->ssl3.prSpec == ss->ssl3.pwSpec );
   8974 
   8975     enc_pms.data = b;
   8976     enc_pms.len  = length;
   8977     pmsItem.data = rsaPmsBuf;
   8978     pmsItem.len  = sizeof rsaPmsBuf;
   8979 
   8980     if (ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0) { /* isTLS */
   8981 	PRInt32 kLen;
   8982 	kLen = ssl3_ConsumeHandshakeNumber(ss, 2, &enc_pms.data, &enc_pms.len);
   8983 	if (kLen < 0) {
   8984 	    PORT_SetError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   8985 	    return SECFailure;
   8986 	}
   8987 	if ((unsigned)kLen < enc_pms.len) {
   8988 	    enc_pms.len = kLen;
   8989 	}
   8990 	isTLS = PR_TRUE;
   8991     } else {
   8992 	isTLS = (PRBool)(ss->ssl3.hs.kea_def->tls_keygen != 0);
   8993     }
   8994 
   8995 #ifndef NO_PKCS11_BYPASS
   8996     if (ss->opt.bypassPKCS11) {
   8997 	/* TRIPLE BYPASS, get PMS directly from RSA decryption.
   8998 	 * Use PK11_PrivDecryptPKCS1 to decrypt the PMS to a buffer,
   8999 	 * then, check for version rollback attack, then
   9000 	 * do the equivalent of ssl3_DeriveMasterSecret, placing the MS in
   9001 	 * pwSpec->msItem.  Finally call ssl3_InitPendingCipherSpec with
   9002 	 * ss and NULL, so that it will use the MS we've already derived here.
   9003 	 */
   9004 
   9005 	rv = PK11_PrivDecryptPKCS1(serverKey, rsaPmsBuf, &outLen,
   9006 				   sizeof rsaPmsBuf, enc_pms.data, enc_pms.len);
   9007 	if (rv != SECSuccess) {
   9008 	    /* triple bypass failed.  Let's try for a double bypass. */
   9009 	    goto double_bypass;
   9010 	} else if (ss->opt.detectRollBack) {
   9011 	    SSL3ProtocolVersion client_version =
   9012 					 (rsaPmsBuf[0] << 8) | rsaPmsBuf[1];
   9013 
   9014 	    if (IS_DTLS(ss)) {
   9015 		client_version = dtls_DTLSVersionToTLSVersion(client_version);
   9016 	    }
   9017 
   9018 	    if (client_version != ss->clientHelloVersion) {
   9019 		/* Version roll-back detected. ensure failure.  */
   9020 		rv = PK11_GenerateRandom(rsaPmsBuf, sizeof rsaPmsBuf);
   9021 	    }
   9022 	}
   9023 	/* have PMS, build MS without PKCS11 */
   9024 	rv = ssl3_MasterKeyDeriveBypass(pwSpec, cr, sr, &pmsItem, isTLS,
   9025 					PR_TRUE);
   9026 	if (rv != SECSuccess) {
   9027 	    pwSpec->msItem.data = pwSpec->raw_master_secret;
   9028 	    pwSpec->msItem.len  = SSL3_MASTER_SECRET_LENGTH;
   9029 	    PK11_GenerateRandom(pwSpec->msItem.data, pwSpec->msItem.len);
   9030 	}
   9031 	rv = ssl3_InitPendingCipherSpec(ss,  NULL);
   9032     } else
   9033 #endif
   9034     {
   9035 #ifndef NO_PKCS11_BYPASS
   9036 double_bypass:
   9037 #endif
   9038 	/*
   9039 	 * unwrap pms out of the incoming buffer
   9040 	 * Note: CKM_SSL3_MASTER_KEY_DERIVE is NOT the mechanism used to do
   9041 	 *	the unwrap.  Rather, it is the mechanism with which the
   9042 	 *      unwrapped pms will be used.
   9043 	 */
   9044 	pms = PK11_PubUnwrapSymKey(serverKey, &enc_pms,
   9045 				   CKM_SSL3_MASTER_KEY_DERIVE, CKA_DERIVE, 0);
   9046 	if (pms != NULL) {
   9047 	    PRINT_BUF(60, (ss, "decrypted premaster secret:",
   9048 			   PK11_GetKeyData(pms)->data,
   9049 			   PK11_GetKeyData(pms)->len));
   9050 	} else {
   9051 	    /* unwrap failed. Generate a bogus PMS and carry on. */
   9052 	    PK11SlotInfo *  slot   = PK11_GetSlotFromPrivateKey(serverKey);
   9053 
   9054 	    ssl_GetSpecWriteLock(ss);
   9055 	    pms = ssl3_GenerateRSAPMS(ss, ss->ssl3.prSpec, slot);
   9056 	    ssl_ReleaseSpecWriteLock(ss);
   9057 	    PK11_FreeSlot(slot);
   9058 	}
   9059 
   9060 	if (pms == NULL) {
   9061 	    /* last gasp.  */
   9062 	    ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
   9063 	    return SECFailure;
   9064 	}
   9065 
   9066 	/* This step will derive the MS from the PMS, among other things. */
   9067 	rv = ssl3_InitPendingCipherSpec(ss,  pms);
   9068 	PK11_FreeSymKey(pms);
   9069     }
   9070 
   9071     if (rv != SECSuccess) {
   9072 	SEND_ALERT
   9073 	return SECFailure; /* error code set by ssl3_InitPendingCipherSpec */
   9074     }
   9075     return SECSuccess;
   9076 }
   9077 
   9078 
   9079 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   9080  * ssl3 ClientKeyExchange message from the remote client
   9081  * Caller must hold Handshake and RecvBuf locks.
   9082  */
   9083 static SECStatus
   9084 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   9085 {
   9086     SECKEYPrivateKey *serverKey         = NULL;
   9087     SECStatus         rv;
   9088     const ssl3KEADef *kea_def;
   9089     ssl3KeyPair     *serverKeyPair      = NULL;
   9090 #ifdef NSS_ENABLE_ECC
   9091     SECKEYPublicKey *serverPubKey       = NULL;
   9092 #endif /* NSS_ENABLE_ECC */
   9093 
   9094     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
   9095 		SSL_GETPID(), ss->fd));
   9096 
   9097     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9098     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9099 
   9100     if (ss->ssl3.hs.ws != wait_client_key) {
   9101 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   9102     	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
   9103 	return SECFailure;
   9104     }
   9105 
   9106     kea_def   = ss->ssl3.hs.kea_def;
   9107 
   9108     if (ss->ssl3.hs.usedStepDownKey) {
   9109 	 PORT_Assert(kea_def->is_limited /* XXX OR cert is signing only */
   9110 		 && kea_def->exchKeyType == kt_rsa
   9111 		 && ss->stepDownKeyPair != NULL);
   9112 	 if (!kea_def->is_limited  ||
   9113 	      kea_def->exchKeyType != kt_rsa ||
   9114 	      ss->stepDownKeyPair == NULL) {
   9115 	 	/* shouldn't happen, don't use step down if it does */
   9116 		goto skip;
   9117 	 }
   9118     	serverKeyPair = ss->stepDownKeyPair;
   9119 	ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
   9120     } else
   9121 skip:
   9122 #ifdef NSS_ENABLE_ECC
   9123     /* XXX Using SSLKEAType to index server certifiates
   9124      * does not work for (EC)DHE ciphers. Until we have
   9125      * an indexing mechanism general enough for all key
   9126      * exchange algorithms, we'll need to deal with each
   9127      * one seprately.
   9128      */
   9129     if ((kea_def->kea == kea_ecdhe_rsa) ||
   9130                (kea_def->kea == kea_ecdhe_ecdsa)) {
   9131 	if (ss->ephemeralECDHKeyPair != NULL) {
   9132 	   serverKeyPair = ss->ephemeralECDHKeyPair;
   9133 	   if (serverKeyPair->pubKey) {
   9134 		ss->sec.keaKeyBits =
   9135 		    SECKEY_PublicKeyStrengthInBits(serverKeyPair->pubKey);
   9136 	   }
   9137 	}
   9138     } else
   9139 #endif
   9140     {
   9141 	sslServerCerts * sc = ss->serverCerts + kea_def->exchKeyType;
   9142 	serverKeyPair = sc->serverKeyPair;
   9143 	ss->sec.keaKeyBits = sc->serverKeyBits;
   9144     }
   9145 
   9146     if (serverKeyPair) {
   9147 	serverKey = serverKeyPair->privKey;
   9148     }
   9149 
   9150     if (serverKey == NULL) {
   9151     	SEND_ALERT
   9152 	PORT_SetError(SSL_ERROR_NO_SERVER_KEY_FOR_ALG);
   9153 	return SECFailure;
   9154     }
   9155 
   9156     ss->sec.keaType    = kea_def->exchKeyType;
   9157 
   9158     switch (kea_def->exchKeyType) {
   9159     case kt_rsa:
   9160 	rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
   9161 	if (rv != SECSuccess) {
   9162 	    SEND_ALERT
   9163 	    return SECFailure;	/* error code set */
   9164 	}
   9165 	break;
   9166 
   9167 
   9168 #ifdef NSS_ENABLE_ECC
   9169     case kt_ecdh:
   9170 	/* XXX We really ought to be able to store multiple
   9171 	 * EC certs (a requirement if we wish to support both
   9172 	 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
   9173 	 * When we make that change, we'll need an index other
   9174 	 * than kt_ecdh to pick the right EC certificate.
   9175 	 */
   9176 	if (serverKeyPair) {
   9177 	    serverPubKey = serverKeyPair->pubKey;
   9178         }
   9179 	if (serverPubKey == NULL) {
   9180 	    /* XXX Is this the right error code? */
   9181 	    PORT_SetError(SSL_ERROR_EXTRACT_PUBLIC_KEY_FAILURE);
   9182 	    return SECFailure;
   9183 	}
   9184 	rv = ssl3_HandleECDHClientKeyExchange(ss, b, length,
   9185 					      serverPubKey, serverKey);
   9186 	if (rv != SECSuccess) {
   9187 	    return SECFailure;	/* error code set */
   9188 	}
   9189 	break;
   9190 #endif /* NSS_ENABLE_ECC */
   9191 
   9192     default:
   9193 	(void) ssl3_HandshakeFailure(ss);
   9194 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
   9195 	return SECFailure;
   9196     }
   9197     ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
   9198     return SECSuccess;
   9199 
   9200 }
   9201 
   9202 /* This is TLS's equivalent of sending a no_certificate alert. */
   9203 static SECStatus
   9204 ssl3_SendEmptyCertificate(sslSocket *ss)
   9205 {
   9206     SECStatus            rv;
   9207 
   9208     rv = ssl3_AppendHandshakeHeader(ss, certificate, 3);
   9209     if (rv == SECSuccess) {
   9210 	rv = ssl3_AppendHandshakeNumber(ss, 0, 3);
   9211     }
   9212     return rv;	/* error, if any, set by functions called above. */
   9213 }
   9214 
   9215 SECStatus
   9216 ssl3_HandleNewSessionTicket(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   9217 {
   9218     SECStatus         rv;
   9219     NewSessionTicket  session_ticket;
   9220 
   9221     SSL_TRC(3, ("%d: SSL3[%d]: handle session_ticket handshake",
   9222 		SSL_GETPID(), ss->fd));
   9223 
   9224     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9225     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9226 
   9227     if (ss->ssl3.hs.ws != wait_new_session_ticket) {
   9228 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   9229 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
   9230 	return SECFailure;
   9231     }
   9232 
   9233     session_ticket.received_timestamp = ssl_Time();
   9234     if (length < 4) {
   9235 	(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
   9236 	PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
   9237 	return SECFailure;
   9238     }
   9239     session_ticket.ticket_lifetime_hint =
   9240 	(PRUint32)ssl3_ConsumeHandshakeNumber(ss, 4, &b, &length);
   9241 
   9242     rv = ssl3_ConsumeHandshakeVariable(ss, &session_ticket.ticket, 2,
   9243 	&b, &length);
   9244     if (length != 0 || rv != SECSuccess) {
   9245 	(void)SSL3_SendAlert(ss, alert_fatal, decode_error);
   9246 	PORT_SetError(SSL_ERROR_RX_MALFORMED_NEW_SESSION_TICKET);
   9247 	return SECFailure;  /* malformed */
   9248     }
   9249 
   9250     rv = ssl3_SetSIDSessionTicket(ss->sec.ci.sid, &session_ticket);
   9251     if (rv != SECSuccess) {
   9252 	(void)SSL3_SendAlert(ss, alert_fatal, handshake_failure);
   9253 	PORT_SetError(SSL_ERROR_INTERNAL_ERROR_ALERT);
   9254 	return SECFailure;
   9255     }
   9256     ss->ssl3.hs.ws = wait_change_cipher;
   9257     return SECSuccess;
   9258 }
   9259 
   9260 #ifdef NISCC_TEST
   9261 static PRInt32 connNum = 0;
   9262 
   9263 static SECStatus
   9264 get_fake_cert(SECItem *pCertItem, int *pIndex)
   9265 {
   9266     PRFileDesc *cf;
   9267     char *      testdir;
   9268     char *      startat;
   9269     char *      stopat;
   9270     const char *extension;
   9271     int         fileNum;
   9272     PRInt32     numBytes   = 0;
   9273     PRStatus    prStatus;
   9274     PRFileInfo  info;
   9275     char        cfn[100];
   9276 
   9277     pCertItem->data = 0;
   9278     if ((testdir = PR_GetEnv("NISCC_TEST")) == NULL) {
   9279 	return SECSuccess;
   9280     }
   9281     *pIndex   = (NULL != strstr(testdir, "root"));
   9282     extension = (strstr(testdir, "simple") ? "" : ".der");
   9283     fileNum     = PR_ATOMIC_INCREMENT(&connNum) - 1;
   9284     if ((startat = PR_GetEnv("START_AT")) != NULL) {
   9285 	fileNum += atoi(startat);
   9286     }
   9287     if ((stopat = PR_GetEnv("STOP_AT")) != NULL &&
   9288 	fileNum >= atoi(stopat)) {
   9289 	*pIndex = -1;
   9290 	return SECSuccess;
   9291     }
   9292     sprintf(cfn, "%s/%08d%s", testdir, fileNum, extension);
   9293     cf = PR_Open(cfn, PR_RDONLY, 0);
   9294     if (!cf) {
   9295 	goto loser;
   9296     }
   9297     prStatus = PR_GetOpenFileInfo(cf, &info);
   9298     if (prStatus != PR_SUCCESS) {
   9299 	PR_Close(cf);
   9300 	goto loser;
   9301     }
   9302     pCertItem = SECITEM_AllocItem(NULL, pCertItem, info.size);
   9303     if (pCertItem) {
   9304 	numBytes = PR_Read(cf, pCertItem->data, info.size);
   9305     }
   9306     PR_Close(cf);
   9307     if (numBytes != info.size) {
   9308 	SECITEM_FreeItem(pCertItem, PR_FALSE);
   9309 	PORT_SetError(SEC_ERROR_IO);
   9310 	goto loser;
   9311     }
   9312     fprintf(stderr, "using %s\n", cfn);
   9313     return SECSuccess;
   9314 
   9315 loser:
   9316     fprintf(stderr, "failed to use %s\n", cfn);
   9317     *pIndex = -1;
   9318     return SECFailure;
   9319 }
   9320 #endif
   9321 
   9322 /*
   9323  * Used by both client and server.
   9324  * Called from HandleServerHelloDone and from SendServerHelloSequence.
   9325  */
   9326 static SECStatus
   9327 ssl3_SendCertificate(sslSocket *ss)
   9328 {
   9329     SECStatus            rv;
   9330     CERTCertificateList *certChain;
   9331     int                  len 		= 0;
   9332     int                  i;
   9333     SSL3KEAType          certIndex;
   9334 #ifdef NISCC_TEST
   9335     SECItem              fakeCert;
   9336     int                  ndex           = -1;
   9337 #endif
   9338 
   9339     SSL_TRC(3, ("%d: SSL3[%d]: send certificate handshake",
   9340 		SSL_GETPID(), ss->fd));
   9341 
   9342     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9343     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9344 
   9345     if (ss->sec.localCert)
   9346     	CERT_DestroyCertificate(ss->sec.localCert);
   9347     if (ss->sec.isServer) {
   9348 	sslServerCerts * sc = NULL;
   9349 
   9350 	/* XXX SSLKEAType isn't really a good choice for
   9351 	 * indexing certificates (it breaks when we deal
   9352 	 * with (EC)DHE-* cipher suites. This hack ensures
   9353 	 * the RSA cert is picked for (EC)DHE-RSA.
   9354 	 * Revisit this when we add server side support
   9355 	 * for ECDHE-ECDSA or client-side authentication
   9356 	 * using EC certificates.
   9357 	 */
   9358 	if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
   9359 	    (ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
   9360 	    certIndex = kt_rsa;
   9361 	} else {
   9362 	    certIndex = ss->ssl3.hs.kea_def->exchKeyType;
   9363 	}
   9364 	sc                    = ss->serverCerts + certIndex;
   9365 	certChain             = sc->serverCertChain;
   9366 	ss->sec.authKeyBits   = sc->serverKeyBits;
   9367 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
   9368 	ss->sec.localCert     = CERT_DupCertificate(sc->serverCert);
   9369     } else {
   9370 	certChain          = ss->ssl3.clientCertChain;
   9371 	ss->sec.localCert = CERT_DupCertificate(ss->ssl3.clientCertificate);
   9372     }
   9373 
   9374 #ifdef NISCC_TEST
   9375     rv = get_fake_cert(&fakeCert, &ndex);
   9376 #endif
   9377 
   9378     if (certChain) {
   9379 	for (i = 0; i < certChain->len; i++) {
   9380 #ifdef NISCC_TEST
   9381 	    if (fakeCert.len > 0 && i == ndex) {
   9382 		len += fakeCert.len + 3;
   9383 	    } else {
   9384 		len += certChain->certs[i].len + 3;
   9385 	    }
   9386 #else
   9387 	    len += certChain->certs[i].len + 3;
   9388 #endif
   9389 	}
   9390     }
   9391 
   9392     rv = ssl3_AppendHandshakeHeader(ss, certificate, len + 3);
   9393     if (rv != SECSuccess) {
   9394 	return rv; 		/* err set by AppendHandshake. */
   9395     }
   9396     rv = ssl3_AppendHandshakeNumber(ss, len, 3);
   9397     if (rv != SECSuccess) {
   9398 	return rv; 		/* err set by AppendHandshake. */
   9399     }
   9400     if (certChain) {
   9401         for (i = 0; i < certChain->len; i++) {
   9402 #ifdef NISCC_TEST
   9403             if (fakeCert.len > 0 && i == ndex) {
   9404                 rv = ssl3_AppendHandshakeVariable(ss, fakeCert.data,
   9405                                                   fakeCert.len, 3);
   9406                 SECITEM_FreeItem(&fakeCert, PR_FALSE);
   9407             } else {
   9408                 rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
   9409                                                   certChain->certs[i].len, 3);
   9410             }
   9411 #else
   9412             rv = ssl3_AppendHandshakeVariable(ss, certChain->certs[i].data,
   9413                                               certChain->certs[i].len, 3);
   9414 #endif
   9415             if (rv != SECSuccess) {
   9416                 return rv; 		/* err set by AppendHandshake. */
   9417             }
   9418         }
   9419     }
   9420 
   9421     return SECSuccess;
   9422 }
   9423 
   9424 /*
   9425  * Used by server only.
   9426  * single-stapling, send only a single cert status
   9427  */
   9428 static SECStatus
   9429 ssl3_SendCertificateStatus(sslSocket *ss)
   9430 {
   9431     SECStatus rv;
   9432     int len = 0;
   9433     SECItemArray *statusToSend = NULL;
   9434     SSL3KEAType certIndex;
   9435 
   9436     SSL_TRC(3, ("%d: SSL3[%d]: send certificate status handshake",
   9437 		SSL_GETPID(), ss->fd));
   9438 
   9439     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   9440     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   9441     PORT_Assert( ss->sec.isServer);
   9442 
   9443     if (!ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn))
   9444 	return SECSuccess;
   9445 
   9446     /* Use certStatus based on the cert being used. */
   9447     if ((ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) ||
   9448 	(ss->ssl3.hs.kea_def->kea == kea_dhe_rsa)) {
   9449 	certIndex = kt_rsa;
   9450     } else {
   9451 	certIndex = ss->ssl3.hs.kea_def->exchKeyType;
   9452     }
   9453     if (ss->certStatusArray[certIndex] && ss->certStatusArray[certIndex]->len) {
   9454 	statusToSend = ss->certStatusArray[certIndex];
   9455     }
   9456     if (!statusToSend)
   9457 	return SECSuccess;
   9458 
   9459     /* Use the array's first item only (single stapling) */
   9460     len = 1 + statusToSend->items[0].len + 3;
   9461 
   9462     rv = ssl3_AppendHandshakeHeader(ss, certificate_status, len);
   9463     if (rv != SECSuccess) {
   9464 	return rv; 		/* err set by AppendHandshake. */
   9465     }
   9466     rv = ssl3_AppendHandshakeNumber(ss, 1 /*ocsp*/, 1);
   9467     if (rv != SECSuccess)
   9468 	return rv; 		/* err set by AppendHandshake. */
   9469 
   9470     rv = ssl3_AppendHandshakeVariable(ss,
   9471 				      statusToSend->items[0].data,
   9472 				      statusToSend->items[0].len,
   9473 				      3);
   9474     if (rv != SECSuccess)
   9475 	return rv; 		/* err set by AppendHandshake. */
   9476 
   9477     return SECSuccess;
   9478 }
   9479 
   9480 /* This is used to delete the CA certificates in the peer certificate chain
   9481  * from the cert database after they've been validated.
   9482  */
   9483 static void
   9484 ssl3_CleanupPeerCerts(sslSocket *ss)
   9485 {
   9486     PLArenaPool * arena = ss->ssl3.peerCertArena;
   9487     ssl3CertNode *certs = (ssl3CertNode *)ss->ssl3.peerCertChain;
   9488 
   9489     for (; certs; certs = certs->next) {
   9490 	CERT_DestroyCertificate(certs->cert);
   9491     }
   9492     if (arena) PORT_FreeArena(arena, PR_FALSE);
   9493     ss->ssl3.peerCertArena = NULL;
   9494     ss->ssl3.peerCertChain = NULL;
   9495 }
   9496 
   9497 static void
   9498 ssl3_CopyPeerCertsFromSID(sslSocket *ss, sslSessionID *sid)
   9499 {
   9500     PLArenaPool *arena;
   9501     ssl3CertNode *lastCert = NULL;
   9502     ssl3CertNode *certs = NULL;
   9503     int i;
   9504 
   9505     if (!sid->peerCertChain[0])
   9506 	return;
   9507     PORT_Assert(!ss->ssl3.peerCertArena);
   9508     PORT_Assert(!ss->ssl3.peerCertChain);
   9509     ss->ssl3.peerCertArena = arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   9510     for (i = 0; i < MAX_PEER_CERT_CHAIN_SIZE && sid->peerCertChain[i]; i++) {
   9511 	ssl3CertNode *c = PORT_ArenaNew(arena, ssl3CertNode);
   9512 	c->cert = CERT_DupCertificate(sid->peerCertChain[i]);
   9513 	c->next = NULL;
   9514 	if (lastCert) {
   9515 	    lastCert->next = c;
   9516 	} else {
   9517 	    certs = c;
   9518 	}
   9519 	lastCert = c;
   9520     }
   9521     ss->ssl3.peerCertChain = certs;
   9522 }
   9523 
   9524 static void
   9525 ssl3_CopyPeerCertsToSID(ssl3CertNode *certs, sslSessionID *sid)
   9526 {
   9527     int i = 0;
   9528     ssl3CertNode *c = certs;
   9529     for (; i < MAX_PEER_CERT_CHAIN_SIZE && c; i++, c = c->next) {
   9530 	PORT_Assert(!sid->peerCertChain[i]);
   9531 	sid->peerCertChain[i] = CERT_DupCertificate(c->cert);
   9532     }
   9533 }
   9534 
   9535 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   9536  * ssl3 CertificateStatus message.
   9537  * Caller must hold Handshake and RecvBuf locks.
   9538  * This is always called before ssl3_HandleCertificate, even if the Certificate
   9539  * message is sent first.
   9540  */
   9541 static SECStatus
   9542 ssl3_HandleCertificateStatus(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   9543 {
   9544     PRInt32 status, len;
   9545 
   9546     if (ss->ssl3.hs.ws != wait_certificate_status) {
   9547         (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   9548         PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_STATUS);
   9549         return SECFailure;
   9550     }
   9551 
   9552     PORT_Assert(!ss->sec.isServer);
   9553 
   9554     /* Consume the CertificateStatusType enum */
   9555     status = ssl3_ConsumeHandshakeNumber(ss, 1, &b, &length);
   9556     if (status != 1 /* ocsp */) {
   9557        goto format_loser;
   9558     }
   9559 
   9560     len = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   9561     if (len != length) {
   9562        goto format_loser;
   9563     }
   9564 
   9565 #define MAX_CERTSTATUS_LEN 0x1ffff   /* 128k - 1 */
   9566     if (length > MAX_CERTSTATUS_LEN)
   9567        goto format_loser;
   9568 #undef MAX_CERTSTATUS_LEN
   9569 
   9570     /* Array size 1, because we currently implement single-stapling only */
   9571     SECITEM_AllocArray(NULL, &ss->sec.ci.sid->peerCertStatus, 1);
   9572     if (!ss->sec.ci.sid->peerCertStatus.items)
   9573        return SECFailure;
   9574 
   9575     ss->sec.ci.sid->peerCertStatus.items[0].data = PORT_Alloc(length);
   9576 
   9577     if (!ss->sec.ci.sid->peerCertStatus.items[0].data) {
   9578         SECITEM_FreeArray(&ss->sec.ci.sid->peerCertStatus, PR_FALSE);
   9579         return SECFailure;
   9580     }
   9581 
   9582     PORT_Memcpy(ss->sec.ci.sid->peerCertStatus.items[0].data, b, length);
   9583     ss->sec.ci.sid->peerCertStatus.items[0].len = length;
   9584     ss->sec.ci.sid->peerCertStatus.items[0].type = siBuffer;
   9585 
   9586     return ssl3_AuthCertificate(ss);
   9587 
   9588 format_loser:
   9589     return ssl3_DecodeError(ss);
   9590 }
   9591 
   9592 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   9593  * ssl3 Certificate message.
   9594  * Caller must hold Handshake and RecvBuf locks.
   9595  */
   9596 static SECStatus
   9597 ssl3_HandleCertificate(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   9598 {
   9599     ssl3CertNode *   c;
   9600     ssl3CertNode *   lastCert 	= NULL;
   9601     PRInt32          remaining  = 0;
   9602     PRInt32          size;
   9603     SECStatus        rv;
   9604     PRBool           isServer	= (PRBool)(!!ss->sec.isServer);
   9605     PRBool           isTLS;
   9606     SSL3AlertDescription desc;
   9607     int              errCode    = SSL_ERROR_RX_MALFORMED_CERTIFICATE;
   9608     SECItem          certItem;
   9609 
   9610     SSL_TRC(3, ("%d: SSL3[%d]: handle certificate handshake",
   9611 		SSL_GETPID(), ss->fd));
   9612     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   9613     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   9614 
   9615     if ((ss->ssl3.hs.ws != wait_server_cert) &&
   9616 	(ss->ssl3.hs.ws != wait_client_cert)) {
   9617 	desc    = unexpected_message;
   9618 	errCode = SSL_ERROR_RX_UNEXPECTED_CERTIFICATE;
   9619 	goto alert_loser;
   9620     }
   9621 
   9622     if (ss->sec.peerCert != NULL) {
   9623 	if (ss->sec.peerKey) {
   9624 	    SECKEY_DestroyPublicKey(ss->sec.peerKey);
   9625 	    ss->sec.peerKey = NULL;
   9626 	}
   9627 	CERT_DestroyCertificate(ss->sec.peerCert);
   9628 	ss->sec.peerCert = NULL;
   9629     }
   9630 
   9631     ssl3_CleanupPeerCerts(ss);
   9632     isTLS = (PRBool)(ss->ssl3.prSpec->version > SSL_LIBRARY_VERSION_3_0);
   9633 
   9634     /* It is reported that some TLS client sends a Certificate message
   9635     ** with a zero-length message body.  We'll treat that case like a
   9636     ** normal no_certificates message to maximize interoperability.
   9637     */
   9638     if (length) {
   9639 	remaining = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   9640 	if (remaining < 0)
   9641 	    goto loser;	/* fatal alert already sent by ConsumeHandshake. */
   9642 	if ((PRUint32)remaining > length)
   9643 	    goto decode_loser;
   9644     }
   9645 
   9646     if (!remaining) {
   9647 	if (!(isTLS && isServer)) {
   9648 	    desc = bad_certificate;
   9649 	    goto alert_loser;
   9650 	}
   9651     	/* This is TLS's version of a no_certificate alert. */
   9652     	/* I'm a server. I've requested a client cert. He hasn't got one. */
   9653 	rv = ssl3_HandleNoCertificate(ss);
   9654 	if (rv != SECSuccess) {
   9655 	    errCode = PORT_GetError();
   9656 	    goto loser;
   9657 	}
   9658        ss->ssl3.hs.ws = wait_client_key;
   9659        return SECSuccess;
   9660     }
   9661 
   9662     ss->ssl3.peerCertArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
   9663     if (ss->ssl3.peerCertArena == NULL) {
   9664 	goto loser;	/* don't send alerts on memory errors */
   9665     }
   9666 
   9667     /* First get the peer cert. */
   9668     remaining -= 3;
   9669     if (remaining < 0)
   9670 	goto decode_loser;
   9671 
   9672     size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   9673     if (size <= 0)
   9674 	goto loser;	/* fatal alert already sent by ConsumeHandshake. */
   9675 
   9676     if (remaining < size)
   9677 	goto decode_loser;
   9678 
   9679     certItem.data = b;
   9680     certItem.len = size;
   9681     b      += size;
   9682     length -= size;
   9683     remaining -= size;
   9684 
   9685     ss->sec.peerCert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
   9686                                             PR_FALSE, PR_TRUE);
   9687     if (ss->sec.peerCert == NULL) {
   9688 	/* We should report an alert if the cert was bad, but not if the
   9689 	 * problem was just some local problem, like memory error.
   9690 	 */
   9691 	goto ambiguous_err;
   9692     }
   9693 
   9694     /* Now get all of the CA certs. */
   9695     while (remaining > 0) {
   9696 	remaining -= 3;
   9697 	if (remaining < 0)
   9698 	    goto decode_loser;
   9699 
   9700 	size = ssl3_ConsumeHandshakeNumber(ss, 3, &b, &length);
   9701 	if (size <= 0)
   9702 	    goto loser;	/* fatal alert already sent by ConsumeHandshake. */
   9703 
   9704 	if (remaining < size)
   9705 	    goto decode_loser;
   9706 
   9707 	certItem.data = b;
   9708 	certItem.len = size;
   9709 	b      += size;
   9710 	length -= size;
   9711 	remaining -= size;
   9712 
   9713 	c = PORT_ArenaNew(ss->ssl3.peerCertArena, ssl3CertNode);
   9714 	if (c == NULL) {
   9715 	    goto loser;	/* don't send alerts on memory errors */
   9716 	}
   9717 
   9718 	c->cert = CERT_NewTempCertificate(ss->dbHandle, &certItem, NULL,
   9719 	                                  PR_FALSE, PR_TRUE);
   9720 	if (c->cert == NULL) {
   9721 	    goto ambiguous_err;
   9722 	}
   9723 
   9724 	c->next = NULL;
   9725 	if (lastCert) {
   9726 	    lastCert->next = c;
   9727 	} else {
   9728 	    ss->ssl3.peerCertChain = c;
   9729 	}
   9730 	lastCert = c;
   9731     }
   9732 
   9733     if (remaining != 0)
   9734         goto decode_loser;
   9735 
   9736     SECKEY_UpdateCertPQG(ss->sec.peerCert);
   9737 
   9738     if (!isServer && ssl3_ExtensionNegotiated(ss, ssl_cert_status_xtn)) {
   9739        ss->ssl3.hs.ws = wait_certificate_status;
   9740        rv = SECSuccess;
   9741     } else {
   9742        rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
   9743     }
   9744 
   9745     return rv;
   9746 
   9747 ambiguous_err:
   9748     errCode = PORT_GetError();
   9749     switch (errCode) {
   9750     case PR_OUT_OF_MEMORY_ERROR:
   9751     case SEC_ERROR_BAD_DATABASE:
   9752     case SEC_ERROR_NO_MEMORY:
   9753        if (isTLS) {
   9754            desc = internal_error;
   9755            goto alert_loser;
   9756        }
   9757        goto loser;
   9758     }
   9759     ssl3_SendAlertForCertError(ss, errCode);
   9760     goto loser;
   9761 
   9762 decode_loser:
   9763     desc = isTLS ? decode_error : bad_certificate;
   9764 
   9765 alert_loser:
   9766     (void)SSL3_SendAlert(ss, alert_fatal, desc);
   9767 
   9768 loser:
   9769     (void)ssl_MapLowLevelError(errCode);
   9770     return SECFailure;
   9771 }
   9772 
   9773 static SECStatus
   9774 ssl3_AuthCertificate(sslSocket *ss)
   9775 {
   9776     SECStatus        rv;
   9777     PRBool           isServer   = (PRBool)(!!ss->sec.isServer);
   9778     int              errCode;
   9779 
   9780     ss->ssl3.hs.authCertificatePending = PR_FALSE;
   9781 
   9782     /*
   9783      * Ask caller-supplied callback function to validate cert chain.
   9784      */
   9785     rv = (SECStatus)(*ss->authCertificate)(ss->authCertificateArg, ss->fd,
   9786 					   PR_TRUE, isServer);
   9787     if (rv) {
   9788 	errCode = PORT_GetError();
   9789 	if (rv != SECWouldBlock) {
   9790 	    if (ss->handleBadCert) {
   9791 		rv = (*ss->handleBadCert)(ss->badCertArg, ss->fd);
   9792 	    }
   9793 	}
   9794 
   9795 	if (rv == SECWouldBlock) {
   9796 	    if (ss->sec.isServer) {
   9797 		errCode = SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS;
   9798 		rv = SECFailure;
   9799 		goto loser;
   9800 	    }
   9801 
   9802 	    ss->ssl3.hs.authCertificatePending = PR_TRUE;
   9803 	    rv = SECSuccess;
   9804 
   9805 	    /* XXX: Async cert validation and False Start don't work together
   9806 	     * safely yet; if we leave False Start enabled, we may end up false
   9807 	     * starting (sending application data) before we
   9808 	     * SSL_AuthCertificateComplete has been called.
   9809 	     */
   9810 	    ss->opt.enableFalseStart = PR_FALSE;
   9811 	}
   9812 
   9813 	if (rv != SECSuccess) {
   9814 	    ssl3_SendAlertForCertError(ss, errCode);
   9815 	    goto loser;
   9816 	}
   9817     }
   9818 
   9819     ss->sec.ci.sid->peerCert = CERT_DupCertificate(ss->sec.peerCert);
   9820     ssl3_CopyPeerCertsToSID(ss->ssl3.peerCertChain, ss->sec.ci.sid);
   9821 
   9822     if (!ss->sec.isServer) {
   9823         CERTCertificate *cert = ss->sec.peerCert;
   9824 
   9825 	/* set the server authentication and key exchange types and sizes
   9826 	** from the value in the cert.  If the key exchange key is different,
   9827 	** it will get fixed when we handle the server key exchange message.
   9828 	*/
   9829 	SECKEYPublicKey * pubKey  = CERT_ExtractPublicKey(cert);
   9830 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
   9831 	ss->sec.keaType       = ss->ssl3.hs.kea_def->exchKeyType;
   9832 	if (pubKey) {
   9833 	    ss->sec.keaKeyBits = ss->sec.authKeyBits =
   9834 		SECKEY_PublicKeyStrengthInBits(pubKey);
   9835 #ifdef NSS_ENABLE_ECC
   9836 	    if (ss->sec.keaType == kt_ecdh) {
   9837 		/* Get authKeyBits from signing key.
   9838 		 * XXX The code below uses a quick approximation of
   9839 		 * key size based on cert->signatureWrap.signature.data
   9840 		 * (which contains the DER encoded signature). The field
   9841 		 * cert->signatureWrap.signature.len contains the
   9842 		 * length of the encoded signature in bits.
   9843 		 */
   9844 		if (ss->ssl3.hs.kea_def->kea == kea_ecdh_ecdsa) {
   9845 		    ss->sec.authKeyBits =
   9846 			cert->signatureWrap.signature.data[3]*8;
   9847 		    if (cert->signatureWrap.signature.data[4] == 0x00)
   9848 			    ss->sec.authKeyBits -= 8;
   9849 		    /*
   9850 		     * XXX: if cert is not signed by ecdsa we should
   9851 		     * destroy pubKey and goto bad_cert
   9852 		     */
   9853 		} else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
   9854 		    ss->sec.authKeyBits = cert->signatureWrap.signature.len;
   9855 		    /*
   9856 		     * XXX: if cert is not signed by rsa we should
   9857 		     * destroy pubKey and goto bad_cert
   9858 		     */
   9859 		}
   9860 	    }
   9861 #endif /* NSS_ENABLE_ECC */
   9862 	    SECKEY_DestroyPublicKey(pubKey);
   9863 	    pubKey = NULL;
   9864     	}
   9865 
   9866 	ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
   9867 	if (ss->ssl3.hs.kea_def->is_limited ||
   9868 	    /* XXX OR server cert is signing only. */
   9869 #ifdef NSS_ENABLE_ECC
   9870 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
   9871 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
   9872 #endif /* NSS_ENABLE_ECC */
   9873 	    ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
   9874 	    ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
   9875 	}
   9876     } else {
   9877 	ss->ssl3.hs.ws = wait_client_key;
   9878     }
   9879 
   9880     PORT_Assert(rv == SECSuccess);
   9881     if (rv != SECSuccess) {
   9882 	errCode = SEC_ERROR_LIBRARY_FAILURE;
   9883 	rv = SECFailure;
   9884 	goto loser;
   9885     }
   9886 
   9887     return rv;
   9888 
   9889 loser:
   9890     (void)ssl_MapLowLevelError(errCode);
   9891     return SECFailure;
   9892 }
   9893 
   9894 static SECStatus ssl3_FinishHandshake(sslSocket *ss);
   9895 
   9896 static SECStatus
   9897 ssl3_AlwaysFail(sslSocket * ss)
   9898 {
   9899     PORT_SetError(PR_INVALID_STATE_ERROR);
   9900     return SECFailure;
   9901 }
   9902 
   9903 /* Caller must hold 1stHandshakeLock.
   9904 */
   9905 SECStatus
   9906 ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error)
   9907 {
   9908     SECStatus rv;
   9909 
   9910     PORT_Assert(ss->opt.noLocks || ssl_Have1stHandshakeLock(ss));
   9911 
   9912     if (ss->sec.isServer) {
   9913 	PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SERVERS);
   9914 	return SECFailure;
   9915     }
   9916 
   9917     ssl_GetRecvBufLock(ss);
   9918     ssl_GetSSL3HandshakeLock(ss);
   9919 
   9920     if (!ss->ssl3.hs.authCertificatePending) {
   9921 	PORT_SetError(PR_INVALID_STATE_ERROR);
   9922 	rv = SECFailure;
   9923 	goto done;
   9924     }
   9925 
   9926     ss->ssl3.hs.authCertificatePending = PR_FALSE;
   9927 
   9928     if (error != 0) {
   9929 	ss->ssl3.hs.restartTarget = ssl3_AlwaysFail;
   9930 	ssl3_SendAlertForCertError(ss, error);
   9931 	rv = SECSuccess;
   9932     } else if (ss->ssl3.hs.restartTarget != NULL) {
   9933 	sslRestartTarget target = ss->ssl3.hs.restartTarget;
   9934 	ss->ssl3.hs.restartTarget = NULL;
   9935 	rv = target(ss);
   9936 	/* Even if we blocked here, we have accomplished enough to claim
   9937 	 * success. Any remaining work will be taken care of by subsequent
   9938 	 * calls to SSL_ForceHandshake/PR_Send/PR_Read/etc.
   9939 	 */
   9940 	if (rv == SECWouldBlock) {
   9941 	    rv = SECSuccess;
   9942 	}
   9943     } else {
   9944 	rv = SECSuccess;
   9945     }
   9946 
   9947 done:
   9948     ssl_ReleaseSSL3HandshakeLock(ss);
   9949     ssl_ReleaseRecvBufLock(ss);
   9950 
   9951     return rv;
   9952 }
   9953 
   9954 static SECStatus
   9955 ssl3_ComputeTLSFinished(ssl3CipherSpec *spec,
   9956 			PRBool          isServer,
   9957                 const   SSL3Hashes   *  hashes,
   9958                         TLSFinished  *  tlsFinished)
   9959 {
   9960     const char * label;
   9961     unsigned int len;
   9962     SECStatus    rv;
   9963 
   9964     label = isServer ? "server finished" : "client finished";
   9965     len   = 15;
   9966 
   9967     rv = ssl3_TLSPRFWithMasterSecret(spec, label, len, hashes->u.raw,
   9968 	hashes->len, tlsFinished->verify_data,
   9969 	sizeof tlsFinished->verify_data);
   9970 
   9971     return rv;
   9972 }
   9973 
   9974 /* The calling function must acquire and release the appropriate
   9975  * lock (e.g., ssl_GetSpecReadLock / ssl_ReleaseSpecReadLock for
   9976  * ss->ssl3.crSpec).
   9977  */
   9978 SECStatus
   9979 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec, const char *label,
   9980     unsigned int labelLen, const unsigned char *val, unsigned int valLen,
   9981     unsigned char *out, unsigned int outLen)
   9982 {
   9983     SECStatus rv = SECSuccess;
   9984 
   9985     if (spec->master_secret && !spec->bypassCiphers) {
   9986 	SECItem param = {siBuffer, NULL, 0};
   9987 	CK_MECHANISM_TYPE mech = CKM_TLS_PRF_GENERAL;
   9988 	PK11Context *prf_context;
   9989 	unsigned int retLen;
   9990 
   9991 	if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   9992 	    mech = CKM_NSS_TLS_PRF_GENERAL_SHA256;
   9993 	}
   9994 	prf_context = PK11_CreateContextBySymKey(mech, CKA_SIGN,
   9995 						 spec->master_secret, &param);
   9996 	if (!prf_context)
   9997 	    return SECFailure;
   9998 
   9999 	rv  = PK11_DigestBegin(prf_context);
   10000 	rv |= PK11_DigestOp(prf_context, (unsigned char *) label, labelLen);
   10001 	rv |= PK11_DigestOp(prf_context, val, valLen);
   10002 	rv |= PK11_DigestFinal(prf_context, out, &retLen, outLen);
   10003 	PORT_Assert(rv != SECSuccess || retLen == outLen);
   10004 
   10005 	PK11_DestroyContext(prf_context, PR_TRUE);
   10006     } else {
   10007 	/* bypass PKCS11 */
   10008 #ifdef NO_PKCS11_BYPASS
   10009 	PORT_Assert(spec->master_secret);
   10010 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   10011 	rv = SECFailure;
   10012 #else
   10013 	SECItem inData  = { siBuffer, };
   10014 	SECItem outData = { siBuffer, };
   10015 	PRBool isFIPS   = PR_FALSE;
   10016 
   10017 	inData.data  = (unsigned char *) val;
   10018 	inData.len   = valLen;
   10019 	outData.data = out;
   10020 	outData.len  = outLen;
   10021 	if (spec->version >= SSL_LIBRARY_VERSION_TLS_1_2) {
   10022 	    rv = TLS_P_hash(HASH_AlgSHA256, &spec->msItem, label, &inData,
   10023 			    &outData, isFIPS);
   10024 	} else {
   10025 	    rv = TLS_PRF(&spec->msItem, label, &inData, &outData, isFIPS);
   10026 	}
   10027 	PORT_Assert(rv != SECSuccess || outData.len == outLen);
   10028 #endif
   10029     }
   10030     return rv;
   10031 }
   10032 
   10033 /* called from ssl3_HandleServerHelloDone
   10034  */
   10035 static SECStatus
   10036 ssl3_SendNextProto(sslSocket *ss)
   10037 {
   10038     SECStatus rv;
   10039     int padding_len;
   10040     static const unsigned char padding[32] = {0};
   10041 
   10042     if (ss->ssl3.nextProto.len == 0 ||
   10043         ss->ssl3.nextProtoState == SSL_NEXT_PROTO_SELECTED) {
   10044 	return SECSuccess;
   10045     }
   10046 
   10047     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   10048     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10049 
   10050     padding_len = 32 - ((ss->ssl3.nextProto.len + 2) % 32);
   10051 
   10052     rv = ssl3_AppendHandshakeHeader(ss, next_proto, ss->ssl3.nextProto.len +
   10053 						    2 + padding_len);
   10054     if (rv != SECSuccess) {
   10055 	return rv;	/* error code set by AppendHandshakeHeader */
   10056     }
   10057     rv = ssl3_AppendHandshakeVariable(ss, ss->ssl3.nextProto.data,
   10058 				      ss->ssl3.nextProto.len, 1);
   10059     if (rv != SECSuccess) {
   10060 	return rv;	/* error code set by AppendHandshake */
   10061     }
   10062     rv = ssl3_AppendHandshakeVariable(ss, padding, padding_len, 1);
   10063     if (rv != SECSuccess) {
   10064 	return rv;	/* error code set by AppendHandshake */
   10065     }
   10066     return rv;
   10067 }
   10068 
   10069 /* called from ssl3_SendFinished
   10070  *
   10071  * This function is simply a debugging aid and therefore does not return a
   10072  * SECStatus. */
   10073 static void
   10074 ssl3_RecordKeyLog(sslSocket *ss)
   10075 {
   10076     sslSessionID *sid;
   10077     SECStatus rv;
   10078     SECItem *keyData;
   10079     char buf[14 /* "CLIENT_RANDOM " */ +
   10080 	     SSL3_RANDOM_LENGTH*2 /* client_random */ +
   10081 	     1 /* " " */ +
   10082 	     48*2 /* master secret */ +
   10083              1 /* new line */];
   10084     unsigned int j;
   10085 
   10086     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10087 
   10088     sid = ss->sec.ci.sid;
   10089 
   10090     if (!ssl_keylog_iob)
   10091 	return;
   10092 
   10093     rv = PK11_ExtractKeyValue(ss->ssl3.cwSpec->master_secret);
   10094     if (rv != SECSuccess)
   10095 	return;
   10096 
   10097     ssl_GetSpecReadLock(ss);
   10098 
   10099     /* keyData does not need to be freed. */
   10100     keyData = PK11_GetKeyData(ss->ssl3.cwSpec->master_secret);
   10101     if (!keyData || !keyData->data || keyData->len != 48) {
   10102 	ssl_ReleaseSpecReadLock(ss);
   10103 	return;
   10104     }
   10105 
   10106     /* https://developer.mozilla.org/en/NSS_Key_Log_Format */
   10107 
   10108     /* There could be multiple, concurrent writers to the
   10109      * keylog, so we have to do everything in a single call to
   10110      * fwrite. */
   10111 
   10112     memcpy(buf, "CLIENT_RANDOM ", 14);
   10113     j = 14;
   10114     hexEncode(buf + j, ss->ssl3.hs.client_random.rand, SSL3_RANDOM_LENGTH);
   10115     j += SSL3_RANDOM_LENGTH*2;
   10116     buf[j++] = ' ';
   10117     hexEncode(buf + j, keyData->data, 48);
   10118     j += 48*2;
   10119     buf[j++] = '\n';
   10120 
   10121     PORT_Assert(j == sizeof(buf));
   10122 
   10123     ssl_ReleaseSpecReadLock(ss);
   10124 
   10125     if (fwrite(buf, sizeof(buf), 1, ssl_keylog_iob) != 1)
   10126         return;
   10127     fflush(ssl_keylog_iob);
   10128     return;
   10129 }
   10130 
   10131 /* called from ssl3_SendClientSecondRound
   10132  *	     ssl3_HandleFinished
   10133  */
   10134 static SECStatus
   10135 ssl3_SendEncryptedExtensions(sslSocket *ss)
   10136 {
   10137     static const char CHANNEL_ID_MAGIC[] = "TLS Channel ID signature";
   10138     /* This is the ASN.1 prefix for a P-256 public key. Specifically it's:
   10139      * SEQUENCE
   10140      *   SEQUENCE
   10141      *     OID id-ecPublicKey
   10142      *     OID prime256v1
   10143      *   BIT STRING, length 66, 0 trailing bits: 0x04
   10144      *
   10145      * The 0x04 in the BIT STRING is the prefix for an uncompressed, X9.62
   10146      * public key. Following that are the two field elements as 32-byte,
   10147      * big-endian numbers, as required by the Channel ID. */
   10148     static const unsigned char P256_SPKI_PREFIX[] = {
   10149 	0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,
   10150 	0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,
   10151 	0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
   10152 	0x42, 0x00, 0x04
   10153     };
   10154     /* ChannelIDs are always 128 bytes long: 64 bytes of P-256 public key and 64
   10155      * bytes of ECDSA signature. */
   10156     static const int CHANNEL_ID_PUBLIC_KEY_LENGTH = 64;
   10157     static const int CHANNEL_ID_LENGTH = 128;
   10158 
   10159     SECStatus rv = SECFailure;
   10160     SECItem *spki = NULL;
   10161     SSL3Hashes hashes;
   10162     const unsigned char *pub_bytes;
   10163     unsigned char signed_data[sizeof(CHANNEL_ID_MAGIC) + sizeof(SSL3Hashes)];
   10164     unsigned char digest[SHA256_LENGTH];
   10165     SECItem digest_item;
   10166     unsigned char signature[64];
   10167     SECItem signature_item;
   10168 
   10169     PORT_Assert(ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   10170     PORT_Assert(ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10171 
   10172     if (ss->ssl3.channelID == NULL)
   10173 	return SECSuccess;
   10174 
   10175     PORT_Assert(ssl3_ExtensionNegotiated(ss, ssl_channel_id_xtn));
   10176 
   10177     if (SECKEY_GetPrivateKeyType(ss->ssl3.channelID) != ecKey ||
   10178 	PK11_SignatureLen(ss->ssl3.channelID) != sizeof(signature)) {
   10179 	PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
   10180 	rv = SECFailure;
   10181 	goto loser;
   10182     }
   10183 
   10184     ssl_GetSpecReadLock(ss);
   10185     rv = ssl3_ComputeHandshakeHashes(ss, ss->ssl3.cwSpec, &hashes, 0);
   10186     ssl_ReleaseSpecReadLock(ss);
   10187 
   10188     if (rv != SECSuccess)
   10189 	goto loser;
   10190 
   10191     rv = ssl3_AppendHandshakeHeader(ss, encrypted_extensions,
   10192 				    2 + 2 + CHANNEL_ID_LENGTH);
   10193     if (rv != SECSuccess)
   10194 	goto loser;	/* error code set by AppendHandshakeHeader */
   10195     rv = ssl3_AppendHandshakeNumber(ss, ssl_channel_id_xtn, 2);
   10196     if (rv != SECSuccess)
   10197 	goto loser;	/* error code set by AppendHandshake */
   10198     rv = ssl3_AppendHandshakeNumber(ss, CHANNEL_ID_LENGTH, 2);
   10199     if (rv != SECSuccess)
   10200 	goto loser;	/* error code set by AppendHandshake */
   10201 
   10202     spki = SECKEY_EncodeDERSubjectPublicKeyInfo(ss->ssl3.channelIDPub);
   10203 
   10204     if (spki->len != sizeof(P256_SPKI_PREFIX) + CHANNEL_ID_PUBLIC_KEY_LENGTH ||
   10205 	memcmp(spki->data, P256_SPKI_PREFIX, sizeof(P256_SPKI_PREFIX) != 0)) {
   10206 	PORT_SetError(SSL_ERROR_INVALID_CHANNEL_ID_KEY);
   10207 	rv = SECFailure;
   10208 	goto loser;
   10209     }
   10210 
   10211     pub_bytes = spki->data + sizeof(P256_SPKI_PREFIX);
   10212 
   10213     memcpy(signed_data, CHANNEL_ID_MAGIC, sizeof(CHANNEL_ID_MAGIC));
   10214     memcpy(signed_data + sizeof(CHANNEL_ID_MAGIC), hashes.u.raw, hashes.len);
   10215 
   10216     rv = PK11_HashBuf(SEC_OID_SHA256, digest, signed_data,
   10217 		      sizeof(CHANNEL_ID_MAGIC) + hashes.len);
   10218     if (rv != SECSuccess)
   10219 	goto loser;
   10220 
   10221     digest_item.data = digest;
   10222     digest_item.len = sizeof(digest);
   10223 
   10224     signature_item.data = signature;
   10225     signature_item.len = sizeof(signature);
   10226 
   10227     rv = PK11_Sign(ss->ssl3.channelID, &signature_item, &digest_item);
   10228     if (rv != SECSuccess)
   10229 	goto loser;
   10230 
   10231     rv = ssl3_AppendHandshake(ss, pub_bytes, CHANNEL_ID_PUBLIC_KEY_LENGTH);
   10232     if (rv != SECSuccess)
   10233 	goto loser;
   10234     rv = ssl3_AppendHandshake(ss, signature, sizeof(signature));
   10235 
   10236 loser:
   10237     if (spki)
   10238 	SECITEM_FreeItem(spki, PR_TRUE);
   10239     if (ss->ssl3.channelID) {
   10240 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   10241 	ss->ssl3.channelID = NULL;
   10242     }
   10243     if (ss->ssl3.channelIDPub) {
   10244 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   10245 	ss->ssl3.channelIDPub = NULL;
   10246     }
   10247 
   10248     return rv;
   10249 }
   10250 
   10251 /* ssl3_RestartHandshakeAfterChannelIDReq is called to restart a handshake
   10252  * after a ChannelID callback returned SECWouldBlock. At this point we have
   10253  * processed the server's ServerHello but not yet any further messages. We will
   10254  * always get a message from the server after a ServerHello so either they are
   10255  * waiting in the buffer or we'll get network I/O. */
   10256 SECStatus
   10257 ssl3_RestartHandshakeAfterChannelIDReq(sslSocket *ss,
   10258 				       SECKEYPublicKey *channelIDPub,
   10259 				       SECKEYPrivateKey *channelID)
   10260 {
   10261     if (ss->handshake == 0) {
   10262 	SECKEY_DestroyPublicKey(channelIDPub);
   10263 	SECKEY_DestroyPrivateKey(channelID);
   10264 	PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   10265 	return SECFailure;
   10266     }
   10267 
   10268     if (channelIDPub == NULL ||
   10269 	channelID == NULL) {
   10270 	if (channelIDPub)
   10271 	    SECKEY_DestroyPublicKey(channelIDPub);
   10272 	if (channelID)
   10273 	    SECKEY_DestroyPrivateKey(channelID);
   10274 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   10275 	return SECFailure;
   10276     }
   10277 
   10278     if (ss->ssl3.channelID)
   10279 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   10280     if (ss->ssl3.channelIDPub)
   10281 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   10282 
   10283     ss->handshake = ssl_GatherRecord1stHandshake;
   10284     ss->ssl3.channelID = channelID;
   10285     ss->ssl3.channelIDPub = channelIDPub;
   10286 
   10287     return SECSuccess;
   10288 }
   10289 
   10290 /* called from ssl3_HandleServerHelloDone
   10291  *             ssl3_HandleClientHello
   10292  *             ssl3_HandleFinished
   10293  */
   10294 static SECStatus
   10295 ssl3_SendFinished(sslSocket *ss, PRInt32 flags)
   10296 {
   10297     ssl3CipherSpec *cwSpec;
   10298     PRBool          isTLS;
   10299     PRBool          isServer = ss->sec.isServer;
   10300     SECStatus       rv;
   10301     SSL3Sender      sender = isServer ? sender_server : sender_client;
   10302     SSL3Hashes      hashes;
   10303     TLSFinished     tlsFinished;
   10304 
   10305     SSL_TRC(3, ("%d: SSL3[%d]: send finished handshake", SSL_GETPID(), ss->fd));
   10306 
   10307     PORT_Assert( ss->opt.noLocks || ssl_HaveXmitBufLock(ss));
   10308     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   10309 
   10310     ssl_GetSpecReadLock(ss);
   10311     cwSpec = ss->ssl3.cwSpec;
   10312     isTLS = (PRBool)(cwSpec->version > SSL_LIBRARY_VERSION_3_0);
   10313     rv = ssl3_ComputeHandshakeHashes(ss, cwSpec, &hashes, sender);
   10314     if (isTLS && rv == SECSuccess) {
   10315 	rv = ssl3_ComputeTLSFinished(cwSpec, isServer, &hashes, &tlsFinished);
   10316     }
   10317     ssl_ReleaseSpecReadLock(ss);
   10318     if (rv != SECSuccess) {
   10319 	goto fail;	/* err code was set by ssl3_ComputeHandshakeHashes */
   10320     }
   10321 
   10322     if (isTLS) {
   10323 	if (isServer)
   10324 	    ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
   10325 	else
   10326 	    ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
   10327 	ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
   10328 	rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof tlsFinished);
   10329 	if (rv != SECSuccess)
   10330 	    goto fail; 		/* err set by AppendHandshake. */
   10331 	rv = ssl3_AppendHandshake(ss, &tlsFinished, sizeof tlsFinished);
   10332 	if (rv != SECSuccess)
   10333 	    goto fail; 		/* err set by AppendHandshake. */
   10334     } else {
   10335 	if (isServer)
   10336 	    ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes.u.s;
   10337 	else
   10338 	    ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes.u.s;
   10339 	PORT_Assert(hashes.len == sizeof hashes.u.s);
   10340 	ss->ssl3.hs.finishedBytes = sizeof hashes.u.s;
   10341 	rv = ssl3_AppendHandshakeHeader(ss, finished, sizeof hashes.u.s);
   10342 	if (rv != SECSuccess)
   10343 	    goto fail; 		/* err set by AppendHandshake. */
   10344 	rv = ssl3_AppendHandshake(ss, &hashes.u.s, sizeof hashes.u.s);
   10345 	if (rv != SECSuccess)
   10346 	    goto fail; 		/* err set by AppendHandshake. */
   10347     }
   10348     rv = ssl3_FlushHandshake(ss, flags);
   10349     if (rv != SECSuccess) {
   10350 	goto fail;	/* error code set by ssl3_FlushHandshake */
   10351     }
   10352 
   10353     ssl3_RecordKeyLog(ss);
   10354 
   10355     return SECSuccess;
   10356 
   10357 fail:
   10358     return rv;
   10359 }
   10360 
   10361 /* wrap the master secret, and put it into the SID.
   10362  * Caller holds the Spec read lock.
   10363  */
   10364 SECStatus
   10365 ssl3_CacheWrappedMasterSecret(sslSocket *ss, sslSessionID *sid,
   10366     ssl3CipherSpec *spec, SSL3KEAType effectiveExchKeyType)
   10367 {
   10368     PK11SymKey *      wrappingKey  = NULL;
   10369     PK11SlotInfo *    symKeySlot;
   10370     void *            pwArg        = ss->pkcs11PinArg;
   10371     SECStatus         rv           = SECFailure;
   10372     PRBool            isServer     = ss->sec.isServer;
   10373     CK_MECHANISM_TYPE mechanism    = CKM_INVALID_MECHANISM;
   10374     symKeySlot = PK11_GetSlotFromKey(spec->master_secret);
   10375     if (!isServer) {
   10376 	int  wrapKeyIndex;
   10377 	int  incarnation;
   10378 
   10379 	/* these next few functions are mere accessors and don't fail. */
   10380 	sid->u.ssl3.masterWrapIndex  = wrapKeyIndex =
   10381 				       PK11_GetCurrentWrapIndex(symKeySlot);
   10382 	PORT_Assert(wrapKeyIndex == 0);	/* array has only one entry! */
   10383 
   10384 	sid->u.ssl3.masterWrapSeries = incarnation =
   10385 				       PK11_GetSlotSeries(symKeySlot);
   10386 	sid->u.ssl3.masterSlotID   = PK11_GetSlotID(symKeySlot);
   10387 	sid->u.ssl3.masterModuleID = PK11_GetModuleID(symKeySlot);
   10388 	sid->u.ssl3.masterValid    = PR_TRUE;
   10389 	/* Get the default wrapping key, for wrapping the master secret before
   10390 	 * placing it in the SID cache entry. */
   10391 	wrappingKey = PK11_GetWrapKey(symKeySlot, wrapKeyIndex,
   10392 				      CKM_INVALID_MECHANISM, incarnation,
   10393 				      pwArg);
   10394 	if (wrappingKey) {
   10395 	    mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
   10396 	} else {
   10397 	    int keyLength;
   10398 	    /* if the wrappingKey doesn't exist, attempt to create it.
   10399 	     * Note: we intentionally ignore errors here.  If we cannot
   10400 	     * generate a wrapping key, it is not fatal to this SSL connection,
   10401 	     * but we will not be able to restart this session.
   10402 	     */
   10403 	    mechanism = PK11_GetBestWrapMechanism(symKeySlot);
   10404 	    keyLength = PK11_GetBestKeyLength(symKeySlot, mechanism);
   10405 	    /* Zero length means fixed key length algorithm, or error.
   10406 	     * It's ambiguous.
   10407 	     */
   10408 	    wrappingKey = PK11_KeyGen(symKeySlot, mechanism, NULL,
   10409 				      keyLength, pwArg);
   10410 	    if (wrappingKey) {
   10411 		PK11_SetWrapKey(symKeySlot, wrapKeyIndex, wrappingKey);
   10412 	    }
   10413 	}
   10414     } else {
   10415 	/* server socket using session cache. */
   10416 	mechanism = PK11_GetBestWrapMechanism(symKeySlot);
   10417 	if (mechanism != CKM_INVALID_MECHANISM) {
   10418 	    wrappingKey =
   10419 		getWrappingKey(ss, symKeySlot, effectiveExchKeyType,
   10420 			       mechanism, pwArg);
   10421 	    if (wrappingKey) {
   10422 		mechanism = PK11_GetMechanism(wrappingKey); /* can't fail. */
   10423 	    }
   10424 	}
   10425     }
   10426 
   10427     sid->u.ssl3.masterWrapMech = mechanism;
   10428     PK11_FreeSlot(symKeySlot);
   10429 
   10430     if (wrappingKey) {
   10431 	SECItem wmsItem;
   10432 
   10433 	wmsItem.data = sid->u.ssl3.keys.wrapped_master_secret;
   10434 	wmsItem.len  = sizeof sid->u.ssl3.keys.wrapped_master_secret;
   10435 	rv = PK11_WrapSymKey(mechanism, NULL, wrappingKey,
   10436 			     spec->master_secret, &wmsItem);
   10437 	/* rv is examined below. */
   10438 	sid->u.ssl3.keys.wrapped_master_secret_len = wmsItem.len;
   10439 	PK11_FreeSymKey(wrappingKey);
   10440     }
   10441     return rv;
   10442 }
   10443 
   10444 /* Called from ssl3_HandleHandshakeMessage() when it has deciphered a complete
   10445  * ssl3 Finished message from the peer.
   10446  * Caller must hold Handshake and RecvBuf locks.
   10447  */
   10448 static SECStatus
   10449 ssl3_HandleFinished(sslSocket *ss, SSL3Opaque *b, PRUint32 length,
   10450 		    const SSL3Hashes *hashes)
   10451 {
   10452     sslSessionID *    sid	   = ss->sec.ci.sid;
   10453     SECStatus         rv           = SECSuccess;
   10454     PRBool            isServer     = ss->sec.isServer;
   10455     PRBool            isTLS;
   10456     SSL3KEAType       effectiveExchKeyType;
   10457 
   10458     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   10459     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   10460 
   10461     SSL_TRC(3, ("%d: SSL3[%d]: handle finished handshake",
   10462     	SSL_GETPID(), ss->fd));
   10463 
   10464     if (ss->ssl3.hs.ws != wait_finished) {
   10465 	SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10466     	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_FINISHED);
   10467 	return SECFailure;
   10468     }
   10469 
   10470     isTLS = (PRBool)(ss->ssl3.crSpec->version > SSL_LIBRARY_VERSION_3_0);
   10471     if (isTLS) {
   10472 	TLSFinished tlsFinished;
   10473 
   10474 	if (length != sizeof tlsFinished) {
   10475 	    (void)SSL3_SendAlert(ss, alert_fatal, decode_error);
   10476 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
   10477 	    return SECFailure;
   10478 	}
   10479 	rv = ssl3_ComputeTLSFinished(ss->ssl3.crSpec, !isServer,
   10480 	                             hashes, &tlsFinished);
   10481 	if (!isServer)
   10482 	    ss->ssl3.hs.finishedMsgs.tFinished[1] = tlsFinished;
   10483 	else
   10484 	    ss->ssl3.hs.finishedMsgs.tFinished[0] = tlsFinished;
   10485 	ss->ssl3.hs.finishedBytes = sizeof tlsFinished;
   10486 	if (rv != SECSuccess ||
   10487 	    0 != NSS_SecureMemcmp(&tlsFinished, b, length)) {
   10488 	    (void)SSL3_SendAlert(ss, alert_fatal, decrypt_error);
   10489 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   10490 	    return SECFailure;
   10491 	}
   10492     } else {
   10493 	if (length != sizeof(SSL3Finished)) {
   10494 	    (void)ssl3_IllegalParameter(ss);
   10495 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_FINISHED);
   10496 	    return SECFailure;
   10497 	}
   10498 
   10499 	if (!isServer)
   10500 	    ss->ssl3.hs.finishedMsgs.sFinished[1] = hashes->u.s;
   10501 	else
   10502 	    ss->ssl3.hs.finishedMsgs.sFinished[0] = hashes->u.s;
   10503 	PORT_Assert(hashes->len == sizeof hashes->u.s);
   10504 	ss->ssl3.hs.finishedBytes = sizeof hashes->u.s;
   10505 	if (0 != NSS_SecureMemcmp(&hashes->u.s, b, length)) {
   10506 	    (void)ssl3_HandshakeFailure(ss);
   10507 	    PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
   10508 	    return SECFailure;
   10509 	}
   10510     }
   10511 
   10512     ssl_GetXmitBufLock(ss);	/*************************************/
   10513 
   10514     if ((isServer && !ss->ssl3.hs.isResuming) ||
   10515 	(!isServer && ss->ssl3.hs.isResuming)) {
   10516 	PRInt32 flags = 0;
   10517 
   10518 	/* Send a NewSessionTicket message if the client sent us
   10519 	 * either an empty session ticket, or one that did not verify.
   10520 	 * (Note that if either of these conditions was met, then the
   10521 	 * server has sent a SessionTicket extension in the
   10522 	 * ServerHello message.)
   10523 	 */
   10524 	if (isServer && !ss->ssl3.hs.isResuming &&
   10525 	    ssl3_ExtensionNegotiated(ss, ssl_session_ticket_xtn)) {
   10526 	    rv = ssl3_SendNewSessionTicket(ss);
   10527 	    if (rv != SECSuccess) {
   10528 		goto xmit_loser;
   10529 	    }
   10530 	}
   10531 
   10532 	rv = ssl3_SendChangeCipherSpecs(ss);
   10533 	if (rv != SECSuccess) {
   10534 	    goto xmit_loser;	/* err is set. */
   10535 	}
   10536 	/* If this thread is in SSL_SecureSend (trying to write some data)
   10537 	** then set the ssl_SEND_FLAG_FORCE_INTO_BUFFER flag, so that the
   10538 	** last two handshake messages (change cipher spec and finished)
   10539 	** will be sent in the same send/write call as the application data.
   10540 	*/
   10541 	if (ss->writerThread == PR_GetCurrentThread()) {
   10542 	    flags = ssl_SEND_FLAG_FORCE_INTO_BUFFER;
   10543 	}
   10544 
   10545 	if (!isServer) {
   10546 	    if (!ss->firstHsDone) {
   10547 		rv = ssl3_SendNextProto(ss);
   10548 		if (rv != SECSuccess) {
   10549 		    goto xmit_loser; /* err code was set. */
   10550 		}
   10551 	    }
   10552 	    rv = ssl3_SendEncryptedExtensions(ss);
   10553 	    if (rv != SECSuccess)
   10554 		goto xmit_loser; /* err code was set. */
   10555 	}
   10556 
   10557 	if (IS_DTLS(ss)) {
   10558 	    flags |= ssl_SEND_FLAG_NO_RETRANSMIT;
   10559 	}
   10560 
   10561 	rv = ssl3_SendFinished(ss, flags);
   10562 	if (rv != SECSuccess) {
   10563 	    goto xmit_loser;	/* err is set. */
   10564 	}
   10565     }
   10566 
   10567 xmit_loser:
   10568     ssl_ReleaseXmitBufLock(ss);	/*************************************/
   10569     if (rv != SECSuccess) {
   10570         return rv;
   10571     }
   10572 
   10573     ss->gs.writeOffset = 0;
   10574     ss->gs.readOffset  = 0;
   10575 
   10576     if (ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa) {
   10577 	effectiveExchKeyType = kt_rsa;
   10578     } else {
   10579 	effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
   10580     }
   10581 
   10582     if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
   10583 	/* fill in the sid */
   10584 	sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
   10585 	sid->u.ssl3.compression = ss->ssl3.hs.compression;
   10586 	sid->u.ssl3.policy      = ss->ssl3.policy;
   10587 #ifdef NSS_ENABLE_ECC
   10588 	sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
   10589 #endif
   10590 	sid->u.ssl3.exchKeyType = effectiveExchKeyType;
   10591 	sid->version            = ss->version;
   10592 	sid->authAlgorithm      = ss->sec.authAlgorithm;
   10593 	sid->authKeyBits        = ss->sec.authKeyBits;
   10594 	sid->keaType            = ss->sec.keaType;
   10595 	sid->keaKeyBits         = ss->sec.keaKeyBits;
   10596 	sid->lastAccessTime     = sid->creationTime = ssl_Time();
   10597 	sid->expirationTime     = sid->creationTime + ssl3_sid_timeout;
   10598 	sid->localCert          = CERT_DupCertificate(ss->sec.localCert);
   10599 
   10600 	ssl_GetSpecReadLock(ss);	/*************************************/
   10601 
   10602 	/* Copy the master secret (wrapped or unwrapped) into the sid */
   10603 	if (ss->ssl3.crSpec->msItem.len && ss->ssl3.crSpec->msItem.data) {
   10604 	    sid->u.ssl3.keys.wrapped_master_secret_len =
   10605 			    ss->ssl3.crSpec->msItem.len;
   10606 	    memcpy(sid->u.ssl3.keys.wrapped_master_secret,
   10607 		   ss->ssl3.crSpec->msItem.data, ss->ssl3.crSpec->msItem.len);
   10608 	    sid->u.ssl3.masterValid    = PR_TRUE;
   10609 	    sid->u.ssl3.keys.msIsWrapped = PR_FALSE;
   10610 	    rv = SECSuccess;
   10611 	} else {
   10612 	    rv = ssl3_CacheWrappedMasterSecret(ss, ss->sec.ci.sid,
   10613 					       ss->ssl3.crSpec,
   10614 					       effectiveExchKeyType);
   10615 	    sid->u.ssl3.keys.msIsWrapped = PR_TRUE;
   10616 	}
   10617 	ssl_ReleaseSpecReadLock(ss);  /*************************************/
   10618 
   10619 	/* If the wrap failed, we don't cache the sid.
   10620 	 * The connection continues normally however.
   10621 	 */
   10622 	ss->ssl3.hs.cacheSID = rv == SECSuccess;
   10623     }
   10624 
   10625     if (ss->ssl3.hs.authCertificatePending) {
   10626 	if (ss->ssl3.hs.restartTarget) {
   10627 	    PR_NOT_REACHED("ssl3_HandleFinished: unexpected restartTarget");
   10628 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   10629 	    return SECFailure;
   10630 	}
   10631 
   10632 	ss->ssl3.hs.restartTarget = ssl3_FinishHandshake;
   10633 	return SECWouldBlock;
   10634     }
   10635 
   10636     rv = ssl3_FinishHandshake(ss);
   10637     return rv;
   10638 }
   10639 
   10640 SECStatus
   10641 ssl3_FinishHandshake(sslSocket * ss)
   10642 {
   10643     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   10644     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   10645     PORT_Assert( ss->ssl3.hs.restartTarget == NULL );
   10646 
   10647     /* The first handshake is now completed. */
   10648     ss->handshake           = NULL;
   10649     ss->firstHsDone         = PR_TRUE;
   10650 
   10651     if (ss->ssl3.hs.cacheSID) {
   10652 	(*ss->sec.cache)(ss->sec.ci.sid);
   10653 	ss->ssl3.hs.cacheSID = PR_FALSE;
   10654     }
   10655 
   10656     ss->ssl3.hs.ws = idle_handshake;
   10657 
   10658     /* Do the handshake callback for sslv3 here, if we cannot false start. */
   10659     if (ss->handshakeCallback != NULL && !ssl3_CanFalseStart(ss)) {
   10660 	(ss->handshakeCallback)(ss->fd, ss->handshakeCallbackData);
   10661     }
   10662 
   10663     return SECSuccess;
   10664 }
   10665 
   10666 /* Called from ssl3_HandleHandshake() when it has gathered a complete ssl3
   10667  * hanshake message.
   10668  * Caller must hold Handshake and RecvBuf locks.
   10669  */
   10670 SECStatus
   10671 ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
   10672 {
   10673     SECStatus         rv 	= SECSuccess;
   10674     SSL3HandshakeType type 	= ss->ssl3.hs.msg_type;
   10675     SSL3Hashes        hashes;	/* computed hashes are put here. */
   10676     PRUint8           hdr[4];
   10677     PRUint8           dtlsData[8];
   10678 
   10679     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   10680     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   10681     /*
   10682      * We have to compute the hashes before we update them with the
   10683      * current message.
   10684      */
   10685     ssl_GetSpecReadLock(ss);	/************************************/
   10686     if((type == finished) || (type == certificate_verify)) {
   10687 	SSL3Sender      sender = (SSL3Sender)0;
   10688 	ssl3CipherSpec *rSpec  = ss->ssl3.prSpec;
   10689 
   10690 	if (type == finished) {
   10691 	    sender = ss->sec.isServer ? sender_client : sender_server;
   10692 	    rSpec  = ss->ssl3.crSpec;
   10693 	}
   10694 	rv = ssl3_ComputeHandshakeHashes(ss, rSpec, &hashes, sender);
   10695     }
   10696     ssl_ReleaseSpecReadLock(ss); /************************************/
   10697     if (rv != SECSuccess) {
   10698 	return rv;	/* error code was set by ssl3_ComputeHandshakeHashes*/
   10699     }
   10700     SSL_TRC(30,("%d: SSL3[%d]: handle handshake message: %s", SSL_GETPID(),
   10701 		ss->fd, ssl3_DecodeHandshakeType(ss->ssl3.hs.msg_type)));
   10702 
   10703     hdr[0] = (PRUint8)ss->ssl3.hs.msg_type;
   10704     hdr[1] = (PRUint8)(length >> 16);
   10705     hdr[2] = (PRUint8)(length >>  8);
   10706     hdr[3] = (PRUint8)(length      );
   10707 
   10708     /* Start new handshake hashes when we start a new handshake */
   10709     if (ss->ssl3.hs.msg_type == client_hello) {
   10710 	rv = ssl3_RestartHandshakeHashes(ss);
   10711 	if (rv != SECSuccess) {
   10712 	    return rv;
   10713 	}
   10714     }
   10715     /* We should not include hello_request and hello_verify_request messages
   10716      * in the handshake hashes */
   10717     if ((ss->ssl3.hs.msg_type != hello_request) &&
   10718 	(ss->ssl3.hs.msg_type != hello_verify_request)) {
   10719 	rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) hdr, 4);
   10720 	if (rv != SECSuccess) return rv;	/* err code already set. */
   10721 
   10722 	/* Extra data to simulate a complete DTLS handshake fragment */
   10723 	if (IS_DTLS(ss)) {
   10724 	    /* Sequence number */
   10725 	    dtlsData[0] = MSB(ss->ssl3.hs.recvMessageSeq);
   10726 	    dtlsData[1] = LSB(ss->ssl3.hs.recvMessageSeq);
   10727 
   10728 	    /* Fragment offset */
   10729 	    dtlsData[2] = 0;
   10730 	    dtlsData[3] = 0;
   10731 	    dtlsData[4] = 0;
   10732 
   10733 	    /* Fragment length */
   10734 	    dtlsData[5] = (PRUint8)(length >> 16);
   10735 	    dtlsData[6] = (PRUint8)(length >>  8);
   10736 	    dtlsData[7] = (PRUint8)(length      );
   10737 
   10738 	    rv = ssl3_UpdateHandshakeHashes(ss, (unsigned char*) dtlsData,
   10739 					    sizeof(dtlsData));
   10740 	    if (rv != SECSuccess) return rv;	/* err code already set. */
   10741 	}
   10742 
   10743 	/* The message body */
   10744 	rv = ssl3_UpdateHandshakeHashes(ss, b, length);
   10745 	if (rv != SECSuccess) return rv;	/* err code already set. */
   10746     }
   10747 
   10748     PORT_SetError(0);	/* each message starts with no error. */
   10749 
   10750     if (ss->ssl3.hs.ws == wait_certificate_status &&
   10751         ss->ssl3.hs.msg_type != certificate_status) {
   10752         /* If we negotiated the certificate_status extension then we deferred
   10753          * certificate validation until we get the CertificateStatus messsage.
   10754          * But the CertificateStatus message is optional. If the server did
   10755          * not send it then we need to validate the certificate now. If the
   10756          * server does send the CertificateStatus message then we will
   10757          * authenticate the certificate in ssl3_HandleCertificateStatus.
   10758          */
   10759         rv = ssl3_AuthCertificate(ss); /* sets ss->ssl3.hs.ws */
   10760         PORT_Assert(rv != SECWouldBlock);
   10761         if (rv != SECSuccess) {
   10762             return rv;
   10763         }
   10764     }
   10765 
   10766     switch (ss->ssl3.hs.msg_type) {
   10767     case hello_request:
   10768 	if (length != 0) {
   10769 	    (void)ssl3_DecodeError(ss);
   10770 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_REQUEST);
   10771 	    return SECFailure;
   10772 	}
   10773 	if (ss->sec.isServer) {
   10774 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10775 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_REQUEST);
   10776 	    return SECFailure;
   10777 	}
   10778 	rv = ssl3_HandleHelloRequest(ss);
   10779 	break;
   10780     case client_hello:
   10781 	if (!ss->sec.isServer) {
   10782 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10783 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_HELLO);
   10784 	    return SECFailure;
   10785 	}
   10786 	rv = ssl3_HandleClientHello(ss, b, length);
   10787 	break;
   10788     case server_hello:
   10789 	if (ss->sec.isServer) {
   10790 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10791 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_HELLO);
   10792 	    return SECFailure;
   10793 	}
   10794 	rv = ssl3_HandleServerHello(ss, b, length);
   10795 	break;
   10796     case hello_verify_request:
   10797 	if (!IS_DTLS(ss) || ss->sec.isServer) {
   10798 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10799 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_VERIFY_REQUEST);
   10800 	    return SECFailure;
   10801 	}
   10802 	rv = dtls_HandleHelloVerifyRequest(ss, b, length);
   10803 	break;
   10804     case certificate:
   10805 	rv = ssl3_HandleCertificate(ss, b, length);
   10806 	break;
   10807     case certificate_status:
   10808 	rv = ssl3_HandleCertificateStatus(ss, b, length);
   10809 	break;
   10810     case server_key_exchange:
   10811 	if (ss->sec.isServer) {
   10812 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10813 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_SERVER_KEY_EXCH);
   10814 	    return SECFailure;
   10815 	}
   10816 	rv = ssl3_HandleServerKeyExchange(ss, b, length);
   10817 	break;
   10818     case certificate_request:
   10819 	if (ss->sec.isServer) {
   10820 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10821 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_REQUEST);
   10822 	    return SECFailure;
   10823 	}
   10824 	rv = ssl3_HandleCertificateRequest(ss, b, length);
   10825 	break;
   10826     case server_hello_done:
   10827 	if (length != 0) {
   10828 	    (void)ssl3_DecodeError(ss);
   10829 	    PORT_SetError(SSL_ERROR_RX_MALFORMED_HELLO_DONE);
   10830 	    return SECFailure;
   10831 	}
   10832 	if (ss->sec.isServer) {
   10833 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10834 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_HELLO_DONE);
   10835 	    return SECFailure;
   10836 	}
   10837 	rv = ssl3_HandleServerHelloDone(ss);
   10838 	break;
   10839     case certificate_verify:
   10840 	if (!ss->sec.isServer) {
   10841 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10842 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CERT_VERIFY);
   10843 	    return SECFailure;
   10844 	}
   10845 	rv = ssl3_HandleCertificateVerify(ss, b, length, &hashes);
   10846 	break;
   10847     case client_key_exchange:
   10848 	if (!ss->sec.isServer) {
   10849 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10850 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_CLIENT_KEY_EXCH);
   10851 	    return SECFailure;
   10852 	}
   10853 	rv = ssl3_HandleClientKeyExchange(ss, b, length);
   10854 	break;
   10855     case new_session_ticket:
   10856 	if (ss->sec.isServer) {
   10857 	    (void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10858 	    PORT_SetError(SSL_ERROR_RX_UNEXPECTED_NEW_SESSION_TICKET);
   10859 	    return SECFailure;
   10860 	}
   10861 	rv = ssl3_HandleNewSessionTicket(ss, b, length);
   10862 	break;
   10863     case finished:
   10864         rv = ssl3_HandleFinished(ss, b, length, &hashes);
   10865 	break;
   10866     default:
   10867 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   10868 	PORT_SetError(SSL_ERROR_RX_UNKNOWN_HANDSHAKE);
   10869 	rv = SECFailure;
   10870     }
   10871 
   10872     if (IS_DTLS(ss) && (rv != SECFailure)) {
   10873 	/* Increment the expected sequence number */
   10874 	ss->ssl3.hs.recvMessageSeq++;
   10875     }
   10876 
   10877     return rv;
   10878 }
   10879 
   10880 /* Called only from ssl3_HandleRecord, for each (deciphered) ssl3 record.
   10881  * origBuf is the decrypted ssl record content.
   10882  * Caller must hold the handshake and RecvBuf locks.
   10883  */
   10884 static SECStatus
   10885 ssl3_HandleHandshake(sslSocket *ss, sslBuffer *origBuf)
   10886 {
   10887     /*
   10888      * There may be a partial handshake message already in the handshake
   10889      * state. The incoming buffer may contain another portion, or a
   10890      * complete message or several messages followed by another portion.
   10891      *
   10892      * Each message is made contiguous before being passed to the actual
   10893      * message parser.
   10894      */
   10895     sslBuffer *buf = &ss->ssl3.hs.msgState; /* do not lose the original buffer pointer */
   10896     SECStatus rv;
   10897 
   10898     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   10899     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   10900 
   10901     if (buf->buf == NULL) {
   10902 	*buf = *origBuf;
   10903     }
   10904     while (buf->len > 0) {
   10905 	if (ss->ssl3.hs.header_bytes < 4) {
   10906 	    PRUint8 t;
   10907 	    t = *(buf->buf++);
   10908 	    buf->len--;
   10909 	    if (ss->ssl3.hs.header_bytes++ == 0)
   10910 		ss->ssl3.hs.msg_type = (SSL3HandshakeType)t;
   10911 	    else
   10912 		ss->ssl3.hs.msg_len = (ss->ssl3.hs.msg_len << 8) + t;
   10913 	    if (ss->ssl3.hs.header_bytes < 4)
   10914 	    	continue;
   10915 
   10916 #define MAX_HANDSHAKE_MSG_LEN 0x1ffff	/* 128k - 1 */
   10917 	    if (ss->ssl3.hs.msg_len > MAX_HANDSHAKE_MSG_LEN) {
   10918 		(void)ssl3_DecodeError(ss);
   10919 		PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
   10920 		return SECFailure;
   10921 	    }
   10922 #undef MAX_HANDSHAKE_MSG_LEN
   10923 
   10924 	    /* If msg_len is zero, be sure we fall through,
   10925 	    ** even if buf->len is zero.
   10926 	    */
   10927 	    if (ss->ssl3.hs.msg_len > 0)
   10928 	    	continue;
   10929 	}
   10930 
   10931 	/*
   10932 	 * Header has been gathered and there is at least one byte of new
   10933 	 * data available for this message. If it can be done right out
   10934 	 * of the original buffer, then use it from there.
   10935 	 */
   10936 	if (ss->ssl3.hs.msg_body.len == 0 && buf->len >= ss->ssl3.hs.msg_len) {
   10937 	    /* handle it from input buffer */
   10938 	    rv = ssl3_HandleHandshakeMessage(ss, buf->buf, ss->ssl3.hs.msg_len);
   10939 	    if (rv == SECFailure) {
   10940 		/* This test wants to fall through on either
   10941 		 * SECSuccess or SECWouldBlock.
   10942 		 * ssl3_HandleHandshakeMessage MUST set the error code.
   10943 		 */
   10944 		return rv;
   10945 	    }
   10946 	    buf->buf += ss->ssl3.hs.msg_len;
   10947 	    buf->len -= ss->ssl3.hs.msg_len;
   10948 	    ss->ssl3.hs.msg_len = 0;
   10949 	    ss->ssl3.hs.header_bytes = 0;
   10950 	    if (rv != SECSuccess) { /* return if SECWouldBlock. */
   10951 		return rv;
   10952 	    }
   10953 	} else {
   10954 	    /* must be copied to msg_body and dealt with from there */
   10955 	    unsigned int bytes;
   10956 
   10957 	    PORT_Assert(ss->ssl3.hs.msg_body.len < ss->ssl3.hs.msg_len);
   10958 	    bytes = PR_MIN(buf->len, ss->ssl3.hs.msg_len - ss->ssl3.hs.msg_body.len);
   10959 
   10960 	    /* Grow the buffer if needed */
   10961 	    rv = sslBuffer_Grow(&ss->ssl3.hs.msg_body, ss->ssl3.hs.msg_len);
   10962 	    if (rv != SECSuccess) {
   10963 		/* sslBuffer_Grow has set a memory error code. */
   10964 		return SECFailure;
   10965 	    }
   10966 
   10967 	    PORT_Memcpy(ss->ssl3.hs.msg_body.buf + ss->ssl3.hs.msg_body.len,
   10968 		        buf->buf, bytes);
   10969 	    ss->ssl3.hs.msg_body.len += bytes;
   10970 	    buf->buf += bytes;
   10971 	    buf->len -= bytes;
   10972 
   10973 	    PORT_Assert(ss->ssl3.hs.msg_body.len <= ss->ssl3.hs.msg_len);
   10974 
   10975 	    /* if we have a whole message, do it */
   10976 	    if (ss->ssl3.hs.msg_body.len == ss->ssl3.hs.msg_len) {
   10977 		rv = ssl3_HandleHandshakeMessage(
   10978 		    ss, ss->ssl3.hs.msg_body.buf, ss->ssl3.hs.msg_len);
   10979 		if (rv == SECFailure) {
   10980 		    /* This test wants to fall through on either
   10981 		     * SECSuccess or SECWouldBlock.
   10982 		     * ssl3_HandleHandshakeMessage MUST set error code.
   10983 		     */
   10984 		    return rv;
   10985 		}
   10986 		ss->ssl3.hs.msg_body.len = 0;
   10987 		ss->ssl3.hs.msg_len = 0;
   10988 		ss->ssl3.hs.header_bytes = 0;
   10989 		if (rv != SECSuccess) { /* return if SECWouldBlock. */
   10990 		    return rv;
   10991 		}
   10992 	    } else {
   10993 		PORT_Assert(buf->len == 0);
   10994 		break;
   10995 	    }
   10996 	}
   10997     }	/* end loop */
   10998 
   10999     origBuf->len = 0;	/* So ssl3_GatherAppDataRecord will keep looping. */
   11000     buf->buf = NULL;	/* not a leak. */
   11001     return SECSuccess;
   11002 }
   11003 
   11004 /* These macros return the given value with the MSB copied to all the other
   11005  * bits. They use the fact that arithmetic shift shifts-in the sign bit.
   11006  * However, this is not ensured by the C standard so you may need to replace
   11007  * them with something else for odd compilers. */
   11008 #define DUPLICATE_MSB_TO_ALL(x) ( (unsigned)( (int)(x) >> (sizeof(int)*8-1) ) )
   11009 #define DUPLICATE_MSB_TO_ALL_8(x) ((unsigned char)(DUPLICATE_MSB_TO_ALL(x)))
   11010 
   11011 /* SECStatusToMask returns, in constant time, a mask value of all ones if
   11012  * rv == SECSuccess.  Otherwise it returns zero. */
   11013 static unsigned int
   11014 SECStatusToMask(SECStatus rv)
   11015 {
   11016     unsigned int good;
   11017     /* rv ^ SECSuccess is zero iff rv == SECSuccess. Subtracting one results
   11018      * in the MSB being set to one iff it was zero before. */
   11019     good = rv ^ SECSuccess;
   11020     good--;
   11021     return DUPLICATE_MSB_TO_ALL(good);
   11022 }
   11023 
   11024 /* ssl_ConstantTimeGE returns 0xff if a>=b and 0x00 otherwise. */
   11025 static unsigned char
   11026 ssl_ConstantTimeGE(unsigned int a, unsigned int b)
   11027 {
   11028     a -= b;
   11029     return DUPLICATE_MSB_TO_ALL(~a);
   11030 }
   11031 
   11032 /* ssl_ConstantTimeEQ8 returns 0xff if a==b and 0x00 otherwise. */
   11033 static unsigned char
   11034 ssl_ConstantTimeEQ8(unsigned char a, unsigned char b)
   11035 {
   11036     unsigned int c = a ^ b;
   11037     c--;
   11038     return DUPLICATE_MSB_TO_ALL_8(c);
   11039 }
   11040 
   11041 static SECStatus
   11042 ssl_RemoveSSLv3CBCPadding(sslBuffer *plaintext,
   11043 			  unsigned int blockSize,
   11044 			  unsigned int macSize)
   11045 {
   11046     unsigned int paddingLength, good, t;
   11047     const unsigned int overhead = 1 /* padding length byte */ + macSize;
   11048 
   11049     /* These lengths are all public so we can test them in non-constant
   11050      * time. */
   11051     if (overhead > plaintext->len) {
   11052 	return SECFailure;
   11053     }
   11054 
   11055     paddingLength = plaintext->buf[plaintext->len-1];
   11056     /* SSLv3 padding bytes are random and cannot be checked. */
   11057     t = plaintext->len;
   11058     t -= paddingLength+overhead;
   11059     /* If len >= paddingLength+overhead then the MSB of t is zero. */
   11060     good = DUPLICATE_MSB_TO_ALL(~t);
   11061     /* SSLv3 requires that the padding is minimal. */
   11062     t = blockSize - (paddingLength+1);
   11063     good &= DUPLICATE_MSB_TO_ALL(~t);
   11064     plaintext->len -= good & (paddingLength+1);
   11065     return (good & SECSuccess) | (~good & SECFailure);
   11066 }
   11067 
   11068 static SECStatus
   11069 ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize)
   11070 {
   11071     unsigned int paddingLength, good, t, toCheck, i;
   11072     const unsigned int overhead = 1 /* padding length byte */ + macSize;
   11073 
   11074     /* These lengths are all public so we can test them in non-constant
   11075      * time. */
   11076     if (overhead > plaintext->len) {
   11077 	return SECFailure;
   11078     }
   11079 
   11080     paddingLength = plaintext->buf[plaintext->len-1];
   11081     t = plaintext->len;
   11082     t -= paddingLength+overhead;
   11083     /* If len >= paddingLength+overhead then the MSB of t is zero. */
   11084     good = DUPLICATE_MSB_TO_ALL(~t);
   11085 
   11086     /* The padding consists of a length byte at the end of the record and then
   11087      * that many bytes of padding, all with the same value as the length byte.
   11088      * Thus, with the length byte included, there are paddingLength+1 bytes of
   11089      * padding.
   11090      *
   11091      * We can't check just |paddingLength+1| bytes because that leaks
   11092      * decrypted information. Therefore we always have to check the maximum
   11093      * amount of padding possible. (Again, the length of the record is
   11094      * public information so we can use it.) */
   11095     toCheck = 255; /* maximum amount of padding. */
   11096     if (toCheck > plaintext->len-1) {
   11097 	toCheck = plaintext->len-1;
   11098     }
   11099 
   11100     for (i = 0; i < toCheck; i++) {
   11101 	unsigned int t = paddingLength - i;
   11102 	/* If i <= paddingLength then the MSB of t is zero and mask is
   11103 	 * 0xff.  Otherwise, mask is 0. */
   11104 	unsigned char mask = DUPLICATE_MSB_TO_ALL(~t);
   11105 	unsigned char b = plaintext->buf[plaintext->len-1-i];
   11106 	/* The final |paddingLength+1| bytes should all have the value
   11107 	 * |paddingLength|. Therefore the XOR should be zero. */
   11108 	good &= ~(mask&(paddingLength ^ b));
   11109     }
   11110 
   11111     /* If any of the final |paddingLength+1| bytes had the wrong value,
   11112      * one or more of the lower eight bits of |good| will be cleared. We
   11113      * AND the bottom 8 bits together and duplicate the result to all the
   11114      * bits. */
   11115     good &= good >> 4;
   11116     good &= good >> 2;
   11117     good &= good >> 1;
   11118     good <<= sizeof(good)*8-1;
   11119     good = DUPLICATE_MSB_TO_ALL(good);
   11120 
   11121     plaintext->len -= good & (paddingLength+1);
   11122     return (good & SECSuccess) | (~good & SECFailure);
   11123 }
   11124 
   11125 /* On entry:
   11126  *   originalLength >= macSize
   11127  *   macSize <= MAX_MAC_LENGTH
   11128  *   plaintext->len >= macSize
   11129  */
   11130 static void
   11131 ssl_CBCExtractMAC(sslBuffer *plaintext,
   11132 		  unsigned int originalLength,
   11133 		  SSL3Opaque* out,
   11134 		  unsigned int macSize)
   11135 {
   11136     unsigned char rotatedMac[MAX_MAC_LENGTH];
   11137     /* macEnd is the index of |plaintext->buf| just after the end of the
   11138      * MAC. */
   11139     unsigned macEnd = plaintext->len;
   11140     unsigned macStart = macEnd - macSize;
   11141     /* scanStart contains the number of bytes that we can ignore because
   11142      * the MAC's position can only vary by 255 bytes. */
   11143     unsigned scanStart = 0;
   11144     unsigned i, j, divSpoiler;
   11145     unsigned char rotateOffset;
   11146 
   11147     if (originalLength > macSize + 255 + 1)
   11148 	scanStart = originalLength - (macSize + 255 + 1);
   11149 
   11150     /* divSpoiler contains a multiple of macSize that is used to cause the
   11151      * modulo operation to be constant time. Without this, the time varies
   11152      * based on the amount of padding when running on Intel chips at least.
   11153      *
   11154      * The aim of right-shifting macSize is so that the compiler doesn't
   11155      * figure out that it can remove divSpoiler as that would require it
   11156      * to prove that macSize is always even, which I hope is beyond it. */
   11157     divSpoiler = macSize >> 1;
   11158     divSpoiler <<= (sizeof(divSpoiler)-1)*8;
   11159     rotateOffset = (divSpoiler + macStart - scanStart) % macSize;
   11160 
   11161     memset(rotatedMac, 0, macSize);
   11162     for (i = scanStart; i < originalLength;) {
   11163 	for (j = 0; j < macSize && i < originalLength; i++, j++) {
   11164 	    unsigned char macStarted = ssl_ConstantTimeGE(i, macStart);
   11165 	    unsigned char macEnded = ssl_ConstantTimeGE(i, macEnd);
   11166 	    unsigned char b = 0;
   11167 	    b = plaintext->buf[i];
   11168 	    rotatedMac[j] |= b & macStarted & ~macEnded;
   11169 	}
   11170     }
   11171 
   11172     /* Now rotate the MAC. If we knew that the MAC fit into a CPU cache line
   11173      * we could line-align |rotatedMac| and rotate in place. */
   11174     memset(out, 0, macSize);
   11175     for (i = 0; i < macSize; i++) {
   11176 	unsigned char offset =
   11177 	    (divSpoiler + macSize - rotateOffset + i) % macSize;
   11178 	for (j = 0; j < macSize; j++) {
   11179 	    out[j] |= rotatedMac[i] & ssl_ConstantTimeEQ8(j, offset);
   11180 	}
   11181     }
   11182 }
   11183 
   11184 /* if cText is non-null, then decipher, check MAC, and decompress the
   11185  * SSL record from cText->buf (typically gs->inbuf)
   11186  * into databuf (typically gs->buf), and any previous contents of databuf
   11187  * is lost.  Then handle databuf according to its SSL record type,
   11188  * unless it's an application record.
   11189  *
   11190  * If cText is NULL, then the ciphertext has previously been deciphered and
   11191  * checked, and is already sitting in databuf.  It is processed as an SSL
   11192  * Handshake message.
   11193  *
   11194  * DOES NOT process the decrypted/decompressed application data.
   11195  * On return, databuf contains the decrypted/decompressed record.
   11196  *
   11197  * Called from ssl3_GatherCompleteHandshake
   11198  *             ssl3_RestartHandshakeAfterCertReq
   11199  *
   11200  * Caller must hold the RecvBufLock.
   11201  *
   11202  * This function aquires and releases the SSL3Handshake Lock, holding the
   11203  * lock around any calls to functions that handle records other than
   11204  * Application Data records.
   11205  */
   11206 SECStatus
   11207 ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cText, sslBuffer *databuf)
   11208 {
   11209     const ssl3BulkCipherDef *cipher_def;
   11210     ssl3CipherSpec *     crSpec;
   11211     SECStatus            rv;
   11212     unsigned int         hashBytes = MAX_MAC_LENGTH + 1;
   11213     PRBool               isTLS;
   11214     SSL3ContentType      rType;
   11215     SSL3Opaque           hash[MAX_MAC_LENGTH];
   11216     SSL3Opaque           givenHashBuf[MAX_MAC_LENGTH];
   11217     SSL3Opaque          *givenHash;
   11218     sslBuffer           *plaintext;
   11219     sslBuffer            temp_buf;
   11220     PRUint64             dtls_seq_num;
   11221     unsigned int         ivLen = 0;
   11222     unsigned int         originalLen = 0;
   11223     unsigned int         good;
   11224     unsigned int         minLength;
   11225 
   11226     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
   11227 
   11228     if (!ss->ssl3.initialized) {
   11229 	ssl_GetSSL3HandshakeLock(ss);
   11230 	rv = ssl3_InitState(ss);
   11231 	ssl_ReleaseSSL3HandshakeLock(ss);
   11232 	if (rv != SECSuccess) {
   11233 	    return rv;		/* ssl3_InitState has set the error code. */
   11234     	}
   11235     }
   11236 
   11237     /* check for Token Presence */
   11238     if (!ssl3_ClientAuthTokenPresent(ss->sec.ci.sid)) {
   11239 	PORT_SetError(SSL_ERROR_TOKEN_INSERTION_REMOVAL);
   11240 	return SECFailure;
   11241     }
   11242 
   11243     /* cText is NULL when we're called from ssl3_RestartHandshakeAfterXXX().
   11244      * This implies that databuf holds a previously deciphered SSL Handshake
   11245      * message.
   11246      */
   11247     if (cText == NULL) {
   11248 	SSL_DBG(("%d: SSL3[%d]: HandleRecord, resuming handshake",
   11249 		 SSL_GETPID(), ss->fd));
   11250 	rType = content_handshake;
   11251 	goto process_it;
   11252     }
   11253 
   11254     ssl_GetSpecReadLock(ss); /******************************************/
   11255 
   11256     crSpec = ss->ssl3.crSpec;
   11257     cipher_def = crSpec->cipher_def;
   11258 
   11259     /*
   11260      * DTLS relevance checks:
   11261      * Note that this code currently ignores all out-of-epoch packets,
   11262      * which means we lose some in the case of rehandshake +
   11263      * loss/reordering. Since DTLS is explicitly unreliable, this
   11264      * seems like a good tradeoff for implementation effort and is
   11265      * consistent with the guidance of RFC 6347 Sections 4.1 and 4.2.4.1
   11266      */
   11267     if (IS_DTLS(ss)) {
   11268 	DTLSEpoch epoch = (cText->seq_num.high >> 16) & 0xffff;
   11269 
   11270 	if (crSpec->epoch != epoch) {
   11271 	    ssl_ReleaseSpecReadLock(ss);
   11272 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, received packet "
   11273 		     "from irrelevant epoch %d", SSL_GETPID(), ss->fd, epoch));
   11274 	    /* Silently drop the packet */
   11275             databuf->len = 0; /* Needed to ensure data not left around */
   11276 	    return SECSuccess;
   11277 	}
   11278 
   11279 	dtls_seq_num = (((PRUint64)(cText->seq_num.high & 0xffff)) << 32) |
   11280 			((PRUint64)cText->seq_num.low);
   11281 
   11282 	if (dtls_RecordGetRecvd(&crSpec->recvdRecords, dtls_seq_num) != 0) {
   11283 	    ssl_ReleaseSpecReadLock(ss);
   11284 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, rejecting "
   11285 		     "potentially replayed packet", SSL_GETPID(), ss->fd));
   11286 	    /* Silently drop the packet */
   11287             databuf->len = 0; /* Needed to ensure data not left around */
   11288 	    return SECSuccess;
   11289 	}
   11290     }
   11291 
   11292     good = ~0U;
   11293     minLength = crSpec->mac_size;
   11294     if (cipher_def->type == type_block) {
   11295 	/* CBC records have a padding length byte at the end. */
   11296 	minLength++;
   11297 	if (crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   11298 	    /* With >= TLS 1.1, CBC records have an explicit IV. */
   11299 	    minLength += cipher_def->iv_size;
   11300 	}
   11301     }
   11302 
   11303     /* We can perform this test in variable time because the record's total
   11304      * length and the ciphersuite are both public knowledge. */
   11305     if (cText->buf->len < minLength) {
   11306         goto decrypt_loser;
   11307     }
   11308 
   11309     if (cipher_def->type == type_block &&
   11310 	crSpec->version >= SSL_LIBRARY_VERSION_TLS_1_1) {
   11311 	/* Consume the per-record explicit IV. RFC 4346 Section 6.2.3.2 states
   11312 	 * "The receiver decrypts the entire GenericBlockCipher structure and
   11313 	 * then discards the first cipher block corresponding to the IV
   11314 	 * component." Instead, we decrypt the first cipher block and then
   11315 	 * discard it before decrypting the rest.
   11316 	 */
   11317 	SSL3Opaque iv[MAX_IV_LENGTH];
   11318 	int decoded;
   11319 
   11320 	ivLen = cipher_def->iv_size;
   11321 	if (ivLen < 8 || ivLen > sizeof(iv)) {
   11322 	    ssl_ReleaseSpecReadLock(ss);
   11323 	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
   11324 	    return SECFailure;
   11325 	}
   11326 
   11327 	PRINT_BUF(80, (ss, "IV (ciphertext):", cText->buf->buf, ivLen));
   11328 
   11329 	/* The decryption result is garbage, but since we just throw away
   11330 	 * the block it doesn't matter.  The decryption of the next block
   11331 	 * depends only on the ciphertext of the IV block.
   11332 	 */
   11333 	rv = crSpec->decode(crSpec->decodeContext, iv, &decoded,
   11334 			    sizeof(iv), cText->buf->buf, ivLen);
   11335 
   11336 	good &= SECStatusToMask(rv);
   11337     }
   11338 
   11339     /* If we will be decompressing the buffer we need to decrypt somewhere
   11340      * other than into databuf */
   11341     if (crSpec->decompressor) {
   11342 	temp_buf.buf = NULL;
   11343 	temp_buf.space = 0;
   11344 	plaintext = &temp_buf;
   11345     } else {
   11346 	plaintext = databuf;
   11347     }
   11348 
   11349     plaintext->len = 0; /* filled in by decode call below. */
   11350     if (plaintext->space < MAX_FRAGMENT_LENGTH) {
   11351 	rv = sslBuffer_Grow(plaintext, MAX_FRAGMENT_LENGTH + 2048);
   11352 	if (rv != SECSuccess) {
   11353 	    ssl_ReleaseSpecReadLock(ss);
   11354 	    SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
   11355 		     SSL_GETPID(), ss->fd, MAX_FRAGMENT_LENGTH + 2048));
   11356 	    /* sslBuffer_Grow has set a memory error code. */
   11357 	    /* Perhaps we should send an alert. (but we have no memory!) */
   11358 	    return SECFailure;
   11359 	}
   11360     }
   11361 
   11362     PRINT_BUF(80, (ss, "ciphertext:", cText->buf->buf + ivLen,
   11363 				      cText->buf->len - ivLen));
   11364 
   11365     isTLS = (PRBool)(crSpec->version > SSL_LIBRARY_VERSION_3_0);
   11366 
   11367     if (isTLS && cText->buf->len - ivLen > (MAX_FRAGMENT_LENGTH + 2048)) {
   11368 	ssl_ReleaseSpecReadLock(ss);
   11369 	SSL3_SendAlert(ss, alert_fatal, record_overflow);
   11370 	PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
   11371 	return SECFailure;
   11372     }
   11373 
   11374     if (cipher_def->type == type_block &&
   11375 	((cText->buf->len - ivLen) % cipher_def->block_size) != 0) {
   11376 	goto decrypt_loser;
   11377     }
   11378 
   11379     /* decrypt from cText buf to plaintext. */
   11380     rv = crSpec->decode(
   11381 	crSpec->decodeContext, plaintext->buf, (int *)&plaintext->len,
   11382 	plaintext->space, cText->buf->buf + ivLen, cText->buf->len - ivLen);
   11383     if (rv != SECSuccess) {
   11384 	goto decrypt_loser;
   11385     }
   11386 
   11387     PRINT_BUF(80, (ss, "cleartext:", plaintext->buf, plaintext->len));
   11388 
   11389     originalLen = plaintext->len;
   11390 
   11391     /* If it's a block cipher, check and strip the padding. */
   11392     if (cipher_def->type == type_block) {
   11393 	const unsigned int blockSize = cipher_def->block_size;
   11394 	const unsigned int macSize = crSpec->mac_size;
   11395 
   11396 	if (crSpec->version <= SSL_LIBRARY_VERSION_3_0) {
   11397 	    good &= SECStatusToMask(ssl_RemoveSSLv3CBCPadding(
   11398 			plaintext, blockSize, macSize));
   11399 	} else {
   11400 	    good &= SECStatusToMask(ssl_RemoveTLSCBCPadding(
   11401 			plaintext, macSize));
   11402 	}
   11403     }
   11404 
   11405     /* compute the MAC */
   11406     rType = cText->type;
   11407     if (cipher_def->type == type_block) {
   11408 	rv = ssl3_ComputeRecordMACConstantTime(
   11409 	    crSpec, (PRBool)(!ss->sec.isServer),
   11410 	    IS_DTLS(ss), rType, cText->version,
   11411 	    IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
   11412 	    plaintext->buf, plaintext->len, originalLen,
   11413 	    hash, &hashBytes);
   11414 
   11415 	ssl_CBCExtractMAC(plaintext, originalLen, givenHashBuf,
   11416 			  crSpec->mac_size);
   11417 	givenHash = givenHashBuf;
   11418 
   11419 	/* plaintext->len will always have enough space to remove the MAC
   11420 	 * because in ssl_Remove{SSLv3|TLS}CBCPadding we only adjust
   11421 	 * plaintext->len if the result has enough space for the MAC and we
   11422 	 * tested the unadjusted size against minLength, above. */
   11423 	plaintext->len -= crSpec->mac_size;
   11424     } else {
   11425 	/* This is safe because we checked the minLength above. */
   11426 	plaintext->len -= crSpec->mac_size;
   11427 
   11428 	rv = ssl3_ComputeRecordMAC(
   11429 	    crSpec, (PRBool)(!ss->sec.isServer),
   11430 	    IS_DTLS(ss), rType, cText->version,
   11431 	    IS_DTLS(ss) ? cText->seq_num : crSpec->read_seq_num,
   11432 	    plaintext->buf, plaintext->len,
   11433 	    hash, &hashBytes);
   11434 
   11435 	/* We can read the MAC directly from the record because its location is
   11436 	 * public when a stream cipher is used. */
   11437 	givenHash = plaintext->buf + plaintext->len;
   11438     }
   11439 
   11440     good &= SECStatusToMask(rv);
   11441 
   11442     if (hashBytes != (unsigned)crSpec->mac_size ||
   11443 	NSS_SecureMemcmp(givenHash, hash, crSpec->mac_size) != 0) {
   11444 	/* We're allowed to leak whether or not the MAC check was correct */
   11445 	good = 0;
   11446     }
   11447 
   11448     if (good == 0) {
   11449 decrypt_loser:
   11450 	/* must not hold spec lock when calling SSL3_SendAlert. */
   11451 	ssl_ReleaseSpecReadLock(ss);
   11452 
   11453 	SSL_DBG(("%d: SSL3[%d]: decryption failed", SSL_GETPID(), ss->fd));
   11454 
   11455 	if (!IS_DTLS(ss)) {
   11456 	    SSL3_SendAlert(ss, alert_fatal, bad_record_mac);
   11457 	    /* always log mac error, in case attacker can read server logs. */
   11458 	    PORT_SetError(SSL_ERROR_BAD_MAC_READ);
   11459 	    return SECFailure;
   11460 	} else {
   11461 	    /* Silently drop the packet */
   11462             databuf->len = 0; /* Needed to ensure data not left around */
   11463 	    return SECSuccess;
   11464 	}
   11465     }
   11466 
   11467     if (!IS_DTLS(ss)) {
   11468 	ssl3_BumpSequenceNumber(&crSpec->read_seq_num);
   11469     } else {
   11470 	dtls_RecordSetRecvd(&crSpec->recvdRecords, dtls_seq_num);
   11471     }
   11472 
   11473     ssl_ReleaseSpecReadLock(ss); /*****************************************/
   11474 
   11475     /*
   11476      * The decrypted data is now in plaintext.
   11477      */
   11478 
   11479     /* possibly decompress the record. If we aren't using compression then
   11480      * plaintext == databuf and so the uncompressed data is already in
   11481      * databuf. */
   11482     if (crSpec->decompressor) {
   11483 	if (databuf->space < plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION) {
   11484 	    rv = sslBuffer_Grow(
   11485 	        databuf, plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION);
   11486 	    if (rv != SECSuccess) {
   11487 		SSL_DBG(("%d: SSL3[%d]: HandleRecord, tried to get %d bytes",
   11488 			 SSL_GETPID(), ss->fd,
   11489 			 plaintext->len + SSL3_COMPRESSION_MAX_EXPANSION));
   11490 		/* sslBuffer_Grow has set a memory error code. */
   11491 		/* Perhaps we should send an alert. (but we have no memory!) */
   11492 		PORT_Free(plaintext->buf);
   11493 		return SECFailure;
   11494 	    }
   11495 	}
   11496 
   11497 	rv = crSpec->decompressor(crSpec->decompressContext,
   11498 				  databuf->buf,
   11499 				  (int*) &databuf->len,
   11500 				  databuf->space,
   11501 				  plaintext->buf,
   11502 				  plaintext->len);
   11503 
   11504 	if (rv != SECSuccess) {
   11505 	    int err = ssl_MapLowLevelError(SSL_ERROR_DECOMPRESSION_FAILURE);
   11506 	    SSL3_SendAlert(ss, alert_fatal,
   11507 			   isTLS ? decompression_failure : bad_record_mac);
   11508 
   11509 	    /* There appears to be a bug with (at least) Apache + OpenSSL where
   11510 	     * resumed SSLv3 connections don't actually use compression. See
   11511 	     * comments 93-95 of
   11512 	     * https://bugzilla.mozilla.org/show_bug.cgi?id=275744
   11513 	     *
   11514 	     * So, if we get a decompression error, and the record appears to
   11515 	     * be already uncompressed, then we return a more specific error
   11516 	     * code to hopefully save somebody some debugging time in the
   11517 	     * future.
   11518 	     */
   11519 	    if (plaintext->len >= 4) {
   11520 		unsigned int len = ((unsigned int) plaintext->buf[1] << 16) |
   11521 		                   ((unsigned int) plaintext->buf[2] << 8) |
   11522 		                   (unsigned int) plaintext->buf[3];
   11523 		if (len == plaintext->len - 4) {
   11524 		    /* This appears to be uncompressed already */
   11525 		    err = SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD;
   11526 		}
   11527 	    }
   11528 
   11529 	    PORT_Free(plaintext->buf);
   11530 	    PORT_SetError(err);
   11531 	    return SECFailure;
   11532 	}
   11533 
   11534 	PORT_Free(plaintext->buf);
   11535     }
   11536 
   11537     /*
   11538     ** Having completed the decompression, check the length again.
   11539     */
   11540     if (isTLS && databuf->len > (MAX_FRAGMENT_LENGTH + 1024)) {
   11541 	SSL3_SendAlert(ss, alert_fatal, record_overflow);
   11542 	PORT_SetError(SSL_ERROR_RX_RECORD_TOO_LONG);
   11543 	return SECFailure;
   11544     }
   11545 
   11546     /* Application data records are processed by the caller of this
   11547     ** function, not by this function.
   11548     */
   11549     if (rType == content_application_data) {
   11550 	if (ss->firstHsDone)
   11551 	    return SECSuccess;
   11552 	(void)SSL3_SendAlert(ss, alert_fatal, unexpected_message);
   11553 	PORT_SetError(SSL_ERROR_RX_UNEXPECTED_APPLICATION_DATA);
   11554 	return SECFailure;
   11555     }
   11556 
   11557     /* It's a record that must be handled by ssl itself, not the application.
   11558     */
   11559 process_it:
   11560     /* XXX  Get the xmit lock here.  Odds are very high that we'll be xmiting
   11561      * data ang getting the xmit lock here prevents deadlocks.
   11562      */
   11563     ssl_GetSSL3HandshakeLock(ss);
   11564 
   11565     /* All the functions called in this switch MUST set error code if
   11566     ** they return SECFailure or SECWouldBlock.
   11567     */
   11568     switch (rType) {
   11569     case content_change_cipher_spec:
   11570 	rv = ssl3_HandleChangeCipherSpecs(ss, databuf);
   11571 	break;
   11572     case content_alert:
   11573 	rv = ssl3_HandleAlert(ss, databuf);
   11574 	break;
   11575     case content_handshake:
   11576 	if (!IS_DTLS(ss)) {
   11577 	    rv = ssl3_HandleHandshake(ss, databuf);
   11578 	} else {
   11579 	    rv = dtls_HandleHandshake(ss, databuf);
   11580 	}
   11581 	break;
   11582     /*
   11583     case content_application_data is handled before this switch
   11584     */
   11585     default:
   11586 	SSL_DBG(("%d: SSL3[%d]: bogus content type=%d",
   11587 		 SSL_GETPID(), ss->fd, cText->type));
   11588 	/* XXX Send an alert ???  */
   11589 	PORT_SetError(SSL_ERROR_RX_UNKNOWN_RECORD_TYPE);
   11590 	rv = SECFailure;
   11591 	break;
   11592     }
   11593 
   11594     ssl_ReleaseSSL3HandshakeLock(ss);
   11595     return rv;
   11596 
   11597 }
   11598 
   11599 /*
   11600  * Initialization functions
   11601  */
   11602 
   11603 /* Called from ssl3_InitState, immediately below. */
   11604 /* Caller must hold the SpecWriteLock. */
   11605 static void
   11606 ssl3_InitCipherSpec(sslSocket *ss, ssl3CipherSpec *spec)
   11607 {
   11608     spec->cipher_def               = &bulk_cipher_defs[cipher_null];
   11609     PORT_Assert(spec->cipher_def->cipher == cipher_null);
   11610     spec->mac_def                  = &mac_defs[mac_null];
   11611     PORT_Assert(spec->mac_def->mac == mac_null);
   11612     spec->encode                   = Null_Cipher;
   11613     spec->decode                   = Null_Cipher;
   11614     spec->destroy                  = NULL;
   11615     spec->compressor               = NULL;
   11616     spec->decompressor             = NULL;
   11617     spec->destroyCompressContext   = NULL;
   11618     spec->destroyDecompressContext = NULL;
   11619     spec->mac_size                 = 0;
   11620     spec->master_secret            = NULL;
   11621     spec->bypassCiphers            = PR_FALSE;
   11622 
   11623     spec->msItem.data              = NULL;
   11624     spec->msItem.len               = 0;
   11625 
   11626     spec->client.write_key         = NULL;
   11627     spec->client.write_mac_key     = NULL;
   11628     spec->client.write_mac_context = NULL;
   11629 
   11630     spec->server.write_key         = NULL;
   11631     spec->server.write_mac_key     = NULL;
   11632     spec->server.write_mac_context = NULL;
   11633 
   11634     spec->write_seq_num.high       = 0;
   11635     spec->write_seq_num.low        = 0;
   11636 
   11637     spec->read_seq_num.high        = 0;
   11638     spec->read_seq_num.low         = 0;
   11639 
   11640     spec->epoch                    = 0;
   11641     dtls_InitRecvdRecords(&spec->recvdRecords);
   11642 
   11643     spec->version                  = ss->vrange.max;
   11644 }
   11645 
   11646 /* Called from:	ssl3_SendRecord
   11647 **		ssl3_StartHandshakeHash() <- ssl2_BeginClientHandshake()
   11648 **		ssl3_SendClientHello()
   11649 **		ssl3_HandleV2ClientHello()
   11650 **		ssl3_HandleRecord()
   11651 **
   11652 ** This function should perhaps acquire and release the SpecWriteLock.
   11653 **
   11654 **
   11655 */
   11656 static SECStatus
   11657 ssl3_InitState(sslSocket *ss)
   11658 {
   11659     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss));
   11660 
   11661     if (ss->ssl3.initialized)
   11662     	return SECSuccess;	/* Function should be idempotent */
   11663 
   11664     ss->ssl3.policy = SSL_ALLOWED;
   11665 
   11666     ssl_GetSpecWriteLock(ss);
   11667     ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
   11668     ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
   11669     ss->ssl3.hs.sendingSCSV = PR_FALSE;
   11670     ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
   11671     ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
   11672 
   11673     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
   11674 #ifdef NSS_ENABLE_ECC
   11675     ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
   11676 #endif
   11677     ssl_ReleaseSpecWriteLock(ss);
   11678 
   11679     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
   11680 
   11681     if (IS_DTLS(ss)) {
   11682 	ss->ssl3.hs.sendMessageSeq = 0;
   11683 	ss->ssl3.hs.recvMessageSeq = 0;
   11684 	ss->ssl3.hs.rtTimeoutMs = INITIAL_DTLS_TIMEOUT_MS;
   11685 	ss->ssl3.hs.rtRetries = 0;
   11686 	ss->ssl3.hs.recvdHighWater = -1;
   11687 	PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
   11688 	dtls_SetMTU(ss, 0); /* Set the MTU to the highest plateau */
   11689     }
   11690 
   11691     PORT_Assert(!ss->ssl3.hs.messages.buf && !ss->ssl3.hs.messages.space);
   11692     ss->ssl3.hs.messages.buf = NULL;
   11693     ss->ssl3.hs.messages.space = 0;
   11694 
   11695     ss->ssl3.initialized = PR_TRUE;
   11696     return SECSuccess;
   11697 }
   11698 
   11699 /* Returns a reference counted object that contains a key pair.
   11700  * Or NULL on failure.  Initial ref count is 1.
   11701  * Uses the keys in the pair as input.
   11702  */
   11703 ssl3KeyPair *
   11704 ssl3_NewKeyPair( SECKEYPrivateKey * privKey, SECKEYPublicKey * pubKey)
   11705 {
   11706     ssl3KeyPair * pair;
   11707 
   11708     if (!privKey || !pubKey) {
   11709 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   11710     	return NULL;
   11711     }
   11712     pair = PORT_ZNew(ssl3KeyPair);
   11713     if (!pair)
   11714     	return NULL;			/* error code is set. */
   11715     pair->refCount = 1;
   11716     pair->privKey  = privKey;
   11717     pair->pubKey   = pubKey;
   11718     return pair;			/* success */
   11719 }
   11720 
   11721 ssl3KeyPair *
   11722 ssl3_GetKeyPairRef(ssl3KeyPair * keyPair)
   11723 {
   11724     PR_ATOMIC_INCREMENT(&keyPair->refCount);
   11725     return keyPair;
   11726 }
   11727 
   11728 void
   11729 ssl3_FreeKeyPair(ssl3KeyPair * keyPair)
   11730 {
   11731     PRInt32 newCount =  PR_ATOMIC_DECREMENT(&keyPair->refCount);
   11732     if (!newCount) {
   11733 	if (keyPair->privKey)
   11734 	    SECKEY_DestroyPrivateKey(keyPair->privKey);
   11735 	if (keyPair->pubKey)
   11736 	    SECKEY_DestroyPublicKey( keyPair->pubKey);
   11737     	PORT_Free(keyPair);
   11738     }
   11739 }
   11740 
   11741 
   11742 
   11743 /*
   11744  * Creates the public and private RSA keys for SSL Step down.
   11745  * Called from SSL_ConfigSecureServer in sslsecur.c
   11746  */
   11747 SECStatus
   11748 ssl3_CreateRSAStepDownKeys(sslSocket *ss)
   11749 {
   11750     SECStatus             rv  	 = SECSuccess;
   11751     SECKEYPrivateKey *    privKey;		/* RSA step down key */
   11752     SECKEYPublicKey *     pubKey;		/* RSA step down key */
   11753 
   11754     if (ss->stepDownKeyPair)
   11755 	ssl3_FreeKeyPair(ss->stepDownKeyPair);
   11756     ss->stepDownKeyPair = NULL;
   11757 #ifndef HACKED_EXPORT_SERVER
   11758     /* Sigh, should have a get key strength call for private keys */
   11759     if (PK11_GetPrivateModulusLen(ss->serverCerts[kt_rsa].SERVERKEY) >
   11760                                                      EXPORT_RSA_KEY_LENGTH) {
   11761 	/* need to ask for the key size in bits */
   11762 	privKey = SECKEY_CreateRSAPrivateKey(EXPORT_RSA_KEY_LENGTH * BPB,
   11763 					     &pubKey, NULL);
   11764     	if (!privKey || !pubKey ||
   11765 	    !(ss->stepDownKeyPair = ssl3_NewKeyPair(privKey, pubKey))) {
   11766 	    ssl_MapLowLevelError(SEC_ERROR_KEYGEN_FAIL);
   11767 	    rv = SECFailure;
   11768 	}
   11769     }
   11770 #endif
   11771     return rv;
   11772 }
   11773 
   11774 
   11775 /* record the export policy for this cipher suite */
   11776 SECStatus
   11777 ssl3_SetPolicy(ssl3CipherSuite which, int policy)
   11778 {
   11779     ssl3CipherSuiteCfg *suite;
   11780 
   11781     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   11782     if (suite == NULL) {
   11783 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
   11784     }
   11785     suite->policy = policy;
   11786 
   11787     return SECSuccess;
   11788 }
   11789 
   11790 SECStatus
   11791 ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *oPolicy)
   11792 {
   11793     ssl3CipherSuiteCfg *suite;
   11794     PRInt32             policy;
   11795     SECStatus           rv;
   11796 
   11797     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   11798     if (suite) {
   11799     	policy = suite->policy;
   11800 	rv     = SECSuccess;
   11801     } else {
   11802     	policy = SSL_NOT_ALLOWED;
   11803 	rv     = SECFailure;	/* err code was set by Lookup. */
   11804     }
   11805     *oPolicy = policy;
   11806     return rv;
   11807 }
   11808 
   11809 /* record the user preference for this suite */
   11810 SECStatus
   11811 ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool enabled)
   11812 {
   11813     ssl3CipherSuiteCfg *suite;
   11814 
   11815     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   11816     if (suite == NULL) {
   11817 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
   11818     }
   11819     suite->enabled = enabled;
   11820     return SECSuccess;
   11821 }
   11822 
   11823 /* return the user preference for this suite */
   11824 SECStatus
   11825 ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *enabled)
   11826 {
   11827     ssl3CipherSuiteCfg *suite;
   11828     PRBool              pref;
   11829     SECStatus           rv;
   11830 
   11831     suite = ssl_LookupCipherSuiteCfg(which, cipherSuites);
   11832     if (suite) {
   11833     	pref   = suite->enabled;
   11834 	rv     = SECSuccess;
   11835     } else {
   11836     	pref   = SSL_NOT_ALLOWED;
   11837 	rv     = SECFailure;	/* err code was set by Lookup. */
   11838     }
   11839     *enabled = pref;
   11840     return rv;
   11841 }
   11842 
   11843 SECStatus
   11844 ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool enabled)
   11845 {
   11846     ssl3CipherSuiteCfg *suite;
   11847 
   11848     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
   11849     if (suite == NULL) {
   11850 	return SECFailure; /* err code was set by ssl_LookupCipherSuiteCfg */
   11851     }
   11852     suite->enabled = enabled;
   11853     return SECSuccess;
   11854 }
   11855 
   11856 SECStatus
   11857 ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *enabled)
   11858 {
   11859     ssl3CipherSuiteCfg *suite;
   11860     PRBool              pref;
   11861     SECStatus           rv;
   11862 
   11863     suite = ssl_LookupCipherSuiteCfg(which, ss->cipherSuites);
   11864     if (suite) {
   11865     	pref   = suite->enabled;
   11866 	rv     = SECSuccess;
   11867     } else {
   11868     	pref   = SSL_NOT_ALLOWED;
   11869 	rv     = SECFailure;	/* err code was set by Lookup. */
   11870     }
   11871     *enabled = pref;
   11872     return rv;
   11873 }
   11874 
   11875 /* copy global default policy into socket. */
   11876 void
   11877 ssl3_InitSocketPolicy(sslSocket *ss)
   11878 {
   11879     PORT_Memcpy(ss->cipherSuites, cipherSuites, sizeof cipherSuites);
   11880 }
   11881 
   11882 SECStatus
   11883 ssl3_GetTLSUniqueChannelBinding(sslSocket *ss,
   11884 				unsigned char *out,
   11885 				unsigned int *outLen,
   11886 				unsigned int outLenMax) {
   11887     PRBool       isTLS;
   11888     int          index = 0;
   11889     unsigned int len;
   11890     SECStatus    rv = SECFailure;
   11891 
   11892     *outLen = 0;
   11893 
   11894     ssl_GetSSL3HandshakeLock(ss);
   11895 
   11896     ssl_GetSpecReadLock(ss);
   11897     isTLS = (PRBool)(ss->ssl3.cwSpec->version > SSL_LIBRARY_VERSION_3_0);
   11898     ssl_ReleaseSpecReadLock(ss);
   11899 
   11900     /* The tls-unique channel binding is the first Finished structure in the
   11901      * handshake. In the case of a resumption, that's the server's Finished.
   11902      * Otherwise, it's the client's Finished. */
   11903     len = ss->ssl3.hs.finishedBytes;
   11904 
   11905     /* Sending or receiving a Finished message will set finishedBytes to a
   11906      * non-zero value. */
   11907     if (len == 0) {
   11908 	PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
   11909 	goto loser;
   11910     }
   11911 
   11912     /* If we are in the middle of a renegotiation then the channel binding
   11913      * value is poorly defined and depends on the direction that it will be
   11914      * used on. Therefore we simply return an error in this case. */
   11915     if (ss->firstHsDone && ss->ssl3.hs.ws != idle_handshake) {
   11916 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
   11917 	goto loser;
   11918     }
   11919 
   11920     /* If resuming, then we want the second Finished value in the array, which
   11921      * is the server's */
   11922     if (ss->ssl3.hs.isResuming)
   11923 	index = 1;
   11924 
   11925     *outLen = len;
   11926     if (outLenMax < len) {
   11927 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
   11928 	goto loser;
   11929     }
   11930 
   11931     if (isTLS) {
   11932 	memcpy(out, &ss->ssl3.hs.finishedMsgs.tFinished[index], len);
   11933     } else {
   11934 	memcpy(out, &ss->ssl3.hs.finishedMsgs.sFinished[index], len);
   11935     }
   11936 
   11937     rv = SECSuccess;
   11938 
   11939 loser:
   11940     ssl_ReleaseSSL3HandshakeLock(ss);
   11941     return rv;
   11942 }
   11943 
   11944 /* ssl3_config_match_init must have already been called by
   11945  * the caller of this function.
   11946  */
   11947 SECStatus
   11948 ssl3_ConstructV2CipherSpecsHack(sslSocket *ss, unsigned char *cs, int *size)
   11949 {
   11950     int i, count = 0;
   11951 
   11952     PORT_Assert(ss != 0);
   11953     if (!ss) {
   11954 	PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
   11955 	return SECFailure;
   11956     }
   11957     if (SSL3_ALL_VERSIONS_DISABLED(&ss->vrange)) {
   11958     	*size = 0;
   11959 	return SECSuccess;
   11960     }
   11961     if (cs == NULL) {
   11962 	*size = count_cipher_suites(ss, SSL_ALLOWED, PR_TRUE);
   11963 	return SECSuccess;
   11964     }
   11965 
   11966     /* ssl3_config_match_init was called by the caller of this function. */
   11967     for (i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
   11968 	ssl3CipherSuiteCfg *suite = &ss->cipherSuites[i];
   11969 	if (config_match(suite, SSL_ALLOWED, PR_TRUE)) {
   11970 	    if (cs != NULL) {
   11971 		*cs++ = 0x00;
   11972 		*cs++ = (suite->cipher_suite >> 8) & 0xFF;
   11973 		*cs++ =  suite->cipher_suite       & 0xFF;
   11974 	    }
   11975 	    count++;
   11976 	}
   11977     }
   11978     *size = count;
   11979     return SECSuccess;
   11980 }
   11981 
   11982 /*
   11983 ** If ssl3 socket has completed the first handshake, and is in idle state,
   11984 ** then start a new handshake.
   11985 ** If flushCache is true, the SID cache will be flushed first, forcing a
   11986 ** "Full" handshake (not a session restart handshake), to be done.
   11987 **
   11988 ** called from SSL_RedoHandshake(), which already holds the handshake locks.
   11989 */
   11990 SECStatus
   11991 ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache)
   11992 {
   11993     sslSessionID *   sid = ss->sec.ci.sid;
   11994     SECStatus        rv;
   11995 
   11996     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
   11997 
   11998     if (!ss->firstHsDone ||
   11999         ((ss->version >= SSL_LIBRARY_VERSION_3_0) &&
   12000 	 ss->ssl3.initialized &&
   12001 	 (ss->ssl3.hs.ws != idle_handshake))) {
   12002 	PORT_SetError(SSL_ERROR_HANDSHAKE_NOT_COMPLETED);
   12003 	return SECFailure;
   12004     }
   12005 
   12006     if (IS_DTLS(ss)) {
   12007 	dtls_RehandshakeCleanup(ss);
   12008     }
   12009 
   12010     if (ss->opt.enableRenegotiation == SSL_RENEGOTIATE_NEVER) {
   12011 	PORT_SetError(SSL_ERROR_RENEGOTIATION_NOT_ALLOWED);
   12012 	return SECFailure;
   12013     }
   12014     if (sid && flushCache) {
   12015         if (ss->sec.uncache)
   12016             ss->sec.uncache(sid); /* remove it from whichever cache it's in. */
   12017 	ssl_FreeSID(sid);	/* dec ref count and free if zero. */
   12018 	ss->sec.ci.sid = NULL;
   12019     }
   12020 
   12021     ssl_GetXmitBufLock(ss);	/**************************************/
   12022 
   12023     /* start off a new handshake. */
   12024     rv = (ss->sec.isServer) ? ssl3_SendHelloRequest(ss)
   12025                             : ssl3_SendClientHello(ss, PR_FALSE);
   12026 
   12027     ssl_ReleaseXmitBufLock(ss);	/**************************************/
   12028     return rv;
   12029 }
   12030 
   12031 /* Called from ssl_DestroySocketContents() in sslsock.c */
   12032 void
   12033 ssl3_DestroySSL3Info(sslSocket *ss)
   12034 {
   12035 
   12036     if (ss->ssl3.clientCertificate != NULL)
   12037 	CERT_DestroyCertificate(ss->ssl3.clientCertificate);
   12038 
   12039     if (ss->ssl3.clientPrivateKey != NULL)
   12040 	SECKEY_DestroyPrivateKey(ss->ssl3.clientPrivateKey);
   12041 #ifdef NSS_PLATFORM_CLIENT_AUTH
   12042     if (ss->ssl3.platformClientKey)
   12043 	ssl_FreePlatformKey(ss->ssl3.platformClientKey);
   12044 #endif /* NSS_PLATFORM_CLIENT_AUTH */
   12045 
   12046     if (ss->ssl3.channelID)
   12047 	SECKEY_DestroyPrivateKey(ss->ssl3.channelID);
   12048     if (ss->ssl3.channelIDPub)
   12049 	SECKEY_DestroyPublicKey(ss->ssl3.channelIDPub);
   12050 
   12051     if (ss->ssl3.peerCertArena != NULL)
   12052 	ssl3_CleanupPeerCerts(ss);
   12053 
   12054     if (ss->ssl3.clientCertChain != NULL) {
   12055        CERT_DestroyCertificateList(ss->ssl3.clientCertChain);
   12056        ss->ssl3.clientCertChain = NULL;
   12057     }
   12058 
   12059     /* clean up handshake */
   12060 #ifndef NO_PKCS11_BYPASS
   12061     if (ss->opt.bypassPKCS11) {
   12062 	if (ss->ssl3.hs.hashType == handshake_hash_combo) {
   12063 	    SHA1_DestroyContext((SHA1Context *)ss->ssl3.hs.sha_cx, PR_FALSE);
   12064 	    MD5_DestroyContext((MD5Context *)ss->ssl3.hs.md5_cx, PR_FALSE);
   12065 	} else if (ss->ssl3.hs.hashType == handshake_hash_single) {
   12066 	    ss->ssl3.hs.sha_obj->destroy(ss->ssl3.hs.sha_cx, PR_FALSE);
   12067 	}
   12068     }
   12069 #endif
   12070     if (ss->ssl3.hs.md5) {
   12071 	PK11_DestroyContext(ss->ssl3.hs.md5,PR_TRUE);
   12072     }
   12073     if (ss->ssl3.hs.sha) {
   12074 	PK11_DestroyContext(ss->ssl3.hs.sha,PR_TRUE);
   12075     }
   12076     if (ss->ssl3.hs.clientSigAndHash) {
   12077 	PORT_Free(ss->ssl3.hs.clientSigAndHash);
   12078     }
   12079     if (ss->ssl3.hs.messages.buf) {
   12080     	PORT_Free(ss->ssl3.hs.messages.buf);
   12081 	ss->ssl3.hs.messages.buf = NULL;
   12082 	ss->ssl3.hs.messages.len = 0;
   12083 	ss->ssl3.hs.messages.space = 0;
   12084     }
   12085 
   12086     /* free the SSL3Buffer (msg_body) */
   12087     PORT_Free(ss->ssl3.hs.msg_body.buf);
   12088 
   12089     /* free up the CipherSpecs */
   12090     ssl3_DestroyCipherSpec(&ss->ssl3.specs[0], PR_TRUE/*freeSrvName*/);
   12091     ssl3_DestroyCipherSpec(&ss->ssl3.specs[1], PR_TRUE/*freeSrvName*/);
   12092 
   12093     /* Destroy the DTLS data */
   12094     if (IS_DTLS(ss)) {
   12095 	dtls_FreeHandshakeMessages(&ss->ssl3.hs.lastMessageFlight);
   12096 	if (ss->ssl3.hs.recvdFragments.buf) {
   12097 	    PORT_Free(ss->ssl3.hs.recvdFragments.buf);
   12098 	}
   12099     }
   12100 
   12101     ss->ssl3.initialized = PR_FALSE;
   12102 
   12103     SECITEM_FreeItem(&ss->ssl3.nextProto, PR_FALSE);
   12104 }
   12105 
   12106 /* End of ssl3con.c */
   12107