Bug Summary

File:root/firefox-clang/security/nss/lib/ssl/sslimpl.h
Warning:line 1068, column 8
Excessive padding in 'struct sslSocketStr' (34 padding bytes, where 2 is optimal). Optimal fields order: fd, ops, now, nowArg, clientAuthRequested, delayDisabled, firstHsDone, enoughFirstHsDone, handshakeBegun, lastWriteBlocked, recvdCloseNotify, TCPconnected, appDataBuffered, peerRequestedProtection, url, handshake, peerID, authCertificate, authCertificateArg, getClientAuthData, getClientAuthDataArg, sniSocketConfig, sniSocketConfigArg, alertReceivedCallback, alertReceivedCallbackArg, alertSentCallback, alertSentCallbackArg, handleBadCert, badCertArg, handshakeCallback, handshakeCallbackData, canFalseStartCallback, canFalseStartCallbackData, pkcs11PinArg, nextProtoCallback, nextProtoArg, hrrCallback, hrrCallbackArg, resumptionTokenCallback, resumptionTokenContext, secretCallback, secretCallbackArg, recordWriteCallback, recordWriteCallbackArg, recvLock, sendLock, recvBufLock, xmitBufLock, firstHandshakeLock, ssl3HandshakeLock, specLock, dbHandle, writerThread, echPubKey, echPrivKey, antiReplay, psk, ephemeralKeyPairs, extensionHooks, serverCerts, echConfigs, saveBuf, pendingBuf, opt, gs, sec, namedGroupPreferences, xtnData, ssl3, rTimeout, wTimeout, cTimeout, additionalShares, statelessResume, protocolVariant, cipherSuites, version, clientHelloVersion, shutdownHow, vrange, 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-11-12-001017-1011516-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 unsigned int enablePlaintextResumptionExport : 1;
319} sslOptions;
320
321#define SSL_LOCK_RANK_SPEC255 255
322
323/* These are the valid values for shutdownHow.
324** These values are each 1 greater than the NSPR values, and the code
325** depends on that relation to efficiently convert PR_SHUTDOWN values
326** into ssl_SHUTDOWN values. These values use one bit for read, and
327** another bit for write, and can be used as bitmasks.
328*/
329#define ssl_SHUTDOWN_NONE0 0 /* NOT shutdown at all */
330#define ssl_SHUTDOWN_RCV1 1 /* PR_SHUTDOWN_RCV +1 */
331#define ssl_SHUTDOWN_SEND2 2 /* PR_SHUTDOWN_SEND +1 */
332#define ssl_SHUTDOWN_BOTH3 3 /* PR_SHUTDOWN_BOTH +1 */
333
334/*
335** A gather object. Used to read some data until a count has been
336** satisfied. Primarily for support of async sockets.
337** Everything in here is protected by the recvBufLock.
338*/
339struct sslGatherStr {
340 int state; /* see GS_ values below. */
341
342 /* "buf" holds received plaintext SSL records, after decrypt and MAC check.
343 * recv'd ciphertext records are put in inbuf (see below), then decrypted
344 * into buf.
345 */
346 sslBuffer buf; /*recvBufLock*/
347
348 /* number of bytes previously read into hdr or inbuf.
349 ** (offset - writeOffset) is the number of ciphertext bytes read in but
350 ** not yet deciphered.
351 */
352 unsigned int offset;
353
354 /* number of bytes to read in next call to ssl_DefRecv (recv) */
355 unsigned int remainder;
356
357 /* DoRecv uses the next two values to extract application data.
358 ** The difference between writeOffset and readOffset is the amount of
359 ** data available to the application. Note that the actual offset of
360 ** the data in "buf" is recordOffset (above), not readOffset.
361 ** In the current implementation, this is made available before the
362 ** MAC is checked!!
363 */
364 unsigned int readOffset; /* Spot where DATA reader (e.g. application
365 ** or handshake code) will read next.
366 ** Always zero for SSl3 application data.
367 */
368 /* offset in buf/inbuf/hdr into which new data will be read from socket. */
369 unsigned int writeOffset;
370
371 /* Buffer for ssl3 to read (encrypted) data from the socket */
372 sslBuffer inbuf; /*recvBufLock*/
373
374 /* The ssl[23]_GatherData functions read data into this buffer, rather
375 ** than into buf or inbuf, while in the GS_HEADER state.
376 ** The portion of the SSL record header put here always comes off the wire
377 ** as plaintext, never ciphertext.
378 ** For SSL3/TLS, the plaintext portion is 5 bytes long. For DTLS it
379 ** varies based on version and header type.
380 */
381 unsigned char hdr[13];
382 unsigned int hdrLen;
383
384 /* Buffer for DTLS data read off the wire as a single datagram */
385 sslBuffer dtlsPacket;
386
387 /* the start of the buffered DTLS record in dtlsPacket */
388 unsigned int dtlsPacketOffset;
389
390 /* tracks whether we've seen a v3-type record before and must reject
391 * any further v2-type records. */
392 PRBool rejectV2Records;
393};
394
395/* sslGather.state */
396#define GS_INIT0 0
397#define GS_HEADER1 1
398#define GS_DATA2 2
399
400#define WRAPPED_MASTER_SECRET_SIZE48 48
401
402typedef struct {
403 PRUint8 wrapped_master_secret[WRAPPED_MASTER_SECRET_SIZE48];
404 PRUint8 wrapped_master_secret_len;
405 PRUint8 resumable;
406 PRUint8 extendedMasterSecretUsed;
407} ssl3SidKeys; /* 52 bytes */
408
409typedef enum { never_cached,
410 in_client_cache,
411 in_server_cache,
412 invalid_cache, /* no longer in any cache. */
413 in_external_cache
414} Cached;
415
416#include "sslcert.h"
417
418struct sslSessionIDStr {
419 /* The global cache lock must be held when accessing these members when the
420 * sid is in any cache.
421 */
422 sslSessionID *next; /* chain used for client sockets, only */
423 Cached cached;
424 int references;
425 PRTime lastAccessTime;
426
427 /* The rest of the members, except for the members of u.ssl3.locked, may
428 * be modified only when the sid is not in any cache.
429 */
430
431 /* DER of the peer's end-entity certificate. Owned by the sid; empty if
432 * the peer did not send a certificate. */
433 SECItem peerCertDER;
434 SECItemArray peerCertStatus; /* client only */
435 const char *peerID; /* client only */
436 const char *urlSvrName; /* client only */
437 const sslNamedGroupDef *namedCurve; /* (server) for certificate lookup */
438 CERTCertificate *localCert;
439
440 PRIPv6Addr addr;
441 PRUint16 port;
442
443 SSL3ProtocolVersion version;
444
445 PRTime creationTime;
446 PRTime expirationTime;
447
448 SSLAuthType authType;
449 PRUint32 authKeyBits;
450 SSLKEAType keaType;
451 PRUint32 keaKeyBits;
452 SSLNamedGroup keaGroup;
453 SSLSignatureScheme sigScheme;
454
455 union {
456 struct {
457 /* values that are copied into the server's on-disk SID cache. */
458 PRUint8 sessionIDLength;
459 PRUint8 sessionID[SSL3_SESSIONID_BYTES32];
460
461 ssl3CipherSuite cipherSuite;
462 PRUint8 policy;
463 ssl3SidKeys keys;
464 /* mechanism used to wrap master secret */
465 CK_MECHANISM_TYPE masterWrapMech;
466
467 /* The following values pertain to the slot that wrapped the
468 ** master secret. (used only in client)
469 */
470 SECMODModuleID masterModuleID;
471 /* what module wrapped the master secret */
472 CK_SLOT_ID masterSlotID;
473 PRUint16 masterWrapIndex;
474 /* what's the key index for the wrapping key */
475 PRUint16 masterWrapSeries;
476 /* keep track of the slot series, so we don't
477 * accidently try to use new keys after the
478 * card gets removed and replaced.*/
479
480 /* The following values pertain to the slot that did the signature
481 ** for client auth. (used only in client)
482 */
483 SECMODModuleID clAuthModuleID;
484 CK_SLOT_ID clAuthSlotID;
485 PRUint16 clAuthSeries;
486
487 char masterValid;
488 char clAuthValid;
489
490 SECItem srvName;
491
492 /* Signed certificate timestamps received in a TLS extension.
493 ** (used only in client).
494 */
495 SECItem signedCertTimestamps;
496
497 /* The ALPN value negotiated in the original connection.
498 * Used for TLS 1.3. */
499 SECItem alpnSelection;
500
501 /* This lock is lazily initialized by CacheSID when a sid is first
502 * cached. Before then, there is no need to lock anything because
503 * the sid isn't being shared by anything.
504 */
505 PRRWLock *lock;
506
507 /* The lock must be held while reading or writing these members
508 * because they change while the sid is cached.
509 */
510 struct {
511 /* The session ticket, if we have one, is sent as an extension
512 * in the ClientHello message. This field is used only by
513 * clients. It is protected by lock when lock is non-null
514 * (after the sid has been added to the client session cache).
515 */
516 NewSessionTicket sessionTicket;
517 } locked;
518 } ssl3;
519 } u;
520};
521
522struct ssl3CipherSuiteDefStr {
523 ssl3CipherSuite cipher_suite;
524 SSL3BulkCipher bulk_cipher_alg;
525 SSL3MACAlgorithm mac_alg;
526 SSL3KeyExchangeAlgorithm key_exchange_alg;
527 SSLHashType prf_hash;
528};
529
530/*
531** There are tables of these, all const.
532*/
533typedef struct {
534 /* An identifier for this struct. */
535 SSL3KeyExchangeAlgorithm kea;
536 /* The type of key exchange used by the cipher suite. */
537 SSLKEAType exchKeyType;
538 /* If the cipher suite uses a signature, the type of key used in the
539 * signature. */
540 KeyType signKeyType;
541 /* In most cases, cipher suites depend on their signature type for
542 * authentication, ECDH certificates being the exception. */
543 SSLAuthType authKeyType;
544 /* True if the key exchange for the suite is ephemeral. Or to be more
545 * precise: true if the ServerKeyExchange message is always required. */
546 PRBool ephemeral;
547 /* An OID describing the key exchange */
548 SECOidTag oid;
549} ssl3KEADef;
550
551typedef enum {
552 ssl_0rtt_none, /* 0-RTT not present */
553 ssl_0rtt_sent, /* 0-RTT sent (no decision yet) */
554 ssl_0rtt_accepted, /* 0-RTT sent and accepted */
555 ssl_0rtt_ignored, /* 0-RTT sent but rejected/ignored */
556 ssl_0rtt_done /* 0-RTT accepted, but finished */
557} sslZeroRttState;
558
559typedef enum {
560 ssl_0rtt_ignore_none, /* not ignoring */
561 ssl_0rtt_ignore_trial, /* ignoring with trial decryption */
562 ssl_0rtt_ignore_hrr /* ignoring until ClientHello (due to HRR) */
563} sslZeroRttIgnore;
564
565typedef enum {
566 idle_handshake,
567 wait_client_hello,
568 wait_end_of_early_data,
569 wait_client_cert,
570 wait_client_key,
571 wait_cert_verify,
572 wait_change_cipher,
573 wait_finished,
574 wait_server_hello,
575 wait_certificate_status,
576 wait_server_cert,
577 wait_server_key,
578 wait_cert_request,
579 wait_hello_done,
580 wait_new_session_ticket,
581 wait_encrypted_extensions,
582 wait_invalid /* Invalid value. There is no handshake message "invalid". */
583} SSL3WaitState;
584
585typedef enum {
586 client_hello_initial, /* The first attempt. */
587 client_hello_retry, /* If we receive HelloRetryRequest. */
588 client_hello_retransmit, /* In DTLS, if we receive HelloVerifyRequest. */
589 client_hello_renegotiation /* A renegotiation attempt. */
590} sslClientHelloType;
591
592typedef struct SessionTicketDataStr SessionTicketData;
593
594typedef SECStatus (*sslRestartTarget)(sslSocket *);
595
596/*
597** A DTLS queued message (potentially to be retransmitted)
598*/
599typedef struct DTLSQueuedMessageStr {
600 PRCList link; /* The linked list link */
601 ssl3CipherSpec *cwSpec; /* The cipher spec to use, null for none */
602 SSLContentType type; /* The message type */
603 unsigned char *data; /* The data */
604 PRUint32 len; /* The data length */
605} DTLSQueuedMessage;
606
607struct TLS13KeyShareEntryStr {
608 PRCList link; /* The linked list link */
609 const sslNamedGroupDef *group; /* The group for the entry */
610 SECItem key_exchange; /* The share itself */
611};
612
613typedef struct TLS13EarlyDataStr {
614 PRCList link; /* The linked list link */
615 unsigned int consumed; /* How much has been read. */
616 SECItem data; /* The data */
617} TLS13EarlyData;
618
619typedef enum {
620 handshake_hash_unknown = 0,
621 handshake_hash_combo = 1, /* The MD5/SHA-1 combination */
622 handshake_hash_single = 2, /* A single hash */
623 handshake_hash_record
624} SSL3HandshakeHashType;
625
626// A DTLS Timer.
627typedef void (*DTLSTimerCb)(sslSocket *);
628
629typedef struct {
630 const char *label;
631 DTLSTimerCb cb;
632 PRIntervalTime started;
633 PRUint32 timeout;
634} dtlsTimer;
635
636/* TLS 1.3 client GREASE entry indices. */
637typedef enum {
638 grease_cipher,
639 grease_extension1,
640 grease_extension2,
641 grease_group,
642 grease_sigalg,
643 grease_version,
644 grease_alpn,
645 grease_entries
646} tls13ClientGreaseEntry;
647
648/* TLS 1.3 client GREASE values struct. */
649typedef struct tls13ClientGreaseStr {
650 PRUint16 idx[grease_entries];
651 PRUint8 pskKem;
652} tls13ClientGrease;
653
654/*
655** This is the "hs" member of the "ssl3" struct.
656** This entire struct is protected by ssl3HandshakeLock
657*/
658typedef struct SSL3HandshakeStateStr {
659 SSL3Random server_random;
660 SSL3Random client_random;
661 SSL3Random client_inner_random; /* TLS 1.3 ECH Inner. */
662 SSL3WaitState ws; /* May also contain SSL3WaitState | 0x80 for TLS 1.3 */
663
664 /* This group of members is used for handshake running hashes. */
665 SSL3HandshakeHashType hashType;
666 sslBuffer messages; /* Accumulated handshake messages */
667 sslBuffer echInnerMessages; /* Accumulated ECH Inner handshake messages */
668 /* PKCS #11 mode:
669 * SSL 3.0 - TLS 1.1 use both |md5| and |sha|. |md5| is used for MD5 and
670 * |sha| for SHA-1.
671 * TLS 1.2 and later use only |sha| variants, for SHA-256.
672 * Under normal (non-1.3 ECH) handshakes, only |sha| and |shaPostHandshake|
673 * are used. When doing 1.3 ECH, |sha| contains the transcript hash
674 * corresponding to the outer Client Hello. To facilitate secure retry and
675 * disablement, |shaEchInner|, tracks, in parallel, the transcript hash
676 * corresponding to the inner Client Hello. Once we process the SH
677 * extensions, coalesce into |sha|. */
678 PK11Context *md5;
679 PK11Context *sha;
680 PK11Context *shaEchInner;
681 PK11Context *shaPostHandshake;
682 SSLSignatureScheme signatureScheme;
683 const ssl3KEADef *kea_def;
684 ssl3CipherSuite cipher_suite;
685 const ssl3CipherSuiteDef *suite_def;
686 sslBuffer msg_body; /* protected by recvBufLock */
687 /* partial handshake message from record layer */
688 unsigned int header_bytes;
689 /* number of bytes consumed from handshake */
690 /* message for message type and header length */
691 SSLHandshakeType msg_type;
692 unsigned long msg_len;
693 PRBool isResuming; /* we are resuming (not used in TLS 1.3) */
694 PRBool sendingSCSV; /* instead of empty RI */
695
696 /* The session ticket received in a NewSessionTicket message is temporarily
697 * stored in newSessionTicket until the handshake is finished; then it is
698 * moved to the sid.
699 */
700 PRBool receivedNewSessionTicket;
701 NewSessionTicket newSessionTicket;
702
703 PRUint16 finishedBytes; /* size of single finished below */
704 union {
705 TLSFinished tFinished[2]; /* client, then server */
706 SSL3Finished sFinished[2];
707 PRUint8 data[72];
708 } finishedMsgs;
709
710 /* True when handshake is blocked on client certificate selection */
711 PRBool clientCertificatePending;
712 /* Parameters stored whilst waiting for client certificate */
713 SSLSignatureScheme *clientAuthSignatureSchemes;
714 unsigned int clientAuthSignatureSchemesLen;
715
716 PRBool authCertificatePending;
717 /* Which function should SSL_RestartHandshake* call if we're blocked?
718 * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake,
719 * or ssl3_AlwaysFail */
720 sslRestartTarget restartTarget;
721
722 PRBool canFalseStart; /* Can/did we False Start */
723 /* Which preliminaryinfo values have been set. */
724 PRUint32 preliminaryInfo;
725
726 /* Parsed extensions */
727 PRCList remoteExtensions; /* Parsed incoming extensions */
728 PRCList echOuterExtensions; /* If ECH, hold CHOuter extensions for decompression. */
729
730 /* This group of values is used for DTLS */
731 PRUint16 sendMessageSeq; /* The sending message sequence
732 * number */
733 PRCList lastMessageFlight; /* The last message flight we
734 * sent */
735 PRUint16 maxMessageSent; /* The largest message we sent */
736 PRUint16 recvMessageSeq; /* The receiving message sequence
737 * number */
738 sslBuffer recvdFragments; /* The fragments we have received in
739 * a bitmask */
740 PRInt32 recvdHighWater; /* The high water mark for fragments
741 * received. -1 means no reassembly
742 * in progress. */
743 SECItem cookie; /* The Hello(Retry|Verify)Request cookie. */
744 dtlsTimer timers[3]; /* Holder for timers. */
745 dtlsTimer *rtTimer; /* Retransmit timer. */
746 dtlsTimer *ackTimer; /* Ack timer (DTLS 1.3 only). */
747 dtlsTimer *hdTimer; /* Read cipher holddown timer. */
748
749 /* KeyUpdate state machines */
750 PRBool isKeyUpdateInProgress; /* The status of KeyUpdate -: {true == started, false == finished}. */
751 PRBool allowPreviousEpoch; /* The flag whether the previous epoch messages are allowed or not: {true == allowed, false == forbidden}. */
752
753 PRUint32 rtRetries; /* The retry counter */
754 SECItem srvVirtName; /* for server: name that was negotiated
755 * with a client. For client - is
756 * always set to NULL.*/
757
758 /* This group of values is used for TLS 1.3 and above */
759 PK11SymKey *currentSecret; /* The secret down the "left hand side"
760 * of the TLS 1.3 key schedule. */
761 PK11SymKey *resumptionMasterSecret; /* The resumption_master_secret. */
762 PK11SymKey *dheSecret; /* The (EC)DHE shared secret. */
763 PK11SymKey *clientEarlyTrafficSecret; /* The secret we use for 0-RTT. */
764 PK11SymKey *clientHsTrafficSecret; /* The source keys for handshake */
765 PK11SymKey *serverHsTrafficSecret; /* traffic keys. */
766 PK11SymKey *clientTrafficSecret; /* The source keys for application */
767 PK11SymKey *serverTrafficSecret; /* traffic keys */
768 PK11SymKey *earlyExporterSecret; /* for 0-RTT exporters */
769 PK11SymKey *exporterSecret; /* for exporters */
770 PRCList cipherSpecs; /* The cipher specs in the sequence they
771 * will be applied. */
772 sslZeroRttState zeroRttState; /* Are we doing a 0-RTT handshake? */
773 sslZeroRttIgnore zeroRttIgnore; /* Are we ignoring 0-RTT? */
774 ssl3CipherSuite zeroRttSuite; /* The cipher suite we used for 0-RTT. */
775 PRCList bufferedEarlyData; /* Buffered TLS 1.3 early data
776 * on server.*/
777 PRBool helloRetry; /* True if HelloRetryRequest has been sent
778 * or received. */
779 PRBool dtlsReceivedHVR; /* True if a DTLS HelloVerifyRequest was
780 * 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)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", 833))
; ((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"
, 833)); ((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"
, 833)); } while (0)
\
834 do { \
835 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", 835))
; \
836 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", 836))
; \
837 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"
, 837))
; \
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*/
847struct 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_SUITES4];
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_SCHEMES21];
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_ALGS32];
905 PRUint8 supportedCertCompressionAlgorithmsCount;
906};
907
908/* Ethernet MTU but without subtracting the headers,
909 * so slightly larger than expected */
910#define DTLS_MAX_MTU1500U 1500U
911#define IS_DTLS(ss)(ss->protocolVariant == ssl_variant_datagram) (ss->protocolVariant == ssl_variant_datagram)
912#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)
913#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)
914
915typedef 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
926struct sslKeyPairStr {
927 SECKEYPrivateKey *privKey;
928 SECKEYPublicKey *pubKey;
929 PRInt32 refCount; /* use PR_Atomic calls for this. */
930};
931
932struct sslEphemeralKeyPairStr {
933 PRCList link;
934 const sslNamedGroupDef *group;
935 sslKeyPair *keys;
936 sslKeyPair *kemKeys;
937 SECItem *kemCt;
938};
939
940struct ssl3DHParamsStr {
941 SSLNamedGroup name;
942 SECItem prime; /* p */
943 SECItem base; /* g */
944};
945
946typedef struct SSLWrappedSymWrappingKeyStr {
947 PRUint8 wrappedSymmetricWrappingkey[SSL_MAX_RSA_KEY_BITS8192 / 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
958typedef 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, except where noted per field.
1002*/
1003struct sslConnectInfoStr {
1004 /* outgoing handshakes appended to this. */
1005 sslBuffer sendBuf; /*xmitBufLock*/
1006
1007 PRIPv6Addr peer;
1008 unsigned short port;
1009
1010 /* Assign only with ssl_SetSocketSID and clear only with
1011 * ssl_TakeSocketSID; both swap and release under the session cache lock.
1012 * A thread holding neither handshake lock -- an application calling
1013 * SSL_GetChannelInfo, say -- must read this with ssl_ReferenceSocketSID,
1014 * because the peer can replace the session at any time by renegotiating
1015 * or by sending a new session ticket. */
1016 sslSessionID *sid;
1017};
1018
1019/* Note: The entire content of this struct and whatever it points to gets
1020 * blown away by SSL_ResetHandshake(). This is "sec" as in "ss->sec".
1021 *
1022 * Unless otherwise specified below, the contents of this struct are
1023 * protected by firstHandshakeLock AND ssl3HandshakeLock.
1024 */
1025struct sslSecurityInfoStr {
1026
1027#define SSL_ROLE(ss)(ss->sec.isServer ? "server" : "client") (ss->sec.isServer ? "server" : "client")
1028
1029 PRBool isServer;
1030 sslBuffer writeBuf; /*xmitBufLock*/
1031
1032 CERTCertificate *localCert;
1033 /* The peer's end-entity certificate, held as DER rather than as a
1034 * CERTCertificate so that the handshake does not have to instantiate a
1035 * CERTCertificate or consult a certificate database. |peerCertSPKI| is
1036 * the subjectPublicKeyInfo parsed out of |peerCertDER| when it was set,
1037 * so that the certificate is only ever decoded once. Both are owned by
1038 * this struct and are set and cleared together, by
1039 * ssl_SetPeerCertificate() and ssl_ClearPeerCertificate(); both are empty
1040 * if the peer did not send a certificate. The (few) places that have to
1041 * hand a CERTCertificate to an application build one with
1042 * CERT_NewTempCertificate(). */
1043 SECItem peerCertDER;
1044 CERTSubjectPublicKeyInfo *peerCertSPKI;
1045 /* The peer's ephemeral key from ServerKeyExchange -- not the key in
1046 * |peerCertDER|. */
1047 SECKEYPublicKey *peerKey;
1048
1049 SSLAuthType authType;
1050 PRUint32 authKeyBits;
1051 SSLSignatureScheme signatureScheme;
1052 SSLKEAType keaType;
1053 PRUint32 keaKeyBits;
1054 const sslNamedGroupDef *keaGroup;
1055 const sslNamedGroupDef *originalKeaGroup;
1056 /* The selected certificate (for servers only). */
1057 const sslServerCert *serverCert;
1058
1059 /* These are used during a connection handshake */
1060 sslConnectInfo ci;
1061};
1062
1063/*
1064** SSL Socket struct
1065**
1066** Protection: XXX
1067*/
1068struct sslSocketStr {
Excessive padding in 'struct sslSocketStr' (34 padding bytes, where 2 is optimal). Optimal fields order: fd, ops, now, nowArg, clientAuthRequested, delayDisabled, firstHsDone, enoughFirstHsDone, handshakeBegun, lastWriteBlocked, recvdCloseNotify, TCPconnected, appDataBuffered, peerRequestedProtection, url, handshake, peerID, authCertificate, authCertificateArg, getClientAuthData, getClientAuthDataArg, sniSocketConfig, sniSocketConfigArg, alertReceivedCallback, alertReceivedCallbackArg, alertSentCallback, alertSentCallbackArg, handleBadCert, badCertArg, handshakeCallback, handshakeCallbackData, canFalseStartCallback, canFalseStartCallbackData, pkcs11PinArg, nextProtoCallback, nextProtoArg, hrrCallback, hrrCallbackArg, resumptionTokenCallback, resumptionTokenContext, secretCallback, secretCallbackArg, recordWriteCallback, recordWriteCallbackArg, recvLock, sendLock, recvBufLock, xmitBufLock, firstHandshakeLock, ssl3HandshakeLock, specLock, dbHandle, writerThread, echPubKey, echPrivKey, antiReplay, psk, ephemeralKeyPairs, extensionHooks, serverCerts, echConfigs, saveBuf, pendingBuf, opt, gs, sec, namedGroupPreferences, xtnData, ssl3, rTimeout, wTimeout, cTimeout, additionalShares, statelessResume, protocolVariant, cipherSuites, version, clientHelloVersion, shutdownHow, vrange, consider reordering the fields or adding explicit padding members
1069 PRFileDesc *fd;
1070
1071 /* Pointer to operations vector for this socket */
1072 const sslSocketOps *ops;
1073
1074 /* SSL socket options */
1075 sslOptions opt;
1076 /* Enabled version range */
1077 SSLVersionRange vrange;
1078
1079 /* A function that returns the current time. */
1080 SSLTimeFunc now;
1081 void *nowArg;
1082
1083 /* State flags */
1084 unsigned long clientAuthRequested;
1085 unsigned long delayDisabled; /* Nagle delay disabled */
1086 unsigned long firstHsDone; /* first handshake is complete. */
1087 unsigned long enoughFirstHsDone; /* enough of the first handshake is
1088 * done for callbacks to be able to
1089 * retrieve channel security
1090 * parameters from the SSL socket. */
1091 unsigned long handshakeBegun;
1092 unsigned long lastWriteBlocked;
1093 unsigned long recvdCloseNotify; /* received SSL EOF. */
1094 unsigned long TCPconnected;
1095 unsigned long appDataBuffered;
1096 unsigned long peerRequestedProtection; /* from old renegotiation */
1097
1098 /* version of the protocol to use */
1099 SSL3ProtocolVersion version;
1100 SSL3ProtocolVersion clientHelloVersion; /* version sent in client hello. */
1101
1102 sslSecurityInfo sec; /* not a pointer any more */
1103
1104 /* protected by firstHandshakeLock AND ssl3HandshakeLock. */
1105 const char *url;
1106
1107 sslHandshakeFunc handshake; /*firstHandshakeLock*/
1108
1109 /* the following variable is only used with socks or other proxies. */
1110 char *peerID; /* String uniquely identifies target server. */
1111
1112 /* ECDHE and DHE keys: In TLS 1.3, we might have to maintain multiple of
1113 * these on the client side. The server inserts a single value into this
1114 * list for all versions. */
1115 PRCList /*<sslEphemeralKeyPair>*/ ephemeralKeyPairs;
1116
1117 /* Callbacks */
1118 SSLAuthCertificate authCertificate;
1119 void *authCertificateArg;
1120 SSLGetClientAuthData getClientAuthData;
1121 void *getClientAuthDataArg;
1122 SSLSNISocketConfig sniSocketConfig;
1123 void *sniSocketConfigArg;
1124 SSLAlertCallback alertReceivedCallback;
1125 void *alertReceivedCallbackArg;
1126 SSLAlertCallback alertSentCallback;
1127 void *alertSentCallbackArg;
1128 SSLBadCertHandler handleBadCert;
1129 void *badCertArg;
1130 SSLHandshakeCallback handshakeCallback;
1131 void *handshakeCallbackData;
1132 SSLCanFalseStartCallback canFalseStartCallback;
1133 void *canFalseStartCallbackData;
1134 void *pkcs11PinArg;
1135 SSLNextProtoCallback nextProtoCallback;
1136 void *nextProtoArg;
1137 SSLHelloRetryRequestCallback hrrCallback;
1138 void *hrrCallbackArg;
1139 PRCList extensionHooks;
1140 SSLResumptionTokenCallback resumptionTokenCallback;
1141 void *resumptionTokenContext;
1142 SSLSecretCallback secretCallback;
1143 void *secretCallbackArg;
1144 SSLRecordWriteCallback recordWriteCallback;
1145 void *recordWriteCallbackArg;
1146
1147 PRIntervalTime rTimeout; /* timeout for NSPR I/O */
1148 PRIntervalTime wTimeout; /* timeout for NSPR I/O */
1149 PRIntervalTime cTimeout; /* timeout for NSPR I/O */
1150
1151 PRLock *recvLock; /* lock against multiple reader threads. */
1152 PRLock *sendLock; /* lock against multiple sender threads. */
1153
1154 PRMonitor *recvBufLock; /* locks low level recv buffers. */
1155 PRMonitor *xmitBufLock; /* locks low level xmit buffers. */
1156
1157 /* Only one thread may operate on the socket until the initial handshake
1158 ** is complete. This Monitor ensures that. Since SSL2 handshake is
1159 ** only done once, this is also effectively the SSL2 handshake lock.
1160 */
1161 PRMonitor *firstHandshakeLock;
1162
1163 /* This monitor protects the ssl3 handshake state machine data.
1164 ** Only one thread (reader or writer) may be in the ssl3 handshake state
1165 ** machine at any time. */
1166 PRMonitor *ssl3HandshakeLock;
1167
1168 /* reader/writer lock, protects the secret data needed to encrypt and MAC
1169 ** outgoing records, and to decrypt and MAC check incoming ciphertext
1170 ** records. */
1171 NSSRWLock *specLock;
1172
1173 /* handle to perm cert db (and implicitly to the temp cert db) used
1174 ** with this socket.
1175 */
1176 CERTCertDBHandle *dbHandle;
1177
1178 PRThread *writerThread; /* thread holds SSL_LOCK_WRITER lock */
1179
1180 PRUint16 shutdownHow; /* See ssl_SHUTDOWN defines below. */
1181
1182 /* Gather object used for gathering data */
1183 sslGather gs; /*recvBufLock*/
1184
1185 sslBuffer saveBuf; /*xmitBufLock*/
1186 sslBuffer pendingBuf; /*xmitBufLock*/
1187
1188 /* Configuration state for server sockets */
1189 /* One server cert and key for each authentication type. */
1190 PRCList /* <sslServerCert> */ serverCerts;
1191
1192 ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED71];
1193
1194 /* A list of groups that are sorted according to user preferences pointing
1195 * to entries of ssl_named_groups. By default this list contains pointers
1196 * to all elements in ssl_named_groups in the default order.
1197 * This list also determines which groups are enabled. This
1198 * starts with all being enabled and can be modified either by negotiation
1199 * (in which case groups not supported by a peer are masked off), or by
1200 * calling SSL_DHEGroupPrefSet().
1201 * Note that renegotiation will ignore groups that were disabled in the
1202 * first handshake.
1203 */
1204 const sslNamedGroupDef *namedGroupPreferences[SSL_NAMED_GROUP_COUNT35];
1205 /* The number of additional shares to generate for the TLS 1.3 ClientHello */
1206 unsigned int additionalShares;
1207
1208 /* SSL3 state info. Formerly was a pointer */
1209 ssl3State ssl3;
1210
1211 /*
1212 * TLS extension related data.
1213 */
1214 /* True when the current session is a stateless resume. */
1215 PRBool statelessResume;
1216 /* Like ss->ssl3.hs, this is handshake state: it is written by the
1217 * extension handlers and senders, and is protected by
1218 * ssl3HandshakeLock. */
1219 TLSExtensionData xtnData;
1220
1221 /* Whether we are doing stream or datagram mode */
1222 SSLProtocolVariant protocolVariant;
1223
1224 /* TLS 1.3 Encrypted Client Hello. */
1225 PRCList echConfigs; /* Client/server: Must not change while hs
1226 * is in-progress. */
1227 SECKEYPublicKey *echPubKey; /* Server: The ECH keypair used in HPKE. */
1228 SECKEYPrivateKey *echPrivKey; /* As above. */
1229
1230 /* Anti-replay for TLS 1.3 0-RTT. */
1231 SSLAntiReplayContext *antiReplay;
1232
1233 /* An out-of-band PSK. */
1234 sslPsk *psk;
1235};
1236
1237struct sslSelfEncryptKeysStr {
1238 PRCallOnceType setup;
1239 PRUint8 keyName[SELF_ENCRYPT_KEY_NAME_LEN16];
1240 PK11SymKey *encKey;
1241 PK11SymKey *macKey;
1242};
1243typedef struct sslSelfEncryptKeysStr sslSelfEncryptKeys;
1244
1245extern char ssl_debug;
1246extern char ssl_trace;
1247extern FILE *ssl_trace_iob;
1248extern FILE *ssl_keylog_iob;
1249extern PRLock *ssl_keylog_lock;
1250static const PRUint32 ssl_ticket_lifetime = 2 * 24 * 60 * 60; // 2 days.
1251
1252extern const char *const ssl3_cipherName[];
1253
1254extern sslSessionIDLookupFunc ssl_sid_lookup;
1255
1256extern const sslNamedGroupDef ssl_named_groups[];
1257
1258/************************************************************************/
1259
1260SEC_BEGIN_PROTOS
1261
1262/* Internal initialization and installation of the SSL error tables */
1263extern SECStatus ssl_Init(void);
1264extern SECStatus ssl_InitializePRErrorTable(void);
1265
1266/* Implementation of ops for default (non socks, non secure) case */
1267extern int ssl_DefConnect(sslSocket *ss, const PRNetAddr *addr);
1268extern PRFileDesc *ssl_DefAccept(sslSocket *ss, PRNetAddr *addr);
1269extern int ssl_DefBind(sslSocket *ss, const PRNetAddr *addr);
1270extern int ssl_DefListen(sslSocket *ss, int backlog);
1271extern int ssl_DefShutdown(sslSocket *ss, int how);
1272extern int ssl_DefClose(sslSocket *ss);
1273extern int ssl_DefRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
1274extern int ssl_DefSend(sslSocket *ss, const unsigned char *buf,
1275 int len, int flags);
1276extern int ssl_DefRead(sslSocket *ss, unsigned char *buf, int len);
1277extern int ssl_DefWrite(sslSocket *ss, const unsigned char *buf, int len);
1278extern int ssl_DefGetpeername(sslSocket *ss, PRNetAddr *name);
1279extern int ssl_DefGetsockname(sslSocket *ss, PRNetAddr *name);
1280extern int ssl_DefGetsockopt(sslSocket *ss, PRSockOption optname,
1281 void *optval, PRInt32 *optlen);
1282extern int ssl_DefSetsockopt(sslSocket *ss, PRSockOption optname,
1283 const void *optval, PRInt32 optlen);
1284
1285/* Implementation of ops for socks only case */
1286extern int ssl_SocksConnect(sslSocket *ss, const PRNetAddr *addr);
1287extern PRFileDesc *ssl_SocksAccept(sslSocket *ss, PRNetAddr *addr);
1288extern int ssl_SocksBind(sslSocket *ss, const PRNetAddr *addr);
1289extern int ssl_SocksListen(sslSocket *ss, int backlog);
1290extern int ssl_SocksGetsockname(sslSocket *ss, PRNetAddr *name);
1291extern int ssl_SocksRecv(sslSocket *ss, unsigned char *buf, int len, int flags);
1292extern int ssl_SocksSend(sslSocket *ss, const unsigned char *buf,
1293 int len, int flags);
1294extern int ssl_SocksRead(sslSocket *ss, unsigned char *buf, int len);
1295extern int ssl_SocksWrite(sslSocket *ss, const unsigned char *buf, int len);
1296
1297/* Implementation of ops for secure only case */
1298extern int ssl_SecureConnect(sslSocket *ss, const PRNetAddr *addr);
1299extern PRFileDesc *ssl_SecureAccept(sslSocket *ss, PRNetAddr *addr);
1300extern int ssl_SecureRecv(sslSocket *ss, unsigned char *buf,
1301 int len, int flags);
1302extern int ssl_SecureSend(sslSocket *ss, const unsigned char *buf,
1303 int len, int flags);
1304extern int ssl_SecureRead(sslSocket *ss, unsigned char *buf, int len);
1305extern int ssl_SecureWrite(sslSocket *ss, const unsigned char *buf, int len);
1306extern int ssl_SecureShutdown(sslSocket *ss, int how);
1307extern int ssl_SecureClose(sslSocket *ss);
1308
1309/* Implementation of ops for secure socks case */
1310extern int ssl_SecureSocksConnect(sslSocket *ss, const PRNetAddr *addr);
1311extern PRFileDesc *ssl_SecureSocksAccept(sslSocket *ss, PRNetAddr *addr);
1312extern PRFileDesc *ssl_FindTop(sslSocket *ss);
1313
1314/* Gather funcs. */
1315extern sslGather *ssl_NewGather(void);
1316extern SECStatus ssl3_InitGather(sslGather *gs);
1317extern void ssl3_DestroyGather(sslGather *gs);
1318extern SECStatus ssl_GatherRecord1stHandshake(sslSocket *ss);
1319
1320extern SECStatus ssl_CreateSecurityInfo(sslSocket *ss);
1321extern SECStatus ssl_CopySecurityInfo(sslSocket *ss, sslSocket *os);
1322extern void ssl_ResetSecurityInfo(sslSecurityInfo *sec, PRBool doMemset);
1323extern void ssl_DestroySecurityInfo(sslSecurityInfo *sec);
1324
1325extern void ssl_PrintBuf(const sslSocket *ss, const char *msg, const void *cp,
1326 int len);
1327extern void ssl_PrintKey(const sslSocket *ss, const char *msg, PK11SymKey *key);
1328
1329extern int ssl_SendSavedWriteData(sslSocket *ss);
1330extern SECStatus ssl_SaveWriteData(sslSocket *ss,
1331 const void *p, unsigned int l);
1332extern SECStatus ssl_BeginClientHandshake(sslSocket *ss);
1333extern SECStatus ssl_BeginServerHandshake(sslSocket *ss);
1334extern SECStatus ssl_Do1stHandshake(sslSocket *ss);
1335
1336extern SECStatus ssl3_InitPendingCipherSpecs(sslSocket *ss, PK11SymKey *secret,
1337 PRBool derive);
1338extern void ssl_DestroyKeyMaterial(ssl3KeyMaterial *keyMaterial);
1339extern sslSessionID *ssl3_NewSessionID(sslSocket *ss, PRBool is_server);
1340extern sslSessionID *ssl_LookupSID(PRTime now, const PRIPv6Addr *addr,
1341 PRUint16 port, const char *peerID,
1342 const char *urlSvrName);
1343extern void ssl_FreeSID(sslSessionID *sid);
1344extern void ssl_DestroySID(sslSessionID *sid, PRBool freeIt);
1345extern sslSessionID *ssl_ReferenceSID(sslSessionID *sid);
1346extern void ssl_SetSocketSID(sslSocket *ss, sslSessionID *sid);
1347extern sslSessionID *ssl_TakeSocketSID(sslSocket *ss);
1348extern sslSessionID *ssl_ReferenceSocketSID(sslSocket *ss);
1349
1350extern int ssl3_SendApplicationData(sslSocket *ss, const PRUint8 *in,
1351 int len, int flags);
1352
1353extern PRBool ssl_FdIsBlocking(PRFileDesc *fd);
1354
1355extern PRBool ssl_SocketIsBlocking(sslSocket *ss);
1356
1357extern void ssl3_SetAlwaysBlock(sslSocket *ss);
1358
1359extern SECStatus ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled);
1360
1361extern SECStatus ssl_FinishHandshake(sslSocket *ss);
1362
1363extern SECStatus ssl_CipherPolicySet(PRInt32 which, PRInt32 policy);
1364
1365extern SECStatus ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled);
1366
1367extern SECStatus ssl3_ConstrainRangeByPolicy(void);
1368
1369extern SECStatus ssl3_InitState(sslSocket *ss);
1370extern SECStatus Null_Cipher(void *ctx, unsigned char *output, unsigned int *outputLen,
1371 unsigned int maxOutputLen, const unsigned char *input,
1372 unsigned int inputLen);
1373extern void ssl3_RestartHandshakeHashes(sslSocket *ss);
1374typedef SECStatus (*sslUpdateHandshakeHashes)(sslSocket *ss,
1375 const unsigned char *b,
1376 unsigned int l);
1377extern SECStatus ssl3_UpdateHandshakeHashes(sslSocket *ss,
1378 const unsigned char *b,
1379 unsigned int l);
1380extern SECStatus ssl3_UpdatePostHandshakeHashes(sslSocket *ss,
1381 const unsigned char *b,
1382 unsigned int l);
1383SECStatus
1384ssl_HashHandshakeMessageInt(sslSocket *ss, SSLHandshakeType type,
1385 PRUint32 dtlsSeq,
1386 const PRUint8 *b, PRUint32 length,
1387 sslUpdateHandshakeHashes cb);
1388SECStatus ssl_HashHandshakeMessage(sslSocket *ss, SSLHandshakeType type,
1389 const PRUint8 *b, PRUint32 length);
1390SECStatus ssl_HashHandshakeMessageEchInner(sslSocket *ss, SSLHandshakeType type,
1391 const PRUint8 *b, PRUint32 length);
1392SECStatus ssl_HashHandshakeMessageDefault(sslSocket *ss, SSLHandshakeType type,
1393 const PRUint8 *b, PRUint32 length);
1394SECStatus ssl_HashPostHandshakeMessage(sslSocket *ss, SSLHandshakeType type,
1395 const PRUint8 *b, PRUint32 length);
1396
1397/* Returns PR_TRUE if we are still waiting for the server to complete its
1398 * response to our client second round. Once we've received the Finished from
1399 * the server then there is no need to check false start.
1400 */
1401extern PRBool ssl3_WaitingForServerSecondRound(sslSocket *ss);
1402
1403extern PRInt32 ssl3_SendRecord(sslSocket *ss, ssl3CipherSpec *cwSpec,
1404 SSLContentType type,
1405 const PRUint8 *pIn, PRInt32 nIn,
1406 PRInt32 flags);
1407
1408/* Clear any PRCList, optionally calling f on the value. */
1409void ssl_ClearPRCList(PRCList *list, void (*f)(void *));
1410
1411/*
1412 * Make sure there is room in the write buffer for padding and
1413 * cryptographic expansions.
1414 */
1415#define SSL3_BUFFER_FUDGE100 100
1416
1417#define SSL_LOCK_READER(ss)if (ss->recvLock) PR_Lock(ss->recvLock) \
1418 if (ss->recvLock) \
1419 PR_Lock(ss->recvLock)
1420#define SSL_UNLOCK_READER(ss)if (ss->recvLock) PR_Unlock(ss->recvLock) \
1421 if (ss->recvLock) \
1422 PR_Unlock(ss->recvLock)
1423#define SSL_LOCK_WRITER(ss)if (ss->sendLock) PR_Lock(ss->sendLock) \
1424 if (ss->sendLock) \
1425 PR_Lock(ss->sendLock)
1426#define SSL_UNLOCK_WRITER(ss)if (ss->sendLock) PR_Unlock(ss->sendLock) \
1427 if (ss->sendLock) \
1428 PR_Unlock(ss->sendLock)
1429
1430PRBool ssl_HaveRecvBufLock(sslSocket *ss);
1431PRBool ssl_HaveXmitBufLock(sslSocket *ss);
1432PRBool ssl_Have1stHandshakeLock(sslSocket *ss);
1433PRBool ssl_HaveSSL3HandshakeLock(sslSocket *ss);
1434PRBool ssl_HaveSpecWriteLock(sslSocket *ss);
1435
1436void ssl_Get1stHandshakeLock(sslSocket *ss);
1437void ssl_Release1stHandshakeLock(sslSocket *ss);
1438
1439void ssl_GetSSL3HandshakeLock(sslSocket *ss);
1440void ssl_ReleaseSSL3HandshakeLock(sslSocket *ss);
1441
1442void ssl_GetSpecReadLock(sslSocket *ss);
1443void ssl_ReleaseSpecReadLock(sslSocket *ss);
1444
1445void ssl_GetSpecWriteLock(sslSocket *ss);
1446void ssl_ReleaseSpecWriteLock(sslSocket *ss);
1447
1448void ssl_GetRecvBufLock(sslSocket *ss);
1449void ssl_ReleaseRecvBufLock(sslSocket *ss);
1450
1451void ssl_GetXmitBufLock(sslSocket *ss);
1452void ssl_ReleaseXmitBufLock(sslSocket *ss);
1453
1454/* Placeholder value used in version ranges when SSL 3.0 and all
1455 * versions of TLS are disabled.
1456 */
1457#define SSL_LIBRARY_VERSION_NONE0 0
1458
1459/* SSL_LIBRARY_VERSION_MIN_SUPPORTED is the minimum version that this version
1460 * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
1461 * runtime to determine which versions are supported by the version of libssl
1462 * in use.
1463 */
1464#define SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAMSSL_LIBRARY_VERSION_TLS_1_1 SSL_LIBRARY_VERSION_TLS_1_1
1465#define SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAMSSL_LIBRARY_VERSION_3_0 SSL_LIBRARY_VERSION_3_0
1466
1467/* SSL_LIBRARY_VERSION_MAX_SUPPORTED is the maximum version that this version
1468 * of libssl supports. Applications should use SSL_VersionRangeGetSupported at
1469 * runtime to determine which versions are supported by the version of libssl
1470 * in use.
1471 */
1472#ifndef NSS_DISABLE_TLS_1_3
1473#define SSL_LIBRARY_VERSION_MAX_SUPPORTEDSSL_LIBRARY_VERSION_TLS_1_3 SSL_LIBRARY_VERSION_TLS_1_3
1474#else
1475#define SSL_LIBRARY_VERSION_MAX_SUPPORTEDSSL_LIBRARY_VERSION_TLS_1_3 SSL_LIBRARY_VERSION_TLS_1_2
1476#endif
1477
1478#define SSL_ALL_VERSIONS_DISABLED(vrange)((vrange)->min == 0) \
1479 ((vrange)->min == SSL_LIBRARY_VERSION_NONE0)
1480
1481extern PRBool ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
1482 SSL3ProtocolVersion version);
1483
1484/* These functions are called from secnav, even though they're "private". */
1485
1486extern int SSL_RestartHandshakeAfterCertReq(struct sslSocketStr *ss,
1487 CERTCertificate *cert,
1488 SECKEYPrivateKey *key,
1489 CERTCertificateList *certChain);
1490extern sslSocket *ssl_FindSocket(PRFileDesc *fd);
1491extern void ssl_FreeSocket(struct sslSocketStr *ssl);
1492extern SECStatus SSL3_SendAlert(sslSocket *ss, SSL3AlertLevel level,
1493 SSL3AlertDescription desc);
1494extern SECStatus ssl3_DecodeError(sslSocket *ss);
1495
1496extern SECStatus ssl3_AuthCertificateComplete(sslSocket *ss, PRErrorCode error);
1497extern SECStatus ssl3_ClientCertCallbackComplete(sslSocket *ss, SECStatus outcome, SECKEYPrivateKey *clientPrivateKey, CERTCertificate *clientCertificate);
1498
1499/*
1500 * for dealing with SSL 3.0 clients sending SSL 2.0 format hellos
1501 */
1502extern SECStatus ssl3_HandleV2ClientHello(
1503 sslSocket *ss, unsigned char *buffer, unsigned int length, PRUint8 padding);
1504
1505SECStatus
1506ssl3_CreateClientHelloPreamble(sslSocket *ss, const sslSessionID *sid,
1507 PRBool realSid, PRUint16 version, PRBool isEchInner,
1508 const sslBuffer *extensions, sslBuffer *preamble);
1509SECStatus ssl3_InsertChHeaderSize(const sslSocket *ss, sslBuffer *preamble, const sslBuffer *extensions);
1510SECStatus ssl3_SendClientHello(sslSocket *ss, sslClientHelloType type);
1511
1512/*
1513 * input into the SSL3 machinery from the actualy network reading code
1514 */
1515SECStatus ssl3_HandleRecord(sslSocket *ss, SSL3Ciphertext *cipher);
1516SECStatus ssl3_HandleNonApplicationData(sslSocket *ss, SSLContentType rType,
1517 DTLSEpoch epoch,
1518 sslSequenceNumber seqNum,
1519 sslBuffer *databuf);
1520SECStatus ssl_RemoveTLSCBCPadding(sslBuffer *plaintext, unsigned int macSize);
1521
1522int ssl3_GatherAppDataRecord(sslSocket *ss, int flags);
1523int ssl3_GatherCompleteHandshake(sslSocket *ss, int flags);
1524
1525/* Create a new ref counted key pair object from two keys. */
1526extern sslKeyPair *ssl_NewKeyPair(SECKEYPrivateKey *privKey,
1527 SECKEYPublicKey *pubKey);
1528
1529/* get a new reference (bump ref count) to an ssl3KeyPair. */
1530extern sslKeyPair *ssl_GetKeyPairRef(sslKeyPair *keyPair);
1531
1532/* Decrement keypair's ref count and free if zero. */
1533extern void ssl_FreeKeyPair(sslKeyPair *keyPair);
1534
1535extern sslEphemeralKeyPair *ssl_NewEphemeralKeyPair(
1536 const sslNamedGroupDef *group,
1537 SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey);
1538extern sslEphemeralKeyPair *ssl_NewEphemeralKeyPairWithKeys(
1539 const sslNamedGroupDef *group, sslKeyPair *keys);
1540extern sslEphemeralKeyPair *ssl_CopyEphemeralKeyPair(
1541 sslEphemeralKeyPair *keyPair);
1542extern void ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair *keyPair);
1543extern sslEphemeralKeyPair *ssl_LookupEphemeralKeyPair(
1544 sslSocket *ss, const sslNamedGroupDef *groupDef);
1545extern PRBool ssl_HaveEphemeralKeyPair(const sslSocket *ss,
1546 const sslNamedGroupDef *groupDef);
1547extern void ssl_FreeEphemeralKeyPairs(sslSocket *ss);
1548
1549extern SECStatus ssl_AppendPaddedDHKeyShare(sslBuffer *buf,
1550 const SECKEYPublicKey *pubKey,
1551 PRBool appendLength);
1552extern PRBool ssl_CanUseSignatureScheme(SSLSignatureScheme scheme,
1553 const SSLSignatureScheme *peerSchemes,
1554 unsigned int peerSchemeCount,
1555 PRBool requireSha1,
1556 PRBool slotDoesPss);
1557extern const ssl3DHParams *ssl_GetDHEParams(const sslNamedGroupDef *groupDef);
1558extern SECStatus ssl_SelectDHEGroup(sslSocket *ss,
1559 const sslNamedGroupDef **groupDef);
1560extern SECStatus ssl_CreateDHEKeyPair(const sslNamedGroupDef *groupDef,
1561 const ssl3DHParams *params,
1562 sslEphemeralKeyPair **keyPair);
1563extern PRBool ssl_IsValidDHEShare(const SECItem *dh_p, const SECItem *dh_Ys);
1564extern SECStatus ssl_ValidateDHENamedGroup(sslSocket *ss,
1565 const SECItem *dh_p,
1566 const SECItem *dh_g,
1567 const sslNamedGroupDef **groupDef,
1568 const ssl3DHParams **dhParams);
1569
1570extern PRBool ssl_IsECCEnabled(const sslSocket *ss);
1571extern PRBool ssl_IsDHEEnabled(const sslSocket *ss);
1572
1573/* Macro for finding a curve equivalent in strength to RSA key's */
1574#define SSL_RSASTRENGTH_TO_ECSTRENGTH(s)((s <= 1024) ? 160 : ((s <= 2048) ? 224 : ((s <= 3072
) ? 256 : ((s <= 7168) ? 384 : 521))))
\
1575 ((s <= 1024) ? 160 \
1576 : ((s <= 2048) ? 224 \
1577 : ((s <= 3072) ? 256 \
1578 : ((s <= 7168) ? 384 \
1579 : 521))))
1580
1581extern const sslNamedGroupDef *ssl_LookupNamedGroup(SSLNamedGroup group);
1582extern PRBool ssl_NamedGroupEnabled(const sslSocket *ss, const sslNamedGroupDef *group);
1583extern SECStatus ssl_NamedGroup2ECParams(PLArenaPool *arena,
1584 const sslNamedGroupDef *curve,
1585 SECKEYECParams *params);
1586extern const sslNamedGroupDef *ssl_ECPubKey2NamedGroup(
1587 const SECKEYPublicKey *pubKey);
1588
1589extern const sslNamedGroupDef *ssl_GetECGroupForServerSocket(sslSocket *ss);
1590extern void ssl_FilterSupportedGroups(sslSocket *ss);
1591
1592extern SECStatus ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool on);
1593extern SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *on);
1594
1595extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on);
1596extern SECStatus ssl3_CipherPrefGet(const sslSocket *ss, ssl3CipherSuite which, PRBool *on);
1597
1598extern SECStatus ssl3_SetPolicy(ssl3CipherSuite which, PRInt32 policy);
1599extern SECStatus ssl3_GetPolicy(ssl3CipherSuite which, PRInt32 *policy);
1600
1601extern void ssl3_InitSocketPolicy(sslSocket *ss);
1602
1603extern SECStatus ssl3_RedoHandshake(sslSocket *ss, PRBool flushCache);
1604extern SECStatus ssl3_HandleHandshakeMessage(sslSocket *ss, PRUint8 *b,
1605 PRUint32 length,
1606 PRBool endOfRecord);
1607
1608extern void ssl3_DestroySSL3Info(sslSocket *ss);
1609
1610extern SECStatus ssl_ClientReadVersion(sslSocket *ss, PRUint8 **b,
1611 PRUint32 *length,
1612 SSL3ProtocolVersion *version);
1613extern SECStatus ssl3_NegotiateVersion(sslSocket *ss,
1614 SSL3ProtocolVersion peerVersion,
1615 PRBool allowLargerPeerVersion);
1616extern SECStatus ssl_ClientSetCipherSuite(sslSocket *ss,
1617 SSL3ProtocolVersion version,
1618 ssl3CipherSuite suite,
1619 PRBool initHashes);
1620
1621extern SECStatus ssl_GetPeerInfo(sslSocket *ss);
1622
1623/* ECDH functions */
1624extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket *ss,
1625 SECKEYPublicKey *svrPubKey);
1626extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss,
1627 PRUint8 *b, PRUint32 length);
1628extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss,
1629 PRUint8 *b, PRUint32 length,
1630 sslKeyPair *serverKeys);
1631extern SECStatus ssl3_SendECDHServerKeyExchange(sslSocket *ss);
1632extern SECStatus ssl_ImportECDHKeyShare(
1633 SECKEYPublicKey *peerKey,
1634 PRUint8 *b, PRUint32 length, const sslNamedGroupDef *curve);
1635
1636extern SECStatus ssl3_ComputeCommonKeyHash(SSLHashType hashAlg,
1637 PRUint8 *hashBuf,
1638 unsigned int bufLen,
1639 SSL3Hashes *hashes);
1640extern SECStatus ssl3_AppendSignatureAndHashAlgorithm(
1641 sslSocket *ss, const SSLSignatureAndHashAlg *sigAndHash);
1642extern SECStatus ssl3_ConsumeHandshake(sslSocket *ss, void *v, PRUint32 bytes,
1643 PRUint8 **b, PRUint32 *length);
1644extern SECStatus ssl3_ConsumeHandshakeNumber(sslSocket *ss, PRUint32 *num,
1645 PRUint32 bytes, PRUint8 **b,
1646 PRUint32 *length);
1647extern SECStatus ssl3_ConsumeHandshakeNumber64(sslSocket *ss, PRUint64 *num,
1648 PRUint32 bytes, PRUint8 **b,
1649 PRUint32 *length);
1650extern SECStatus ssl3_ConsumeHandshakeVariable(sslSocket *ss, SECItem *i,
1651 PRUint32 bytes, PRUint8 **b,
1652 PRUint32 *length);
1653extern SECStatus ssl_SignatureSchemeFromSpki(const CERTSubjectPublicKeyInfo *spki,
1654 PRBool isTls13,
1655 SSLSignatureScheme *scheme);
1656extern PRBool ssl_SignatureSchemeEnabled(const sslSocket *ss,
1657 SSLSignatureScheme scheme);
1658extern PRBool ssl_IsSupportedSignatureScheme(SSLSignatureScheme scheme);
1659extern SECStatus ssl_CheckSignatureSchemeConsistency(
1660 sslSocket *ss, SSLSignatureScheme scheme, CERTSubjectPublicKeyInfo *spki);
1661/* Parse the subjectPublicKeyInfo out of a DER-encoded certificate with
1662 * mozpkix (see mozpkixwrappers.cpp). Free the result with
1663 * SECKEY_DestroySubjectPublicKeyInfo(). */
1664extern CERTSubjectPublicKeyInfo *ssl_ExtractSPKIFromDER(const SECItem *derCert);
1665/* Install |derCert| as the peer's end-entity certificate, replacing any
1666 * previous one. Fails if no subjectPublicKeyInfo can be parsed out of it. */
1667extern SECStatus ssl_SetPeerCertificate(sslSecurityInfo *sec,
1668 const SECItem *derCert);
1669extern void ssl_ClearPeerCertificate(sslSecurityInfo *sec);
1670extern SECStatus ssl_ParseSignatureSchemes(const sslSocket *ss, PLArenaPool *arena,
1671 SSLSignatureScheme **schemesOut,
1672 unsigned int *numSchemesOut,
1673 unsigned char **b,
1674 unsigned int *len);
1675extern SECStatus ssl_ConsumeSignatureScheme(
1676 sslSocket *ss, PRUint8 **b, PRUint32 *length, SSLSignatureScheme *out);
1677extern SECStatus ssl3_SignHashes(sslSocket *ss, SSL3Hashes *hash,
1678 SECKEYPrivateKey *key, SECItem *buf);
1679extern SECStatus ssl3_VerifySignedHashes(sslSocket *ss, SSLSignatureScheme scheme,
1680 SSL3Hashes *hash, SECItem *buf);
1681/* new signature algorithms don't really have a 'sign hashes' interface,
1682 * TLS13 now supports proper signing, where, if we are signing hashes, we
1683 * will sign them with a proper hash-and-sign signature. Provide
1684 * an API for those places in TLS13 where we need to sign. This leverages
1685 * the work in secsign and secvfy, so we don't need to add a lot of
1686 * algorithm specific code. Once the sign/verify interfaces work, we can
1687 * just add the oid in tls13con.c and the ssl_sig_xxxx value and we are
1688 * good to go */
1689extern tlsSignOrVerifyContext tls_CreateSignOrVerifyContext(
1690 SECKEYPrivateKey *privKey,
1691 SECKEYPublicKey *pubKey,
1692 SSLSignatureScheme scheme, sslSignOrVerify type,
1693 SECItem *signature, void *pwArg);
1694SECStatus tls_SignOrVerifyUpdate(tlsSignOrVerifyContext ctx,
1695 const unsigned char *buf, int len);
1696SECStatus tls_SignOrVerifyEnd(tlsSignOrVerifyContext ctx, SECItem *sig);
1697void tls_DestroySignOrVerifyContext(tlsSignOrVerifyContext *ctx);
1698
1699extern SECStatus ssl3_CacheWrappedSecret(sslSocket *ss, sslSessionID *sid,
1700 PK11SymKey *secret);
1701extern void ssl3_FreeSniNameArray(TLSExtensionData *xtnData);
1702
1703/* Hello Extension related routines. */
1704extern void ssl3_SetSIDSessionTicket(sslSessionID *sid,
1705 /*in/out*/ NewSessionTicket *session_ticket);
1706SECStatus ssl3_EncodeSessionTicket(sslSocket *ss,
1707 const NewSessionTicket *ticket,
1708 const PRUint8 *appToken,
1709 unsigned int appTokenLen,
1710 PK11SymKey *secret, SECItem *ticket_data);
1711SECStatus SSLExp_SendSessionTicket(PRFileDesc *fd, const PRUint8 *token,
1712 unsigned int tokenLen);
1713
1714SECStatus ssl_MaybeSetSelfEncryptKeyPair(const sslKeyPair *keyPair);
1715SECStatus ssl_GetSelfEncryptKeys(sslSocket *ss, unsigned char *keyName,
1716 PK11SymKey **encKey, PK11SymKey **macKey);
1717void ssl_ResetSelfEncryptKeys();
1718
1719extern SECStatus ssl3_ValidateAppProtocol(const unsigned char *data,
1720 unsigned int length);
1721
1722/* Construct a new NSPR socket for the app to use */
1723extern PRFileDesc *ssl_NewPRSocket(sslSocket *ss, PRFileDesc *fd);
1724extern void ssl_FreePRSocket(PRFileDesc *fd);
1725
1726/* Internal config function so SSL3 can initialize the present state of
1727 * various ciphers */
1728extern unsigned int ssl3_config_match_init(sslSocket *);
1729
1730/* Return PR_TRUE if suite is usable. This if the suite is permitted by policy,
1731 * enabled, has a certificate (as needed), has a viable key agreement method, is
1732 * usable with the negotiated TLS version, and is otherwise usable. */
1733PRBool ssl3_config_match(const ssl3CipherSuiteCfg *suite, PRUint8 policy,
1734 const SSLVersionRange *vrange, const sslSocket *ss);
1735
1736/* calls for accessing wrapping keys across processes. */
1737extern SECStatus
1738ssl_GetWrappingKey(unsigned int symWrapMechIndex,
1739 unsigned int wrapKeyIndex, SSLWrappedSymWrappingKey *wswk);
1740
1741/* The caller passes in the new value it wants
1742 * to set. This code tests the wrapped sym key entry in the file on disk.
1743 * If it is uninitialized, this function writes the caller's value into
1744 * the disk entry, and returns false.
1745 * Otherwise, it overwrites the caller's wswk with the value obtained from
1746 * the disk, and returns PR_TRUE.
1747 * This is all done while holding the locks/semaphores necessary to make
1748 * the operation atomic.
1749 */
1750extern SECStatus
1751ssl_SetWrappingKey(SSLWrappedSymWrappingKey *wswk);
1752
1753/* get rid of the symmetric wrapping key references. */
1754extern SECStatus SSL3_ShutdownServerCache(void);
1755
1756extern SECStatus ssl_InitSymWrapKeysLock(void);
1757
1758extern SECStatus ssl_FreeSymWrapKeysLock(void);
1759
1760extern SECStatus ssl_InitSessionCacheLocks(PRBool lazyInit);
1761
1762extern SECStatus ssl_FreeSessionCacheLocks(void);
1763
1764CK_MECHANISM_TYPE ssl3_Alg2Mech(SSLCipherAlgorithm calg);
1765SECStatus ssl3_NegotiateCipherSuiteInner(sslSocket *ss, const SECItem *suites,
1766 PRUint16 version, PRUint16 *suitep);
1767SECStatus ssl3_NegotiateCipherSuite(sslSocket *ss, const SECItem *suites,
1768 PRBool initHashes);
1769SECStatus ssl3_InitHandshakeHashes(sslSocket *ss);
1770void ssl3_CoalesceEchHandshakeHashes(sslSocket *ss);
1771SECStatus ssl3_ServerCallSNICallback(sslSocket *ss);
1772SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
1773SECStatus ssl3_CompleteHandleCertificate(sslSocket *ss,
1774 PRUint8 *b, PRUint32 length);
1775void ssl3_SendAlertForCertError(sslSocket *ss, PRErrorCode errCode);
1776SECStatus ssl3_HandleNoCertificate(sslSocket *ss);
1777SECStatus ssl3_SendEmptyCertificate(sslSocket *ss);
1778void ssl3_CleanupPeerCerts(sslSocket *ss);
1779SECStatus ssl3_SendCertificateStatus(sslSocket *ss);
1780SECStatus ssl_SetAuthKeyBits(sslSocket *ss, const SECKEYPublicKey *pubKey);
1781SECStatus ssl3_HandleServerSpki(sslSocket *ss);
1782SECStatus ssl3_AuthCertificate(sslSocket *ss);
1783SECStatus ssl_ReadCertificateStatus(sslSocket *ss, PRUint8 *b,
1784 PRUint32 length);
1785SECStatus ssl3_EncodeSigAlgs(const sslSocket *ss, PRUint16 maxVersion,
1786 PRUint16 minVersion, PRBool forCert,
1787 PRBool grease, sslBuffer *buf);
1788SECStatus ssl3_EncodeFilteredSigAlgs(const sslSocket *ss,
1789 const SSLSignatureScheme *schemes,
1790 PRUint32 numSchemes, PRBool grease, sslBuffer *buf);
1791SECStatus ssl3_FilterSigAlgs(const sslSocket *ss, PRUint16 maxVersion, PRUint16 minVersion,
1792 PRBool disableRsae, PRBool forCert,
1793 unsigned int maxSchemes, SSLSignatureScheme *filteredSchemes,
1794 unsigned int *numFilteredSchemes);
1795SECStatus ssl_GetCertificateRequestCAs(const sslSocket *ss,
1796 unsigned int *calenp,
1797 const SECItem **namesp,
1798 unsigned int *nnamesp);
1799SECStatus ssl3_ParseCertificateRequestCAs(sslSocket *ss, PRUint8 **b,
1800 PRUint32 *length, CERTDistNames *ca_list);
1801SECStatus ssl3_BeginHandleCertificateRequest(
1802 sslSocket *ss, const SSLSignatureScheme *signatureSchemes,
1803 unsigned int signatureSchemeCount, CERTDistNames *ca_list);
1804SECStatus ssl_ConstructServerHello(sslSocket *ss, PRBool helloRetry,
1805 const sslBuffer *extensionBuf,
1806 sslBuffer *messageBuf);
1807SECStatus ssl3_SendServerHello(sslSocket *ss);
1808SECStatus ssl3_SendChangeCipherSpecsInt(sslSocket *ss);
1809SECStatus ssl3_ComputeHandshakeHashes(sslSocket *ss,
1810 ssl3CipherSpec *spec,
1811 SSL3Hashes *hashes,
1812 PRUint32 sender);
1813SECStatus ssl_CreateECDHEphemeralKeyPair(const sslSocket *ss,
1814 const sslNamedGroupDef *ecGroup,
1815 sslEphemeralKeyPair **keyPair);
1816SECStatus ssl_CreateStaticECDHEKey(sslSocket *ss,
1817 const sslNamedGroupDef *ecGroup);
1818SECStatus ssl3_FlushHandshake(sslSocket *ss, PRInt32 flags);
1819SECStatus ssl3_GetNewRandom(SSL3Random random);
1820PK11SymKey *ssl3_GetWrappingKey(sslSocket *ss,
1821 PK11SlotInfo *masterSecretSlot,
1822 CK_MECHANISM_TYPE masterWrapMech,
1823 void *pwArg);
1824SECStatus ssl3_FillInCachedSID(sslSocket *ss, sslSessionID *sid,
1825 PK11SymKey *secret);
1826const ssl3CipherSuiteDef *ssl_LookupCipherSuiteDef(ssl3CipherSuite suite);
1827const ssl3CipherSuiteCfg *ssl_LookupCipherSuiteCfg(ssl3CipherSuite suite,
1828 const ssl3CipherSuiteCfg *suites);
1829PRBool ssl3_CipherSuiteAllowedForVersionRange(ssl3CipherSuite cipherSuite,
1830 const SSLVersionRange *vrange);
1831
1832SECStatus ssl3_SelectServerCert(sslSocket *ss);
1833SECStatus ssl_PrivateKeySupportsRsaPss(SECKEYPrivateKey *privKey,
1834 CERTCertificate *cert,
1835 void *pwArg,
1836 PRBool *supportsRsaPss);
1837SECStatus ssl_PickSignatureScheme(sslSocket *ss,
1838 CERTCertificate *cert,
1839 SECKEYPublicKey *pubKey,
1840 SECKEYPrivateKey *privKey,
1841 const SSLSignatureScheme *peerSchemes,
1842 unsigned int peerSchemeCount,
1843 PRBool requireSha1,
1844 SSLSignatureScheme *schemPtr);
1845SECStatus ssl_PickClientSignatureScheme(sslSocket *ss,
1846 CERTCertificate *clientCertificate,
1847 SECKEYPrivateKey *privKey,
1848 const SSLSignatureScheme *schemes,
1849 unsigned int numSchemes,
1850 SSLSignatureScheme *schemePtr);
1851SECOidTag ssl3_HashTypeToOID(SSLHashType hashType);
1852SECOidTag ssl3_AuthTypeToOID(SSLAuthType hashType);
1853SSLHashType ssl_SignatureSchemeToHashType(SSLSignatureScheme scheme);
1854SSLAuthType ssl_SignatureSchemeToAuthType(SSLSignatureScheme scheme);
1855
1856SECStatus ssl3_SetupCipherSuite(sslSocket *ss, PRBool initHashes);
1857SECStatus ssl_InsertRecordHeader(const sslSocket *ss, ssl3CipherSpec *cwSpec,
1858 SSLContentType contentType, sslBuffer *wrBuf,
1859 PRBool *needsLength);
1860PRBool ssl_SignatureSchemeValid(SSLSignatureScheme scheme, SECOidTag spkiOid,
1861 PRBool isTls13);
1862
1863/* Pull in DTLS functions */
1864#include "dtlscon.h"
1865
1866/* Pull in TLS 1.3 functions */
1867#include "tls13con.h"
1868#include "dtls13con.h"
1869
1870/********************** misc calls *********************/
1871
1872#ifdef DEBUG1
1873extern void ssl3_CheckCipherSuiteOrderConsistency();
1874#endif
1875
1876extern int ssl_MapLowLevelError(int hiLevelError);
1877
1878PRTime ssl_Time(const sslSocket *ss);
1879PRBool ssl_TicketTimeValid(const sslSocket *ss, const NewSessionTicket *ticket);
1880
1881extern void SSL_AtomicIncrementLong(long *x);
1882
1883SECStatus ssl3_ApplyNSSPolicy(void);
1884
1885extern SECStatus
1886ssl3_TLSPRFWithMasterSecret(sslSocket *ss, ssl3CipherSpec *spec,
1887 const char *label, unsigned int labelLen,
1888 const unsigned char *val, unsigned int valLen,
1889 unsigned char *out, unsigned int outLen);
1890
1891extern void
1892ssl3_RecordKeyLog(sslSocket *ss, const char *label, PK11SymKey *secret);
1893
1894extern void
1895ssl3_WriteKeyLog(sslSocket *ss, const char *label, const SECItem *item);
1896
1897PRBool ssl_AlpnTagAllowed(const sslSocket *ss, const SECItem *tag);
1898
1899#ifdef TRACE
1900#define SSL_TRACE(msg)ssl_Trace msg ssl_Trace msg
1901#else
1902#define SSL_TRACE(msg)ssl_Trace msg
1903#endif
1904
1905void ssl_Trace(const char *format, ...);
1906
1907void ssl_CacheExternalToken(sslSocket *ss);
1908SECStatus ssl_DecodeResumptionToken(sslSocket *ss, sslSessionID *sid,
1909 const PRUint8 *encodedTicket,
1910 PRUint32 encodedTicketLen);
1911PRBool ssl_IsResumptionTokenUsable(sslSocket *ss, sslSessionID *sid);
1912
1913/* unwrap helper function to handle the case where the wrapKey doesn't wind
1914 * * up in the correct token for the master secret */
1915PK11SymKey *ssl_unwrapSymKey(PK11SymKey *wrapKey,
1916 CK_MECHANISM_TYPE wrapType, SECItem *param,
1917 SECItem *wrappedKey,
1918 CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
1919 int keySize, CK_FLAGS keyFlags, void *pinArg);
1920
1921/* determine if the current ssl connection is operating in FIPS mode */
1922PRBool ssl_isFIPS(sslSocket *ss);
1923
1924/* Experimental APIs. Remove when stable. */
1925
1926SECStatus SSLExp_SetResumptionTokenCallback(PRFileDesc *fd,
1927 SSLResumptionTokenCallback cb,
1928 void *ctx);
1929SECStatus SSLExp_SetResumptionToken(PRFileDesc *fd, const PRUint8 *token,
1930 unsigned int len);
1931SECStatus SSLExp_EnablePlaintextResumptionExport(PRFileDesc *fd, PRBool enabled);
1932
1933SECStatus SSLExp_GetResumptionTokenInfo(const PRUint8 *tokenData, unsigned int tokenLen,
1934 SSLResumptionTokenInfo *token, unsigned int version);
1935SECStatus SSLExp_GetResumptionTokenInfoWithFlags(const PRUint8 *tokenData,
1936 unsigned int tokenLen,
1937 SSLResumptionTokenInfo *token,
1938 unsigned int version,
1939 PRUint32 flags);
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 SSLResumptionTokenVersion3 3
1955#define SSLResumptionTokenFeatureRawMS0x01 0x01
1956/* 0x80 is reserved to signal a longer feature field. */
1957#define SSLResumptionTokenSupportedFeatures0x01 SSLResumptionTokenFeatureRawMS0x01
1958
1959SECStatus SSLExp_MakeAead(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *secret,
1960 const char *labelPrefix, unsigned int labelPrefixLen,
1961 SSLAeadContext **ctx);
1962
1963SECStatus SSLExp_MakeVariantAead(PRUint16 version, PRUint16 cipherSuite, SSLProtocolVariant variant,
1964 PK11SymKey *secret, const char *labelPrefix,
1965 unsigned int labelPrefixLen, SSLAeadContext **ctx);
1966SECStatus SSLExp_DestroyAead(SSLAeadContext *ctx);
1967SECStatus SSLExp_AeadEncrypt(const SSLAeadContext *ctx, PRUint64 counter,
1968 const PRUint8 *aad, unsigned int aadLen,
1969 const PRUint8 *plaintext, unsigned int plaintextLen,
1970 PRUint8 *out, unsigned int *outLen, unsigned int maxOut);
1971SECStatus SSLExp_AeadDecrypt(const SSLAeadContext *ctx, PRUint64 counter,
1972 const PRUint8 *aad, unsigned int aadLen,
1973 const PRUint8 *plaintext, unsigned int plaintextLen,
1974 PRUint8 *out, unsigned int *outLen, unsigned int maxOut);
1975
1976/* The next function is responsible for registering a certificate compression mechanism
1977 to be used for TLS connection.
1978 The caller passes SSLCertificateCompressionAlgorithm algorithm:
1979
1980 typedef struct SSLCertificateCompressionAlgorithmStr {
1981 SSLCertificateCompressionAlgorithmID id;
1982 const char* name;
1983 SECStatus (*encode)(const SECItem* input, SECItem* output);
1984 SECStatus (*decode)(const SECItem* input, unsigned char* output, size_t outputLen, size_t* usedLen);
1985 } SSLCertificateCompressionAlgorithm;
1986
1987 Certificate Compression encoding function is responsible for allocating the output buffer itself.
1988 If encoding function fails, the function has the install the appropriate error code and return an error.
1989
1990 Certificate Compression decoding function operates an output buffer allocated in NSS.
1991 The function returns success or an error code.
1992 If successful, the function sets the number of bytes used to stored the decoded certificate
1993 in the outparam usedLen. If provided buffer is not enough to store the output (or any problem has occured during
1994 decoding of the buffer), the function has the install the appropriate error code and return an error.
1995 Note: usedLen is always <= outputLen.
1996
1997 */
1998SECStatus SSLExp_SetCertificateCompressionAlgorithm(PRFileDesc *fd, SSLCertificateCompressionAlgorithm alg);
1999SECStatus SSLExp_HkdfExtract(PRUint16 version, PRUint16 cipherSuite,
2000 PK11SymKey *salt, PK11SymKey *ikm, PK11SymKey **keyp);
2001SECStatus SSLExp_HkdfExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
2002 const PRUint8 *hsHash, unsigned int hsHashLen,
2003 const char *label, unsigned int labelLen,
2004 PK11SymKey **key);
2005SECStatus SSLExp_HkdfVariantExpandLabel(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
2006 const PRUint8 *hsHash, unsigned int hsHashLen,
2007 const char *label, unsigned int labelLen,
2008 SSLProtocolVariant variant, PK11SymKey **key);
2009SECStatus
2010SSLExp_HkdfExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
2011 const PRUint8 *hsHash, unsigned int hsHashLen,
2012 const char *label, unsigned int labelLen,
2013 CK_MECHANISM_TYPE mech, unsigned int keySize,
2014 PK11SymKey **keyp);
2015SECStatus
2016SSLExp_HkdfVariantExpandLabelWithMech(PRUint16 version, PRUint16 cipherSuite, PK11SymKey *prk,
2017 const PRUint8 *hsHash, unsigned int hsHashLen,
2018 const char *label, unsigned int labelLen,
2019 CK_MECHANISM_TYPE mech, unsigned int keySize,
2020 SSLProtocolVariant variant, PK11SymKey **keyp);
2021
2022SECStatus SSLExp_SetDtls13VersionWorkaround(PRFileDesc *fd, PRBool enabled);
2023
2024SECStatus SSLExp_SetTimeFunc(PRFileDesc *fd, SSLTimeFunc f, void *arg);
2025
2026extern SECStatus ssl_CreateMaskingContextInner(PRUint16 version, PRUint16 cipherSuite,
2027 SSLProtocolVariant variant,
2028 PK11SymKey *secret,
2029 const char *label,
2030 unsigned int labelLen,
2031 SSLMaskingContext **ctx);
2032
2033extern SECStatus ssl_CreateMaskInner(SSLMaskingContext *ctx, const PRUint8 *sample,
2034 unsigned int sampleLen, PRUint8 *outMask,
2035 unsigned int maskLen);
2036
2037extern SECStatus ssl_DestroyMaskingContextInner(SSLMaskingContext *ctx);
2038
2039SECStatus SSLExp_CreateMaskingContext(PRUint16 version, PRUint16 cipherSuite,
2040 PK11SymKey *secret,
2041 const char *label,
2042 unsigned int labelLen,
2043 SSLMaskingContext **ctx);
2044
2045SECStatus SSLExp_CreateVariantMaskingContext(PRUint16 version, PRUint16 cipherSuite,
2046 SSLProtocolVariant variant,
2047 PK11SymKey *secret,
2048 const char *label,
2049 unsigned int labelLen,
2050 SSLMaskingContext **ctx);
2051
2052SECStatus SSLExp_CreateMask(SSLMaskingContext *ctx, const PRUint8 *sample,
2053 unsigned int sampleLen, PRUint8 *mask,
2054 unsigned int len);
2055
2056SECStatus SSLExp_DestroyMaskingContext(SSLMaskingContext *ctx);
2057
2058SECStatus SSLExp_EnableTls13GreaseEch(PRFileDesc *fd, PRBool enabled);
2059SECStatus SSLExp_SetTls13GreaseEchSize(PRFileDesc *fd, PRUint8 size);
2060
2061SECStatus SSLExp_EnableTls13BackendEch(PRFileDesc *fd, PRBool enabled);
2062SECStatus SSLExp_CallExtensionWriterOnEchInner(PRFileDesc *fd, PRBool enabled);
2063
2064SECStatus SSLExp_PeerCertificateChainDER(PRFileDesc *fd, SECItemArray **out);
2065
2066SEC_END_PROTOS
2067
2068#if defined(XP_UNIX1)
2069#define SSL_GETPIDgetpid getpid
2070#elif defined(WIN32)
2071#define SSL_GETPIDgetpid _getpid
2072#else
2073#define SSL_GETPIDgetpid() 0
2074#endif
2075
2076#endif /* __sslimpl_h_ */