security/nss/lib/ssl/sslimpl.h

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

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

mercurial