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