Home | History | Annotate | Download | only in ssl
      1 /*
      2  * This file is PRIVATE to SSL and should be the first thing included by
      3  * any SSL implementation file.
      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 #ifndef __sslimpl_h_
     10 #define __sslimpl_h_
     11 
     12 #ifdef DEBUG
     13 #undef NDEBUG
     14 #else
     15 #undef NDEBUG
     16 #define NDEBUG
     17 #endif
     18 #include "secport.h"
     19 #include "secerr.h"
     20 #include "sslerr.h"
     21 #include "ssl3prot.h"
     22 #include "hasht.h"
     23 #include "keythi.h"
     24 #include "nssilock.h"
     25 #include "pkcs11t.h"
     26 #if defined(XP_UNIX) || defined(XP_BEOS)
     27 #include "unistd.h"
     28 #endif
     29 #include "nssrwlk.h"
     30 #include "prthread.h"
     31 #include "prclist.h"
     32 
     33 #include "sslt.h" /* for some formerly private types, now public */
     34 
     35 #ifdef NSS_PLATFORM_CLIENT_AUTH
     36 #if defined(XP_WIN32)
     37 #include <windows.h>
     38 #include <wincrypt.h>
     39 #elif defined(XP_MACOSX)
     40 #include <Security/Security.h>
     41 #endif
     42 #endif
     43 
     44 /* to make some of these old enums public without namespace pollution,
     45 ** it was necessary to prepend ssl_ to the names.
     46 ** These #defines preserve compatibility with the old code here in libssl.
     47 */
     48 typedef SSLKEAType      SSL3KEAType;
     49 typedef SSLMACAlgorithm SSL3MACAlgorithm;
     50 typedef SSLSignType     SSL3SignType;
     51 
     52 #define sign_null	ssl_sign_null
     53 #define sign_rsa	ssl_sign_rsa
     54 #define sign_dsa	ssl_sign_dsa
     55 #define sign_ecdsa	ssl_sign_ecdsa
     56 
     57 #define calg_null	ssl_calg_null
     58 #define calg_rc4	ssl_calg_rc4
     59 #define calg_rc2	ssl_calg_rc2
     60 #define calg_des	ssl_calg_des
     61 #define calg_3des	ssl_calg_3des
     62 #define calg_idea	ssl_calg_idea
     63 #define calg_fortezza	ssl_calg_fortezza /* deprecated, must preserve */
     64 #define calg_aes	ssl_calg_aes
     65 #define calg_camellia	ssl_calg_camellia
     66 #define calg_seed	ssl_calg_seed
     67 #define calg_aes_gcm    ssl_calg_aes_gcm
     68 #define calg_chacha20	ssl_calg_chacha20
     69 
     70 #define mac_null	ssl_mac_null
     71 #define mac_md5 	ssl_mac_md5
     72 #define mac_sha 	ssl_mac_sha
     73 #define hmac_md5	ssl_hmac_md5
     74 #define hmac_sha	ssl_hmac_sha
     75 #define hmac_sha256	ssl_hmac_sha256
     76 #define mac_aead	ssl_mac_aead
     77 
     78 #define SET_ERROR_CODE		/* reminder */
     79 #define SEND_ALERT		/* reminder */
     80 #define TEST_FOR_FAILURE	/* reminder */
     81 #define DEAL_WITH_FAILURE	/* reminder */
     82 
     83 #if defined(DEBUG) || defined(TRACE)
     84 #ifdef __cplusplus
     85 #define Debug 1
     86 #else
     87 extern int Debug;
     88 #endif
     89 #else
     90 #undef Debug
     91 #endif
     92 
     93 #if defined(DEBUG) && !defined(TRACE) && !defined(NISCC_TEST)
     94 #define TRACE
     95 #endif
     96 
     97 #ifdef TRACE
     98 #define SSL_TRC(a,b) if (ssl_trace >= (a)) ssl_Trace b
     99 #define PRINT_BUF(a,b) if (ssl_trace >= (a)) ssl_PrintBuf b
    100 #define DUMP_MSG(a,b) if (ssl_trace >= (a)) ssl_DumpMsg b
    101 #else
    102 #define SSL_TRC(a,b)
    103 #define PRINT_BUF(a,b)
    104 #define DUMP_MSG(a,b)
    105 #endif
    106 
    107 #ifdef DEBUG
    108 #define SSL_DBG(b) if (ssl_debug) ssl_Trace b
    109 #else
    110 #define SSL_DBG(b)
    111 #endif
    112 
    113 #include "private/pprthred.h"	/* for PR_InMonitor() */
    114 #define ssl_InMonitor(m) PZ_InMonitor(m)
    115 
    116 #define LSB(x) ((unsigned char) ((x) & 0xff))
    117 #define MSB(x) ((unsigned char) (((unsigned)(x)) >> 8))
    118 
    119 /************************************************************************/
    120 
    121 typedef enum { SSLAppOpRead = 0,
    122 	       SSLAppOpWrite,
    123 	       SSLAppOpRDWR,
    124 	       SSLAppOpPost,
    125 	       SSLAppOpHeader
    126 } SSLAppOperation;
    127 
    128 #define SSL_MIN_MASTER_KEY_BYTES	5
    129 #define SSL_MAX_MASTER_KEY_BYTES	64
    130 
    131 #define SSL2_SESSIONID_BYTES		16
    132 #define SSL3_SESSIONID_BYTES		32
    133 
    134 #define SSL_MIN_CHALLENGE_BYTES		16
    135 #define SSL_MAX_CHALLENGE_BYTES		32
    136 #define SSL_CHALLENGE_BYTES		16
    137 
    138 #define SSL_CONNECTIONID_BYTES		16
    139 
    140 #define SSL_MIN_CYPHER_ARG_BYTES	0
    141 #define SSL_MAX_CYPHER_ARG_BYTES	32
    142 
    143 #define SSL_MAX_MAC_BYTES		16
    144 
    145 #define SSL3_RSA_PMS_LENGTH 48
    146 #define SSL3_MASTER_SECRET_LENGTH 48
    147 
    148 /* number of wrap mechanisms potentially used to wrap master secrets. */
    149 #define SSL_NUM_WRAP_MECHS              16
    150 
    151 /* This makes the cert cache entry exactly 4k. */
    152 #define SSL_MAX_CACHED_CERT_LEN		4060
    153 
    154 #define NUM_MIXERS                      9
    155 
    156 /* Mask of the 25 named curves we support. */
    157 #define SSL3_ALL_SUPPORTED_CURVES_MASK 0x3fffffe
    158 /* Mask of only 3 curves, suite B */
    159 #define SSL3_SUITE_B_SUPPORTED_CURVES_MASK 0x3800000
    160 
    161 #ifndef BPB
    162 #define BPB 8 /* Bits Per Byte */
    163 #endif
    164 
    165 #define EXPORT_RSA_KEY_LENGTH 64	/* bytes */
    166 
    167 #define INITIAL_DTLS_TIMEOUT_MS   1000  /* Default value from RFC 4347 = 1s*/
    168 #define MAX_DTLS_TIMEOUT_MS      60000  /* 1 minute */
    169 #define DTLS_FINISHED_TIMER_MS  120000  /* Time to wait in FINISHED state */
    170 
    171 typedef struct sslBufferStr             sslBuffer;
    172 typedef struct sslConnectInfoStr        sslConnectInfo;
    173 typedef struct sslGatherStr             sslGather;
    174 typedef struct sslSecurityInfoStr       sslSecurityInfo;
    175 typedef struct sslSessionIDStr          sslSessionID;
    176 typedef struct sslSocketStr             sslSocket;
    177 typedef struct sslSocketOpsStr          sslSocketOps;
    178 
    179 typedef struct ssl3StateStr             ssl3State;
    180 typedef struct ssl3CertNodeStr          ssl3CertNode;
    181 typedef struct ssl3BulkCipherDefStr     ssl3BulkCipherDef;
    182 typedef struct ssl3MACDefStr            ssl3MACDef;
    183 typedef struct ssl3KeyPairStr		ssl3KeyPair;
    184 
    185 struct ssl3CertNodeStr {
    186     struct ssl3CertNodeStr *next;
    187     CERTCertificate *       cert;
    188 };
    189 
    190 typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss);
    191 
    192 /* This type points to the low layer send func,
    193 ** e.g. ssl2_SendStream or ssl3_SendPlainText.
    194 ** These functions return the same values as PR_Send,
    195 ** i.e.  >= 0 means number of bytes sent, < 0 means error.
    196 */
    197 typedef PRInt32       (*sslSendFunc)(sslSocket *ss, const unsigned char *buf,
    198 			             PRInt32 n, PRInt32 flags);
    199 
    200 typedef void          (*sslSessionIDCacheFunc)  (sslSessionID *sid);
    201 typedef void          (*sslSessionIDUncacheFunc)(sslSessionID *sid);
    202 typedef sslSessionID *(*sslSessionIDLookupFunc)(const PRIPv6Addr    *addr,
    203 						unsigned char* sid,
    204 						unsigned int   sidLen,
    205                                                 CERTCertDBHandle * dbHandle);
    206 
    207 /* registerable callback function that either appends extension to buffer
    208  * or returns length of data that it would have appended.
    209  */
    210 typedef PRInt32 (*ssl3HelloExtensionSenderFunc)(sslSocket *ss, PRBool append,
    211 						PRUint32 maxBytes);
    212 
    213 /* registerable callback function that handles a received extension,
    214  * of the given type.
    215  */
    216 typedef SECStatus (* ssl3HelloExtensionHandlerFunc)(sslSocket *ss,
    217 						    PRUint16   ex_type,
    218                                                     SECItem *  data);
    219 
    220 /* row in a table of hello extension senders */
    221 typedef struct {
    222     PRInt32                      ex_type;
    223     ssl3HelloExtensionSenderFunc ex_sender;
    224 } ssl3HelloExtensionSender;
    225 
    226 /* row in a table of hello extension handlers */
    227 typedef struct {
    228     PRInt32                       ex_type;
    229     ssl3HelloExtensionHandlerFunc ex_handler;
    230 } ssl3HelloExtensionHandler;
    231 
    232 extern SECStatus
    233 ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
    234 				        ssl3HelloExtensionSenderFunc cb);
    235 
    236 extern PRInt32
    237 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
    238                                const ssl3HelloExtensionSender *sender);
    239 
    240 extern unsigned int
    241 ssl3_CalculatePaddingExtensionLength(unsigned int clientHelloLength);
    242 
    243 extern PRInt32
    244 ssl3_AppendPaddingExtension(sslSocket *ss, unsigned int extensionLen,
    245 			    PRUint32 maxBytes);
    246 
    247 /* Socket ops */
    248 struct sslSocketOpsStr {
    249     int         (*connect) (sslSocket *, const PRNetAddr *);
    250     PRFileDesc *(*accept)  (sslSocket *, PRNetAddr *);
    251     int         (*bind)    (sslSocket *, const PRNetAddr *);
    252     int         (*listen)  (sslSocket *, int);
    253     int         (*shutdown)(sslSocket *, int);
    254     int         (*close)   (sslSocket *);
    255 
    256     int         (*recv)    (sslSocket *, unsigned char *, int, int);
    257 
    258     /* points to the higher-layer send func, e.g. ssl_SecureSend. */
    259     int         (*send)    (sslSocket *, const unsigned char *, int, int);
    260     int         (*read)    (sslSocket *, unsigned char *, int);
    261     int         (*write)   (sslSocket *, const unsigned char *, int);
    262 
    263     int         (*getpeername)(sslSocket *, PRNetAddr *);
    264     int         (*getsockname)(sslSocket *, PRNetAddr *);
    265 };
    266 
    267 /* Flags interpreted by ssl send functions. */
    268 #define ssl_SEND_FLAG_FORCE_INTO_BUFFER	0x40000000
    269 #define ssl_SEND_FLAG_NO_BUFFER		0x20000000
    270 #define ssl_SEND_FLAG_USE_EPOCH		0x10000000 /* DTLS only */
    271 #define ssl_SEND_FLAG_NO_RETRANSMIT	0x08000000 /* DTLS only */
    272 #define ssl_SEND_FLAG_CAP_RECORD_VERSION \
    273 					0x04000000 /* TLS only */
    274 #define ssl_SEND_FLAG_MASK		0x7f000000
    275 
    276 /*
    277 ** A buffer object.
    278 */
    279 struct sslBufferStr {
    280     unsigned char *	buf;
    281     unsigned int 	len;
    282     unsigned int 	space;
    283 };
    284 
    285 /*
    286 ** SSL3 cipher suite policy and preference struct.
    287 */
    288 typedef struct {
    289 #if !defined(_WIN32)
    290     unsigned int    cipher_suite : 16;
    291     unsigned int    policy       :  8;
    292     unsigned int    enabled      :  1;
    293     unsigned int    isPresent    :  1;
    294 #else
    295     ssl3CipherSuite cipher_suite;
    296     PRUint8         policy;
    297     unsigned char   enabled   : 1;
    298     unsigned char   isPresent : 1;
    299 #endif
    300 } ssl3CipherSuiteCfg;
    301 
    302 #ifdef NSS_ENABLE_ECC
    303 #define ssl_V3_SUITES_IMPLEMENTED 63
    304 #else
    305 #define ssl_V3_SUITES_IMPLEMENTED 37
    306 #endif /* NSS_ENABLE_ECC */
    307 
    308 #define MAX_DTLS_SRTP_CIPHER_SUITES 4
    309 
    310 typedef struct sslOptionsStr {
    311     /* If SSL_SetNextProtoNego has been called, then this contains the
    312      * list of supported protocols. */
    313     SECItem nextProtoNego;
    314 
    315     unsigned int useSecurity		: 1;  /*  1 */
    316     unsigned int useSocks		: 1;  /*  2 */
    317     unsigned int requestCertificate	: 1;  /*  3 */
    318     unsigned int requireCertificate	: 2;  /*  4-5 */
    319     unsigned int handshakeAsClient	: 1;  /*  6 */
    320     unsigned int handshakeAsServer	: 1;  /*  7 */
    321     unsigned int enableSSL2		: 1;  /*  8 */
    322     unsigned int unusedBit9		: 1;  /*  9 */
    323     unsigned int unusedBit10		: 1;  /* 10 */
    324     unsigned int noCache		: 1;  /* 11 */
    325     unsigned int fdx			: 1;  /* 12 */
    326     unsigned int v2CompatibleHello	: 1;  /* 13 */
    327     unsigned int detectRollBack  	: 1;  /* 14 */
    328     unsigned int noStepDown             : 1;  /* 15 */
    329     unsigned int bypassPKCS11           : 1;  /* 16 */
    330     unsigned int noLocks                : 1;  /* 17 */
    331     unsigned int enableSessionTickets   : 1;  /* 18 */
    332     unsigned int enableDeflate          : 1;  /* 19 */
    333     unsigned int enableRenegotiation    : 2;  /* 20-21 */
    334     unsigned int requireSafeNegotiation : 1;  /* 22 */
    335     unsigned int enableFalseStart       : 1;  /* 23 */
    336     unsigned int cbcRandomIV            : 1;  /* 24 */
    337     unsigned int enableOCSPStapling     : 1;  /* 25 */
    338     unsigned int enableNPN              : 1;  /* 26 */
    339     unsigned int enableALPN             : 1;  /* 27 */
    340     unsigned int enableSignedCertTimestamps : 1;  /* 28 */
    341     unsigned int enableFallbackSCSV     : 1;  /* 29 */
    342 } sslOptions;
    343 
    344 typedef enum { sslHandshakingUndetermined = 0,
    345 	       sslHandshakingAsClient,
    346 	       sslHandshakingAsServer
    347 } sslHandshakingType;
    348 
    349 typedef struct sslServerCertsStr {
    350     /* Configuration state for server sockets */
    351     CERTCertificate *     serverCert;
    352     CERTCertificateList * serverCertChain;
    353     ssl3KeyPair *         serverKeyPair;
    354     unsigned int          serverKeyBits;
    355 } sslServerCerts;
    356 
    357 #define SERVERKEY serverKeyPair->privKey
    358 
    359 #define SSL_LOCK_RANK_SPEC 	255
    360 #define SSL_LOCK_RANK_GLOBAL 	NSS_RWLOCK_RANK_NONE
    361 
    362 /* These are the valid values for shutdownHow.
    363 ** These values are each 1 greater than the NSPR values, and the code
    364 ** depends on that relation to efficiently convert PR_SHUTDOWN values
    365 ** into ssl_SHUTDOWN values.  These values use one bit for read, and
    366 ** another bit for write, and can be used as bitmasks.
    367 */
    368 #define ssl_SHUTDOWN_NONE	0	/* NOT shutdown at all */
    369 #define ssl_SHUTDOWN_RCV	1	/* PR_SHUTDOWN_RCV  +1 */
    370 #define ssl_SHUTDOWN_SEND	2	/* PR_SHUTDOWN_SEND +1 */
    371 #define ssl_SHUTDOWN_BOTH	3	/* PR_SHUTDOWN_BOTH +1 */
    372 
    373 /*
    374 ** A gather object. Used to read some data until a count has been
    375 ** satisfied. Primarily for support of async sockets.
    376 ** Everything in here is protected by the recvBufLock.
    377 */
    378 struct sslGatherStr {
    379     int           state;	/* see GS_ values below. */     /* ssl 2 & 3 */
    380 
    381     /* "buf" holds received plaintext SSL records, after decrypt and MAC check.
    382      * SSL2: recv'd ciphertext records are put here, then decrypted in place.
    383      * SSL3: recv'd ciphertext records are put in inbuf (see below), then
    384      *       decrypted into buf.
    385      */
    386     sslBuffer     buf;				/*recvBufLock*/	/* ssl 2 & 3 */
    387 
    388     /* number of bytes previously read into hdr or buf(ssl2) or inbuf (ssl3).
    389     ** (offset - writeOffset) is the number of ciphertext bytes read in but
    390     **     not yet deciphered.
    391     */
    392     unsigned int  offset;                                       /* ssl 2 & 3 */
    393 
    394     /* number of bytes to read in next call to ssl_DefRecv (recv) */
    395     unsigned int  remainder;                                    /* ssl 2 & 3 */
    396 
    397     /* Number of ciphertext bytes to read in after 2-byte SSL record header. */
    398     unsigned int  count;					/* ssl2 only */
    399 
    400     /* size of the final plaintext record.
    401     ** == count - (recordPadding + MAC size)
    402     */
    403     unsigned int  recordLen;					/* ssl2 only */
    404 
    405     /* number of bytes of padding to be removed after decrypting. */
    406     /* This value is taken from the record's hdr[2], which means a too large
    407      * value could crash us.
    408      */
    409     unsigned int  recordPadding;				/* ssl2 only */
    410 
    411     /* plaintext DATA begins this many bytes into "buf".  */
    412     unsigned int  recordOffset;					/* ssl2 only */
    413 
    414     int           encrypted;    /* SSL2 session is now encrypted.  ssl2 only */
    415 
    416     /* These next two values are used by SSL2 and SSL3.
    417     ** DoRecv uses them to extract application data.
    418     ** The difference between writeOffset and readOffset is the amount of
    419     ** data available to the application.   Note that the actual offset of
    420     ** the data in "buf" is recordOffset (above), not readOffset.
    421     ** In the current implementation, this is made available before the
    422     ** MAC is checked!!
    423     */
    424     unsigned int  readOffset;  /* Spot where DATA reader (e.g. application
    425                                ** or handshake code) will read next.
    426                                ** Always zero for SSl3 application data.
    427 			       */
    428     /* offset in buf/inbuf/hdr into which new data will be read from socket. */
    429     unsigned int  writeOffset;
    430 
    431     /* Buffer for ssl3 to read (encrypted) data from the socket */
    432     sslBuffer     inbuf;			/*recvBufLock*/	/* ssl3 only */
    433 
    434     /* The ssl[23]_GatherData functions read data into this buffer, rather
    435     ** than into buf or inbuf, while in the GS_HEADER state.
    436     ** The portion of the SSL record header put here always comes off the wire
    437     ** as plaintext, never ciphertext.
    438     ** For SSL2, the plaintext portion is two bytes long.  For SSl3 it is 5.
    439     ** For DTLS it is 13.
    440     */
    441     unsigned char hdr[13];				/* ssl 2 & 3 or dtls */
    442 
    443     /* Buffer for DTLS data read off the wire as a single datagram */
    444     sslBuffer     dtlsPacket;
    445 
    446     /* the start of the buffered DTLS record in dtlsPacket */
    447     unsigned int  dtlsPacketOffset;
    448 };
    449 
    450 /* sslGather.state */
    451 #define GS_INIT		0
    452 #define GS_HEADER	1
    453 #define GS_MAC		2
    454 #define GS_DATA		3
    455 #define GS_PAD		4
    456 
    457 #if defined(NSS_PLATFORM_CLIENT_AUTH) && defined(XP_WIN32)
    458 typedef PCERT_KEY_CONTEXT PlatformKey;
    459 #elif defined(NSS_PLATFORM_CLIENT_AUTH) && defined(XP_MACOSX)
    460 typedef SecKeyRef PlatformKey;
    461 #else
    462 typedef void *PlatformKey;
    463 #endif
    464 
    465 
    466 
    467 /*
    468 ** ssl3State and CipherSpec structs
    469 */
    470 
    471 /* The SSL bulk cipher definition */
    472 typedef enum {
    473     cipher_null,
    474     cipher_rc4,
    475     cipher_rc4_40,
    476     cipher_rc4_56,
    477     cipher_rc2,
    478     cipher_rc2_40,
    479     cipher_des,
    480     cipher_3des,
    481     cipher_des40,
    482     cipher_idea,
    483     cipher_aes_128,
    484     cipher_aes_256,
    485     cipher_camellia_128,
    486     cipher_camellia_256,
    487     cipher_seed,
    488     cipher_aes_128_gcm,
    489     cipher_chacha20,
    490     cipher_missing              /* reserved for no such supported cipher */
    491     /* This enum must match ssl3_cipherName[] in ssl3con.c.  */
    492 } SSL3BulkCipher;
    493 
    494 typedef enum { type_stream, type_block, type_aead } CipherType;
    495 
    496 #define MAX_IV_LENGTH 24
    497 
    498 /*
    499  * Do not depend upon 64 bit arithmetic in the underlying machine.
    500  */
    501 typedef struct {
    502     PRUint32         high;
    503     PRUint32         low;
    504 } SSL3SequenceNumber;
    505 
    506 typedef PRUint16 DTLSEpoch;
    507 
    508 typedef void (*DTLSTimerCb)(sslSocket *);
    509 
    510 #define MAX_MAC_CONTEXT_BYTES 400  /* 400 is large enough for MD5, SHA-1, and
    511                                     * SHA-256. For SHA-384 support, increase
    512                                     * it to 712. */
    513 #define MAX_MAC_CONTEXT_LLONGS (MAX_MAC_CONTEXT_BYTES / 8)
    514 
    515 #define MAX_CIPHER_CONTEXT_BYTES 2080
    516 #define MAX_CIPHER_CONTEXT_LLONGS (MAX_CIPHER_CONTEXT_BYTES / 8)
    517 
    518 typedef struct {
    519     SSL3Opaque        wrapped_master_secret[48];
    520     PRUint16          wrapped_master_secret_len;
    521     PRUint8           msIsWrapped;
    522     PRUint8           resumable;
    523 } ssl3SidKeys; /* 52 bytes */
    524 
    525 typedef struct {
    526     PK11SymKey  *write_key;
    527     PK11SymKey  *write_mac_key;
    528     PK11Context *write_mac_context;
    529     SECItem     write_key_item;
    530     SECItem     write_iv_item;
    531     SECItem     write_mac_key_item;
    532     SSL3Opaque  write_iv[MAX_IV_LENGTH];
    533     PRUint64    cipher_context[MAX_CIPHER_CONTEXT_LLONGS];
    534 } ssl3KeyMaterial;
    535 
    536 typedef SECStatus (*SSLCipher)(void *               context,
    537                                unsigned char *      out,
    538 			       int *                outlen,
    539 			       int                  maxout,
    540 			       const unsigned char *in,
    541 			       int                  inlen);
    542 typedef SECStatus (*SSLAEADCipher)(
    543 			       ssl3KeyMaterial *    keys,
    544 			       PRBool               doDecrypt,
    545 			       unsigned char *      out,
    546 			       int *                outlen,
    547 			       int                  maxout,
    548 			       const unsigned char *in,
    549 			       int                  inlen,
    550 			       const unsigned char *additionalData,
    551 			       int                  additionalDataLen);
    552 typedef SECStatus (*SSLCompressor)(void *               context,
    553                                    unsigned char *      out,
    554                                    int *                outlen,
    555                                    int                  maxout,
    556                                    const unsigned char *in,
    557                                    int                  inlen);
    558 typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit);
    559 
    560 /* The DTLS anti-replay window. Defined here because we need it in
    561  * the cipher spec. Note that this is a ring buffer but left and
    562  * right represent the true window, with modular arithmetic used to
    563  * map them onto the buffer.
    564  */
    565 #define DTLS_RECVD_RECORDS_WINDOW 1024 /* Packets; approximate
    566 				        * Must be divisible by 8
    567 				        */
    568 typedef struct DTLSRecvdRecordsStr {
    569     unsigned char data[DTLS_RECVD_RECORDS_WINDOW/8];
    570     PRUint64 left;
    571     PRUint64 right;
    572 } DTLSRecvdRecords;
    573 
    574 /*
    575 ** These are the "specs" in the "ssl3" struct.
    576 ** Access to the pointers to these specs, and all the specs' contents
    577 ** (direct and indirect) is protected by the reader/writer lock ss->specLock.
    578 */
    579 typedef struct {
    580     const ssl3BulkCipherDef *cipher_def;
    581     const ssl3MACDef * mac_def;
    582     SSLCompressionMethod compression_method;
    583     int                mac_size;
    584     SSLCipher          encode;
    585     SSLCipher          decode;
    586     SSLAEADCipher      aead;
    587     SSLDestroy         destroy;
    588     void *             encodeContext;
    589     void *             decodeContext;
    590     SSLCompressor      compressor;    /* Don't name these fields compress */
    591     SSLCompressor      decompressor;  /* and uncompress because zconf.h   */
    592                                       /* may define them as macros.       */
    593     SSLDestroy         destroyCompressContext;
    594     void *             compressContext;
    595     SSLDestroy         destroyDecompressContext;
    596     void *             decompressContext;
    597     PRBool             bypassCiphers;	/* did double bypass (at least) */
    598     PK11SymKey *       master_secret;
    599     SSL3SequenceNumber write_seq_num;
    600     SSL3SequenceNumber read_seq_num;
    601     SSL3ProtocolVersion version;
    602     ssl3KeyMaterial    client;
    603     ssl3KeyMaterial    server;
    604     SECItem            msItem;
    605     unsigned char      key_block[NUM_MIXERS * MD5_LENGTH];
    606     unsigned char      raw_master_secret[56];
    607     SECItem            srvVirtName;    /* for server: name that was negotiated
    608                                         * with a client. For client - is
    609                                         * always set to NULL.*/
    610     DTLSEpoch          epoch;
    611     DTLSRecvdRecords   recvdRecords;
    612 } ssl3CipherSpec;
    613 
    614 typedef enum {	never_cached,
    615 		in_client_cache,
    616 		in_server_cache,
    617 		invalid_cache		/* no longer in any cache. */
    618 } Cached;
    619 
    620 #define MAX_PEER_CERT_CHAIN_SIZE 8
    621 
    622 struct sslSessionIDStr {
    623     /* The global cache lock must be held when accessing these members when the
    624      * sid is in any cache.
    625      */
    626     sslSessionID *        next;   /* chain used for client sockets, only */
    627     Cached                cached;
    628     int                   references;
    629     PRUint32              lastAccessTime;	/* seconds since Jan 1, 1970 */
    630 
    631     /* The rest of the members, except for the members of u.ssl3.locked, may
    632      * be modified only when the sid is not in any cache.
    633      */
    634 
    635     CERTCertificate *     peerCert;
    636     CERTCertificate *     peerCertChain[MAX_PEER_CERT_CHAIN_SIZE];
    637     SECItemArray          peerCertStatus; /* client only */
    638     const char *          peerID;     /* client only */
    639     const char *          urlSvrName; /* client only */
    640     CERTCertificate *     localCert;
    641 
    642     PRIPv6Addr            addr;
    643     PRUint16              port;
    644 
    645     SSL3ProtocolVersion   version;
    646 
    647     PRUint32              creationTime;		/* seconds since Jan 1, 1970 */
    648     PRUint32              expirationTime;	/* seconds since Jan 1, 1970 */
    649 
    650     SSLSignType           authAlgorithm;
    651     PRUint32              authKeyBits;
    652     SSLKEAType            keaType;
    653     PRUint32              keaKeyBits;
    654 
    655     union {
    656 	struct {
    657 	    /* the V2 code depends upon the size of sessionID.  */
    658 	    unsigned char         sessionID[SSL2_SESSIONID_BYTES];
    659 
    660 	    /* Stuff used to recreate key and read/write cipher objects */
    661 	    SECItem               masterKey;        /* never wrapped */
    662 	    int                   cipherType;
    663 	    SECItem               cipherArg;
    664 	    int                   keyBits;
    665 	    int                   secretKeyBits;
    666 	} ssl2;
    667 	struct {
    668 	    /* values that are copied into the server's on-disk SID cache. */
    669 	    PRUint8               sessionIDLength;
    670 	    SSL3Opaque            sessionID[SSL3_SESSIONID_BYTES];
    671 
    672 	    ssl3CipherSuite       cipherSuite;
    673 	    SSLCompressionMethod  compression;
    674 	    int                   policy;
    675 	    ssl3SidKeys           keys;
    676 	    CK_MECHANISM_TYPE     masterWrapMech;
    677 				  /* mechanism used to wrap master secret */
    678             SSL3KEAType           exchKeyType;
    679 				  /* key type used in exchange algorithm,
    680 				   * and to wrap the sym wrapping key. */
    681 #ifdef NSS_ENABLE_ECC
    682 	    PRUint32              negotiatedECCurves;
    683 #endif /* NSS_ENABLE_ECC */
    684 
    685 	    /* The following values are NOT restored from the server's on-disk
    686 	     * session cache, but are restored from the client's cache.
    687 	     */
    688  	    PK11SymKey *      clientWriteKey;
    689 	    PK11SymKey *      serverWriteKey;
    690 
    691 	    /* The following values pertain to the slot that wrapped the
    692 	    ** master secret. (used only in client)
    693 	    */
    694 	    SECMODModuleID    masterModuleID;
    695 				    /* what module wrapped the master secret */
    696 	    CK_SLOT_ID        masterSlotID;
    697 	    PRUint16	      masterWrapIndex;
    698 				/* what's the key index for the wrapping key */
    699 	    PRUint16          masterWrapSeries;
    700 	                        /* keep track of the slot series, so we don't
    701 				 * accidently try to use new keys after the
    702 				 * card gets removed and replaced.*/
    703 
    704 	    /* The following values pertain to the slot that did the signature
    705 	    ** for client auth.   (used only in client)
    706 	    */
    707 	    SECMODModuleID    clAuthModuleID;
    708 	    CK_SLOT_ID        clAuthSlotID;
    709 	    PRUint16          clAuthSeries;
    710 
    711             char              masterValid;
    712 	    char              clAuthValid;
    713 
    714 	    SECItem           srvName;
    715 
    716             /* originalHandshakeHash contains the hash of the original, full
    717              * handshake prior to the server's final flow. This is either a
    718              * SHA-1/MD5 combination (for TLS < 1.2) or the TLS PRF hash (for
    719              * TLS 1.2). This is recorded and used only when ChannelID is
    720              * negotiated as it's used to bind the ChannelID signature on the
    721              * resumption handshake to the original handshake. */
    722 	    SECItem           originalHandshakeHash;
    723 
    724 	    /* Signed certificate timestamps received in a TLS extension.
    725 	    ** (used only in client).
    726 	    */
    727 	    SECItem	      signedCertTimestamps;
    728 
    729 	    /* This lock is lazily initialized by CacheSID when a sid is first
    730 	     * cached. Before then, there is no need to lock anything because
    731 	     * the sid isn't being shared by anything.
    732 	     */
    733 	    NSSRWLock *lock;
    734 
    735 	    /* The lock must be held while reading or writing these members
    736 	     * because they change while the sid is cached.
    737 	     */
    738 	    struct {
    739 		/* The session ticket, if we have one, is sent as an extension
    740 		 * in the ClientHello message. This field is used only by
    741 		 * clients. It is protected by lock when lock is non-null
    742 		 * (after the sid has been added to the client session cache).
    743 		 */
    744 		NewSessionTicket sessionTicket;
    745 	    } locked;
    746 	} ssl3;
    747     } u;
    748 };
    749 
    750 typedef struct ssl3CipherSuiteDefStr {
    751     ssl3CipherSuite          cipher_suite;
    752     SSL3BulkCipher           bulk_cipher_alg;
    753     SSL3MACAlgorithm         mac_alg;
    754     SSL3KeyExchangeAlgorithm key_exchange_alg;
    755 } ssl3CipherSuiteDef;
    756 
    757 /*
    758 ** There are tables of these, all const.
    759 */
    760 typedef struct {
    761     SSL3KeyExchangeAlgorithm kea;
    762     SSL3KEAType              exchKeyType;
    763     SSL3SignType             signKeyType;
    764     PRBool                   is_limited;
    765     int                      key_size_limit;
    766     PRBool                   tls_keygen;
    767 } ssl3KEADef;
    768 
    769 /*
    770 ** There are tables of these, all const.
    771 */
    772 struct ssl3BulkCipherDefStr {
    773     SSL3BulkCipher  cipher;
    774     SSLCipherAlgorithm calg;
    775     int             key_size;
    776     int             secret_key_size;
    777     CipherType      type;
    778     int             iv_size;
    779     int             block_size;
    780     int             tag_size;  /* authentication tag size for AEAD ciphers. */
    781     int             explicit_nonce_size;               /* for AEAD ciphers. */
    782 };
    783 
    784 /*
    785 ** There are tables of these, all const.
    786 */
    787 struct ssl3MACDefStr {
    788     SSL3MACAlgorithm mac;
    789     CK_MECHANISM_TYPE mmech;
    790     int              pad_size;
    791     int              mac_size;
    792 };
    793 
    794 typedef enum {
    795     wait_client_hello,
    796     wait_client_cert,
    797     wait_client_key,
    798     wait_cert_verify,
    799     wait_change_cipher,
    800     wait_finished,
    801     wait_server_hello,
    802     wait_certificate_status,
    803     wait_server_cert,
    804     wait_server_key,
    805     wait_cert_request,
    806     wait_hello_done,
    807     wait_new_session_ticket,
    808     idle_handshake
    809 } SSL3WaitState;
    810 
    811 /*
    812  * TLS extension related constants and data structures.
    813  */
    814 typedef struct TLSExtensionDataStr       TLSExtensionData;
    815 typedef struct SessionTicketDataStr      SessionTicketData;
    816 
    817 struct TLSExtensionDataStr {
    818     /* registered callbacks that send server hello extensions */
    819     ssl3HelloExtensionSender serverSenders[SSL_MAX_EXTENSIONS];
    820     /* Keep track of the extensions that are negotiated. */
    821     PRUint16 numAdvertised;
    822     PRUint16 numNegotiated;
    823     PRUint16 advertised[SSL_MAX_EXTENSIONS];
    824     PRUint16 negotiated[SSL_MAX_EXTENSIONS];
    825 
    826     /* SessionTicket Extension related data. */
    827     PRBool ticketTimestampVerified;
    828     PRBool emptySessionTicket;
    829     PRBool sentSessionTicketInClientHello;
    830 
    831     /* SNI Extension related data
    832      * Names data is not coppied from the input buffer. It can not be
    833      * used outside the scope where input buffer is defined and that
    834      * is beyond ssl3_HandleClientHello function. */
    835     SECItem *sniNameArr;
    836     PRUint32 sniNameArrSize;
    837 
    838     /* Signed Certificate Timestamps extracted from the TLS extension.
    839      * (client only).
    840      * This container holds a temporary pointer to the extension data,
    841      * until a session structure (the sec.ci.sid of an sslSocket) is setup
    842      * that can hold a permanent copy of the data
    843      * (in sec.ci.sid.u.ssl3.signedCertTimestamps).
    844      * The data pointed to by this structure is neither explicitly allocated
    845      * nor copied: the pointer points to the handshake message buffer and is
    846      * only valid in the scope of ssl3_HandleServerHello.
    847      */
    848     SECItem signedCertTimestamps;
    849 };
    850 
    851 typedef SECStatus (*sslRestartTarget)(sslSocket *);
    852 
    853 /*
    854 ** A DTLS queued message (potentially to be retransmitted)
    855 */
    856 typedef struct DTLSQueuedMessageStr {
    857     PRCList link;         /* The linked list link */
    858     DTLSEpoch epoch;      /* The epoch to use */
    859     SSL3ContentType type; /* The message type */
    860     unsigned char *data;  /* The data */
    861     PRUint16 len;         /* The data length */
    862 } DTLSQueuedMessage;
    863 
    864 typedef enum {
    865     handshake_hash_unknown = 0,
    866     handshake_hash_combo = 1,  /* The MD5/SHA-1 combination */
    867     handshake_hash_single = 2  /* A single hash */
    868 } SSL3HandshakeHashType;
    869 
    870 /*
    871 ** This is the "hs" member of the "ssl3" struct.
    872 ** This entire struct is protected by ssl3HandshakeLock
    873 */
    874 typedef struct SSL3HandshakeStateStr {
    875     SSL3Random            server_random;
    876     SSL3Random            client_random;
    877     SSL3WaitState         ws;
    878 
    879     /* This group of members is used for handshake running hashes. */
    880     SSL3HandshakeHashType hashType;
    881     sslBuffer             messages;    /* Accumulated handshake messages */
    882 #ifndef NO_PKCS11_BYPASS
    883     /* Bypass mode:
    884      * SSL 3.0 - TLS 1.1 use both |md5_cx| and |sha_cx|. |md5_cx| is used for
    885      * MD5 and |sha_cx| for SHA-1.
    886      * TLS 1.2 and later use only |sha_cx|, for SHA-256. NOTE: When we support
    887      * SHA-384, increase MAX_MAC_CONTEXT_BYTES to 712. */
    888     PRUint64              md5_cx[MAX_MAC_CONTEXT_LLONGS];
    889     PRUint64              sha_cx[MAX_MAC_CONTEXT_LLONGS];
    890     const SECHashObject * sha_obj;
    891     /* The function prototype of sha_obj->clone() does not match the prototype
    892      * of the freebl <HASH>_Clone functions, so we need a dedicated function
    893      * pointer for the <HASH>_Clone function. */
    894     void (*sha_clone)(void *dest, void *src);
    895 #endif
    896     /* PKCS #11 mode:
    897      * SSL 3.0 - TLS 1.1 use both |md5| and |sha|. |md5| is used for MD5 and
    898      * |sha| for SHA-1.
    899      * TLS 1.2 and later use only |sha|, for SHA-256. */
    900     /* NOTE: On the client side, TLS 1.2 and later use |md5| as a backup
    901      * handshake hash for generating client auth signatures. Confusingly, the
    902      * backup hash function is SHA-1. */
    903 #define backupHash md5
    904     PK11Context *         md5;
    905     PK11Context *         sha;
    906 
    907 const ssl3KEADef *        kea_def;
    908     ssl3CipherSuite       cipher_suite;
    909 const ssl3CipherSuiteDef *suite_def;
    910     SSLCompressionMethod  compression;
    911     sslBuffer             msg_body;    /* protected by recvBufLock */
    912                                /* partial handshake message from record layer */
    913     unsigned int          header_bytes;
    914                                /* number of bytes consumed from handshake */
    915                                /* message for message type and header length */
    916     SSL3HandshakeType     msg_type;
    917     unsigned long         msg_len;
    918     SECItem               ca_list;     /* used only by client */
    919     PRBool                isResuming;  /* are we resuming a session */
    920     PRBool                usedStepDownKey;  /* we did a server key exchange. */
    921     PRBool                sendingSCSV; /* instead of empty RI */
    922     sslBuffer             msgState;    /* current state for handshake messages*/
    923                                        /* protected by recvBufLock */
    924 
    925     /* The session ticket received in a NewSessionTicket message is temporarily
    926      * stored in newSessionTicket until the handshake is finished; then it is
    927      * moved to the sid.
    928      */
    929     PRBool                receivedNewSessionTicket;
    930     NewSessionTicket      newSessionTicket;
    931 
    932     PRUint16              finishedBytes; /* size of single finished below */
    933     union {
    934 	TLSFinished       tFinished[2]; /* client, then server */
    935 	SSL3Finished      sFinished[2];
    936 	SSL3Opaque        data[72];
    937     }                     finishedMsgs;
    938 #ifdef NSS_ENABLE_ECC
    939     PRUint32              negotiatedECCurves; /* bit mask */
    940 #endif /* NSS_ENABLE_ECC */
    941 
    942     PRBool                authCertificatePending;
    943     /* Which function should SSL_RestartHandshake* call if we're blocked?
    944      * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake,
    945      * or ssl3_AlwaysFail */
    946     sslRestartTarget      restartTarget;
    947     /* Shared state between ssl3_HandleFinished and ssl3_FinishHandshake */
    948     PRBool                cacheSID;
    949 
    950     PRBool                canFalseStart;   /* Can/did we False Start */
    951 
    952     /* clientSigAndHash contains the contents of the signature_algorithms
    953      * extension (if any) from the client. This is only valid for TLS 1.2
    954      * or later. */
    955     SSL3SignatureAndHashAlgorithm *clientSigAndHash;
    956     unsigned int          numClientSigAndHash;
    957 
    958     /* This group of values is used for DTLS */
    959     PRUint16              sendMessageSeq;  /* The sending message sequence
    960 					    * number */
    961     PRCList               lastMessageFlight; /* The last message flight we
    962 					      * sent */
    963     PRUint16              maxMessageSent;    /* The largest message we sent */
    964     PRUint16              recvMessageSeq;  /* The receiving message sequence
    965 					    * number */
    966     sslBuffer             recvdFragments;  /* The fragments we have received in
    967 					    * a bitmask */
    968     PRInt32               recvdHighWater;  /* The high water mark for fragments
    969 					    * received. -1 means no reassembly
    970 					    * in progress. */
    971     unsigned char         cookie[32];      /* The cookie */
    972     unsigned char         cookieLen;       /* The length of the cookie */
    973     PRIntervalTime        rtTimerStarted;  /* When the timer was started */
    974     DTLSTimerCb           rtTimerCb;       /* The function to call on expiry */
    975     PRUint32              rtTimeoutMs;     /* The length of the current timeout
    976 					    * used for backoff (in ms) */
    977     PRUint32              rtRetries;       /* The retry counter */
    978 } SSL3HandshakeState;
    979 
    980 
    981 
    982 /*
    983 ** This is the "ssl3" struct, as in "ss->ssl3".
    984 ** note:
    985 ** usually,   crSpec == cwSpec and prSpec == pwSpec.
    986 ** Sometimes, crSpec == pwSpec and prSpec == cwSpec.
    987 ** But there are never more than 2 actual specs.
    988 ** No spec must ever be modified if either "current" pointer points to it.
    989 */
    990 struct ssl3StateStr {
    991 
    992     /*
    993     ** The following Specs and Spec pointers must be protected using the
    994     ** Spec Lock.
    995     */
    996     ssl3CipherSpec *     crSpec; 	/* current read spec. */
    997     ssl3CipherSpec *     prSpec; 	/* pending read spec. */
    998     ssl3CipherSpec *     cwSpec; 	/* current write spec. */
    999     ssl3CipherSpec *     pwSpec; 	/* pending write spec. */
   1000 
   1001     CERTCertificate *    clientCertificate;  /* used by client */
   1002     SECKEYPrivateKey *   clientPrivateKey;   /* used by client */
   1003     /* platformClientKey is present even when NSS_PLATFORM_CLIENT_AUTH is not
   1004      * defined in order to allow cleaner conditional code.
   1005      * At most one of clientPrivateKey and platformClientKey may be set. */
   1006     PlatformKey          platformClientKey;  /* used by client */
   1007     CERTCertificateList *clientCertChain;    /* used by client */
   1008     PRBool               sendEmptyCert;      /* used by client */
   1009 
   1010     SECKEYPrivateKey    *channelID;          /* used by client */
   1011     SECKEYPublicKey     *channelIDPub;       /* used by client */
   1012 
   1013     int                  policy;
   1014 			/* This says what cipher suites we can do, and should
   1015 			 * be either SSL_ALLOWED or SSL_RESTRICTED
   1016 			 */
   1017     PLArenaPool *        peerCertArena;
   1018 			    /* These are used to keep track of the peer CA */
   1019     void *               peerCertChain;
   1020 			    /* chain while we are trying to validate it.   */
   1021     CERTDistNames *      ca_list;
   1022 			    /* used by server.  trusted CAs for this socket. */
   1023     PRBool               initialized;
   1024     SSL3HandshakeState   hs;
   1025     ssl3CipherSpec       specs[2];	/* one is current, one is pending. */
   1026 
   1027     /* In a client: if the server supports Next Protocol Negotiation, then
   1028      * this is the protocol that was negotiated.
   1029      */
   1030     SECItem		 nextProto;
   1031     SSLNextProtoState    nextProtoState;
   1032 
   1033     PRUint16             mtu;   /* Our estimate of the MTU */
   1034 
   1035     /* DTLS-SRTP cipher suite preferences (if any) */
   1036     PRUint16             dtlsSRTPCiphers[MAX_DTLS_SRTP_CIPHER_SUITES];
   1037     PRUint16             dtlsSRTPCipherCount;
   1038     PRUint16             dtlsSRTPCipherSuite;	/* 0 if not selected */
   1039 };
   1040 
   1041 #define DTLS_MAX_MTU  1500      /* Ethernet MTU but without subtracting the
   1042 				 * headers, so slightly larger than expected */
   1043 #define IS_DTLS(ss) (ss->protocolVariant == ssl_variant_datagram)
   1044 
   1045 typedef struct {
   1046     SSL3ContentType      type;
   1047     SSL3ProtocolVersion  version;
   1048     SSL3SequenceNumber   seq_num;  /* DTLS only */
   1049     sslBuffer *          buf;
   1050 } SSL3Ciphertext;
   1051 
   1052 struct ssl3KeyPairStr {
   1053     SECKEYPrivateKey *    privKey;
   1054     SECKEYPublicKey *     pubKey;
   1055     PRInt32               refCount;	/* use PR_Atomic calls for this. */
   1056 };
   1057 
   1058 typedef struct SSLWrappedSymWrappingKeyStr {
   1059     SSL3Opaque        wrappedSymmetricWrappingkey[512];
   1060     CK_MECHANISM_TYPE symWrapMechanism;
   1061 		    /* unwrapped symmetric wrapping key uses this mechanism */
   1062     CK_MECHANISM_TYPE asymWrapMechanism;
   1063 		    /* mechanism used to wrap the SymmetricWrappingKey using
   1064 		     * server's public and/or private keys. */
   1065     SSL3KEAType       exchKeyType;   /* type of keys used to wrap SymWrapKey*/
   1066     PRInt32           symWrapMechIndex;
   1067     PRUint16          wrappedSymKeyLen;
   1068 } SSLWrappedSymWrappingKey;
   1069 
   1070 typedef struct SessionTicketStr {
   1071     PRUint16              ticket_version;
   1072     SSL3ProtocolVersion   ssl_version;
   1073     ssl3CipherSuite       cipher_suite;
   1074     SSLCompressionMethod  compression_method;
   1075     SSLSignType           authAlgorithm;
   1076     PRUint32              authKeyBits;
   1077     SSLKEAType            keaType;
   1078     PRUint32              keaKeyBits;
   1079     /*
   1080      * exchKeyType and msWrapMech contain meaningful values only if
   1081      * ms_is_wrapped is true.
   1082      */
   1083     PRUint8               ms_is_wrapped;
   1084     SSLKEAType            exchKeyType; /* XXX(wtc): same as keaType above? */
   1085     CK_MECHANISM_TYPE     msWrapMech;
   1086     PRUint16              ms_length;
   1087     SSL3Opaque            master_secret[48];
   1088     ClientIdentity        client_identity;
   1089     SECItem               peer_cert;
   1090     PRUint32              timestamp;
   1091     SECItem               srvName; /* negotiated server name */
   1092 }  SessionTicket;
   1093 
   1094 /*
   1095  * SSL2 buffers used in SSL3.
   1096  *     writeBuf in the SecurityInfo maintained by sslsecur.c is used
   1097  *              to hold the data just about to be passed to the kernel
   1098  *     sendBuf in the ConnectInfo maintained by sslcon.c is used
   1099  *              to hold handshake messages as they are accumulated
   1100  */
   1101 
   1102 /*
   1103 ** This is "ci", as in "ss->sec.ci".
   1104 **
   1105 ** Protection:  All the variables in here are protected by
   1106 ** firstHandshakeLock AND (in ssl3) ssl3HandshakeLock
   1107 */
   1108 struct sslConnectInfoStr {
   1109     /* outgoing handshakes appended to this. */
   1110     sslBuffer       sendBuf;	                /*xmitBufLock*/ /* ssl 2 & 3 */
   1111 
   1112     PRIPv6Addr      peer;                                       /* ssl 2 & 3 */
   1113     unsigned short  port;                                       /* ssl 2 & 3 */
   1114 
   1115     sslSessionID   *sid;                                        /* ssl 2 & 3 */
   1116 
   1117     /* see CIS_HAVE defines below for the bit values in *elements. */
   1118     char            elements;					/* ssl2 only */
   1119     char            requiredElements;				/* ssl2 only */
   1120     char            sentElements;                               /* ssl2 only */
   1121 
   1122     char            sentFinished;                               /* ssl2 only */
   1123 
   1124     /* Length of server challenge.  Used by client when saving challenge */
   1125     int             serverChallengeLen;                         /* ssl2 only */
   1126     /* type of authentication requested by server */
   1127     unsigned char   authType;                                   /* ssl2 only */
   1128 
   1129     /* Challenge sent by client to server in client-hello message */
   1130     /* SSL3 gets a copy of this.  See ssl3_StartHandshakeHash().  */
   1131     unsigned char   clientChallenge[SSL_MAX_CHALLENGE_BYTES];   /* ssl 2 & 3 */
   1132 
   1133     /* Connection-id sent by server to client in server-hello message */
   1134     unsigned char   connectionID[SSL_CONNECTIONID_BYTES];	/* ssl2 only */
   1135 
   1136     /* Challenge sent by server to client in request-certificate message */
   1137     unsigned char   serverChallenge[SSL_MAX_CHALLENGE_BYTES];	/* ssl2 only */
   1138 
   1139     /* Information kept to handle a request-certificate message */
   1140     unsigned char   readKey[SSL_MAX_MASTER_KEY_BYTES];		/* ssl2 only */
   1141     unsigned char   writeKey[SSL_MAX_MASTER_KEY_BYTES];		/* ssl2 only */
   1142     unsigned        keySize;					/* ssl2 only */
   1143 };
   1144 
   1145 /* bit values for ci->elements, ci->requiredElements, sentElements. */
   1146 #define CIS_HAVE_MASTER_KEY		0x01
   1147 #define CIS_HAVE_CERTIFICATE		0x02
   1148 #define CIS_HAVE_FINISHED		0x04
   1149 #define CIS_HAVE_VERIFY			0x08
   1150 
   1151 /* Note: The entire content of this struct and whatever it points to gets
   1152  * blown away by SSL_ResetHandshake().  This is "sec" as in "ss->sec".
   1153  *
   1154  * Unless otherwise specified below, the contents of this struct are
   1155  * protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock.
   1156  */
   1157 struct sslSecurityInfoStr {
   1158     sslSendFunc      send;			/*xmitBufLock*/	/* ssl 2 & 3 */
   1159     int              isServer;			/* Spec Lock?*/	/* ssl 2 & 3 */
   1160     sslBuffer        writeBuf;			/*xmitBufLock*/	/* ssl 2 & 3 */
   1161 
   1162     int              cipherType;				/* ssl 2 & 3 */
   1163     int              keyBits;					/* ssl 2 & 3 */
   1164     int              secretKeyBits;				/* ssl 2 & 3 */
   1165     CERTCertificate *localCert;					/* ssl 2 & 3 */
   1166     CERTCertificate *peerCert;					/* ssl 2 & 3 */
   1167     SECKEYPublicKey *peerKey;					/* ssl3 only */
   1168 
   1169     SSLSignType      authAlgorithm;
   1170     PRUint32         authKeyBits;
   1171     SSLKEAType       keaType;
   1172     PRUint32         keaKeyBits;
   1173 
   1174     /*
   1175     ** Procs used for SID cache (nonce) management.
   1176     ** Different implementations exist for clients/servers
   1177     ** The lookup proc is only used for servers.  Baloney!
   1178     */
   1179     sslSessionIDCacheFunc     cache;				/* ssl 2 & 3 */
   1180     sslSessionIDUncacheFunc   uncache;				/* ssl 2 & 3 */
   1181 
   1182     /*
   1183     ** everything below here is for ssl2 only.
   1184     ** This stuff is equivalent to SSL3's "spec", and is protected by the
   1185     ** same "Spec Lock" as used for SSL3's specs.
   1186     */
   1187     PRUint32           sendSequence;		/*xmitBufLock*/	/* ssl2 only */
   1188     PRUint32           rcvSequence;		/*recvBufLock*/	/* ssl2 only */
   1189 
   1190     /* Hash information; used for one-way-hash functions (MD2, MD5, etc.) */
   1191     const SECHashObject   *hash;		/* Spec Lock */ /* ssl2 only */
   1192     void            *hashcx;			/* Spec Lock */	/* ssl2 only */
   1193 
   1194     SECItem          sendSecret;		/* Spec Lock */	/* ssl2 only */
   1195     SECItem          rcvSecret;			/* Spec Lock */	/* ssl2 only */
   1196 
   1197     /* Session cypher contexts; one for each direction */
   1198     void            *readcx;			/* Spec Lock */	/* ssl2 only */
   1199     void            *writecx;			/* Spec Lock */	/* ssl2 only */
   1200     SSLCipher        enc;			/* Spec Lock */	/* ssl2 only */
   1201     SSLCipher        dec;			/* Spec Lock */	/* ssl2 only */
   1202     void           (*destroy)(void *, PRBool);	/* Spec Lock */	/* ssl2 only */
   1203 
   1204     /* Blocking information for the session cypher */
   1205     int              blockShift;		/* Spec Lock */	/* ssl2 only */
   1206     int              blockSize;			/* Spec Lock */	/* ssl2 only */
   1207 
   1208     /* These are used during a connection handshake */
   1209     sslConnectInfo   ci;					/* ssl 2 & 3 */
   1210 
   1211 };
   1212 
   1213 /*
   1214 ** SSL Socket struct
   1215 **
   1216 ** Protection:  XXX
   1217 */
   1218 struct sslSocketStr {
   1219     PRFileDesc *	fd;
   1220 
   1221     /* Pointer to operations vector for this socket */
   1222     const sslSocketOps * ops;
   1223 
   1224     /* SSL socket options */
   1225     sslOptions       opt;
   1226     /* Enabled version range */
   1227     SSLVersionRange  vrange;
   1228 
   1229     /* State flags */
   1230     unsigned long    clientAuthRequested;
   1231     unsigned long    delayDisabled;       /* Nagle delay disabled */
   1232     unsigned long    firstHsDone;         /* first handshake is complete. */
   1233     unsigned long    enoughFirstHsDone;   /* enough of the first handshake is
   1234 					   * done for callbacks to be able to
   1235 					   * retrieve channel security
   1236 					   * parameters from the SSL socket. */
   1237     unsigned long    handshakeBegun;
   1238     unsigned long    lastWriteBlocked;
   1239     unsigned long    recvdCloseNotify;    /* received SSL EOF. */
   1240     unsigned long    TCPconnected;
   1241     unsigned long    appDataBuffered;
   1242     unsigned long    peerRequestedProtection; /* from old renegotiation */
   1243 
   1244     /* version of the protocol to use */
   1245     SSL3ProtocolVersion version;
   1246     SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. */
   1247 
   1248     sslSecurityInfo  sec;		/* not a pointer any more */
   1249 
   1250     /* protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock. */
   1251     const char      *url;				/* ssl 2 & 3 */
   1252 
   1253     sslHandshakeFunc handshake;				/*firstHandshakeLock*/
   1254     sslHandshakeFunc nextHandshake;			/*firstHandshakeLock*/
   1255     sslHandshakeFunc securityHandshake;			/*firstHandshakeLock*/
   1256 
   1257     /* the following variable is only used with socks or other proxies. */
   1258     char *           peerID;	/* String uniquely identifies target server. */
   1259 
   1260     unsigned char *  cipherSpecs;
   1261     unsigned int     sizeCipherSpecs;
   1262 const unsigned char *  preferredCipher;
   1263 
   1264     /* TLS ClientCertificateTypes requested during HandleCertificateRequest. */
   1265     /* Will be NULL at all other times. */
   1266     const SECItem      *requestedCertTypes;
   1267 
   1268     ssl3KeyPair *         stepDownKeyPair;	/* RSA step down keys */
   1269 
   1270     /* Callbacks */
   1271     SSLAuthCertificate        authCertificate;
   1272     void                     *authCertificateArg;
   1273     SSLGetClientAuthData      getClientAuthData;
   1274     void                     *getClientAuthDataArg;
   1275 #ifdef NSS_PLATFORM_CLIENT_AUTH
   1276     SSLGetPlatformClientAuthData getPlatformClientAuthData;
   1277     void                        *getPlatformClientAuthDataArg;
   1278 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
   1279     SSLSNISocketConfig        sniSocketConfig;
   1280     void                     *sniSocketConfigArg;
   1281     SSLBadCertHandler         handleBadCert;
   1282     void                     *badCertArg;
   1283     SSLHandshakeCallback      handshakeCallback;
   1284     void                     *handshakeCallbackData;
   1285     SSLCanFalseStartCallback  canFalseStartCallback;
   1286     void                     *canFalseStartCallbackData;
   1287     void                     *pkcs11PinArg;
   1288     SSLNextProtoCallback      nextProtoCallback;
   1289     void                     *nextProtoArg;
   1290     SSLClientChannelIDCallback getChannelID;
   1291     void                     *getChannelIDArg;
   1292 
   1293     PRIntervalTime            rTimeout; /* timeout for NSPR I/O */
   1294     PRIntervalTime            wTimeout; /* timeout for NSPR I/O */
   1295     PRIntervalTime            cTimeout; /* timeout for NSPR I/O */
   1296 
   1297     PZLock *      recvLock;	/* lock against multiple reader threads. */
   1298     PZLock *      sendLock;	/* lock against multiple sender threads. */
   1299 
   1300     PZMonitor *   recvBufLock;	/* locks low level recv buffers. */
   1301     PZMonitor *   xmitBufLock;	/* locks low level xmit buffers. */
   1302 
   1303     /* Only one thread may operate on the socket until the initial handshake
   1304     ** is complete.  This Monitor ensures that.  Since SSL2 handshake is
   1305     ** only done once, this is also effectively the SSL2 handshake lock.
   1306     */
   1307     PZMonitor *   firstHandshakeLock;
   1308 
   1309     /* This monitor protects the ssl3 handshake state machine data.
   1310     ** Only one thread (reader or writer) may be in the ssl3 handshake state
   1311     ** machine at any time.  */
   1312     PZMonitor *   ssl3HandshakeLock;
   1313 
   1314     /* reader/writer lock, protects the secret data needed to encrypt and MAC
   1315     ** outgoing records, and to decrypt and MAC check incoming ciphertext
   1316     ** records.  */
   1317     NSSRWLock *   specLock;
   1318 
   1319     /* handle to perm cert db (and implicitly to the temp cert db) used
   1320     ** with this socket.
   1321     */
   1322     CERTCertDBHandle * dbHandle;
   1323 
   1324     PRThread *  writerThread;   /* thread holds SSL_LOCK_WRITER lock */
   1325 
   1326     PRUint16	shutdownHow; 	/* See ssl_SHUTDOWN defines below. */
   1327 
   1328     PRUint16	allowedByPolicy;          /* copy of global policy bits. */
   1329     PRUint16	maybeAllowedByPolicy;     /* copy of global policy bits. */
   1330     PRUint16	chosenPreference;         /* SSL2 cipher preferences. */
   1331 
   1332     sslHandshakingType handshaking;
   1333 
   1334     /* Gather object used for gathering data */
   1335     sslGather        gs;				/*recvBufLock*/
   1336 
   1337     sslBuffer        saveBuf;				/*xmitBufLock*/
   1338     sslBuffer        pendingBuf;			/*xmitBufLock*/
   1339 
   1340     /* Configuration state for server sockets */
   1341     /* server cert and key for each KEA type */
   1342     sslServerCerts        serverCerts[kt_kea_size];
   1343     /* each cert needs its own status */
   1344     SECItemArray *        certStatusArray[kt_kea_size];
   1345 
   1346     ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED];
   1347     ssl3KeyPair *         ephemeralECDHKeyPair; /* for ECDHE-* handshake */
   1348 
   1349     /* SSL3 state info.  Formerly was a pointer */
   1350     ssl3State        ssl3;
   1351 
   1352     /*
   1353      * TLS extension related data.
   1354      */
   1355     /* True when the current session is a stateless resume. */
   1356     PRBool               statelessResume;
   1357     TLSExtensionData     xtnData;
   1358 
   1359     /* Whether we are doing stream or datagram mode */
   1360     SSLProtocolVariant   protocolVariant;
   1361 };
   1362 
   1363 
   1364 
   1365 /* All the global data items declared here should be protected using the
   1366 ** ssl_global_data_lock, which is a reader/writer lock.
   1367 */
   1368 extern NSSRWLock *             ssl_global_data_lock;
   1369 extern char                    ssl_debug;
   1370 extern char                    ssl_trace;
   1371 extern FILE *                  ssl_trace_iob;
   1372 extern FILE *                  ssl_keylog_iob;
   1373 extern CERTDistNames *         ssl3_server_ca_list;
   1374 extern PRUint32                ssl_sid_timeout;
   1375 extern PRUint32                ssl3_sid_timeout;
   1376 
   1377 extern const char * const      ssl_cipherName[];
   1378 extern const char * const      ssl3_cipherName[];
   1379 
   1380 extern sslSessionIDLookupFunc  ssl_sid_lookup;
   1381 extern sslSessionIDCacheFunc   ssl_sid_cache;
   1382 extern sslSessionIDUncacheFunc ssl_sid_uncache;
   1383 
   1384 /************************************************************************/
   1385 
   1386 SEC_BEGIN_PROTOS
   1387 
   1388 /* Functions for handling SECItemArrays, added in NSS 3.15 */
   1389 extern SECItemArray *SECITEM_AllocArray(PLArenaPool *arena,
   1390                                         SECItemArray *array,
   1391                                         unsigned int len);
   1392 extern SECItemArray *SECITEM_DupArray(PLArenaPool *arena,
   1393                                       const SECItemArray *from);
   1394 extern void SECITEM_FreeArray(SECItemArray *array, PRBool freeit);
   1395 extern void SECITEM_ZfreeArray(SECItemArray *array, PRBool freeit);
   1396 
   1397 /* Internal initialization and installation of the SSL error tables */
   1398 extern SECStatus ssl_Init(void);
   1399 extern SECStatus ssl_InitializePRErrorTable(void);
   1400 
   1401 /* Implementation of ops for default (non socks, non secure) case */
   1402 extern int ssl_DefConnect(sslSocket *ss, const PRNetAddr *addr);
   1403 extern PRFileDesc *ssl_DefAccept(sslSocket *ss, PRNetAddr *addr);
   1404 extern int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr);
   1405 extern int ssl_DefListen(sslSocket *ss, int backlog);
   1406 extern int ssl_DefShutdown(sslSocket *ss, int how);
   1407 extern int ssl_DefClose(sslSocket *ss);
   1408 extern int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
   1409 extern int ssl_DefSend(sslSocket *ss, const unsigned char *buf,
   1410 		       int len, int flags);
   1411 extern int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len);
   1412 extern int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len);
   1413 extern int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name);
   1414 extern int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name);
   1415 extern int ssl_DefGetsockopt(sslSocket *ss, PRSockOption optname,
   1416 			     void *optval, PRInt32 *optlen);
   1417 extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname,
   1418 			     const void *optval, PRInt32 optlen);
   1419 
   1420 /* Implementation of ops for socks only case */
   1421 extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr);
   1422 extern PRFileDesc *ssl_SocksAccept(sslSocket *ss, PRNetAddr *addr);
   1423 extern int ssl_SocksBind(sslSocket *ss, const PRNetAddr *addr);
   1424 extern int ssl_SocksListen(sslSocket *ss, int backlog);
   1425 extern int ssl_SocksGetsockname(sslSocket *ss, PRNetAddr *name);
   1426 extern int ssl_SocksRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
   1427 extern int ssl_SocksSend(sslSocket *ss, const unsigned char *buf,
   1428 			 int len, int flags);
   1429 extern int ssl_SocksRead(sslSocket *ss, unsigned char *buf, int len);
   1430 extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len);
   1431 
   1432 /* Implementation of ops for secure only case */
   1433 extern int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *addr);
   1434 extern PRFileDesc *ssl_SecureAccept(sslSocket *ss, PRNetAddr *addr);
   1435 extern int ssl_SecureRecv(sslSocket *ss, unsigned char *buf,
   1436 			  int len, int flags);
   1437 extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf,
   1438 			  int len, int flags);
   1439 extern int ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len);
   1440 extern int ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len);
   1441 extern int ssl_SecureShutdown(sslSocket *ss, int how);
   1442 extern int ssl_SecureClose(sslSocket *ss);
   1443 
   1444 /* Implementation of ops for secure socks case */
   1445 extern int ssl_SecureSocksConnect(sslSocket *ss, const PRNetAddr *addr);
   1446 extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr);
   1447 extern PRFileDesc *ssl_FindTop(sslSocket *ss);
   1448 
   1449 /* Gather funcs. */
   1450 extern sslGather * ssl_NewGather(void);
   1451 extern SECStatus   ssl_InitGather(sslGather *gs);
   1452 extern void        ssl_DestroyGather(sslGather *gs);
   1453 extern int         ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags);
   1454 extern int         ssl2_GatherRecord(sslSocket *ss, int flags);
   1455 extern SECStatus   ssl_GatherRecord1stHandshake(sslSocket *ss);
   1456 
   1457 extern SECStatus   ssl2_HandleClientHelloMessage(sslSocket *ss);
   1458 extern SECStatus   ssl2_HandleServerHelloMessage(sslSocket *ss);
   1459 extern int         ssl2_StartGatherBytes(sslSocket *ss, sslGather *gs,
   1460                                          unsigned int count);
   1461 
   1462 extern SECStatus   ssl_CreateSecurityInfo(sslSocket *ss);
   1463 extern SECStatus   ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os);
   1464 extern void        ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset);
   1465 extern void        ssl_DestroySecurityInfo(sslSecurityInfo *sec);
   1466 
   1467 extern void        ssl_PrintBuf(sslSocket *ss, const char *msg, const void *cp, int len);
   1468 extern void        ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len);
   1469 
   1470 extern int         ssl_SendSavedWriteData(sslSocket *ss);
   1471 extern SECStatus ssl_SaveWriteData(sslSocket *ss,
   1472                                    const void* p, unsigned int l);
   1473 extern SECStatus ssl2_BeginClientHandshake(sslSocket *ss);
   1474 extern SECStatus ssl2_BeginServerHandshake(sslSocket *ss);
   1475 extern int       ssl_Do1stHandshake(sslSocket *ss);
   1476 
   1477 extern SECStatus sslBuffer_Grow(sslBuffer *b, unsigned int newLen);
   1478 extern SECStatus sslBuffer_Append(sslBuffer *b, const void * data,
   1479 		                  unsigned int len);
   1480 
   1481 extern void      ssl2_UseClearSendFunc(sslSocket *ss);
   1482 extern void      ssl_ChooseSessionIDProcs(sslSecurityInfo *sec);
   1483 
   1484 extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server);
   1485 extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port,
   1486                                    const char *peerID, const char *urlSvrName);
   1487 extern void      ssl_FreeSID(sslSessionID *sid);
   1488 
   1489 extern int       ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in,
   1490 				          int len, int flags);
   1491 
   1492 extern PRBool    ssl_FdIsBlocking(PRFileDesc *fd);
   1493 
   1494 extern PRBool    ssl_SocketIsBlocking(sslSocket *ss);
   1495 
   1496 extern void      ssl3_SetAlwaysBlock(sslSocket *ss);
   1497 
   1498 extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled);
   1499 
   1500 extern void      ssl_FinishHandshake(sslSocket *ss);
   1501 
   1502 /* Returns PR_TRUE if we are still waiting for the server to respond to our
   1503  * client second round. Once we've received any part of the server's second
   1504  * round then we don't bother trying to false start since it is almost always
   1505  * the case that the NewSessionTicket, ChangeCipherSoec, and Finished messages
   1506  * were sent in the same packet and we want to process them all at the same
   1507  * time. If we were to try to false start in the middle of the server's second
   1508  * round, then we would increase the number of I/O operations
   1509  * (SSL_ForceHandshake/PR_Recv/PR_Send/etc.) needed to finish the handshake.
   1510  */
   1511 extern PRBool    ssl3_WaitingForStartOfServerSecondRound(sslSocket *ss);
   1512 
   1513 extern SECStatus
   1514 ssl3_CompressMACEncryptRecord(ssl3CipherSpec *   cwSpec,
   1515 		              PRBool             isServer,
   1516 			      PRBool             isDTLS,
   1517 			      PRBool             capRecordVersion,
   1518                               SSL3ContentType    type,
   1519 		              const SSL3Opaque * pIn,
   1520 		              PRUint32           contentLen,
   1521 		              sslBuffer *        wrBuf);
   1522 extern PRInt32   ssl3_SendRecord(sslSocket *ss, DTLSEpoch epoch,
   1523 				 SSL3ContentType type,
   1524                                  const SSL3Opaque* pIn, PRInt32 nIn,
   1525                                  PRInt32 flags);
   1526 
   1527 #ifdef NSS_ENABLE_ZLIB
   1528 /*
   1529  * The DEFLATE algorithm can result in an expansion of 0.1% + 12 bytes. For a
   1530  * maximum TLS record payload of 2**14 bytes, that's 29 bytes.
   1531  */
   1532 #define SSL3_COMPRESSION_MAX_EXPANSION 29
   1533 #else  /* !NSS_ENABLE_ZLIB */
   1534 #define SSL3_COMPRESSION_MAX_EXPANSION 0
   1535 #endif
   1536 
   1537 /*
   1538  * make sure there is room in the write buffer for padding and
   1539  * other compression and cryptographic expansions.
   1540  */
   1541 #define SSL3_BUFFER_FUDGE     100 + SSL3_COMPRESSION_MAX_EXPANSION
   1542 
   1543 #define SSL_LOCK_READER(ss)		if (ss->recvLock) PZ_Lock(ss->recvLock)
   1544 #define SSL_UNLOCK_READER(ss)		if (ss->recvLock) PZ_Unlock(ss->recvLock)
   1545 #define SSL_LOCK_WRITER(ss)		if (ss->sendLock) PZ_Lock(ss->sendLock)
   1546 #define SSL_UNLOCK_WRITER(ss)		if (ss->sendLock) PZ_Unlock(ss->sendLock)
   1547 
   1548 /* firstHandshakeLock -> recvBufLock */
   1549 #define ssl_Get1stHandshakeLock(ss)     \
   1550     { if (!ss->opt.noLocks) { \
   1551 	  PORT_Assert(PZ_InMonitor((ss)->firstHandshakeLock) || \
   1552 		      !ssl_HaveRecvBufLock(ss)); \
   1553 	  PZ_EnterMonitor((ss)->firstHandshakeLock); \
   1554       } }
   1555 #define ssl_Release1stHandshakeLock(ss) \
   1556     { if (!ss->opt.noLocks) PZ_ExitMonitor((ss)->firstHandshakeLock); }
   1557 #define ssl_Have1stHandshakeLock(ss)    \
   1558     (PZ_InMonitor((ss)->firstHandshakeLock))
   1559 
   1560 /* ssl3HandshakeLock -> xmitBufLock */
   1561 #define ssl_GetSSL3HandshakeLock(ss)	\
   1562     { if (!ss->opt.noLocks) { \
   1563 	  PORT_Assert(!ssl_HaveXmitBufLock(ss)); \
   1564 	  PZ_EnterMonitor((ss)->ssl3HandshakeLock); \
   1565       } }
   1566 #define ssl_ReleaseSSL3HandshakeLock(ss) \
   1567     { if (!ss->opt.noLocks) PZ_ExitMonitor((ss)->ssl3HandshakeLock); }
   1568 #define ssl_HaveSSL3HandshakeLock(ss)	\
   1569     (PZ_InMonitor((ss)->ssl3HandshakeLock))
   1570 
   1571 #define ssl_GetSpecReadLock(ss)		\
   1572     { if (!ss->opt.noLocks) NSSRWLock_LockRead((ss)->specLock); }
   1573 #define ssl_ReleaseSpecReadLock(ss)	\
   1574     { if (!ss->opt.noLocks) NSSRWLock_UnlockRead((ss)->specLock); }
   1575 /* NSSRWLock_HaveReadLock is not exported so there's no
   1576  * ssl_HaveSpecReadLock macro. */
   1577 
   1578 #define ssl_GetSpecWriteLock(ss)	\
   1579     { if (!ss->opt.noLocks) NSSRWLock_LockWrite((ss)->specLock); }
   1580 #define ssl_ReleaseSpecWriteLock(ss)	\
   1581     { if (!ss->opt.noLocks) NSSRWLock_UnlockWrite((ss)->specLock); }
   1582 #define ssl_HaveSpecWriteLock(ss)	\
   1583     (NSSRWLock_HaveWriteLock((ss)->specLock))
   1584 
   1585 /* recvBufLock -> ssl3HandshakeLock -> xmitBufLock */
   1586 #define ssl_GetRecvBufLock(ss)		\
   1587     { if (!ss->opt.noLocks) { \
   1588 	  PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss)); \
   1589 	  PORT_Assert(!ssl_HaveXmitBufLock(ss)); \
   1590 	  PZ_EnterMonitor((ss)->recvBufLock); \
   1591       } }
   1592 #define ssl_ReleaseRecvBufLock(ss)	\
   1593     { if (!ss->opt.noLocks) PZ_ExitMonitor( (ss)->recvBufLock); }
   1594 #define ssl_HaveRecvBufLock(ss)		\
   1595     (PZ_InMonitor((ss)->recvBufLock))
   1596 
   1597 /* xmitBufLock -> specLock */
   1598 #define ssl_GetXmitBufLock(ss)		\
   1599     { if (!ss->opt.noLocks) PZ_EnterMonitor((ss)->xmitBufLock); }
   1600 #define ssl_ReleaseXmitBufLock(ss)	\
   1601     { if (!ss->opt.noLocks) PZ_ExitMonitor( (ss)->xmitBufLock); }
   1602 #define ssl_HaveXmitBufLock(ss)		\
   1603     (PZ_InMonitor((ss)->xmitBufLock))
   1604 
   1605 /* Placeholder value used in version ranges when SSL 3.0 and all
   1606  * versions of TLS are disabled.
   1607  */
   1608 #define SSL_LIBRARY_VERSION_NONE 0
   1609 
   1610 /* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version
   1611  * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
   1612  * runtime to determine which versions are supported by the version of libssl
   1613  * in use.
   1614  */
   1615 #define SSL_LIBRARY_VERSION_MAX_SUPPORTED SSL_LIBRARY_VERSION_TLS_1_2
   1616 
   1617 /* Rename this macro SSL_ALL_VERSIONS_DISABLED when SSL 2.0 is removed. */
   1618 #define SSL3_ALL_VERSIONS_DISABLED(vrange) \
   1619     ((vrange)->min == SSL_LIBRARY_VERSION_NONE)
   1620 
   1621 extern PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
   1622 				      SSL3ProtocolVersion version);
   1623 
   1624 extern SECStatus ssl3_KeyAndMacDeriveBypass(ssl3CipherSpec * pwSpec,
   1625 		    const unsigned char * cr, const unsigned char * sr,
   1626 		    PRBool isTLS, PRBool isExport);
   1627 extern  SECStatus ssl3_MasterKeyDeriveBypass( ssl3CipherSpec * pwSpec,
   1628 		    const unsigned char * cr, const unsigned char * sr,
   1629 		    const SECItem * pms, PRBool isTLS, PRBool isRSA);
   1630 
   1631 /* These functions are called from secnav, even though they're "private". */
   1632 
   1633 extern int ssl2_SendErrorMessage(struct sslSocketStr *ss, int error);
   1634 extern sslSocket *ssl_FindSocket(PRFileDesc *fd);
   1635 extern void ssl_FreeSocket(struct sslSocketStr *ssl);
   1636 extern SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level,
   1637 				SSL3AlertDescription desc);
   1638 extern SECStatus ssl3_DecodeError(sslSocket *ss);
   1639 
   1640 extern SECStatus ssl3_RestartHandshakeAfterCertReq(sslSocket *    ss,
   1641 					     CERTCertificate *    cert,
   1642 					     SECKEYPrivateKey *   key,
   1643 					     CERTCertificateList *certChain);
   1644 
   1645 extern SECStatus ssl3_RestartHandshakeAfterChannelIDReq(
   1646     sslSocket *ss,
   1647     SECKEYPublicKey *channelIDPub,
   1648     SECKEYPrivateKey *channelID);
   1649 
   1650 extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error);
   1651 
   1652 /*
   1653  * for dealing with SSL 3.0 clients sending SSL 2.0 format hellos
   1654  */
   1655 extern SECStatus ssl3_HandleV2ClientHello(
   1656     sslSocket *ss, unsigned char *buffer, int length);
   1657 extern SECStatus ssl3_StartHandshakeHash(
   1658     sslSocket *ss, unsigned char *buf, int length);
   1659 
   1660 /*
   1661  * SSL3 specific routines
   1662  */
   1663 SECStatus ssl3_SendClientHello(sslSocket *ss, PRBool resending);
   1664 
   1665 /*
   1666  * input into the SSL3 machinery from the actualy network reading code
   1667  */
   1668 SECStatus ssl3_HandleRecord(
   1669     sslSocket *ss, SSL3Ciphertext *cipher, sslBuffer *out);
   1670 
   1671 int ssl3_GatherAppDataRecord(sslSocket *ss, int flags);
   1672 int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags);
   1673 /*
   1674  * When talking to export clients or using export cipher suites, servers
   1675  * with public RSA keys larger than 512 bits need to use a 512-bit public
   1676  * key, signed by the larger key.  The smaller key is a "step down" key.
   1677  * Generate that key pair and keep it around.
   1678  */
   1679 extern SECStatus ssl3_CreateRSAStepDownKeys(sslSocket *ss);
   1680 
   1681 #ifdef NSS_ENABLE_ECC
   1682 extern void      ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss);
   1683 extern PRBool    ssl3_IsECCEnabled(sslSocket *ss);
   1684 extern SECStatus ssl3_DisableECCSuites(sslSocket * ss,
   1685                                        const ssl3CipherSuite * suite);
   1686 extern PRUint32  ssl3_GetSupportedECCurveMask(sslSocket *ss);
   1687 
   1688 
   1689 /* Macro for finding a curve equivalent in strength to RSA key's */
   1690 #define SSL_RSASTRENGTH_TO_ECSTRENGTH(s) \
   1691         ((s <= 1024) ? 160 \
   1692 	  : ((s <= 2048) ? 224 \
   1693 	    : ((s <= 3072) ? 256 \
   1694 	      : ((s <= 7168) ? 384 : 521 ) ) ) )
   1695 
   1696 /* Types and names of elliptic curves used in TLS */
   1697 typedef enum { ec_type_explicitPrime      = 1,
   1698 	       ec_type_explicitChar2Curve = 2,
   1699 	       ec_type_named
   1700 } ECType;
   1701 
   1702 typedef enum { ec_noName     = 0,
   1703 	       ec_sect163k1  = 1,
   1704 	       ec_sect163r1  = 2,
   1705 	       ec_sect163r2  = 3,
   1706 	       ec_sect193r1  = 4,
   1707 	       ec_sect193r2  = 5,
   1708 	       ec_sect233k1  = 6,
   1709 	       ec_sect233r1  = 7,
   1710 	       ec_sect239k1  = 8,
   1711 	       ec_sect283k1  = 9,
   1712 	       ec_sect283r1  = 10,
   1713 	       ec_sect409k1  = 11,
   1714 	       ec_sect409r1  = 12,
   1715 	       ec_sect571k1  = 13,
   1716 	       ec_sect571r1  = 14,
   1717 	       ec_secp160k1  = 15,
   1718 	       ec_secp160r1  = 16,
   1719 	       ec_secp160r2  = 17,
   1720 	       ec_secp192k1  = 18,
   1721 	       ec_secp192r1  = 19,
   1722 	       ec_secp224k1  = 20,
   1723 	       ec_secp224r1  = 21,
   1724 	       ec_secp256k1  = 22,
   1725 	       ec_secp256r1  = 23,
   1726 	       ec_secp384r1  = 24,
   1727 	       ec_secp521r1  = 25,
   1728 	       ec_pastLastName
   1729 } ECName;
   1730 
   1731 extern SECStatus ssl3_ECName2Params(PLArenaPool *arena, ECName curve,
   1732 				   SECKEYECParams *params);
   1733 ECName	ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits);
   1734 
   1735 
   1736 #endif /* NSS_ENABLE_ECC */
   1737 
   1738 extern SECStatus ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool on);
   1739 extern SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *on);
   1740 extern SECStatus ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled);
   1741 extern SECStatus ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled);
   1742 
   1743 extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on);
   1744 extern SECStatus ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *on);
   1745 extern SECStatus ssl2_CipherPrefSet(sslSocket *ss, PRInt32 which, PRBool enabled);
   1746 extern SECStatus ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled);
   1747 extern SECStatus ssl3_CipherOrderSet(sslSocket *ss, const ssl3CipherSuite *cipher,
   1748 				     unsigned int len);
   1749 
   1750 extern SECStatus ssl3_SetPolicy(ssl3CipherSuite which, PRInt32 policy);
   1751 extern SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *policy);
   1752 extern SECStatus ssl2_SetPolicy(PRInt32 which, PRInt32 policy);
   1753 extern SECStatus ssl2_GetPolicy(PRInt32 which, PRInt32 *policy);
   1754 
   1755 extern void      ssl2_InitSocketPolicy(sslSocket *ss);
   1756 extern void      ssl3_InitSocketPolicy(sslSocket *ss);
   1757 
   1758 extern SECStatus ssl3_ConstructV2CipherSpecsHack(sslSocket *ss,
   1759 						 unsigned char *cs, int *size);
   1760 
   1761 extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache);
   1762 extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, SSL3Opaque *b,
   1763 					     PRUint32 length);
   1764 
   1765 extern void ssl3_DestroySSL3Info(sslSocket *ss);
   1766 
   1767 extern SECStatus ssl3_NegotiateVersion(sslSocket *ss,
   1768 				       SSL3ProtocolVersion peerVersion,
   1769 				       PRBool allowLargerPeerVersion);
   1770 
   1771 extern SECStatus ssl_GetPeerInfo(sslSocket *ss);
   1772 
   1773 #ifdef NSS_ENABLE_ECC
   1774 /* ECDH functions */
   1775 extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket * ss,
   1776 			     SECKEYPublicKey * svrPubKey);
   1777 extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss,
   1778 					SSL3Opaque *b, PRUint32 length);
   1779 extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss,
   1780 				     SSL3Opaque *b, PRUint32 length,
   1781                                      SECKEYPublicKey *srvrPubKey,
   1782                                      SECKEYPrivateKey *srvrPrivKey);
   1783 extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss,
   1784 			const SSL3SignatureAndHashAlgorithm *sigAndHash);
   1785 #endif
   1786 
   1787 extern SECStatus ssl3_ComputeCommonKeyHash(SECOidTag hashAlg,
   1788 				PRUint8 * hashBuf,
   1789 				unsigned int bufLen, SSL3Hashes *hashes,
   1790 				PRBool bypassPKCS11);
   1791 extern void ssl3_DestroyCipherSpec(ssl3CipherSpec *spec, PRBool freeSrvName);
   1792 extern SECStatus ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms);
   1793 extern SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src,
   1794 			PRInt32 bytes);
   1795 extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss,
   1796 			SSL3HandshakeType t, PRUint32 length);
   1797 extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num,
   1798 			PRInt32 lenSize);
   1799 extern SECStatus ssl3_AppendHandshakeVariable( sslSocket *ss,
   1800 			const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize);
   1801 extern SECStatus ssl3_AppendSignatureAndHashAlgorithm(sslSocket *ss,
   1802 			const SSL3SignatureAndHashAlgorithm* sigAndHash);
   1803 extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes,
   1804 			SSL3Opaque **b, PRUint32 *length);
   1805 extern PRInt32   ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes,
   1806 			SSL3Opaque **b, PRUint32 *length);
   1807 extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i,
   1808 			PRInt32 bytes, SSL3Opaque **b, PRUint32 *length);
   1809 extern SECOidTag ssl3_TLSHashAlgorithmToOID(int hashFunc);
   1810 extern SECStatus ssl3_CheckSignatureAndHashAlgorithmConsistency(
   1811 			const SSL3SignatureAndHashAlgorithm *sigAndHash,
   1812 			CERTCertificate* cert);
   1813 extern SECStatus ssl3_ConsumeSignatureAndHashAlgorithm(sslSocket *ss,
   1814 			SSL3Opaque **b, PRUint32 *length,
   1815 			SSL3SignatureAndHashAlgorithm *out);
   1816 extern SECStatus ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key,
   1817 			SECItem *buf, PRBool isTLS);
   1818 extern SECStatus ssl3_VerifySignedHashes(SSL3Hashes *hash,
   1819 			CERTCertificate *cert, SECItem *buf, PRBool isTLS,
   1820 			void *pwArg);
   1821 extern SECStatus ssl3_CacheWrappedMasterSecret(sslSocket *ss,
   1822 			sslSessionID *sid, ssl3CipherSpec *spec,
   1823 			SSL3KEAType effectiveExchKeyType);
   1824 
   1825 /* Functions that handle ClientHello and ServerHello extensions. */
   1826 extern SECStatus ssl3_HandleServerNameXtn(sslSocket * ss,
   1827 			PRUint16 ex_type, SECItem *data);
   1828 extern SECStatus ssl3_HandleSupportedCurvesXtn(sslSocket * ss,
   1829 			PRUint16 ex_type, SECItem *data);
   1830 extern SECStatus ssl3_HandleSupportedPointFormatsXtn(sslSocket * ss,
   1831 			PRUint16 ex_type, SECItem *data);
   1832 extern SECStatus ssl3_ClientHandleSessionTicketXtn(sslSocket *ss,
   1833 			PRUint16 ex_type, SECItem *data);
   1834 extern SECStatus ssl3_ServerHandleSessionTicketXtn(sslSocket *ss,
   1835 			PRUint16 ex_type, SECItem *data);
   1836 
   1837 /* ClientHello and ServerHello extension senders.
   1838  * Note that not all extension senders are exposed here; only those that
   1839  * that need exposure.
   1840  */
   1841 extern PRInt32 ssl3_SendSessionTicketXtn(sslSocket *ss, PRBool append,
   1842 			PRUint32 maxBytes);
   1843 
   1844 /* ClientHello and ServerHello extension senders.
   1845  * The code is in ssl3ext.c.
   1846  */
   1847 extern PRInt32 ssl3_SendServerNameXtn(sslSocket *ss, PRBool append,
   1848                      PRUint32 maxBytes);
   1849 
   1850 /* Assigns new cert, cert chain and keys to ss->serverCerts
   1851  * struct. If certChain is NULL, tries to find one. Aborts if
   1852  * fails to do so. If cert and keyPair are NULL - unconfigures
   1853  * sslSocket of kea type.*/
   1854 extern SECStatus ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert,
   1855                                         const CERTCertificateList *certChain,
   1856                                         ssl3KeyPair *keyPair, SSLKEAType kea);
   1857 
   1858 #ifdef NSS_ENABLE_ECC
   1859 extern PRInt32 ssl3_SendSupportedCurvesXtn(sslSocket *ss,
   1860 			PRBool append, PRUint32 maxBytes);
   1861 extern PRInt32 ssl3_SendSupportedPointFormatsXtn(sslSocket *ss,
   1862 			PRBool append, PRUint32 maxBytes);
   1863 #endif
   1864 
   1865 /* call the registered extension handlers. */
   1866 extern SECStatus ssl3_HandleHelloExtensions(sslSocket *ss,
   1867 			SSL3Opaque **b, PRUint32 *length);
   1868 
   1869 /* Hello Extension related routines. */
   1870 extern PRBool ssl3_ExtensionNegotiated(sslSocket *ss, PRUint16 ex_type);
   1871 extern void ssl3_SetSIDSessionTicket(sslSessionID *sid,
   1872 			/*in/out*/ NewSessionTicket *session_ticket);
   1873 extern SECStatus ssl3_SendNewSessionTicket(sslSocket *ss);
   1874 extern PRBool ssl_GetSessionTicketKeys(unsigned char *keyName,
   1875 			unsigned char *encKey, unsigned char *macKey);
   1876 extern PRBool ssl_GetSessionTicketKeysPKCS11(SECKEYPrivateKey *svrPrivKey,
   1877 			SECKEYPublicKey *svrPubKey, void *pwArg,
   1878 			unsigned char *keyName, PK11SymKey **aesKey,
   1879 			PK11SymKey **macKey);
   1880 
   1881 /* Tell clients to consider tickets valid for this long. */
   1882 #define TLS_EX_SESS_TICKET_LIFETIME_HINT    (2 * 24 * 60 * 60) /* 2 days */
   1883 #define TLS_EX_SESS_TICKET_VERSION          (0x0100)
   1884 
   1885 extern SECStatus ssl3_ValidateNextProtoNego(const unsigned char* data,
   1886 					    unsigned int length);
   1887 
   1888 extern SECStatus ssl3_GetTLSUniqueChannelBinding(sslSocket *ss,
   1889 						 unsigned char *out,
   1890 						 unsigned int *outLen,
   1891 						 unsigned int outLenMax);
   1892 
   1893 /* Construct a new NSPR socket for the app to use */
   1894 extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
   1895 extern void ssl_FreePRSocket(PRFileDesc *fd);
   1896 
   1897 /* Internal config function so SSL3 can initialize the present state of
   1898  * various ciphers */
   1899 extern int ssl3_config_match_init(sslSocket *);
   1900 
   1901 
   1902 /* Create a new ref counted key pair object from two keys. */
   1903 extern ssl3KeyPair * ssl3_NewKeyPair( SECKEYPrivateKey * privKey,
   1904                                       SECKEYPublicKey * pubKey);
   1905 
   1906 /* get a new reference (bump ref count) to an ssl3KeyPair. */
   1907 extern ssl3KeyPair * ssl3_GetKeyPairRef(ssl3KeyPair * keyPair);
   1908 
   1909 /* Decrement keypair's ref count and free if zero. */
   1910 extern void ssl3_FreeKeyPair(ssl3KeyPair * keyPair);
   1911 
   1912 /* calls for accessing wrapping keys across processes. */
   1913 extern PRBool
   1914 ssl_GetWrappingKey( PRInt32                   symWrapMechIndex,
   1915                     SSL3KEAType               exchKeyType,
   1916 		    SSLWrappedSymWrappingKey *wswk);
   1917 
   1918 /* The caller passes in the new value it wants
   1919  * to set.  This code tests the wrapped sym key entry in the file on disk.
   1920  * If it is uninitialized, this function writes the caller's value into
   1921  * the disk entry, and returns false.
   1922  * Otherwise, it overwrites the caller's wswk with the value obtained from
   1923  * the disk, and returns PR_TRUE.
   1924  * This is all done while holding the locks/semaphores necessary to make
   1925  * the operation atomic.
   1926  */
   1927 extern PRBool
   1928 ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk);
   1929 
   1930 /* get rid of the symmetric wrapping key references. */
   1931 extern SECStatus SSL3_ShutdownServerCache(void);
   1932 
   1933 extern SECStatus ssl_InitSymWrapKeysLock(void);
   1934 
   1935 extern SECStatus ssl_FreeSymWrapKeysLock(void);
   1936 
   1937 extern SECStatus ssl_InitSessionCacheLocks(void);
   1938 
   1939 /***************** platform client auth ****************/
   1940 
   1941 #ifdef NSS_PLATFORM_CLIENT_AUTH
   1942 // Releases the platform key.
   1943 extern void ssl_FreePlatformKey(PlatformKey key);
   1944 
   1945 // Implement the client CertificateVerify message for SSL3/TLS1.0
   1946 extern SECStatus ssl3_PlatformSignHashes(SSL3Hashes *hash,
   1947                                          PlatformKey key, SECItem *buf,
   1948                                          PRBool isTLS, KeyType keyType);
   1949 
   1950 // Converts a CERTCertList* (A collection of CERTCertificates) into a
   1951 // CERTCertificateList* (A collection of SECItems), or returns NULL if
   1952 // it cannot be converted.
   1953 // This is to allow the platform-supplied chain to be created with purely
   1954 // public API functions, using the preferred CERTCertList mutators, rather
   1955 // pushing this hack to clients.
   1956 extern CERTCertificateList* hack_NewCertificateListFromCertList(
   1957         CERTCertList* list);
   1958 #endif  /* NSS_PLATFORM_CLIENT_AUTH */
   1959 
   1960 /**************** DTLS-specific functions **************/
   1961 extern void dtls_FreeQueuedMessage(DTLSQueuedMessage *msg);
   1962 extern void dtls_FreeQueuedMessages(PRCList *lst);
   1963 extern void dtls_FreeHandshakeMessages(PRCList *lst);
   1964 
   1965 extern SECStatus dtls_HandleHandshake(sslSocket *ss, sslBuffer *origBuf);
   1966 extern SECStatus dtls_HandleHelloVerifyRequest(sslSocket *ss,
   1967 					       SSL3Opaque *b, PRUint32 length);
   1968 extern SECStatus dtls_StageHandshakeMessage(sslSocket *ss);
   1969 extern SECStatus dtls_QueueMessage(sslSocket *ss, SSL3ContentType type,
   1970 				   const SSL3Opaque *pIn, PRInt32 nIn);
   1971 extern SECStatus dtls_FlushHandshakeMessages(sslSocket *ss, PRInt32 flags);
   1972 extern SECStatus dtls_CompressMACEncryptRecord(sslSocket *ss,
   1973 					       DTLSEpoch epoch,
   1974 					       PRBool use_epoch,
   1975 					       SSL3ContentType type,
   1976 					       const SSL3Opaque *pIn,
   1977 					       PRUint32 contentLen,
   1978 					       sslBuffer *wrBuf);
   1979 SECStatus ssl3_DisableNonDTLSSuites(sslSocket * ss);
   1980 extern SECStatus dtls_StartTimer(sslSocket *ss, DTLSTimerCb cb);
   1981 extern SECStatus dtls_RestartTimer(sslSocket *ss, PRBool backoff,
   1982 				   DTLSTimerCb cb);
   1983 extern void dtls_CheckTimer(sslSocket *ss);
   1984 extern void dtls_CancelTimer(sslSocket *ss);
   1985 extern void dtls_FinishedTimerCb(sslSocket *ss);
   1986 extern void dtls_SetMTU(sslSocket *ss, PRUint16 advertised);
   1987 extern void dtls_InitRecvdRecords(DTLSRecvdRecords *records);
   1988 extern int dtls_RecordGetRecvd(DTLSRecvdRecords *records, PRUint64 seq);
   1989 extern void dtls_RecordSetRecvd(DTLSRecvdRecords *records, PRUint64 seq);
   1990 extern void dtls_RehandshakeCleanup(sslSocket *ss);
   1991 extern SSL3ProtocolVersion
   1992 dtls_TLSVersionToDTLSVersion(SSL3ProtocolVersion tlsv);
   1993 extern SSL3ProtocolVersion
   1994 dtls_DTLSVersionToTLSVersion(SSL3ProtocolVersion dtlsv);
   1995 
   1996 /********************** misc calls *********************/
   1997 
   1998 #ifdef DEBUG
   1999 extern void ssl3_CheckCipherSuiteOrderConsistency();
   2000 #endif
   2001 
   2002 extern int ssl_MapLowLevelError(int hiLevelError);
   2003 
   2004 extern PRUint32 ssl_Time(void);
   2005 
   2006 extern void SSL_AtomicIncrementLong(long * x);
   2007 
   2008 SECStatus SSL_DisableDefaultExportCipherSuites(void);
   2009 SECStatus SSL_DisableExportCipherSuites(PRFileDesc * fd);
   2010 PRBool    SSL_IsExportCipherSuite(PRUint16 cipherSuite);
   2011 
   2012 extern SECStatus
   2013 ssl3_TLSPRFWithMasterSecret(ssl3CipherSpec *spec,
   2014                             const char *label, unsigned int labelLen,
   2015                             const unsigned char *val, unsigned int valLen,
   2016                             unsigned char *out, unsigned int outLen);
   2017 
   2018 #ifdef TRACE
   2019 #define SSL_TRACE(msg) ssl_Trace msg
   2020 #else
   2021 #define SSL_TRACE(msg)
   2022 #endif
   2023 
   2024 void ssl_Trace(const char *format, ...);
   2025 
   2026 SEC_END_PROTOS
   2027 
   2028 #if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
   2029 #define SSL_GETPID getpid
   2030 #elif defined(WIN32)
   2031 extern int __cdecl _getpid(void);
   2032 #define SSL_GETPID _getpid
   2033 #else
   2034 #define SSL_GETPID() 0
   2035 #endif
   2036 
   2037 #endif /* __sslimpl_h_ */
   2038