tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

sslimpl.h (84010B)


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