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