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