Back to index

lightning-sunbird  0.9+nobinonly
sslimpl.h
Go to the documentation of this file.
00001 /*
00002  * This file is PRIVATE to SSL and should be the first thing included by
00003  * any SSL implementation file.
00004  *
00005  * ***** BEGIN LICENSE BLOCK *****
00006  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00007  *
00008  * The contents of this file are subject to the Mozilla Public License Version
00009  * 1.1 (the "License"); you may not use this file except in compliance with
00010  * the License. You may obtain a copy of the License at
00011  * http://www.mozilla.org/MPL/
00012  *
00013  * Software distributed under the License is distributed on an "AS IS" basis,
00014  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00015  * for the specific language governing rights and limitations under the
00016  * License.
00017  *
00018  * The Original Code is the Netscape security libraries.
00019  *
00020  * The Initial Developer of the Original Code is
00021  * Netscape Communications Corporation.
00022  * Portions created by the Initial Developer are Copyright (C) 1994-2000
00023  * the Initial Developer. All Rights Reserved.
00024  *
00025  * Contributor(s):
00026  *   Dr Stephen Henson <stephen.henson@gemplus.com>
00027  *   Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
00028  *
00029  * Alternatively, the contents of this file may be used under the terms of
00030  * either the GNU General Public License Version 2 or later (the "GPL"), or
00031  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00032  * in which case the provisions of the GPL or the LGPL are applicable instead
00033  * of those above. If you wish to allow use of your version of this file only
00034  * under the terms of either the GPL or the LGPL, and not to allow others to
00035  * use your version of this file under the terms of the MPL, indicate your
00036  * decision by deleting the provisions above and replace them with the notice
00037  * and other provisions required by the GPL or the LGPL. If you do not delete
00038  * the provisions above, a recipient may use your version of this file under
00039  * the terms of any one of the MPL, the GPL or the LGPL.
00040  *
00041  * ***** END LICENSE BLOCK ***** */
00042 /* $Id: sslimpl.h,v 1.42.2.8 2006/07/19 01:42:58 nelson%bolyard.com Exp $ */
00043 
00044 #ifndef __sslimpl_h_
00045 #define __sslimpl_h_
00046 
00047 #ifdef DEBUG
00048 #undef NDEBUG
00049 #else
00050 #undef NDEBUG
00051 #define NDEBUG
00052 #endif
00053 #include "secport.h"
00054 #include "secerr.h"
00055 #include "sslerr.h"
00056 #include "ssl3prot.h"
00057 #include "hasht.h"
00058 #include "nssilock.h"
00059 #include "pkcs11t.h"
00060 #if defined(XP_UNIX) || defined(XP_BEOS)
00061 #include "unistd.h"
00062 #endif
00063 #include "nssrwlk.h"
00064 #include "prthread.h"
00065 
00066 #include "sslt.h" /* for some formerly private types, now public */
00067 
00068 /* to make some of these old enums public without namespace pollution,
00069 ** it was necessary to prepend ssl_ to the names.
00070 ** These #defines preserve compatibility with the old code here in libssl.
00071 */
00072 typedef SSLKEAType      SSL3KEAType;
00073 typedef SSLMACAlgorithm SSL3MACAlgorithm;
00074 typedef SSLSignType     SSL3SignType;
00075 
00076 #define sign_null    ssl_sign_null
00077 #define sign_rsa     ssl_sign_rsa
00078 #define sign_dsa     ssl_sign_dsa
00079 #define sign_ecdsa   ssl_sign_ecdsa
00080 
00081 #define calg_null    ssl_calg_null
00082 #define calg_rc4     ssl_calg_rc4
00083 #define calg_rc2     ssl_calg_rc2
00084 #define calg_des     ssl_calg_des
00085 #define calg_3des    ssl_calg_3des
00086 #define calg_idea    ssl_calg_idea
00087 #define calg_fortezza       ssl_calg_fortezza /* deprecated, must preserve */
00088 #define calg_aes     ssl_calg_aes
00089 
00090 #define mac_null     ssl_mac_null
00091 #define mac_md5      ssl_mac_md5
00092 #define mac_sha      ssl_mac_sha
00093 #define hmac_md5     ssl_hmac_md5
00094 #define hmac_sha     ssl_hmac_sha
00095 
00096 #define SET_ERROR_CODE             /* reminder */
00097 #define SEND_ALERT          /* reminder */
00098 #define TEST_FOR_FAILURE    /* reminder */
00099 #define DEAL_WITH_FAILURE   /* reminder */
00100 
00101 #if defined(DEBUG) || defined(TRACE)
00102 #ifdef __cplusplus
00103 #define Debug 1
00104 #else
00105 extern int Debug;
00106 #endif
00107 #else
00108 #undef Debug
00109 #endif
00110 
00111 #if defined(DEBUG) && !defined(TRACE) && !defined(NISCC_TEST)
00112 #define TRACE
00113 #endif
00114 
00115 #ifdef TRACE
00116 #define SSL_TRC(a,b) if (ssl_trace >= (a)) ssl_Trace b
00117 #define PRINT_BUF(a,b) if (ssl_trace >= (a)) ssl_PrintBuf b
00118 #define DUMP_MSG(a,b) if (ssl_trace >= (a)) ssl_DumpMsg b
00119 #else
00120 #define SSL_TRC(a,b)
00121 #define PRINT_BUF(a,b)
00122 #define DUMP_MSG(a,b)
00123 #endif
00124 
00125 #ifdef DEBUG
00126 #define SSL_DBG(b) if (ssl_debug) ssl_Trace b
00127 #else
00128 #define SSL_DBG(b)
00129 #endif
00130 
00131 #if defined (DEBUG)
00132 #ifdef macintosh
00133 #include "pprthred.h"
00134 #else
00135 #include "private/pprthred.h"      /* for PR_InMonitor() */
00136 #endif
00137 #define ssl_InMonitor(m) PZ_InMonitor(m)
00138 #endif
00139 
00140 #define LSB(x) ((unsigned char) (x & 0xff))
00141 #define MSB(x) ((unsigned char) (((unsigned)(x)) >> 8))
00142 
00143 /************************************************************************/
00144 
00145 typedef enum { SSLAppOpRead = 0,
00146               SSLAppOpWrite,
00147               SSLAppOpRDWR,
00148               SSLAppOpPost,
00149               SSLAppOpHeader
00150 } SSLAppOperation;
00151 
00152 #define SSL_MIN_MASTER_KEY_BYTES   5
00153 #define SSL_MAX_MASTER_KEY_BYTES   64
00154 
00155 #define SSL2_SESSIONID_BYTES              16
00156 #define SSL3_SESSIONID_BYTES              32
00157 
00158 #define SSL_MIN_CHALLENGE_BYTES           16
00159 #define SSL_MAX_CHALLENGE_BYTES           32
00160 #define SSL_CHALLENGE_BYTES        16
00161 
00162 #define SSL_CONNECTIONID_BYTES            16
00163 
00164 #define SSL_MIN_CYPHER_ARG_BYTES   0
00165 #define SSL_MAX_CYPHER_ARG_BYTES   32
00166 
00167 #define SSL_MAX_MAC_BYTES          16
00168 
00169 #define SSL3_RSA_PMS_LENGTH 48
00170 #define SSL3_MASTER_SECRET_LENGTH 48
00171 
00172 /* number of wrap mechanisms potentially used to wrap master secrets. */
00173 #define SSL_NUM_WRAP_MECHS              14
00174 
00175 /* This makes the cert cache entry exactly 4k. */
00176 #define SSL_MAX_CACHED_CERT_LEN           4060
00177 
00178 #define MAX_EXTENSION_SENDERS             3
00179 
00180 #define NUM_MIXERS                      9
00181 
00182 /* Mask of the 25 named curves we support. */
00183 #ifndef NSS_ECC_MORE_THAN_SUITE_B
00184 #define SSL3_SUPPORTED_CURVES_MASK 0x3800000     /* only 3 curves, suite B*/
00185 #else
00186 #define SSL3_SUPPORTED_CURVES_MASK 0x3fffffe
00187 #endif
00188 
00189 #ifndef BPB
00190 #define BPB 8 /* Bits Per Byte */
00191 #endif
00192 
00193 typedef struct sslBufferStr             sslBuffer;
00194 typedef struct sslConnectInfoStr        sslConnectInfo;
00195 typedef struct sslGatherStr             sslGather;
00196 typedef struct sslSecurityInfoStr       sslSecurityInfo;
00197 typedef struct sslSessionIDStr          sslSessionID;
00198 typedef struct sslSocketStr             sslSocket;
00199 typedef struct sslSocketOpsStr          sslSocketOps;
00200 
00201 typedef struct ssl3StateStr             ssl3State;
00202 typedef struct ssl3CertNodeStr          ssl3CertNode;
00203 typedef struct ssl3BulkCipherDefStr     ssl3BulkCipherDef;
00204 typedef struct ssl3MACDefStr            ssl3MACDef;
00205 typedef struct ssl3KeyPairStr             ssl3KeyPair;
00206 
00207 struct ssl3CertNodeStr {
00208     struct ssl3CertNodeStr *next;
00209     CERTCertificate *       cert;
00210 };
00211 
00212 typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss);
00213 
00214 /* This type points to the low layer send func, 
00215 ** e.g. ssl2_SendStream or ssl3_SendPlainText.
00216 ** These functions return the same values as PR_Send, 
00217 ** i.e.  >= 0 means number of bytes sent, < 0 means error.
00218 */
00219 typedef PRInt32       (*sslSendFunc)(sslSocket *ss, const unsigned char *buf,
00220                                   PRInt32 n, PRInt32 flags);
00221 
00222 typedef void          (*sslSessionIDCacheFunc)  (sslSessionID *sid);
00223 typedef void          (*sslSessionIDUncacheFunc)(sslSessionID *sid);
00224 typedef sslSessionID *(*sslSessionIDLookupFunc)(const PRIPv6Addr    *addr,
00225                                           unsigned char* sid,
00226                                           unsigned int   sidLen,
00227                                                 CERTCertDBHandle * dbHandle);
00228 
00229 /* registerable callback function that either appends extension to buffer
00230  * or returns length of data that it would have appended.
00231  */
00232 typedef PRInt32 (*ssl3HelloExtensionSenderFunc)(sslSocket *ss, PRBool append,
00233                                           PRUint32 maxBytes);
00234 
00235 /* registerable callback function that handles a received extension, 
00236  * of the given type.
00237  */
00238 typedef SECStatus (* ssl3HelloExtensionHandlerFunc)(sslSocket *ss,
00239                                               PRUint16   ex_type,
00240                                                     SECItem *  data);
00241 
00242 /* row in a table of hello extension senders */
00243 typedef struct {
00244     PRInt32                      ex_type;
00245     ssl3HelloExtensionSenderFunc ex_sender;
00246 } ssl3HelloExtensionSender;
00247 
00248 /* row in a table of hello extension handlers */
00249 typedef struct {
00250     PRInt32                       ex_type;
00251     ssl3HelloExtensionHandlerFunc ex_handler;
00252 } ssl3HelloExtensionHandler;
00253 
00254 extern SECStatus 
00255 ssl3_RegisterServerHelloExtensionSender(sslSocket *ss, PRUint16 ex_type,
00256                                     ssl3HelloExtensionSenderFunc cb);
00257 
00258 extern PRInt32
00259 ssl3_CallHelloExtensionSenders(sslSocket *ss, PRBool append, PRUint32 maxBytes,
00260                                const ssl3HelloExtensionSender *sender);
00261 
00262 /* Socket ops */
00263 struct sslSocketOpsStr {
00264     int         (*connect) (sslSocket *, const PRNetAddr *);
00265     PRFileDesc *(*accept)  (sslSocket *, PRNetAddr *);
00266     int         (*bind)    (sslSocket *, const PRNetAddr *);
00267     int         (*listen)  (sslSocket *, int);
00268     int         (*shutdown)(sslSocket *, int);
00269     int         (*close)   (sslSocket *);
00270 
00271     int         (*recv)    (sslSocket *, unsigned char *, int, int);
00272 
00273     /* points to the higher-layer send func, e.g. ssl_SecureSend. */
00274     int         (*send)    (sslSocket *, const unsigned char *, int, int);
00275     int         (*read)    (sslSocket *, unsigned char *, int);
00276     int         (*write)   (sslSocket *, const unsigned char *, int);
00277 
00278     int         (*getpeername)(sslSocket *, PRNetAddr *);
00279     int         (*getsockname)(sslSocket *, PRNetAddr *);
00280 };
00281 
00282 /* Flags interpreted by ssl send functions. */
00283 #define ssl_SEND_FLAG_FORCE_INTO_BUFFER   0x40000000
00284 #define ssl_SEND_FLAG_NO_BUFFER           0x20000000
00285 #define ssl_SEND_FLAG_MASK         0x7f000000
00286 
00287 /*
00288 ** A buffer object.
00289 */
00290 struct sslBufferStr {
00291     unsigned char *  buf;
00292     unsigned int     len;
00293     unsigned int     space;
00294 };
00295 
00296 /*
00297 ** SSL3 cipher suite policy and preference struct.
00298 */
00299 typedef struct {
00300 #if !defined(_WIN32)
00301     unsigned int    cipher_suite : 16;
00302     unsigned int    policy       :  8;
00303     unsigned int    enabled      :  1;
00304     unsigned int    isPresent    :  1;
00305 #else
00306     ssl3CipherSuite cipher_suite;
00307     PRUint8         policy;
00308     unsigned char   enabled   : 1;
00309     unsigned char   isPresent : 1;
00310 #endif
00311 } ssl3CipherSuiteCfg;
00312 
00313 #ifdef NSS_ENABLE_ECC
00314 #define ssl_V3_SUITES_IMPLEMENTED 43
00315 #else
00316 #define ssl_V3_SUITES_IMPLEMENTED 23
00317 #endif /* NSS_ENABLE_ECC */
00318 
00319 typedef struct sslOptionsStr {
00320     unsigned int useSecurity              : 1;  /*  1 */
00321     unsigned int useSocks          : 1;  /*  2 */
00322     unsigned int requestCertificate       : 1;  /*  3 */
00323     unsigned int requireCertificate       : 2;  /*  4-5 */
00324     unsigned int handshakeAsClient : 1;  /*  6 */
00325     unsigned int handshakeAsServer : 1;  /*  7 */
00326     unsigned int enableSSL2        : 1;  /*  8 */
00327     unsigned int enableSSL3        : 1;  /*  9 */
00328     unsigned int enableTLS         : 1;  /* 10 */
00329     unsigned int noCache           : 1;  /* 11 */
00330     unsigned int fdx               : 1;  /* 12 */
00331     unsigned int v2CompatibleHello : 1;  /* 13 */
00332     unsigned int detectRollBack    : 1;  /* 14 */
00333     unsigned int noStepDown             : 1;  /* 15 */
00334     unsigned int bypassPKCS11           : 1;  /* 16 */
00335     unsigned int noLocks                : 1;  /* 17 */
00336 } sslOptions;
00337 
00338 typedef enum { sslHandshakingUndetermined = 0,
00339               sslHandshakingAsClient,
00340               sslHandshakingAsServer 
00341 } sslHandshakingType;
00342 
00343 typedef struct sslServerCertsStr {
00344     /* Configuration state for server sockets */
00345     CERTCertificate *     serverCert;
00346     CERTCertificateList * serverCertChain;
00347     ssl3KeyPair *         serverKeyPair;
00348     unsigned int          serverKeyBits;
00349 } sslServerCerts;
00350 
00351 #define SERVERKEY serverKeyPair->privKey
00352 
00353 #define SSL_LOCK_RANK_SPEC  255
00354 #define SSL_LOCK_RANK_GLOBAL       NSS_RWLOCK_RANK_NONE
00355 
00356 /* These are the valid values for shutdownHow. 
00357 ** These values are each 1 greater than the NSPR values, and the code
00358 ** depends on that relation to efficiently convert PR_SHUTDOWN values 
00359 ** into ssl_SHUTDOWN values.  These values use one bit for read, and 
00360 ** another bit for write, and can be used as bitmasks.
00361 */
00362 #define ssl_SHUTDOWN_NONE   0      /* NOT shutdown at all */
00363 #define ssl_SHUTDOWN_RCV    1      /* PR_SHUTDOWN_RCV  +1 */
00364 #define ssl_SHUTDOWN_SEND   2      /* PR_SHUTDOWN_SEND +1 */
00365 #define ssl_SHUTDOWN_BOTH   3      /* PR_SHUTDOWN_BOTH +1 */
00366 
00367 /*
00368 ** A gather object. Used to read some data until a count has been
00369 ** satisfied. Primarily for support of async sockets.
00370 ** Everything in here is protected by the recvBufLock.
00371 */
00372 struct sslGatherStr {
00373     int           state;    /* see GS_ values below. */     /* ssl 2 & 3 */
00374 
00375     /* "buf" holds received plaintext SSL records, after decrypt and MAC check.
00376      * SSL2: recv'd ciphertext records are put here, then decrypted in place.
00377      * SSL3: recv'd ciphertext records are put in inbuf (see below), then 
00378      *       decrypted into buf.
00379      */
00380     sslBuffer     buf;                           /*recvBufLock*/      /* ssl 2 & 3 */
00381 
00382     /* number of bytes previously read into hdr or buf(ssl2) or inbuf (ssl3). 
00383     ** (offset - writeOffset) is the number of ciphertext bytes read in but 
00384     **     not yet deciphered.
00385     */
00386     unsigned int  offset;                                       /* ssl 2 & 3 */
00387 
00388     /* number of bytes to read in next call to ssl_DefRecv (recv) */
00389     unsigned int  remainder;                                    /* ssl 2 & 3 */
00390 
00391     /* Number of ciphertext bytes to read in after 2-byte SSL record header. */
00392     unsigned int  count;                                /* ssl2 only */
00393 
00394     /* size of the final plaintext record. 
00395     ** == count - (recordPadding + MAC size)
00396     */
00397     unsigned int  recordLen;                                   /* ssl2 only */
00398 
00399     /* number of bytes of padding to be removed after decrypting. */
00400     /* This value is taken from the record's hdr[2], which means a too large
00401      * value could crash us.
00402      */
00403     unsigned int  recordPadding;                        /* ssl2 only */
00404 
00405     /* plaintext DATA begins this many bytes into "buf".  */
00406     unsigned int  recordOffset;                                /* ssl2 only */
00407 
00408     int           encrypted;    /* SSL2 session is now encrypted.  ssl2 only */
00409 
00410     /* These next two values are used by SSL2 and SSL3.  
00411     ** DoRecv uses them to extract application data.
00412     ** The difference between writeOffset and readOffset is the amount of 
00413     ** data available to the application.   Note that the actual offset of 
00414     ** the data in "buf" is recordOffset (above), not readOffset.
00415     ** In the current implementation, this is made available before the 
00416     ** MAC is checked!!
00417     */
00418     unsigned int  readOffset;  /* Spot where DATA reader (e.g. application
00419                                ** or handshake code) will read next.
00420                                ** Always zero for SSl3 application data.
00421                             */
00422     /* offset in buf/inbuf/hdr into which new data will be read from socket. */
00423     unsigned int  writeOffset; 
00424 
00425     /* Buffer for ssl3 to read (encrypted) data from the socket */
00426     sslBuffer     inbuf;                  /*recvBufLock*/      /* ssl3 only */
00427 
00428     /* The ssl[23]_GatherData functions read data into this buffer, rather
00429     ** than into buf or inbuf, while in the GS_HEADER state.  
00430     ** The portion of the SSL record header put here always comes off the wire 
00431     ** as plaintext, never ciphertext.
00432     ** For SSL2, the plaintext portion is two bytes long.  For SSl3 it is 5.
00433     */
00434     unsigned char hdr[5];                               /* ssl 2 & 3 */
00435 };
00436 
00437 /* sslGather.state */
00438 #define GS_INIT             0
00439 #define GS_HEADER    1
00440 #define GS_MAC              2
00441 #define GS_DATA             3
00442 #define GS_PAD              4
00443 
00444 typedef SECStatus (*SSLCipher)(void *               context, 
00445                                unsigned char *      out,
00446                             int *                outlen, 
00447                             int                  maxout, 
00448                             const unsigned char *in,
00449                             int                  inlen);
00450 typedef SECStatus (*SSLDestroy)(void *context, PRBool freeit);
00451 
00452 
00453 
00454 /*
00455 ** ssl3State and CipherSpec structs
00456 */
00457 
00458 /* The SSL bulk cipher definition */
00459 typedef enum {
00460     cipher_null,
00461     cipher_rc4, 
00462     cipher_rc4_40,
00463     cipher_rc4_56,
00464     cipher_rc2, 
00465     cipher_rc2_40,
00466     cipher_des, 
00467     cipher_3des, 
00468     cipher_des40,
00469     cipher_idea, 
00470     cipher_aes_128,
00471     cipher_aes_256,
00472     cipher_missing              /* reserved for no such supported cipher */
00473     /* This enum must match ssl3_cipherName[] in ssl3con.c.  */
00474 } SSL3BulkCipher;
00475 
00476 typedef enum { type_stream, type_block } CipherType;
00477 
00478 #define MAX_IV_LENGTH 64
00479 
00480 /*
00481  * Do not depend upon 64 bit arithmetic in the underlying machine. 
00482  */
00483 typedef struct {
00484     uint32         high;
00485     uint32         low;
00486 } SSL3SequenceNumber;
00487 
00488 #define MAX_MAC_CONTEXT_BYTES 400
00489 #define MAX_MAC_CONTEXT_LLONGS (MAX_MAC_CONTEXT_BYTES / 8)
00490 
00491 #define MAX_CIPHER_CONTEXT_BYTES 2080
00492 #define MAX_CIPHER_CONTEXT_LLONGS (MAX_CIPHER_CONTEXT_BYTES / 8)
00493 
00494 typedef struct {
00495     SSL3Opaque        client_write_iv         [24];
00496     SSL3Opaque        server_write_iv         [24];
00497     SSL3Opaque        wrapped_master_secret   [48];
00498     PRUint16          wrapped_master_secret_len;
00499     PRUint8           msIsWrapped;
00500     PRUint8           resumable;
00501 } ssl3SidKeys; /* 100 bytes */
00502 
00503 typedef struct {
00504     PK11SymKey  *write_key;
00505     PK11SymKey  *write_mac_key;
00506     PK11Context *write_mac_context;
00507     SECItem     write_key_item;
00508     SECItem     write_iv_item;
00509     SECItem     write_mac_key_item;
00510     SSL3Opaque  write_iv[MAX_IV_LENGTH];
00511     PRUint64    cipher_context[MAX_CIPHER_CONTEXT_LLONGS];
00512 } ssl3KeyMaterial;
00513 
00514 /*
00515 ** These are the "specs" in the "ssl3" struct.
00516 ** Access to the pointers to these specs, and all the specs' contents
00517 ** (direct and indirect) is protected by the reader/writer lock ss->specLock.
00518 */
00519 typedef struct {
00520     const ssl3BulkCipherDef *cipher_def;
00521     const ssl3MACDef * mac_def;
00522     int                mac_size;
00523     SSLCipher          encode;
00524     SSLCipher          decode;
00525     SSLDestroy         destroy;
00526     void *             encodeContext;
00527     void *             decodeContext;
00528     PRBool             bypassCiphers;     /* did double bypass (at least) */
00529     PK11SymKey *       master_secret;
00530     SSL3SequenceNumber write_seq_num;
00531     SSL3SequenceNumber read_seq_num;
00532     SSL3ProtocolVersion version;
00533     ssl3KeyMaterial    client;
00534     ssl3KeyMaterial    server;
00535     SECItem            msItem;
00536     unsigned char      key_block[NUM_MIXERS * MD5_LENGTH];
00537     unsigned char      raw_master_secret[56];
00538 } ssl3CipherSpec;
00539 
00540 typedef enum {       never_cached, 
00541               in_client_cache, 
00542               in_server_cache, 
00543               invalid_cache        /* no longer in any cache. */
00544 } Cached;
00545 
00546 struct sslSessionIDStr {
00547     sslSessionID *        next;   /* chain used for client sockets, only */
00548 
00549     CERTCertificate *     peerCert;
00550     const char *          peerID;     /* client only */
00551     const char *          urlSvrName; /* client only */
00552     CERTCertificate *     localCert;
00553 
00554     PRIPv6Addr            addr;
00555     PRUint16              port;
00556 
00557     SSL3ProtocolVersion   version;
00558 
00559     PRUint32              creationTime;          /* seconds since Jan 1, 1970 */
00560     PRUint32              lastAccessTime; /* seconds since Jan 1, 1970 */
00561     PRUint32              expirationTime; /* seconds since Jan 1, 1970 */
00562     Cached                cached;
00563     int                   references;
00564 
00565     SSLSignType           authAlgorithm;
00566     PRUint32              authKeyBits;
00567     SSLKEAType            keaType;
00568     PRUint32              keaKeyBits;
00569 
00570     union {
00571        struct {
00572            /* the V2 code depends upon the size of sessionID.  */
00573            unsigned char         sessionID[SSL2_SESSIONID_BYTES];
00574 
00575            /* Stuff used to recreate key and read/write cipher objects */
00576            SECItem               masterKey;        /* never wrapped */
00577            int                   cipherType;
00578            SECItem               cipherArg;
00579            int                   keyBits;
00580            int                   secretKeyBits;
00581        } ssl2;
00582        struct {
00583            /* values that are copied into the server's on-disk SID cache. */
00584            uint8                 sessionIDLength;
00585            SSL3Opaque            sessionID[SSL3_SESSIONID_BYTES];
00586 
00587            ssl3CipherSuite       cipherSuite;
00588            SSL3CompressionMethod compression;
00589            int                   policy;
00590            ssl3SidKeys           keys;
00591            CK_MECHANISM_TYPE     masterWrapMech;
00592                               /* mechanism used to wrap master secret */
00593             SSL3KEAType           exchKeyType;
00594                               /* key type used in exchange algorithm,
00595                                * and to wrap the sym wrapping key. */
00596 #ifdef NSS_ENABLE_ECC
00597            PRUint32              negotiatedECCurves;
00598 #endif /* NSS_ENABLE_ECC */
00599 
00600            /* The following values are NOT restored from the server's on-disk
00601             * session cache, but are restored from the client's cache.
00602             */
00603            PK11SymKey *      clientWriteKey;
00604            PK11SymKey *      serverWriteKey;
00605 
00606            /* The following values pertain to the slot that wrapped the 
00607            ** master secret. (used only in client)
00608            */
00609            SECMODModuleID    masterModuleID;
00610                                 /* what module wrapped the master secret */
00611            CK_SLOT_ID        masterSlotID;
00612            PRUint16        masterWrapIndex;
00613                             /* what's the key index for the wrapping key */
00614            PRUint16          masterWrapSeries;
00615                                /* keep track of the slot series, so we don't 
00616                              * accidently try to use new keys after the 
00617                              * card gets removed and replaced.*/
00618 
00619            /* The following values pertain to the slot that did the signature
00620            ** for client auth.   (used only in client)
00621            */
00622            SECMODModuleID    clAuthModuleID;
00623            CK_SLOT_ID        clAuthSlotID;
00624            PRUint16          clAuthSeries;
00625 
00626             char              masterValid;
00627            char              clAuthValid;
00628 
00629        } ssl3;
00630     } u;
00631 };
00632 
00633 
00634 typedef struct ssl3CipherSuiteDefStr {
00635     ssl3CipherSuite          cipher_suite;
00636     SSL3BulkCipher           bulk_cipher_alg;
00637     SSL3MACAlgorithm         mac_alg;
00638     SSL3KeyExchangeAlgorithm key_exchange_alg;
00639 } ssl3CipherSuiteDef;
00640 
00641 /*
00642 ** There are tables of these, all const.
00643 */
00644 typedef struct {
00645     SSL3KeyExchangeAlgorithm kea;
00646     SSL3KEAType              exchKeyType;
00647     SSL3SignType             signKeyType;
00648     PRBool                   is_limited;
00649     int                      key_size_limit;
00650     PRBool                   tls_keygen;
00651 } ssl3KEADef;
00652 
00653 typedef enum { kg_null, kg_strong, kg_export } SSL3KeyGenMode;
00654 
00655 /*
00656 ** There are tables of these, all const.
00657 */
00658 struct ssl3BulkCipherDefStr {
00659     SSL3BulkCipher  cipher;
00660     SSLCipherAlgorithm calg;
00661     int             key_size;
00662     int             secret_key_size;
00663     CipherType      type;
00664     int             iv_size;
00665     int             block_size;
00666     SSL3KeyGenMode  keygen_mode;
00667 };
00668 
00669 /*
00670 ** There are tables of these, all const.
00671 */
00672 struct ssl3MACDefStr {
00673     SSL3MACAlgorithm mac;
00674     CK_MECHANISM_TYPE mmech;
00675     int              pad_size;
00676     int              mac_size;
00677 };
00678 
00679 typedef enum {
00680     wait_client_hello, 
00681     wait_client_cert, 
00682     wait_client_key,
00683     wait_cert_verify, 
00684     wait_change_cipher, 
00685     wait_finished,
00686     wait_server_hello, 
00687     wait_server_cert, 
00688     wait_server_key,
00689     wait_cert_request, 
00690     wait_hello_done,
00691     idle_handshake
00692 } SSL3WaitState;
00693 
00694 /*
00695 ** This is the "hs" member of the "ssl3" struct.
00696 ** This entire struct is protected by ssl3HandshakeLock
00697 */
00698 typedef struct SSL3HandshakeStateStr {
00699     SSL3Random            server_random;
00700     SSL3Random            client_random;
00701     SSL3WaitState         ws;
00702     PRUint64              md5_cx[MAX_MAC_CONTEXT_LLONGS];
00703     PRUint64              sha_cx[MAX_MAC_CONTEXT_LLONGS];
00704     PK11Context *         md5;            /* handshake running hashes */
00705     PK11Context *         sha;
00706 const ssl3KEADef *        kea_def;
00707     ssl3CipherSuite       cipher_suite;
00708 const ssl3CipherSuiteDef *suite_def;
00709     SSL3CompressionMethod compression;
00710     sslBuffer             msg_body;    /* protected by recvBufLock */
00711                                /* partial handshake message from record layer */
00712     unsigned int          header_bytes; 
00713                                /* number of bytes consumed from handshake */
00714                                /* message for message type and header length */
00715     SSL3HandshakeType     msg_type;
00716     unsigned long         msg_len;
00717     SECItem               ca_list;     /* used only by client */
00718     PRBool                isResuming;  /* are we resuming a session */
00719     PRBool                rehandshake; /* immediately start another handshake 
00720                                         * when this one finishes */
00721     PRBool                usedStepDownKey;  /* we did a server key exchange. */
00722     sslBuffer             msgState;    /* current state for handshake messages*/
00723                                        /* protected by recvBufLock */
00724 #ifdef NSS_ENABLE_ECC
00725     PRUint32              negotiatedECCurves; /* bit mask */
00726 #endif /* NSS_ENABLE_ECC */
00727 } SSL3HandshakeState;
00728 
00729 
00730 
00731 /*
00732 ** This is the "ssl3" struct, as in "ss->ssl3".
00733 ** note:
00734 ** usually,   crSpec == cwSpec and prSpec == pwSpec.  
00735 ** Sometimes, crSpec == pwSpec and prSpec == cwSpec.
00736 ** But there are never more than 2 actual specs.  
00737 ** No spec must ever be modified if either "current" pointer points to it.
00738 */
00739 struct ssl3StateStr {
00740 
00741     /*
00742     ** The following Specs and Spec pointers must be protected using the 
00743     ** Spec Lock.
00744     */
00745     ssl3CipherSpec *     crSpec;   /* current read spec. */
00746     ssl3CipherSpec *     prSpec;   /* pending read spec. */
00747     ssl3CipherSpec *     cwSpec;   /* current write spec. */
00748     ssl3CipherSpec *     pwSpec;   /* pending write spec. */
00749 
00750     CERTCertificate *    clientCertificate;  /* used by client */
00751     SECKEYPrivateKey *   clientPrivateKey;   /* used by client */
00752     CERTCertificateList *clientCertChain;    /* used by client */
00753     PRBool               sendEmptyCert;      /* used by client */
00754 
00755     int                  policy;
00756                      /* This says what cipher suites we can do, and should 
00757                       * be either SSL_ALLOWED or SSL_RESTRICTED 
00758                       */
00759     PRArenaPool *        peerCertArena;  
00760                          /* These are used to keep track of the peer CA */
00761     void *               peerCertChain;     
00762                          /* chain while we are trying to validate it.   */
00763     CERTDistNames *      ca_list; 
00764                          /* used by server.  trusted CAs for this socket. */
00765     PRBool               initialized;
00766     SSL3HandshakeState   hs;
00767     ssl3CipherSpec       specs[2]; /* one is current, one is pending. */
00768 };
00769 
00770 typedef struct {
00771     SSL3ContentType      type;
00772     SSL3ProtocolVersion  version;
00773     sslBuffer *          buf;
00774 } SSL3Ciphertext;
00775 
00776 struct ssl3KeyPairStr {
00777     SECKEYPrivateKey *    privKey;
00778     SECKEYPublicKey *     pubKey;
00779     PRInt32               refCount;       /* use PR_Atomic calls for this. */
00780 };
00781 
00782 typedef struct SSLWrappedSymWrappingKeyStr {
00783     SSL3Opaque        wrappedSymmetricWrappingkey[512];
00784     SSL3Opaque        wrapIV[24];
00785     CK_MECHANISM_TYPE symWrapMechanism;  
00786                   /* unwrapped symmetric wrapping key uses this mechanism */
00787     CK_MECHANISM_TYPE asymWrapMechanism; 
00788                   /* mechanism used to wrap the SymmetricWrappingKey using
00789                    * server's public and/or private keys. */
00790     SSL3KEAType       exchKeyType;   /* type of keys used to wrap SymWrapKey*/
00791     PRInt32           symWrapMechIndex;
00792     PRUint16          wrappedSymKeyLen;
00793     PRUint16          wrapIVLen;
00794 } SSLWrappedSymWrappingKey;
00795 
00796 
00797 
00798 
00799 
00800 
00801 
00802 
00803 
00804 
00805 /*
00806  * SSL2 buffers used in SSL3.
00807  *     writeBuf in the SecurityInfo maintained by sslsecur.c is used
00808  *              to hold the data just about to be passed to the kernel
00809  *     sendBuf in the ConnectInfo maintained by sslcon.c is used
00810  *              to hold handshake messages as they are accumulated
00811  */
00812 
00813 /*
00814 ** This is "ci", as in "ss->sec.ci".
00815 **
00816 ** Protection:  All the variables in here are protected by 
00817 ** firstHandshakeLock AND (in ssl3) ssl3HandshakeLock 
00818 */
00819 struct sslConnectInfoStr {
00820     /* outgoing handshakes appended to this. */
00821     sslBuffer       sendBuf;                       /*xmitBufLock*/ /* ssl 2 & 3 */
00822 
00823     PRIPv6Addr      peer;                                       /* ssl 2 & 3 */
00824     unsigned short  port;                                       /* ssl 2 & 3 */
00825 
00826     sslSessionID   *sid;                                        /* ssl 2 & 3 */
00827 
00828     /* see CIS_HAVE defines below for the bit values in *elements. */
00829     char            elements;                                  /* ssl2 only */
00830     char            requiredElements;                          /* ssl2 only */
00831     char            sentElements;                               /* ssl2 only */
00832 
00833     char            sentFinished;                               /* ssl2 only */
00834 
00835     /* Length of server challenge.  Used by client when saving challenge */
00836     int             serverChallengeLen;                         /* ssl2 only */
00837     /* type of authentication requested by server */
00838     unsigned char   authType;                                   /* ssl2 only */
00839 
00840     /* Challenge sent by client to server in client-hello message */
00841     /* SSL3 gets a copy of this.  See ssl3_StartHandshakeHash().  */
00842     unsigned char   clientChallenge[SSL_MAX_CHALLENGE_BYTES];   /* ssl 2 & 3 */
00843 
00844     /* Connection-id sent by server to client in server-hello message */
00845     unsigned char   connectionID[SSL_CONNECTIONID_BYTES];      /* ssl2 only */
00846 
00847     /* Challenge sent by server to client in request-certificate message */
00848     unsigned char   serverChallenge[SSL_MAX_CHALLENGE_BYTES];  /* ssl2 only */
00849 
00850     /* Information kept to handle a request-certificate message */
00851     unsigned char   readKey[SSL_MAX_MASTER_KEY_BYTES];         /* ssl2 only */
00852     unsigned char   writeKey[SSL_MAX_MASTER_KEY_BYTES];        /* ssl2 only */
00853     unsigned        keySize;                                   /* ssl2 only */
00854 };
00855 
00856 /* bit values for ci->elements, ci->requiredElements, sentElements. */
00857 #define CIS_HAVE_MASTER_KEY        0x01
00858 #define CIS_HAVE_CERTIFICATE              0x02
00859 #define CIS_HAVE_FINISHED          0x04
00860 #define CIS_HAVE_VERIFY                   0x08
00861 
00862 /* Note: The entire content of this struct and whatever it points to gets
00863  * blown away by SSL_ResetHandshake().  This is "sec" as in "ss->sec".
00864  *
00865  * Unless otherwise specified below, the contents of this struct are 
00866  * protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock.
00867  */
00868 struct sslSecurityInfoStr {
00869     sslSendFunc      send;                /*xmitBufLock*/      /* ssl 2 & 3 */
00870     int              isServer;                   /* Spec Lock?*/      /* ssl 2 & 3 */
00871     sslBuffer        writeBuf;                   /*xmitBufLock*/      /* ssl 2 & 3 */
00872 
00873     int              cipherType;                        /* ssl 2 & 3 */
00874     int              keyBits;                                  /* ssl 2 & 3 */
00875     int              secretKeyBits;                            /* ssl 2 & 3 */
00876     CERTCertificate *localCert;                                /* ssl 2 & 3 */
00877     CERTCertificate *peerCert;                                 /* ssl 2 & 3 */
00878     SECKEYPublicKey *peerKey;                                  /* ssl3 only */
00879 
00880     SSLSignType      authAlgorithm;
00881     PRUint32         authKeyBits;
00882     SSLKEAType       keaType;
00883     PRUint32         keaKeyBits;
00884 
00885     /*
00886     ** Procs used for SID cache (nonce) management. 
00887     ** Different implementations exist for clients/servers 
00888     ** The lookup proc is only used for servers.  Baloney!
00889     */
00890     sslSessionIDCacheFunc     cache;                           /* ssl 2 & 3 */
00891     sslSessionIDUncacheFunc   uncache;                         /* ssl 2 & 3 */
00892 
00893     /*
00894     ** everything below here is for ssl2 only.
00895     ** This stuff is equivalent to SSL3's "spec", and is protected by the 
00896     ** same "Spec Lock" as used for SSL3's specs.
00897     */
00898     uint32           sendSequence;        /*xmitBufLock*/      /* ssl2 only */
00899     uint32           rcvSequence;         /*recvBufLock*/      /* ssl2 only */
00900 
00901     /* Hash information; used for one-way-hash functions (MD2, MD5, etc.) */
00902     const SECHashObject   *hash;          /* Spec Lock */ /* ssl2 only */
00903     void            *hashcx;                     /* Spec Lock */      /* ssl2 only */
00904 
00905     SECItem          sendSecret;          /* Spec Lock */      /* ssl2 only */
00906     SECItem          rcvSecret;                  /* Spec Lock */      /* ssl2 only */
00907 
00908     /* Session cypher contexts; one for each direction */
00909     void            *readcx;                     /* Spec Lock */      /* ssl2 only */
00910     void            *writecx;                    /* Spec Lock */      /* ssl2 only */
00911     SSLCipher        enc;                 /* Spec Lock */      /* ssl2 only */
00912     SSLCipher        dec;                 /* Spec Lock */      /* ssl2 only */
00913     void           (*destroy)(void *, PRBool);   /* Spec Lock */      /* ssl2 only */
00914 
00915     /* Blocking information for the session cypher */
00916     int              blockShift;          /* Spec Lock */      /* ssl2 only */
00917     int              blockSize;                  /* Spec Lock */      /* ssl2 only */
00918 
00919     /* These are used during a connection handshake */
00920     sslConnectInfo   ci;                                /* ssl 2 & 3 */
00921 
00922 };
00923 
00924 
00925 /*
00926 ** SSL Socket struct
00927 **
00928 ** Protection:  XXX
00929 */
00930 struct sslSocketStr {
00931     PRFileDesc *     fd;
00932 
00933     /* Pointer to operations vector for this socket */
00934     const sslSocketOps * ops;
00935 
00936     /* SSL socket options */
00937     sslOptions       opt;
00938 
00939     /* State flags */
00940     unsigned long    clientAuthRequested;
00941     unsigned long    delayDisabled;       /* Nagle delay disabled */
00942     unsigned long    firstHsDone;         /* first handshake is complete. */
00943     unsigned long    handshakeBegun;     
00944     unsigned long    lastWriteBlocked;   
00945     unsigned long    recvdCloseNotify;    /* received SSL EOF. */
00946     unsigned long    TCPconnected;       
00947     unsigned long    appDataBuffered;
00948 
00949     /* version of the protocol to use */
00950     SSL3ProtocolVersion version;
00951     SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. */
00952 
00953     sslSecurityInfo  sec;          /* not a pointer any more */
00954 
00955     /* protected by firstHandshakeLock AND (in ssl3) ssl3HandshakeLock. */
00956     const char      *url;                        /* ssl 2 & 3 */
00957 
00958     sslHandshakeFunc handshake;                         /*firstHandshakeLock*/
00959     sslHandshakeFunc nextHandshake;                     /*firstHandshakeLock*/
00960     sslHandshakeFunc securityHandshake;                 /*firstHandshakeLock*/
00961 
00962     /* registered callbacks that send server hello extensions */
00963     ssl3HelloExtensionSender serverExtensionSenders[MAX_EXTENSION_SENDERS];
00964 
00965     /* the following variable is only used with socks or other proxies. */
00966     char *           peerID;       /* String uniquely identifies target server. */
00967 
00968     unsigned char *  cipherSpecs;
00969     unsigned int     sizeCipherSpecs;
00970 const unsigned char *  preferredCipher;
00971 
00972     ssl3KeyPair *         stepDownKeyPair;       /* RSA step down keys */
00973 
00974     /* Callbacks */
00975     SSLAuthCertificate        authCertificate;
00976     void                     *authCertificateArg;
00977     SSLGetClientAuthData      getClientAuthData;
00978     void                     *getClientAuthDataArg;
00979     SSLBadCertHandler         handleBadCert;
00980     void                     *badCertArg;
00981     SSLHandshakeCallback      handshakeCallback;
00982     void                     *handshakeCallbackData;
00983     void                     *pkcs11PinArg;
00984 
00985     PRIntervalTime            rTimeout; /* timeout for NSPR I/O */
00986     PRIntervalTime            wTimeout; /* timeout for NSPR I/O */
00987     PRIntervalTime            cTimeout; /* timeout for NSPR I/O */
00988 
00989     PZLock *      recvLock; /* lock against multiple reader threads. */
00990     PZLock *      sendLock; /* lock against multiple sender threads. */
00991 
00992     PZMonitor *   recvBufLock;     /* locks low level recv buffers. */
00993     PZMonitor *   xmitBufLock;     /* locks low level xmit buffers. */
00994 
00995     /* Only one thread may operate on the socket until the initial handshake
00996     ** is complete.  This Monitor ensures that.  Since SSL2 handshake is
00997     ** only done once, this is also effectively the SSL2 handshake lock.
00998     */
00999     PZMonitor *   firstHandshakeLock; 
01000 
01001     /* This monitor protects the ssl3 handshake state machine data.
01002     ** Only one thread (reader or writer) may be in the ssl3 handshake state
01003     ** machine at any time.  */
01004     PZMonitor *   ssl3HandshakeLock;
01005 
01006     /* reader/writer lock, protects the secret data needed to encrypt and MAC
01007     ** outgoing records, and to decrypt and MAC check incoming ciphertext 
01008     ** records.  */
01009     NSSRWLock *   specLock;
01010 
01011     /* handle to perm cert db (and implicitly to the temp cert db) used 
01012     ** with this socket. 
01013     */
01014     CERTCertDBHandle * dbHandle;
01015 
01016     PRThread *  writerThread;   /* thread holds SSL_LOCK_WRITER lock */
01017 
01018     PRUint16  shutdownHow;  /* See ssl_SHUTDOWN defines below. */
01019 
01020     PRUint16  allowedByPolicy;          /* copy of global policy bits. */
01021     PRUint16  maybeAllowedByPolicy;     /* copy of global policy bits. */
01022     PRUint16  chosenPreference;         /* SSL2 cipher preferences. */
01023 
01024     sslHandshakingType handshaking;
01025 
01026     /* Gather object used for gathering data */
01027     sslGather        gs;                         /*recvBufLock*/
01028 
01029     sslBuffer        saveBuf;                           /*xmitBufLock*/
01030     sslBuffer        pendingBuf;                 /*xmitBufLock*/
01031 
01032     /* Configuration state for server sockets */
01033     /* server cert and key for each KEA type */
01034     sslServerCerts        serverCerts[kt_kea_size];
01035 
01036     ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED];
01037     ssl3KeyPair *         ephemeralECDHKeyPair; /* for ECDHE-* handshake */
01038 
01039     /* SSL3 state info.  Formerly was a pointer */
01040     ssl3State        ssl3;
01041 };
01042 
01043 
01044 
01045 /* All the global data items declared here should be protected using the 
01046 ** ssl_global_data_lock, which is a reader/writer lock.
01047 */
01048 extern NSSRWLock *             ssl_global_data_lock;
01049 extern char                    ssl_debug;
01050 extern char                    ssl_trace;
01051 extern CERTDistNames *         ssl3_server_ca_list;
01052 extern PRUint32                ssl_sid_timeout;
01053 extern PRUint32                ssl3_sid_timeout;
01054 extern PRBool                  ssl3_global_policy_some_restricted;
01055 
01056 extern const char * const      ssl_cipherName[];
01057 extern const char * const      ssl3_cipherName[];
01058 
01059 extern sslSessionIDLookupFunc  ssl_sid_lookup;
01060 extern sslSessionIDCacheFunc   ssl_sid_cache;
01061 extern sslSessionIDUncacheFunc ssl_sid_uncache;
01062 
01063 /************************************************************************/
01064 
01065 SEC_BEGIN_PROTOS
01066 
01067 /* Implementation of ops for default (non socks, non secure) case */
01068 extern int ssl_DefConnect(sslSocket *ss, const PRNetAddr *addr);
01069 extern PRFileDesc *ssl_DefAccept(sslSocket *ss, PRNetAddr *addr);
01070 extern int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr);
01071 extern int ssl_DefListen(sslSocket *ss, int backlog);
01072 extern int ssl_DefShutdown(sslSocket *ss, int how);
01073 extern int ssl_DefClose(sslSocket *ss);
01074 extern int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
01075 extern int ssl_DefSend(sslSocket *ss, const unsigned char *buf,
01076                      int len, int flags);
01077 extern int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len);
01078 extern int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len);
01079 extern int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name);
01080 extern int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name);
01081 extern int ssl_DefGetsockopt(sslSocket *ss, PRSockOption optname,
01082                           void *optval, PRInt32 *optlen);
01083 extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname,
01084                           const void *optval, PRInt32 optlen);
01085 
01086 /* Implementation of ops for socks only case */
01087 extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr);
01088 extern PRFileDesc *ssl_SocksAccept(sslSocket *ss, PRNetAddr *addr);
01089 extern int ssl_SocksBind(sslSocket *ss, const PRNetAddr *addr);
01090 extern int ssl_SocksListen(sslSocket *ss, int backlog);
01091 extern int ssl_SocksGetsockname(sslSocket *ss, PRNetAddr *name);
01092 extern int ssl_SocksRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
01093 extern int ssl_SocksSend(sslSocket *ss, const unsigned char *buf,
01094                       int len, int flags);
01095 extern int ssl_SocksRead(sslSocket *ss, unsigned char *buf, int len);
01096 extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len);
01097 
01098 /* Implementation of ops for secure only case */
01099 extern int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *addr);
01100 extern PRFileDesc *ssl_SecureAccept(sslSocket *ss, PRNetAddr *addr);
01101 extern int ssl_SecureRecv(sslSocket *ss, unsigned char *buf,
01102                        int len, int flags);
01103 extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf,
01104                        int len, int flags);
01105 extern int ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len);
01106 extern int ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len);
01107 extern int ssl_SecureShutdown(sslSocket *ss, int how);
01108 extern int ssl_SecureClose(sslSocket *ss);
01109 
01110 /* Implementation of ops for secure socks case */
01111 extern int ssl_SecureSocksConnect(sslSocket *ss, const PRNetAddr *addr);
01112 extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr);
01113 extern PRFileDesc *ssl_FindTop(sslSocket *ss);
01114 
01115 /* Gather funcs. */
01116 extern sslGather * ssl_NewGather(void);
01117 extern SECStatus   ssl_InitGather(sslGather *gs);
01118 extern void        ssl_DestroyGather(sslGather *gs);
01119 extern int         ssl2_GatherData(sslSocket *ss, sslGather *gs, int flags);
01120 extern int         ssl2_GatherRecord(sslSocket *ss, int flags);
01121 extern SECStatus   ssl_GatherRecord1stHandshake(sslSocket *ss);
01122 
01123 extern SECStatus   ssl2_HandleClientHelloMessage(sslSocket *ss);
01124 extern SECStatus   ssl2_HandleServerHelloMessage(sslSocket *ss);
01125 extern int         ssl2_StartGatherBytes(sslSocket *ss, sslGather *gs, 
01126                                          unsigned int count);
01127 
01128 extern SECStatus   ssl_CreateSecurityInfo(sslSocket *ss);
01129 extern SECStatus   ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os);
01130 extern void        ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset);
01131 extern void        ssl_DestroySecurityInfo(sslSecurityInfo *sec);
01132 
01133 extern sslSocket * ssl_DupSocket(sslSocket *old);
01134 
01135 extern void        ssl_PrintBuf(sslSocket *ss, const char *msg, const void *cp, int len);
01136 extern void        ssl_DumpMsg(sslSocket *ss, unsigned char *bp, unsigned len);
01137 
01138 extern int         ssl_SendSavedWriteData(sslSocket *ss);
01139 extern SECStatus ssl_SaveWriteData(sslSocket *ss, 
01140                                    const void* p, unsigned int l);
01141 extern SECStatus ssl2_BeginClientHandshake(sslSocket *ss);
01142 extern SECStatus ssl2_BeginServerHandshake(sslSocket *ss);
01143 extern int       ssl_Do1stHandshake(sslSocket *ss);
01144 
01145 extern SECStatus sslBuffer_Grow(sslBuffer *b, unsigned int newLen);
01146 
01147 extern void      ssl2_UseClearSendFunc(sslSocket *ss);
01148 extern void      ssl_ChooseSessionIDProcs(sslSecurityInfo *sec);
01149 
01150 extern sslSessionID *ssl_LookupSID(const PRIPv6Addr *addr, PRUint16 port, 
01151                                    const char *peerID, const char *urlSvrName);
01152 extern void      ssl_FreeSID(sslSessionID *sid);
01153 
01154 extern int       ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in,
01155                                       int len, int flags);
01156 
01157 extern PRBool    ssl_FdIsBlocking(PRFileDesc *fd);
01158 
01159 extern SECStatus ssl_SetTimeout(PRFileDesc *fd, PRIntervalTime timeout);
01160 
01161 extern PRBool    ssl_SocketIsBlocking(sslSocket *ss);
01162 
01163 extern void      ssl_SetAlwaysBlock(sslSocket *ss);
01164 
01165 extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled);
01166 
01167 #define SSL_LOCK_READER(ss)        if (ss->recvLock) PZ_Lock(ss->recvLock)
01168 #define SSL_UNLOCK_READER(ss)             if (ss->recvLock) PZ_Unlock(ss->recvLock)
01169 #define SSL_LOCK_WRITER(ss)        if (ss->sendLock) PZ_Lock(ss->sendLock)
01170 #define SSL_UNLOCK_WRITER(ss)             if (ss->sendLock) PZ_Unlock(ss->sendLock)
01171 
01172 #define ssl_Get1stHandshakeLock(ss)     \
01173     { if (!ss->opt.noLocks) PZ_EnterMonitor((ss)->firstHandshakeLock); }
01174 #define ssl_Release1stHandshakeLock(ss) \
01175     { if (!ss->opt.noLocks) PZ_ExitMonitor((ss)->firstHandshakeLock); }
01176 #define ssl_Have1stHandshakeLock(ss)    \
01177     (PZ_InMonitor((ss)->firstHandshakeLock))
01178 
01179 #define ssl_GetSSL3HandshakeLock(ss)      \
01180     { if (!ss->opt.noLocks) PZ_EnterMonitor((ss)->ssl3HandshakeLock); }
01181 #define ssl_ReleaseSSL3HandshakeLock(ss) \
01182     { if (!ss->opt.noLocks) PZ_ExitMonitor((ss)->ssl3HandshakeLock); }
01183 #define ssl_HaveSSL3HandshakeLock(ss)     \
01184     (PZ_InMonitor((ss)->ssl3HandshakeLock))
01185 
01186 #define ssl_GetSpecReadLock(ss)           \
01187     { if (!ss->opt.noLocks) NSSRWLock_LockRead((ss)->specLock); }
01188 #define ssl_ReleaseSpecReadLock(ss)       \
01189     { if (!ss->opt.noLocks) NSSRWLock_UnlockRead((ss)->specLock); }
01190 
01191 #define ssl_GetSpecWriteLock(ss)   \
01192     { if (!ss->opt.noLocks) NSSRWLock_LockWrite((ss)->specLock); }
01193 #define ssl_ReleaseSpecWriteLock(ss)      \
01194     { if (!ss->opt.noLocks) NSSRWLock_UnlockWrite((ss)->specLock); }
01195 #define ssl_HaveSpecWriteLock(ss)  \
01196     (NSSRWLock_HaveWriteLock((ss)->specLock))
01197 
01198 #define ssl_GetRecvBufLock(ss)            \
01199     { if (!ss->opt.noLocks) PZ_EnterMonitor((ss)->recvBufLock); }
01200 #define ssl_ReleaseRecvBufLock(ss) \
01201     { if (!ss->opt.noLocks) PZ_ExitMonitor( (ss)->recvBufLock); }
01202 #define ssl_HaveRecvBufLock(ss)           \
01203     (PZ_InMonitor((ss)->recvBufLock))
01204 
01205 #define ssl_GetXmitBufLock(ss)            \
01206     { if (!ss->opt.noLocks) PZ_EnterMonitor((ss)->xmitBufLock); }
01207 #define ssl_ReleaseXmitBufLock(ss) \
01208     { if (!ss->opt.noLocks) PZ_ExitMonitor( (ss)->xmitBufLock); }
01209 #define ssl_HaveXmitBufLock(ss)           \
01210     (PZ_InMonitor((ss)->xmitBufLock))
01211 
01212 
01213 extern SECStatus ssl3_KeyAndMacDeriveBypass(ssl3CipherSpec * pwSpec,
01214                   const unsigned char * cr, const unsigned char * sr,
01215                   PRBool isTLS, PRBool isExport);
01216 extern  SECStatus ssl3_MasterKeyDeriveBypass( ssl3CipherSpec * pwSpec,
01217                   const unsigned char * cr, const unsigned char * sr,
01218                   const SECItem * pms, PRBool isTLS, PRBool isRSA);
01219 
01220 /* These functions are called from secnav, even though they're "private". */
01221 
01222 extern int ssl2_SendErrorMessage(struct sslSocketStr *ss, int error);
01223 extern int SSL_RestartHandshakeAfterServerCert(struct sslSocketStr *ss);
01224 extern int SSL_RestartHandshakeAfterCertReq(struct sslSocketStr *ss,
01225                                        CERTCertificate *cert,
01226                                        SECKEYPrivateKey *key,
01227                                        CERTCertificateList *certChain);
01228 extern sslSocket *ssl_FindSocket(PRFileDesc *fd);
01229 extern void ssl_FreeSocket(struct sslSocketStr *ssl);
01230 extern SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level,
01231                             SSL3AlertDescription desc);
01232 
01233 extern int ssl2_RestartHandshakeAfterCertReq(sslSocket *          ss,
01234                                         CERTCertificate *    cert, 
01235                                         SECKEYPrivateKey *   key);
01236 
01237 extern SECStatus ssl3_RestartHandshakeAfterCertReq(sslSocket *    ss,
01238                                         CERTCertificate *    cert, 
01239                                         SECKEYPrivateKey *   key,
01240                                         CERTCertificateList *certChain);
01241 
01242 extern int ssl2_RestartHandshakeAfterServerCert(sslSocket *ss);
01243 extern int ssl3_RestartHandshakeAfterServerCert(sslSocket *ss);
01244 
01245 /*
01246  * for dealing with SSL 3.0 clients sending SSL 2.0 format hellos
01247  */
01248 extern SECStatus ssl3_HandleV2ClientHello(
01249     sslSocket *ss, unsigned char *buffer, int length);
01250 extern SECStatus ssl3_StartHandshakeHash(
01251     sslSocket *ss, unsigned char *buf, int length);
01252 
01253 /*
01254  * SSL3 specific routines
01255  */
01256 SECStatus ssl3_SendClientHello(sslSocket *ss);
01257 
01258 /*
01259  * input into the SSL3 machinery from the actualy network reading code
01260  */
01261 SECStatus ssl3_HandleRecord(
01262     sslSocket *ss, SSL3Ciphertext *cipher, sslBuffer *out);
01263 
01264 int ssl3_GatherAppDataRecord(sslSocket *ss, int flags);
01265 int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags);
01266 /*
01267  * When talking to export clients or using export cipher suites, servers 
01268  * with public RSA keys larger than 512 bits need to use a 512-bit public
01269  * key, signed by the larger key.  The smaller key is a "step down" key.
01270  * Generate that key pair and keep it around.
01271  */
01272 extern SECStatus ssl3_CreateRSAStepDownKeys(sslSocket *ss);
01273 
01274 #ifdef NSS_ENABLE_ECC
01275 extern void      ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss);
01276 extern PRBool    ssl3_IsECCEnabled(sslSocket *ss);
01277 extern SECStatus ssl3_DisableECCSuites(sslSocket * ss, 
01278                                        const ssl3CipherSuite * suite);
01279 #endif /* NSS_ENABLE_ECC */
01280 
01281 extern SECStatus ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool on);
01282 extern SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *on);
01283 extern SECStatus ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled);
01284 extern SECStatus ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled);
01285 
01286 extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on);
01287 extern SECStatus ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *on);
01288 extern SECStatus ssl2_CipherPrefSet(sslSocket *ss, PRInt32 which, PRBool enabled);
01289 extern SECStatus ssl2_CipherPrefGet(sslSocket *ss, PRInt32 which, PRBool *enabled);
01290 
01291 extern SECStatus ssl3_SetPolicy(ssl3CipherSuite which, PRInt32 policy);
01292 extern SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *policy);
01293 extern SECStatus ssl2_SetPolicy(PRInt32 which, PRInt32 policy);
01294 extern SECStatus ssl2_GetPolicy(PRInt32 which, PRInt32 *policy);
01295 
01296 extern void      ssl2_InitSocketPolicy(sslSocket *ss);
01297 extern void      ssl3_InitSocketPolicy(sslSocket *ss);
01298 
01299 extern SECStatus ssl3_ConstructV2CipherSpecsHack(sslSocket *ss,
01300                                            unsigned char *cs, int *size);
01301 
01302 extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache);
01303 
01304 extern void ssl3_DestroySSL3Info(sslSocket *ss);
01305 
01306 extern SECStatus ssl3_NegotiateVersion(sslSocket *ss, 
01307                                        SSL3ProtocolVersion peerVersion);
01308 
01309 extern SECStatus ssl_GetPeerInfo(sslSocket *ss);
01310 
01311 #ifdef NSS_ENABLE_ECC
01312 /* ECDH functions */
01313 extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket * ss, 
01314                           SECKEYPublicKey * svrPubKey);
01315 extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, 
01316                                    SSL3Opaque *b, PRUint32 length);
01317 extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, 
01318                                  SSL3Opaque *b, PRUint32 length,
01319                                      SECKEYPublicKey *srvrPubKey,
01320                                      SECKEYPrivateKey *srvrPrivKey);
01321 extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss);
01322 #endif
01323 
01324 extern SECStatus ssl3_ComputeCommonKeyHash(PRUint8 * hashBuf, 
01325                             unsigned int bufLen, SSL3Hashes *hashes, 
01326                             PRBool bypassPKCS11);
01327 extern SECStatus ssl3_InitPendingCipherSpec(sslSocket *ss, PK11SymKey *pms);
01328 extern SECStatus ssl3_AppendHandshake(sslSocket *ss, const void *void_src, 
01329                      PRInt32 bytes);
01330 extern SECStatus ssl3_AppendHandshakeHeader(sslSocket *ss, 
01331                      SSL3HandshakeType t, PRUint32 length);
01332 extern SECStatus ssl3_AppendHandshakeNumber(sslSocket *ss, PRInt32 num, 
01333                      PRInt32 lenSize);
01334 extern SECStatus ssl3_AppendHandshakeVariable( sslSocket *ss, 
01335                      const SSL3Opaque *src, PRInt32 bytes, PRInt32 lenSize);
01336 extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRInt32 bytes, 
01337                      SSL3Opaque **b, PRUint32 *length);
01338 extern PRInt32   ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRInt32 bytes, 
01339                      SSL3Opaque **b, PRUint32 *length);
01340 extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i, 
01341                      PRInt32 bytes, SSL3Opaque **b, PRUint32 *length);
01342 extern SECStatus ssl3_SignHashes(SSL3Hashes *hash, SECKEYPrivateKey *key, 
01343                      SECItem *buf, PRBool isTLS);
01344 extern SECStatus ssl3_VerifySignedHashes(SSL3Hashes *hash, 
01345                      CERTCertificate *cert, SECItem *buf, PRBool isTLS, 
01346                      void *pwArg);
01347 
01348 /* functions that append extensions to hello messages. */
01349 extern PRInt32   ssl3_SendServerNameIndicationExtension( sslSocket * ss,
01350                      PRBool append, PRUint32 maxBytes);
01351 
01352 /* call the registered extension handlers. */
01353 extern SECStatus ssl3_HandleClientHelloExtensions(sslSocket *ss, 
01354                      SSL3Opaque **b, PRUint32 *length);
01355 
01356 /* Construct a new NSPR socket for the app to use */
01357 extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
01358 extern void ssl_FreePRSocket(PRFileDesc *fd);
01359 
01360 /* Internal config function so SSL2 can initialize the present state of 
01361  * various ciphers */
01362 extern int ssl3_config_match_init(sslSocket *);
01363 
01364 
01365 /* Create a new ref counted key pair object from two keys. */
01366 extern ssl3KeyPair * ssl3_NewKeyPair( SECKEYPrivateKey * privKey, 
01367                                       SECKEYPublicKey * pubKey);
01368 
01369 /* get a new reference (bump ref count) to an ssl3KeyPair. */
01370 extern ssl3KeyPair * ssl3_GetKeyPairRef(ssl3KeyPair * keyPair);
01371 
01372 /* Decrement keypair's ref count and free if zero. */
01373 extern void ssl3_FreeKeyPair(ssl3KeyPair * keyPair);
01374 
01375 /* calls for accessing wrapping keys across processes. */
01376 extern PRBool
01377 ssl_GetWrappingKey( PRInt32                   symWrapMechIndex,
01378                     SSL3KEAType               exchKeyType, 
01379                   SSLWrappedSymWrappingKey *wswk);
01380 
01381 /* The caller passes in the new value it wants
01382  * to set.  This code tests the wrapped sym key entry in the file on disk.  
01383  * If it is uninitialized, this function writes the caller's value into 
01384  * the disk entry, and returns false.  
01385  * Otherwise, it overwrites the caller's wswk with the value obtained from 
01386  * the disk, and returns PR_TRUE.  
01387  * This is all done while holding the locks/semaphores necessary to make 
01388  * the operation atomic.
01389  */
01390 extern PRBool
01391 ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk);
01392 
01393 /* get rid of the symmetric wrapping key references. */
01394 extern SECStatus SSL3_ShutdownServerCache(void);
01395 
01396 extern void ssl_InitClientSessionCacheLock(void);
01397 
01398 extern void ssl_InitSymWrapKeysLock(void);
01399 
01400 /********************** misc calls *********************/
01401 
01402 extern int ssl_MapLowLevelError(int hiLevelError);
01403 
01404 extern PRUint32 ssl_Time(void);
01405 
01406 
01407 SECStatus SSL_DisableDefaultExportCipherSuites(void);
01408 SECStatus SSL_DisableExportCipherSuites(PRFileDesc * fd);
01409 PRBool    SSL_IsExportCipherSuite(PRUint16 cipherSuite);
01410 
01411 
01412 #ifdef TRACE
01413 #define SSL_TRACE(msg) ssl_Trace msg
01414 #else
01415 #define SSL_TRACE(msg)
01416 #endif
01417 
01418 void ssl_Trace(const char *format, ...);
01419 
01420 SEC_END_PROTOS
01421 
01422 #ifdef XP_OS2_VACPP
01423 #include <process.h>
01424 #endif
01425 
01426 #if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
01427 #define SSL_GETPID getpid
01428 #elif defined(_WIN32_WCE)
01429 #define SSL_GETPID GetCurrentProcessId
01430 #elif defined(WIN32)
01431 extern int __cdecl _getpid(void);
01432 #define SSL_GETPID _getpid
01433 #else
01434 #define SSL_GETPID() 0
01435 #endif
01436 
01437 #endif /* __sslimpl_h_ */