1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * vtables (and methods that call through them) for the 4 types of
4 * SSLSockets supported. Only one type is still supported.
5 * Various other functions.
6 *
7 * This Source Code Form is subject to the terms of the Mozilla Public
8 * License, v. 2.0. If a copy of the MPL was not distributed with this
9 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
10 #include "seccomon.h"
11 #include "cert.h"
12 #include "keyhi.h"
13 #include "ssl.h"
14 #include "sslexp.h"
15 #include "sslimpl.h"
16 #include "sslproto.h"
17 #include <nspr.h>
18 #include "private/pprio.h"
19 #include "nss.h"
20 #include "pk11pqg.h"
21 #include "pk11pub.h"
22 #include "tls13ech.h"
23 #include "tls13psk.h"
24 #include "tls13subcerts.h"
25
26 static const sslSocketOps ssl_default_ops = { /* No SSL. */
27 ssl_DefConnect,
28 NULL,
29 ssl_DefBind,
30 ssl_DefListen,
31 ssl_DefShutdown,
32 ssl_DefClose,
33 ssl_DefRecv,
34 ssl_DefSend,
35 ssl_DefRead,
36 ssl_DefWrite,
37 ssl_DefGetpeername,
38 ssl_DefGetsockname
39 };
40
41 static const sslSocketOps ssl_secure_ops = { /* SSL. */
42 ssl_SecureConnect,
43 NULL,
44 ssl_DefBind,
45 ssl_DefListen,
46 ssl_SecureShutdown,
47 ssl_SecureClose,
48 ssl_SecureRecv,
49 ssl_SecureSend,
50 ssl_SecureRead,
51 ssl_SecureWrite,
52 ssl_DefGetpeername,
53 ssl_DefGetsockname
54 };
55
56 /*
57 ** default settings for socket enables
58 */
59 static sslOptions ssl_defaults = {
60 .nextProtoNego = { siBuffer, NULL, 0 },
61 .maxEarlyDataSize = 1 << 16,
62 .recordSizeLimit = MAX_FRAGMENT_LENGTH + 1,
63 .useSecurity = PR_TRUE,
64 .useSocks = PR_FALSE,
65 .requestCertificate = PR_FALSE,
66 .requireCertificate = SSL_REQUIRE_FIRST_HANDSHAKE,
67 .handshakeAsClient = PR_FALSE,
68 .handshakeAsServer = PR_FALSE,
69 .noCache = PR_FALSE,
70 .fdx = PR_FALSE,
71 .detectRollBack = PR_TRUE,
72 .noLocks = PR_FALSE,
73 .enableSessionTickets = PR_FALSE,
74 .enableDeflate = PR_FALSE,
75 .enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN,
76 .requireSafeNegotiation = PR_FALSE,
77 .enableFalseStart = PR_FALSE,
78 .cbcRandomIV = PR_TRUE,
79 .enableOCSPStapling = PR_FALSE,
80 .enableDelegatedCredentials = PR_FALSE,
81 .enableALPN = PR_TRUE,
82 .reuseServerECDHEKey = PR_TRUE,
83 .enableFallbackSCSV = PR_FALSE,
84 .enableServerDhe = PR_TRUE,
85 .enableExtendedMS = PR_TRUE,
86 .enableSignedCertTimestamps = PR_FALSE,
87 .requireDHENamedGroups = PR_FALSE,
88 .enable0RttData = PR_FALSE,
89 .enableTls13CompatMode = PR_FALSE,
90 .enableDtls13VersionCompat = PR_FALSE,
91 .enableDtlsShortHeader = PR_FALSE,
92 .enableHelloDowngradeCheck = PR_TRUE,
93 .enableV2CompatibleHello = PR_FALSE,
94 .enablePostHandshakeAuth = PR_FALSE,
95 .suppressEndOfEarlyData = PR_FALSE,
96 .enableTls13GreaseEch = PR_FALSE,
97 .enableTls13BackendEch = PR_FALSE,
98 .callExtensionWriterOnEchInner = PR_FALSE,
99 };
100
101 /*
102 * default range of enabled SSL/TLS protocols
103 */
104 static SSLVersionRange versions_defaults_stream = {
105 SSL_LIBRARY_VERSION_TLS_1_2,
106 SSL_LIBRARY_VERSION_TLS_1_3
107 };
108
109 static SSLVersionRange versions_defaults_datagram = {
110 SSL_LIBRARY_VERSION_TLS_1_2,
111 SSL_LIBRARY_VERSION_TLS_1_2
112 };
113
114 #define VERSIONS_DEFAULTS(variant) \
115 (variant == ssl_variant_stream ? &versions_defaults_stream : &versions_defaults_datagram)
116 #define VERSIONS_POLICY_MIN(variant) \
117 (variant == ssl_variant_stream ? NSS_TLS_VERSION_MIN_POLICY : NSS_DTLS_VERSION_MIN_POLICY)
118 #define VERSIONS_POLICY_MAX(variant) \
119 (variant == ssl_variant_stream ? NSS_TLS_VERSION_MAX_POLICY : NSS_DTLS_VERSION_MAX_POLICY)
120
121 sslSessionIDLookupFunc ssl_sid_lookup;
122
123 static PRDescIdentity ssl_layer_id;
124
125 PRBool locksEverDisabled; /* implicitly PR_FALSE */
126 PRBool ssl_force_locks; /* implicitly PR_FALSE */
127 int ssl_lock_readers = 1; /* default true. */
128 char ssl_debug;
129 char ssl_trace;
130 FILE *ssl_trace_iob;
131
132 #ifdef NSS_ALLOW_SSLKEYLOGFILE
133 FILE *ssl_keylog_iob;
134 PZLock *ssl_keylog_lock;
135 #endif
136
137 char lockStatus[] = "Locks are ENABLED. ";
138 #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
139
140 /* SRTP_NULL_HMAC_SHA1_80 and SRTP_NULL_HMAC_SHA1_32 are not implemented. */
141 static const PRUint16 srtpCiphers[] = {
142 SRTP_AES128_CM_HMAC_SHA1_80,
143 SRTP_AES128_CM_HMAC_SHA1_32,
144 0
145 };
146
147 /* This list is in preference order. Note that while some smaller groups appear
148 * early in the list, smaller groups are generally ignored when iterating
149 * through this list. ffdhe_custom must not appear in this list. */
150 #define ECGROUP(name, size, oid, assumeSupported) \
151 { \
152 ssl_grp_ec_##name, size, ssl_kea_ecdh, \
153 SEC_OID_SECG_EC_##oid, assumeSupported \
154 }
155 #define FFGROUP(size) \
156 { \
157 ssl_grp_ffdhe_##size, size, ssl_kea_dh, \
158 SEC_OID_TLS_FFDHE_##size, PR_TRUE \
159 }
160
161 const sslNamedGroupDef ssl_named_groups[] = {
162 /* Note that 256 for 25519 is a lie, but we only use it for checking bit
163 * security and expect 256 bits there (not 255). */
164 { ssl_grp_ec_curve25519, 256, ssl_kea_ecdh, SEC_OID_CURVE25519, PR_TRUE },
165 ECGROUP(secp256r1, 256, SECP256R1, PR_TRUE),
166 ECGROUP(secp384r1, 384, SECP384R1, PR_TRUE),
167 ECGROUP(secp521r1, 521, SECP521R1, PR_TRUE),
168 FFGROUP(2048),
169 FFGROUP(3072),
170 FFGROUP(4096),
171 FFGROUP(6144),
172 FFGROUP(8192),
173 ECGROUP(secp192r1, 192, SECP192R1, PR_FALSE),
174 ECGROUP(secp160r2, 160, SECP160R2, PR_FALSE),
175 ECGROUP(secp160k1, 160, SECP160K1, PR_FALSE),
176 ECGROUP(secp160r1, 160, SECP160R1, PR_FALSE),
177 ECGROUP(sect163k1, 163, SECT163K1, PR_FALSE),
178 ECGROUP(sect163r1, 163, SECT163R1, PR_FALSE),
179 ECGROUP(sect163r2, 163, SECT163R2, PR_FALSE),
180 ECGROUP(secp192k1, 192, SECP192K1, PR_FALSE),
181 ECGROUP(sect193r1, 193, SECT193R1, PR_FALSE),
182 ECGROUP(sect193r2, 193, SECT193R2, PR_FALSE),
183 ECGROUP(secp224r1, 224, SECP224R1, PR_FALSE),
184 ECGROUP(secp224k1, 224, SECP224K1, PR_FALSE),
185 ECGROUP(sect233k1, 233, SECT233K1, PR_FALSE),
186 ECGROUP(sect233r1, 233, SECT233R1, PR_FALSE),
187 ECGROUP(sect239k1, 239, SECT239K1, PR_FALSE),
188 ECGROUP(secp256k1, 256, SECP256K1, PR_FALSE),
189 ECGROUP(sect283k1, 283, SECT283K1, PR_FALSE),
190 ECGROUP(sect283r1, 283, SECT283R1, PR_FALSE),
191 ECGROUP(sect409k1, 409, SECT409K1, PR_FALSE),
192 ECGROUP(sect409r1, 409, SECT409R1, PR_FALSE),
193 ECGROUP(sect571k1, 571, SECT571K1, PR_FALSE),
194 ECGROUP(sect571r1, 571, SECT571R1, PR_FALSE),
195 };
196 PR_STATIC_ASSERT(SSL_NAMED_GROUP_COUNT == PR_ARRAY_SIZE(ssl_named_groups));
197
198 #undef ECGROUP
199 #undef FFGROUP
200
201 /* forward declarations. */
202 static sslSocket *ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant variant);
203 static SECStatus ssl_MakeLocks(sslSocket *ss);
204 static void ssl_SetDefaultsFromEnvironment(void);
205 static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack,
206 PRDescIdentity id);
207
208 /************************************************************************/
209
210 /*
211 ** Lookup a socket structure from a file descriptor.
212 ** Only functions called through the PRIOMethods table should use this.
213 ** Other app-callable functions should use ssl_FindSocket.
214 */
215 static sslSocket *
ssl_GetPrivate(PRFileDesc * fd)216 ssl_GetPrivate(PRFileDesc *fd)
217 {
218 sslSocket *ss;
219
220 PORT_Assert(fd != NULL);
221 PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
222 PORT_Assert(fd->identity == ssl_layer_id);
223
224 if (fd->methods->file_type != PR_DESC_LAYERED ||
225 fd->identity != ssl_layer_id) {
226 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
227 return NULL;
228 }
229
230 ss = (sslSocket *)fd->secret;
231 /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
232 * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
233 * contents of the PRFileDesc pointed by ss->fd and the new layer.
234 * See bug 807250.
235 */
236 ss->fd = fd;
237 return ss;
238 }
239
240 /* This function tries to find the SSL layer in the stack.
241 * It searches for the first SSL layer at or below the argument fd,
242 * and failing that, it searches for the nearest SSL layer above the
243 * argument fd. It returns the private sslSocket from the found layer.
244 */
245 sslSocket *
ssl_FindSocket(PRFileDesc * fd)246 ssl_FindSocket(PRFileDesc *fd)
247 {
248 PRFileDesc *layer;
249 sslSocket *ss;
250
251 PORT_Assert(fd != NULL);
252 PORT_Assert(ssl_layer_id != 0);
253
254 layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
255 if (layer == NULL) {
256 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
257 return NULL;
258 }
259
260 ss = (sslSocket *)layer->secret;
261 /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
262 * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
263 * contents of the PRFileDesc pointed by ss->fd and the new layer.
264 * See bug 807250.
265 */
266 ss->fd = layer;
267 return ss;
268 }
269
270 static sslSocket *
ssl_DupSocket(sslSocket * os)271 ssl_DupSocket(sslSocket *os)
272 {
273 sslSocket *ss;
274 SECStatus rv;
275
276 ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant);
277 if (!ss) {
278 return NULL;
279 }
280
281 ss->opt = os->opt;
282 ss->opt.useSocks = PR_FALSE;
283 rv = SECITEM_CopyItem(NULL, &ss->opt.nextProtoNego, &os->opt.nextProtoNego);
284 if (rv != SECSuccess) {
285 goto loser;
286 }
287 ss->vrange = os->vrange;
288 ss->now = os->now;
289 ss->nowArg = os->nowArg;
290
291 ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID);
292 ss->url = !os->url ? NULL : PORT_Strdup(os->url);
293
294 ss->ops = os->ops;
295 ss->rTimeout = os->rTimeout;
296 ss->wTimeout = os->wTimeout;
297 ss->cTimeout = os->cTimeout;
298 ss->dbHandle = os->dbHandle;
299
300 /* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
301 PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
302 PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, os->ssl3.dtlsSRTPCiphers,
303 sizeof(PRUint16) * os->ssl3.dtlsSRTPCipherCount);
304 ss->ssl3.dtlsSRTPCipherCount = os->ssl3.dtlsSRTPCipherCount;
305 PORT_Memcpy(ss->ssl3.signatureSchemes, os->ssl3.signatureSchemes,
306 sizeof(ss->ssl3.signatureSchemes[0]) *
307 os->ssl3.signatureSchemeCount);
308 ss->ssl3.signatureSchemeCount = os->ssl3.signatureSchemeCount;
309 ss->ssl3.downgradeCheckVersion = os->ssl3.downgradeCheckVersion;
310
311 ss->ssl3.dheWeakGroupEnabled = os->ssl3.dheWeakGroupEnabled;
312
313 if (ss->opt.useSecurity) {
314 PRCList *cursor;
315
316 for (cursor = PR_NEXT_LINK(&os->serverCerts);
317 cursor != &os->serverCerts;
318 cursor = PR_NEXT_LINK(cursor)) {
319 sslServerCert *sc = ssl_CopyServerCert((sslServerCert *)cursor);
320 if (!sc)
321 goto loser;
322 PR_APPEND_LINK(&sc->link, &ss->serverCerts);
323 }
324
325 for (cursor = PR_NEXT_LINK(&os->ephemeralKeyPairs);
326 cursor != &os->ephemeralKeyPairs;
327 cursor = PR_NEXT_LINK(cursor)) {
328 sslEphemeralKeyPair *okp = (sslEphemeralKeyPair *)cursor;
329 sslEphemeralKeyPair *skp = ssl_CopyEphemeralKeyPair(okp);
330 if (!skp)
331 goto loser;
332 PR_APPEND_LINK(&skp->link, &ss->ephemeralKeyPairs);
333 }
334
335 for (cursor = PR_NEXT_LINK(&os->extensionHooks);
336 cursor != &os->extensionHooks;
337 cursor = PR_NEXT_LINK(cursor)) {
338 sslCustomExtensionHooks *oh = (sslCustomExtensionHooks *)cursor;
339 sslCustomExtensionHooks *sh = PORT_ZNew(sslCustomExtensionHooks);
340 if (!sh) {
341 goto loser;
342 }
343 *sh = *oh;
344 PR_APPEND_LINK(&sh->link, &ss->extensionHooks);
345 }
346
347 /*
348 * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL.
349 * XXX We should detect this, and not just march on with NULL pointers.
350 */
351 ss->authCertificate = os->authCertificate;
352 ss->authCertificateArg = os->authCertificateArg;
353 ss->getClientAuthData = os->getClientAuthData;
354 ss->getClientAuthDataArg = os->getClientAuthDataArg;
355 ss->sniSocketConfig = os->sniSocketConfig;
356 ss->sniSocketConfigArg = os->sniSocketConfigArg;
357 ss->alertReceivedCallback = os->alertReceivedCallback;
358 ss->alertReceivedCallbackArg = os->alertReceivedCallbackArg;
359 ss->alertSentCallback = os->alertSentCallback;
360 ss->alertSentCallbackArg = os->alertSentCallbackArg;
361 ss->handleBadCert = os->handleBadCert;
362 ss->badCertArg = os->badCertArg;
363 ss->handshakeCallback = os->handshakeCallback;
364 ss->handshakeCallbackData = os->handshakeCallbackData;
365 ss->canFalseStartCallback = os->canFalseStartCallback;
366 ss->canFalseStartCallbackData = os->canFalseStartCallbackData;
367 ss->pkcs11PinArg = os->pkcs11PinArg;
368 ss->nextProtoCallback = os->nextProtoCallback;
369 ss->nextProtoArg = os->nextProtoArg;
370 PORT_Memcpy((void *)ss->namedGroupPreferences,
371 os->namedGroupPreferences,
372 sizeof(ss->namedGroupPreferences));
373 ss->additionalShares = os->additionalShares;
374 ss->resumptionTokenCallback = os->resumptionTokenCallback;
375 ss->resumptionTokenContext = os->resumptionTokenContext;
376
377 rv = tls13_CopyEchConfigs(&os->echConfigs, &ss->echConfigs);
378 if (rv != SECSuccess) {
379 goto loser;
380 }
381 if (os->echPrivKey && os->echPubKey) {
382 ss->echPrivKey = SECKEY_CopyPrivateKey(os->echPrivKey);
383 ss->echPubKey = SECKEY_CopyPublicKey(os->echPubKey);
384 if (!ss->echPrivKey || !ss->echPubKey) {
385 goto loser;
386 }
387 }
388
389 if (os->antiReplay) {
390 ss->antiReplay = tls13_RefAntiReplayContext(os->antiReplay);
391 PORT_Assert(ss->antiReplay); /* Can't fail. */
392 if (!ss->antiReplay) {
393 goto loser;
394 }
395 }
396 if (os->psk) {
397 ss->psk = tls13_CopyPsk(os->psk);
398 if (!ss->psk) {
399 goto loser;
400 }
401 }
402
403 /* Create security data */
404 rv = ssl_CopySecurityInfo(ss, os);
405 if (rv != SECSuccess) {
406 goto loser;
407 }
408 }
409
410 return ss;
411
412 loser:
413 ssl_FreeSocket(ss);
414 return NULL;
415 }
416
417 static void
ssl_DestroyLocks(sslSocket * ss)418 ssl_DestroyLocks(sslSocket *ss)
419 {
420 /* Destroy locks. */
421 if (ss->firstHandshakeLock) {
422 PZ_DestroyMonitor(ss->firstHandshakeLock);
423 ss->firstHandshakeLock = NULL;
424 }
425 if (ss->ssl3HandshakeLock) {
426 PZ_DestroyMonitor(ss->ssl3HandshakeLock);
427 ss->ssl3HandshakeLock = NULL;
428 }
429 if (ss->specLock) {
430 NSSRWLock_Destroy(ss->specLock);
431 ss->specLock = NULL;
432 }
433
434 if (ss->recvLock) {
435 PZ_DestroyLock(ss->recvLock);
436 ss->recvLock = NULL;
437 }
438 if (ss->sendLock) {
439 PZ_DestroyLock(ss->sendLock);
440 ss->sendLock = NULL;
441 }
442 if (ss->xmitBufLock) {
443 PZ_DestroyMonitor(ss->xmitBufLock);
444 ss->xmitBufLock = NULL;
445 }
446 if (ss->recvBufLock) {
447 PZ_DestroyMonitor(ss->recvBufLock);
448 ss->recvBufLock = NULL;
449 }
450 }
451
452 /* Caller holds any relevant locks */
453 static void
ssl_DestroySocketContents(sslSocket * ss)454 ssl_DestroySocketContents(sslSocket *ss)
455 {
456 PRCList *cursor;
457
458 /* Free up socket */
459 ssl_DestroySecurityInfo(&ss->sec);
460
461 ssl3_DestroySSL3Info(ss);
462
463 PORT_Free(ss->saveBuf.buf);
464 PORT_Free(ss->pendingBuf.buf);
465 ssl3_DestroyGather(&ss->gs);
466
467 if (ss->peerID != NULL)
468 PORT_Free(ss->peerID);
469 if (ss->url != NULL)
470 PORT_Free((void *)ss->url); /* CONST */
471
472 /* Clean up server certificates and sundries. */
473 while (!PR_CLIST_IS_EMPTY(&ss->serverCerts)) {
474 cursor = PR_LIST_TAIL(&ss->serverCerts);
475 PR_REMOVE_LINK(cursor);
476 ssl_FreeServerCert((sslServerCert *)cursor);
477 }
478
479 /* Remove extension handlers. */
480 ssl_ClearPRCList(&ss->extensionHooks, NULL);
481
482 ssl_FreeEphemeralKeyPairs(ss);
483 SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
484 ssl3_FreeSniNameArray(&ss->xtnData);
485
486 ssl_ClearPRCList(&ss->ssl3.hs.dtlsSentHandshake, NULL);
487 ssl_ClearPRCList(&ss->ssl3.hs.dtlsRcvdHandshake, NULL);
488 tls13_DestroyPskList(&ss->ssl3.hs.psks);
489
490 tls13_ReleaseAntiReplayContext(ss->antiReplay);
491
492 tls13_DestroyPsk(ss->psk);
493
494 tls13_DestroyEchConfigs(&ss->echConfigs);
495 SECKEY_DestroyPrivateKey(ss->echPrivKey);
496 SECKEY_DestroyPublicKey(ss->echPubKey);
497 }
498
499 /*
500 * free an sslSocket struct, and all the stuff that hangs off of it
501 */
502 void
ssl_FreeSocket(sslSocket * ss)503 ssl_FreeSocket(sslSocket *ss)
504 {
505 /* Get every lock you can imagine!
506 ** Caller already holds these:
507 ** SSL_LOCK_READER(ss);
508 ** SSL_LOCK_WRITER(ss);
509 */
510 ssl_Get1stHandshakeLock(ss);
511 ssl_GetRecvBufLock(ss);
512 ssl_GetSSL3HandshakeLock(ss);
513 ssl_GetXmitBufLock(ss);
514 ssl_GetSpecWriteLock(ss);
515
516 ssl_DestroySocketContents(ss);
517
518 /* Release all the locks acquired above. */
519 SSL_UNLOCK_READER(ss);
520 SSL_UNLOCK_WRITER(ss);
521 ssl_Release1stHandshakeLock(ss);
522 ssl_ReleaseRecvBufLock(ss);
523 ssl_ReleaseSSL3HandshakeLock(ss);
524 ssl_ReleaseXmitBufLock(ss);
525 ssl_ReleaseSpecWriteLock(ss);
526
527 ssl_DestroyLocks(ss);
528
529 #ifdef DEBUG
530 PORT_Memset(ss, 0x1f, sizeof *ss);
531 #endif
532 PORT_Free(ss);
533 return;
534 }
535
536 /************************************************************************/
537 SECStatus
ssl_EnableNagleDelay(sslSocket * ss,PRBool enabled)538 ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
539 {
540 PRFileDesc *osfd = ss->fd->lower;
541 SECStatus rv = SECFailure;
542 PRSocketOptionData opt;
543
544 opt.option = PR_SockOpt_NoDelay;
545 opt.value.no_delay = (PRBool)!enabled;
546
547 if (osfd->methods->setsocketoption) {
548 rv = (SECStatus)osfd->methods->setsocketoption(osfd, &opt);
549 } else {
550 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
551 }
552
553 return rv;
554 }
555
556 static void
ssl_ChooseOps(sslSocket * ss)557 ssl_ChooseOps(sslSocket *ss)
558 {
559 ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
560 }
561
562 /* Called from SSL_Enable (immediately below) */
563 static SECStatus
PrepareSocket(sslSocket * ss)564 PrepareSocket(sslSocket *ss)
565 {
566 SECStatus rv = SECSuccess;
567
568 ssl_ChooseOps(ss);
569 return rv;
570 }
571
572 SECStatus
SSL_Enable(PRFileDesc * fd,int which,PRIntn on)573 SSL_Enable(PRFileDesc *fd, int which, PRIntn on)
574 {
575 return SSL_OptionSet(fd, which, on);
576 }
577
578 static PRBool ssl_VersionIsSupportedByPolicy(
579 SSLProtocolVariant protocolVariant, SSL3ProtocolVersion version);
580
581 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in
582 * ssl.h in the section "SSL version range setting API".
583 */
584 static void
ssl_EnableTLS(SSLVersionRange * vrange,PRIntn enable)585 ssl_EnableTLS(SSLVersionRange *vrange, PRIntn enable)
586 {
587 if (enable) {
588 /* don't turn it on if tls1.0 disallowed by by policy */
589 if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream,
590 SSL_LIBRARY_VERSION_TLS_1_0)) {
591 return;
592 }
593 }
594 if (SSL_ALL_VERSIONS_DISABLED(vrange)) {
595 if (enable) {
596 vrange->min = SSL_LIBRARY_VERSION_TLS_1_0;
597 vrange->max = SSL_LIBRARY_VERSION_TLS_1_0;
598 } /* else don't change anything */
599 return;
600 }
601
602 if (enable) {
603 /* Expand the range of enabled version to include TLS 1.0 */
604 vrange->min = PR_MIN(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
605 vrange->max = PR_MAX(vrange->max, SSL_LIBRARY_VERSION_TLS_1_0);
606 } else {
607 /* Disable all TLS versions, leaving only SSL 3.0 if it was enabled */
608 if (vrange->min == SSL_LIBRARY_VERSION_3_0) {
609 vrange->max = SSL_LIBRARY_VERSION_3_0;
610 } else {
611 /* Only TLS was enabled, so now no versions are. */
612 vrange->min = SSL_LIBRARY_VERSION_NONE;
613 vrange->max = SSL_LIBRARY_VERSION_NONE;
614 }
615 }
616 }
617
618 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_SSL3, on) described in
619 * ssl.h in the section "SSL version range setting API".
620 */
621 static void
ssl_EnableSSL3(SSLVersionRange * vrange,PRIntn enable)622 ssl_EnableSSL3(SSLVersionRange *vrange, PRIntn enable)
623 {
624 if (enable) {
625 /* don't turn it on if ssl3 disallowed by by policy */
626 if (!ssl_VersionIsSupportedByPolicy(ssl_variant_stream,
627 SSL_LIBRARY_VERSION_3_0)) {
628 return;
629 }
630 }
631 if (SSL_ALL_VERSIONS_DISABLED(vrange)) {
632 if (enable) {
633 vrange->min = SSL_LIBRARY_VERSION_3_0;
634 vrange->max = SSL_LIBRARY_VERSION_3_0;
635 } /* else don't change anything */
636 return;
637 }
638
639 if (enable) {
640 /* Expand the range of enabled versions to include SSL 3.0. We know
641 * SSL 3.0 or some version of TLS is already enabled at this point, so
642 * we don't need to change vrange->max.
643 */
644 vrange->min = SSL_LIBRARY_VERSION_3_0;
645 } else {
646 /* Disable SSL 3.0, leaving TLS unaffected. */
647 if (vrange->max > SSL_LIBRARY_VERSION_3_0) {
648 vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
649 } else {
650 /* Only SSL 3.0 was enabled, so now no versions are. */
651 vrange->min = SSL_LIBRARY_VERSION_NONE;
652 vrange->max = SSL_LIBRARY_VERSION_NONE;
653 }
654 }
655 }
656
657 SECStatus
SSL_OptionSet(PRFileDesc * fd,PRInt32 which,PRIntn val)658 SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRIntn val)
659 {
660 sslSocket *ss = ssl_FindSocket(fd);
661 SECStatus rv = SECSuccess;
662 PRBool holdingLocks;
663
664 if (!ss) {
665 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
666 return SECFailure;
667 }
668
669 holdingLocks = (!ss->opt.noLocks);
670 ssl_Get1stHandshakeLock(ss);
671 ssl_GetSSL3HandshakeLock(ss);
672
673 switch (which) {
674 case SSL_SOCKS:
675 ss->opt.useSocks = PR_FALSE;
676 rv = PrepareSocket(ss);
677 if (val) {
678 PORT_SetError(SEC_ERROR_INVALID_ARGS);
679 rv = SECFailure;
680 }
681 break;
682
683 case SSL_SECURITY:
684 ss->opt.useSecurity = val;
685 rv = PrepareSocket(ss);
686 break;
687
688 case SSL_REQUEST_CERTIFICATE:
689 ss->opt.requestCertificate = val;
690 break;
691
692 case SSL_REQUIRE_CERTIFICATE:
693 ss->opt.requireCertificate = val;
694 break;
695
696 case SSL_HANDSHAKE_AS_CLIENT:
697 if (ss->opt.handshakeAsServer && val) {
698 PORT_SetError(SEC_ERROR_INVALID_ARGS);
699 rv = SECFailure;
700 break;
701 }
702 ss->opt.handshakeAsClient = val;
703 break;
704
705 case SSL_HANDSHAKE_AS_SERVER:
706 if (ss->opt.handshakeAsClient && val) {
707 PORT_SetError(SEC_ERROR_INVALID_ARGS);
708 rv = SECFailure;
709 break;
710 }
711 ss->opt.handshakeAsServer = val;
712 break;
713
714 case SSL_ENABLE_TLS:
715 if (IS_DTLS(ss)) {
716 if (val) {
717 PORT_SetError(SEC_ERROR_INVALID_ARGS);
718 rv = SECFailure; /* not allowed */
719 }
720 break;
721 }
722 ssl_EnableTLS(&ss->vrange, val);
723 break;
724
725 case SSL_ENABLE_SSL3:
726 if (IS_DTLS(ss)) {
727 if (val) {
728 PORT_SetError(SEC_ERROR_INVALID_ARGS);
729 rv = SECFailure; /* not allowed */
730 }
731 break;
732 }
733 ssl_EnableSSL3(&ss->vrange, val);
734 break;
735
736 case SSL_ENABLE_SSL2:
737 case SSL_V2_COMPATIBLE_HELLO:
738 /* We no longer support SSL v2.
739 * However, if an old application requests to disable SSL v2,
740 * we shouldn't fail.
741 */
742 if (val) {
743 PORT_SetError(SEC_ERROR_INVALID_ARGS);
744 rv = SECFailure;
745 }
746 break;
747
748 case SSL_NO_CACHE:
749 ss->opt.noCache = val;
750 break;
751
752 case SSL_ENABLE_FDX:
753 if (val && ss->opt.noLocks) {
754 PORT_SetError(SEC_ERROR_INVALID_ARGS);
755 rv = SECFailure;
756 }
757 ss->opt.fdx = val;
758 break;
759
760 case SSL_ROLLBACK_DETECTION:
761 ss->opt.detectRollBack = val;
762 break;
763
764 case SSL_NO_STEP_DOWN:
765 break;
766
767 case SSL_BYPASS_PKCS11:
768 break;
769
770 case SSL_NO_LOCKS:
771 if (val && ss->opt.fdx) {
772 PORT_SetError(SEC_ERROR_INVALID_ARGS);
773 rv = SECFailure;
774 }
775 if (val && ssl_force_locks)
776 val = PR_FALSE; /* silent override */
777 ss->opt.noLocks = val;
778 if (val) {
779 locksEverDisabled = PR_TRUE;
780 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
781 } else if (!holdingLocks) {
782 rv = ssl_MakeLocks(ss);
783 if (rv != SECSuccess) {
784 ss->opt.noLocks = PR_TRUE;
785 }
786 }
787 break;
788
789 case SSL_ENABLE_SESSION_TICKETS:
790 ss->opt.enableSessionTickets = val;
791 break;
792
793 case SSL_ENABLE_DEFLATE:
794 ss->opt.enableDeflate = val;
795 break;
796
797 case SSL_ENABLE_RENEGOTIATION:
798 if (IS_DTLS(ss) && val != SSL_RENEGOTIATE_NEVER) {
799 PORT_SetError(SEC_ERROR_INVALID_ARGS);
800 rv = SECFailure;
801 break;
802 }
803 ss->opt.enableRenegotiation = val;
804 break;
805
806 case SSL_REQUIRE_SAFE_NEGOTIATION:
807 ss->opt.requireSafeNegotiation = val;
808 break;
809
810 case SSL_ENABLE_FALSE_START:
811 ss->opt.enableFalseStart = val;
812 break;
813
814 case SSL_CBC_RANDOM_IV:
815 ss->opt.cbcRandomIV = val;
816 break;
817
818 case SSL_ENABLE_OCSP_STAPLING:
819 ss->opt.enableOCSPStapling = val;
820 break;
821
822 case SSL_ENABLE_DELEGATED_CREDENTIALS:
823 ss->opt.enableDelegatedCredentials = val;
824 break;
825
826 case SSL_ENABLE_NPN:
827 break;
828
829 case SSL_ENABLE_ALPN:
830 ss->opt.enableALPN = val;
831 break;
832
833 case SSL_REUSE_SERVER_ECDHE_KEY:
834 ss->opt.reuseServerECDHEKey = val;
835 break;
836
837 case SSL_ENABLE_FALLBACK_SCSV:
838 ss->opt.enableFallbackSCSV = val;
839 break;
840
841 case SSL_ENABLE_SERVER_DHE:
842 ss->opt.enableServerDhe = val;
843 break;
844
845 case SSL_ENABLE_EXTENDED_MASTER_SECRET:
846 ss->opt.enableExtendedMS = val;
847 break;
848
849 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
850 ss->opt.enableSignedCertTimestamps = val;
851 break;
852
853 case SSL_REQUIRE_DH_NAMED_GROUPS:
854 ss->opt.requireDHENamedGroups = val;
855 break;
856
857 case SSL_ENABLE_0RTT_DATA:
858 ss->opt.enable0RttData = val;
859 break;
860
861 case SSL_RECORD_SIZE_LIMIT:
862 if (val < 64 || val > (MAX_FRAGMENT_LENGTH + 1)) {
863 PORT_SetError(SEC_ERROR_INVALID_ARGS);
864 rv = SECFailure;
865 } else {
866 ss->opt.recordSizeLimit = val;
867 }
868 break;
869
870 case SSL_ENABLE_TLS13_COMPAT_MODE:
871 ss->opt.enableTls13CompatMode = val;
872 break;
873
874 case SSL_ENABLE_DTLS_SHORT_HEADER:
875 ss->opt.enableDtlsShortHeader = val;
876 break;
877
878 case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
879 ss->opt.enableHelloDowngradeCheck = val;
880 break;
881
882 case SSL_ENABLE_V2_COMPATIBLE_HELLO:
883 ss->opt.enableV2CompatibleHello = val;
884 break;
885
886 case SSL_ENABLE_POST_HANDSHAKE_AUTH:
887 ss->opt.enablePostHandshakeAuth = val;
888 break;
889
890 case SSL_SUPPRESS_END_OF_EARLY_DATA:
891 ss->opt.suppressEndOfEarlyData = val;
892 break;
893
894 default:
895 PORT_SetError(SEC_ERROR_INVALID_ARGS);
896 rv = SECFailure;
897 }
898
899 /* We can't use the macros for releasing the locks here,
900 * because ss->opt.noLocks might have changed just above.
901 * We must release these locks (monitors) here, if we aquired them above,
902 * regardless of the current value of ss->opt.noLocks.
903 */
904 if (holdingLocks) {
905 PZ_ExitMonitor((ss)->ssl3HandshakeLock);
906 PZ_ExitMonitor((ss)->firstHandshakeLock);
907 }
908
909 return rv;
910 }
911
912 SECStatus
SSL_OptionGet(PRFileDesc * fd,PRInt32 which,PRIntn * pVal)913 SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRIntn *pVal)
914 {
915 sslSocket *ss = ssl_FindSocket(fd);
916 SECStatus rv = SECSuccess;
917 PRIntn val = PR_FALSE;
918
919 if (!pVal) {
920 PORT_SetError(SEC_ERROR_INVALID_ARGS);
921 return SECFailure;
922 }
923 if (!ss) {
924 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
925 *pVal = PR_FALSE;
926 return SECFailure;
927 }
928
929 ssl_Get1stHandshakeLock(ss);
930 ssl_GetSSL3HandshakeLock(ss);
931
932 switch (which) {
933 case SSL_SOCKS:
934 val = PR_FALSE;
935 break;
936 case SSL_SECURITY:
937 val = ss->opt.useSecurity;
938 break;
939 case SSL_REQUEST_CERTIFICATE:
940 val = ss->opt.requestCertificate;
941 break;
942 case SSL_REQUIRE_CERTIFICATE:
943 val = ss->opt.requireCertificate;
944 break;
945 case SSL_HANDSHAKE_AS_CLIENT:
946 val = ss->opt.handshakeAsClient;
947 break;
948 case SSL_HANDSHAKE_AS_SERVER:
949 val = ss->opt.handshakeAsServer;
950 break;
951 case SSL_ENABLE_TLS:
952 val = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0;
953 break;
954 case SSL_ENABLE_SSL3:
955 val = ss->vrange.min == SSL_LIBRARY_VERSION_3_0;
956 break;
957 case SSL_ENABLE_SSL2:
958 case SSL_V2_COMPATIBLE_HELLO:
959 val = PR_FALSE;
960 break;
961 case SSL_NO_CACHE:
962 val = ss->opt.noCache;
963 break;
964 case SSL_ENABLE_FDX:
965 val = ss->opt.fdx;
966 break;
967 case SSL_ROLLBACK_DETECTION:
968 val = ss->opt.detectRollBack;
969 break;
970 case SSL_NO_STEP_DOWN:
971 val = PR_FALSE;
972 break;
973 case SSL_BYPASS_PKCS11:
974 val = PR_FALSE;
975 break;
976 case SSL_NO_LOCKS:
977 val = ss->opt.noLocks;
978 break;
979 case SSL_ENABLE_SESSION_TICKETS:
980 val = ss->opt.enableSessionTickets;
981 break;
982 case SSL_ENABLE_DEFLATE:
983 val = ss->opt.enableDeflate;
984 break;
985 case SSL_ENABLE_RENEGOTIATION:
986 val = ss->opt.enableRenegotiation;
987 break;
988 case SSL_REQUIRE_SAFE_NEGOTIATION:
989 val = ss->opt.requireSafeNegotiation;
990 break;
991 case SSL_ENABLE_FALSE_START:
992 val = ss->opt.enableFalseStart;
993 break;
994 case SSL_CBC_RANDOM_IV:
995 val = ss->opt.cbcRandomIV;
996 break;
997 case SSL_ENABLE_OCSP_STAPLING:
998 val = ss->opt.enableOCSPStapling;
999 break;
1000 case SSL_ENABLE_DELEGATED_CREDENTIALS:
1001 val = ss->opt.enableDelegatedCredentials;
1002 break;
1003 case SSL_ENABLE_NPN:
1004 val = PR_FALSE;
1005 break;
1006 case SSL_ENABLE_ALPN:
1007 val = ss->opt.enableALPN;
1008 break;
1009 case SSL_REUSE_SERVER_ECDHE_KEY:
1010 val = ss->opt.reuseServerECDHEKey;
1011 break;
1012 case SSL_ENABLE_FALLBACK_SCSV:
1013 val = ss->opt.enableFallbackSCSV;
1014 break;
1015 case SSL_ENABLE_SERVER_DHE:
1016 val = ss->opt.enableServerDhe;
1017 break;
1018 case SSL_ENABLE_EXTENDED_MASTER_SECRET:
1019 val = ss->opt.enableExtendedMS;
1020 break;
1021 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
1022 val = ss->opt.enableSignedCertTimestamps;
1023 break;
1024 case SSL_REQUIRE_DH_NAMED_GROUPS:
1025 val = ss->opt.requireDHENamedGroups;
1026 break;
1027 case SSL_ENABLE_0RTT_DATA:
1028 val = ss->opt.enable0RttData;
1029 break;
1030 case SSL_RECORD_SIZE_LIMIT:
1031 val = ss->opt.recordSizeLimit;
1032 break;
1033 case SSL_ENABLE_TLS13_COMPAT_MODE:
1034 val = ss->opt.enableTls13CompatMode;
1035 break;
1036 case SSL_ENABLE_DTLS_SHORT_HEADER:
1037 val = ss->opt.enableDtlsShortHeader;
1038 break;
1039 case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
1040 val = ss->opt.enableHelloDowngradeCheck;
1041 break;
1042 case SSL_ENABLE_V2_COMPATIBLE_HELLO:
1043 val = ss->opt.enableV2CompatibleHello;
1044 break;
1045 case SSL_ENABLE_POST_HANDSHAKE_AUTH:
1046 val = ss->opt.enablePostHandshakeAuth;
1047 break;
1048 case SSL_SUPPRESS_END_OF_EARLY_DATA:
1049 val = ss->opt.suppressEndOfEarlyData;
1050 break;
1051 default:
1052 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1053 rv = SECFailure;
1054 }
1055
1056 ssl_ReleaseSSL3HandshakeLock(ss);
1057 ssl_Release1stHandshakeLock(ss);
1058
1059 *pVal = val;
1060 return rv;
1061 }
1062
1063 SECStatus
SSL_OptionGetDefault(PRInt32 which,PRIntn * pVal)1064 SSL_OptionGetDefault(PRInt32 which, PRIntn *pVal)
1065 {
1066 SECStatus rv = SECSuccess;
1067 PRIntn val = PR_FALSE;
1068
1069 if (!pVal) {
1070 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1071 return SECFailure;
1072 }
1073
1074 ssl_SetDefaultsFromEnvironment();
1075
1076 switch (which) {
1077 case SSL_SOCKS:
1078 val = PR_FALSE;
1079 break;
1080 case SSL_SECURITY:
1081 val = ssl_defaults.useSecurity;
1082 break;
1083 case SSL_REQUEST_CERTIFICATE:
1084 val = ssl_defaults.requestCertificate;
1085 break;
1086 case SSL_REQUIRE_CERTIFICATE:
1087 val = ssl_defaults.requireCertificate;
1088 break;
1089 case SSL_HANDSHAKE_AS_CLIENT:
1090 val = ssl_defaults.handshakeAsClient;
1091 break;
1092 case SSL_HANDSHAKE_AS_SERVER:
1093 val = ssl_defaults.handshakeAsServer;
1094 break;
1095 case SSL_ENABLE_TLS:
1096 val = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0;
1097 break;
1098 case SSL_ENABLE_SSL3:
1099 val = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0;
1100 break;
1101 case SSL_ENABLE_SSL2:
1102 case SSL_V2_COMPATIBLE_HELLO:
1103 val = PR_FALSE;
1104 break;
1105 case SSL_NO_CACHE:
1106 val = ssl_defaults.noCache;
1107 break;
1108 case SSL_ENABLE_FDX:
1109 val = ssl_defaults.fdx;
1110 break;
1111 case SSL_ROLLBACK_DETECTION:
1112 val = ssl_defaults.detectRollBack;
1113 break;
1114 case SSL_NO_STEP_DOWN:
1115 val = PR_FALSE;
1116 break;
1117 case SSL_BYPASS_PKCS11:
1118 val = PR_FALSE;
1119 break;
1120 case SSL_NO_LOCKS:
1121 val = ssl_defaults.noLocks;
1122 break;
1123 case SSL_ENABLE_SESSION_TICKETS:
1124 val = ssl_defaults.enableSessionTickets;
1125 break;
1126 case SSL_ENABLE_DEFLATE:
1127 val = ssl_defaults.enableDeflate;
1128 break;
1129 case SSL_ENABLE_RENEGOTIATION:
1130 val = ssl_defaults.enableRenegotiation;
1131 break;
1132 case SSL_REQUIRE_SAFE_NEGOTIATION:
1133 val = ssl_defaults.requireSafeNegotiation;
1134 break;
1135 case SSL_ENABLE_FALSE_START:
1136 val = ssl_defaults.enableFalseStart;
1137 break;
1138 case SSL_CBC_RANDOM_IV:
1139 val = ssl_defaults.cbcRandomIV;
1140 break;
1141 case SSL_ENABLE_OCSP_STAPLING:
1142 val = ssl_defaults.enableOCSPStapling;
1143 break;
1144 case SSL_ENABLE_DELEGATED_CREDENTIALS:
1145 val = ssl_defaults.enableDelegatedCredentials;
1146 break;
1147 case SSL_ENABLE_NPN:
1148 val = PR_FALSE;
1149 break;
1150 case SSL_ENABLE_ALPN:
1151 val = ssl_defaults.enableALPN;
1152 break;
1153 case SSL_REUSE_SERVER_ECDHE_KEY:
1154 val = ssl_defaults.reuseServerECDHEKey;
1155 break;
1156 case SSL_ENABLE_FALLBACK_SCSV:
1157 val = ssl_defaults.enableFallbackSCSV;
1158 break;
1159 case SSL_ENABLE_SERVER_DHE:
1160 val = ssl_defaults.enableServerDhe;
1161 break;
1162 case SSL_ENABLE_EXTENDED_MASTER_SECRET:
1163 val = ssl_defaults.enableExtendedMS;
1164 break;
1165 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
1166 val = ssl_defaults.enableSignedCertTimestamps;
1167 break;
1168 case SSL_ENABLE_0RTT_DATA:
1169 val = ssl_defaults.enable0RttData;
1170 break;
1171 case SSL_RECORD_SIZE_LIMIT:
1172 val = ssl_defaults.recordSizeLimit;
1173 break;
1174 case SSL_ENABLE_TLS13_COMPAT_MODE:
1175 val = ssl_defaults.enableTls13CompatMode;
1176 break;
1177 case SSL_ENABLE_DTLS_SHORT_HEADER:
1178 val = ssl_defaults.enableDtlsShortHeader;
1179 break;
1180 case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
1181 val = ssl_defaults.enableHelloDowngradeCheck;
1182 break;
1183 case SSL_ENABLE_V2_COMPATIBLE_HELLO:
1184 val = ssl_defaults.enableV2CompatibleHello;
1185 break;
1186 case SSL_ENABLE_POST_HANDSHAKE_AUTH:
1187 val = ssl_defaults.enablePostHandshakeAuth;
1188 break;
1189 case SSL_SUPPRESS_END_OF_EARLY_DATA:
1190 val = ssl_defaults.suppressEndOfEarlyData;
1191 break;
1192 default:
1193 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1194 rv = SECFailure;
1195 }
1196
1197 *pVal = val;
1198 return rv;
1199 }
1200
1201 /* XXX Use Global Lock to protect this stuff. */
1202 SECStatus
SSL_EnableDefault(int which,PRIntn val)1203 SSL_EnableDefault(int which, PRIntn val)
1204 {
1205 return SSL_OptionSetDefault(which, val);
1206 }
1207
1208 SECStatus
SSL_OptionSetDefault(PRInt32 which,PRIntn val)1209 SSL_OptionSetDefault(PRInt32 which, PRIntn val)
1210 {
1211 SECStatus status = ssl_Init();
1212
1213 if (status != SECSuccess) {
1214 return status;
1215 }
1216
1217 ssl_SetDefaultsFromEnvironment();
1218
1219 switch (which) {
1220 case SSL_SOCKS:
1221 ssl_defaults.useSocks = PR_FALSE;
1222 if (val) {
1223 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1224 return SECFailure;
1225 }
1226 break;
1227
1228 case SSL_SECURITY:
1229 ssl_defaults.useSecurity = val;
1230 break;
1231
1232 case SSL_REQUEST_CERTIFICATE:
1233 ssl_defaults.requestCertificate = val;
1234 break;
1235
1236 case SSL_REQUIRE_CERTIFICATE:
1237 ssl_defaults.requireCertificate = val;
1238 break;
1239
1240 case SSL_HANDSHAKE_AS_CLIENT:
1241 if (ssl_defaults.handshakeAsServer && val) {
1242 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1243 return SECFailure;
1244 }
1245 ssl_defaults.handshakeAsClient = val;
1246 break;
1247
1248 case SSL_HANDSHAKE_AS_SERVER:
1249 if (ssl_defaults.handshakeAsClient && val) {
1250 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1251 return SECFailure;
1252 }
1253 ssl_defaults.handshakeAsServer = val;
1254 break;
1255
1256 case SSL_ENABLE_TLS:
1257 ssl_EnableTLS(&versions_defaults_stream, val);
1258 break;
1259
1260 case SSL_ENABLE_SSL3:
1261 ssl_EnableSSL3(&versions_defaults_stream, val);
1262 break;
1263
1264 case SSL_ENABLE_SSL2:
1265 case SSL_V2_COMPATIBLE_HELLO:
1266 /* We no longer support SSL v2.
1267 * However, if an old application requests to disable SSL v2,
1268 * we shouldn't fail.
1269 */
1270 if (val) {
1271 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1272 return SECFailure;
1273 }
1274 break;
1275
1276 case SSL_NO_CACHE:
1277 ssl_defaults.noCache = val;
1278 break;
1279
1280 case SSL_ENABLE_FDX:
1281 if (val && ssl_defaults.noLocks) {
1282 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1283 return SECFailure;
1284 }
1285 ssl_defaults.fdx = val;
1286 break;
1287
1288 case SSL_ROLLBACK_DETECTION:
1289 ssl_defaults.detectRollBack = val;
1290 break;
1291
1292 case SSL_NO_STEP_DOWN:
1293 break;
1294
1295 case SSL_BYPASS_PKCS11:
1296 break;
1297
1298 case SSL_NO_LOCKS:
1299 if (val && ssl_defaults.fdx) {
1300 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1301 return SECFailure;
1302 }
1303 if (val && ssl_force_locks)
1304 val = PR_FALSE; /* silent override */
1305 ssl_defaults.noLocks = val;
1306 if (val) {
1307 locksEverDisabled = PR_TRUE;
1308 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
1309 }
1310 break;
1311
1312 case SSL_ENABLE_SESSION_TICKETS:
1313 ssl_defaults.enableSessionTickets = val;
1314 break;
1315
1316 case SSL_ENABLE_DEFLATE:
1317 ssl_defaults.enableDeflate = val;
1318 break;
1319
1320 case SSL_ENABLE_RENEGOTIATION:
1321 ssl_defaults.enableRenegotiation = val;
1322 break;
1323
1324 case SSL_REQUIRE_SAFE_NEGOTIATION:
1325 ssl_defaults.requireSafeNegotiation = val;
1326 break;
1327
1328 case SSL_ENABLE_FALSE_START:
1329 ssl_defaults.enableFalseStart = val;
1330 break;
1331
1332 case SSL_CBC_RANDOM_IV:
1333 ssl_defaults.cbcRandomIV = val;
1334 break;
1335
1336 case SSL_ENABLE_OCSP_STAPLING:
1337 ssl_defaults.enableOCSPStapling = val;
1338 break;
1339
1340 case SSL_ENABLE_DELEGATED_CREDENTIALS:
1341 ssl_defaults.enableDelegatedCredentials = val;
1342 break;
1343
1344 case SSL_ENABLE_NPN:
1345 break;
1346
1347 case SSL_ENABLE_ALPN:
1348 ssl_defaults.enableALPN = val;
1349 break;
1350
1351 case SSL_REUSE_SERVER_ECDHE_KEY:
1352 ssl_defaults.reuseServerECDHEKey = val;
1353 break;
1354
1355 case SSL_ENABLE_FALLBACK_SCSV:
1356 ssl_defaults.enableFallbackSCSV = val;
1357 break;
1358
1359 case SSL_ENABLE_SERVER_DHE:
1360 ssl_defaults.enableServerDhe = val;
1361 break;
1362
1363 case SSL_ENABLE_EXTENDED_MASTER_SECRET:
1364 ssl_defaults.enableExtendedMS = val;
1365 break;
1366
1367 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
1368 ssl_defaults.enableSignedCertTimestamps = val;
1369 break;
1370
1371 case SSL_ENABLE_0RTT_DATA:
1372 ssl_defaults.enable0RttData = val;
1373 break;
1374
1375 case SSL_RECORD_SIZE_LIMIT:
1376 if (val < 64 || val > (MAX_FRAGMENT_LENGTH + 1)) {
1377 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1378 return SECFailure;
1379 }
1380 ssl_defaults.recordSizeLimit = val;
1381 break;
1382
1383 case SSL_ENABLE_TLS13_COMPAT_MODE:
1384 ssl_defaults.enableTls13CompatMode = val;
1385 break;
1386
1387 case SSL_ENABLE_DTLS_SHORT_HEADER:
1388 ssl_defaults.enableDtlsShortHeader = val;
1389 break;
1390
1391 case SSL_ENABLE_HELLO_DOWNGRADE_CHECK:
1392 ssl_defaults.enableHelloDowngradeCheck = val;
1393 break;
1394
1395 case SSL_ENABLE_V2_COMPATIBLE_HELLO:
1396 ssl_defaults.enableV2CompatibleHello = val;
1397 break;
1398
1399 case SSL_ENABLE_POST_HANDSHAKE_AUTH:
1400 ssl_defaults.enablePostHandshakeAuth = val;
1401 break;
1402
1403 case SSL_SUPPRESS_END_OF_EARLY_DATA:
1404 ssl_defaults.suppressEndOfEarlyData = val;
1405 break;
1406
1407 default:
1408 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1409 return SECFailure;
1410 }
1411 return SECSuccess;
1412 }
1413
1414 SECStatus
SSLExp_SetMaxEarlyDataSize(PRFileDesc * fd,PRUint32 size)1415 SSLExp_SetMaxEarlyDataSize(PRFileDesc *fd, PRUint32 size)
1416 {
1417 sslSocket *ss = ssl_FindSocket(fd);
1418 if (!ss) {
1419 return SECFailure; /* Error code already set. */
1420 }
1421
1422 ss->opt.maxEarlyDataSize = size;
1423 return SECSuccess;
1424 }
1425
1426 /* function tells us if the cipher suite is one that we no longer support. */
1427 static PRBool
ssl_IsRemovedCipherSuite(PRInt32 suite)1428 ssl_IsRemovedCipherSuite(PRInt32 suite)
1429 {
1430 switch (suite) {
1431 case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
1432 case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
1433 case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
1434 return PR_TRUE;
1435 default:
1436 return PR_FALSE;
1437 }
1438 }
1439
1440 /* Part of the public NSS API.
1441 * Since this is a global (not per-socket) setting, we cannot use the
1442 * HandshakeLock to protect this. Probably want a global lock.
1443 */
1444 SECStatus
SSL_SetPolicy(long which,int policy)1445 SSL_SetPolicy(long which, int policy)
1446 {
1447 if (ssl_IsRemovedCipherSuite(which))
1448 return SECSuccess;
1449 return SSL_CipherPolicySet(which, policy);
1450 }
1451
1452 SECStatus
ssl_CipherPolicySet(PRInt32 which,PRInt32 policy)1453 ssl_CipherPolicySet(PRInt32 which, PRInt32 policy)
1454 {
1455 SECStatus rv = SECSuccess;
1456
1457 if (ssl_IsRemovedCipherSuite(which)) {
1458 rv = SECSuccess;
1459 } else {
1460 rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
1461 }
1462 return rv;
1463 }
1464 SECStatus
SSL_CipherPolicySet(PRInt32 which,PRInt32 policy)1465 SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
1466 {
1467 SECStatus rv = ssl_Init();
1468
1469 if (rv != SECSuccess) {
1470 return rv;
1471 }
1472 if (NSS_IsPolicyLocked()) {
1473 PORT_SetError(SEC_ERROR_POLICY_LOCKED);
1474 return SECFailure;
1475 }
1476 return ssl_CipherPolicySet(which, policy);
1477 }
1478
1479 SECStatus
SSL_CipherPolicyGet(PRInt32 which,PRInt32 * oPolicy)1480 SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
1481 {
1482 SECStatus rv;
1483
1484 if (!oPolicy) {
1485 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1486 return SECFailure;
1487 }
1488 if (ssl_IsRemovedCipherSuite(which)) {
1489 *oPolicy = SSL_NOT_ALLOWED;
1490 rv = SECSuccess;
1491 } else {
1492 rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
1493 }
1494 return rv;
1495 }
1496
1497 /* Part of the public NSS API.
1498 * Since this is a global (not per-socket) setting, we cannot use the
1499 * HandshakeLock to protect this. Probably want a global lock.
1500 * These changes have no effect on any sslSockets already created.
1501 */
1502 SECStatus
SSL_EnableCipher(long which,PRBool enabled)1503 SSL_EnableCipher(long which, PRBool enabled)
1504 {
1505 if (ssl_IsRemovedCipherSuite(which))
1506 return SECSuccess;
1507 return SSL_CipherPrefSetDefault(which, enabled);
1508 }
1509
1510 SECStatus
ssl_CipherPrefSetDefault(PRInt32 which,PRBool enabled)1511 ssl_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
1512 {
1513 if (ssl_IsRemovedCipherSuite(which))
1514 return SECSuccess;
1515 return ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
1516 }
1517
1518 SECStatus
SSL_CipherPrefSetDefault(PRInt32 which,PRBool enabled)1519 SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
1520 {
1521 SECStatus rv = ssl_Init();
1522 PRInt32 locks;
1523
1524 if (rv != SECSuccess) {
1525 return rv;
1526 }
1527 rv = NSS_OptionGet(NSS_DEFAULT_LOCKS, &locks);
1528 if ((rv == SECSuccess) && (locks & NSS_DEFAULT_SSL_LOCK)) {
1529 return SECSuccess;
1530 }
1531 return ssl_CipherPrefSetDefault(which, enabled);
1532 }
1533
1534 SECStatus
SSL_CipherPrefGetDefault(PRInt32 which,PRBool * enabled)1535 SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
1536 {
1537 SECStatus rv;
1538
1539 if (!enabled) {
1540 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1541 return SECFailure;
1542 }
1543 if (ssl_IsRemovedCipherSuite(which)) {
1544 *enabled = PR_FALSE;
1545 rv = SECSuccess;
1546 } else {
1547 rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
1548 }
1549 return rv;
1550 }
1551
1552 SECStatus
SSL_CipherPrefSet(PRFileDesc * fd,PRInt32 which,PRBool enabled)1553 SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
1554 {
1555 sslSocket *ss = ssl_FindSocket(fd);
1556 PRInt32 locks;
1557 SECStatus rv;
1558
1559 if (!ss) {
1560 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
1561 return SECFailure;
1562 }
1563 rv = NSS_OptionGet(NSS_DEFAULT_LOCKS, &locks);
1564 if ((rv == SECSuccess) && (locks & NSS_DEFAULT_SSL_LOCK)) {
1565 return SECSuccess;
1566 }
1567 if (ssl_IsRemovedCipherSuite(which))
1568 return SECSuccess;
1569 return ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
1570 }
1571
1572 SECStatus
SSL_CipherPrefGet(PRFileDesc * fd,PRInt32 which,PRBool * enabled)1573 SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
1574 {
1575 SECStatus rv;
1576 sslSocket *ss = ssl_FindSocket(fd);
1577
1578 if (!enabled) {
1579 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1580 return SECFailure;
1581 }
1582 if (!ss) {
1583 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
1584 *enabled = PR_FALSE;
1585 return SECFailure;
1586 }
1587 if (ssl_IsRemovedCipherSuite(which)) {
1588 *enabled = PR_FALSE;
1589 rv = SECSuccess;
1590 } else {
1591 rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
1592 }
1593 return rv;
1594 }
1595
1596 /* The client can call this function to be aware of the current
1597 * CipherSuites order. */
1598 SECStatus
SSLExp_CipherSuiteOrderGet(PRFileDesc * fd,PRUint16 * cipherOrder,unsigned int * numCiphers)1599 SSLExp_CipherSuiteOrderGet(PRFileDesc *fd, PRUint16 *cipherOrder,
1600 unsigned int *numCiphers)
1601 {
1602 if (!fd) {
1603 SSL_DBG(("%d: SSL: file descriptor in CipherSuiteOrderGet is null",
1604 SSL_GETPID()));
1605 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1606 return SECFailure;
1607 }
1608 if (!cipherOrder || !numCiphers) {
1609 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1610 return SECFailure;
1611 }
1612 sslSocket *ss = ssl_FindSocket(fd);
1613 if (!ss) {
1614 SSL_DBG(("%d: SSL[%d]: bad socket in CipherSuiteOrderGet", SSL_GETPID(),
1615 fd));
1616 return SECFailure; /* Error code already set. */
1617 }
1618
1619 unsigned int enabled = 0;
1620 ssl_Get1stHandshakeLock(ss);
1621 ssl_GetSSL3HandshakeLock(ss);
1622 for (unsigned int i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
1623 const ssl3CipherSuiteCfg *suiteCfg = &ss->cipherSuites[i];
1624 if (suiteCfg && suiteCfg->enabled &&
1625 suiteCfg->policy != SSL_NOT_ALLOWED) {
1626 cipherOrder[enabled++] = suiteCfg->cipher_suite;
1627 }
1628 }
1629 ssl_ReleaseSSL3HandshakeLock(ss);
1630 ssl_Release1stHandshakeLock(ss);
1631 *numCiphers = enabled;
1632 return SECSuccess;
1633 }
1634
1635 /* This function permits reorder the CipherSuites List for the Handshake
1636 * (Client Hello). */
1637 SECStatus
SSLExp_CipherSuiteOrderSet(PRFileDesc * fd,const PRUint16 * cipherOrder,unsigned int numCiphers)1638 SSLExp_CipherSuiteOrderSet(PRFileDesc *fd, const PRUint16 *cipherOrder,
1639 unsigned int numCiphers)
1640 {
1641 if (!fd) {
1642 SSL_DBG(("%d: SSL: file descriptor in CipherSuiteOrderGet is null",
1643 SSL_GETPID()));
1644 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1645 return SECFailure;
1646 }
1647 if (!cipherOrder || !numCiphers || numCiphers > ssl_V3_SUITES_IMPLEMENTED) {
1648 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1649 return SECFailure;
1650 }
1651 sslSocket *ss = ssl_FindSocket(fd);
1652 if (!ss) {
1653 SSL_DBG(("%d: SSL[%d]: bad socket in CipherSuiteOrderSet", SSL_GETPID(),
1654 fd));
1655 return SECFailure; /* Error code already set. */
1656 }
1657 ssl3CipherSuiteCfg tmpSuiteCfg[ssl_V3_SUITES_IMPLEMENTED];
1658 ssl_Get1stHandshakeLock(ss);
1659 ssl_GetSSL3HandshakeLock(ss);
1660 /* For each cipherSuite given as input, verify that it is
1661 * known to NSS and only present in the list once. */
1662 for (unsigned int i = 0; i < numCiphers; i++) {
1663 const ssl3CipherSuiteCfg *suiteCfg =
1664 ssl_LookupCipherSuiteCfg(cipherOrder[i], ss->cipherSuites);
1665 if (!suiteCfg) {
1666 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1667 ssl_ReleaseSSL3HandshakeLock(ss);
1668 ssl_Release1stHandshakeLock(ss);
1669 return SECFailure;
1670 }
1671 for (unsigned int j = i + 1; j < numCiphers; j++) {
1672 /* This is a duplicate entry. */
1673 if (cipherOrder[i] == cipherOrder[j]) {
1674 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1675 ssl_ReleaseSSL3HandshakeLock(ss);
1676 ssl_Release1stHandshakeLock(ss);
1677 return SECFailure;
1678 }
1679 }
1680 tmpSuiteCfg[i] = *suiteCfg;
1681 tmpSuiteCfg[i].enabled = PR_TRUE;
1682 }
1683 /* Find all defined ciphersuites not present in the input list and append
1684 * them after the preferred. This guarantees that the socket will always
1685 * have a complete list of size ssl_V3_SUITES_IMPLEMENTED */
1686 unsigned int cfgIdx = numCiphers;
1687 for (unsigned int i = 0; i < ssl_V3_SUITES_IMPLEMENTED; i++) {
1688 PRBool received = PR_FALSE;
1689 for (unsigned int j = 0; j < numCiphers; j++) {
1690 if (ss->cipherSuites[i].cipher_suite ==
1691 tmpSuiteCfg[j].cipher_suite) {
1692 received = PR_TRUE;
1693 break;
1694 }
1695 }
1696 if (!received) {
1697 tmpSuiteCfg[cfgIdx] = ss->cipherSuites[i];
1698 tmpSuiteCfg[cfgIdx++].enabled = PR_FALSE;
1699 }
1700 }
1701 PORT_Assert(cfgIdx == ssl_V3_SUITES_IMPLEMENTED);
1702 /* now we can rewrite the socket with the desired order */
1703 PORT_Memcpy(ss->cipherSuites, tmpSuiteCfg, sizeof(tmpSuiteCfg));
1704 ssl_ReleaseSSL3HandshakeLock(ss);
1705 ssl_Release1stHandshakeLock(ss);
1706 return SECSuccess;
1707 }
1708
1709 SECStatus
NSS_SetDomesticPolicy(void)1710 NSS_SetDomesticPolicy(void)
1711 {
1712 SECStatus status = SECSuccess;
1713 const PRUint16 *cipher;
1714 SECStatus rv;
1715 PRUint32 policy;
1716
1717 /* If we've already defined some policy oids, skip changing them */
1718 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policy);
1719 if ((rv == SECSuccess) && (policy & NSS_USE_POLICY_IN_SSL)) {
1720 return ssl_Init(); /* make sure the policies have been loaded */
1721 }
1722
1723 for (cipher = SSL_ImplementedCiphers; *cipher != 0; ++cipher) {
1724 status = SSL_SetPolicy(*cipher, SSL_ALLOWED);
1725 if (status != SECSuccess)
1726 break;
1727 }
1728 return status;
1729 }
1730
1731 SECStatus
NSS_SetExportPolicy(void)1732 NSS_SetExportPolicy(void)
1733 {
1734 return NSS_SetDomesticPolicy();
1735 }
1736
1737 SECStatus
NSS_SetFrancePolicy(void)1738 NSS_SetFrancePolicy(void)
1739 {
1740 return NSS_SetDomesticPolicy();
1741 }
1742
1743 SECStatus
SSL_NamedGroupConfig(PRFileDesc * fd,const SSLNamedGroup * groups,unsigned int numGroups)1744 SSL_NamedGroupConfig(PRFileDesc *fd, const SSLNamedGroup *groups,
1745 unsigned int numGroups)
1746 {
1747 unsigned int i;
1748 unsigned int j = 0;
1749 sslSocket *ss = ssl_FindSocket(fd);
1750
1751 if (!ss) {
1752 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
1753 return SECFailure;
1754 }
1755
1756 if (!groups) {
1757 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1758 return SECFailure;
1759 }
1760 if (numGroups > SSL_NAMED_GROUP_COUNT) {
1761 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1762 return SECFailure;
1763 }
1764
1765 memset((void *)ss->namedGroupPreferences, 0,
1766 sizeof(ss->namedGroupPreferences));
1767 for (i = 0; i < numGroups; ++i) {
1768 const sslNamedGroupDef *groupDef = ssl_LookupNamedGroup(groups[i]);
1769 if (!ssl_NamedGroupEnabled(ss, groupDef)) {
1770 ss->namedGroupPreferences[j++] = groupDef;
1771 }
1772 }
1773
1774 return SECSuccess;
1775 }
1776
1777 SECStatus
SSL_DHEGroupPrefSet(PRFileDesc * fd,const SSLDHEGroupType * groups,PRUint16 num_groups)1778 SSL_DHEGroupPrefSet(PRFileDesc *fd, const SSLDHEGroupType *groups,
1779 PRUint16 num_groups)
1780 {
1781 sslSocket *ss;
1782 const SSLDHEGroupType *list;
1783 unsigned int count;
1784 int i, k, j;
1785 const sslNamedGroupDef *enabled[SSL_NAMED_GROUP_COUNT] = { 0 };
1786 static const SSLDHEGroupType default_dhe_groups[] = {
1787 ssl_ff_dhe_2048_group
1788 };
1789
1790 if ((num_groups && !groups) || (!num_groups && groups) ||
1791 num_groups > SSL_NAMED_GROUP_COUNT) {
1792 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1793 return SECFailure;
1794 }
1795
1796 ss = ssl_FindSocket(fd);
1797 if (!ss) {
1798 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_DHEGroupPrefSet", SSL_GETPID(), fd));
1799 return SECFailure;
1800 }
1801
1802 if (groups) {
1803 list = groups;
1804 count = num_groups;
1805 } else {
1806 list = default_dhe_groups;
1807 count = PR_ARRAY_SIZE(default_dhe_groups);
1808 }
1809
1810 /* save enabled ec groups and clear ss->namedGroupPreferences */
1811 k = 0;
1812 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
1813 if (ss->namedGroupPreferences[i] &&
1814 ss->namedGroupPreferences[i]->keaType != ssl_kea_dh) {
1815 enabled[k++] = ss->namedGroupPreferences[i];
1816 }
1817 ss->namedGroupPreferences[i] = NULL;
1818 }
1819
1820 ss->ssl3.dhePreferredGroup = NULL;
1821 for (i = 0; i < count; ++i) {
1822 PRBool duplicate = PR_FALSE;
1823 SSLNamedGroup name;
1824 const sslNamedGroupDef *groupDef;
1825 switch (list[i]) {
1826 case ssl_ff_dhe_2048_group:
1827 name = ssl_grp_ffdhe_2048;
1828 break;
1829 case ssl_ff_dhe_3072_group:
1830 name = ssl_grp_ffdhe_3072;
1831 break;
1832 case ssl_ff_dhe_4096_group:
1833 name = ssl_grp_ffdhe_4096;
1834 break;
1835 case ssl_ff_dhe_6144_group:
1836 name = ssl_grp_ffdhe_6144;
1837 break;
1838 case ssl_ff_dhe_8192_group:
1839 name = ssl_grp_ffdhe_8192;
1840 break;
1841 default:
1842 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1843 return SECFailure;
1844 }
1845 groupDef = ssl_LookupNamedGroup(name);
1846 PORT_Assert(groupDef);
1847 if (!ss->ssl3.dhePreferredGroup) {
1848 ss->ssl3.dhePreferredGroup = groupDef;
1849 }
1850 PORT_Assert(k < SSL_NAMED_GROUP_COUNT);
1851 for (j = 0; j < k; ++j) {
1852 /* skip duplicates */
1853 if (enabled[j] == groupDef) {
1854 duplicate = PR_TRUE;
1855 break;
1856 }
1857 }
1858 if (!duplicate) {
1859 enabled[k++] = groupDef;
1860 }
1861 }
1862 for (i = 0; i < k; ++i) {
1863 ss->namedGroupPreferences[i] = enabled[i];
1864 }
1865
1866 return SECSuccess;
1867 }
1868
1869 PRCallOnceType gWeakDHParamsRegisterOnce;
1870 int gWeakDHParamsRegisterError;
1871
1872 PRCallOnceType gWeakDHParamsOnce;
1873 int gWeakDHParamsError;
1874 /* As our code allocates type PQGParams, we'll keep it around,
1875 * even though we only make use of it's parameters through gWeakDHParam. */
1876 static PQGParams *gWeakParamsPQG;
1877 static ssl3DHParams *gWeakDHParams;
1878 #define WEAK_DHE_SIZE 1024
1879
1880 static PRStatus
ssl3_CreateWeakDHParams(void)1881 ssl3_CreateWeakDHParams(void)
1882 {
1883 PQGVerify *vfy;
1884 SECStatus rv, passed;
1885
1886 PORT_Assert(!gWeakDHParams && !gWeakParamsPQG);
1887
1888 rv = PK11_PQG_ParamGenV2(WEAK_DHE_SIZE, 160, 64 /*maximum seed that will work*/,
1889 &gWeakParamsPQG, &vfy);
1890 if (rv != SECSuccess) {
1891 gWeakDHParamsError = PORT_GetError();
1892 return PR_FAILURE;
1893 }
1894
1895 rv = PK11_PQG_VerifyParams(gWeakParamsPQG, vfy, &passed);
1896 if (rv != SECSuccess || passed != SECSuccess) {
1897 SSL_DBG(("%d: PK11_PQG_VerifyParams failed in ssl3_CreateWeakDHParams",
1898 SSL_GETPID()));
1899 gWeakDHParamsError = PORT_GetError();
1900 return PR_FAILURE;
1901 }
1902
1903 gWeakDHParams = PORT_ArenaNew(gWeakParamsPQG->arena, ssl3DHParams);
1904 if (!gWeakDHParams) {
1905 gWeakDHParamsError = PORT_GetError();
1906 return PR_FAILURE;
1907 }
1908
1909 gWeakDHParams->name = ssl_grp_ffdhe_custom;
1910 gWeakDHParams->prime.data = gWeakParamsPQG->prime.data;
1911 gWeakDHParams->prime.len = gWeakParamsPQG->prime.len;
1912 gWeakDHParams->base.data = gWeakParamsPQG->base.data;
1913 gWeakDHParams->base.len = gWeakParamsPQG->base.len;
1914
1915 PK11_PQG_DestroyVerify(vfy);
1916 return PR_SUCCESS;
1917 }
1918
1919 static SECStatus
ssl3_WeakDHParamsShutdown(void * appData,void * nssData)1920 ssl3_WeakDHParamsShutdown(void *appData, void *nssData)
1921 {
1922 if (gWeakParamsPQG) {
1923 PK11_PQG_DestroyParams(gWeakParamsPQG);
1924 gWeakParamsPQG = NULL;
1925 gWeakDHParams = NULL;
1926 }
1927 return SECSuccess;
1928 }
1929
1930 static PRStatus
ssl3_WeakDHParamsRegisterShutdown(void)1931 ssl3_WeakDHParamsRegisterShutdown(void)
1932 {
1933 SECStatus rv;
1934 rv = NSS_RegisterShutdown(ssl3_WeakDHParamsShutdown, NULL);
1935 if (rv != SECSuccess) {
1936 gWeakDHParamsRegisterError = PORT_GetError();
1937 }
1938 return (PRStatus)rv;
1939 }
1940
1941 /* global init strategy inspired by ssl3_CreateECDHEphemeralKeys */
1942 SECStatus
SSL_EnableWeakDHEPrimeGroup(PRFileDesc * fd,PRBool enabled)1943 SSL_EnableWeakDHEPrimeGroup(PRFileDesc *fd, PRBool enabled)
1944 {
1945 sslSocket *ss;
1946 PRStatus status;
1947
1948 if (enabled) {
1949 status = PR_CallOnce(&gWeakDHParamsRegisterOnce,
1950 ssl3_WeakDHParamsRegisterShutdown);
1951 if (status != PR_SUCCESS) {
1952 PORT_SetError(gWeakDHParamsRegisterError);
1953 return SECFailure;
1954 }
1955
1956 status = PR_CallOnce(&gWeakDHParamsOnce, ssl3_CreateWeakDHParams);
1957 if (status != PR_SUCCESS) {
1958 PORT_SetError(gWeakDHParamsError);
1959 return SECFailure;
1960 }
1961 }
1962
1963 if (!fd)
1964 return SECSuccess;
1965
1966 ss = ssl_FindSocket(fd);
1967 if (!ss) {
1968 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_DHEGroupPrefSet", SSL_GETPID(), fd));
1969 return SECFailure;
1970 }
1971
1972 ss->ssl3.dheWeakGroupEnabled = enabled;
1973 return SECSuccess;
1974 }
1975
1976 #include "dhe-param.c"
1977
1978 const ssl3DHParams *
ssl_GetDHEParams(const sslNamedGroupDef * groupDef)1979 ssl_GetDHEParams(const sslNamedGroupDef *groupDef)
1980 {
1981 switch (groupDef->name) {
1982 case ssl_grp_ffdhe_2048:
1983 return &ff_dhe_2048_params;
1984 case ssl_grp_ffdhe_3072:
1985 return &ff_dhe_3072_params;
1986 case ssl_grp_ffdhe_4096:
1987 return &ff_dhe_4096_params;
1988 case ssl_grp_ffdhe_6144:
1989 return &ff_dhe_6144_params;
1990 case ssl_grp_ffdhe_8192:
1991 return &ff_dhe_8192_params;
1992 case ssl_grp_ffdhe_custom:
1993 PORT_Assert(gWeakDHParams);
1994 return gWeakDHParams;
1995 default:
1996 PORT_Assert(0);
1997 }
1998 return NULL;
1999 }
2000
2001 /* This validates dh_Ys against the group prime. */
2002 PRBool
ssl_IsValidDHEShare(const SECItem * dh_p,const SECItem * dh_Ys)2003 ssl_IsValidDHEShare(const SECItem *dh_p, const SECItem *dh_Ys)
2004 {
2005 unsigned int size_p = SECKEY_BigIntegerBitLength(dh_p);
2006 unsigned int size_y = SECKEY_BigIntegerBitLength(dh_Ys);
2007 unsigned int commonPart;
2008 int cmp;
2009
2010 if (dh_p->len == 0 || dh_Ys->len == 0) {
2011 return PR_FALSE;
2012 }
2013 /* Check that the prime is at least odd. */
2014 if ((dh_p->data[dh_p->len - 1] & 0x01) == 0) {
2015 return PR_FALSE;
2016 }
2017 /* dh_Ys can't be 1, or bigger than dh_p. */
2018 if (size_y <= 1 || size_y > size_p) {
2019 return PR_FALSE;
2020 }
2021 /* If dh_Ys is shorter, then it's definitely smaller than p-1. */
2022 if (size_y < size_p) {
2023 return PR_TRUE;
2024 }
2025
2026 /* Compare the common part of each, minus the final octet. */
2027 commonPart = (size_p + 7) / 8;
2028 PORT_Assert(commonPart <= dh_Ys->len);
2029 PORT_Assert(commonPart <= dh_p->len);
2030 cmp = PORT_Memcmp(dh_Ys->data + dh_Ys->len - commonPart,
2031 dh_p->data + dh_p->len - commonPart, commonPart - 1);
2032 if (cmp < 0) {
2033 return PR_TRUE;
2034 }
2035 if (cmp > 0) {
2036 return PR_FALSE;
2037 }
2038
2039 /* The last octet of the prime is the only thing that is different and that
2040 * has to be two greater than the share, otherwise we have Ys == p - 1,
2041 * and that means small subgroups. */
2042 if (dh_Ys->data[dh_Ys->len - 1] >= (dh_p->data[dh_p->len - 1] - 1)) {
2043 return PR_FALSE;
2044 }
2045
2046 return PR_TRUE;
2047 }
2048
2049 /* Checks that the provided DH parameters match those in one of the named groups
2050 * that we have enabled. The groups are defined in dhe-param.c and are those
2051 * defined in Appendix A of draft-ietf-tls-negotiated-ff-dhe.
2052 *
2053 * |groupDef| and |dhParams| are optional outparams that identify the group and
2054 * its parameters respectively (if this is successful). */
2055 SECStatus
ssl_ValidateDHENamedGroup(sslSocket * ss,const SECItem * dh_p,const SECItem * dh_g,const sslNamedGroupDef ** groupDef,const ssl3DHParams ** dhParams)2056 ssl_ValidateDHENamedGroup(sslSocket *ss,
2057 const SECItem *dh_p,
2058 const SECItem *dh_g,
2059 const sslNamedGroupDef **groupDef,
2060 const ssl3DHParams **dhParams)
2061 {
2062 unsigned int i;
2063
2064 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
2065 const ssl3DHParams *params;
2066 if (!ss->namedGroupPreferences[i]) {
2067 continue;
2068 }
2069 if (ss->namedGroupPreferences[i]->keaType != ssl_kea_dh) {
2070 continue;
2071 }
2072
2073 params = ssl_GetDHEParams(ss->namedGroupPreferences[i]);
2074 PORT_Assert(params);
2075 if (SECITEM_ItemsAreEqual(¶ms->prime, dh_p)) {
2076 if (!SECITEM_ItemsAreEqual(¶ms->base, dh_g)) {
2077 return SECFailure;
2078 }
2079 if (groupDef)
2080 *groupDef = ss->namedGroupPreferences[i];
2081 if (dhParams)
2082 *dhParams = params;
2083 return SECSuccess;
2084 }
2085 }
2086
2087 return SECFailure;
2088 }
2089
2090 /* Ensure DH parameters have been selected. This just picks the first enabled
2091 * FFDHE group in ssl_named_groups, or the weak one if it was enabled. */
2092 SECStatus
ssl_SelectDHEGroup(sslSocket * ss,const sslNamedGroupDef ** groupDef)2093 ssl_SelectDHEGroup(sslSocket *ss, const sslNamedGroupDef **groupDef)
2094 {
2095 unsigned int i;
2096 static const sslNamedGroupDef weak_group_def = {
2097 ssl_grp_ffdhe_custom, WEAK_DHE_SIZE, ssl_kea_dh,
2098 SEC_OID_TLS_DHE_CUSTOM, PR_TRUE
2099 };
2100 PRInt32 minDH;
2101 SECStatus rv;
2102
2103 // make sure we select a group consistent with our
2104 // current policy policy
2105 rv = NSS_OptionGet(NSS_DH_MIN_KEY_SIZE, &minDH);
2106 if (rv != SECSuccess || minDH <= 0) {
2107 minDH = DH_MIN_P_BITS;
2108 }
2109
2110 /* Only select weak groups in TLS 1.2 and earlier, but not if the client has
2111 * indicated that it supports an FFDHE named group. */
2112 if (ss->ssl3.dheWeakGroupEnabled &&
2113 ss->version < SSL_LIBRARY_VERSION_TLS_1_3 &&
2114 !ss->xtnData.peerSupportsFfdheGroups &&
2115 weak_group_def.bits >= minDH) {
2116 *groupDef = &weak_group_def;
2117 return SECSuccess;
2118 }
2119 if (ss->ssl3.dhePreferredGroup &&
2120 ssl_NamedGroupEnabled(ss, ss->ssl3.dhePreferredGroup) &&
2121 ss->ssl3.dhePreferredGroup->bits >= minDH) {
2122 *groupDef = ss->ssl3.dhePreferredGroup;
2123 return SECSuccess;
2124 }
2125 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
2126 if (ss->namedGroupPreferences[i] &&
2127 ss->namedGroupPreferences[i]->keaType == ssl_kea_dh &&
2128 ss->namedGroupPreferences[i]->bits >= minDH) {
2129 *groupDef = ss->namedGroupPreferences[i];
2130 return SECSuccess;
2131 }
2132 }
2133
2134 *groupDef = NULL;
2135 PORT_SetError(SSL_ERROR_NO_CYPHER_OVERLAP);
2136 return SECFailure;
2137 }
2138
2139 /* LOCKS ??? XXX */
2140 static PRFileDesc *
ssl_ImportFD(PRFileDesc * model,PRFileDesc * fd,SSLProtocolVariant variant)2141 ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant)
2142 {
2143 sslSocket *ns = NULL;
2144 PRStatus rv;
2145 PRNetAddr addr;
2146 SECStatus status = ssl_Init();
2147
2148 if (status != SECSuccess) {
2149 return NULL;
2150 }
2151
2152 if (model == NULL) {
2153 /* Just create a default socket if we're given NULL for the model */
2154 ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks), variant);
2155 } else {
2156 sslSocket *ss = ssl_FindSocket(model);
2157 if (ss == NULL || ss->protocolVariant != variant) {
2158 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
2159 SSL_GETPID(), model));
2160 return NULL;
2161 }
2162 ns = ssl_DupSocket(ss);
2163 }
2164 if (ns == NULL)
2165 return NULL;
2166
2167 rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
2168 if (rv != PR_SUCCESS) {
2169 ssl_FreeSocket(ns);
2170 PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
2171 return NULL;
2172 }
2173 #if defined(DEBUG) || defined(FORCE_PR_ASSERT)
2174 {
2175 sslSocket *ss = ssl_FindSocket(fd);
2176 PORT_Assert(ss == ns);
2177 }
2178 #endif
2179 ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
2180 return fd;
2181 }
2182
2183 PRFileDesc *
SSL_ImportFD(PRFileDesc * model,PRFileDesc * fd)2184 SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
2185 {
2186 return ssl_ImportFD(model, fd, ssl_variant_stream);
2187 }
2188
2189 PRFileDesc *
DTLS_ImportFD(PRFileDesc * model,PRFileDesc * fd)2190 DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd)
2191 {
2192 return ssl_ImportFD(model, fd, ssl_variant_datagram);
2193 }
2194
2195 /* SSL_SetNextProtoCallback is used to select an application protocol
2196 * for ALPN. */
2197 SECStatus
SSL_SetNextProtoCallback(PRFileDesc * fd,SSLNextProtoCallback callback,void * arg)2198 SSL_SetNextProtoCallback(PRFileDesc *fd, SSLNextProtoCallback callback,
2199 void *arg)
2200 {
2201 sslSocket *ss = ssl_FindSocket(fd);
2202
2203 if (!ss) {
2204 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoCallback", SSL_GETPID(),
2205 fd));
2206 return SECFailure;
2207 }
2208
2209 ssl_GetSSL3HandshakeLock(ss);
2210 ss->nextProtoCallback = callback;
2211 ss->nextProtoArg = arg;
2212 ssl_ReleaseSSL3HandshakeLock(ss);
2213
2214 return SECSuccess;
2215 }
2216
2217 /* ssl_NextProtoNegoCallback is set as an ALPN callback when
2218 * SSL_SetNextProtoNego is used.
2219 */
2220 static SECStatus
ssl_NextProtoNegoCallback(void * arg,PRFileDesc * fd,const unsigned char * protos,unsigned int protos_len,unsigned char * protoOut,unsigned int * protoOutLen,unsigned int protoMaxLen)2221 ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
2222 const unsigned char *protos, unsigned int protos_len,
2223 unsigned char *protoOut, unsigned int *protoOutLen,
2224 unsigned int protoMaxLen)
2225 {
2226 unsigned int i, j;
2227 sslSocket *ss = ssl_FindSocket(fd);
2228 if (!ss) {
2229 SSL_DBG(("%d: SSL[%d]: bad socket in ssl_NextProtoNegoCallback",
2230 SSL_GETPID(), fd));
2231 return SECFailure;
2232 }
2233 if (ss->opt.nextProtoNego.len == 0) {
2234 SSL_DBG(("%d: SSL[%d]: ssl_NextProtoNegoCallback ALPN disabled",
2235 SSL_GETPID(), fd));
2236 SSL3_SendAlert(ss, alert_fatal, unsupported_extension);
2237 return SECFailure;
2238 }
2239
2240 PORT_Assert(protoMaxLen <= 255);
2241 if (protoMaxLen > 255) {
2242 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
2243 return SECFailure;
2244 }
2245
2246 /* For each protocol in client preference, see if we support it. */
2247 for (j = 0; j < ss->opt.nextProtoNego.len;) {
2248 for (i = 0; i < protos_len;) {
2249 if (protos[i] == ss->opt.nextProtoNego.data[j] &&
2250 PORT_Memcmp(&protos[i + 1], &ss->opt.nextProtoNego.data[j + 1],
2251 protos[i]) == 0) {
2252 /* We found a match. */
2253 const unsigned char *result = &protos[i];
2254 memcpy(protoOut, result + 1, result[0]);
2255 *protoOutLen = result[0];
2256 return SECSuccess;
2257 }
2258 i += 1 + (unsigned int)protos[i];
2259 }
2260 j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
2261 }
2262
2263 return SECSuccess;
2264 }
2265
2266 SECStatus
SSL_SetNextProtoNego(PRFileDesc * fd,const unsigned char * data,unsigned int length)2267 SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
2268 unsigned int length)
2269 {
2270 sslSocket *ss;
2271
2272 ss = ssl_FindSocket(fd);
2273 if (!ss) {
2274 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego",
2275 SSL_GETPID(), fd));
2276 return SECFailure;
2277 }
2278
2279 if (length > 0 && ssl3_ValidateAppProtocol(data, length) != SECSuccess) {
2280 return SECFailure;
2281 }
2282
2283 /* NPN required that the client's fallback protocol is first in the
2284 * list. However, ALPN sends protocols in preference order. So move the
2285 * first protocol to the end of the list. */
2286 ssl_GetSSL3HandshakeLock(ss);
2287 SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
2288 if (length > 0) {
2289 SECITEM_AllocItem(NULL, &ss->opt.nextProtoNego, length);
2290 size_t firstLen = data[0] + 1;
2291 /* firstLen <= length is ensured by ssl3_ValidateAppProtocol. */
2292 PORT_Memcpy(ss->opt.nextProtoNego.data + (length - firstLen), data, firstLen);
2293 PORT_Memcpy(ss->opt.nextProtoNego.data, data + firstLen, length - firstLen);
2294 }
2295 ssl_ReleaseSSL3HandshakeLock(ss);
2296
2297 return SSL_SetNextProtoCallback(fd, ssl_NextProtoNegoCallback, NULL);
2298 }
2299
2300 SECStatus
SSL_GetNextProto(PRFileDesc * fd,SSLNextProtoState * state,unsigned char * buf,unsigned int * bufLen,unsigned int bufLenMax)2301 SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf,
2302 unsigned int *bufLen, unsigned int bufLenMax)
2303 {
2304 sslSocket *ss = ssl_FindSocket(fd);
2305
2306 if (!ss) {
2307 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNextProto", SSL_GETPID(),
2308 fd));
2309 return SECFailure;
2310 }
2311
2312 if (!state || !buf || !bufLen) {
2313 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2314 return SECFailure;
2315 }
2316
2317 *state = ss->xtnData.nextProtoState;
2318
2319 if (ss->xtnData.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
2320 ss->xtnData.nextProto.data) {
2321 if (ss->xtnData.nextProto.len > bufLenMax) {
2322 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
2323 return SECFailure;
2324 }
2325 PORT_Memcpy(buf, ss->xtnData.nextProto.data, ss->xtnData.nextProto.len);
2326 *bufLen = ss->xtnData.nextProto.len;
2327 } else {
2328 *bufLen = 0;
2329 }
2330
2331 return SECSuccess;
2332 }
2333
2334 SECStatus
SSL_SetSRTPCiphers(PRFileDesc * fd,const PRUint16 * ciphers,unsigned int numCiphers)2335 SSL_SetSRTPCiphers(PRFileDesc *fd,
2336 const PRUint16 *ciphers,
2337 unsigned int numCiphers)
2338 {
2339 sslSocket *ss;
2340 unsigned int i;
2341
2342 ss = ssl_FindSocket(fd);
2343 if (!ss || !IS_DTLS(ss)) {
2344 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSRTPCiphers",
2345 SSL_GETPID(), fd));
2346 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2347 return SECFailure;
2348 }
2349
2350 if (numCiphers > MAX_DTLS_SRTP_CIPHER_SUITES) {
2351 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2352 return SECFailure;
2353 }
2354
2355 ss->ssl3.dtlsSRTPCipherCount = 0;
2356 for (i = 0; i < numCiphers; i++) {
2357 const PRUint16 *srtpCipher = srtpCiphers;
2358
2359 while (*srtpCipher) {
2360 if (ciphers[i] == *srtpCipher)
2361 break;
2362 srtpCipher++;
2363 }
2364 if (*srtpCipher) {
2365 ss->ssl3.dtlsSRTPCiphers[ss->ssl3.dtlsSRTPCipherCount++] =
2366 ciphers[i];
2367 } else {
2368 SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher "
2369 "suite specified: 0x%04hx",
2370 SSL_GETPID(), fd,
2371 ciphers[i]));
2372 }
2373 }
2374
2375 if (ss->ssl3.dtlsSRTPCipherCount == 0) {
2376 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2377 return SECFailure;
2378 }
2379
2380 return SECSuccess;
2381 }
2382
2383 SECStatus
SSL_GetSRTPCipher(PRFileDesc * fd,PRUint16 * cipher)2384 SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher)
2385 {
2386 sslSocket *ss;
2387
2388 ss = ssl_FindSocket(fd);
2389 if (!ss) {
2390 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetSRTPCipher",
2391 SSL_GETPID(), fd));
2392 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2393 return SECFailure;
2394 }
2395
2396 if (!ss->xtnData.dtlsSRTPCipherSuite) {
2397 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2398 return SECFailure;
2399 }
2400
2401 *cipher = ss->xtnData.dtlsSRTPCipherSuite;
2402 return SECSuccess;
2403 }
2404
2405 PRFileDesc *
SSL_ReconfigFD(PRFileDesc * model,PRFileDesc * fd)2406 SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd)
2407 {
2408 sslSocket *sm = NULL, *ss = NULL;
2409 PRCList *cursor;
2410 SECStatus rv;
2411
2412 if (model == NULL) {
2413 PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
2414 return NULL;
2415 }
2416 sm = ssl_FindSocket(model);
2417 if (sm == NULL) {
2418 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ReconfigFD",
2419 SSL_GETPID(), model));
2420 return NULL;
2421 }
2422 ss = ssl_FindSocket(fd);
2423 PORT_Assert(ss);
2424 if (ss == NULL) {
2425 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2426 return NULL;
2427 }
2428
2429 ss->opt = sm->opt;
2430 ss->vrange = sm->vrange;
2431 ss->now = sm->now;
2432 ss->nowArg = sm->nowArg;
2433 PORT_Memcpy(ss->cipherSuites, sm->cipherSuites, sizeof sm->cipherSuites);
2434 PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, sm->ssl3.dtlsSRTPCiphers,
2435 sizeof(PRUint16) * sm->ssl3.dtlsSRTPCipherCount);
2436 ss->ssl3.dtlsSRTPCipherCount = sm->ssl3.dtlsSRTPCipherCount;
2437 PORT_Memcpy(ss->ssl3.signatureSchemes, sm->ssl3.signatureSchemes,
2438 sizeof(ss->ssl3.signatureSchemes[0]) *
2439 sm->ssl3.signatureSchemeCount);
2440 ss->ssl3.signatureSchemeCount = sm->ssl3.signatureSchemeCount;
2441 ss->ssl3.downgradeCheckVersion = sm->ssl3.downgradeCheckVersion;
2442
2443 if (!ss->opt.useSecurity) {
2444 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2445 return NULL;
2446 }
2447 while (!PR_CLIST_IS_EMPTY(&ss->serverCerts)) {
2448 cursor = PR_LIST_TAIL(&ss->serverCerts);
2449 PR_REMOVE_LINK(cursor);
2450 ssl_FreeServerCert((sslServerCert *)cursor);
2451 }
2452 for (cursor = PR_NEXT_LINK(&sm->serverCerts);
2453 cursor != &sm->serverCerts;
2454 cursor = PR_NEXT_LINK(cursor)) {
2455 sslServerCert *sc = ssl_CopyServerCert((sslServerCert *)cursor);
2456 if (!sc)
2457 return NULL;
2458 PR_APPEND_LINK(&sc->link, &ss->serverCerts);
2459 }
2460
2461 ssl_FreeEphemeralKeyPairs(ss);
2462 for (cursor = PR_NEXT_LINK(&sm->ephemeralKeyPairs);
2463 cursor != &sm->ephemeralKeyPairs;
2464 cursor = PR_NEXT_LINK(cursor)) {
2465 sslEphemeralKeyPair *mkp = (sslEphemeralKeyPair *)cursor;
2466 sslEphemeralKeyPair *skp = ssl_CopyEphemeralKeyPair(mkp);
2467 if (!skp)
2468 return NULL;
2469 PR_APPEND_LINK(&skp->link, &ss->ephemeralKeyPairs);
2470 }
2471
2472 while (!PR_CLIST_IS_EMPTY(&ss->extensionHooks)) {
2473 cursor = PR_LIST_TAIL(&ss->extensionHooks);
2474 PR_REMOVE_LINK(cursor);
2475 PORT_Free(cursor);
2476 }
2477 for (cursor = PR_NEXT_LINK(&sm->extensionHooks);
2478 cursor != &sm->extensionHooks;
2479 cursor = PR_NEXT_LINK(cursor)) {
2480 sslCustomExtensionHooks *hook = (sslCustomExtensionHooks *)cursor;
2481 rv = SSL_InstallExtensionHooks(ss->fd, hook->type,
2482 hook->writer, hook->writerArg,
2483 hook->handler, hook->handlerArg);
2484 if (rv != SECSuccess) {
2485 return NULL;
2486 }
2487 }
2488
2489 PORT_Memcpy((void *)ss->namedGroupPreferences,
2490 sm->namedGroupPreferences,
2491 sizeof(ss->namedGroupPreferences));
2492 ss->additionalShares = sm->additionalShares;
2493
2494 /* copy trust anchor names */
2495 if (sm->ssl3.ca_list) {
2496 if (ss->ssl3.ca_list) {
2497 CERT_FreeDistNames(ss->ssl3.ca_list);
2498 }
2499 ss->ssl3.ca_list = CERT_DupDistNames(sm->ssl3.ca_list);
2500 if (!ss->ssl3.ca_list) {
2501 return NULL;
2502 }
2503 }
2504
2505 /* Copy ECH. */
2506 tls13_DestroyEchConfigs(&ss->echConfigs);
2507 SECKEY_DestroyPrivateKey(ss->echPrivKey);
2508 SECKEY_DestroyPublicKey(ss->echPubKey);
2509 rv = tls13_CopyEchConfigs(&sm->echConfigs, &ss->echConfigs);
2510 if (rv != SECSuccess) {
2511 return NULL;
2512 }
2513 if (sm->echPrivKey && sm->echPubKey) {
2514 /* Might be client (no keys). */
2515 ss->echPrivKey = SECKEY_CopyPrivateKey(sm->echPrivKey);
2516 ss->echPubKey = SECKEY_CopyPublicKey(sm->echPubKey);
2517 if (!ss->echPrivKey || !ss->echPubKey) {
2518 return NULL;
2519 }
2520 }
2521
2522 /* Copy anti-replay context. */
2523 if (ss->antiReplay) {
2524 tls13_ReleaseAntiReplayContext(ss->antiReplay);
2525 ss->antiReplay = NULL;
2526 }
2527 if (sm->antiReplay) {
2528 ss->antiReplay = tls13_RefAntiReplayContext(sm->antiReplay);
2529 PORT_Assert(ss->antiReplay);
2530 if (!ss->antiReplay) {
2531 return NULL;
2532 }
2533 }
2534
2535 tls13_ResetHandshakePsks(sm, &ss->ssl3.hs.psks);
2536
2537 if (sm->authCertificate)
2538 ss->authCertificate = sm->authCertificate;
2539 if (sm->authCertificateArg)
2540 ss->authCertificateArg = sm->authCertificateArg;
2541 if (sm->getClientAuthData)
2542 ss->getClientAuthData = sm->getClientAuthData;
2543 if (sm->getClientAuthDataArg)
2544 ss->getClientAuthDataArg = sm->getClientAuthDataArg;
2545 if (sm->sniSocketConfig)
2546 ss->sniSocketConfig = sm->sniSocketConfig;
2547 if (sm->sniSocketConfigArg)
2548 ss->sniSocketConfigArg = sm->sniSocketConfigArg;
2549 if (sm->alertReceivedCallback) {
2550 ss->alertReceivedCallback = sm->alertReceivedCallback;
2551 ss->alertReceivedCallbackArg = sm->alertReceivedCallbackArg;
2552 }
2553 if (sm->alertSentCallback) {
2554 ss->alertSentCallback = sm->alertSentCallback;
2555 ss->alertSentCallbackArg = sm->alertSentCallbackArg;
2556 }
2557 if (sm->handleBadCert)
2558 ss->handleBadCert = sm->handleBadCert;
2559 if (sm->badCertArg)
2560 ss->badCertArg = sm->badCertArg;
2561 if (sm->handshakeCallback)
2562 ss->handshakeCallback = sm->handshakeCallback;
2563 if (sm->handshakeCallbackData)
2564 ss->handshakeCallbackData = sm->handshakeCallbackData;
2565 if (sm->pkcs11PinArg)
2566 ss->pkcs11PinArg = sm->pkcs11PinArg;
2567 return fd;
2568 }
2569
2570 SECStatus
ssl3_GetEffectiveVersionPolicy(SSLProtocolVariant variant,SSLVersionRange * effectivePolicy)2571 ssl3_GetEffectiveVersionPolicy(SSLProtocolVariant variant,
2572 SSLVersionRange *effectivePolicy)
2573 {
2574 SECStatus rv;
2575 PRUint32 policyFlag;
2576 PRInt32 minPolicy, maxPolicy;
2577
2578 if (variant == ssl_variant_stream) {
2579 effectivePolicy->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM;
2580 effectivePolicy->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
2581 } else {
2582 effectivePolicy->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM;
2583 effectivePolicy->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
2584 }
2585
2586 rv = NSS_GetAlgorithmPolicy(SEC_OID_APPLY_SSL_POLICY, &policyFlag);
2587 if ((rv != SECSuccess) || !(policyFlag & NSS_USE_POLICY_IN_SSL)) {
2588 /* Policy is not active, report library extents. */
2589 return SECSuccess;
2590 }
2591
2592 rv = NSS_OptionGet(VERSIONS_POLICY_MIN(variant), &minPolicy);
2593 if (rv != SECSuccess) {
2594 return SECFailure;
2595 }
2596 rv = NSS_OptionGet(VERSIONS_POLICY_MAX(variant), &maxPolicy);
2597 if (rv != SECSuccess) {
2598 return SECFailure;
2599 }
2600
2601 if (minPolicy > effectivePolicy->max ||
2602 maxPolicy < effectivePolicy->min ||
2603 minPolicy > maxPolicy) {
2604 return SECFailure;
2605 }
2606 effectivePolicy->min = PR_MAX(effectivePolicy->min, minPolicy);
2607 effectivePolicy->max = PR_MIN(effectivePolicy->max, maxPolicy);
2608 return SECSuccess;
2609 }
2610
2611 /*
2612 * Assumes that rangeParam values are within the supported boundaries,
2613 * but should contain all potentially allowed versions, even if they contain
2614 * conflicting versions.
2615 * Will return the overlap, or a NONE range if system policy is invalid.
2616 */
2617 static SECStatus
ssl3_CreateOverlapWithPolicy(SSLProtocolVariant protocolVariant,SSLVersionRange * input,SSLVersionRange * overlap)2618 ssl3_CreateOverlapWithPolicy(SSLProtocolVariant protocolVariant,
2619 SSLVersionRange *input,
2620 SSLVersionRange *overlap)
2621 {
2622 SECStatus rv;
2623 SSLVersionRange effectivePolicyBoundary;
2624 SSLVersionRange vrange;
2625
2626 PORT_Assert(input != NULL);
2627
2628 rv = ssl3_GetEffectiveVersionPolicy(protocolVariant,
2629 &effectivePolicyBoundary);
2630 if (rv == SECFailure) {
2631 /* SECFailure means internal failure or invalid configuration. */
2632 overlap->min = overlap->max = SSL_LIBRARY_VERSION_NONE;
2633 return SECFailure;
2634 }
2635
2636 vrange.min = PR_MAX(input->min, effectivePolicyBoundary.min);
2637 vrange.max = PR_MIN(input->max, effectivePolicyBoundary.max);
2638
2639 if (vrange.max < vrange.min) {
2640 /* there was no overlap, turn off range altogether */
2641 overlap->min = overlap->max = SSL_LIBRARY_VERSION_NONE;
2642 return SECFailure;
2643 }
2644
2645 *overlap = vrange;
2646 return SECSuccess;
2647 }
2648
2649 static PRBool
ssl_VersionIsSupportedByPolicy(SSLProtocolVariant protocolVariant,SSL3ProtocolVersion version)2650 ssl_VersionIsSupportedByPolicy(SSLProtocolVariant protocolVariant,
2651 SSL3ProtocolVersion version)
2652 {
2653 SECStatus rv;
2654 SSLVersionRange effectivePolicyBoundary;
2655
2656 rv = ssl3_GetEffectiveVersionPolicy(protocolVariant,
2657 &effectivePolicyBoundary);
2658 if (rv == SECFailure) {
2659 /* SECFailure means internal failure or invalid configuration. */
2660 return PR_FALSE;
2661 }
2662 return version >= effectivePolicyBoundary.min &&
2663 version <= effectivePolicyBoundary.max;
2664 }
2665
2666 /*
2667 * This is called at SSL init time to constrain the existing range based
2668 * on user supplied policy.
2669 */
2670 SECStatus
ssl3_ConstrainRangeByPolicy(void)2671 ssl3_ConstrainRangeByPolicy(void)
2672 {
2673 /* We ignore failures in ssl3_CreateOverlapWithPolicy. Although an empty
2674 * overlap disables all connectivity, it's an allowed state.
2675 */
2676 ssl3_CreateOverlapWithPolicy(ssl_variant_stream,
2677 VERSIONS_DEFAULTS(ssl_variant_stream),
2678 VERSIONS_DEFAULTS(ssl_variant_stream));
2679 ssl3_CreateOverlapWithPolicy(ssl_variant_datagram,
2680 VERSIONS_DEFAULTS(ssl_variant_datagram),
2681 VERSIONS_DEFAULTS(ssl_variant_datagram));
2682 return SECSuccess;
2683 }
2684
2685 PRBool
ssl3_VersionIsSupportedByCode(SSLProtocolVariant protocolVariant,SSL3ProtocolVersion version)2686 ssl3_VersionIsSupportedByCode(SSLProtocolVariant protocolVariant,
2687 SSL3ProtocolVersion version)
2688 {
2689 switch (protocolVariant) {
2690 case ssl_variant_stream:
2691 return (version >= SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM &&
2692 version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
2693 case ssl_variant_datagram:
2694 return (version >= SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM &&
2695 version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
2696 }
2697
2698 /* Can't get here */
2699 PORT_Assert(PR_FALSE);
2700 return PR_FALSE;
2701 }
2702
2703 PRBool
ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,SSL3ProtocolVersion version)2704 ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
2705 SSL3ProtocolVersion version)
2706 {
2707 if (!ssl_VersionIsSupportedByPolicy(protocolVariant, version)) {
2708 return PR_FALSE;
2709 }
2710 return ssl3_VersionIsSupportedByCode(protocolVariant, version);
2711 }
2712
2713 const SECItem *
SSL_PeerSignedCertTimestamps(PRFileDesc * fd)2714 SSL_PeerSignedCertTimestamps(PRFileDesc *fd)
2715 {
2716 sslSocket *ss = ssl_FindSocket(fd);
2717
2718 if (!ss) {
2719 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerSignedCertTimestamps",
2720 SSL_GETPID(), fd));
2721 return NULL;
2722 }
2723
2724 if (!ss->sec.ci.sid) {
2725 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
2726 return NULL;
2727 }
2728
2729 return &ss->sec.ci.sid->u.ssl3.signedCertTimestamps;
2730 }
2731
2732 SECStatus
SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant,SSLVersionRange * vrange)2733 SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant,
2734 SSLVersionRange *vrange)
2735 {
2736 SECStatus rv;
2737
2738 if (!vrange) {
2739 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2740 return SECFailure;
2741 }
2742
2743 switch (protocolVariant) {
2744 case ssl_variant_stream:
2745 vrange->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_STREAM;
2746 vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
2747 /* We don't allow SSLv3 and TLSv1.3 together.
2748 * However, don't check yet, apply the policy first.
2749 * Because if the effective supported range doesn't use TLS 1.3,
2750 * then we don't need to increase the minimum. */
2751 break;
2752 case ssl_variant_datagram:
2753 vrange->min = SSL_LIBRARY_VERSION_MIN_SUPPORTED_DATAGRAM;
2754 vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
2755 break;
2756 default:
2757 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2758 return SECFailure;
2759 }
2760
2761 rv = ssl3_CreateOverlapWithPolicy(protocolVariant, vrange, vrange);
2762 if (rv != SECSuccess) {
2763 /* Library default and policy don't overlap. */
2764 return rv;
2765 }
2766
2767 /* We don't allow SSLv3 and TLSv1.3 together */
2768 if (vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3) {
2769 vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
2770 }
2771
2772 return SECSuccess;
2773 }
2774
2775 SECStatus
SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant,SSLVersionRange * vrange)2776 SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant,
2777 SSLVersionRange *vrange)
2778 {
2779 if ((protocolVariant != ssl_variant_stream &&
2780 protocolVariant != ssl_variant_datagram) ||
2781 !vrange) {
2782 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2783 return SECFailure;
2784 }
2785
2786 *vrange = *VERSIONS_DEFAULTS(protocolVariant);
2787 return ssl3_CreateOverlapWithPolicy(protocolVariant, vrange, vrange);
2788 }
2789
2790 static PRBool
ssl3_HasConflictingSSLVersions(const SSLVersionRange * vrange)2791 ssl3_HasConflictingSSLVersions(const SSLVersionRange *vrange)
2792 {
2793 return (vrange->min <= SSL_LIBRARY_VERSION_3_0 &&
2794 vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3);
2795 }
2796
2797 static SECStatus
ssl3_CheckRangeValidAndConstrainByPolicy(SSLProtocolVariant protocolVariant,SSLVersionRange * vrange)2798 ssl3_CheckRangeValidAndConstrainByPolicy(SSLProtocolVariant protocolVariant,
2799 SSLVersionRange *vrange)
2800 {
2801 SECStatus rv;
2802
2803 if (vrange->min > vrange->max ||
2804 !ssl3_VersionIsSupportedByCode(protocolVariant, vrange->min) ||
2805 !ssl3_VersionIsSupportedByCode(protocolVariant, vrange->max) ||
2806 ssl3_HasConflictingSSLVersions(vrange)) {
2807 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
2808 return SECFailure;
2809 }
2810
2811 /* Try to adjust the received range using our policy.
2812 * If there's overlap, we'll use the (possibly reduced) range.
2813 * If there isn't overlap, it's failure. */
2814
2815 rv = ssl3_CreateOverlapWithPolicy(protocolVariant, vrange, vrange);
2816 if (rv != SECSuccess) {
2817 return rv;
2818 }
2819
2820 /* We don't allow SSLv3 and TLSv1.3 together */
2821 if (vrange->max >= SSL_LIBRARY_VERSION_TLS_1_3) {
2822 vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
2823 }
2824
2825 return SECSuccess;
2826 }
2827
2828 SECStatus
SSL_VersionRangeSetDefault(SSLProtocolVariant protocolVariant,const SSLVersionRange * vrange)2829 SSL_VersionRangeSetDefault(SSLProtocolVariant protocolVariant,
2830 const SSLVersionRange *vrange)
2831 {
2832 SSLVersionRange constrainedRange;
2833 SECStatus rv;
2834
2835 if (!vrange) {
2836 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2837 return SECFailure;
2838 }
2839
2840 constrainedRange = *vrange;
2841 rv = ssl3_CheckRangeValidAndConstrainByPolicy(protocolVariant,
2842 &constrainedRange);
2843 if (rv != SECSuccess)
2844 return rv;
2845
2846 *VERSIONS_DEFAULTS(protocolVariant) = constrainedRange;
2847 return SECSuccess;
2848 }
2849
2850 SECStatus
SSL_VersionRangeGet(PRFileDesc * fd,SSLVersionRange * vrange)2851 SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange)
2852 {
2853 sslSocket *ss = ssl_FindSocket(fd);
2854
2855 if (!ss) {
2856 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeGet",
2857 SSL_GETPID(), fd));
2858 return SECFailure;
2859 }
2860
2861 if (!vrange) {
2862 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2863 return SECFailure;
2864 }
2865
2866 ssl_Get1stHandshakeLock(ss);
2867 ssl_GetSSL3HandshakeLock(ss);
2868
2869 *vrange = ss->vrange;
2870
2871 ssl_ReleaseSSL3HandshakeLock(ss);
2872 ssl_Release1stHandshakeLock(ss);
2873
2874 return ssl3_CreateOverlapWithPolicy(ss->protocolVariant, vrange, vrange);
2875 }
2876
2877 SECStatus
SSL_VersionRangeSet(PRFileDesc * fd,const SSLVersionRange * vrange)2878 SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange)
2879 {
2880 SSLVersionRange constrainedRange;
2881 sslSocket *ss;
2882 SECStatus rv;
2883
2884 if (!vrange) {
2885 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2886 return SECFailure;
2887 }
2888
2889 ss = ssl_FindSocket(fd);
2890 if (!ss) {
2891 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_VersionRangeSet",
2892 SSL_GETPID(), fd));
2893 return SECFailure;
2894 }
2895
2896 constrainedRange = *vrange;
2897 rv = ssl3_CheckRangeValidAndConstrainByPolicy(ss->protocolVariant,
2898 &constrainedRange);
2899 if (rv != SECSuccess)
2900 return rv;
2901
2902 ssl_Get1stHandshakeLock(ss);
2903 ssl_GetSSL3HandshakeLock(ss);
2904
2905 if (ss->ssl3.downgradeCheckVersion &&
2906 ss->vrange.max > ss->ssl3.downgradeCheckVersion) {
2907 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
2908 ssl_ReleaseSSL3HandshakeLock(ss);
2909 ssl_Release1stHandshakeLock(ss);
2910 return SECFailure;
2911 }
2912
2913 ss->vrange = constrainedRange;
2914
2915 ssl_ReleaseSSL3HandshakeLock(ss);
2916 ssl_Release1stHandshakeLock(ss);
2917
2918 return SECSuccess;
2919 }
2920
2921 SECStatus
SSL_SetDowngradeCheckVersion(PRFileDesc * fd,PRUint16 version)2922 SSL_SetDowngradeCheckVersion(PRFileDesc *fd, PRUint16 version)
2923 {
2924 sslSocket *ss = ssl_FindSocket(fd);
2925 SECStatus rv = SECFailure;
2926
2927 if (!ss) {
2928 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetDowngradeCheckVersion",
2929 SSL_GETPID(), fd));
2930 return SECFailure;
2931 }
2932
2933 if (version && !ssl3_VersionIsSupported(ss->protocolVariant, version)) {
2934 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2935 return SECFailure;
2936 }
2937
2938 ssl_Get1stHandshakeLock(ss);
2939 ssl_GetSSL3HandshakeLock(ss);
2940
2941 if (version && version < ss->vrange.max) {
2942 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2943 goto loser;
2944 }
2945 ss->ssl3.downgradeCheckVersion = version;
2946 rv = SECSuccess;
2947
2948 loser:
2949 ssl_ReleaseSSL3HandshakeLock(ss);
2950 ssl_Release1stHandshakeLock(ss);
2951
2952 return rv;
2953 }
2954
2955 const SECItemArray *
SSL_PeerStapledOCSPResponses(PRFileDesc * fd)2956 SSL_PeerStapledOCSPResponses(PRFileDesc *fd)
2957 {
2958 sslSocket *ss = ssl_FindSocket(fd);
2959
2960 if (!ss) {
2961 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerStapledOCSPResponses",
2962 SSL_GETPID(), fd));
2963 return NULL;
2964 }
2965
2966 if (!ss->sec.ci.sid) {
2967 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
2968 return NULL;
2969 }
2970
2971 return &ss->sec.ci.sid->peerCertStatus;
2972 }
2973
2974 /************************************************************************/
2975 /* The following functions are the TOP LEVEL SSL functions.
2976 ** They all get called through the NSPRIOMethods table below.
2977 */
2978
2979 static PRFileDesc *PR_CALLBACK
ssl_Accept(PRFileDesc * fd,PRNetAddr * sockaddr,PRIntervalTime timeout)2980 ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
2981 {
2982 sslSocket *ss;
2983 sslSocket *ns = NULL;
2984 PRFileDesc *newfd = NULL;
2985 PRFileDesc *osfd;
2986 PRStatus status;
2987
2988 ss = ssl_GetPrivate(fd);
2989 if (!ss) {
2990 SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
2991 return NULL;
2992 }
2993
2994 /* IF this is a listen socket, there shouldn't be any I/O going on */
2995 SSL_LOCK_READER(ss);
2996 SSL_LOCK_WRITER(ss);
2997 ssl_Get1stHandshakeLock(ss);
2998 ssl_GetSSL3HandshakeLock(ss);
2999
3000 ss->cTimeout = timeout;
3001
3002 osfd = ss->fd->lower;
3003
3004 /* First accept connection */
3005 newfd = osfd->methods->accept(osfd, sockaddr, timeout);
3006 if (newfd == NULL) {
3007 SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
3008 SSL_GETPID(), ss->fd, PORT_GetError()));
3009 } else {
3010 /* Create ssl module */
3011 ns = ssl_DupSocket(ss);
3012 }
3013
3014 ssl_ReleaseSSL3HandshakeLock(ss);
3015 ssl_Release1stHandshakeLock(ss);
3016 SSL_UNLOCK_WRITER(ss);
3017 SSL_UNLOCK_READER(ss); /* ss isn't used below here. */
3018
3019 if (ns == NULL)
3020 goto loser;
3021
3022 /* push ssl module onto the new socket */
3023 status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
3024 if (status != PR_SUCCESS)
3025 goto loser;
3026
3027 /* Now start server connection handshake with client.
3028 ** Don't need locks here because nobody else has a reference to ns yet.
3029 */
3030 if (ns->opt.useSecurity) {
3031 if (ns->opt.handshakeAsClient) {
3032 ns->handshake = ssl_BeginClientHandshake;
3033 ss->handshaking = sslHandshakingAsClient;
3034 } else {
3035 ns->handshake = ssl_BeginServerHandshake;
3036 ss->handshaking = sslHandshakingAsServer;
3037 }
3038 }
3039 ns->TCPconnected = 1;
3040 return newfd;
3041
3042 loser:
3043 if (ns != NULL)
3044 ssl_FreeSocket(ns);
3045 if (newfd != NULL)
3046 PR_Close(newfd);
3047 return NULL;
3048 }
3049
3050 static PRStatus PR_CALLBACK
ssl_Connect(PRFileDesc * fd,const PRNetAddr * sockaddr,PRIntervalTime timeout)3051 ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
3052 {
3053 sslSocket *ss;
3054 PRStatus rv;
3055
3056 ss = ssl_GetPrivate(fd);
3057 if (!ss) {
3058 SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
3059 return PR_FAILURE;
3060 }
3061
3062 /* IF this is a listen socket, there shouldn't be any I/O going on */
3063 SSL_LOCK_READER(ss);
3064 SSL_LOCK_WRITER(ss);
3065
3066 ss->cTimeout = timeout;
3067 rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
3068
3069 SSL_UNLOCK_WRITER(ss);
3070 SSL_UNLOCK_READER(ss);
3071
3072 return rv;
3073 }
3074
3075 static PRStatus PR_CALLBACK
ssl_Bind(PRFileDesc * fd,const PRNetAddr * addr)3076 ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
3077 {
3078 sslSocket *ss = ssl_GetPrivate(fd);
3079 PRStatus rv;
3080
3081 if (!ss) {
3082 SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
3083 return PR_FAILURE;
3084 }
3085 SSL_LOCK_READER(ss);
3086 SSL_LOCK_WRITER(ss);
3087
3088 rv = (PRStatus)(*ss->ops->bind)(ss, addr);
3089
3090 SSL_UNLOCK_WRITER(ss);
3091 SSL_UNLOCK_READER(ss);
3092 return rv;
3093 }
3094
3095 static PRStatus PR_CALLBACK
ssl_Listen(PRFileDesc * fd,PRIntn backlog)3096 ssl_Listen(PRFileDesc *fd, PRIntn backlog)
3097 {
3098 sslSocket *ss = ssl_GetPrivate(fd);
3099 PRStatus rv;
3100
3101 if (!ss) {
3102 SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
3103 return PR_FAILURE;
3104 }
3105 SSL_LOCK_READER(ss);
3106 SSL_LOCK_WRITER(ss);
3107
3108 rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
3109
3110 SSL_UNLOCK_WRITER(ss);
3111 SSL_UNLOCK_READER(ss);
3112 return rv;
3113 }
3114
3115 static PRStatus PR_CALLBACK
ssl_Shutdown(PRFileDesc * fd,PRIntn how)3116 ssl_Shutdown(PRFileDesc *fd, PRIntn how)
3117 {
3118 sslSocket *ss = ssl_GetPrivate(fd);
3119 PRStatus rv;
3120
3121 if (!ss) {
3122 SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
3123 return PR_FAILURE;
3124 }
3125 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
3126 SSL_LOCK_READER(ss);
3127 }
3128 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
3129 SSL_LOCK_WRITER(ss);
3130 }
3131
3132 rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
3133
3134 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
3135 SSL_UNLOCK_WRITER(ss);
3136 }
3137 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
3138 SSL_UNLOCK_READER(ss);
3139 }
3140 return rv;
3141 }
3142
3143 static PRStatus PR_CALLBACK
ssl_Close(PRFileDesc * fd)3144 ssl_Close(PRFileDesc *fd)
3145 {
3146 sslSocket *ss;
3147 PRStatus rv;
3148
3149 ss = ssl_GetPrivate(fd);
3150 if (!ss) {
3151 SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
3152 return PR_FAILURE;
3153 }
3154
3155 /* There must not be any I/O going on */
3156 SSL_LOCK_READER(ss);
3157 SSL_LOCK_WRITER(ss);
3158
3159 /* By the time this function returns,
3160 ** ss is an invalid pointer, and the locks to which it points have
3161 ** been unlocked and freed. So, this is the ONE PLACE in all of SSL
3162 ** where the LOCK calls and the corresponding UNLOCK calls are not in
3163 ** the same function scope. The unlock calls are in ssl_FreeSocket().
3164 */
3165 rv = (PRStatus)(*ss->ops->close)(ss);
3166
3167 return rv;
3168 }
3169
3170 static int PR_CALLBACK
ssl_Recv(PRFileDesc * fd,void * buf,PRInt32 len,PRIntn flags,PRIntervalTime timeout)3171 ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
3172 PRIntervalTime timeout)
3173 {
3174 sslSocket *ss;
3175 int rv;
3176
3177 ss = ssl_GetPrivate(fd);
3178 if (!ss) {
3179 SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
3180 return SECFailure;
3181 }
3182 SSL_LOCK_READER(ss);
3183 ss->rTimeout = timeout;
3184 if (!ss->opt.fdx)
3185 ss->wTimeout = timeout;
3186 rv = (*ss->ops->recv)(ss, (unsigned char *)buf, len, flags);
3187 SSL_UNLOCK_READER(ss);
3188 return rv;
3189 }
3190
3191 static int PR_CALLBACK
ssl_Send(PRFileDesc * fd,const void * buf,PRInt32 len,PRIntn flags,PRIntervalTime timeout)3192 ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
3193 PRIntervalTime timeout)
3194 {
3195 sslSocket *ss;
3196 int rv;
3197
3198 ss = ssl_GetPrivate(fd);
3199 if (!ss) {
3200 SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
3201 return SECFailure;
3202 }
3203 SSL_LOCK_WRITER(ss);
3204 ss->wTimeout = timeout;
3205 if (!ss->opt.fdx)
3206 ss->rTimeout = timeout;
3207 rv = (*ss->ops->send)(ss, (const unsigned char *)buf, len, flags);
3208 SSL_UNLOCK_WRITER(ss);
3209 return rv;
3210 }
3211
3212 static int PR_CALLBACK
ssl_Read(PRFileDesc * fd,void * buf,PRInt32 len)3213 ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
3214 {
3215 sslSocket *ss;
3216 int rv;
3217
3218 ss = ssl_GetPrivate(fd);
3219 if (!ss) {
3220 SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
3221 return SECFailure;
3222 }
3223 SSL_LOCK_READER(ss);
3224 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
3225 if (!ss->opt.fdx)
3226 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
3227 rv = (*ss->ops->read)(ss, (unsigned char *)buf, len);
3228 SSL_UNLOCK_READER(ss);
3229 return rv;
3230 }
3231
3232 static int PR_CALLBACK
ssl_Write(PRFileDesc * fd,const void * buf,PRInt32 len)3233 ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
3234 {
3235 sslSocket *ss;
3236 int rv;
3237
3238 ss = ssl_GetPrivate(fd);
3239 if (!ss) {
3240 SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
3241 return SECFailure;
3242 }
3243 SSL_LOCK_WRITER(ss);
3244 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
3245 if (!ss->opt.fdx)
3246 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
3247 rv = (*ss->ops->write)(ss, (const unsigned char *)buf, len);
3248 SSL_UNLOCK_WRITER(ss);
3249 return rv;
3250 }
3251
3252 static PRStatus PR_CALLBACK
ssl_GetPeerName(PRFileDesc * fd,PRNetAddr * addr)3253 ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
3254 {
3255 sslSocket *ss;
3256
3257 ss = ssl_GetPrivate(fd);
3258 if (!ss) {
3259 SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
3260 return PR_FAILURE;
3261 }
3262 return (PRStatus)(*ss->ops->getpeername)(ss, addr);
3263 }
3264
3265 /*
3266 */
3267 SECStatus
ssl_GetPeerInfo(sslSocket * ss)3268 ssl_GetPeerInfo(sslSocket *ss)
3269 {
3270 PRFileDesc *osfd;
3271 int rv;
3272 PRNetAddr sin;
3273
3274 osfd = ss->fd->lower;
3275
3276 PORT_Memset(&sin, 0, sizeof(sin));
3277 rv = osfd->methods->getpeername(osfd, &sin);
3278 if (rv < 0) {
3279 return SECFailure;
3280 }
3281 ss->TCPconnected = 1;
3282 if (sin.inet.family == PR_AF_INET) {
3283 PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
3284 ss->sec.ci.port = sin.inet.port;
3285 } else if (sin.ipv6.family == PR_AF_INET6) {
3286 ss->sec.ci.peer = sin.ipv6.ip;
3287 ss->sec.ci.port = sin.ipv6.port;
3288 } else {
3289 PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
3290 return SECFailure;
3291 }
3292 return SECSuccess;
3293 }
3294
3295 static PRStatus PR_CALLBACK
ssl_GetSockName(PRFileDesc * fd,PRNetAddr * name)3296 ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
3297 {
3298 sslSocket *ss;
3299
3300 ss = ssl_GetPrivate(fd);
3301 if (!ss) {
3302 SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
3303 return PR_FAILURE;
3304 }
3305 return (PRStatus)(*ss->ops->getsockname)(ss, name);
3306 }
3307
3308 SECStatus
SSL_SetSockPeerID(PRFileDesc * fd,const char * peerID)3309 SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID)
3310 {
3311 sslSocket *ss;
3312
3313 ss = ssl_FindSocket(fd);
3314 if (!ss) {
3315 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSockPeerID",
3316 SSL_GETPID(), fd));
3317 return SECFailure;
3318 }
3319
3320 if (ss->peerID) {
3321 PORT_Free(ss->peerID);
3322 ss->peerID = NULL;
3323 }
3324 if (peerID)
3325 ss->peerID = PORT_Strdup(peerID);
3326 return (ss->peerID || !peerID) ? SECSuccess : SECFailure;
3327 }
3328
3329 #define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
3330
3331 static PRInt16 PR_CALLBACK
ssl_Poll(PRFileDesc * fd,PRInt16 how_flags,PRInt16 * p_out_flags)3332 ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
3333 {
3334 sslSocket *ss;
3335 PRInt16 new_flags = how_flags; /* should select on these flags. */
3336 PRNetAddr addr;
3337
3338 *p_out_flags = 0;
3339 ss = ssl_GetPrivate(fd);
3340 if (!ss) {
3341 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
3342 SSL_GETPID(), fd));
3343 return 0; /* don't poll on this socket */
3344 }
3345
3346 if (ss->opt.useSecurity &&
3347 ss->handshaking != sslHandshakingUndetermined &&
3348 !ss->firstHsDone &&
3349 (how_flags & PR_POLL_RW)) {
3350 if (!ss->TCPconnected) {
3351 ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
3352 }
3353 /* If it's not connected, then presumably the application is polling
3354 ** on read or write appropriately, so don't change it.
3355 */
3356 if (ss->TCPconnected) {
3357 if (!ss->handshakeBegun) {
3358 /* If the handshake has not begun, poll on read or write
3359 ** based on the local application's role in the handshake,
3360 ** not based on what the application requested.
3361 */
3362 new_flags &= ~PR_POLL_RW;
3363 if (ss->handshaking == sslHandshakingAsClient) {
3364 new_flags |= PR_POLL_WRITE;
3365 } else { /* handshaking as server */
3366 new_flags |= PR_POLL_READ;
3367 }
3368 } else if (ss->lastWriteBlocked) {
3369 /* First handshake is in progress */
3370 if (new_flags & PR_POLL_READ) {
3371 /* The caller is waiting for data to be received,
3372 ** but the initial handshake is blocked on write, or the
3373 ** client's first handshake record has not been written.
3374 ** The code should select on write, not read.
3375 */
3376 new_flags &= ~PR_POLL_READ; /* don't select on read. */
3377 new_flags |= PR_POLL_WRITE; /* do select on write. */
3378 }
3379 } else if (new_flags & PR_POLL_WRITE) {
3380 /* The caller is trying to write, but the handshake is
3381 ** blocked waiting for data to read, and the first
3382 ** handshake has been sent. So do NOT to poll on write
3383 ** unless we did false start or we are doing 0-RTT.
3384 */
3385 if (!(ss->ssl3.hs.canFalseStart ||
3386 ss->ssl3.hs.zeroRttState == ssl_0rtt_sent ||
3387 ss->ssl3.hs.zeroRttState == ssl_0rtt_accepted)) {
3388 new_flags &= ~PR_POLL_WRITE; /* don't select on write. */
3389 }
3390 new_flags |= PR_POLL_READ; /* do select on read. */
3391 }
3392 }
3393 } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
3394 *p_out_flags = PR_POLL_READ; /* it's ready already. */
3395 return new_flags;
3396 } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
3397 (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
3398 new_flags |= PR_POLL_WRITE; /* also select on write. */
3399 }
3400
3401 if (ss->ssl3.hs.restartTarget != NULL) {
3402 /* Read and write will block until the asynchronous callback completes
3403 * (e.g. until SSL_AuthCertificateComplete is called), so don't tell
3404 * the caller to poll the socket unless there is pending write data.
3405 */
3406 if (ss->lastWriteBlocked && ss->pendingBuf.len != 0) {
3407 /* Ignore any newly-received data on the socket, but do wait for
3408 * the socket to become writable again. Here, it is OK for an error
3409 * to be detected, because our logic for sending pending write data
3410 * will allow us to report the error to the caller without the risk
3411 * of the application spinning.
3412 */
3413 new_flags &= (PR_POLL_WRITE | PR_POLL_EXCEPT);
3414 } else {
3415 /* Unfortunately, clearing new_flags will make it impossible for
3416 * the application to detect errors that it would otherwise be
3417 * able to detect with PR_POLL_EXCEPT, until the asynchronous
3418 * callback completes. However, we must clear all the flags to
3419 * prevent the application from spinning (alternating between
3420 * calling PR_Poll that would return PR_POLL_EXCEPT, and send/recv
3421 * which won't actually report the I/O error while we are waiting
3422 * for the asynchronous callback to complete).
3423 */
3424 new_flags = 0;
3425 }
3426 }
3427
3428 SSL_TRC(20, ("%d: SSL[%d]: ssl_Poll flags %x -> %x",
3429 SSL_GETPID(), fd, how_flags, new_flags));
3430
3431 if (new_flags && (fd->lower->methods->poll != NULL)) {
3432 PRInt16 lower_out_flags = 0;
3433 PRInt16 lower_new_flags;
3434 lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
3435 &lower_out_flags);
3436 if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
3437 PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
3438 if (lower_out_flags & PR_POLL_READ)
3439 out_flags |= PR_POLL_WRITE;
3440 if (lower_out_flags & PR_POLL_WRITE)
3441 out_flags |= PR_POLL_READ;
3442 *p_out_flags = out_flags;
3443 new_flags = how_flags;
3444 } else {
3445 *p_out_flags = lower_out_flags;
3446 new_flags = lower_new_flags;
3447 }
3448 }
3449
3450 return new_flags;
3451 }
3452
3453 static PRInt32 PR_CALLBACK
ssl_TransmitFile(PRFileDesc * sd,PRFileDesc * fd,const void * headers,PRInt32 hlen,PRTransmitFileFlags flags,PRIntervalTime timeout)3454 ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
3455 const void *headers, PRInt32 hlen,
3456 PRTransmitFileFlags flags, PRIntervalTime timeout)
3457 {
3458 PRSendFileData sfd;
3459
3460 sfd.fd = fd;
3461 sfd.file_offset = 0;
3462 sfd.file_nbytes = 0;
3463 sfd.header = headers;
3464 sfd.hlen = hlen;
3465 sfd.trailer = NULL;
3466 sfd.tlen = 0;
3467
3468 return sd->methods->sendfile(sd, &sfd, flags, timeout);
3469 }
3470
3471 PRBool
ssl_FdIsBlocking(PRFileDesc * fd)3472 ssl_FdIsBlocking(PRFileDesc *fd)
3473 {
3474 PRSocketOptionData opt;
3475 PRStatus status;
3476
3477 opt.option = PR_SockOpt_Nonblocking;
3478 opt.value.non_blocking = PR_FALSE;
3479 status = PR_GetSocketOption(fd, &opt);
3480 if (status != PR_SUCCESS)
3481 return PR_FALSE;
3482 return (PRBool)!opt.value.non_blocking;
3483 }
3484
3485 PRBool
ssl_SocketIsBlocking(sslSocket * ss)3486 ssl_SocketIsBlocking(sslSocket *ss)
3487 {
3488 return ssl_FdIsBlocking(ss->fd);
3489 }
3490
3491 PRInt32 sslFirstBufSize = 8 * 1024;
3492 PRInt32 sslCopyLimit = 1024;
3493
3494 static PRInt32 PR_CALLBACK
ssl_WriteV(PRFileDesc * fd,const PRIOVec * iov,PRInt32 vectors,PRIntervalTime timeout)3495 ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
3496 PRIntervalTime timeout)
3497 {
3498 PRInt32 i;
3499 PRInt32 bufLen;
3500 PRInt32 left;
3501 PRInt32 rv;
3502 PRInt32 sent = 0;
3503 const PRInt32 first_len = sslFirstBufSize;
3504 const PRInt32 limit = sslCopyLimit;
3505 PRBool blocking;
3506 PRIOVec myIov;
3507 char buf[MAX_FRAGMENT_LENGTH];
3508
3509 if (vectors < 0) {
3510 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
3511 return -1;
3512 }
3513 if (vectors > PR_MAX_IOVECTOR_SIZE) {
3514 PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
3515 return -1;
3516 }
3517 for (i = 0; i < vectors; i++) {
3518 if (iov[i].iov_len < 0) {
3519 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
3520 return -1;
3521 }
3522 }
3523 blocking = ssl_FdIsBlocking(fd);
3524
3525 #define K16 ((int)sizeof(buf))
3526 #define KILL_VECTORS \
3527 while (vectors && !iov->iov_len) { \
3528 ++iov; \
3529 --vectors; \
3530 }
3531 #define GET_VECTOR \
3532 do { \
3533 myIov = *iov++; \
3534 --vectors; \
3535 KILL_VECTORS \
3536 } while (0)
3537 #define HANDLE_ERR(rv, len) \
3538 if (rv != len) { \
3539 if (rv < 0) { \
3540 if (!blocking && \
3541 (PR_GetError() == PR_WOULD_BLOCK_ERROR) && \
3542 (sent > 0)) { \
3543 return sent; \
3544 } else { \
3545 return -1; \
3546 } \
3547 } \
3548 /* Only a nonblocking socket can have partial sends */ \
3549 PR_ASSERT(!blocking); \
3550 return sent + rv; \
3551 }
3552 #define SEND(bfr, len) \
3553 do { \
3554 rv = ssl_Send(fd, bfr, len, 0, timeout); \
3555 HANDLE_ERR(rv, len) \
3556 sent += len; \
3557 } while (0)
3558
3559 /* Make sure the first write is at least 8 KB, if possible. */
3560 KILL_VECTORS
3561 if (!vectors)
3562 return ssl_Send(fd, 0, 0, 0, timeout);
3563 GET_VECTOR;
3564 if (!vectors) {
3565 return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
3566 }
3567 if (myIov.iov_len < first_len) {
3568 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
3569 bufLen = myIov.iov_len;
3570 left = first_len - bufLen;
3571 while (vectors && left) {
3572 int toCopy;
3573 GET_VECTOR;
3574 toCopy = PR_MIN(left, myIov.iov_len);
3575 PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
3576 bufLen += toCopy;
3577 left -= toCopy;
3578 myIov.iov_base += toCopy;
3579 myIov.iov_len -= toCopy;
3580 }
3581 SEND(buf, bufLen);
3582 }
3583
3584 while (vectors || myIov.iov_len) {
3585 PRInt32 addLen;
3586 if (!myIov.iov_len) {
3587 GET_VECTOR;
3588 }
3589 while (myIov.iov_len >= K16) {
3590 SEND(myIov.iov_base, K16);
3591 myIov.iov_base += K16;
3592 myIov.iov_len -= K16;
3593 }
3594 if (!myIov.iov_len)
3595 continue;
3596
3597 if (!vectors || myIov.iov_len > limit) {
3598 addLen = 0;
3599 } else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
3600 /* Addlen is already computed. */;
3601 } else if (vectors > 1 &&
3602 iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
3603 addLen = limit - myIov.iov_len;
3604 } else
3605 addLen = 0;
3606
3607 if (!addLen) {
3608 SEND(myIov.iov_base, myIov.iov_len);
3609 myIov.iov_len = 0;
3610 continue;
3611 }
3612 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
3613 bufLen = myIov.iov_len;
3614 do {
3615 GET_VECTOR;
3616 PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
3617 myIov.iov_base += addLen;
3618 myIov.iov_len -= addLen;
3619 bufLen += addLen;
3620
3621 left = PR_MIN(limit, K16 - bufLen);
3622 if (!vectors /* no more left */
3623 || myIov.iov_len > 0 /* we didn't use that one all up */
3624 || bufLen >= K16 /* it's full. */) {
3625 addLen = 0;
3626 } else if ((addLen = iov->iov_len % K16) <= left) {
3627 /* Addlen is already computed. */;
3628 } else if (vectors > 1 &&
3629 iov[1].iov_len % K16 + addLen <= left + limit) {
3630 addLen = left;
3631 } else
3632 addLen = 0;
3633
3634 } while (addLen);
3635 SEND(buf, bufLen);
3636 }
3637 return sent;
3638 }
3639
3640 /*
3641 * These functions aren't implemented.
3642 */
3643
3644 static PRInt32 PR_CALLBACK
ssl_Available(PRFileDesc * fd)3645 ssl_Available(PRFileDesc *fd)
3646 {
3647 PORT_Assert(0);
3648 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3649 return SECFailure;
3650 }
3651
3652 static PRInt64 PR_CALLBACK
ssl_Available64(PRFileDesc * fd)3653 ssl_Available64(PRFileDesc *fd)
3654 {
3655 PRInt64 res;
3656
3657 PORT_Assert(0);
3658 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3659 LL_I2L(res, -1L);
3660 return res;
3661 }
3662
3663 static PRStatus PR_CALLBACK
ssl_FSync(PRFileDesc * fd)3664 ssl_FSync(PRFileDesc *fd)
3665 {
3666 PORT_Assert(0);
3667 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3668 return PR_FAILURE;
3669 }
3670
3671 static PRInt32 PR_CALLBACK
ssl_Seek(PRFileDesc * fd,PRInt32 offset,PRSeekWhence how)3672 ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how)
3673 {
3674 PORT_Assert(0);
3675 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3676 return SECFailure;
3677 }
3678
3679 static PRInt64 PR_CALLBACK
ssl_Seek64(PRFileDesc * fd,PRInt64 offset,PRSeekWhence how)3680 ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how)
3681 {
3682 PRInt64 res;
3683
3684 PORT_Assert(0);
3685 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3686 LL_I2L(res, -1L);
3687 return res;
3688 }
3689
3690 static PRStatus PR_CALLBACK
ssl_FileInfo(PRFileDesc * fd,PRFileInfo * info)3691 ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
3692 {
3693 PORT_Assert(0);
3694 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3695 return PR_FAILURE;
3696 }
3697
3698 static PRStatus PR_CALLBACK
ssl_FileInfo64(PRFileDesc * fd,PRFileInfo64 * info)3699 ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
3700 {
3701 PORT_Assert(0);
3702 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3703 return PR_FAILURE;
3704 }
3705
3706 static PRInt32 PR_CALLBACK
ssl_RecvFrom(PRFileDesc * fd,void * buf,PRInt32 amount,PRIntn flags,PRNetAddr * addr,PRIntervalTime timeout)3707 ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
3708 PRNetAddr *addr, PRIntervalTime timeout)
3709 {
3710 PORT_Assert(0);
3711 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3712 return SECFailure;
3713 }
3714
3715 static PRInt32 PR_CALLBACK
ssl_SendTo(PRFileDesc * fd,const void * buf,PRInt32 amount,PRIntn flags,const PRNetAddr * addr,PRIntervalTime timeout)3716 ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
3717 const PRNetAddr *addr, PRIntervalTime timeout)
3718 {
3719 PORT_Assert(0);
3720 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
3721 return SECFailure;
3722 }
3723
3724 static const PRIOMethods ssl_methods = {
3725 PR_DESC_LAYERED,
3726 ssl_Close, /* close */
3727 ssl_Read, /* read */
3728 ssl_Write, /* write */
3729 ssl_Available, /* available */
3730 ssl_Available64, /* available64 */
3731 ssl_FSync, /* fsync */
3732 ssl_Seek, /* seek */
3733 ssl_Seek64, /* seek64 */
3734 ssl_FileInfo, /* fileInfo */
3735 ssl_FileInfo64, /* fileInfo64 */
3736 ssl_WriteV, /* writev */
3737 ssl_Connect, /* connect */
3738 ssl_Accept, /* accept */
3739 ssl_Bind, /* bind */
3740 ssl_Listen, /* listen */
3741 ssl_Shutdown, /* shutdown */
3742 ssl_Recv, /* recv */
3743 ssl_Send, /* send */
3744 ssl_RecvFrom, /* recvfrom */
3745 ssl_SendTo, /* sendto */
3746 ssl_Poll, /* poll */
3747 PR_EmulateAcceptRead, /* acceptread */
3748 ssl_TransmitFile, /* transmitfile */
3749 ssl_GetSockName, /* getsockname */
3750 ssl_GetPeerName, /* getpeername */
3751 NULL, /* getsockopt OBSOLETE */
3752 NULL, /* setsockopt OBSOLETE */
3753 NULL, /* getsocketoption */
3754 NULL, /* setsocketoption */
3755 PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/
3756 NULL, /* reserved for future use */
3757 NULL, /* reserved for future use */
3758 NULL, /* reserved for future use */
3759 NULL, /* reserved for future use */
3760 NULL /* reserved for future use */
3761 };
3762
3763 static PRIOMethods combined_methods;
3764
3765 static void
ssl_SetupIOMethods(void)3766 ssl_SetupIOMethods(void)
3767 {
3768 PRIOMethods *new_methods = &combined_methods;
3769 const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
3770 const PRIOMethods *my_methods = &ssl_methods;
3771
3772 *new_methods = *nspr_methods;
3773
3774 new_methods->file_type = my_methods->file_type;
3775 new_methods->close = my_methods->close;
3776 new_methods->read = my_methods->read;
3777 new_methods->write = my_methods->write;
3778 new_methods->available = my_methods->available;
3779 new_methods->available64 = my_methods->available64;
3780 new_methods->fsync = my_methods->fsync;
3781 new_methods->seek = my_methods->seek;
3782 new_methods->seek64 = my_methods->seek64;
3783 new_methods->fileInfo = my_methods->fileInfo;
3784 new_methods->fileInfo64 = my_methods->fileInfo64;
3785 new_methods->writev = my_methods->writev;
3786 new_methods->connect = my_methods->connect;
3787 new_methods->accept = my_methods->accept;
3788 new_methods->bind = my_methods->bind;
3789 new_methods->listen = my_methods->listen;
3790 new_methods->shutdown = my_methods->shutdown;
3791 new_methods->recv = my_methods->recv;
3792 new_methods->send = my_methods->send;
3793 new_methods->recvfrom = my_methods->recvfrom;
3794 new_methods->sendto = my_methods->sendto;
3795 new_methods->poll = my_methods->poll;
3796 new_methods->acceptread = my_methods->acceptread;
3797 new_methods->transmitfile = my_methods->transmitfile;
3798 new_methods->getsockname = my_methods->getsockname;
3799 new_methods->getpeername = my_methods->getpeername;
3800 /* new_methods->getsocketoption = my_methods->getsocketoption; */
3801 /* new_methods->setsocketoption = my_methods->setsocketoption; */
3802 new_methods->sendfile = my_methods->sendfile;
3803 }
3804
3805 static PRCallOnceType initIoLayerOnce;
3806
3807 static PRStatus
ssl_InitIOLayer(void)3808 ssl_InitIOLayer(void)
3809 {
3810 ssl_layer_id = PR_GetUniqueIdentity("SSL");
3811 ssl_SetupIOMethods();
3812 return PR_SUCCESS;
3813 }
3814
3815 static PRStatus
ssl_PushIOLayer(sslSocket * ns,PRFileDesc * stack,PRDescIdentity id)3816 ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
3817 {
3818 PRFileDesc *layer = NULL;
3819 PRStatus status;
3820
3821 status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
3822 if (status != PR_SUCCESS) {
3823 goto loser;
3824 }
3825 if (ns == NULL) {
3826 goto loser;
3827 }
3828 layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
3829 if (layer == NULL)
3830 goto loser;
3831 layer->secret = (PRFilePrivate *)ns;
3832
3833 /* Here, "stack" points to the PRFileDesc on the top of the stack.
3834 ** "layer" points to a new FD that is to be inserted into the stack.
3835 ** If layer is being pushed onto the top of the stack, then
3836 ** PR_PushIOLayer switches the contents of stack and layer, and then
3837 ** puts stack on top of layer, so that after it is done, the top of
3838 ** stack is the same "stack" as it was before, and layer is now the
3839 ** FD for the former top of stack.
3840 ** After this call, stack always points to the top PRFD on the stack.
3841 ** If this function fails, the contents of stack and layer are as
3842 ** they were before the call.
3843 */
3844 status = PR_PushIOLayer(stack, id, layer);
3845 if (status != PR_SUCCESS)
3846 goto loser;
3847
3848 ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
3849 return PR_SUCCESS;
3850
3851 loser:
3852 if (layer) {
3853 layer->dtor(layer); /* free layer */
3854 }
3855 return PR_FAILURE;
3856 }
3857
3858 /* if this fails, caller must destroy socket. */
3859 static SECStatus
ssl_MakeLocks(sslSocket * ss)3860 ssl_MakeLocks(sslSocket *ss)
3861 {
3862 ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
3863 if (!ss->firstHandshakeLock)
3864 goto loser;
3865 ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL);
3866 if (!ss->ssl3HandshakeLock)
3867 goto loser;
3868 ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
3869 if (!ss->specLock)
3870 goto loser;
3871 ss->recvBufLock = PZ_NewMonitor(nssILockSSL);
3872 if (!ss->recvBufLock)
3873 goto loser;
3874 ss->xmitBufLock = PZ_NewMonitor(nssILockSSL);
3875 if (!ss->xmitBufLock)
3876 goto loser;
3877 ss->writerThread = NULL;
3878 if (ssl_lock_readers) {
3879 ss->recvLock = PZ_NewLock(nssILockSSL);
3880 if (!ss->recvLock)
3881 goto loser;
3882 ss->sendLock = PZ_NewLock(nssILockSSL);
3883 if (!ss->sendLock)
3884 goto loser;
3885 }
3886 return SECSuccess;
3887 loser:
3888 ssl_DestroyLocks(ss);
3889 return SECFailure;
3890 }
3891
3892 #if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS)
3893 #define NSS_HAVE_GETENV 1
3894 #endif
3895
3896 #define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */
3897
3898 static void
ssl_SetDefaultsFromEnvironment(void)3899 ssl_SetDefaultsFromEnvironment(void)
3900 {
3901 #if defined(NSS_HAVE_GETENV)
3902 static int firsttime = 1;
3903
3904 if (firsttime) {
3905 char *ev;
3906 firsttime = 0;
3907 #ifdef DEBUG
3908 ssl_trace_iob = NULL;
3909 ev = PR_GetEnvSecure("SSLDEBUGFILE");
3910 if (ev && ev[0]) {
3911 ssl_trace_iob = fopen(ev, "w");
3912 }
3913 if (!ssl_trace_iob) {
3914 ssl_trace_iob = stderr;
3915 }
3916 #ifdef TRACE
3917 ev = PR_GetEnvSecure("SSLTRACE");
3918 if (ev && ev[0]) {
3919 ssl_trace = atoi(ev);
3920 SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
3921 }
3922 #endif /* TRACE */
3923 ev = PR_GetEnvSecure("SSLDEBUG");
3924 if (ev && ev[0]) {
3925 ssl_debug = atoi(ev);
3926 SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
3927 }
3928 #endif /* DEBUG */
3929 #ifdef NSS_ALLOW_SSLKEYLOGFILE
3930 ssl_keylog_iob = NULL;
3931 ev = PR_GetEnvSecure("SSLKEYLOGFILE");
3932 if (ev && ev[0]) {
3933 ssl_keylog_iob = fopen(ev, "a");
3934 if (!ssl_keylog_iob) {
3935 SSL_TRACE(("SSL: failed to open key log file"));
3936 } else {
3937 if (ftell(ssl_keylog_iob) == 0) {
3938 fputs("# SSL/TLS secrets log file, generated by NSS\n",
3939 ssl_keylog_iob);
3940 }
3941 SSL_TRACE(("SSL: logging SSL/TLS secrets to %s", ev));
3942 ssl_keylog_lock = PR_NewLock();
3943 if (!ssl_keylog_lock) {
3944 SSL_TRACE(("SSL: failed to create key log lock"));
3945 fclose(ssl_keylog_iob);
3946 ssl_keylog_iob = NULL;
3947 }
3948 }
3949 }
3950 #endif
3951 ev = PR_GetEnvSecure("SSLFORCELOCKS");
3952 if (ev && ev[0] == '1') {
3953 ssl_force_locks = PR_TRUE;
3954 ssl_defaults.noLocks = 0;
3955 strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED. ");
3956 SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
3957 }
3958 ev = PR_GetEnvSecure("NSS_SSL_ENABLE_RENEGOTIATION");
3959 if (ev) {
3960 if (ev[0] == '1' || LOWER(ev[0]) == 'u')
3961 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED;
3962 else if (ev[0] == '0' || LOWER(ev[0]) == 'n')
3963 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
3964 else if (ev[0] == '2' || LOWER(ev[0]) == 'r')
3965 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN;
3966 else if (ev[0] == '3' || LOWER(ev[0]) == 't')
3967 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_TRANSITIONAL;
3968 SSL_TRACE(("SSL: enableRenegotiation set to %d",
3969 ssl_defaults.enableRenegotiation));
3970 }
3971 ev = PR_GetEnvSecure("NSS_SSL_REQUIRE_SAFE_NEGOTIATION");
3972 if (ev && ev[0] == '1') {
3973 ssl_defaults.requireSafeNegotiation = PR_TRUE;
3974 SSL_TRACE(("SSL: requireSafeNegotiation set to %d",
3975 PR_TRUE));
3976 }
3977 ev = PR_GetEnvSecure("NSS_SSL_CBC_RANDOM_IV");
3978 if (ev && ev[0] == '0') {
3979 ssl_defaults.cbcRandomIV = PR_FALSE;
3980 SSL_TRACE(("SSL: cbcRandomIV set to 0"));
3981 }
3982 }
3983 #endif /* NSS_HAVE_GETENV */
3984 }
3985
3986 const sslNamedGroupDef *
ssl_LookupNamedGroup(SSLNamedGroup group)3987 ssl_LookupNamedGroup(SSLNamedGroup group)
3988 {
3989 unsigned int i;
3990
3991 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
3992 if (ssl_named_groups[i].name == group) {
3993 return &ssl_named_groups[i];
3994 }
3995 }
3996 return NULL;
3997 }
3998
3999 PRBool
ssl_NamedGroupEnabled(const sslSocket * ss,const sslNamedGroupDef * groupDef)4000 ssl_NamedGroupEnabled(const sslSocket *ss, const sslNamedGroupDef *groupDef)
4001 {
4002 unsigned int i;
4003
4004 if (!groupDef) {
4005 return PR_FALSE;
4006 }
4007
4008 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
4009 if (ss->namedGroupPreferences[i] &&
4010 ss->namedGroupPreferences[i] == groupDef) {
4011 return PR_TRUE;
4012 }
4013 }
4014 return PR_FALSE;
4015 }
4016
4017 /* Returns a reference counted object that contains a key pair.
4018 * Or NULL on failure. Initial ref count is 1.
4019 * Uses the keys in the pair as input. Adopts the keys given.
4020 */
4021 sslKeyPair *
ssl_NewKeyPair(SECKEYPrivateKey * privKey,SECKEYPublicKey * pubKey)4022 ssl_NewKeyPair(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey)
4023 {
4024 sslKeyPair *pair;
4025
4026 if (!privKey || !pubKey) {
4027 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
4028 return NULL;
4029 }
4030 pair = PORT_ZNew(sslKeyPair);
4031 if (!pair)
4032 return NULL; /* error code is set. */
4033 pair->privKey = privKey;
4034 pair->pubKey = pubKey;
4035 pair->refCount = 1;
4036 return pair; /* success */
4037 }
4038
4039 sslKeyPair *
ssl_GetKeyPairRef(sslKeyPair * keyPair)4040 ssl_GetKeyPairRef(sslKeyPair *keyPair)
4041 {
4042 PR_ATOMIC_INCREMENT(&keyPair->refCount);
4043 return keyPair;
4044 }
4045
4046 void
ssl_FreeKeyPair(sslKeyPair * keyPair)4047 ssl_FreeKeyPair(sslKeyPair *keyPair)
4048 {
4049 if (!keyPair) {
4050 return;
4051 }
4052
4053 PRInt32 newCount = PR_ATOMIC_DECREMENT(&keyPair->refCount);
4054 if (!newCount) {
4055 SECKEY_DestroyPrivateKey(keyPair->privKey);
4056 SECKEY_DestroyPublicKey(keyPair->pubKey);
4057 PORT_Free(keyPair);
4058 }
4059 }
4060
4061 /* Ephemeral key handling. */
4062 sslEphemeralKeyPair *
ssl_NewEphemeralKeyPair(const sslNamedGroupDef * group,SECKEYPrivateKey * privKey,SECKEYPublicKey * pubKey)4063 ssl_NewEphemeralKeyPair(const sslNamedGroupDef *group,
4064 SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey)
4065 {
4066 sslKeyPair *keys;
4067 sslEphemeralKeyPair *pair;
4068
4069 if (!group) {
4070 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
4071 return NULL;
4072 }
4073
4074 keys = ssl_NewKeyPair(privKey, pubKey);
4075 if (!keys) {
4076 return NULL;
4077 }
4078
4079 pair = PORT_ZNew(sslEphemeralKeyPair);
4080 if (!pair) {
4081 ssl_FreeKeyPair(keys);
4082 return NULL; /* error already set */
4083 }
4084
4085 PR_INIT_CLIST(&pair->link);
4086 pair->group = group;
4087 pair->keys = keys;
4088
4089 return pair;
4090 }
4091
4092 sslEphemeralKeyPair *
ssl_CopyEphemeralKeyPair(sslEphemeralKeyPair * keyPair)4093 ssl_CopyEphemeralKeyPair(sslEphemeralKeyPair *keyPair)
4094 {
4095 sslEphemeralKeyPair *pair;
4096
4097 pair = PORT_ZNew(sslEphemeralKeyPair);
4098 if (!pair) {
4099 return NULL; /* error already set */
4100 }
4101
4102 PR_INIT_CLIST(&pair->link);
4103 pair->group = keyPair->group;
4104 pair->keys = ssl_GetKeyPairRef(keyPair->keys);
4105
4106 return pair;
4107 }
4108
4109 void
ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair * keyPair)4110 ssl_FreeEphemeralKeyPair(sslEphemeralKeyPair *keyPair)
4111 {
4112 if (!keyPair) {
4113 return;
4114 }
4115
4116 ssl_FreeKeyPair(keyPair->keys);
4117 PR_REMOVE_LINK(&keyPair->link);
4118 PORT_Free(keyPair);
4119 }
4120
4121 PRBool
ssl_HaveEphemeralKeyPair(const sslSocket * ss,const sslNamedGroupDef * groupDef)4122 ssl_HaveEphemeralKeyPair(const sslSocket *ss, const sslNamedGroupDef *groupDef)
4123 {
4124 return ssl_LookupEphemeralKeyPair((sslSocket *)ss, groupDef) != NULL;
4125 }
4126
4127 sslEphemeralKeyPair *
ssl_LookupEphemeralKeyPair(sslSocket * ss,const sslNamedGroupDef * groupDef)4128 ssl_LookupEphemeralKeyPair(sslSocket *ss, const sslNamedGroupDef *groupDef)
4129 {
4130 PRCList *cursor;
4131 for (cursor = PR_NEXT_LINK(&ss->ephemeralKeyPairs);
4132 cursor != &ss->ephemeralKeyPairs;
4133 cursor = PR_NEXT_LINK(cursor)) {
4134 sslEphemeralKeyPair *keyPair = (sslEphemeralKeyPair *)cursor;
4135 if (keyPair->group == groupDef) {
4136 return keyPair;
4137 }
4138 }
4139 return NULL;
4140 }
4141
4142 void
ssl_FreeEphemeralKeyPairs(sslSocket * ss)4143 ssl_FreeEphemeralKeyPairs(sslSocket *ss)
4144 {
4145 while (!PR_CLIST_IS_EMPTY(&ss->ephemeralKeyPairs)) {
4146 PRCList *cursor = PR_LIST_TAIL(&ss->ephemeralKeyPairs);
4147 ssl_FreeEphemeralKeyPair((sslEphemeralKeyPair *)cursor);
4148 }
4149 }
4150
4151 PRTime
ssl_Time(const sslSocket * ss)4152 ssl_Time(const sslSocket *ss)
4153 {
4154 if (!ss->now) {
4155 return PR_Now();
4156 }
4157 return ss->now(ss->nowArg);
4158 }
4159
4160 /*
4161 ** Create a newsocket structure for a file descriptor.
4162 */
4163 static sslSocket *
ssl_NewSocket(PRBool makeLocks,SSLProtocolVariant protocolVariant)4164 ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant)
4165 {
4166 SECStatus rv;
4167 sslSocket *ss;
4168 int i;
4169 ssl_SetDefaultsFromEnvironment();
4170
4171 if (ssl_force_locks)
4172 makeLocks = PR_TRUE;
4173
4174 /* Make a new socket and get it ready */
4175 ss = PORT_ZNew(sslSocket);
4176 if (!ss) {
4177 return NULL;
4178 }
4179 ss->opt = ssl_defaults;
4180 if (protocolVariant == ssl_variant_datagram) {
4181 ss->opt.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
4182 }
4183 ss->opt.useSocks = PR_FALSE;
4184 ss->opt.noLocks = !makeLocks;
4185 ss->vrange = *VERSIONS_DEFAULTS(protocolVariant);
4186 ss->protocolVariant = protocolVariant;
4187 /* Ignore overlap failures, because returning NULL would trigger assertion
4188 * failures elsewhere. We don't want this scenario to be fatal, it's just
4189 * a state where no SSL connectivity is possible. */
4190 ssl3_CreateOverlapWithPolicy(ss->protocolVariant, &ss->vrange, &ss->vrange);
4191 ss->peerID = NULL;
4192 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
4193 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
4194 ss->cTimeout = PR_INTERVAL_NO_TIMEOUT;
4195 ss->url = NULL;
4196
4197 PR_INIT_CLIST(&ss->serverCerts);
4198 PR_INIT_CLIST(&ss->ephemeralKeyPairs);
4199 PR_INIT_CLIST(&ss->extensionHooks);
4200 PR_INIT_CLIST(&ss->echConfigs);
4201
4202 ss->dbHandle = CERT_GetDefaultCertDB();
4203
4204 /* Provide default implementation of hooks */
4205 ss->authCertificate = SSL_AuthCertificate;
4206 ss->authCertificateArg = (void *)ss->dbHandle;
4207 ss->sniSocketConfig = NULL;
4208 ss->sniSocketConfigArg = NULL;
4209 ss->getClientAuthData = NULL;
4210 ss->alertReceivedCallback = NULL;
4211 ss->alertReceivedCallbackArg = NULL;
4212 ss->alertSentCallback = NULL;
4213 ss->alertSentCallbackArg = NULL;
4214 ss->handleBadCert = NULL;
4215 ss->badCertArg = NULL;
4216 ss->pkcs11PinArg = NULL;
4217
4218 ssl_ChooseOps(ss);
4219 ssl3_InitSocketPolicy(ss);
4220 for (i = 0; i < SSL_NAMED_GROUP_COUNT; ++i) {
4221 ss->namedGroupPreferences[i] = &ssl_named_groups[i];
4222 }
4223 ss->additionalShares = 0;
4224 PR_INIT_CLIST(&ss->ssl3.hs.remoteExtensions);
4225 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
4226 PR_INIT_CLIST(&ss->ssl3.hs.cipherSpecs);
4227 PR_INIT_CLIST(&ss->ssl3.hs.bufferedEarlyData);
4228 ssl3_InitExtensionData(&ss->xtnData, ss);
4229 PR_INIT_CLIST(&ss->ssl3.hs.dtlsSentHandshake);
4230 PR_INIT_CLIST(&ss->ssl3.hs.dtlsRcvdHandshake);
4231 PR_INIT_CLIST(&ss->ssl3.hs.psks);
4232 dtls_InitTimers(ss);
4233
4234 ss->echPrivKey = NULL;
4235 ss->echPubKey = NULL;
4236 ss->antiReplay = NULL;
4237 ss->psk = NULL;
4238
4239 if (makeLocks) {
4240 rv = ssl_MakeLocks(ss);
4241 if (rv != SECSuccess)
4242 goto loser;
4243 }
4244 rv = ssl_CreateSecurityInfo(ss);
4245 if (rv != SECSuccess)
4246 goto loser;
4247 rv = ssl3_InitGather(&ss->gs);
4248 if (rv != SECSuccess)
4249 goto loser;
4250 rv = ssl3_InitState(ss);
4251 if (rv != SECSuccess) {
4252 goto loser;
4253 }
4254 return ss;
4255
4256 loser:
4257 ssl_DestroySocketContents(ss);
4258 ssl_DestroyLocks(ss);
4259 PORT_Free(ss);
4260 return NULL;
4261 }
4262
4263 /**
4264 * DEPRECATED: Will always return false.
4265 */
4266 SECStatus
SSL_CanBypass(CERTCertificate * cert,SECKEYPrivateKey * srvPrivkey,PRUint32 protocolmask,PRUint16 * ciphersuites,int nsuites,PRBool * pcanbypass,void * pwArg)4267 SSL_CanBypass(CERTCertificate *cert, SECKEYPrivateKey *srvPrivkey,
4268 PRUint32 protocolmask, PRUint16 *ciphersuites, int nsuites,
4269 PRBool *pcanbypass, void *pwArg)
4270 {
4271 if (!pcanbypass) {
4272 PORT_SetError(SEC_ERROR_INVALID_ARGS);
4273 return SECFailure;
4274 }
4275 *pcanbypass = PR_FALSE;
4276 return SECSuccess;
4277 }
4278
4279 /* Functions that are truly experimental use EXP, functions that are no longer
4280 * experimental use PUB.
4281 *
4282 * When initially defining a new API, add that API here using the EXP() macro
4283 * and name the function with a SSLExp_ prefix. Define the experimental API as
4284 * a macro in sslexp.h using the SSL_EXPERIMENTAL_API() macro defined there.
4285 *
4286 * Once an API is stable and proven, move the macro definition in sslexp.h to a
4287 * proper function declaration in ssl.h. Keeping the function in this list
4288 * ensures that code built against the release that contained the experimental
4289 * API will continue to work; use PUB() to reference the public function.
4290 */
4291 #define EXP(n) \
4292 { \
4293 "SSL_" #n, SSLExp_##n \
4294 }
4295 #define PUB(n) \
4296 { \
4297 "SSL_" #n, SSL_##n \
4298 }
4299 struct {
4300 const char *const name;
4301 void *function;
4302 } ssl_experimental_functions[] = {
4303 #ifndef SSL_DISABLE_EXPERIMENTAL_API
4304 EXP(AddExternalPsk),
4305 EXP(AddExternalPsk0Rtt),
4306 EXP(AeadDecrypt),
4307 EXP(AeadEncrypt),
4308 EXP(CallExtensionWriterOnEchInner),
4309 EXP(CipherSuiteOrderGet),
4310 EXP(CipherSuiteOrderSet),
4311 EXP(CreateAntiReplayContext),
4312 EXP(CreateMask),
4313 EXP(CreateMaskingContext),
4314 EXP(CreateVariantMaskingContext),
4315 EXP(DelegateCredential),
4316 EXP(DestroyAead),
4317 EXP(DestroyMaskingContext),
4318 EXP(DestroyResumptionTokenInfo),
4319 EXP(EnableTls13BackendEch),
4320 EXP(EnableTls13GreaseEch),
4321 EXP(EncodeEchConfigId),
4322 EXP(GetCurrentEpoch),
4323 EXP(GetEchRetryConfigs),
4324 EXP(GetExtensionSupport),
4325 EXP(GetResumptionTokenInfo),
4326 EXP(HelloRetryRequestCallback),
4327 EXP(InstallExtensionHooks),
4328 EXP(HkdfExtract),
4329 EXP(HkdfExpandLabel),
4330 EXP(HkdfExpandLabelWithMech),
4331 EXP(HkdfVariantExpandLabel),
4332 EXP(HkdfVariantExpandLabelWithMech),
4333 EXP(KeyUpdate),
4334 EXP(MakeAead),
4335 EXP(MakeVariantAead),
4336 EXP(RecordLayerData),
4337 EXP(RecordLayerWriteCallback),
4338 EXP(ReleaseAntiReplayContext),
4339 EXP(RemoveEchConfigs),
4340 EXP(RemoveExternalPsk),
4341 EXP(SecretCallback),
4342 EXP(SendCertificateRequest),
4343 EXP(SendSessionTicket),
4344 EXP(SetAntiReplayContext),
4345 EXP(SetClientEchConfigs),
4346 EXP(SetDtls13VersionWorkaround),
4347 EXP(SetMaxEarlyDataSize),
4348 EXP(SetResumptionTokenCallback),
4349 EXP(SetResumptionToken),
4350 EXP(SetServerEchConfigs),
4351 EXP(SetTimeFunc),
4352 #endif
4353 { "", NULL }
4354 };
4355 #undef EXP
4356 #undef PUB
4357
4358 void *
SSL_GetExperimentalAPI(const char * name)4359 SSL_GetExperimentalAPI(const char *name)
4360 {
4361 unsigned int i;
4362 for (i = 0; i < PR_ARRAY_SIZE(ssl_experimental_functions); ++i) {
4363 if (strcmp(name, ssl_experimental_functions[i].name) == 0) {
4364 return ssl_experimental_functions[i].function;
4365 }
4366 }
4367 PORT_SetError(SSL_ERROR_UNSUPPORTED_EXPERIMENTAL_API);
4368 return NULL;
4369 }
4370
4371 void
ssl_ClearPRCList(PRCList * list,void (* f)(void *))4372 ssl_ClearPRCList(PRCList *list, void (*f)(void *))
4373 {
4374 PRCList *cursor;
4375
4376 while (!PR_CLIST_IS_EMPTY(list)) {
4377 cursor = PR_LIST_TAIL(list);
4378
4379 PR_REMOVE_LINK(cursor);
4380 if (f) {
4381 f(cursor);
4382 }
4383 PORT_Free(cursor);
4384 }
4385 }
4386
4387 SECStatus
SSLExp_EnableTls13GreaseEch(PRFileDesc * fd,PRBool enabled)4388 SSLExp_EnableTls13GreaseEch(PRFileDesc *fd, PRBool enabled)
4389 {
4390 sslSocket *ss = ssl_FindSocket(fd);
4391 if (!ss) {
4392 return SECFailure;
4393 }
4394 ss->opt.enableTls13GreaseEch = enabled;
4395 return SECSuccess;
4396 }
4397
4398 SECStatus
SSLExp_EnableTls13BackendEch(PRFileDesc * fd,PRBool enabled)4399 SSLExp_EnableTls13BackendEch(PRFileDesc *fd, PRBool enabled)
4400 {
4401 sslSocket *ss = ssl_FindSocket(fd);
4402 if (!ss) {
4403 return SECFailure;
4404 }
4405 ss->opt.enableTls13BackendEch = enabled;
4406 return SECSuccess;
4407 }
4408
4409 SECStatus
SSLExp_CallExtensionWriterOnEchInner(PRFileDesc * fd,PRBool enabled)4410 SSLExp_CallExtensionWriterOnEchInner(PRFileDesc *fd, PRBool enabled)
4411 {
4412 sslSocket *ss = ssl_FindSocket(fd);
4413 if (!ss) {
4414 return SECFailure;
4415 }
4416 ss->opt.callExtensionWriterOnEchInner = enabled;
4417 return SECSuccess;
4418 }
4419
4420 SECStatus
SSLExp_SetDtls13VersionWorkaround(PRFileDesc * fd,PRBool enabled)4421 SSLExp_SetDtls13VersionWorkaround(PRFileDesc *fd, PRBool enabled)
4422 {
4423 sslSocket *ss = ssl_FindSocket(fd);
4424 if (!ss) {
4425 return SECFailure;
4426 }
4427 ss->opt.enableDtls13VersionCompat = enabled;
4428 return SECSuccess;
4429 }
4430
4431 SECStatus
SSLExp_SetTimeFunc(PRFileDesc * fd,SSLTimeFunc f,void * arg)4432 SSLExp_SetTimeFunc(PRFileDesc *fd, SSLTimeFunc f, void *arg)
4433 {
4434 sslSocket *ss = ssl_FindSocket(fd);
4435
4436 if (!ss) {
4437 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetTimeFunc",
4438 SSL_GETPID(), fd));
4439 return SECFailure;
4440 }
4441 ss->now = f;
4442 ss->nowArg = arg;
4443 return SECSuccess;
4444 }
4445
4446 /* Experimental APIs for session cache handling. */
4447
4448 SECStatus
SSLExp_SetResumptionTokenCallback(PRFileDesc * fd,SSLResumptionTokenCallback cb,void * ctx)4449 SSLExp_SetResumptionTokenCallback(PRFileDesc *fd,
4450 SSLResumptionTokenCallback cb,
4451 void *ctx)
4452 {
4453 sslSocket *ss = ssl_FindSocket(fd);
4454
4455 if (!ss) {
4456 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetResumptionTokenCallback",
4457 SSL_GETPID(), fd));
4458 return SECFailure;
4459 }
4460
4461 ssl_Get1stHandshakeLock(ss);
4462 ssl_GetSSL3HandshakeLock(ss);
4463 ss->resumptionTokenCallback = cb;
4464 ss->resumptionTokenContext = ctx;
4465 ssl_ReleaseSSL3HandshakeLock(ss);
4466 ssl_Release1stHandshakeLock(ss);
4467
4468 return SECSuccess;
4469 }
4470
4471 SECStatus
SSLExp_SetResumptionToken(PRFileDesc * fd,const PRUint8 * token,unsigned int len)4472 SSLExp_SetResumptionToken(PRFileDesc *fd, const PRUint8 *token,
4473 unsigned int len)
4474 {
4475 sslSocket *ss = ssl_FindSocket(fd);
4476 sslSessionID *sid = NULL;
4477
4478 if (!ss) {
4479 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetResumptionToken",
4480 SSL_GETPID(), fd));
4481 return SECFailure;
4482 }
4483
4484 ssl_Get1stHandshakeLock(ss);
4485 ssl_GetSSL3HandshakeLock(ss);
4486
4487 if (ss->firstHsDone || ss->ssl3.hs.ws != idle_handshake ||
4488 ss->sec.isServer || len == 0 || !token) {
4489 PORT_SetError(SEC_ERROR_INVALID_ARGS);
4490 goto loser;
4491 }
4492
4493 // We override any previously set session.
4494 if (ss->sec.ci.sid) {
4495 ssl_FreeSID(ss->sec.ci.sid);
4496 ss->sec.ci.sid = NULL;
4497 }
4498
4499 PRINT_BUF(50, (ss, "incoming resumption token", token, len));
4500
4501 sid = ssl3_NewSessionID(ss, PR_FALSE);
4502 if (!sid) {
4503 goto loser;
4504 }
4505
4506 /* Populate NewSessionTicket values */
4507 SECStatus rv = ssl_DecodeResumptionToken(sid, token, len);
4508 if (rv != SECSuccess) {
4509 // If decoding fails, we assume the token is bad.
4510 PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
4511 goto loser;
4512 }
4513
4514 // Make sure that the token is currently usable.
4515 if (!ssl_IsResumptionTokenUsable(ss, sid)) {
4516 PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
4517 goto loser;
4518 }
4519
4520 // Generate a new random session ID for this ticket.
4521 rv = PK11_GenerateRandom(sid->u.ssl3.sessionID, SSL3_SESSIONID_BYTES);
4522 if (rv != SECSuccess) {
4523 goto loser; // Code set by PK11_GenerateRandom.
4524 }
4525 sid->u.ssl3.sessionIDLength = SSL3_SESSIONID_BYTES;
4526 /* Use the sid->cached as marker that this is from an external cache and
4527 * we don't have to look up anything in the NSS internal cache. */
4528 sid->cached = in_external_cache;
4529 sid->lastAccessTime = ssl_Time(ss);
4530
4531 ss->sec.ci.sid = sid;
4532
4533 ssl_ReleaseSSL3HandshakeLock(ss);
4534 ssl_Release1stHandshakeLock(ss);
4535 return SECSuccess;
4536
4537 loser:
4538 ssl_FreeSID(sid);
4539 ssl_ReleaseSSL3HandshakeLock(ss);
4540 ssl_Release1stHandshakeLock(ss);
4541
4542 return SECFailure;
4543 }
4544
4545 SECStatus
SSLExp_DestroyResumptionTokenInfo(SSLResumptionTokenInfo * token)4546 SSLExp_DestroyResumptionTokenInfo(SSLResumptionTokenInfo *token)
4547 {
4548 if (!token) {
4549 PORT_SetError(SEC_ERROR_INVALID_ARGS);
4550 return SECFailure;
4551 }
4552 if (token->peerCert) {
4553 CERT_DestroyCertificate(token->peerCert);
4554 }
4555 PORT_Free(token->alpnSelection);
4556 PORT_Memset(token, 0, token->length);
4557 return SECSuccess;
4558 }
4559
4560 SECStatus
SSLExp_GetResumptionTokenInfo(const PRUint8 * tokenData,unsigned int tokenLen,SSLResumptionTokenInfo * tokenOut,PRUintn len)4561 SSLExp_GetResumptionTokenInfo(const PRUint8 *tokenData, unsigned int tokenLen,
4562 SSLResumptionTokenInfo *tokenOut, PRUintn len)
4563 {
4564 if (!tokenData || !tokenOut || !tokenLen ||
4565 len > sizeof(SSLResumptionTokenInfo)) {
4566 PORT_SetError(SEC_ERROR_INVALID_ARGS);
4567 return SECFailure;
4568 }
4569 sslSessionID sid = { 0 };
4570 SSLResumptionTokenInfo token;
4571
4572 /* Populate sid values */
4573 if (ssl_DecodeResumptionToken(&sid, tokenData, tokenLen) != SECSuccess) {
4574 // If decoding fails, we assume the token is bad.
4575 PORT_SetError(SSL_ERROR_BAD_RESUMPTION_TOKEN_ERROR);
4576 return SECFailure;
4577 }
4578
4579 token.peerCert = CERT_DupCertificate(sid.peerCert);
4580
4581 token.alpnSelectionLen = sid.u.ssl3.alpnSelection.len;
4582 token.alpnSelection = PORT_ZAlloc(token.alpnSelectionLen);
4583 if (!token.alpnSelection) {
4584 return SECFailure;
4585 }
4586 if (token.alpnSelectionLen > 0) {
4587 PORT_Assert(sid.u.ssl3.alpnSelection.data);
4588 PORT_Memcpy(token.alpnSelection, sid.u.ssl3.alpnSelection.data,
4589 token.alpnSelectionLen);
4590 }
4591
4592 if (sid.u.ssl3.locked.sessionTicket.flags & ticket_allow_early_data) {
4593 token.maxEarlyDataSize =
4594 sid.u.ssl3.locked.sessionTicket.max_early_data_size;
4595 } else {
4596 token.maxEarlyDataSize = 0;
4597 }
4598 token.expirationTime = sid.expirationTime;
4599
4600 token.length = PR_MIN(sizeof(SSLResumptionTokenInfo), len);
4601 PORT_Memcpy(tokenOut, &token, token.length);
4602
4603 ssl_DestroySID(&sid, PR_FALSE);
4604 return SECSuccess;
4605 }
4606