1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3  * This file is PRIVATE to SSL and should be the first thing included by
4  * any SSL implementation file.
5  *
6  * This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0. If a copy of the MPL was not distributed with this
8  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 
10 #ifndef __sslimpl_h_
11 #define __sslimpl_h_
12 
13 #ifdef DEBUG
14 #undef NDEBUG
15 #else
16 #undef NDEBUG
17 #define NDEBUG
18 #endif
19 #include "secport.h"
20 #include "secerr.h"
21 #include "sslerr.h"
22 #include "sslexp.h"
23 #include "ssl3prot.h"
24 #include "hasht.h"
25 #include "nssilock.h"
26 #include "pkcs11t.h"
27 #if defined(XP_UNIX) || defined(XP_BEOS)
28 #include "unistd.h"
29 #endif
30 #include "nssrwlk.h"
31 #include "prthread.h"
32 #include "prclist.h"
33 #include "private/pprthred.h"
34 
35 #include "sslt.h" /* for some formerly private types, now public */
36 
37 typedef struct sslSocketStr sslSocket;
38 typedef struct sslNamedGroupDefStr sslNamedGroupDef;
39 typedef struct sslEchConfigStr sslEchConfig;
40 typedef struct sslEchConfigContentsStr sslEchConfigContents;
41 typedef struct sslEchCookieDataStr sslEchCookieData;
42 typedef struct sslEchXtnStateStr sslEchXtnState;
43 typedef struct sslPskStr sslPsk;
44 typedef struct sslDelegatedCredentialStr sslDelegatedCredential;
45 typedef struct sslEphemeralKeyPairStr sslEphemeralKeyPair;
46 typedef struct TLS13KeyShareEntryStr TLS13KeyShareEntry;
47 
48 #include "sslencode.h"
49 #include "sslexp.h"
50 #include "ssl3ext.h"
51 #include "sslspec.h"
52 
53 #if defined(DEBUG) || defined(TRACE)
54 #ifdef __cplusplus
55 #define Debug 1
56 #else
57 extern int Debug;
58 #endif
59 #else
60 #undef Debug
61 #endif
62 
63 #if defined(DEBUG) && !defined(TRACE) && !defined(NISCC_TEST)
64 #define TRACE
65 #endif
66 
67 #ifdef TRACE
68 #define SSL_TRC(a, b)     \
69     if (ssl_trace >= (a)) \
70     ssl_Trace b
71 #define PRINT_BUF(a, b)   \
72     if (ssl_trace >= (a)) \
73     ssl_PrintBuf b
74 #define PRINT_KEY(a, b)   \
75     if (ssl_trace >= (a)) \
76     ssl_PrintKey b
77 #else
78 #define SSL_TRC(a, b)
79 #define PRINT_BUF(a, b)
80 #define PRINT_KEY(a, b)
81 #endif
82 
83 #ifdef DEBUG
84 #define SSL_DBG(b) \
85     if (ssl_debug) \
86     ssl_Trace b
87 #else
88 #define SSL_DBG(b)
89 #endif
90 
91 #define LSB(x) ((unsigned char)((x)&0xff))
92 #define MSB(x) ((unsigned char)(((unsigned)(x)) >> 8))
93 
94 #define CONST_CAST(T, X) ((T *)(X))
95 
96 /************************************************************************/
97 
98 typedef enum { SSLAppOpRead = 0,
99                SSLAppOpWrite,
100                SSLAppOpRDWR,
101                SSLAppOpPost,
102                SSLAppOpHeader
103 } SSLAppOperation;
104 
105 #define SSL3_SESSIONID_BYTES 32
106 
107 #define SSL_MIN_CHALLENGE_BYTES 16
108 #define SSL_MAX_CHALLENGE_BYTES 32
109 
110 #define SSL3_MASTER_SECRET_LENGTH 48
111 
112 /* number of wrap mechanisms potentially used to wrap master secrets. */
113 #define SSL_NUM_WRAP_MECHS 15
114 #define SSL_NUM_WRAP_KEYS 6
115 
116 /* This makes the cert cache entry exactly 4k. */
117 #define SSL_MAX_CACHED_CERT_LEN 4060
118 
119 #ifndef BPB
120 #define BPB 8 /* Bits Per Byte */
121 #endif
122 
123 /* The default value from RFC 4347 is 1s, which is too slow. */
124 #define DTLS_RETRANSMIT_INITIAL_MS 50
125 /* The maximum time to wait between retransmissions. */
126 #define DTLS_RETRANSMIT_MAX_MS 10000
127 /* Time to wait in FINISHED state for retransmissions. */
128 #define DTLS_RETRANSMIT_FINISHED_MS 30000
129 
130 /* default number of entries in namedGroupPreferences */
131 #define SSL_NAMED_GROUP_COUNT 31
132 
133 /* The maximum DH and RSA bit-length supported. */
134 #define SSL_MAX_DH_KEY_BITS 8192
135 #define SSL_MAX_RSA_KEY_BITS 8192
136 
137 /* Types and names of elliptic curves used in TLS */
138 typedef enum {
139     ec_type_explicitPrime = 1,      /* not supported */
140     ec_type_explicitChar2Curve = 2, /* not supported */
141     ec_type_named = 3
142 } ECType;
143 
144 typedef enum {
145     ticket_allow_early_data = 1,
146     ticket_allow_psk_ke = 2,
147     ticket_allow_psk_dhe_ke = 4,
148     ticket_allow_psk_auth = 8,
149     ticket_allow_psk_sign_auth = 16
150 } TLS13SessionTicketFlags;
151 
152 typedef enum {
153     update_not_requested = 0,
154     update_requested = 1
155 } tls13KeyUpdateRequest;
156 
157 struct sslNamedGroupDefStr {
158     /* The name is the value that is encoded on the wire in TLS. */
159     SSLNamedGroup name;
160     /* The number of bits in the group. */
161     unsigned int bits;
162     /* The key exchange algorithm this group provides. */
163     SSLKEAType keaType;
164     /* The OID that identifies the group to PKCS11.  This also determines
165      * whether the group is enabled in policy. */
166     SECOidTag oidTag;
167     /* Assume that the group is always supported. */
168     PRBool assumeSupported;
169 };
170 
171 typedef struct sslConnectInfoStr sslConnectInfo;
172 typedef struct sslGatherStr sslGather;
173 typedef struct sslSecurityInfoStr sslSecurityInfo;
174 typedef struct sslSessionIDStr sslSessionID;
175 typedef struct sslSocketOpsStr sslSocketOps;
176 
177 typedef struct ssl3StateStr ssl3State;
178 typedef struct ssl3CertNodeStr ssl3CertNode;
179 typedef struct sslKeyPairStr sslKeyPair;
180 typedef struct ssl3DHParamsStr ssl3DHParams;
181 
182 struct ssl3CertNodeStr {
183     struct ssl3CertNodeStr *next;
184     CERTCertificate *cert;
185 };
186 
187 typedef SECStatus (*sslHandshakeFunc)(sslSocket *ss);
188 
189 void ssl_CacheSessionID(sslSocket *ss);
190 void ssl_UncacheSessionID(sslSocket *ss);
191 void ssl_ServerCacheSessionID(sslSessionID *sid, PRTime creationTime);
192 void ssl_ServerUncacheSessionID(sslSessionID *sid);
193 
194 typedef sslSessionID *(*sslSessionIDLookupFunc)(PRTime ssl_now,
195                                                 const PRIPv6Addr *addr,
196                                                 unsigned char *sid,
197                                                 unsigned int sidLen,
198                                                 CERTCertDBHandle *dbHandle);
199 
200 /* Socket ops */
201 struct sslSocketOpsStr {
202     int (*connect)(sslSocket *, const PRNetAddr *);
203     PRFileDesc *(*accept)(sslSocket *, PRNetAddr *);
204     int (*bind)(sslSocket *, const PRNetAddr *);
205     int (*listen)(sslSocket *, int);
206     int (*shutdown)(sslSocket *, int);
207     int (*close)(sslSocket *);
208 
209     int (*recv)(sslSocket *, unsigned char *, int, int);
210 
211     /* points to the higher-layer send func, e.g. ssl_SecureSend. */
212     int (*send)(sslSocket *, const unsigned char *, int, int);
213     int (*read)(sslSocket *, unsigned char *, int);
214     int (*write)(sslSocket *, const unsigned char *, int);
215 
216     int (*getpeername)(sslSocket *, PRNetAddr *);
217     int (*getsockname)(sslSocket *, PRNetAddr *);
218 };
219 
220 /* Flags interpreted by ssl send functions. */
221 #define ssl_SEND_FLAG_FORCE_INTO_BUFFER 0x40000000
222 #define ssl_SEND_FLAG_NO_BUFFER 0x20000000
223 #define ssl_SEND_FLAG_NO_RETRANSMIT 0x08000000 /* DTLS only */
224 #define ssl_SEND_FLAG_MASK 0x7f000000
225 
226 /*
227 ** SSL3 cipher suite policy and preference struct.
228 */
229 typedef struct {
230 #if !defined(_WIN32)
231     unsigned int cipher_suite : 16;
232     unsigned int policy : 8;
233     unsigned int enabled : 1;
234     unsigned int isPresent : 1;
235 #else
236     ssl3CipherSuite cipher_suite;
237     PRUint8 policy;
238     unsigned char enabled : 1;
239     unsigned char isPresent : 1;
240 #endif
241 } ssl3CipherSuiteCfg;
242 
243 #define ssl_V3_SUITES_IMPLEMENTED 71
244 
245 #define MAX_DTLS_SRTP_CIPHER_SUITES 4
246 
247 /* MAX_SIGNATURE_SCHEMES allows for all the values we support. */
248 #define MAX_SIGNATURE_SCHEMES 18
249 
250 typedef struct sslOptionsStr {
251     /* If SSL_SetNextProtoNego has been called, then this contains the
252      * list of supported protocols. */
253     SECItem nextProtoNego;
254     PRUint16 recordSizeLimit;
255 
256     PRUint32 maxEarlyDataSize;
257     unsigned int useSecurity : 1;
258     unsigned int useSocks : 1;
259     unsigned int requestCertificate : 1;
260     unsigned int requireCertificate : 2;
261     unsigned int handshakeAsClient : 1;
262     unsigned int handshakeAsServer : 1;
263     unsigned int noCache : 1;
264     unsigned int fdx : 1;
265     unsigned int detectRollBack : 1;
266     unsigned int noLocks : 1;
267     unsigned int enableSessionTickets : 1;
268     unsigned int enableDeflate : 1; /* Deprecated. */
269     unsigned int enableRenegotiation : 2;
270     unsigned int requireSafeNegotiation : 1;
271     unsigned int enableFalseStart : 1;
272     unsigned int cbcRandomIV : 1;
273     unsigned int enableOCSPStapling : 1;
274     unsigned int enableALPN : 1;
275     unsigned int reuseServerECDHEKey : 1;
276     unsigned int enableFallbackSCSV : 1;
277     unsigned int enableServerDhe : 1;
278     unsigned int enableExtendedMS : 1;
279     unsigned int enableSignedCertTimestamps : 1;
280     unsigned int requireDHENamedGroups : 1;
281     unsigned int enable0RttData : 1;
282     unsigned int enableTls13CompatMode : 1;
283     unsigned int enableDtlsShortHeader : 1;
284     unsigned int enableHelloDowngradeCheck : 1;
285     unsigned int enableV2CompatibleHello : 1;
286     unsigned int enablePostHandshakeAuth : 1;
287     unsigned int enableDelegatedCredentials : 1;
288     unsigned int enableDtls13VersionCompat : 1;
289     unsigned int suppressEndOfEarlyData : 1;
290     unsigned int enableTls13GreaseEch : 1;
291     unsigned int enableTls13BackendEch : 1;
292     unsigned int callExtensionWriterOnEchInner : 1;
293 } sslOptions;
294 
295 typedef enum { sslHandshakingUndetermined = 0,
296                sslHandshakingAsClient,
297                sslHandshakingAsServer
298 } sslHandshakingType;
299 
300 #define SSL_LOCK_RANK_SPEC 255
301 
302 /* These are the valid values for shutdownHow.
303 ** These values are each 1 greater than the NSPR values, and the code
304 ** depends on that relation to efficiently convert PR_SHUTDOWN values
305 ** into ssl_SHUTDOWN values.  These values use one bit for read, and
306 ** another bit for write, and can be used as bitmasks.
307 */
308 #define ssl_SHUTDOWN_NONE 0 /* NOT shutdown at all */
309 #define ssl_SHUTDOWN_RCV 1  /* PR_SHUTDOWN_RCV  +1 */
310 #define ssl_SHUTDOWN_SEND 2 /* PR_SHUTDOWN_SEND +1 */
311 #define ssl_SHUTDOWN_BOTH 3 /* PR_SHUTDOWN_BOTH +1 */
312 
313 /*
314 ** A gather object. Used to read some data until a count has been
315 ** satisfied. Primarily for support of async sockets.
316 ** Everything in here is protected by the recvBufLock.
317 */
318 struct sslGatherStr {
319     int state; /* see GS_ values below. */
320 
321     /* "buf" holds received plaintext SSL records, after decrypt and MAC check.
322      * recv'd ciphertext records are put in inbuf (see below), then decrypted
323      * into buf.
324      */
325     sslBuffer buf; /*recvBufLock*/
326 
327     /* number of bytes previously read into hdr or inbuf.
328     ** (offset - writeOffset) is the number of ciphertext bytes read in but
329     **     not yet deciphered.
330     */
331     unsigned int offset;
332 
333     /* number of bytes to read in next call to ssl_DefRecv (recv) */
334     unsigned int remainder;
335 
336     /* DoRecv uses the next two values to extract application data.
337     ** The difference between writeOffset and readOffset is the amount of
338     ** data available to the application.   Note that the actual offset of
339     ** the data in "buf" is recordOffset (above), not readOffset.
340     ** In the current implementation, this is made available before the
341     ** MAC is checked!!
342     */
343     unsigned int readOffset; /* Spot where DATA reader (e.g. application
344                                ** or handshake code) will read next.
345                                ** Always zero for SSl3 application data.
346                                */
347     /* offset in buf/inbuf/hdr into which new data will be read from socket. */
348     unsigned int writeOffset;
349 
350     /* Buffer for ssl3 to read (encrypted) data from the socket */
351     sslBuffer inbuf; /*recvBufLock*/
352 
353     /* The ssl[23]_GatherData functions read data into this buffer, rather
354     ** than into buf or inbuf, while in the GS_HEADER state.
355     ** The portion of the SSL record header put here always comes off the wire
356     ** as plaintext, never ciphertext.
357     ** For SSL3/TLS, the plaintext portion is 5 bytes long. For DTLS it
358     ** varies based on version and header type.
359     */
360     unsigned char hdr[13];
361     unsigned int hdrLen;
362 
363     /* Buffer for DTLS data read off the wire as a single datagram */
364     sslBuffer dtlsPacket;
365 
366     /* the start of the buffered DTLS record in dtlsPacket */
367     unsigned int dtlsPacketOffset;
368 
369     /* tracks whether we've seen a v3-type record before and must reject
370      * any further v2-type records. */
371     PRBool rejectV2Records;
372 };
373 
374 /* sslGather.state */
375 #define GS_INIT 0
376 #define GS_HEADER 1
377 #define GS_DATA 2
378 
379 #define WRAPPED_MASTER_SECRET_SIZE 48
380 
381 typedef struct {
382     PRUint8 wrapped_master_secret[WRAPPED_MASTER_SECRET_SIZE];
383     PRUint8 wrapped_master_secret_len;
384     PRUint8 resumable;
385     PRUint8 extendedMasterSecretUsed;
386 } ssl3SidKeys; /* 52 bytes */
387 
388 typedef enum { never_cached,
389                in_client_cache,
390                in_server_cache,
391                invalid_cache, /* no longer in any cache. */
392                in_external_cache
393 } Cached;
394 
395 #include "sslcert.h"
396 
397 struct sslSessionIDStr {
398     /* The global cache lock must be held when accessing these members when the
399      * sid is in any cache.
400      */
401     sslSessionID *next; /* chain used for client sockets, only */
402     Cached cached;
403     int references;
404     PRTime lastAccessTime;
405 
406     /* The rest of the members, except for the members of u.ssl3.locked, may
407      * be modified only when the sid is not in any cache.
408      */
409 
410     CERTCertificate *peerCert;
411     SECItemArray peerCertStatus;        /* client only */
412     const char *peerID;                 /* client only */
413     const char *urlSvrName;             /* client only */
414     const sslNamedGroupDef *namedCurve; /* (server) for certificate lookup */
415     CERTCertificate *localCert;
416 
417     PRIPv6Addr addr;
418     PRUint16 port;
419 
420     SSL3ProtocolVersion version;
421 
422     PRTime creationTime;
423     PRTime expirationTime;
424 
425     SSLAuthType authType;
426     PRUint32 authKeyBits;
427     SSLKEAType keaType;
428     PRUint32 keaKeyBits;
429     SSLNamedGroup keaGroup;
430     SSLSignatureScheme sigScheme;
431 
432     union {
433         struct {
434             /* values that are copied into the server's on-disk SID cache. */
435             PRUint8 sessionIDLength;
436             PRUint8 sessionID[SSL3_SESSIONID_BYTES];
437 
438             ssl3CipherSuite cipherSuite;
439             PRUint8 policy;
440             ssl3SidKeys keys;
441             /* mechanism used to wrap master secret */
442             CK_MECHANISM_TYPE masterWrapMech;
443 
444             /* The following values pertain to the slot that wrapped the
445             ** master secret. (used only in client)
446             */
447             SECMODModuleID masterModuleID;
448             /* what module wrapped the master secret */
449             CK_SLOT_ID masterSlotID;
450             PRUint16 masterWrapIndex;
451             /* what's the key index for the wrapping key */
452             PRUint16 masterWrapSeries;
453             /* keep track of the slot series, so we don't
454              * accidently try to use new keys after the
455              * card gets removed and replaced.*/
456 
457             /* The following values pertain to the slot that did the signature
458             ** for client auth.   (used only in client)
459             */
460             SECMODModuleID clAuthModuleID;
461             CK_SLOT_ID clAuthSlotID;
462             PRUint16 clAuthSeries;
463 
464             char masterValid;
465             char clAuthValid;
466 
467             SECItem srvName;
468 
469             /* Signed certificate timestamps received in a TLS extension.
470             ** (used only in client).
471             */
472             SECItem signedCertTimestamps;
473 
474             /* The ALPN value negotiated in the original connection.
475              * Used for TLS 1.3. */
476             SECItem alpnSelection;
477 
478             /* This lock is lazily initialized by CacheSID when a sid is first
479              * cached. Before then, there is no need to lock anything because
480              * the sid isn't being shared by anything.
481              */
482             PRRWLock *lock;
483 
484             /* The lock must be held while reading or writing these members
485              * because they change while the sid is cached.
486              */
487             struct {
488                 /* The session ticket, if we have one, is sent as an extension
489                  * in the ClientHello message. This field is used only by
490                  * clients. It is protected by lock when lock is non-null
491                  * (after the sid has been added to the client session cache).
492                  */
493                 NewSessionTicket sessionTicket;
494             } locked;
495         } ssl3;
496     } u;
497 };
498 
499 struct ssl3CipherSuiteDefStr {
500     ssl3CipherSuite cipher_suite;
501     SSL3BulkCipher bulk_cipher_alg;
502     SSL3MACAlgorithm mac_alg;
503     SSL3KeyExchangeAlgorithm key_exchange_alg;
504     SSLHashType prf_hash;
505 };
506 
507 /*
508 ** There are tables of these, all const.
509 */
510 typedef struct {
511     /* An identifier for this struct. */
512     SSL3KeyExchangeAlgorithm kea;
513     /* The type of key exchange used by the cipher suite. */
514     SSLKEAType exchKeyType;
515     /* If the cipher suite uses a signature, the type of key used in the
516      * signature. */
517     KeyType signKeyType;
518     /* In most cases, cipher suites depend on their signature type for
519      * authentication, ECDH certificates being the exception. */
520     SSLAuthType authKeyType;
521     /* True if the key exchange for the suite is ephemeral.  Or to be more
522      * precise: true if the ServerKeyExchange message is always required. */
523     PRBool ephemeral;
524     /* An OID describing the key exchange */
525     SECOidTag oid;
526 } ssl3KEADef;
527 
528 typedef enum {
529     ssl_0rtt_none,     /* 0-RTT not present */
530     ssl_0rtt_sent,     /* 0-RTT sent (no decision yet) */
531     ssl_0rtt_accepted, /* 0-RTT sent and accepted */
532     ssl_0rtt_ignored,  /* 0-RTT sent but rejected/ignored */
533     ssl_0rtt_done      /* 0-RTT accepted, but finished */
534 } sslZeroRttState;
535 
536 typedef enum {
537     ssl_0rtt_ignore_none,  /* not ignoring */
538     ssl_0rtt_ignore_trial, /* ignoring with trial decryption */
539     ssl_0rtt_ignore_hrr    /* ignoring until ClientHello (due to HRR) */
540 } sslZeroRttIgnore;
541 
542 typedef enum {
543     idle_handshake,
544     wait_client_hello,
545     wait_end_of_early_data,
546     wait_client_cert,
547     wait_client_key,
548     wait_cert_verify,
549     wait_change_cipher,
550     wait_finished,
551     wait_server_hello,
552     wait_certificate_status,
553     wait_server_cert,
554     wait_server_key,
555     wait_cert_request,
556     wait_hello_done,
557     wait_new_session_ticket,
558     wait_encrypted_extensions,
559     wait_invalid /* Invalid value. There is no handshake message "invalid". */
560 } SSL3WaitState;
561 
562 typedef enum {
563     client_hello_initial,      /* The first attempt. */
564     client_hello_retry,        /* If we receive HelloRetryRequest. */
565     client_hello_retransmit,   /* In DTLS, if we receive HelloVerifyRequest. */
566     client_hello_renegotiation /* A renegotiation attempt. */
567 } sslClientHelloType;
568 
569 typedef struct SessionTicketDataStr SessionTicketData;
570 
571 typedef SECStatus (*sslRestartTarget)(sslSocket *);
572 
573 /*
574 ** A DTLS queued message (potentially to be retransmitted)
575 */
576 typedef struct DTLSQueuedMessageStr {
577     PRCList link;           /* The linked list link */
578     ssl3CipherSpec *cwSpec; /* The cipher spec to use, null for none */
579     SSLContentType type;    /* The message type */
580     unsigned char *data;    /* The data */
581     PRUint16 len;           /* The data length */
582 } DTLSQueuedMessage;
583 
584 struct TLS13KeyShareEntryStr {
585     PRCList link;                  /* The linked list link */
586     const sslNamedGroupDef *group; /* The group for the entry */
587     SECItem key_exchange;          /* The share itself */
588 };
589 
590 typedef struct TLS13EarlyDataStr {
591     PRCList link;          /* The linked list link */
592     unsigned int consumed; /* How much has been read. */
593     SECItem data;          /* The data */
594 } TLS13EarlyData;
595 
596 typedef enum {
597     handshake_hash_unknown = 0,
598     handshake_hash_combo = 1,  /* The MD5/SHA-1 combination */
599     handshake_hash_single = 2, /* A single hash */
600     handshake_hash_record
601 } SSL3HandshakeHashType;
602 
603 // A DTLS Timer.
604 typedef void (*DTLSTimerCb)(sslSocket *);
605 
606 typedef struct {
607     const char *label;
608     DTLSTimerCb cb;
609     PRIntervalTime started;
610     PRUint32 timeout;
611 } dtlsTimer;
612 
613 /*
614 ** This is the "hs" member of the "ssl3" struct.
615 ** This entire struct is protected by ssl3HandshakeLock
616 */
617 typedef struct SSL3HandshakeStateStr {
618     SSL3Random server_random;
619     SSL3Random client_random;
620     SSL3Random client_inner_random; /* TLS 1.3 ECH Inner. */
621     SSL3WaitState ws;               /* May also contain SSL3WaitState | 0x80 for TLS 1.3 */
622 
623     /* This group of members is used for handshake running hashes. */
624     SSL3HandshakeHashType hashType;
625     sslBuffer messages;         /* Accumulated handshake messages */
626     sslBuffer echInnerMessages; /* Accumulated ECH Inner handshake messages */
627     /* PKCS #11 mode:
628      * SSL 3.0 - TLS 1.1 use both |md5| and |sha|. |md5| is used for MD5 and
629      * |sha| for SHA-1.
630      * TLS 1.2 and later use only |sha| variants, for SHA-256.
631      * Under normal (non-1.3 ECH) handshakes, only |sha| and |shaPostHandshake|
632      * are used. When doing 1.3 ECH, |sha| contains the transcript hash
633      * corresponding to the outer Client Hello. To facilitate secure retry and
634      * disablement, |shaEchInner|, tracks, in parallel, the transcript hash
635      * corresponding to the inner Client Hello. Once we process the SH
636      * extensions, coalesce into |sha|. */
637     PK11Context *md5;
638     PK11Context *sha;
639     PK11Context *shaEchInner;
640     PK11Context *shaPostHandshake;
641     SSLSignatureScheme signatureScheme;
642     const ssl3KEADef *kea_def;
643     ssl3CipherSuite cipher_suite;
644     const ssl3CipherSuiteDef *suite_def;
645     sslBuffer msg_body; /* protected by recvBufLock */
646                         /* partial handshake message from record layer */
647     unsigned int header_bytes;
648     /* number of bytes consumed from handshake */
649     /* message for message type and header length */
650     SSLHandshakeType msg_type;
651     unsigned long msg_len;
652     PRBool isResuming;  /* we are resuming (not used in TLS 1.3) */
653     PRBool sendingSCSV; /* instead of empty RI */
654 
655     /* The session ticket received in a NewSessionTicket message is temporarily
656      * stored in newSessionTicket until the handshake is finished; then it is
657      * moved to the sid.
658      */
659     PRBool receivedNewSessionTicket;
660     NewSessionTicket newSessionTicket;
661 
662     PRUint16 finishedBytes; /* size of single finished below */
663     union {
664         TLSFinished tFinished[2]; /* client, then server */
665         SSL3Finished sFinished[2];
666         PRUint8 data[72];
667     } finishedMsgs;
668 
669     PRBool authCertificatePending;
670     /* Which function should SSL_RestartHandshake* call if we're blocked?
671      * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake,
672      * or ssl3_AlwaysFail */
673     sslRestartTarget restartTarget;
674 
675     PRBool canFalseStart; /* Can/did we False Start */
676     /* Which preliminaryinfo values have been set. */
677     PRUint32 preliminaryInfo;
678 
679     /* Parsed extensions */
680     PRCList remoteExtensions;   /* Parsed incoming extensions */
681     PRCList echOuterExtensions; /* If ECH, hold CHOuter extensions for decompression. */
682 
683     /* This group of values is used for DTLS */
684     PRUint16 sendMessageSeq;   /* The sending message sequence
685                                     * number */
686     PRCList lastMessageFlight; /* The last message flight we
687                                     * sent */
688     PRUint16 maxMessageSent;   /* The largest message we sent */
689     PRUint16 recvMessageSeq;   /* The receiving message sequence
690                                     * number */
691     sslBuffer recvdFragments;  /* The fragments we have received in
692                                     * a bitmask */
693     PRInt32 recvdHighWater;    /* The high water mark for fragments
694                                     * received. -1 means no reassembly
695                                     * in progress. */
696     SECItem cookie;            /* The Hello(Retry|Verify)Request cookie. */
697     dtlsTimer timers[3];       /* Holder for timers. */
698     dtlsTimer *rtTimer;        /* Retransmit timer. */
699     dtlsTimer *ackTimer;       /* Ack timer (DTLS 1.3 only). */
700     dtlsTimer *hdTimer;        /* Read cipher holddown timer (DLTS 1.3 only) */
701     PRUint32 rtRetries;        /* The retry counter */
702     SECItem srvVirtName;       /* for server: name that was negotiated
703                                     * with a client. For client - is
704                                     * always set to NULL.*/
705 
706     /* This group of values is used for TLS 1.3 and above */
707     PK11SymKey *currentSecret;            /* The secret down the "left hand side"
708                                            * of the TLS 1.3 key schedule. */
709     PK11SymKey *resumptionMasterSecret;   /* The resumption_master_secret. */
710     PK11SymKey *dheSecret;                /* The (EC)DHE shared secret. */
711     PK11SymKey *clientEarlyTrafficSecret; /* The secret we use for 0-RTT. */
712     PK11SymKey *clientHsTrafficSecret;    /* The source keys for handshake */
713     PK11SymKey *serverHsTrafficSecret;    /* traffic keys. */
714     PK11SymKey *clientTrafficSecret;      /* The source keys for application */
715     PK11SymKey *serverTrafficSecret;      /* traffic keys */
716     PK11SymKey *earlyExporterSecret;      /* for 0-RTT exporters */
717     PK11SymKey *exporterSecret;           /* for exporters */
718     PRCList cipherSpecs;                  /* The cipher specs in the sequence they
719                                            * will be applied. */
720     sslZeroRttState zeroRttState;         /* Are we doing a 0-RTT handshake? */
721     sslZeroRttIgnore zeroRttIgnore;       /* Are we ignoring 0-RTT? */
722     ssl3CipherSuite zeroRttSuite;         /* The cipher suite we used for 0-RTT. */
723     PRCList bufferedEarlyData;            /* Buffered TLS 1.3 early data
724                                            * on server.*/
725     PRBool helloRetry;                    /* True if HelloRetryRequest has been sent
726                                            * or received. */
727     PRBool receivedCcs;                   /* A server received ChangeCipherSpec
728                                            * before the handshake started. */
729     PRBool rejectCcs;                     /* Excessive ChangeCipherSpecs are rejected. */
730     PRBool clientCertRequested;           /* True if CertificateRequest received. */
731     PRBool endOfFlight;                   /* Processed a full flight (DTLS 1.3). */
732     ssl3KEADef kea_def_mutable;           /* Used to hold the writable kea_def
733                                            * we use for TLS 1.3 */
734     PRUint16 ticketNonce;                 /* A counter we use for tickets. */
735     SECItem fakeSid;                      /* ... (server) the SID the client used. */
736     PRCList psks;                         /* A list of PSKs, resumption and/or external. */
737 
738     /* rttEstimate is used to guess the round trip time between server and client.
739      * When the server sends ServerHello it sets this to the current time.
740      * Only after it receives a message from the client's second flight does it
741      * set the value to something resembling an RTT estimate. */
742     PRTime rttEstimate;
743 
744     /* The following lists contain DTLSHandshakeRecordEntry */
745     PRCList dtlsSentHandshake; /* Used to map records to handshake fragments. */
746     PRCList dtlsRcvdHandshake; /* Handshake records we have received
747                                 * used to generate ACKs. */
748 
749     /* TLS 1.3 ECH state. */
750     PRBool echAccepted; /* Client/Server: True if we've commited to using CHInner. */
751     PRBool echDecided;
752     HpkeContext *echHpkeCtx;    /* Client/Server: HPKE context for ECH. */
753     const char *echPublicName;  /* Client: If rejected, the ECHConfig.publicName to
754                                 * use for certificate verification. */
755     sslBuffer greaseEchBuf;     /* Client: Remember GREASE ECH, as advertised, for CH2 (HRR case).
756                                   Server: Remember HRR Grease Value, for transcript calculations */
757     PRBool echInvalidExtension; /* Client: True if the server offered an invalid extension for the ClientHelloInner */
758 } SSL3HandshakeState;
759 
760 #define SSL_ASSERT_HASHES_EMPTY(ss)                                  \
761     do {                                                             \
762         PORT_Assert(ss->ssl3.hs.hashType == handshake_hash_unknown); \
763         PORT_Assert(ss->ssl3.hs.messages.len == 0);                  \
764         PORT_Assert(ss->ssl3.hs.echInnerMessages.len == 0);          \
765     } while (0)
766 
767 /*
768 ** This is the "ssl3" struct, as in "ss->ssl3".
769 ** note:
770 ** usually,   crSpec == cwSpec and prSpec == pwSpec.
771 ** Sometimes, crSpec == pwSpec and prSpec == cwSpec.
772 ** But there are never more than 2 actual specs.
773 ** No spec must ever be modified if either "current" pointer points to it.
774 */
775 struct ssl3StateStr {
776 
777     /*
778     ** The following Specs and Spec pointers must be protected using the
779     ** Spec Lock.
780     */
781     ssl3CipherSpec *crSpec; /* current read spec. */
782     ssl3CipherSpec *prSpec; /* pending read spec. */
783     ssl3CipherSpec *cwSpec; /* current write spec. */
784     ssl3CipherSpec *pwSpec; /* pending write spec. */
785 
786     /* This is true after the peer requests a key update; false after a key
787      * update is initiated locally. */
788     PRBool peerRequestedKeyUpdate;
789 
790     /* This is true if we deferred sending a key update as
791      * post-handshake auth is in progress. */
792     PRBool keyUpdateDeferred;
793     tls13KeyUpdateRequest deferredKeyUpdateRequest;
794 
795     /* This is true after the server requests client certificate;
796      * false after the client certificate is received.  Used by the
797      * server. */
798     PRBool clientCertRequested;
799 
800     CERTCertificate *clientCertificate;   /* used by client */
801     SECKEYPrivateKey *clientPrivateKey;   /* used by client */
802     CERTCertificateList *clientCertChain; /* used by client */
803     PRBool sendEmptyCert;                 /* used by client */
804 
805     PRUint8 policy;
806     /* This says what cipher suites we can do, and should
807      * be either SSL_ALLOWED or SSL_RESTRICTED
808      */
809     PLArenaPool *peerCertArena;
810     /* These are used to keep track of the peer CA */
811     void *peerCertChain;
812     /* chain while we are trying to validate it.   */
813     CERTDistNames *ca_list;
814     /* used by server.  trusted CAs for this socket. */
815     SSL3HandshakeState hs;
816 
817     PRUint16 mtu; /* Our estimate of the MTU */
818 
819     /* DTLS-SRTP cipher suite preferences (if any) */
820     PRUint16 dtlsSRTPCiphers[MAX_DTLS_SRTP_CIPHER_SUITES];
821     PRUint16 dtlsSRTPCipherCount;
822     PRBool fatalAlertSent;
823     PRBool dheWeakGroupEnabled; /* used by server */
824     const sslNamedGroupDef *dhePreferredGroup;
825 
826     /* TLS 1.2 introduces separate signature algorithm negotiation.
827      * TLS 1.3 combined signature and hash into a single enum.
828      * This is our preference order. */
829     SSLSignatureScheme signatureSchemes[MAX_SIGNATURE_SCHEMES];
830     unsigned int signatureSchemeCount;
831 
832     /* The version to check if we fell back from our highest version
833      * of TLS. Default is 0 in which case we check against the maximum
834      * configured version for this socket. Used only on the client. */
835     SSL3ProtocolVersion downgradeCheckVersion;
836 };
837 
838 /* Ethernet MTU but without subtracting the headers,
839  * so slightly larger than expected */
840 #define DTLS_MAX_MTU 1500U
841 #define IS_DTLS(ss) (ss->protocolVariant == ssl_variant_datagram)
842 
843 typedef struct {
844     /* |seqNum| eventually contains the reconstructed sequence number. */
845     sslSequenceNumber seqNum;
846     /* The header of the cipherText. */
847     PRUint8 *hdr;
848     unsigned int hdrLen;
849 
850     /* |buf| is the payload of the ciphertext. */
851     sslBuffer *buf;
852 } SSL3Ciphertext;
853 
854 struct sslKeyPairStr {
855     SECKEYPrivateKey *privKey;
856     SECKEYPublicKey *pubKey;
857     PRInt32 refCount; /* use PR_Atomic calls for this. */
858 };
859 
860 struct sslEphemeralKeyPairStr {
861     PRCList link;
862     const sslNamedGroupDef *group;
863     sslKeyPair *keys;
864 };
865 
866 struct ssl3DHParamsStr {
867     SSLNamedGroup name;
868     SECItem prime; /* p */
869     SECItem base;  /* g */
870 };
871 
872 typedef struct SSLWrappedSymWrappingKeyStr {
873     PRUint8 wrappedSymmetricWrappingkey[SSL_MAX_RSA_KEY_BITS / 8];
874     CK_MECHANISM_TYPE symWrapMechanism;
875     /* unwrapped symmetric wrapping key uses this mechanism */
876     CK_MECHANISM_TYPE asymWrapMechanism;
877     /* mechanism used to wrap the SymmetricWrappingKey using
878      * server's public and/or private keys. */
879     PRInt16 wrapMechIndex;
880     PRUint16 wrapKeyIndex;
881     PRUint16 wrappedSymKeyLen;
882 } SSLWrappedSymWrappingKey;
883 
884 typedef struct SessionTicketStr {
885     PRBool valid;
886     SSL3ProtocolVersion ssl_version;
887     ssl3CipherSuite cipher_suite;
888     SSLAuthType authType;
889     PRUint32 authKeyBits;
890     SSLKEAType keaType;
891     PRUint32 keaKeyBits;
892     SSLNamedGroup originalKeaGroup;
893     SSLSignatureScheme signatureScheme;
894     const sslNamedGroupDef *namedCurve; /* For certificate lookup. */
895 
896     /*
897      * msWrapMech contains a meaningful value only if ms_is_wrapped is true.
898      */
899     PRUint8 ms_is_wrapped;
900     CK_MECHANISM_TYPE msWrapMech;
901     PRUint16 ms_length;
902     PRUint8 master_secret[48];
903     PRBool extendedMasterSecretUsed;
904     ClientAuthenticationType client_auth_type;
905     SECItem peer_cert;
906     PRTime timestamp;
907     PRUint32 flags;
908     SECItem srvName; /* negotiated server name */
909     SECItem alpnSelection;
910     PRUint32 maxEarlyData;
911     PRUint32 ticketAgeBaseline;
912     SECItem applicationToken;
913 } SessionTicket;
914 
915 /*
916  * SSL2 buffers used in SSL3.
917  *     writeBuf in the SecurityInfo maintained by sslsecur.c is used
918  *              to hold the data just about to be passed to the kernel
919  *     sendBuf in the ConnectInfo maintained by sslcon.c is used
920  *              to hold handshake messages as they are accumulated
921  */
922 
923 /*
924 ** This is "ci", as in "ss->sec.ci".
925 **
926 ** Protection:  All the variables in here are protected by
927 ** firstHandshakeLock AND ssl3HandshakeLock
928 */
929 struct sslConnectInfoStr {
930     /* outgoing handshakes appended to this. */
931     sslBuffer sendBuf; /*xmitBufLock*/
932 
933     PRIPv6Addr peer;
934     unsigned short port;
935 
936     sslSessionID *sid;
937 };
938 
939 /* Note: The entire content of this struct and whatever it points to gets
940  * blown away by SSL_ResetHandshake().  This is "sec" as in "ss->sec".
941  *
942  * Unless otherwise specified below, the contents of this struct are
943  * protected by firstHandshakeLock AND ssl3HandshakeLock.
944  */
945 struct sslSecurityInfoStr {
946 
947 #define SSL_ROLE(ss) (ss->sec.isServer ? "server" : "client")
948 
949     PRBool isServer;
950     sslBuffer writeBuf; /*xmitBufLock*/
951 
952     CERTCertificate *localCert;
953     CERTCertificate *peerCert;
954     SECKEYPublicKey *peerKey;
955 
956     SSLAuthType authType;
957     PRUint32 authKeyBits;
958     SSLSignatureScheme signatureScheme;
959     SSLKEAType keaType;
960     PRUint32 keaKeyBits;
961     const sslNamedGroupDef *keaGroup;
962     const sslNamedGroupDef *originalKeaGroup;
963     /* The selected certificate (for servers only). */
964     const sslServerCert *serverCert;
965 
966     /* These are used during a connection handshake */
967     sslConnectInfo ci;
968 };
969 
970 /*
971 ** SSL Socket struct
972 **
973 ** Protection:  XXX
974 */
975 struct sslSocketStr {
976     PRFileDesc *fd;
977 
978     /* Pointer to operations vector for this socket */
979     const sslSocketOps *ops;
980 
981     /* SSL socket options */
982     sslOptions opt;
983     /* Enabled version range */
984     SSLVersionRange vrange;
985 
986     /* A function that returns the current time. */
987     SSLTimeFunc now;
988     void *nowArg;
989 
990     /* State flags */
991     unsigned long clientAuthRequested;
992     unsigned long delayDisabled;     /* Nagle delay disabled */
993     unsigned long firstHsDone;       /* first handshake is complete. */
994     unsigned long enoughFirstHsDone; /* enough of the first handshake is
995                                       * done for callbacks to be able to
996                                       * retrieve channel security
997                                       * parameters from the SSL socket. */
998     unsigned long handshakeBegun;
999     unsigned long lastWriteBlocked;
1000     unsigned long recvdCloseNotify; /* received SSL EOF. */
1001     unsigned long TCPconnected;
1002     unsigned long appDataBuffered;
1003     unsigned long peerRequestedProtection; /* from old renegotiation */
1004 
1005     /* version of the protocol to use */
1006     SSL3ProtocolVersion version;
1007     SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. */
1008 
1009     sslSecurityInfo sec; /* not a pointer any more */
1010 
1011     /* protected by firstHandshakeLock AND ssl3HandshakeLock. */
1012     const char *url;
1013 
1014     sslHandshakeFunc handshake; /*firstHandshakeLock*/
1015 
1016     /* the following variable is only used with socks or other proxies. */
1017     char *peerID; /* String uniquely identifies target server. */
1018 
1019     /* ECDHE and DHE keys: In TLS 1.3, we might have to maintain multiple of
1020      * these on the client side.  The server inserts a single value into this
1021      * list for all versions. */
1022     PRCList /*<sslEphemeralKeyPair>*/ ephemeralKeyPairs;
1023 
1024     /* Callbacks */
1025     SSLAuthCertificate authCertificate;
1026     void *authCertificateArg;
1027     SSLGetClientAuthData getClientAuthData;
1028     void *getClientAuthDataArg;
1029     SSLSNISocketConfig sniSocketConfig;
1030     void *sniSocketConfigArg;
1031     SSLAlertCallback alertReceivedCallback;
1032     void *alertReceivedCallbackArg;
1033     SSLAlertCallback alertSentCallback;
1034     void *alertSentCallbackArg;
1035     SSLBadCertHandler handleBadCert;
1036     void *badCertArg;
1037     SSLHandshakeCallback handshakeCallback;
1038     void *handshakeCallbackData;
1039     SSLCanFalseStartCallback canFalseStartCallback;
1040     void *canFalseStartCallbackData;
1041     void *pkcs11PinArg;
1042     SSLNextProtoCallback nextProtoCallback;
1043     void *nextProtoArg;
1044     SSLHelloRetryRequestCallback hrrCallback;
1045     void *hrrCallbackArg;
1046     PRCList extensionHooks;
1047     SSLResumptionTokenCallback resumptionTokenCallback;
1048     void *resumptionTokenContext;
1049     SSLSecretCallback secretCallback;
1050     void *secretCallbackArg;
1051     SSLRecordWriteCallback recordWriteCallback;
1052     void *recordWriteCallbackArg;
1053 
1054     PRIntervalTime rTimeout; /* timeout for NSPR I/O */
1055     PRIntervalTime wTimeout; /* timeout for NSPR I/O */
1056     PRIntervalTime cTimeout; /* timeout for NSPR I/O */
1057 
1058     PZLock *recvLock; /* lock against multiple reader threads. */
1059     PZLock *sendLock; /* lock against multiple sender threads. */
1060 
1061     PZMonitor *recvBufLock; /* locks low level recv buffers. */
1062     PZMonitor *xmitBufLock; /* locks low level xmit buffers. */
1063 
1064     /* Only one thread may operate on the socket until the initial handshake
1065     ** is complete.  This Monitor ensures that.  Since SSL2 handshake is
1066     ** only done once, this is also effectively the SSL2 handshake lock.
1067     */
1068     PZMonitor *firstHandshakeLock;
1069 
1070     /* This monitor protects the ssl3 handshake state machine data.
1071     ** Only one thread (reader or writer) may be in the ssl3 handshake state
1072     ** machine at any time.  */
1073     PZMonitor *ssl3HandshakeLock;
1074 
1075     /* reader/writer lock, protects the secret data needed to encrypt and MAC
1076     ** outgoing records, and to decrypt and MAC check incoming ciphertext
1077     ** records.  */
1078     NSSRWLock *specLock;
1079 
1080     /* handle to perm cert db (and implicitly to the temp cert db) used
1081     ** with this socket.
1082     */
1083     CERTCertDBHandle *dbHandle;
1084 
1085     PRThread *writerThread; /* thread holds SSL_LOCK_WRITER lock */
1086 
1087     PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */
1088 
1089     sslHandshakingType handshaking;
1090 
1091     /* Gather object used for gathering data */
1092     sslGather gs; /*recvBufLock*/
1093 
1094     sslBuffer saveBuf;    /*xmitBufLock*/
1095     sslBuffer pendingBuf; /*xmitBufLock*/
1096 
1097     /* Configuration state for server sockets */
1098     /* One server cert and key for each authentication type. */
1099     PRCList /* <sslServerCert> */ serverCerts;
1100 
1101     ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED];
1102 
1103     /* A list of groups that are sorted according to user preferences pointing
1104      * to entries of ssl_named_groups. By default this list contains pointers
1105      * to all elements in ssl_named_groups in the default order.
1106      * This list also determines which groups are enabled. This
1107      * starts with all being enabled and can be modified either by negotiation
1108      * (in which case groups not supported by a peer are masked off), or by
1109      * calling SSL_DHEGroupPrefSet().
1110      * Note that renegotiation will ignore groups that were disabled in the
1111      * first handshake.
1112      */
1113     const sslNamedGroupDef *namedGroupPreferences[SSL_NAMED_GROUP_COUNT];
1114     /* The number of additional shares to generate for the TLS 1.3 ClientHello */
1115     unsigned int additionalShares;
1116 
1117     /* SSL3 state info.  Formerly was a pointer */
1118     ssl3State ssl3;
1119 
1120     /*
1121      * TLS extension related data.
1122      */
1123     /* True when the current session is a stateless resume. */
1124     PRBool statelessResume;
1125     TLSExtensionData xtnData;
1126 
1127     /* Whether we are doing stream or datagram mode */
1128     SSLProtocolVariant protocolVariant;
1129 
1130     /* TLS 1.3 Encrypted Client Hello. */
1131     PRCList echConfigs;           /* Client/server: Must not change while hs
1132                                    * is in-progress. */
1133     SECKEYPublicKey *echPubKey;   /* Server: The ECH keypair used in HPKE. */
1134     SECKEYPrivateKey *echPrivKey; /* As above. */
1135 
1136     /* Anti-replay for TLS 1.3 0-RTT. */
1137     SSLAntiReplayContext *antiReplay;
1138 
1139     /* An out-of-band PSK. */
1140     sslPsk *psk;
1141 };
1142 
1143 struct sslSelfEncryptKeysStr {
1144     PRCallOnceType setup;
1145     PRUint8 keyName[SELF_ENCRYPT_KEY_NAME_LEN];
1146     PK11SymKey *encKey;
1147     PK11SymKey *macKey;
1148 };
1149 typedef struct sslSelfEncryptKeysStr sslSelfEncryptKeys;
1150 
1151 extern char ssl_debug;
1152 extern char ssl_trace;
1153 extern FILE *ssl_trace_iob;
1154 extern FILE *ssl_keylog_iob;
1155 extern PZLock *ssl_keylog_lock;
1156 static const PRUint32 ssl_ticket_lifetime = 2 * 24 * 60 * 60; // 2 days.
1157 
1158 extern const char *const ssl3_cipherName[];
1159 
1160 extern sslSessionIDLookupFunc ssl_sid_lookup;
1161 
1162 extern const sslNamedGroupDef ssl_named_groups[];
1163 
1164 /************************************************************************/
1165 
1166 SEC_BEGIN_PROTOS
1167 
1168 /* Internal initialization and installation of the SSL error tables */
1169 extern SECStatus ssl_Init(void);
1170 extern SECStatus ssl_InitializePRErrorTable(void);
1171 
1172 /* Implementation of ops for default (non socks, non secure) case */
1173 extern int ssl_DefConnect(sslSocket *ss, const PRNetAddr *addr);
1174 extern PRFileDesc *ssl_DefAccept(sslSocket *ss, PRNetAddr *addr);
1175 extern int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr);
1176 extern int ssl_DefListen(sslSocket *ss, int backlog);
1177 extern int ssl_DefShutdown(sslSocket *ss, int how);
1178 extern int ssl_DefClose(sslSocket *ss);
1179 extern int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
1180 extern int ssl_DefSend(sslSocket *ss, const unsigned char *buf,
1181                        int len, int flags);
1182 extern int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len);
1183 extern int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len);
1184 extern int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name);
1185 extern int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name);
1186 extern int ssl_DefGetsockopt(sslSocket *ss, PRSockOption optname,
1187                              void *optval, PRInt32 *optlen);
1188 extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname,
1189                              const void *optval, PRInt32 optlen);
1190 
1191 /* Implementation of ops for socks only case */
1192 extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr);
1193 extern PRFileDesc *ssl_SocksAccept(sslSocket *ss, PRNetAddr *addr);
1194 extern int ssl_SocksBind(sslSocket *ss, const PRNetAddr *addr);
1195 extern int ssl_SocksListen(sslSocket *ss, int backlog);
1196 extern int ssl_SocksGetsockname(sslSocket *ss, PRNetAddr *name);
1197 extern int ssl_SocksRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
1198 extern int ssl_SocksSend(sslSocket *ss, const unsigned char *buf,
1199                          int len, int flags);
1200 extern int ssl_SocksRead(sslSocket *ss, unsigned char *buf, int len);
1201 extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len);
1202 
1203 /* Implementation of ops for secure only case */
1204 extern int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *addr);
1205 extern PRFileDesc *ssl_SecureAccept(sslSocket *ss, PRNetAddr *addr);
1206 extern int ssl_SecureRecv(sslSocket *ss, unsigned char *buf,
1207                           int len, int flags);
1208 extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf,
1209                           int len, int flags);
1210 extern int ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len);
1211 extern int ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len);
1212 extern int ssl_SecureShutdown(sslSocket *ss, int how);
1213 extern int ssl_SecureClose(sslSocket *ss);
1214 
1215 /* Implementation of ops for secure socks case */
1216 extern int ssl_SecureSocksConnect(sslSocket *ss, const PRNetAddr *addr);
1217 extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr);
1218 extern PRFileDesc *ssl_FindTop(sslSocket *ss);
1219 
1220 /* Gather funcs. */
1221 extern sslGather *ssl_NewGather(void);
1222 extern SECStatus ssl3_InitGather(sslGather *gs);
1223 extern void ssl3_DestroyGather(sslGather *gs);
1224 extern SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss);
1225 
1226 extern SECStatus ssl_CreateSecurityInfo(sslSocket *ss);
1227 extern SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os);
1228 extern void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset);
1229 extern void ssl_DestroySecurityInfo(sslSecurityInfo *sec);
1230 
1231 extern void ssl_PrintBuf(const sslSocket *ss, const char *msg, const void *cp,
1232                          int len);
1233 extern void ssl_PrintKey(const sslSocket *ss, const char *msg, PK11SymKey *key);
1234 
1235 extern int ssl_SendSavedWriteData(sslSocket *ss);
1236 extern SECStatus ssl_SaveWriteData(sslSocket *ss,
1237                                    const void *p, unsigned int l);
1238 extern SECStatus ssl_BeginClientHandshake(sslSocket *ss);
1239 extern SECStatus ssl_BeginServerHandshake(sslSocket *ss);
1240 extern SECStatus ssl_Do1stHandshake(sslSocket *ss);
1241 
1242 extern SECStatus ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret,
1243                                              PRBool derive);
1244 extern void ssl_DestroyKeyMaterial(ssl3KeyMaterial *keyMaterial);
1245 extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server);
1246 extern sslSessionID *ssl_LookupSID(PRTime now, const PRIPv6Addr *addr,
1247                                    PRUint16 port, const char *peerID,
1248                                    const char *urlSvrName);
1249 extern void ssl_FreeSID(sslSessionID *sid);
1250 extern void ssl_DestroySID(sslSessionID *sid, PRBool freeIt);
1251 extern sslSessionID *ssl_ReferenceSID(sslSessionID *sid);
1252 
1253 extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in,
1254                                     int len, int flags);
1255 
1256 extern PRBool ssl_FdIsBlocking(PRFileDesc *fd);
1257 
1258 extern PRBool ssl_SocketIsBlocking(sslSocket *ss);
1259 
1260 extern void ssl3_SetAlwaysBlock(sslSocket *ss);
1261 
1262 extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled);
1263 
1264 extern void ssl_FinishHandshake(sslSocket *ss);
1265 
1266 extern SECStatus ssl_CipherPolicySet(PRInt32 which, PRInt32 policy);
1267 
1268 extern SECStatus ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled);
1269 
1270 extern SECStatus ssl3_ConstrainRangeByPolicy(void);
1271 
1272 extern SECStatus ssl3_InitState(sslSocket *ss);
1273 extern SECStatus Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen,
1274                              unsigned int maxOutputLen, const unsigned char *input,
1275                              unsigned int inputLen);
1276 extern void ssl3_RestartHandshakeHashes(sslSocket *ss);
1277 typedef SECStatus (*sslUpdateHandshakeHashes)(sslSocket *ss,
1278                                               const unsigned char *b,
1279                                               unsigned int l);
1280 extern SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss,
1281                                             const unsigned char *b,
1282                                             unsigned int l);
1283 extern SECStatus ssl3_UpdatePostHandshakeHashes(sslSocket *ss,
1284                                                 const unsigned char *b,
1285                                                 unsigned int l);
1286 SECStatus
1287 ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType type,
1288                             PRUint32 dtlsSeq,
1289                             const PRUint8 *b, PRUint32 length,
1290                             sslUpdateHandshakeHashes cb);
1291 SECStatus ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType type,
1292                                    const PRUint8 *b, PRUint32 length);
1293 SECStatus ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType type,
1294                                            const PRUint8 *b, PRUint32 length);
1295 SECStatus ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType type,
1296                                           const PRUint8 *b, PRUint32 length);
1297 SECStatus ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType type,
1298                                        const PRUint8 *b, PRUint32 length);
1299 
1300 /* Returns PR_TRUE if we are still waiting for the server to complete its
1301  * response to our client second round. Once we've received the Finished from
1302  * the server then there is no need to check false start.
1303  */
1304 extern PRBool ssl3_WaitingForServerSecondRound(sslSocket *ss);
1305 
1306 extern PRInt32 ssl3_SendRecord(sslSocket *ss, ssl3CipherSpec *cwSpec,
1307                                SSLContentType type,
1308                                const PRUint8 *pIn, PRInt32 nIn,
1309                                PRInt32 flags);
1310 
1311 /* Clear any PRCList, optionally calling f on the value. */
1312 void ssl_ClearPRCList(PRCList *list, void (*f)(void *));
1313 
1314 /*
1315  * Make sure there is room in the write buffer for padding and
1316  * cryptographic expansions.
1317  */
1318 #define SSL3_BUFFER_FUDGE 100
1319 
1320 #define SSL_LOCK_READER(ss) \
1321     if (ss->recvLock)       \
1322     PZ_Lock(ss->recvLock)
1323 #define SSL_UNLOCK_READER(ss) \
1324     if (ss->recvLock)         \
1325     PZ_Unlock(ss->recvLock)
1326 #define SSL_LOCK_WRITER(ss) \
1327     if (ss->sendLock)       \
1328     PZ_Lock(ss->sendLock)
1329 #define SSL_UNLOCK_WRITER(ss) \
1330     if (ss->sendLock)         \
1331     PZ_Unlock(ss->sendLock)
1332 
1333 /* firstHandshakeLock -> recvBufLock */
1334 #define ssl_Get1stHandshakeLock(ss)                               \
1335     {                                                             \
1336         if (!ss->opt.noLocks) {                                   \
1337             PORT_Assert(PZ_InMonitor((ss)->firstHandshakeLock) || \
1338                         !ssl_HaveRecvBufLock(ss));                \
1339             PZ_EnterMonitor((ss)->firstHandshakeLock);            \
1340         }                                                         \
1341     }
1342 #define ssl_Release1stHandshakeLock(ss)               \
1343     {                                                 \
1344         if (!ss->opt.noLocks)                         \
1345             PZ_ExitMonitor((ss)->firstHandshakeLock); \
1346     }
1347 #define ssl_Have1stHandshakeLock(ss) \
1348     (PZ_InMonitor((ss)->firstHandshakeLock))
1349 
1350 /* ssl3HandshakeLock -> xmitBufLock */
1351 #define ssl_GetSSL3HandshakeLock(ss)                  \
1352     {                                                 \
1353         if (!ss->opt.noLocks) {                       \
1354             PORT_Assert(!ssl_HaveXmitBufLock(ss));    \
1355             PZ_EnterMonitor((ss)->ssl3HandshakeLock); \
1356         }                                             \
1357     }
1358 #define ssl_ReleaseSSL3HandshakeLock(ss)             \
1359     {                                                \
1360         if (!ss->opt.noLocks)                        \
1361             PZ_ExitMonitor((ss)->ssl3HandshakeLock); \
1362     }
1363 #define ssl_HaveSSL3HandshakeLock(ss) \
1364     (PZ_InMonitor((ss)->ssl3HandshakeLock))
1365 
1366 #define ssl_GetSpecReadLock(ss)                 \
1367     {                                           \
1368         if (!ss->opt.noLocks)                   \
1369             NSSRWLock_LockRead((ss)->specLock); \
1370     }
1371 #define ssl_ReleaseSpecReadLock(ss)               \
1372     {                                             \
1373         if (!ss->opt.noLocks)                     \
1374             NSSRWLock_UnlockRead((ss)->specLock); \
1375     }
1376 /* NSSRWLock_HaveReadLock is not exported so there's no
1377  * ssl_HaveSpecReadLock macro. */
1378 
1379 #define ssl_GetSpecWriteLock(ss)                 \
1380     {                                            \
1381         if (!ss->opt.noLocks)                    \
1382             NSSRWLock_LockWrite((ss)->specLock); \
1383     }
1384 #define ssl_ReleaseSpecWriteLock(ss)               \
1385     {                                              \
1386         if (!ss->opt.noLocks)                      \
1387             NSSRWLock_UnlockWrite((ss)->specLock); \
1388     }
1389 #define ssl_HaveSpecWriteLock(ss) \
1390     (NSSRWLock_HaveWriteLock((ss)->specLock))
1391 
1392 /* recvBufLock -> ssl3HandshakeLock -> xmitBufLock */
1393 #define ssl_GetRecvBufLock(ss)                           \
1394     {                                                    \
1395         if (!ss->opt.noLocks) {                          \
1396             PORT_Assert(!ssl_HaveSSL3HandshakeLock(ss)); \
1397             PORT_Assert(!ssl_HaveXmitBufLock(ss));       \
1398             PZ_EnterMonitor((ss)->recvBufLock);          \
1399         }                                                \
1400     }
1401 #define ssl_ReleaseRecvBufLock(ss)             \
1402     {                                          \
1403         if (!ss->opt.noLocks)                  \
1404             PZ_ExitMonitor((ss)->recvBufLock); \
1405     }
1406 #define ssl_HaveRecvBufLock(ss) \
1407     (PZ_InMonitor((ss)->recvBufLock))
1408 
1409 /* xmitBufLock -> specLock */
1410 #define ssl_GetXmitBufLock(ss)                  \
1411     {                                           \
1412         if (!ss->opt.noLocks)                   \
1413             PZ_EnterMonitor((ss)->xmitBufLock); \
1414     }
1415 #define ssl_ReleaseXmitBufLock(ss)             \
1416     {                                          \
1417         if (!ss->opt.noLocks)                  \
1418             PZ_ExitMonitor((ss)->xmitBufLock); \
1419     }
1420 #define ssl_HaveXmitBufLock(ss) \
1421     (PZ_InMonitor((ss)->xmitBufLock))
1422 
1423 /* Placeholder value used in version ranges when SSL 3.0 and all
1424  * versions of TLS are disabled.
1425  */
1426 #define SSL_LIBRARY_VERSION_NONE 0
1427 
1428 /* SSL_LIBRARY_VERSION_MIN_SUPPORTED is the minimum version that this version
1429  * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
1430  * runtime to determine which versions are supported by the version of libssl
1431  * in use.
1432  */
1433 #define SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM SSL_LIBRARY_VERSION_TLS_1_1
1434 #define SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM SSL_LIBRARY_VERSION_3_0
1435 
1436 /* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version
1437  * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
1438  * runtime to determine which versions are supported by the version of libssl
1439  * in use.
1440  */
1441 #ifndef NSS_DISABLE_TLS_1_3
1442 #define SSL_LIBRARY_VERSION_MAX_SUPPORTED SSL_LIBRARY_VERSION_TLS_1_3
1443 #else
1444 #define SSL_LIBRARY_VERSION_MAX_SUPPORTED SSL_LIBRARY_VERSION_TLS_1_2
1445 #endif
1446 
1447 #define SSL_ALL_VERSIONS_DISABLED(vrange) \
1448     ((vrange)->min == SSL_LIBRARY_VERSION_NONE)
1449 
1450 extern PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
1451                                       SSL3ProtocolVersion version);
1452 
1453 /* These functions are called from secnav, even though they're "private". */
1454 
1455 extern int SSL_RestartHandshakeAfterCertReq(struct sslSocketStr *ss,
1456                                             CERTCertificate *cert,
1457                                             SECKEYPrivateKey *key,
1458                                             CERTCertificateList *certChain);
1459 extern sslSocket *ssl_FindSocket(PRFileDesc *fd);
1460 extern void ssl_FreeSocket(struct sslSocketStr *ssl);
1461 extern SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level,
1462                                 SSL3AlertDescription desc);
1463 extern SECStatus ssl3_DecodeError(sslSocket *ss);
1464 
1465 extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error);
1466 
1467 /*
1468  * for dealing with SSL 3.0 clients sending SSL 2.0 format hellos
1469  */
1470 extern SECStatus ssl3_HandleV2ClientHello(
1471     sslSocket *ss, unsigned char *buffer, unsigned int length, PRUint8 padding);
1472 
1473 SECStatus
1474 ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
1475                                PRBool realSid, PRUint16 version, PRBool isEchInner,
1476                                const sslBuffer *extensions, sslBuffer *preamble);
1477 SECStatus ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions);
1478 SECStatus ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type);
1479 
1480 /*
1481  * input into the SSL3 machinery from the actualy network reading code
1482  */
1483 SECStatus ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cipher);
1484 SECStatus ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
1485                                         DTLSEpoch epoch,
1486                                         sslSequenceNumber seqNum,
1487                                         sslBuffer *databuf);
1488 SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize);
1489 
1490 int ssl3_GatherAppDataRecord(sslSocket *ss, int flags);
1491 int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags);
1492 
1493 /* Create a new ref counted key pair object from two keys. */
1494 extern sslKeyPair *ssl_NewKeyPair(SECKEYPrivateKey *privKey,
1495                                   SECKEYPublicKey *pubKey);
1496 
1497 /* get a new reference (bump ref count) to an ssl3KeyPair. */
1498 extern sslKeyPair *ssl_GetKeyPairRef(sslKeyPair *keyPair);
1499 
1500 /* Decrement keypair's ref count and free if zero. */
1501 extern void ssl_FreeKeyPair(sslKeyPair *keyPair);
1502 
1503 extern sslEphemeralKeyPair *ssl_NewEphemeralKeyPair(
1504     const sslNamedGroupDef *group,
1505     SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey);
1506 extern sslEphemeralKeyPair *ssl_CopyEphemeralKeyPair(
1507     sslEphemeralKeyPair *keyPair);
1508 extern void ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair *keyPair);
1509 extern sslEphemeralKeyPair *ssl_LookupEphemeralKeyPair(
1510     sslSocket *ss, const sslNamedGroupDef *groupDef);
1511 extern PRBool ssl_HaveEphemeralKeyPair(const sslSocket *ss,
1512                                        const sslNamedGroupDef *groupDef);
1513 extern void ssl_FreeEphemeralKeyPairs(sslSocket *ss);
1514 
1515 extern SECStatus ssl_AppendPaddedDHKeyShare(sslBuffer *buf,
1516                                             const SECKEYPublicKey *pubKey,
1517                                             PRBool appendLength);
1518 extern PRBool ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
1519                                         const SSLSignatureScheme *peerSchemes,
1520                                         unsigned int peerSchemeCount,
1521                                         PRBool requireSha1,
1522                                         PRBool slotDoesPss);
1523 extern const ssl3DHParams *ssl_GetDHEParams(const sslNamedGroupDef *groupDef);
1524 extern SECStatus ssl_SelectDHEGroup(sslSocket *ss,
1525                                     const sslNamedGroupDef **groupDef);
1526 extern SECStatus ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
1527                                       const ssl3DHParams *params,
1528                                       sslEphemeralKeyPair **keyPair);
1529 extern PRBool ssl_IsValidDHEShare(const SECItem *dh_p, const SECItem *dh_Ys);
1530 extern SECStatus ssl_ValidateDHENamedGroup(sslSocket *ss,
1531                                            const SECItem *dh_p,
1532                                            const SECItem *dh_g,
1533                                            const sslNamedGroupDef **groupDef,
1534                                            const ssl3DHParams **dhParams);
1535 
1536 extern PRBool ssl_IsECCEnabled(const sslSocket *ss);
1537 extern PRBool ssl_IsDHEEnabled(const sslSocket *ss);
1538 
1539 /* Macro for finding a curve equivalent in strength to RSA key's */
1540 #define SSL_RSASTRENGTH_TO_ECSTRENGTH(s)                            \
1541     ((s <= 1024) ? 160                                              \
1542                  : ((s <= 2048) ? 224                               \
1543                                 : ((s <= 3072) ? 256                \
1544                                                : ((s <= 7168) ? 384 \
1545                                                               : 521))))
1546 
1547 extern const sslNamedGroupDef *ssl_LookupNamedGroup(SSLNamedGroup group);
1548 extern PRBool ssl_NamedGroupEnabled(const sslSocket *ss, const sslNamedGroupDef *group);
1549 extern SECStatus ssl_NamedGroup2ECParams(PLArenaPool *arena,
1550                                          const sslNamedGroupDef *curve,
1551                                          SECKEYECParams *params);
1552 extern const sslNamedGroupDef *ssl_ECPubKey2NamedGroup(
1553     const SECKEYPublicKey *pubKey);
1554 
1555 extern const sslNamedGroupDef *ssl_GetECGroupForServerSocket(sslSocket *ss);
1556 extern void ssl_FilterSupportedGroups(sslSocket *ss);
1557 
1558 extern SECStatus ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool on);
1559 extern SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *on);
1560 
1561 extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on);
1562 extern SECStatus ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *on);
1563 
1564 extern SECStatus ssl3_SetPolicy(ssl3CipherSuite which, PRInt32 policy);
1565 extern SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *policy);
1566 
1567 extern void ssl3_InitSocketPolicy(sslSocket *ss);
1568 
1569 extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache);
1570 extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b,
1571                                              PRUint32 length,
1572                                              PRBool endOfRecord);
1573 
1574 extern void ssl3_DestroySSL3Info(sslSocket *ss);
1575 
1576 extern SECStatus ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b,
1577                                        PRUint32 *length,
1578                                        SSL3ProtocolVersion *version);
1579 extern SECStatus ssl3_NegotiateVersion(sslSocket *ss,
1580                                        SSL3ProtocolVersion peerVersion,
1581                                        PRBool allowLargerPeerVersion);
1582 extern SECStatus ssl_ClientSetCipherSuite(sslSocket *ss,
1583                                           SSL3ProtocolVersion version,
1584                                           ssl3CipherSuite suite,
1585                                           PRBool initHashes);
1586 
1587 extern SECStatus ssl_GetPeerInfo(sslSocket *ss);
1588 
1589 /* ECDH functions */
1590 extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket *ss,
1591                                                 SECKEYPublicKey *svrPubKey);
1592 extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss,
1593                                                   PRUint8 *b, PRUint32 length);
1594 extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss,
1595                                                   PRUint8 *b, PRUint32 length,
1596                                                   sslKeyPair *serverKeys);
1597 extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss);
1598 extern SECStatus ssl_ImportECDHKeyShare(
1599     SECKEYPublicKey *peerKey,
1600     PRUint8 *b, PRUint32 length, const sslNamedGroupDef *curve);
1601 
1602 extern SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1603                                            PRUint8 *hashBuf,
1604                                            unsigned int bufLen,
1605                                            SSL3Hashes *hashes);
1606 extern SECStatus ssl3_AppendSignatureAndHashAlgorithm(
1607     sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash);
1608 extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes,
1609                                        PRUint8 **b, PRUint32 *length);
1610 extern SECStatus ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num,
1611                                              PRUint32 bytes, PRUint8 **b,
1612                                              PRUint32 *length);
1613 extern SECStatus ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num,
1614                                                PRUint32 bytes, PRUint8 **b,
1615                                                PRUint32 *length);
1616 extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i,
1617                                                PRUint32 bytes, PRUint8 **b,
1618                                                PRUint32 *length);
1619 extern SECStatus ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
1620                                              PRBool isTls13,
1621                                              SSLSignatureScheme *scheme);
1622 extern PRBool ssl_SignatureSchemeEnabled(const sslSocket *ss,
1623                                          SSLSignatureScheme scheme);
1624 extern PRBool ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme);
1625 extern SECStatus ssl_CheckSignatureSchemeConsistency(
1626     sslSocket *ss, SSLSignatureScheme scheme, CERTSubjectPublicKeyInfo *spki);
1627 extern SECStatus ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
1628                                            SSLSignatureScheme **schemesOut,
1629                                            unsigned int *numSchemesOut,
1630                                            unsigned char **b,
1631                                            unsigned int *len);
1632 extern SECStatus ssl_ConsumeSignatureScheme(
1633     sslSocket *ss, PRUint8 **b, PRUint32 *length, SSLSignatureScheme *out);
1634 extern SECStatus ssl3_SignHashesWithPrivKey(SSL3Hashes *hash,
1635                                             SECKEYPrivateKey *key,
1636                                             SSLSignatureScheme scheme,
1637                                             PRBool isTls,
1638                                             SECItem *buf);
1639 extern SECStatus ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash,
1640                                  SECKEYPrivateKey *key, SECItem *buf);
1641 extern SECStatus ssl_VerifySignedHashesWithPubKey(sslSocket *ss,
1642                                                   SECKEYPublicKey *spki,
1643                                                   SSLSignatureScheme scheme,
1644                                                   SSL3Hashes *hash,
1645                                                   SECItem *buf);
1646 extern SECStatus ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme,
1647                                          SSL3Hashes *hash, SECItem *buf);
1648 extern SECStatus ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
1649                                          PK11SymKey *secret);
1650 extern void ssl3_FreeSniNameArray(TLSExtensionData *xtnData);
1651 
1652 /* Hello Extension related routines. */
1653 extern void ssl3_SetSIDSessionTicket(sslSessionID *sid,
1654                                      /*in/out*/ NewSessionTicket *session_ticket);
1655 SECStatus ssl3_EncodeSessionTicket(sslSocket *ss,
1656                                    const NewSessionTicket *ticket,
1657                                    const PRUint8 *appToken,
1658                                    unsigned int appTokenLen,
1659                                    PK11SymKey *secret, SECItem *ticket_data);
1660 SECStatus SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
1661                                    unsigned int tokenLen);
1662 
1663 SECStatus ssl_MaybeSetSelfEncryptKeyPair(const sslKeyPair *keyPair);
1664 SECStatus ssl_GetSelfEncryptKeys(sslSocket *ss, unsigned char *keyName,
1665                                  PK11SymKey **encKey, PK11SymKey **macKey);
1666 void ssl_ResetSelfEncryptKeys();
1667 
1668 extern SECStatus ssl3_ValidateAppProtocol(const unsigned char *data,
1669                                           unsigned int length);
1670 
1671 /* Construct a new NSPR socket for the app to use */
1672 extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
1673 extern void ssl_FreePRSocket(PRFileDesc *fd);
1674 
1675 /* Internal config function so SSL3 can initialize the present state of
1676  * various ciphers */
1677 extern unsigned int ssl3_config_match_init(sslSocket *);
1678 
1679 /* Return PR_TRUE if suite is usable.  This if the suite is permitted by policy,
1680  * enabled, has a certificate (as needed), has a viable key agreement method, is
1681  * usable with the negotiated TLS version, and is otherwise usable. */
1682 PRBool ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1683                          const SSLVersionRange *vrange, const sslSocket *ss);
1684 
1685 /* calls for accessing wrapping keys across processes. */
1686 extern SECStatus
1687 ssl_GetWrappingKey(unsigned int symWrapMechIndex,
1688                    unsigned int wrapKeyIndex, SSLWrappedSymWrappingKey *wswk);
1689 
1690 /* The caller passes in the new value it wants
1691  * to set.  This code tests the wrapped sym key entry in the file on disk.
1692  * If it is uninitialized, this function writes the caller's value into
1693  * the disk entry, and returns false.
1694  * Otherwise, it overwrites the caller's wswk with the value obtained from
1695  * the disk, and returns PR_TRUE.
1696  * This is all done while holding the locks/semaphores necessary to make
1697  * the operation atomic.
1698  */
1699 extern SECStatus
1700 ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk);
1701 
1702 /* get rid of the symmetric wrapping key references. */
1703 extern SECStatus SSL3_ShutdownServerCache(void);
1704 
1705 extern SECStatus ssl_InitSymWrapKeysLock(void);
1706 
1707 extern SECStatus ssl_FreeSymWrapKeysLock(void);
1708 
1709 extern SECStatus ssl_InitSessionCacheLocks(PRBool lazyInit);
1710 
1711 extern SECStatus ssl_FreeSessionCacheLocks(void);
1712 
1713 CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg);
1714 SECStatus ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
1715                                          PRUint16 version, PRUint16 *suitep);
1716 SECStatus ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
1717                                     PRBool initHashes);
1718 SECStatus ssl3_InitHandshakeHashes(sslSocket *ss);
1719 void ssl3_CoalesceEchHandshakeHashes(sslSocket *ss);
1720 SECStatus ssl3_ServerCallSNICallback(sslSocket *ss);
1721 SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
1722 SECStatus ssl3_CompleteHandleCertificate(sslSocket *ss,
1723                                          PRUint8 *b, PRUint32 length);
1724 void ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode);
1725 SECStatus ssl3_HandleNoCertificate(sslSocket *ss);
1726 SECStatus ssl3_SendEmptyCertificate(sslSocket *ss);
1727 void ssl3_CleanupPeerCerts(sslSocket *ss);
1728 SECStatus ssl3_SendCertificateStatus(sslSocket *ss);
1729 SECStatus ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey);
1730 SECStatus ssl3_HandleServerSpki(sslSocket *ss);
1731 SECStatus ssl3_AuthCertificate(sslSocket *ss);
1732 SECStatus ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b,
1733                                     PRUint32 length);
1734 SECStatus ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool forCert,
1735                              sslBuffer *buf);
1736 SECStatus ssl3_EncodeFilteredSigAlgs(const sslSocket *ss,
1737                                      const SSLSignatureScheme *schemes,
1738                                      PRUint32 numSchemes, sslBuffer *buf);
1739 SECStatus ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 minVersion, PRBool disableRsae, PRBool forCert,
1740                              unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
1741                              unsigned int *numFilteredSchemes);
1742 SECStatus ssl_GetCertificateRequestCAs(const sslSocket *ss,
1743                                        unsigned int *calenp,
1744                                        const SECItem **namesp,
1745                                        unsigned int *nnamesp);
1746 SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b,
1747                                           PRUint32 *length, CERTDistNames *ca_list);
1748 SECStatus ssl3_CompleteHandleCertificateRequest(
1749     sslSocket *ss, const SSLSignatureScheme *signatureSchemes,
1750     unsigned int signatureSchemeCount, CERTDistNames *ca_list);
1751 SECStatus ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
1752                                    const sslBuffer *extensionBuf,
1753                                    sslBuffer *messageBuf);
1754 SECStatus ssl3_SendServerHello(sslSocket *ss);
1755 SECStatus ssl3_SendChangeCipherSpecsInt(sslSocket *ss);
1756 SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss,
1757                                       ssl3CipherSpec *spec,
1758                                       SSL3Hashes *hashes,
1759                                       PRUint32 sender);
1760 SECStatus ssl_CreateECDHEphemeralKeyPair(const sslSocket *ss,
1761                                          const sslNamedGroupDef *ecGroup,
1762                                          sslEphemeralKeyPair **keyPair);
1763 SECStatus ssl_CreateStaticECDHEKey(sslSocket *ss,
1764                                    const sslNamedGroupDef *ecGroup);
1765 SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
1766 SECStatus ssl3_GetNewRandom(SSL3Random random);
1767 PK11SymKey *ssl3_GetWrappingKey(sslSocket *ss,
1768                                 PK11SlotInfo *masterSecretSlot,
1769                                 CK_MECHANISM_TYPE masterWrapMech,
1770                                 void *pwArg);
1771 SECStatus ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid,
1772                                PK11SymKey *secret);
1773 const ssl3CipherSuiteDef *ssl_LookupCipherSuiteDef(ssl3CipherSuite suite);
1774 const ssl3CipherSuiteCfg *ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite,
1775                                                    const ssl3CipherSuiteCfg *suites);
1776 PRBool ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
1777                                               const SSLVersionRange *vrange);
1778 
1779 SECStatus ssl3_SelectServerCert(sslSocket *ss);
1780 SECStatus ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey,
1781                                        PRBool *supportsRsaPss);
1782 SECStatus ssl_PickSignatureScheme(sslSocket *ss,
1783                                   CERTCertificate *cert,
1784                                   SECKEYPublicKey *pubKey,
1785                                   SECKEYPrivateKey *privKey,
1786                                   const SSLSignatureScheme *peerSchemes,
1787                                   unsigned int peerSchemeCount,
1788                                   PRBool requireSha1);
1789 SECOidTag ssl3_HashTypeToOID(SSLHashType hashType);
1790 SECOidTag ssl3_AuthTypeToOID(SSLAuthType hashType);
1791 SSLHashType ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme);
1792 SSLAuthType ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme);
1793 
1794 SECStatus ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes);
1795 SECStatus ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
1796                                  SSLContentType contentType, sslBuffer *wrBuf,
1797                                  PRBool *needsLength);
1798 PRBool ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
1799                                 PRBool isTls13);
1800 
1801 /* Pull in DTLS functions */
1802 #include "dtlscon.h"
1803 
1804 /* Pull in TLS 1.3 functions */
1805 #include "tls13con.h"
1806 #include "dtls13con.h"
1807 
1808 /********************** misc calls *********************/
1809 
1810 #ifdef DEBUG
1811 extern void ssl3_CheckCipherSuiteOrderConsistency();
1812 #endif
1813 
1814 extern int ssl_MapLowLevelError(int hiLevelError);
1815 
1816 PRTime ssl_Time(const sslSocket *ss);
1817 PRBool ssl_TicketTimeValid(const sslSocket *ss, const NewSessionTicket *ticket);
1818 
1819 extern void SSL_AtomicIncrementLong(long *x);
1820 
1821 SECStatus ssl3_ApplyNSSPolicy(void);
1822 
1823 extern SECStatus
1824 ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
1825                             const char *label, unsigned int labelLen,
1826                             const unsigned char *val, unsigned int valLen,
1827                             unsigned char *out, unsigned int outLen);
1828 
1829 extern void
1830 ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret);
1831 
1832 PRBool ssl_AlpnTagAllowed(const sslSocket *ss, const SECItem *tag);
1833 
1834 #ifdef TRACE
1835 #define SSL_TRACE(msg) ssl_Trace msg
1836 #else
1837 #define SSL_TRACE(msg)
1838 #endif
1839 
1840 void ssl_Trace(const char *format, ...);
1841 
1842 void ssl_CacheExternalToken(sslSocket *ss);
1843 SECStatus ssl_DecodeResumptionToken(sslSessionID *sid, const PRUint8 *encodedTicket,
1844                                     PRUint32 encodedTicketLen);
1845 PRBool ssl_IsResumptionTokenUsable(sslSocket *ss, sslSessionID *sid);
1846 
1847 /* unwrap helper function to handle the case where the wrapKey doesn't wind
1848  *  * up in the correct token for the master secret */
1849 PK11SymKey *ssl_unwrapSymKey(PK11SymKey *wrapKey,
1850                              CK_MECHANISM_TYPE wrapType, SECItem *param,
1851                              SECItem *wrappedKey,
1852                              CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1853                              int keySize, CK_FLAGS keyFlags, void *pinArg);
1854 
1855 /* determine if the current ssl connection is operating in FIPS mode */
1856 PRBool ssl_isFIPS(sslSocket *ss);
1857 
1858 /* Experimental APIs. Remove when stable. */
1859 
1860 SECStatus SSLExp_SetResumptionTokenCallback(PRFileDesc *fd,
1861                                             SSLResumptionTokenCallback cb,
1862                                             void *ctx);
1863 SECStatus SSLExp_SetResumptionToken(PRFileDesc *fd, const PRUint8 *token,
1864                                     unsigned int len);
1865 
1866 SECStatus SSLExp_GetResumptionTokenInfo(const PRUint8 *tokenData, unsigned int tokenLen,
1867                                         SSLResumptionTokenInfo *token, unsigned int version);
1868 
1869 SECStatus SSLExp_DestroyResumptionTokenInfo(SSLResumptionTokenInfo *token);
1870 
1871 SECStatus SSLExp_SecretCallback(PRFileDesc *fd, SSLSecretCallback cb,
1872                                 void *arg);
1873 SECStatus SSLExp_RecordLayerWriteCallback(PRFileDesc *fd,
1874                                           SSLRecordWriteCallback write,
1875                                           void *arg);
1876 SECStatus SSLExp_RecordLayerData(PRFileDesc *fd, PRUint16 epoch,
1877                                  SSLContentType contentType,
1878                                  const PRUint8 *data, unsigned int len);
1879 SECStatus SSLExp_GetCurrentEpoch(PRFileDesc *fd, PRUint16 *readEpoch,
1880                                  PRUint16 *writeEpoch);
1881 
1882 #define SSLResumptionTokenVersion 2
1883 
1884 SECStatus SSLExp_MakeAead(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *secret,
1885                           const char *labelPrefix, unsigned int labelPrefixLen,
1886                           SSLAeadContext **ctx);
1887 
1888 SECStatus SSLExp_MakeVariantAead(PRUint16 version, PRUint16 cipherSuite, SSLProtocolVariant variant,
1889                                  PK11SymKey *secret, const char *labelPrefix,
1890                                  unsigned int labelPrefixLen, SSLAeadContext **ctx);
1891 SECStatus SSLExp_DestroyAead(SSLAeadContext *ctx);
1892 SECStatus SSLExp_AeadEncrypt(const SSLAeadContext *ctx, PRUint64 counter,
1893                              const PRUint8 *aad, unsigned int aadLen,
1894                              const PRUint8 *plaintext, unsigned int plaintextLen,
1895                              PRUint8 *out, unsigned int *outLen, unsigned int maxOut);
1896 SECStatus SSLExp_AeadDecrypt(const SSLAeadContext *ctx, PRUint64 counter,
1897                              const PRUint8 *aad, unsigned int aadLen,
1898                              const PRUint8 *plaintext, unsigned int plaintextLen,
1899                              PRUint8 *out, unsigned int *outLen, unsigned int maxOut);
1900 
1901 SECStatus SSLExp_HkdfExtract(PRUint16 version, PRUint16 cipherSuite,
1902                              PK11SymKey *salt, PK11SymKey *ikm, PK11SymKey **keyp);
1903 SECStatus SSLExp_HkdfExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
1904                                  const PRUint8 *hsHash, unsigned int hsHashLen,
1905                                  const char *label, unsigned int labelLen,
1906                                  PK11SymKey **key);
1907 SECStatus SSLExp_HkdfVariantExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
1908                                         const PRUint8 *hsHash, unsigned int hsHashLen,
1909                                         const char *label, unsigned int labelLen,
1910                                         SSLProtocolVariant variant, PK11SymKey **key);
1911 SECStatus
1912 SSLExp_HkdfExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
1913                                const PRUint8 *hsHash, unsigned int hsHashLen,
1914                                const char *label, unsigned int labelLen,
1915                                CK_MECHANISM_TYPE mech, unsigned int keySize,
1916                                PK11SymKey **keyp);
1917 SECStatus
1918 SSLExp_HkdfVariantExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
1919                                       const PRUint8 *hsHash, unsigned int hsHashLen,
1920                                       const char *label, unsigned int labelLen,
1921                                       CK_MECHANISM_TYPE mech, unsigned int keySize,
1922                                       SSLProtocolVariant variant, PK11SymKey **keyp);
1923 
1924 SECStatus SSLExp_SetDtls13VersionWorkaround(PRFileDesc *fd, PRBool enabled);
1925 
1926 SECStatus SSLExp_SetTimeFunc(PRFileDesc *fd, SSLTimeFunc f, void *arg);
1927 
1928 extern SECStatus ssl_CreateMaskingContextInner(PRUint16 version, PRUint16 cipherSuite,
1929                                                SSLProtocolVariant variant,
1930                                                PK11SymKey *secret,
1931                                                const char *label,
1932                                                unsigned int labelLen,
1933                                                SSLMaskingContext **ctx);
1934 
1935 extern SECStatus ssl_CreateMaskInner(SSLMaskingContext *ctx, const PRUint8 *sample,
1936                                      unsigned int sampleLen, PRUint8 *outMask,
1937                                      unsigned int maskLen);
1938 
1939 extern SECStatus ssl_DestroyMaskingContextInner(SSLMaskingContext *ctx);
1940 
1941 SECStatus SSLExp_CreateMaskingContext(PRUint16 version, PRUint16 cipherSuite,
1942                                       PK11SymKey *secret,
1943                                       const char *label,
1944                                       unsigned int labelLen,
1945                                       SSLMaskingContext **ctx);
1946 
1947 SECStatus SSLExp_CreateVariantMaskingContext(PRUint16 version, PRUint16 cipherSuite,
1948                                              SSLProtocolVariant variant,
1949                                              PK11SymKey *secret,
1950                                              const char *label,
1951                                              unsigned int labelLen,
1952                                              SSLMaskingContext **ctx);
1953 
1954 SECStatus SSLExp_CreateMask(SSLMaskingContext *ctx, const PRUint8 *sample,
1955                             unsigned int sampleLen, PRUint8 *mask,
1956                             unsigned int len);
1957 
1958 SECStatus SSLExp_DestroyMaskingContext(SSLMaskingContext *ctx);
1959 
1960 SECStatus SSLExp_EnableTls13GreaseEch(PRFileDesc *fd, PRBool enabled);
1961 
1962 SECStatus SSLExp_EnableTls13BackendEch(PRFileDesc *fd, PRBool enabled);
1963 SECStatus SSLExp_CallExtensionWriterOnEchInner(PRFileDesc *fd, PRBool enabled);
1964 
1965 SEC_END_PROTOS
1966 
1967 #if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
1968 #define SSL_GETPID getpid
1969 #elif defined(WIN32)
1970 extern int __cdecl _getpid(void);
1971 #define SSL_GETPID _getpid
1972 #else
1973 #define SSL_GETPID() 0
1974 #endif
1975 
1976 #endif /* __sslimpl_h_ */
1977