Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / third_party / nss / ssl / sslsock.c
blob09a0fb514b293c68d1887ba32c23183e0d447cc7
1 /*
2 * vtables (and methods that call through them) for the 4 types of
3 * SSLSockets supported. Only one type is still supported.
4 * Various other functions.
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
9 #include "seccomon.h"
10 #include "cert.h"
11 #include "keyhi.h"
12 #include "ssl.h"
13 #include "sslimpl.h"
14 #include "sslproto.h"
15 #include "nspr.h"
16 #include "private/pprio.h"
17 #ifndef NO_PKCS11_BYPASS
18 #include "blapi.h"
19 #endif
20 #include "pk11pub.h"
21 #include "nss.h"
23 /* This is a bodge to allow this code to be compiled against older NSS headers
24 * that don't contain the TLS 1.2 changes. */
25 #ifndef CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
26 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
27 #endif
29 #define SET_ERROR_CODE /* reminder */
31 static const sslSocketOps ssl_default_ops = { /* No SSL. */
32 ssl_DefConnect,
33 NULL,
34 ssl_DefBind,
35 ssl_DefListen,
36 ssl_DefShutdown,
37 ssl_DefClose,
38 ssl_DefRecv,
39 ssl_DefSend,
40 ssl_DefRead,
41 ssl_DefWrite,
42 ssl_DefGetpeername,
43 ssl_DefGetsockname
46 static const sslSocketOps ssl_secure_ops = { /* SSL. */
47 ssl_SecureConnect,
48 NULL,
49 ssl_DefBind,
50 ssl_DefListen,
51 ssl_SecureShutdown,
52 ssl_SecureClose,
53 ssl_SecureRecv,
54 ssl_SecureSend,
55 ssl_SecureRead,
56 ssl_SecureWrite,
57 ssl_DefGetpeername,
58 ssl_DefGetsockname
62 ** default settings for socket enables
64 static sslOptions ssl_defaults = {
65 { siBuffer, NULL, 0 }, /* nextProtoNego */
66 PR_TRUE, /* useSecurity */
67 PR_FALSE, /* useSocks */
68 PR_FALSE, /* requestCertificate */
69 2, /* requireCertificate */
70 PR_FALSE, /* handshakeAsClient */
71 PR_FALSE, /* handshakeAsServer */
72 PR_FALSE, /* enableSSL2 */ /* now defaults to off in NSS 3.13 */
73 PR_FALSE, /* unusedBit9 */
74 PR_FALSE, /* unusedBit10 */
75 PR_FALSE, /* noCache */
76 PR_FALSE, /* fdx */
77 PR_FALSE, /* v2CompatibleHello */ /* now defaults to off in NSS 3.13 */
78 PR_TRUE, /* detectRollBack */
79 PR_FALSE, /* noStepDown */
80 PR_FALSE, /* bypassPKCS11 */
81 PR_FALSE, /* noLocks */
82 PR_FALSE, /* enableSessionTickets */
83 PR_FALSE, /* enableDeflate */
84 2, /* enableRenegotiation (default: requires extension) */
85 PR_FALSE, /* requireSafeNegotiation */
86 PR_FALSE, /* enableFalseStart */
87 PR_TRUE, /* cbcRandomIV */
88 PR_FALSE, /* enableOCSPStapling */
89 PR_TRUE, /* enableNPN */
90 PR_FALSE, /* enableALPN */
91 PR_TRUE, /* reuseServerECDHEKey */
92 PR_FALSE, /* enableFallbackSCSV */
93 PR_FALSE, /* enableSignedCertTimestamps */
97 * default range of enabled SSL/TLS protocols
99 static SSLVersionRange versions_defaults_stream = {
100 SSL_LIBRARY_VERSION_TLS_1_0,
101 SSL_LIBRARY_VERSION_TLS_1_2
104 static SSLVersionRange versions_defaults_datagram = {
105 SSL_LIBRARY_VERSION_TLS_1_1,
106 SSL_LIBRARY_VERSION_TLS_1_2
109 #define VERSIONS_DEFAULTS(variant) \
110 (variant == ssl_variant_stream ? &versions_defaults_stream : \
111 &versions_defaults_datagram)
113 sslSessionIDLookupFunc ssl_sid_lookup;
114 sslSessionIDCacheFunc ssl_sid_cache;
115 sslSessionIDUncacheFunc ssl_sid_uncache;
117 static PRBool ssl_inited = PR_FALSE;
118 static PRDescIdentity ssl_layer_id;
120 PRBool locksEverDisabled; /* implicitly PR_FALSE */
121 PRBool ssl_force_locks; /* implicitly PR_FALSE */
122 int ssl_lock_readers = 1; /* default true. */
123 char ssl_debug;
124 char ssl_trace;
125 FILE * ssl_trace_iob;
126 FILE * ssl_keylog_iob;
127 char lockStatus[] = "Locks are ENABLED. ";
128 #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
130 /* SRTP_NULL_HMAC_SHA1_80 and SRTP_NULL_HMAC_SHA1_32 are not implemented. */
131 static const PRUint16 srtpCiphers[] = {
132 SRTP_AES128_CM_HMAC_SHA1_80,
133 SRTP_AES128_CM_HMAC_SHA1_32,
137 /* forward declarations. */
138 static sslSocket *ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant variant);
139 static SECStatus ssl_MakeLocks(sslSocket *ss);
140 static void ssl_SetDefaultsFromEnvironment(void);
141 static PRStatus ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack,
142 PRDescIdentity id);
144 /************************************************************************/
147 ** Lookup a socket structure from a file descriptor.
148 ** Only functions called through the PRIOMethods table should use this.
149 ** Other app-callable functions should use ssl_FindSocket.
151 static sslSocket *
152 ssl_GetPrivate(PRFileDesc *fd)
154 sslSocket *ss;
156 PORT_Assert(fd != NULL);
157 PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
158 PORT_Assert(fd->identity == ssl_layer_id);
160 if (fd->methods->file_type != PR_DESC_LAYERED ||
161 fd->identity != ssl_layer_id) {
162 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
163 return NULL;
166 ss = (sslSocket *)fd->secret;
167 /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
168 * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
169 * contents of the PRFileDesc pointed by ss->fd and the new layer.
170 * See bug 807250.
172 ss->fd = fd;
173 return ss;
176 /* This function tries to find the SSL layer in the stack.
177 * It searches for the first SSL layer at or below the argument fd,
178 * and failing that, it searches for the nearest SSL layer above the
179 * argument fd. It returns the private sslSocket from the found layer.
181 sslSocket *
182 ssl_FindSocket(PRFileDesc *fd)
184 PRFileDesc *layer;
185 sslSocket *ss;
187 PORT_Assert(fd != NULL);
188 PORT_Assert(ssl_layer_id != 0);
190 layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
191 if (layer == NULL) {
192 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
193 return NULL;
196 ss = (sslSocket *)layer->secret;
197 /* Set ss->fd lazily. We can't rely on the value of ss->fd set by
198 * ssl_PushIOLayer because another PR_PushIOLayer call will switch the
199 * contents of the PRFileDesc pointed by ss->fd and the new layer.
200 * See bug 807250.
202 ss->fd = layer;
203 return ss;
206 static sslSocket *
207 ssl_DupSocket(sslSocket *os)
209 sslSocket *ss;
210 SECStatus rv;
212 ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant);
213 if (ss) {
214 ss->opt = os->opt;
215 ss->opt.useSocks = PR_FALSE;
216 ss->vrange = os->vrange;
218 ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID);
219 ss->url = !os->url ? NULL : PORT_Strdup(os->url);
221 ss->ops = os->ops;
222 ss->rTimeout = os->rTimeout;
223 ss->wTimeout = os->wTimeout;
224 ss->cTimeout = os->cTimeout;
225 ss->dbHandle = os->dbHandle;
227 /* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
228 ss->allowedByPolicy = os->allowedByPolicy;
229 ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy;
230 ss->chosenPreference = os->chosenPreference;
231 PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
232 PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, os->ssl3.dtlsSRTPCiphers,
233 sizeof(PRUint16) * os->ssl3.dtlsSRTPCipherCount);
234 ss->ssl3.dtlsSRTPCipherCount = os->ssl3.dtlsSRTPCipherCount;
236 if (os->cipherSpecs) {
237 ss->cipherSpecs = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs);
238 if (ss->cipherSpecs)
239 PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs,
240 os->sizeCipherSpecs);
241 ss->sizeCipherSpecs = os->sizeCipherSpecs;
242 ss->preferredCipher = os->preferredCipher;
243 } else {
244 ss->cipherSpecs = NULL; /* produced lazily */
245 ss->sizeCipherSpecs = 0;
246 ss->preferredCipher = NULL;
248 if (ss->opt.useSecurity) {
249 /* This int should be SSLKEAType, but CC on Irix complains,
250 * during the for loop.
252 int i;
253 sslServerCerts * oc = os->serverCerts;
254 sslServerCerts * sc = ss->serverCerts;
256 for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) {
257 if (oc->serverCert && oc->serverCertChain) {
258 sc->serverCert = CERT_DupCertificate(oc->serverCert);
259 sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
260 if (!sc->serverCertChain)
261 goto loser;
262 } else {
263 sc->serverCert = NULL;
264 sc->serverCertChain = NULL;
266 sc->serverKeyPair = oc->serverKeyPair ?
267 ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL;
268 if (oc->serverKeyPair && !sc->serverKeyPair)
269 goto loser;
270 sc->serverKeyBits = oc->serverKeyBits;
271 ss->certStatusArray[i] = !os->certStatusArray[i] ? NULL :
272 SECITEM_DupArray(NULL, os->certStatusArray[i]);
274 ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL :
275 ssl3_GetKeyPairRef(os->stepDownKeyPair);
276 ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL :
277 ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair);
279 * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL.
280 * XXX We should detect this, and not just march on with NULL pointers.
282 ss->authCertificate = os->authCertificate;
283 ss->authCertificateArg = os->authCertificateArg;
284 ss->getClientAuthData = os->getClientAuthData;
285 ss->getClientAuthDataArg = os->getClientAuthDataArg;
286 #ifdef NSS_PLATFORM_CLIENT_AUTH
287 ss->getPlatformClientAuthData = os->getPlatformClientAuthData;
288 ss->getPlatformClientAuthDataArg = os->getPlatformClientAuthDataArg;
289 #endif
290 ss->sniSocketConfig = os->sniSocketConfig;
291 ss->sniSocketConfigArg = os->sniSocketConfigArg;
292 ss->handleBadCert = os->handleBadCert;
293 ss->badCertArg = os->badCertArg;
294 ss->handshakeCallback = os->handshakeCallback;
295 ss->handshakeCallbackData = os->handshakeCallbackData;
296 ss->canFalseStartCallback = os->canFalseStartCallback;
297 ss->canFalseStartCallbackData = os->canFalseStartCallbackData;
298 ss->pkcs11PinArg = os->pkcs11PinArg;
299 ss->getChannelID = os->getChannelID;
300 ss->getChannelIDArg = os->getChannelIDArg;
302 /* Create security data */
303 rv = ssl_CopySecurityInfo(ss, os);
304 if (rv != SECSuccess) {
305 goto loser;
309 return ss;
311 loser:
312 ssl_FreeSocket(ss);
313 return NULL;
316 static void
317 ssl_DestroyLocks(sslSocket *ss)
319 /* Destroy locks. */
320 if (ss->firstHandshakeLock) {
321 PZ_DestroyMonitor(ss->firstHandshakeLock);
322 ss->firstHandshakeLock = NULL;
324 if (ss->ssl3HandshakeLock) {
325 PZ_DestroyMonitor(ss->ssl3HandshakeLock);
326 ss->ssl3HandshakeLock = NULL;
328 if (ss->specLock) {
329 NSSRWLock_Destroy(ss->specLock);
330 ss->specLock = NULL;
333 if (ss->recvLock) {
334 PZ_DestroyLock(ss->recvLock);
335 ss->recvLock = NULL;
337 if (ss->sendLock) {
338 PZ_DestroyLock(ss->sendLock);
339 ss->sendLock = NULL;
341 if (ss->xmitBufLock) {
342 PZ_DestroyMonitor(ss->xmitBufLock);
343 ss->xmitBufLock = NULL;
345 if (ss->recvBufLock) {
346 PZ_DestroyMonitor(ss->recvBufLock);
347 ss->recvBufLock = NULL;
351 /* Caller holds any relevant locks */
352 static void
353 ssl_DestroySocketContents(sslSocket *ss)
355 /* "i" should be of type SSLKEAType, but CC on IRIX complains during
356 * the for loop.
358 int i;
360 /* Free up socket */
361 ssl_DestroySecurityInfo(&ss->sec);
363 ssl3_DestroySSL3Info(ss);
365 PORT_Free(ss->saveBuf.buf);
366 PORT_Free(ss->pendingBuf.buf);
367 ssl_DestroyGather(&ss->gs);
369 if (ss->peerID != NULL)
370 PORT_Free(ss->peerID);
371 if (ss->url != NULL)
372 PORT_Free((void *)ss->url); /* CONST */
373 if (ss->cipherSpecs) {
374 PORT_Free(ss->cipherSpecs);
375 ss->cipherSpecs = NULL;
376 ss->sizeCipherSpecs = 0;
379 /* Clean up server configuration */
380 for (i=kt_null; i < kt_kea_size; i++) {
381 sslServerCerts * sc = ss->serverCerts + i;
382 if (sc->serverCert != NULL)
383 CERT_DestroyCertificate(sc->serverCert);
384 if (sc->serverCertChain != NULL)
385 CERT_DestroyCertificateList(sc->serverCertChain);
386 if (sc->serverKeyPair != NULL)
387 ssl3_FreeKeyPair(sc->serverKeyPair);
388 if (ss->certStatusArray[i] != NULL) {
389 SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE);
390 ss->certStatusArray[i] = NULL;
393 if (ss->stepDownKeyPair) {
394 ssl3_FreeKeyPair(ss->stepDownKeyPair);
395 ss->stepDownKeyPair = NULL;
397 if (ss->ephemeralECDHKeyPair) {
398 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
399 ss->ephemeralECDHKeyPair = NULL;
401 SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
402 PORT_Assert(!ss->xtnData.sniNameArr);
403 if (ss->xtnData.sniNameArr) {
404 PORT_Free(ss->xtnData.sniNameArr);
405 ss->xtnData.sniNameArr = NULL;
410 * free an sslSocket struct, and all the stuff that hangs off of it
412 void
413 ssl_FreeSocket(sslSocket *ss)
415 /* Get every lock you can imagine!
416 ** Caller already holds these:
417 ** SSL_LOCK_READER(ss);
418 ** SSL_LOCK_WRITER(ss);
420 ssl_Get1stHandshakeLock(ss);
421 ssl_GetRecvBufLock(ss);
422 ssl_GetSSL3HandshakeLock(ss);
423 ssl_GetXmitBufLock(ss);
424 ssl_GetSpecWriteLock(ss);
426 ssl_DestroySocketContents(ss);
428 /* Release all the locks acquired above. */
429 SSL_UNLOCK_READER(ss);
430 SSL_UNLOCK_WRITER(ss);
431 ssl_Release1stHandshakeLock(ss);
432 ssl_ReleaseRecvBufLock(ss);
433 ssl_ReleaseSSL3HandshakeLock(ss);
434 ssl_ReleaseXmitBufLock(ss);
435 ssl_ReleaseSpecWriteLock(ss);
437 ssl_DestroyLocks(ss);
439 #ifdef DEBUG
440 PORT_Memset(ss, 0x1f, sizeof *ss);
441 #endif
442 PORT_Free(ss);
443 return;
446 /************************************************************************/
447 SECStatus
448 ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
450 PRFileDesc * osfd = ss->fd->lower;
451 SECStatus rv = SECFailure;
452 PRSocketOptionData opt;
454 opt.option = PR_SockOpt_NoDelay;
455 opt.value.no_delay = (PRBool)!enabled;
457 if (osfd->methods->setsocketoption) {
458 rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt);
459 } else {
460 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
463 return rv;
466 static void
467 ssl_ChooseOps(sslSocket *ss)
469 ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
472 /* Called from SSL_Enable (immediately below) */
473 static SECStatus
474 PrepareSocket(sslSocket *ss)
476 SECStatus rv = SECSuccess;
478 ssl_ChooseOps(ss);
479 return rv;
482 SECStatus
483 SSL_Enable(PRFileDesc *fd, int which, PRBool on)
485 return SSL_OptionSet(fd, which, on);
488 #ifndef NO_PKCS11_BYPASS
489 static const PRCallOnceType pristineCallOnce;
490 static PRCallOnceType setupBypassOnce;
492 static SECStatus SSL_BypassShutdown(void* appData, void* nssData)
494 /* unload freeBL shared library from memory */
495 BL_Unload();
496 setupBypassOnce = pristineCallOnce;
497 return SECSuccess;
500 static PRStatus SSL_BypassRegisterShutdown(void)
502 SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL);
503 PORT_Assert(SECSuccess == rv);
504 return SECSuccess == rv ? PR_SUCCESS : PR_FAILURE;
506 #endif
508 static PRStatus SSL_BypassSetup(void)
510 #ifdef NO_PKCS11_BYPASS
511 /* Guarantee binary compatibility */
512 return PR_SUCCESS;
513 #else
514 return PR_CallOnce(&setupBypassOnce, &SSL_BypassRegisterShutdown);
515 #endif
518 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in
519 * ssl.h in the section "SSL version range setting API".
521 static void
522 ssl_EnableTLS(SSLVersionRange *vrange, PRBool on)
524 if (SSL3_ALL_VERSIONS_DISABLED(vrange)) {
525 if (on) {
526 vrange->min = SSL_LIBRARY_VERSION_TLS_1_0;
527 vrange->max = SSL_LIBRARY_VERSION_TLS_1_0;
528 } /* else don't change anything */
529 return;
532 if (on) {
533 /* Expand the range of enabled version to include TLS 1.0 */
534 vrange->min = PR_MIN(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
535 vrange->max = PR_MAX(vrange->max, SSL_LIBRARY_VERSION_TLS_1_0);
536 } else {
537 /* Disable all TLS versions, leaving only SSL 3.0 if it was enabled */
538 if (vrange->min == SSL_LIBRARY_VERSION_3_0) {
539 vrange->max = SSL_LIBRARY_VERSION_3_0;
540 } else {
541 /* Only TLS was enabled, so now no versions are. */
542 vrange->min = SSL_LIBRARY_VERSION_NONE;
543 vrange->max = SSL_LIBRARY_VERSION_NONE;
548 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_SSL3, on) described in
549 * ssl.h in the section "SSL version range setting API".
551 static void
552 ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on)
554 if (SSL3_ALL_VERSIONS_DISABLED(vrange)) {
555 if (on) {
556 vrange->min = SSL_LIBRARY_VERSION_3_0;
557 vrange->max = SSL_LIBRARY_VERSION_3_0;
558 } /* else don't change anything */
559 return;
562 if (on) {
563 /* Expand the range of enabled versions to include SSL 3.0. We know
564 * SSL 3.0 or some version of TLS is already enabled at this point, so
565 * we don't need to change vrange->max.
567 vrange->min = SSL_LIBRARY_VERSION_3_0;
568 } else {
569 /* Disable SSL 3.0, leaving TLS unaffected. */
570 if (vrange->max > SSL_LIBRARY_VERSION_3_0) {
571 vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
572 } else {
573 /* Only SSL 3.0 was enabled, so now no versions are. */
574 vrange->min = SSL_LIBRARY_VERSION_NONE;
575 vrange->max = SSL_LIBRARY_VERSION_NONE;
580 SECStatus
581 SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on)
583 sslSocket *ss = ssl_FindSocket(fd);
584 SECStatus rv = SECSuccess;
585 PRBool holdingLocks;
587 if (!ss) {
588 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
589 return SECFailure;
592 holdingLocks = (!ss->opt.noLocks);
593 ssl_Get1stHandshakeLock(ss);
594 ssl_GetSSL3HandshakeLock(ss);
596 switch (which) {
597 case SSL_SOCKS:
598 ss->opt.useSocks = PR_FALSE;
599 rv = PrepareSocket(ss);
600 if (on) {
601 PORT_SetError(SEC_ERROR_INVALID_ARGS);
602 rv = SECFailure;
604 break;
606 case SSL_SECURITY:
607 ss->opt.useSecurity = on;
608 rv = PrepareSocket(ss);
609 break;
611 case SSL_REQUEST_CERTIFICATE:
612 ss->opt.requestCertificate = on;
613 break;
615 case SSL_REQUIRE_CERTIFICATE:
616 ss->opt.requireCertificate = on;
617 break;
619 case SSL_HANDSHAKE_AS_CLIENT:
620 if ( ss->opt.handshakeAsServer && on ) {
621 PORT_SetError(SEC_ERROR_INVALID_ARGS);
622 rv = SECFailure;
623 break;
625 ss->opt.handshakeAsClient = on;
626 break;
628 case SSL_HANDSHAKE_AS_SERVER:
629 if ( ss->opt.handshakeAsClient && on ) {
630 PORT_SetError(SEC_ERROR_INVALID_ARGS);
631 rv = SECFailure;
632 break;
634 ss->opt.handshakeAsServer = on;
635 break;
637 case SSL_ENABLE_TLS:
638 if (IS_DTLS(ss)) {
639 if (on) {
640 PORT_SetError(SEC_ERROR_INVALID_ARGS);
641 rv = SECFailure; /* not allowed */
643 break;
645 ssl_EnableTLS(&ss->vrange, on);
646 ss->preferredCipher = NULL;
647 if (ss->cipherSpecs) {
648 PORT_Free(ss->cipherSpecs);
649 ss->cipherSpecs = NULL;
650 ss->sizeCipherSpecs = 0;
652 break;
654 case SSL_ENABLE_SSL3:
655 if (IS_DTLS(ss)) {
656 if (on) {
657 PORT_SetError(SEC_ERROR_INVALID_ARGS);
658 rv = SECFailure; /* not allowed */
660 break;
662 ssl_EnableSSL3(&ss->vrange, on);
663 ss->preferredCipher = NULL;
664 if (ss->cipherSpecs) {
665 PORT_Free(ss->cipherSpecs);
666 ss->cipherSpecs = NULL;
667 ss->sizeCipherSpecs = 0;
669 break;
671 case SSL_ENABLE_SSL2:
672 if (IS_DTLS(ss)) {
673 if (on) {
674 PORT_SetError(SEC_ERROR_INVALID_ARGS);
675 rv = SECFailure; /* not allowed */
677 break;
679 ss->opt.enableSSL2 = on;
680 if (on) {
681 ss->opt.v2CompatibleHello = on;
683 ss->preferredCipher = NULL;
684 if (ss->cipherSpecs) {
685 PORT_Free(ss->cipherSpecs);
686 ss->cipherSpecs = NULL;
687 ss->sizeCipherSpecs = 0;
689 break;
691 case SSL_NO_CACHE:
692 ss->opt.noCache = on;
693 break;
695 case SSL_ENABLE_FDX:
696 if (on && ss->opt.noLocks) {
697 PORT_SetError(SEC_ERROR_INVALID_ARGS);
698 rv = SECFailure;
700 ss->opt.fdx = on;
701 break;
703 case SSL_V2_COMPATIBLE_HELLO:
704 if (IS_DTLS(ss)) {
705 if (on) {
706 PORT_SetError(SEC_ERROR_INVALID_ARGS);
707 rv = SECFailure; /* not allowed */
709 break;
711 ss->opt.v2CompatibleHello = on;
712 if (!on) {
713 ss->opt.enableSSL2 = on;
715 break;
717 case SSL_ROLLBACK_DETECTION:
718 ss->opt.detectRollBack = on;
719 break;
721 case SSL_NO_STEP_DOWN:
722 ss->opt.noStepDown = on;
723 if (on)
724 SSL_DisableExportCipherSuites(fd);
725 break;
727 case SSL_BYPASS_PKCS11:
728 if (ss->handshakeBegun) {
729 PORT_SetError(PR_INVALID_STATE_ERROR);
730 rv = SECFailure;
731 } else {
732 if (PR_FALSE != on) {
733 if (PR_SUCCESS == SSL_BypassSetup() ) {
734 #ifdef NO_PKCS11_BYPASS
735 ss->opt.bypassPKCS11 = PR_FALSE;
736 #else
737 ss->opt.bypassPKCS11 = on;
738 #endif
739 } else {
740 rv = SECFailure;
742 } else {
743 ss->opt.bypassPKCS11 = PR_FALSE;
746 break;
748 case SSL_NO_LOCKS:
749 if (on && ss->opt.fdx) {
750 PORT_SetError(SEC_ERROR_INVALID_ARGS);
751 rv = SECFailure;
753 if (on && ssl_force_locks)
754 on = PR_FALSE; /* silent override */
755 ss->opt.noLocks = on;
756 if (on) {
757 locksEverDisabled = PR_TRUE;
758 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
759 } else if (!holdingLocks) {
760 rv = ssl_MakeLocks(ss);
761 if (rv != SECSuccess) {
762 ss->opt.noLocks = PR_TRUE;
765 break;
767 case SSL_ENABLE_SESSION_TICKETS:
768 ss->opt.enableSessionTickets = on;
769 break;
771 case SSL_ENABLE_DEFLATE:
772 ss->opt.enableDeflate = on;
773 break;
775 case SSL_ENABLE_RENEGOTIATION:
776 ss->opt.enableRenegotiation = on;
777 break;
779 case SSL_REQUIRE_SAFE_NEGOTIATION:
780 ss->opt.requireSafeNegotiation = on;
781 break;
783 case SSL_ENABLE_FALSE_START:
784 ss->opt.enableFalseStart = on;
785 break;
787 case SSL_CBC_RANDOM_IV:
788 ss->opt.cbcRandomIV = on;
789 break;
791 case SSL_ENABLE_OCSP_STAPLING:
792 ss->opt.enableOCSPStapling = on;
793 break;
795 case SSL_ENABLE_NPN:
796 ss->opt.enableNPN = on;
797 break;
799 case SSL_ENABLE_ALPN:
800 ss->opt.enableALPN = on;
801 break;
803 case SSL_REUSE_SERVER_ECDHE_KEY:
804 ss->opt.reuseServerECDHEKey = on;
805 break;
807 case SSL_ENABLE_FALLBACK_SCSV:
808 ss->opt.enableFallbackSCSV = on;
809 break;
811 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
812 ss->opt.enableSignedCertTimestamps = on;
813 break;
815 default:
816 PORT_SetError(SEC_ERROR_INVALID_ARGS);
817 rv = SECFailure;
820 /* We can't use the macros for releasing the locks here,
821 * because ss->opt.noLocks might have changed just above.
822 * We must release these locks (monitors) here, if we aquired them above,
823 * regardless of the current value of ss->opt.noLocks.
825 if (holdingLocks) {
826 PZ_ExitMonitor((ss)->ssl3HandshakeLock);
827 PZ_ExitMonitor((ss)->firstHandshakeLock);
830 return rv;
833 SECStatus
834 SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn)
836 sslSocket *ss = ssl_FindSocket(fd);
837 SECStatus rv = SECSuccess;
838 PRBool on = PR_FALSE;
840 if (!pOn) {
841 PORT_SetError(SEC_ERROR_INVALID_ARGS);
842 return SECFailure;
844 if (!ss) {
845 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
846 *pOn = PR_FALSE;
847 return SECFailure;
850 ssl_Get1stHandshakeLock(ss);
851 ssl_GetSSL3HandshakeLock(ss);
853 switch (which) {
854 case SSL_SOCKS: on = PR_FALSE; break;
855 case SSL_SECURITY: on = ss->opt.useSecurity; break;
856 case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break;
857 case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break;
858 case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient; break;
859 case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer; break;
860 case SSL_ENABLE_TLS:
861 on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0;
862 break;
863 case SSL_ENABLE_SSL3:
864 on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0;
865 break;
866 case SSL_ENABLE_SSL2: on = ss->opt.enableSSL2; break;
867 case SSL_NO_CACHE: on = ss->opt.noCache; break;
868 case SSL_ENABLE_FDX: on = ss->opt.fdx; break;
869 case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello; break;
870 case SSL_ROLLBACK_DETECTION: on = ss->opt.detectRollBack; break;
871 case SSL_NO_STEP_DOWN: on = ss->opt.noStepDown; break;
872 case SSL_BYPASS_PKCS11: on = ss->opt.bypassPKCS11; break;
873 case SSL_NO_LOCKS: on = ss->opt.noLocks; break;
874 case SSL_ENABLE_SESSION_TICKETS:
875 on = ss->opt.enableSessionTickets;
876 break;
877 case SSL_ENABLE_DEFLATE: on = ss->opt.enableDeflate; break;
878 case SSL_ENABLE_RENEGOTIATION:
879 on = ss->opt.enableRenegotiation; break;
880 case SSL_REQUIRE_SAFE_NEGOTIATION:
881 on = ss->opt.requireSafeNegotiation; break;
882 case SSL_ENABLE_FALSE_START: on = ss->opt.enableFalseStart; break;
883 case SSL_CBC_RANDOM_IV: on = ss->opt.cbcRandomIV; break;
884 case SSL_ENABLE_OCSP_STAPLING: on = ss->opt.enableOCSPStapling; break;
885 case SSL_ENABLE_NPN: on = ss->opt.enableNPN; break;
886 case SSL_ENABLE_ALPN: on = ss->opt.enableALPN; break;
887 case SSL_REUSE_SERVER_ECDHE_KEY:
888 on = ss->opt.reuseServerECDHEKey; break;
889 case SSL_ENABLE_FALLBACK_SCSV: on = ss->opt.enableFallbackSCSV; break;
890 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
891 on = ss->opt.enableSignedCertTimestamps;
892 break;
894 default:
895 PORT_SetError(SEC_ERROR_INVALID_ARGS);
896 rv = SECFailure;
899 ssl_ReleaseSSL3HandshakeLock(ss);
900 ssl_Release1stHandshakeLock(ss);
902 *pOn = on;
903 return rv;
906 SECStatus
907 SSL_OptionGetDefault(PRInt32 which, PRBool *pOn)
909 SECStatus rv = SECSuccess;
910 PRBool on = PR_FALSE;
912 if (!pOn) {
913 PORT_SetError(SEC_ERROR_INVALID_ARGS);
914 return SECFailure;
917 ssl_SetDefaultsFromEnvironment();
919 switch (which) {
920 case SSL_SOCKS: on = PR_FALSE; break;
921 case SSL_SECURITY: on = ssl_defaults.useSecurity; break;
922 case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break;
923 case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break;
924 case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient; break;
925 case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer; break;
926 case SSL_ENABLE_TLS:
927 on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0;
928 break;
929 case SSL_ENABLE_SSL3:
930 on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0;
931 break;
932 case SSL_ENABLE_SSL2: on = ssl_defaults.enableSSL2; break;
933 case SSL_NO_CACHE: on = ssl_defaults.noCache; break;
934 case SSL_ENABLE_FDX: on = ssl_defaults.fdx; break;
935 case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello; break;
936 case SSL_ROLLBACK_DETECTION: on = ssl_defaults.detectRollBack; break;
937 case SSL_NO_STEP_DOWN: on = ssl_defaults.noStepDown; break;
938 case SSL_BYPASS_PKCS11: on = ssl_defaults.bypassPKCS11; break;
939 case SSL_NO_LOCKS: on = ssl_defaults.noLocks; break;
940 case SSL_ENABLE_SESSION_TICKETS:
941 on = ssl_defaults.enableSessionTickets;
942 break;
943 case SSL_ENABLE_DEFLATE: on = ssl_defaults.enableDeflate; break;
944 case SSL_ENABLE_RENEGOTIATION:
945 on = ssl_defaults.enableRenegotiation; break;
946 case SSL_REQUIRE_SAFE_NEGOTIATION:
947 on = ssl_defaults.requireSafeNegotiation;
948 break;
949 case SSL_ENABLE_FALSE_START: on = ssl_defaults.enableFalseStart; break;
950 case SSL_CBC_RANDOM_IV: on = ssl_defaults.cbcRandomIV; break;
951 case SSL_ENABLE_OCSP_STAPLING:
952 on = ssl_defaults.enableOCSPStapling;
953 break;
954 case SSL_ENABLE_NPN: on = ssl_defaults.enableNPN; break;
955 case SSL_ENABLE_ALPN: on = ssl_defaults.enableALPN; break;
956 case SSL_REUSE_SERVER_ECDHE_KEY:
957 on = ssl_defaults.reuseServerECDHEKey;
958 break;
959 case SSL_ENABLE_FALLBACK_SCSV:
960 on = ssl_defaults.enableFallbackSCSV;
961 break;
962 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
963 on = ssl_defaults.enableSignedCertTimestamps;
964 break;
966 default:
967 PORT_SetError(SEC_ERROR_INVALID_ARGS);
968 rv = SECFailure;
971 *pOn = on;
972 return rv;
975 /* XXX Use Global Lock to protect this stuff. */
976 SECStatus
977 SSL_EnableDefault(int which, PRBool on)
979 return SSL_OptionSetDefault(which, on);
982 SECStatus
983 SSL_OptionSetDefault(PRInt32 which, PRBool on)
985 SECStatus status = ssl_Init();
987 if (status != SECSuccess) {
988 return status;
991 ssl_SetDefaultsFromEnvironment();
993 switch (which) {
994 case SSL_SOCKS:
995 ssl_defaults.useSocks = PR_FALSE;
996 if (on) {
997 PORT_SetError(SEC_ERROR_INVALID_ARGS);
998 return SECFailure;
1000 break;
1002 case SSL_SECURITY:
1003 ssl_defaults.useSecurity = on;
1004 break;
1006 case SSL_REQUEST_CERTIFICATE:
1007 ssl_defaults.requestCertificate = on;
1008 break;
1010 case SSL_REQUIRE_CERTIFICATE:
1011 ssl_defaults.requireCertificate = on;
1012 break;
1014 case SSL_HANDSHAKE_AS_CLIENT:
1015 if ( ssl_defaults.handshakeAsServer && on ) {
1016 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1017 return SECFailure;
1019 ssl_defaults.handshakeAsClient = on;
1020 break;
1022 case SSL_HANDSHAKE_AS_SERVER:
1023 if ( ssl_defaults.handshakeAsClient && on ) {
1024 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1025 return SECFailure;
1027 ssl_defaults.handshakeAsServer = on;
1028 break;
1030 case SSL_ENABLE_TLS:
1031 ssl_EnableTLS(&versions_defaults_stream, on);
1032 break;
1034 case SSL_ENABLE_SSL3:
1035 ssl_EnableSSL3(&versions_defaults_stream, on);
1036 break;
1038 case SSL_ENABLE_SSL2:
1039 ssl_defaults.enableSSL2 = on;
1040 if (on) {
1041 ssl_defaults.v2CompatibleHello = on;
1043 break;
1045 case SSL_NO_CACHE:
1046 ssl_defaults.noCache = on;
1047 break;
1049 case SSL_ENABLE_FDX:
1050 if (on && ssl_defaults.noLocks) {
1051 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1052 return SECFailure;
1054 ssl_defaults.fdx = on;
1055 break;
1057 case SSL_V2_COMPATIBLE_HELLO:
1058 ssl_defaults.v2CompatibleHello = on;
1059 if (!on) {
1060 ssl_defaults.enableSSL2 = on;
1062 break;
1064 case SSL_ROLLBACK_DETECTION:
1065 ssl_defaults.detectRollBack = on;
1066 break;
1068 case SSL_NO_STEP_DOWN:
1069 ssl_defaults.noStepDown = on;
1070 if (on)
1071 SSL_DisableDefaultExportCipherSuites();
1072 break;
1074 case SSL_BYPASS_PKCS11:
1075 if (PR_FALSE != on) {
1076 if (PR_SUCCESS == SSL_BypassSetup()) {
1077 #ifdef NO_PKCS11_BYPASS
1078 ssl_defaults.bypassPKCS11 = PR_FALSE;
1079 #else
1080 ssl_defaults.bypassPKCS11 = on;
1081 #endif
1082 } else {
1083 return SECFailure;
1085 } else {
1086 ssl_defaults.bypassPKCS11 = PR_FALSE;
1088 break;
1090 case SSL_NO_LOCKS:
1091 if (on && ssl_defaults.fdx) {
1092 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1093 return SECFailure;
1095 if (on && ssl_force_locks)
1096 on = PR_FALSE; /* silent override */
1097 ssl_defaults.noLocks = on;
1098 if (on) {
1099 locksEverDisabled = PR_TRUE;
1100 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
1102 break;
1104 case SSL_ENABLE_SESSION_TICKETS:
1105 ssl_defaults.enableSessionTickets = on;
1106 break;
1108 case SSL_ENABLE_DEFLATE:
1109 ssl_defaults.enableDeflate = on;
1110 break;
1112 case SSL_ENABLE_RENEGOTIATION:
1113 ssl_defaults.enableRenegotiation = on;
1114 break;
1116 case SSL_REQUIRE_SAFE_NEGOTIATION:
1117 ssl_defaults.requireSafeNegotiation = on;
1118 break;
1120 case SSL_ENABLE_FALSE_START:
1121 ssl_defaults.enableFalseStart = on;
1122 break;
1124 case SSL_CBC_RANDOM_IV:
1125 ssl_defaults.cbcRandomIV = on;
1126 break;
1128 case SSL_ENABLE_OCSP_STAPLING:
1129 ssl_defaults.enableOCSPStapling = on;
1130 break;
1132 case SSL_ENABLE_NPN:
1133 ssl_defaults.enableNPN = on;
1134 break;
1136 case SSL_ENABLE_ALPN:
1137 ssl_defaults.enableALPN = on;
1138 break;
1140 case SSL_REUSE_SERVER_ECDHE_KEY:
1141 ssl_defaults.reuseServerECDHEKey = on;
1142 break;
1144 case SSL_ENABLE_FALLBACK_SCSV:
1145 ssl_defaults.enableFallbackSCSV = on;
1146 break;
1148 case SSL_ENABLE_SIGNED_CERT_TIMESTAMPS:
1149 ssl_defaults.enableSignedCertTimestamps = on;
1150 break;
1152 default:
1153 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1154 return SECFailure;
1156 return SECSuccess;
1159 /* function tells us if the cipher suite is one that we no longer support. */
1160 static PRBool
1161 ssl_IsRemovedCipherSuite(PRInt32 suite)
1163 switch (suite) {
1164 case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
1165 case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
1166 case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
1167 return PR_TRUE;
1168 default:
1169 return PR_FALSE;
1173 /* Part of the public NSS API.
1174 * Since this is a global (not per-socket) setting, we cannot use the
1175 * HandshakeLock to protect this. Probably want a global lock.
1177 SECStatus
1178 SSL_SetPolicy(long which, int policy)
1180 if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1181 /* one of the two old FIPS ciphers */
1182 if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1183 which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1184 else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1185 which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1187 if (ssl_IsRemovedCipherSuite(which))
1188 return SECSuccess;
1189 return SSL_CipherPolicySet(which, policy);
1192 SECStatus
1193 SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
1195 SECStatus rv = ssl_Init();
1197 if (rv != SECSuccess) {
1198 return rv;
1201 if (ssl_IsRemovedCipherSuite(which)) {
1202 rv = SECSuccess;
1203 } else if (SSL_IS_SSL2_CIPHER(which)) {
1204 rv = ssl2_SetPolicy(which, policy);
1205 } else {
1206 rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
1208 return rv;
1211 SECStatus
1212 SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
1214 SECStatus rv;
1216 if (!oPolicy) {
1217 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1218 return SECFailure;
1220 if (ssl_IsRemovedCipherSuite(which)) {
1221 *oPolicy = SSL_NOT_ALLOWED;
1222 rv = SECSuccess;
1223 } else if (SSL_IS_SSL2_CIPHER(which)) {
1224 rv = ssl2_GetPolicy(which, oPolicy);
1225 } else {
1226 rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
1228 return rv;
1231 /* Part of the public NSS API.
1232 * Since this is a global (not per-socket) setting, we cannot use the
1233 * HandshakeLock to protect this. Probably want a global lock.
1234 * These changes have no effect on any sslSockets already created.
1236 SECStatus
1237 SSL_EnableCipher(long which, PRBool enabled)
1239 if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1240 /* one of the two old FIPS ciphers */
1241 if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1242 which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1243 else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1244 which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1246 if (ssl_IsRemovedCipherSuite(which))
1247 return SECSuccess;
1248 return SSL_CipherPrefSetDefault(which, enabled);
1251 SECStatus
1252 SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
1254 SECStatus rv = ssl_Init();
1256 if (rv != SECSuccess) {
1257 return rv;
1260 if (ssl_IsRemovedCipherSuite(which))
1261 return SECSuccess;
1262 if (enabled && ssl_defaults.noStepDown && SSL_IsExportCipherSuite(which)) {
1263 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1264 return SECFailure;
1266 if (SSL_IS_SSL2_CIPHER(which)) {
1267 rv = ssl2_CipherPrefSetDefault(which, enabled);
1268 } else {
1269 rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
1271 return rv;
1274 SECStatus
1275 SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
1277 SECStatus rv;
1279 if (!enabled) {
1280 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1281 return SECFailure;
1283 if (ssl_IsRemovedCipherSuite(which)) {
1284 *enabled = PR_FALSE;
1285 rv = SECSuccess;
1286 } else if (SSL_IS_SSL2_CIPHER(which)) {
1287 rv = ssl2_CipherPrefGetDefault(which, enabled);
1288 } else {
1289 rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
1291 return rv;
1294 SECStatus
1295 SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
1297 SECStatus rv;
1298 sslSocket *ss = ssl_FindSocket(fd);
1300 if (!ss) {
1301 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
1302 return SECFailure;
1304 if (ssl_IsRemovedCipherSuite(which))
1305 return SECSuccess;
1306 if (enabled && ss->opt.noStepDown && SSL_IsExportCipherSuite(which)) {
1307 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1308 return SECFailure;
1310 if (SSL_IS_SSL2_CIPHER(which)) {
1311 rv = ssl2_CipherPrefSet(ss, which, enabled);
1312 } else {
1313 rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
1315 return rv;
1318 SECStatus
1319 SSL_CipherOrderSet(PRFileDesc *fd, const PRUint16 *ciphers, unsigned int len)
1321 sslSocket *ss = ssl_FindSocket(fd);
1323 if (!ss) {
1324 SSL_DBG(("%d: SSL[%d]: bad socket in CipherOrderSet", SSL_GETPID(),
1325 fd));
1326 return SECFailure;
1328 return ssl3_CipherOrderSet(ss, ciphers, len);
1331 SECStatus
1332 SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
1334 SECStatus rv;
1335 sslSocket *ss = ssl_FindSocket(fd);
1337 if (!enabled) {
1338 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1339 return SECFailure;
1341 if (!ss) {
1342 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
1343 *enabled = PR_FALSE;
1344 return SECFailure;
1346 if (ssl_IsRemovedCipherSuite(which)) {
1347 *enabled = PR_FALSE;
1348 rv = SECSuccess;
1349 } else if (SSL_IS_SSL2_CIPHER(which)) {
1350 rv = ssl2_CipherPrefGet(ss, which, enabled);
1351 } else {
1352 rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
1354 return rv;
1357 SECStatus
1358 NSS_SetDomesticPolicy(void)
1360 SECStatus status = SECSuccess;
1361 const PRUint16 *cipher;
1363 for (cipher = SSL_ImplementedCiphers; *cipher != 0; ++cipher) {
1364 status = SSL_SetPolicy(*cipher, SSL_ALLOWED);
1365 if (status != SECSuccess)
1366 break;
1368 return status;
1371 SECStatus
1372 NSS_SetExportPolicy(void)
1374 return NSS_SetDomesticPolicy();
1377 SECStatus
1378 NSS_SetFrancePolicy(void)
1380 return NSS_SetDomesticPolicy();
1383 SECStatus
1384 SSL_GetChannelBinding(PRFileDesc *fd,
1385 SSLChannelBindingType binding_type,
1386 unsigned char *out,
1387 unsigned int *outLen,
1388 unsigned int outLenMax) {
1389 sslSocket *ss = ssl_FindSocket(fd);
1391 if (!ss) {
1392 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelBinding",
1393 SSL_GETPID(), fd));
1394 return SECFailure;
1397 if (binding_type != SSL_CHANNEL_BINDING_TLS_UNIQUE) {
1398 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
1399 return SECFailure;
1402 return ssl3_GetTLSUniqueChannelBinding(ss, out, outLen, outLenMax);
1406 /* LOCKS ??? XXX */
1407 static PRFileDesc *
1408 ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant)
1410 sslSocket * ns = NULL;
1411 PRStatus rv;
1412 PRNetAddr addr;
1413 SECStatus status = ssl_Init();
1415 if (status != SECSuccess) {
1416 return NULL;
1419 if (model == NULL) {
1420 /* Just create a default socket if we're given NULL for the model */
1421 ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks), variant);
1422 } else {
1423 sslSocket * ss = ssl_FindSocket(model);
1424 if (ss == NULL || ss->protocolVariant != variant) {
1425 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
1426 SSL_GETPID(), model));
1427 return NULL;
1429 ns = ssl_DupSocket(ss);
1431 if (ns == NULL)
1432 return NULL;
1434 rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
1435 if (rv != PR_SUCCESS) {
1436 ssl_FreeSocket(ns);
1437 SET_ERROR_CODE
1438 return NULL;
1440 #if defined(DEBUG) || defined(FORCE_PR_ASSERT)
1442 sslSocket * ss = ssl_FindSocket(fd);
1443 PORT_Assert(ss == ns);
1445 #endif
1446 ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
1447 return fd;
1450 PRFileDesc *
1451 SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
1453 return ssl_ImportFD(model, fd, ssl_variant_stream);
1456 PRFileDesc *
1457 DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd)
1459 return ssl_ImportFD(model, fd, ssl_variant_datagram);
1462 /* SSL_SetNextProtoCallback is used to select an application protocol
1463 * for ALPN and NPN. For ALPN, this runs on the server; for NPN it
1464 * runs on the client. */
1465 /* Note: The ALPN version doesn't allow for the use of a default, setting a
1466 * status of SSL_NEXT_PROTO_NO_OVERLAP is treated as a failure. */
1467 SECStatus
1468 SSL_SetNextProtoCallback(PRFileDesc *fd, SSLNextProtoCallback callback,
1469 void *arg)
1471 sslSocket *ss = ssl_FindSocket(fd);
1473 if (!ss) {
1474 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoCallback", SSL_GETPID(),
1475 fd));
1476 return SECFailure;
1479 ssl_GetSSL3HandshakeLock(ss);
1480 ss->nextProtoCallback = callback;
1481 ss->nextProtoArg = arg;
1482 ssl_ReleaseSSL3HandshakeLock(ss);
1484 return SECSuccess;
1487 /* ssl_NextProtoNegoCallback is set as an ALPN/NPN callback when
1488 * SSL_SetNextProtoNego is used.
1490 static SECStatus
1491 ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
1492 const unsigned char *protos, unsigned int protos_len,
1493 unsigned char *protoOut, unsigned int *protoOutLen,
1494 unsigned int protoMaxLen)
1496 unsigned int i, j;
1497 const unsigned char *result;
1498 sslSocket *ss = ssl_FindSocket(fd);
1500 if (!ss) {
1501 SSL_DBG(("%d: SSL[%d]: bad socket in ssl_NextProtoNegoCallback",
1502 SSL_GETPID(), fd));
1503 return SECFailure;
1506 /* For each protocol in server preference, see if we support it. */
1507 for (i = 0; i < protos_len; ) {
1508 for (j = 0; j < ss->opt.nextProtoNego.len; ) {
1509 if (protos[i] == ss->opt.nextProtoNego.data[j] &&
1510 PORT_Memcmp(&protos[i+1], &ss->opt.nextProtoNego.data[j+1],
1511 protos[i]) == 0) {
1512 /* We found a match. */
1513 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
1514 result = &protos[i];
1515 goto found;
1517 j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
1519 i += 1 + (unsigned int)protos[i];
1522 /* The other side supports the extension, and either doesn't have any
1523 * protocols configured, or none of its options match ours. In this case we
1524 * request our favoured protocol. */
1525 /* This will be treated as a failure for ALPN. */
1526 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP;
1527 result = ss->opt.nextProtoNego.data;
1529 found:
1530 if (protoMaxLen < result[0]) {
1531 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1532 return SECFailure;
1534 memcpy(protoOut, result + 1, result[0]);
1535 *protoOutLen = result[0];
1536 return SECSuccess;
1539 SECStatus
1540 SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
1541 unsigned int length)
1543 sslSocket *ss;
1544 SECStatus rv;
1545 SECItem dataItem = { siBuffer, (unsigned char *) data, length };
1547 ss = ssl_FindSocket(fd);
1548 if (!ss) {
1549 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego",
1550 SSL_GETPID(), fd));
1551 return SECFailure;
1554 if (ssl3_ValidateNextProtoNego(data, length) != SECSuccess)
1555 return SECFailure;
1557 ssl_GetSSL3HandshakeLock(ss);
1558 SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
1559 rv = SECITEM_CopyItem(NULL, &ss->opt.nextProtoNego, &dataItem);
1560 ssl_ReleaseSSL3HandshakeLock(ss);
1562 if (rv != SECSuccess)
1563 return rv;
1565 return SSL_SetNextProtoCallback(fd, ssl_NextProtoNegoCallback, NULL);
1568 SECStatus
1569 SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf,
1570 unsigned int *bufLen, unsigned int bufLenMax)
1572 sslSocket *ss = ssl_FindSocket(fd);
1574 if (!ss) {
1575 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNextProto", SSL_GETPID(),
1576 fd));
1577 return SECFailure;
1580 if (!state || !buf || !bufLen) {
1581 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1582 return SECFailure;
1585 *state = ss->ssl3.nextProtoState;
1587 if (ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
1588 ss->ssl3.nextProto.data) {
1589 if (ss->ssl3.nextProto.len > bufLenMax) {
1590 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1591 return SECFailure;
1593 PORT_Memcpy(buf, ss->ssl3.nextProto.data, ss->ssl3.nextProto.len);
1594 *bufLen = ss->ssl3.nextProto.len;
1595 } else {
1596 *bufLen = 0;
1599 return SECSuccess;
1602 SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd,
1603 const PRUint16 *ciphers,
1604 unsigned int numCiphers)
1606 sslSocket *ss;
1607 unsigned int i;
1609 ss = ssl_FindSocket(fd);
1610 if (!ss || !IS_DTLS(ss)) {
1611 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSRTPCiphers",
1612 SSL_GETPID(), fd));
1613 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1614 return SECFailure;
1617 if (numCiphers > MAX_DTLS_SRTP_CIPHER_SUITES) {
1618 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1619 return SECFailure;
1622 ss->ssl3.dtlsSRTPCipherCount = 0;
1623 for (i = 0; i < numCiphers; i++) {
1624 const PRUint16 *srtpCipher = srtpCiphers;
1626 while (*srtpCipher) {
1627 if (ciphers[i] == *srtpCipher)
1628 break;
1629 srtpCipher++;
1631 if (*srtpCipher) {
1632 ss->ssl3.dtlsSRTPCiphers[ss->ssl3.dtlsSRTPCipherCount++] =
1633 ciphers[i];
1634 } else {
1635 SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher "
1636 "suite specified: 0x%04hx", SSL_GETPID(), fd,
1637 ciphers[i]));
1641 if (ss->ssl3.dtlsSRTPCipherCount == 0) {
1642 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1643 return SECFailure;
1646 return SECSuccess;
1649 SECStatus
1650 SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher)
1652 sslSocket * ss;
1654 ss = ssl_FindSocket(fd);
1655 if (!ss) {
1656 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetSRTPCipher",
1657 SSL_GETPID(), fd));
1658 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1659 return SECFailure;
1662 if (!ss->ssl3.dtlsSRTPCipherSuite) {
1663 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1664 return SECFailure;
1667 *cipher = ss->ssl3.dtlsSRTPCipherSuite;
1668 return SECSuccess;
1671 PRFileDesc *
1672 SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd)
1674 sslSocket * sm = NULL, *ss = NULL;
1675 int i;
1676 sslServerCerts * mc = NULL;
1677 sslServerCerts * sc = NULL;
1679 if (model == NULL) {
1680 PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
1681 return NULL;
1683 sm = ssl_FindSocket(model);
1684 if (sm == NULL) {
1685 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ReconfigFD",
1686 SSL_GETPID(), model));
1687 return NULL;
1689 ss = ssl_FindSocket(fd);
1690 PORT_Assert(ss);
1691 if (ss == NULL) {
1692 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1693 return NULL;
1696 ss->opt = sm->opt;
1697 ss->vrange = sm->vrange;
1698 PORT_Memcpy(ss->cipherSuites, sm->cipherSuites, sizeof sm->cipherSuites);
1699 PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, sm->ssl3.dtlsSRTPCiphers,
1700 sizeof(PRUint16) * sm->ssl3.dtlsSRTPCipherCount);
1701 ss->ssl3.dtlsSRTPCipherCount = sm->ssl3.dtlsSRTPCipherCount;
1703 if (!ss->opt.useSecurity) {
1704 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1705 return NULL;
1707 /* This int should be SSLKEAType, but CC on Irix complains,
1708 * during the for loop.
1710 for (i=kt_null; i < kt_kea_size; i++) {
1711 mc = &(sm->serverCerts[i]);
1712 sc = &(ss->serverCerts[i]);
1713 if (mc->serverCert && mc->serverCertChain) {
1714 if (sc->serverCert) {
1715 CERT_DestroyCertificate(sc->serverCert);
1717 sc->serverCert = CERT_DupCertificate(mc->serverCert);
1718 if (sc->serverCertChain) {
1719 CERT_DestroyCertificateList(sc->serverCertChain);
1721 sc->serverCertChain = CERT_DupCertList(mc->serverCertChain);
1722 if (!sc->serverCertChain)
1723 goto loser;
1724 if (sm->certStatusArray[i]) {
1725 if (ss->certStatusArray[i]) {
1726 SECITEM_FreeArray(ss->certStatusArray[i], PR_TRUE);
1727 ss->certStatusArray[i] = NULL;
1729 ss->certStatusArray[i] = SECITEM_DupArray(NULL, sm->certStatusArray[i]);
1730 if (!ss->certStatusArray[i])
1731 goto loser;
1734 if (mc->serverKeyPair) {
1735 if (sc->serverKeyPair) {
1736 ssl3_FreeKeyPair(sc->serverKeyPair);
1738 sc->serverKeyPair = ssl3_GetKeyPairRef(mc->serverKeyPair);
1739 sc->serverKeyBits = mc->serverKeyBits;
1742 if (sm->stepDownKeyPair) {
1743 if (ss->stepDownKeyPair) {
1744 ssl3_FreeKeyPair(ss->stepDownKeyPair);
1746 ss->stepDownKeyPair = ssl3_GetKeyPairRef(sm->stepDownKeyPair);
1748 if (sm->ephemeralECDHKeyPair) {
1749 if (ss->ephemeralECDHKeyPair) {
1750 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
1752 ss->ephemeralECDHKeyPair =
1753 ssl3_GetKeyPairRef(sm->ephemeralECDHKeyPair);
1755 /* copy trust anchor names */
1756 if (sm->ssl3.ca_list) {
1757 if (ss->ssl3.ca_list) {
1758 CERT_FreeDistNames(ss->ssl3.ca_list);
1760 ss->ssl3.ca_list = CERT_DupDistNames(sm->ssl3.ca_list);
1761 if (!ss->ssl3.ca_list) {
1762 goto loser;
1766 if (sm->authCertificate)
1767 ss->authCertificate = sm->authCertificate;
1768 if (sm->authCertificateArg)
1769 ss->authCertificateArg = sm->authCertificateArg;
1770 if (sm->getClientAuthData)
1771 ss->getClientAuthData = sm->getClientAuthData;
1772 if (sm->getClientAuthDataArg)
1773 ss->getClientAuthDataArg = sm->getClientAuthDataArg;
1774 #ifdef NSS_PLATFORM_CLIENT_AUTH
1775 if (sm->getPlatformClientAuthData)
1776 ss->getPlatformClientAuthData = sm->getPlatformClientAuthData;
1777 if (sm->getPlatformClientAuthDataArg)
1778 ss->getPlatformClientAuthDataArg = sm->getPlatformClientAuthDataArg;
1779 #endif
1780 if (sm->sniSocketConfig)
1781 ss->sniSocketConfig = sm->sniSocketConfig;
1782 if (sm->sniSocketConfigArg)
1783 ss->sniSocketConfigArg = sm->sniSocketConfigArg;
1784 if (sm->handleBadCert)
1785 ss->handleBadCert = sm->handleBadCert;
1786 if (sm->badCertArg)
1787 ss->badCertArg = sm->badCertArg;
1788 if (sm->handshakeCallback)
1789 ss->handshakeCallback = sm->handshakeCallback;
1790 if (sm->handshakeCallbackData)
1791 ss->handshakeCallbackData = sm->handshakeCallbackData;
1792 if (sm->pkcs11PinArg)
1793 ss->pkcs11PinArg = sm->pkcs11PinArg;
1794 if (sm->getChannelID)
1795 ss->getChannelID = sm->getChannelID;
1796 if (sm->getChannelIDArg)
1797 ss->getChannelIDArg = sm->getChannelIDArg;
1798 return fd;
1799 loser:
1800 return NULL;
1803 PRBool
1804 ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
1805 SSL3ProtocolVersion version)
1807 switch (protocolVariant) {
1808 case ssl_variant_stream:
1809 return (version >= SSL_LIBRARY_VERSION_3_0 &&
1810 version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
1811 case ssl_variant_datagram:
1812 return (version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
1813 version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
1814 default:
1815 /* Can't get here */
1816 PORT_Assert(PR_FALSE);
1817 return PR_FALSE;
1821 /* Returns PR_TRUE if the given version range is valid and
1822 ** fully supported; otherwise, returns PR_FALSE.
1824 static PRBool
1825 ssl3_VersionRangeIsValid(SSLProtocolVariant protocolVariant,
1826 const SSLVersionRange *vrange)
1828 return vrange &&
1829 vrange->min <= vrange->max &&
1830 ssl3_VersionIsSupported(protocolVariant, vrange->min) &&
1831 ssl3_VersionIsSupported(protocolVariant, vrange->max);
1834 SECStatus
1835 SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant,
1836 SSLVersionRange *vrange)
1838 if (!vrange) {
1839 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1840 return SECFailure;
1843 switch (protocolVariant) {
1844 case ssl_variant_stream:
1845 vrange->min = SSL_LIBRARY_VERSION_3_0;
1846 vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
1847 break;
1848 case ssl_variant_datagram:
1849 vrange->min = SSL_LIBRARY_VERSION_TLS_1_1;
1850 vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
1851 break;
1852 default:
1853 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1854 return SECFailure;
1857 return SECSuccess;
1860 SECStatus
1861 SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant,
1862 SSLVersionRange *vrange)
1864 if ((protocolVariant != ssl_variant_stream &&
1865 protocolVariant != ssl_variant_datagram) || !vrange) {
1866 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1867 return SECFailure;
1870 *vrange = *VERSIONS_DEFAULTS(protocolVariant);
1872 return SECSuccess;
1875 SECStatus
1876 SSL_VersionRangeSetDefault(SSLProtocolVariant protocolVariant,
1877 const SSLVersionRange *vrange)
1879 if (!ssl3_VersionRangeIsValid(protocolVariant, vrange)) {
1880 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
1881 return SECFailure;
1884 *VERSIONS_DEFAULTS(protocolVariant) = *vrange;
1886 return SECSuccess;
1889 SECStatus
1890 SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange)
1892 sslSocket *ss = ssl_FindSocket(fd);
1894 if (!ss) {
1895 SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeGet",
1896 SSL_GETPID(), fd));
1897 return SECFailure;
1900 if (!vrange) {
1901 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1902 return SECFailure;
1905 ssl_Get1stHandshakeLock(ss);
1906 ssl_GetSSL3HandshakeLock(ss);
1908 *vrange = ss->vrange;
1910 ssl_ReleaseSSL3HandshakeLock(ss);
1911 ssl_Release1stHandshakeLock(ss);
1913 return SECSuccess;
1916 static PRCallOnceType checkTLS12TokenOnce;
1917 static PRBool tls12TokenExists;
1919 static PRStatus
1920 ssl_CheckTLS12Token(void)
1922 tls12TokenExists =
1923 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256);
1924 return PR_SUCCESS;
1927 static PRBool
1928 ssl_TLS12TokenExists(void)
1930 (void) PR_CallOnce(&checkTLS12TokenOnce, ssl_CheckTLS12Token);
1931 return tls12TokenExists;
1934 SECStatus
1935 SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange)
1937 sslSocket *ss = ssl_FindSocket(fd);
1939 if (!ss) {
1940 SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeSet",
1941 SSL_GETPID(), fd));
1942 return SECFailure;
1945 if (!ssl3_VersionRangeIsValid(ss->protocolVariant, vrange)) {
1946 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
1947 return SECFailure;
1950 ssl_Get1stHandshakeLock(ss);
1951 ssl_GetSSL3HandshakeLock(ss);
1953 ss->vrange = *vrange;
1954 /* If we don't have a sufficiently up-to-date softoken then we cannot do
1955 * TLS 1.2. */
1956 if (ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_2 &&
1957 !ssl_TLS12TokenExists()) {
1958 /* If the user requested a minimum version of 1.2, then we don't
1959 * silently downgrade. */
1960 if (ss->vrange.min >= SSL_LIBRARY_VERSION_TLS_1_2) {
1961 ssl_ReleaseSSL3HandshakeLock(ss);
1962 ssl_Release1stHandshakeLock(ss);
1963 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
1964 return SECFailure;
1966 ss->vrange.max = SSL_LIBRARY_VERSION_TLS_1_1;
1969 ssl_ReleaseSSL3HandshakeLock(ss);
1970 ssl_Release1stHandshakeLock(ss);
1972 return SECSuccess;
1975 const SECItemArray *
1976 SSL_PeerStapledOCSPResponses(PRFileDesc *fd)
1978 sslSocket *ss = ssl_FindSocket(fd);
1980 if (!ss) {
1981 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerStapledOCSPResponses",
1982 SSL_GETPID(), fd));
1983 return NULL;
1986 if (!ss->sec.ci.sid) {
1987 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
1988 return NULL;
1991 return &ss->sec.ci.sid->peerCertStatus;
1994 const SECItem *
1995 SSL_PeerSignedCertTimestamps(PRFileDesc *fd)
1997 sslSocket *ss = ssl_FindSocket(fd);
1999 if (!ss) {
2000 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_PeerSignedCertTimestamps",
2001 SSL_GETPID(), fd));
2002 return NULL;
2005 if (!ss->sec.ci.sid) {
2006 PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
2007 return NULL;
2010 if (ss->sec.ci.sid->version < SSL_LIBRARY_VERSION_3_0) {
2011 PORT_SetError(SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2);
2012 return NULL;
2014 return &ss->sec.ci.sid->u.ssl3.signedCertTimestamps;
2017 SECStatus
2018 SSL_HandshakeResumedSession(PRFileDesc *fd, PRBool *handshake_resumed) {
2019 sslSocket *ss = ssl_FindSocket(fd);
2021 if (!ss) {
2022 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_HandshakeResumedSession",
2023 SSL_GETPID(), fd));
2024 return SECFailure;
2027 *handshake_resumed = ss->ssl3.hs.isResuming;
2028 return SECSuccess;
2031 const SECItem *
2032 SSL_GetRequestedClientCertificateTypes(PRFileDesc *fd)
2034 sslSocket *ss = ssl_FindSocket(fd);
2036 if (!ss) {
2037 SSL_DBG(("%d: SSL[%d]: bad socket in "
2038 "SSL_GetRequestedClientCertificateTypes", SSL_GETPID(), fd));
2039 return NULL;
2042 return ss->requestedCertTypes;
2045 /************************************************************************/
2046 /* The following functions are the TOP LEVEL SSL functions.
2047 ** They all get called through the NSPRIOMethods table below.
2050 static PRFileDesc * PR_CALLBACK
2051 ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
2053 sslSocket *ss;
2054 sslSocket *ns = NULL;
2055 PRFileDesc *newfd = NULL;
2056 PRFileDesc *osfd;
2057 PRStatus status;
2059 ss = ssl_GetPrivate(fd);
2060 if (!ss) {
2061 SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
2062 return NULL;
2065 /* IF this is a listen socket, there shouldn't be any I/O going on */
2066 SSL_LOCK_READER(ss);
2067 SSL_LOCK_WRITER(ss);
2068 ssl_Get1stHandshakeLock(ss);
2069 ssl_GetSSL3HandshakeLock(ss);
2071 ss->cTimeout = timeout;
2073 osfd = ss->fd->lower;
2075 /* First accept connection */
2076 newfd = osfd->methods->accept(osfd, sockaddr, timeout);
2077 if (newfd == NULL) {
2078 SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
2079 SSL_GETPID(), ss->fd, PORT_GetError()));
2080 } else {
2081 /* Create ssl module */
2082 ns = ssl_DupSocket(ss);
2085 ssl_ReleaseSSL3HandshakeLock(ss);
2086 ssl_Release1stHandshakeLock(ss);
2087 SSL_UNLOCK_WRITER(ss);
2088 SSL_UNLOCK_READER(ss); /* ss isn't used below here. */
2090 if (ns == NULL)
2091 goto loser;
2093 /* push ssl module onto the new socket */
2094 status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
2095 if (status != PR_SUCCESS)
2096 goto loser;
2098 /* Now start server connection handshake with client.
2099 ** Don't need locks here because nobody else has a reference to ns yet.
2101 if ( ns->opt.useSecurity ) {
2102 if ( ns->opt.handshakeAsClient ) {
2103 ns->handshake = ssl2_BeginClientHandshake;
2104 ss->handshaking = sslHandshakingAsClient;
2105 } else {
2106 ns->handshake = ssl2_BeginServerHandshake;
2107 ss->handshaking = sslHandshakingAsServer;
2110 ns->TCPconnected = 1;
2111 return newfd;
2113 loser:
2114 if (ns != NULL)
2115 ssl_FreeSocket(ns);
2116 if (newfd != NULL)
2117 PR_Close(newfd);
2118 return NULL;
2121 static PRStatus PR_CALLBACK
2122 ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
2124 sslSocket *ss;
2125 PRStatus rv;
2127 ss = ssl_GetPrivate(fd);
2128 if (!ss) {
2129 SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
2130 return PR_FAILURE;
2133 /* IF this is a listen socket, there shouldn't be any I/O going on */
2134 SSL_LOCK_READER(ss);
2135 SSL_LOCK_WRITER(ss);
2137 ss->cTimeout = timeout;
2138 rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
2140 SSL_UNLOCK_WRITER(ss);
2141 SSL_UNLOCK_READER(ss);
2143 return rv;
2146 static PRStatus PR_CALLBACK
2147 ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
2149 sslSocket * ss = ssl_GetPrivate(fd);
2150 PRStatus rv;
2152 if (!ss) {
2153 SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
2154 return PR_FAILURE;
2156 SSL_LOCK_READER(ss);
2157 SSL_LOCK_WRITER(ss);
2159 rv = (PRStatus)(*ss->ops->bind)(ss, addr);
2161 SSL_UNLOCK_WRITER(ss);
2162 SSL_UNLOCK_READER(ss);
2163 return rv;
2166 static PRStatus PR_CALLBACK
2167 ssl_Listen(PRFileDesc *fd, PRIntn backlog)
2169 sslSocket * ss = ssl_GetPrivate(fd);
2170 PRStatus rv;
2172 if (!ss) {
2173 SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
2174 return PR_FAILURE;
2176 SSL_LOCK_READER(ss);
2177 SSL_LOCK_WRITER(ss);
2179 rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
2181 SSL_UNLOCK_WRITER(ss);
2182 SSL_UNLOCK_READER(ss);
2183 return rv;
2186 static PRStatus PR_CALLBACK
2187 ssl_Shutdown(PRFileDesc *fd, PRIntn how)
2189 sslSocket * ss = ssl_GetPrivate(fd);
2190 PRStatus rv;
2192 if (!ss) {
2193 SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
2194 return PR_FAILURE;
2196 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
2197 SSL_LOCK_READER(ss);
2199 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
2200 SSL_LOCK_WRITER(ss);
2203 rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
2205 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
2206 SSL_UNLOCK_WRITER(ss);
2208 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
2209 SSL_UNLOCK_READER(ss);
2211 return rv;
2214 static PRStatus PR_CALLBACK
2215 ssl_Close(PRFileDesc *fd)
2217 sslSocket *ss;
2218 PRStatus rv;
2220 ss = ssl_GetPrivate(fd);
2221 if (!ss) {
2222 SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
2223 return PR_FAILURE;
2226 /* There must not be any I/O going on */
2227 SSL_LOCK_READER(ss);
2228 SSL_LOCK_WRITER(ss);
2230 /* By the time this function returns,
2231 ** ss is an invalid pointer, and the locks to which it points have
2232 ** been unlocked and freed. So, this is the ONE PLACE in all of SSL
2233 ** where the LOCK calls and the corresponding UNLOCK calls are not in
2234 ** the same function scope. The unlock calls are in ssl_FreeSocket().
2236 rv = (PRStatus)(*ss->ops->close)(ss);
2238 return rv;
2241 static int PR_CALLBACK
2242 ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
2243 PRIntervalTime timeout)
2245 sslSocket *ss;
2246 int rv;
2248 ss = ssl_GetPrivate(fd);
2249 if (!ss) {
2250 SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
2251 return SECFailure;
2253 SSL_LOCK_READER(ss);
2254 ss->rTimeout = timeout;
2255 if (!ss->opt.fdx)
2256 ss->wTimeout = timeout;
2257 rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags);
2258 SSL_UNLOCK_READER(ss);
2259 return rv;
2262 static int PR_CALLBACK
2263 ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
2264 PRIntervalTime timeout)
2266 sslSocket *ss;
2267 int rv;
2269 ss = ssl_GetPrivate(fd);
2270 if (!ss) {
2271 SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
2272 return SECFailure;
2274 SSL_LOCK_WRITER(ss);
2275 ss->wTimeout = timeout;
2276 if (!ss->opt.fdx)
2277 ss->rTimeout = timeout;
2278 rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags);
2279 SSL_UNLOCK_WRITER(ss);
2280 return rv;
2283 static int PR_CALLBACK
2284 ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
2286 sslSocket *ss;
2287 int rv;
2289 ss = ssl_GetPrivate(fd);
2290 if (!ss) {
2291 SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
2292 return SECFailure;
2294 SSL_LOCK_READER(ss);
2295 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
2296 if (!ss->opt.fdx)
2297 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
2298 rv = (*ss->ops->read)(ss, (unsigned char*)buf, len);
2299 SSL_UNLOCK_READER(ss);
2300 return rv;
2303 static int PR_CALLBACK
2304 ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
2306 sslSocket *ss;
2307 int rv;
2309 ss = ssl_GetPrivate(fd);
2310 if (!ss) {
2311 SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
2312 return SECFailure;
2314 SSL_LOCK_WRITER(ss);
2315 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
2316 if (!ss->opt.fdx)
2317 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
2318 rv = (*ss->ops->write)(ss, (const unsigned char*)buf, len);
2319 SSL_UNLOCK_WRITER(ss);
2320 return rv;
2323 static PRStatus PR_CALLBACK
2324 ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
2326 sslSocket *ss;
2328 ss = ssl_GetPrivate(fd);
2329 if (!ss) {
2330 SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
2331 return PR_FAILURE;
2333 return (PRStatus)(*ss->ops->getpeername)(ss, addr);
2338 SECStatus
2339 ssl_GetPeerInfo(sslSocket *ss)
2341 PRFileDesc * osfd;
2342 int rv;
2343 PRNetAddr sin;
2345 osfd = ss->fd->lower;
2347 PORT_Memset(&sin, 0, sizeof(sin));
2348 rv = osfd->methods->getpeername(osfd, &sin);
2349 if (rv < 0) {
2350 return SECFailure;
2352 ss->TCPconnected = 1;
2353 if (sin.inet.family == PR_AF_INET) {
2354 PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
2355 ss->sec.ci.port = sin.inet.port;
2356 } else if (sin.ipv6.family == PR_AF_INET6) {
2357 ss->sec.ci.peer = sin.ipv6.ip;
2358 ss->sec.ci.port = sin.ipv6.port;
2359 } else {
2360 PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
2361 return SECFailure;
2363 return SECSuccess;
2366 static PRStatus PR_CALLBACK
2367 ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
2369 sslSocket *ss;
2371 ss = ssl_GetPrivate(fd);
2372 if (!ss) {
2373 SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
2374 return PR_FAILURE;
2376 return (PRStatus)(*ss->ops->getsockname)(ss, name);
2379 SECStatus
2380 SSL_SetStapledOCSPResponses(PRFileDesc *fd, const SECItemArray *responses,
2381 SSLKEAType kea)
2383 sslSocket *ss;
2385 ss = ssl_FindSocket(fd);
2386 if (!ss) {
2387 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetStapledOCSPResponses",
2388 SSL_GETPID(), fd));
2389 return SECFailure;
2392 if ( kea <= 0 || kea >= kt_kea_size) {
2393 SSL_DBG(("%d: SSL[%d]: invalid key in SSL_SetStapledOCSPResponses",
2394 SSL_GETPID(), fd));
2395 return SECFailure;
2398 if (ss->certStatusArray[kea]) {
2399 SECITEM_FreeArray(ss->certStatusArray[kea], PR_TRUE);
2400 ss->certStatusArray[kea] = NULL;
2402 if (responses) {
2403 ss->certStatusArray[kea] = SECITEM_DupArray(NULL, responses);
2405 return (ss->certStatusArray[kea] || !responses) ? SECSuccess : SECFailure;
2408 SECStatus
2409 SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID)
2411 sslSocket *ss;
2413 ss = ssl_FindSocket(fd);
2414 if (!ss) {
2415 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSockPeerID",
2416 SSL_GETPID(), fd));
2417 return SECFailure;
2420 if (ss->peerID) {
2421 PORT_Free(ss->peerID);
2422 ss->peerID = NULL;
2424 if (peerID)
2425 ss->peerID = PORT_Strdup(peerID);
2426 return (ss->peerID || !peerID) ? SECSuccess : SECFailure;
2429 #define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
2431 static PRInt16 PR_CALLBACK
2432 ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
2434 sslSocket *ss;
2435 PRInt16 new_flags = how_flags; /* should select on these flags. */
2436 PRNetAddr addr;
2438 *p_out_flags = 0;
2439 ss = ssl_GetPrivate(fd);
2440 if (!ss) {
2441 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
2442 SSL_GETPID(), fd));
2443 return 0; /* don't poll on this socket */
2446 if (ss->opt.useSecurity &&
2447 ss->handshaking != sslHandshakingUndetermined &&
2448 !ss->firstHsDone &&
2449 (how_flags & PR_POLL_RW)) {
2450 if (!ss->TCPconnected) {
2451 ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
2453 /* If it's not connected, then presumably the application is polling
2454 ** on read or write appropriately, so don't change it.
2456 if (ss->TCPconnected) {
2457 if (!ss->handshakeBegun) {
2458 /* If the handshake has not begun, poll on read or write
2459 ** based on the local application's role in the handshake,
2460 ** not based on what the application requested.
2462 new_flags &= ~PR_POLL_RW;
2463 if (ss->handshaking == sslHandshakingAsClient) {
2464 new_flags |= PR_POLL_WRITE;
2465 } else { /* handshaking as server */
2466 new_flags |= PR_POLL_READ;
2468 } else
2469 /* First handshake is in progress */
2470 if (ss->lastWriteBlocked) {
2471 if (new_flags & PR_POLL_READ) {
2472 /* The caller is waiting for data to be received,
2473 ** but the initial handshake is blocked on write, or the
2474 ** client's first handshake record has not been written.
2475 ** The code should select on write, not read.
2477 new_flags ^= PR_POLL_READ; /* don't select on read. */
2478 new_flags |= PR_POLL_WRITE; /* do select on write. */
2480 } else if (new_flags & PR_POLL_WRITE) {
2481 /* The caller is trying to write, but the handshake is
2482 ** blocked waiting for data to read, and the first
2483 ** handshake has been sent. So do NOT to poll on write
2484 ** unless we did false start.
2486 if (!(ss->version >= SSL_LIBRARY_VERSION_3_0 &&
2487 ss->ssl3.hs.canFalseStart)) {
2488 new_flags ^= PR_POLL_WRITE; /* don't select on write. */
2490 new_flags |= PR_POLL_READ; /* do select on read. */
2493 } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
2494 *p_out_flags = PR_POLL_READ; /* it's ready already. */
2495 return new_flags;
2496 } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
2497 (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
2498 new_flags |= PR_POLL_WRITE; /* also select on write. */
2501 if (ss->version >= SSL_LIBRARY_VERSION_3_0 &&
2502 ss->ssl3.hs.restartTarget != NULL) {
2503 /* Read and write will block until the asynchronous callback completes
2504 * (e.g. until SSL_AuthCertificateComplete is called), so don't tell
2505 * the caller to poll the socket unless there is pending write data.
2507 if (ss->lastWriteBlocked && ss->pendingBuf.len != 0) {
2508 /* Ignore any newly-received data on the socket, but do wait for
2509 * the socket to become writable again. Here, it is OK for an error
2510 * to be detected, because our logic for sending pending write data
2511 * will allow us to report the error to the caller without the risk
2512 * of the application spinning.
2514 new_flags &= (PR_POLL_WRITE | PR_POLL_EXCEPT);
2515 } else {
2516 /* Unfortunately, clearing new_flags will make it impossible for
2517 * the application to detect errors that it would otherwise be
2518 * able to detect with PR_POLL_EXCEPT, until the asynchronous
2519 * callback completes. However, we must clear all the flags to
2520 * prevent the application from spinning (alternating between
2521 * calling PR_Poll that would return PR_POLL_EXCEPT, and send/recv
2522 * which won't actually report the I/O error while we are waiting
2523 * for the asynchronous callback to complete).
2525 new_flags = 0;
2529 if (new_flags && (fd->lower->methods->poll != NULL)) {
2530 PRInt16 lower_out_flags = 0;
2531 PRInt16 lower_new_flags;
2532 lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
2533 &lower_out_flags);
2534 if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
2535 PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
2536 if (lower_out_flags & PR_POLL_READ)
2537 out_flags |= PR_POLL_WRITE;
2538 if (lower_out_flags & PR_POLL_WRITE)
2539 out_flags |= PR_POLL_READ;
2540 *p_out_flags = out_flags;
2541 new_flags = how_flags;
2542 } else {
2543 *p_out_flags = lower_out_flags;
2544 new_flags = lower_new_flags;
2548 return new_flags;
2551 static PRInt32 PR_CALLBACK
2552 ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
2553 const void *headers, PRInt32 hlen,
2554 PRTransmitFileFlags flags, PRIntervalTime timeout)
2556 PRSendFileData sfd;
2558 sfd.fd = fd;
2559 sfd.file_offset = 0;
2560 sfd.file_nbytes = 0;
2561 sfd.header = headers;
2562 sfd.hlen = hlen;
2563 sfd.trailer = NULL;
2564 sfd.tlen = 0;
2566 return sd->methods->sendfile(sd, &sfd, flags, timeout);
2570 PRBool
2571 ssl_FdIsBlocking(PRFileDesc *fd)
2573 PRSocketOptionData opt;
2574 PRStatus status;
2576 opt.option = PR_SockOpt_Nonblocking;
2577 opt.value.non_blocking = PR_FALSE;
2578 status = PR_GetSocketOption(fd, &opt);
2579 if (status != PR_SUCCESS)
2580 return PR_FALSE;
2581 return (PRBool)!opt.value.non_blocking;
2584 PRBool
2585 ssl_SocketIsBlocking(sslSocket *ss)
2587 return ssl_FdIsBlocking(ss->fd);
2590 PRInt32 sslFirstBufSize = 8 * 1024;
2591 PRInt32 sslCopyLimit = 1024;
2593 static PRInt32 PR_CALLBACK
2594 ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
2595 PRIntervalTime timeout)
2597 PRInt32 i;
2598 PRInt32 bufLen;
2599 PRInt32 left;
2600 PRInt32 rv;
2601 PRInt32 sent = 0;
2602 const PRInt32 first_len = sslFirstBufSize;
2603 const PRInt32 limit = sslCopyLimit;
2604 PRBool blocking;
2605 PRIOVec myIov = { 0, 0 };
2606 char buf[MAX_FRAGMENT_LENGTH];
2608 if (vectors < 0) {
2609 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2610 return -1;
2612 if (vectors > PR_MAX_IOVECTOR_SIZE) {
2613 PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
2614 return -1;
2616 for (i = 0; i < vectors; i++) {
2617 if (iov[i].iov_len < 0) {
2618 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
2619 return -1;
2622 blocking = ssl_FdIsBlocking(fd);
2624 #define K16 sizeof(buf)
2625 #define KILL_VECTORS while (vectors && !iov->iov_len) { ++iov; --vectors; }
2626 #define GET_VECTOR do { myIov = *iov++; --vectors; KILL_VECTORS } while (0)
2627 #define HANDLE_ERR(rv, len) \
2628 if (rv != len) { \
2629 if (rv < 0) { \
2630 if (!blocking \
2631 && (PR_GetError() == PR_WOULD_BLOCK_ERROR) \
2632 && (sent > 0)) { \
2633 return sent; \
2634 } else { \
2635 return -1; \
2638 /* Only a nonblocking socket can have partial sends */ \
2639 PR_ASSERT(!blocking); \
2640 return sent + rv; \
2642 #define SEND(bfr, len) \
2643 do { \
2644 rv = ssl_Send(fd, bfr, len, 0, timeout); \
2645 HANDLE_ERR(rv, len) \
2646 sent += len; \
2647 } while (0)
2649 /* Make sure the first write is at least 8 KB, if possible. */
2650 KILL_VECTORS
2651 if (!vectors)
2652 return ssl_Send(fd, 0, 0, 0, timeout);
2653 GET_VECTOR;
2654 if (!vectors) {
2655 return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
2657 if (myIov.iov_len < first_len) {
2658 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
2659 bufLen = myIov.iov_len;
2660 left = first_len - bufLen;
2661 while (vectors && left) {
2662 int toCopy;
2663 GET_VECTOR;
2664 toCopy = PR_MIN(left, myIov.iov_len);
2665 PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
2666 bufLen += toCopy;
2667 left -= toCopy;
2668 myIov.iov_base += toCopy;
2669 myIov.iov_len -= toCopy;
2671 SEND( buf, bufLen );
2674 while (vectors || myIov.iov_len) {
2675 PRInt32 addLen;
2676 if (!myIov.iov_len) {
2677 GET_VECTOR;
2679 while (myIov.iov_len >= K16) {
2680 SEND(myIov.iov_base, K16);
2681 myIov.iov_base += K16;
2682 myIov.iov_len -= K16;
2684 if (!myIov.iov_len)
2685 continue;
2687 if (!vectors || myIov.iov_len > limit) {
2688 addLen = 0;
2689 } else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
2690 /* Addlen is already computed. */;
2691 } else if (vectors > 1 &&
2692 iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
2693 addLen = limit - myIov.iov_len;
2694 } else
2695 addLen = 0;
2697 if (!addLen) {
2698 SEND( myIov.iov_base, myIov.iov_len );
2699 myIov.iov_len = 0;
2700 continue;
2702 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
2703 bufLen = myIov.iov_len;
2704 do {
2705 GET_VECTOR;
2706 PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
2707 myIov.iov_base += addLen;
2708 myIov.iov_len -= addLen;
2709 bufLen += addLen;
2711 left = PR_MIN( limit, K16 - bufLen);
2712 if (!vectors /* no more left */
2713 || myIov.iov_len > 0 /* we didn't use that one all up */
2714 || bufLen >= K16 /* it's full. */
2716 addLen = 0;
2717 } else if ((addLen = iov->iov_len % K16) <= left) {
2718 /* Addlen is already computed. */;
2719 } else if (vectors > 1 &&
2720 iov[1].iov_len % K16 + addLen <= left + limit) {
2721 addLen = left;
2722 } else
2723 addLen = 0;
2725 } while (addLen);
2726 SEND( buf, bufLen );
2728 return sent;
2732 * These functions aren't implemented.
2735 static PRInt32 PR_CALLBACK
2736 ssl_Available(PRFileDesc *fd)
2738 PORT_Assert(0);
2739 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2740 return SECFailure;
2743 static PRInt64 PR_CALLBACK
2744 ssl_Available64(PRFileDesc *fd)
2746 PRInt64 res;
2748 PORT_Assert(0);
2749 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2750 LL_I2L(res, -1L);
2751 return res;
2754 static PRStatus PR_CALLBACK
2755 ssl_FSync(PRFileDesc *fd)
2757 PORT_Assert(0);
2758 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2759 return PR_FAILURE;
2762 static PRInt32 PR_CALLBACK
2763 ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) {
2764 PORT_Assert(0);
2765 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2766 return SECFailure;
2769 static PRInt64 PR_CALLBACK
2770 ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) {
2771 PRInt64 res;
2773 PORT_Assert(0);
2774 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2775 LL_I2L(res, -1L);
2776 return res;
2779 static PRStatus PR_CALLBACK
2780 ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
2782 PORT_Assert(0);
2783 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2784 return PR_FAILURE;
2787 static PRStatus PR_CALLBACK
2788 ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
2790 PORT_Assert(0);
2791 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2792 return PR_FAILURE;
2795 static PRInt32 PR_CALLBACK
2796 ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
2797 PRNetAddr *addr, PRIntervalTime timeout)
2799 PORT_Assert(0);
2800 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2801 return SECFailure;
2804 static PRInt32 PR_CALLBACK
2805 ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
2806 const PRNetAddr *addr, PRIntervalTime timeout)
2808 PORT_Assert(0);
2809 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2810 return SECFailure;
2813 static const PRIOMethods ssl_methods = {
2814 PR_DESC_LAYERED,
2815 ssl_Close, /* close */
2816 ssl_Read, /* read */
2817 ssl_Write, /* write */
2818 ssl_Available, /* available */
2819 ssl_Available64, /* available64 */
2820 ssl_FSync, /* fsync */
2821 ssl_Seek, /* seek */
2822 ssl_Seek64, /* seek64 */
2823 ssl_FileInfo, /* fileInfo */
2824 ssl_FileInfo64, /* fileInfo64 */
2825 ssl_WriteV, /* writev */
2826 ssl_Connect, /* connect */
2827 ssl_Accept, /* accept */
2828 ssl_Bind, /* bind */
2829 ssl_Listen, /* listen */
2830 ssl_Shutdown, /* shutdown */
2831 ssl_Recv, /* recv */
2832 ssl_Send, /* send */
2833 ssl_RecvFrom, /* recvfrom */
2834 ssl_SendTo, /* sendto */
2835 ssl_Poll, /* poll */
2836 PR_EmulateAcceptRead, /* acceptread */
2837 ssl_TransmitFile, /* transmitfile */
2838 ssl_GetSockName, /* getsockname */
2839 ssl_GetPeerName, /* getpeername */
2840 NULL, /* getsockopt OBSOLETE */
2841 NULL, /* setsockopt OBSOLETE */
2842 NULL, /* getsocketoption */
2843 NULL, /* setsocketoption */
2844 PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/
2845 NULL, /* reserved for future use */
2846 NULL, /* reserved for future use */
2847 NULL, /* reserved for future use */
2848 NULL, /* reserved for future use */
2849 NULL /* reserved for future use */
2853 static PRIOMethods combined_methods;
2855 static void
2856 ssl_SetupIOMethods(void)
2858 PRIOMethods *new_methods = &combined_methods;
2859 const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
2860 const PRIOMethods *my_methods = &ssl_methods;
2862 *new_methods = *nspr_methods;
2864 new_methods->file_type = my_methods->file_type;
2865 new_methods->close = my_methods->close;
2866 new_methods->read = my_methods->read;
2867 new_methods->write = my_methods->write;
2868 new_methods->available = my_methods->available;
2869 new_methods->available64 = my_methods->available64;
2870 new_methods->fsync = my_methods->fsync;
2871 new_methods->seek = my_methods->seek;
2872 new_methods->seek64 = my_methods->seek64;
2873 new_methods->fileInfo = my_methods->fileInfo;
2874 new_methods->fileInfo64 = my_methods->fileInfo64;
2875 new_methods->writev = my_methods->writev;
2876 new_methods->connect = my_methods->connect;
2877 new_methods->accept = my_methods->accept;
2878 new_methods->bind = my_methods->bind;
2879 new_methods->listen = my_methods->listen;
2880 new_methods->shutdown = my_methods->shutdown;
2881 new_methods->recv = my_methods->recv;
2882 new_methods->send = my_methods->send;
2883 new_methods->recvfrom = my_methods->recvfrom;
2884 new_methods->sendto = my_methods->sendto;
2885 new_methods->poll = my_methods->poll;
2886 new_methods->acceptread = my_methods->acceptread;
2887 new_methods->transmitfile = my_methods->transmitfile;
2888 new_methods->getsockname = my_methods->getsockname;
2889 new_methods->getpeername = my_methods->getpeername;
2890 /* new_methods->getsocketoption = my_methods->getsocketoption; */
2891 /* new_methods->setsocketoption = my_methods->setsocketoption; */
2892 new_methods->sendfile = my_methods->sendfile;
2896 static PRCallOnceType initIoLayerOnce;
2898 static PRStatus
2899 ssl_InitIOLayer(void)
2901 ssl_layer_id = PR_GetUniqueIdentity("SSL");
2902 ssl_SetupIOMethods();
2903 ssl_inited = PR_TRUE;
2904 return PR_SUCCESS;
2907 static PRStatus
2908 ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
2910 PRFileDesc *layer = NULL;
2911 PRStatus status;
2913 if (!ssl_inited) {
2914 status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
2915 if (status != PR_SUCCESS)
2916 goto loser;
2919 if (ns == NULL)
2920 goto loser;
2922 layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
2923 if (layer == NULL)
2924 goto loser;
2925 layer->secret = (PRFilePrivate *)ns;
2927 /* Here, "stack" points to the PRFileDesc on the top of the stack.
2928 ** "layer" points to a new FD that is to be inserted into the stack.
2929 ** If layer is being pushed onto the top of the stack, then
2930 ** PR_PushIOLayer switches the contents of stack and layer, and then
2931 ** puts stack on top of layer, so that after it is done, the top of
2932 ** stack is the same "stack" as it was before, and layer is now the
2933 ** FD for the former top of stack.
2934 ** After this call, stack always points to the top PRFD on the stack.
2935 ** If this function fails, the contents of stack and layer are as
2936 ** they were before the call.
2938 status = PR_PushIOLayer(stack, id, layer);
2939 if (status != PR_SUCCESS)
2940 goto loser;
2942 ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
2943 return PR_SUCCESS;
2945 loser:
2946 if (layer) {
2947 layer->dtor(layer); /* free layer */
2949 return PR_FAILURE;
2952 /* if this fails, caller must destroy socket. */
2953 static SECStatus
2954 ssl_MakeLocks(sslSocket *ss)
2956 ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
2957 if (!ss->firstHandshakeLock)
2958 goto loser;
2959 ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL);
2960 if (!ss->ssl3HandshakeLock)
2961 goto loser;
2962 ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
2963 if (!ss->specLock)
2964 goto loser;
2965 ss->recvBufLock = PZ_NewMonitor(nssILockSSL);
2966 if (!ss->recvBufLock)
2967 goto loser;
2968 ss->xmitBufLock = PZ_NewMonitor(nssILockSSL);
2969 if (!ss->xmitBufLock)
2970 goto loser;
2971 ss->writerThread = NULL;
2972 if (ssl_lock_readers) {
2973 ss->recvLock = PZ_NewLock(nssILockSSL);
2974 if (!ss->recvLock)
2975 goto loser;
2976 ss->sendLock = PZ_NewLock(nssILockSSL);
2977 if (!ss->sendLock)
2978 goto loser;
2980 return SECSuccess;
2981 loser:
2982 ssl_DestroyLocks(ss);
2983 return SECFailure;
2986 #if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS)
2987 #define NSS_HAVE_GETENV 1
2988 #endif
2990 #define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */
2992 static void
2993 ssl_SetDefaultsFromEnvironment(void)
2995 #if defined( NSS_HAVE_GETENV )
2996 static int firsttime = 1;
2998 if (firsttime) {
2999 char * ev;
3000 firsttime = 0;
3001 #ifdef DEBUG
3002 ev = getenv("SSLDEBUGFILE");
3003 if (ev && ev[0]) {
3004 ssl_trace_iob = fopen(ev, "w");
3006 if (!ssl_trace_iob) {
3007 ssl_trace_iob = stderr;
3009 #ifdef TRACE
3010 ev = getenv("SSLTRACE");
3011 if (ev && ev[0]) {
3012 ssl_trace = atoi(ev);
3013 SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
3015 #endif /* TRACE */
3016 ev = getenv("SSLDEBUG");
3017 if (ev && ev[0]) {
3018 ssl_debug = atoi(ev);
3019 SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
3021 #endif /* DEBUG */
3022 ev = getenv("SSLKEYLOGFILE");
3023 if (ev && ev[0]) {
3024 ssl_keylog_iob = fopen(ev, "a");
3025 if (!ssl_keylog_iob) {
3026 SSL_TRACE(("SSL: failed to open key log file"));
3027 } else {
3028 if (ftell(ssl_keylog_iob) == 0) {
3029 fputs("# SSL/TLS secrets log file, generated by NSS\n",
3030 ssl_keylog_iob);
3032 SSL_TRACE(("SSL: logging SSL/TLS secrets to %s", ev));
3035 #ifndef NO_PKCS11_BYPASS
3036 ev = getenv("SSLBYPASS");
3037 if (ev && ev[0]) {
3038 ssl_defaults.bypassPKCS11 = (ev[0] == '1');
3039 SSL_TRACE(("SSL: bypass default set to %d", \
3040 ssl_defaults.bypassPKCS11));
3042 #endif /* NO_PKCS11_BYPASS */
3043 ev = getenv("SSLFORCELOCKS");
3044 if (ev && ev[0] == '1') {
3045 ssl_force_locks = PR_TRUE;
3046 ssl_defaults.noLocks = 0;
3047 strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED. ");
3048 SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
3050 ev = getenv("NSS_SSL_ENABLE_RENEGOTIATION");
3051 if (ev) {
3052 if (ev[0] == '1' || LOWER(ev[0]) == 'u')
3053 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED;
3054 else if (ev[0] == '0' || LOWER(ev[0]) == 'n')
3055 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
3056 else if (ev[0] == '2' || LOWER(ev[0]) == 'r')
3057 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN;
3058 else if (ev[0] == '3' || LOWER(ev[0]) == 't')
3059 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_TRANSITIONAL;
3060 SSL_TRACE(("SSL: enableRenegotiation set to %d",
3061 ssl_defaults.enableRenegotiation));
3063 ev = getenv("NSS_SSL_REQUIRE_SAFE_NEGOTIATION");
3064 if (ev && ev[0] == '1') {
3065 ssl_defaults.requireSafeNegotiation = PR_TRUE;
3066 SSL_TRACE(("SSL: requireSafeNegotiation set to %d",
3067 PR_TRUE));
3069 ev = getenv("NSS_SSL_CBC_RANDOM_IV");
3070 if (ev && ev[0] == '0') {
3071 ssl_defaults.cbcRandomIV = PR_FALSE;
3072 SSL_TRACE(("SSL: cbcRandomIV set to 0"));
3075 #endif /* NSS_HAVE_GETENV */
3079 ** Create a newsocket structure for a file descriptor.
3081 static sslSocket *
3082 ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant)
3084 sslSocket *ss;
3086 ssl_SetDefaultsFromEnvironment();
3088 if (ssl_force_locks)
3089 makeLocks = PR_TRUE;
3091 /* Make a new socket and get it ready */
3092 ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket));
3093 if (ss) {
3094 /* This should be of type SSLKEAType, but CC on IRIX
3095 * complains during the for loop.
3097 int i;
3098 SECStatus status;
3100 ss->opt = ssl_defaults;
3101 ss->opt.useSocks = PR_FALSE;
3102 ss->opt.noLocks = !makeLocks;
3103 ss->vrange = *VERSIONS_DEFAULTS(protocolVariant);
3104 ss->protocolVariant = protocolVariant;
3106 ss->peerID = NULL;
3107 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
3108 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
3109 ss->cTimeout = PR_INTERVAL_NO_TIMEOUT;
3110 ss->cipherSpecs = NULL;
3111 ss->sizeCipherSpecs = 0; /* produced lazily */
3112 ss->preferredCipher = NULL;
3113 ss->url = NULL;
3115 for (i=kt_null; i < kt_kea_size; i++) {
3116 sslServerCerts * sc = ss->serverCerts + i;
3117 sc->serverCert = NULL;
3118 sc->serverCertChain = NULL;
3119 sc->serverKeyPair = NULL;
3120 sc->serverKeyBits = 0;
3121 ss->certStatusArray[i] = NULL;
3123 ss->requestedCertTypes = NULL;
3124 ss->stepDownKeyPair = NULL;
3125 ss->dbHandle = CERT_GetDefaultCertDB();
3127 /* Provide default implementation of hooks */
3128 ss->authCertificate = SSL_AuthCertificate;
3129 ss->authCertificateArg = (void *)ss->dbHandle;
3130 ss->sniSocketConfig = NULL;
3131 ss->sniSocketConfigArg = NULL;
3132 ss->getClientAuthData = NULL;
3133 #ifdef NSS_PLATFORM_CLIENT_AUTH
3134 ss->getPlatformClientAuthData = NULL;
3135 ss->getPlatformClientAuthDataArg = NULL;
3136 #endif /* NSS_PLATFORM_CLIENT_AUTH */
3137 ss->handleBadCert = NULL;
3138 ss->badCertArg = NULL;
3139 ss->pkcs11PinArg = NULL;
3140 ss->ephemeralECDHKeyPair = NULL;
3141 ss->getChannelID = NULL;
3142 ss->getChannelIDArg = NULL;
3144 ssl_ChooseOps(ss);
3145 ssl2_InitSocketPolicy(ss);
3146 ssl3_InitSocketPolicy(ss);
3147 PR_INIT_CLIST(&ss->ssl3.hs.lastMessageFlight);
3149 if (makeLocks) {
3150 status = ssl_MakeLocks(ss);
3151 if (status != SECSuccess)
3152 goto loser;
3154 status = ssl_CreateSecurityInfo(ss);
3155 if (status != SECSuccess)
3156 goto loser;
3157 status = ssl_InitGather(&ss->gs);
3158 if (status != SECSuccess) {
3159 loser:
3160 ssl_DestroySocketContents(ss);
3161 ssl_DestroyLocks(ss);
3162 PORT_Free(ss);
3163 ss = NULL;
3166 return ss;