Bug Summary

File:root/firefox-clang/security/nss/lib/ssl/sslimpl.h
Warning:line 662, column 16
Excessive padding in 'struct SSL3HandshakeStateStr' (57 padding bytes, where 1 is optimal). Optimal fields order: md5, sha, shaEchInner, shaPostHandshake, kea_def, suite_def, msg_len, clientAuthSignatureSchemes, restartTarget, rtTimer, ackTimer, hdTimer, currentSecret, resumptionMasterSecret, dheSecret, clientEarlyTrafficSecret, clientHsTrafficSecret, serverHsTrafficSecret, clientTrafficSecret, serverTrafficSecret, earlyExporterSecret, exporterSecret, rttEstimate, echHpkeCtx, echPublicName, grease, dtlsHandhakeKeyUpdateMessage, chExtensionPermutation, remoteExtensions, echOuterExtensions, lastMessageFlight, cipherSpecs, bufferedEarlyData, psks, dtlsSentHandshake, dtlsRcvdHandshake, messages, echInnerMessages, msg_body, recvdFragments, cookie, srvVirtName, fakeSid, greaseEchBuf, dtls13ClientMessageBuffer, newSessionTicket, timers, ws, hashType, signatureScheme, header_bytes, msg_type, isResuming, sendingSCSV, receivedNewSessionTicket, clientCertificatePending, clientAuthSignatureSchemesLen, authCertificatePending, canFalseStart, preliminaryInfo, recvdHighWater, isKeyUpdateInProgress, allowPreviousEpoch, rtRetries, zeroRttState, zeroRttIgnore, helloRetry, dtlsReceivedHVR, receivedCcs, rejectCcs, clientCertRequested, endOfFlight, echAccepted, echDecided, echInvalidExtension, keyUpdateDeferred, deferredKeyUpdateRequest, kea_def_mutable, cipher_suite, finishedBytes, sendMessageSeq, maxMessageSent, recvMessageSeq, zeroRttSuite, ticketNonce, greaseEchSize, server_random, client_random, client_inner_random, finishedMsgs, consider reordering the fields or adding explicit padding members

Annotated Source Code

Press '?' to see keyboard shortcuts

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