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