Revert "Merged all Chromoting Host code into remoting_core.dll (Windows)."
[chromium-blink-merge.git] / net / third_party / nss / ssl / sslsock.c
bloba068230875e81b3d422b2c689172fac06f77cb2f
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 /* $Id: sslsock.c,v 1.96 2012/09/24 23:57:42 wtc%google.com Exp $ */
10 #include "seccomon.h"
11 #include "cert.h"
12 #include "keyhi.h"
13 #include "ssl.h"
14 #include "sslimpl.h"
15 #include "sslproto.h"
16 #include "nspr.h"
17 #include "private/pprio.h"
18 #ifndef NO_PKCS11_BYPASS
19 #include "blapi.h"
20 #endif
21 #include "nss.h"
23 #define SET_ERROR_CODE /* reminder */
25 struct cipherPolicyStr {
26 int cipher;
27 unsigned char export; /* policy value for export policy */
28 unsigned char france; /* policy value for france policy */
31 typedef struct cipherPolicyStr cipherPolicy;
33 /* This table contains two preconfigured policies: Export and France.
34 ** It is used only by the functions SSL_SetDomesticPolicy,
35 ** SSL_SetExportPolicy, and SSL_SetFrancyPolicy.
36 ** Order of entries is not important.
38 static cipherPolicy ssl_ciphers[] = { /* Export France */
39 { SSL_EN_RC4_128_WITH_MD5, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
40 { SSL_EN_RC4_128_EXPORT40_WITH_MD5, SSL_ALLOWED, SSL_ALLOWED },
41 { SSL_EN_RC2_128_CBC_WITH_MD5, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
42 { SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, SSL_ALLOWED, SSL_ALLOWED },
43 { SSL_EN_DES_64_CBC_WITH_MD5, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
44 { SSL_EN_DES_192_EDE3_CBC_WITH_MD5, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
45 { SSL_RSA_WITH_RC4_128_MD5, SSL_RESTRICTED, SSL_NOT_ALLOWED },
46 { SSL_RSA_WITH_RC4_128_SHA, SSL_RESTRICTED, SSL_NOT_ALLOWED },
47 { SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
48 { SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RESTRICTED, SSL_NOT_ALLOWED },
49 { SSL_RSA_FIPS_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
50 { SSL_RSA_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
51 { SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_ALLOWED, SSL_ALLOWED },
52 { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, SSL_ALLOWED, SSL_ALLOWED },
53 { SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
54 { SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
55 { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
56 { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
57 { TLS_DHE_DSS_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
58 { SSL_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
59 { SSL_RSA_WITH_NULL_MD5, SSL_ALLOWED, SSL_ALLOWED },
60 { TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
61 { TLS_DHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
62 { TLS_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
63 { TLS_DHE_DSS_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
64 { TLS_DHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
65 { TLS_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
66 { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
67 { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
68 { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
69 { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
70 { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
71 { TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
72 { TLS_RSA_WITH_SEED_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
73 { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA, SSL_ALLOWED, SSL_NOT_ALLOWED },
74 { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA, SSL_ALLOWED, SSL_NOT_ALLOWED },
75 #ifdef NSS_ENABLE_ECC
76 { TLS_ECDH_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
77 { TLS_ECDH_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
78 { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
79 { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
80 { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
81 { TLS_ECDHE_ECDSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
82 { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
83 { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
84 { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
85 { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
86 { TLS_ECDH_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
87 { TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
88 { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
89 { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
90 { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
91 { TLS_ECDHE_RSA_WITH_NULL_SHA, SSL_ALLOWED, SSL_ALLOWED },
92 { TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
93 { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
94 { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
95 { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED },
96 #endif /* NSS_ENABLE_ECC */
97 { 0, SSL_NOT_ALLOWED, SSL_NOT_ALLOWED }
100 static const sslSocketOps ssl_default_ops = { /* No SSL. */
101 ssl_DefConnect,
102 NULL,
103 ssl_DefBind,
104 ssl_DefListen,
105 ssl_DefShutdown,
106 ssl_DefClose,
107 ssl_DefRecv,
108 ssl_DefSend,
109 ssl_DefRead,
110 ssl_DefWrite,
111 ssl_DefGetpeername,
112 ssl_DefGetsockname
115 static const sslSocketOps ssl_secure_ops = { /* SSL. */
116 ssl_SecureConnect,
117 NULL,
118 ssl_DefBind,
119 ssl_DefListen,
120 ssl_SecureShutdown,
121 ssl_SecureClose,
122 ssl_SecureRecv,
123 ssl_SecureSend,
124 ssl_SecureRead,
125 ssl_SecureWrite,
126 ssl_DefGetpeername,
127 ssl_DefGetsockname
131 ** default settings for socket enables
133 static sslOptions ssl_defaults = {
134 { siBuffer, NULL, 0 }, /* nextProtoNego */
135 PR_TRUE, /* useSecurity */
136 PR_FALSE, /* useSocks */
137 PR_FALSE, /* requestCertificate */
138 2, /* requireCertificate */
139 PR_FALSE, /* handshakeAsClient */
140 PR_FALSE, /* handshakeAsServer */
141 PR_FALSE, /* enableSSL2 */ /* now defaults to off in NSS 3.13 */
142 PR_FALSE, /* unusedBit9 */
143 PR_FALSE, /* unusedBit10 */
144 PR_FALSE, /* noCache */
145 PR_FALSE, /* fdx */
146 PR_FALSE, /* v2CompatibleHello */ /* now defaults to off in NSS 3.13 */
147 PR_TRUE, /* detectRollBack */
148 PR_FALSE, /* noStepDown */
149 PR_FALSE, /* bypassPKCS11 */
150 PR_FALSE, /* noLocks */
151 PR_FALSE, /* enableSessionTickets */
152 PR_FALSE, /* enableDeflate */
153 2, /* enableRenegotiation (default: requires extension) */
154 PR_FALSE, /* requireSafeNegotiation */
155 PR_FALSE, /* enableFalseStart */
156 PR_TRUE, /* cbcRandomIV */
157 PR_FALSE, /* enableOCSPStapling */
161 * default range of enabled SSL/TLS protocols
163 static SSLVersionRange versions_defaults_stream = {
164 SSL_LIBRARY_VERSION_3_0,
165 SSL_LIBRARY_VERSION_TLS_1_0
168 static SSLVersionRange versions_defaults_datagram = {
169 SSL_LIBRARY_VERSION_TLS_1_1,
170 SSL_LIBRARY_VERSION_TLS_1_1
173 #define VERSIONS_DEFAULTS(variant) \
174 (variant == ssl_variant_stream ? &versions_defaults_stream : \
175 &versions_defaults_datagram)
177 sslSessionIDLookupFunc ssl_sid_lookup;
178 sslSessionIDCacheFunc ssl_sid_cache;
179 sslSessionIDUncacheFunc ssl_sid_uncache;
181 static PRBool ssl_inited = PR_FALSE;
182 static PRDescIdentity ssl_layer_id;
184 PRBool locksEverDisabled; /* implicitly PR_FALSE */
185 PRBool ssl_force_locks; /* implicitly PR_FALSE */
186 int ssl_lock_readers = 1; /* default true. */
187 char ssl_debug;
188 char ssl_trace;
189 FILE * ssl_trace_iob;
190 FILE * ssl_keylog_iob;
191 char lockStatus[] = "Locks are ENABLED. ";
192 #define LOCKSTATUS_OFFSET 10 /* offset of ENABLED */
194 /* SRTP_NULL_HMAC_SHA1_80 and SRTP_NULL_HMAC_SHA1_32 are not implemented. */
195 static const PRUint16 srtpCiphers[] = {
196 SRTP_AES128_CM_HMAC_SHA1_80,
197 SRTP_AES128_CM_HMAC_SHA1_32,
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);
208 /************************************************************************/
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.
215 static sslSocket *
216 ssl_GetPrivate(PRFileDesc *fd)
218 sslSocket *ss;
220 PORT_Assert(fd != NULL);
221 PORT_Assert(fd->methods->file_type == PR_DESC_LAYERED);
222 PORT_Assert(fd->identity == ssl_layer_id);
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;
230 ss = (sslSocket *)fd->secret;
231 ss->fd = fd;
232 return ss;
235 /* This function tries to find the SSL layer in the stack.
236 * It searches for the first SSL layer at or below the argument fd,
237 * and failing that, it searches for the nearest SSL layer above the
238 * argument fd. It returns the private sslSocket from the found layer.
240 sslSocket *
241 ssl_FindSocket(PRFileDesc *fd)
243 PRFileDesc *layer;
244 sslSocket *ss;
246 PORT_Assert(fd != NULL);
247 PORT_Assert(ssl_layer_id != 0);
249 layer = PR_GetIdentitiesLayer(fd, ssl_layer_id);
250 if (layer == NULL) {
251 PORT_SetError(PR_BAD_DESCRIPTOR_ERROR);
252 return NULL;
255 ss = (sslSocket *)layer->secret;
256 ss->fd = layer;
257 return ss;
260 static sslSocket *
261 ssl_DupSocket(sslSocket *os)
263 sslSocket *ss;
264 SECStatus rv;
266 ss = ssl_NewSocket((PRBool)(!os->opt.noLocks), os->protocolVariant);
267 if (ss) {
268 ss->opt = os->opt;
269 ss->opt.useSocks = PR_FALSE;
270 ss->vrange = os->vrange;
272 ss->peerID = !os->peerID ? NULL : PORT_Strdup(os->peerID);
273 ss->url = !os->url ? NULL : PORT_Strdup(os->url);
275 ss->ops = os->ops;
276 ss->rTimeout = os->rTimeout;
277 ss->wTimeout = os->wTimeout;
278 ss->cTimeout = os->cTimeout;
279 ss->dbHandle = os->dbHandle;
281 /* copy ssl2&3 policy & prefs, even if it's not selected (yet) */
282 ss->allowedByPolicy = os->allowedByPolicy;
283 ss->maybeAllowedByPolicy= os->maybeAllowedByPolicy;
284 ss->chosenPreference = os->chosenPreference;
285 PORT_Memcpy(ss->cipherSuites, os->cipherSuites, sizeof os->cipherSuites);
286 PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, os->ssl3.dtlsSRTPCiphers,
287 sizeof(PRUint16) * os->ssl3.dtlsSRTPCipherCount);
288 ss->ssl3.dtlsSRTPCipherCount = os->ssl3.dtlsSRTPCipherCount;
290 if (os->cipherSpecs) {
291 ss->cipherSpecs = (unsigned char*)PORT_Alloc(os->sizeCipherSpecs);
292 if (ss->cipherSpecs)
293 PORT_Memcpy(ss->cipherSpecs, os->cipherSpecs,
294 os->sizeCipherSpecs);
295 ss->sizeCipherSpecs = os->sizeCipherSpecs;
296 ss->preferredCipher = os->preferredCipher;
297 } else {
298 ss->cipherSpecs = NULL; /* produced lazily */
299 ss->sizeCipherSpecs = 0;
300 ss->preferredCipher = NULL;
302 if (ss->opt.useSecurity) {
303 /* This int should be SSLKEAType, but CC on Irix complains,
304 * during the for loop.
306 int i;
307 sslServerCerts * oc = os->serverCerts;
308 sslServerCerts * sc = ss->serverCerts;
310 for (i=kt_null; i < kt_kea_size; i++, oc++, sc++) {
311 if (oc->serverCert && oc->serverCertChain) {
312 sc->serverCert = CERT_DupCertificate(oc->serverCert);
313 sc->serverCertChain = CERT_DupCertList(oc->serverCertChain);
314 if (!sc->serverCertChain)
315 goto loser;
316 } else {
317 sc->serverCert = NULL;
318 sc->serverCertChain = NULL;
320 sc->serverKeyPair = oc->serverKeyPair ?
321 ssl3_GetKeyPairRef(oc->serverKeyPair) : NULL;
322 if (oc->serverKeyPair && !sc->serverKeyPair)
323 goto loser;
324 sc->serverKeyBits = oc->serverKeyBits;
326 ss->stepDownKeyPair = !os->stepDownKeyPair ? NULL :
327 ssl3_GetKeyPairRef(os->stepDownKeyPair);
328 ss->ephemeralECDHKeyPair = !os->ephemeralECDHKeyPair ? NULL :
329 ssl3_GetKeyPairRef(os->ephemeralECDHKeyPair);
331 * XXX the preceding CERT_ and SECKEY_ functions can fail and return NULL.
332 * XXX We should detect this, and not just march on with NULL pointers.
334 ss->authCertificate = os->authCertificate;
335 ss->authCertificateArg = os->authCertificateArg;
336 ss->getClientAuthData = os->getClientAuthData;
337 ss->getClientAuthDataArg = os->getClientAuthDataArg;
338 #ifdef NSS_PLATFORM_CLIENT_AUTH
339 ss->getPlatformClientAuthData = os->getPlatformClientAuthData;
340 ss->getPlatformClientAuthDataArg = os->getPlatformClientAuthDataArg;
341 #endif
342 ss->sniSocketConfig = os->sniSocketConfig;
343 ss->sniSocketConfigArg = os->sniSocketConfigArg;
344 ss->handleBadCert = os->handleBadCert;
345 ss->badCertArg = os->badCertArg;
346 ss->handshakeCallback = os->handshakeCallback;
347 ss->handshakeCallbackData = os->handshakeCallbackData;
348 ss->pkcs11PinArg = os->pkcs11PinArg;
349 ss->getChannelID = os->getChannelID;
350 ss->getChannelIDArg = os->getChannelIDArg;
352 /* Create security data */
353 rv = ssl_CopySecurityInfo(ss, os);
354 if (rv != SECSuccess) {
355 goto loser;
359 return ss;
361 loser:
362 ssl_FreeSocket(ss);
363 return NULL;
366 static void
367 ssl_DestroyLocks(sslSocket *ss)
369 /* Destroy locks. */
370 if (ss->firstHandshakeLock) {
371 PZ_DestroyMonitor(ss->firstHandshakeLock);
372 ss->firstHandshakeLock = NULL;
374 if (ss->ssl3HandshakeLock) {
375 PZ_DestroyMonitor(ss->ssl3HandshakeLock);
376 ss->ssl3HandshakeLock = NULL;
378 if (ss->specLock) {
379 NSSRWLock_Destroy(ss->specLock);
380 ss->specLock = NULL;
383 if (ss->recvLock) {
384 PZ_DestroyLock(ss->recvLock);
385 ss->recvLock = NULL;
387 if (ss->sendLock) {
388 PZ_DestroyLock(ss->sendLock);
389 ss->sendLock = NULL;
391 if (ss->xmitBufLock) {
392 PZ_DestroyMonitor(ss->xmitBufLock);
393 ss->xmitBufLock = NULL;
395 if (ss->recvBufLock) {
396 PZ_DestroyMonitor(ss->recvBufLock);
397 ss->recvBufLock = NULL;
401 /* Caller holds any relevant locks */
402 static void
403 ssl_DestroySocketContents(sslSocket *ss)
405 /* "i" should be of type SSLKEAType, but CC on IRIX complains during
406 * the for loop.
408 int i;
410 /* Free up socket */
411 ssl_DestroySecurityInfo(&ss->sec);
413 ssl3_DestroySSL3Info(ss);
415 PORT_Free(ss->saveBuf.buf);
416 PORT_Free(ss->pendingBuf.buf);
417 ssl_DestroyGather(&ss->gs);
419 if (ss->peerID != NULL)
420 PORT_Free(ss->peerID);
421 if (ss->url != NULL)
422 PORT_Free((void *)ss->url); /* CONST */
423 if (ss->cipherSpecs) {
424 PORT_Free(ss->cipherSpecs);
425 ss->cipherSpecs = NULL;
426 ss->sizeCipherSpecs = 0;
429 /* Clean up server configuration */
430 for (i=kt_null; i < kt_kea_size; i++) {
431 sslServerCerts * sc = ss->serverCerts + i;
432 if (sc->serverCert != NULL)
433 CERT_DestroyCertificate(sc->serverCert);
434 if (sc->serverCertChain != NULL)
435 CERT_DestroyCertificateList(sc->serverCertChain);
436 if (sc->serverKeyPair != NULL)
437 ssl3_FreeKeyPair(sc->serverKeyPair);
439 if (ss->stepDownKeyPair) {
440 ssl3_FreeKeyPair(ss->stepDownKeyPair);
441 ss->stepDownKeyPair = NULL;
443 if (ss->ephemeralECDHKeyPair) {
444 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
445 ss->ephemeralECDHKeyPair = NULL;
447 SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
448 PORT_Assert(!ss->xtnData.sniNameArr);
449 if (ss->xtnData.sniNameArr) {
450 PORT_Free(ss->xtnData.sniNameArr);
451 ss->xtnData.sniNameArr = NULL;
456 * free an sslSocket struct, and all the stuff that hangs off of it
458 void
459 ssl_FreeSocket(sslSocket *ss)
461 /* Get every lock you can imagine!
462 ** Caller already holds these:
463 ** SSL_LOCK_READER(ss);
464 ** SSL_LOCK_WRITER(ss);
466 ssl_Get1stHandshakeLock(ss);
467 ssl_GetRecvBufLock(ss);
468 ssl_GetSSL3HandshakeLock(ss);
469 ssl_GetXmitBufLock(ss);
470 ssl_GetSpecWriteLock(ss);
472 ssl_DestroySocketContents(ss);
474 /* Release all the locks acquired above. */
475 SSL_UNLOCK_READER(ss);
476 SSL_UNLOCK_WRITER(ss);
477 ssl_Release1stHandshakeLock(ss);
478 ssl_ReleaseRecvBufLock(ss);
479 ssl_ReleaseSSL3HandshakeLock(ss);
480 ssl_ReleaseXmitBufLock(ss);
481 ssl_ReleaseSpecWriteLock(ss);
483 ssl_DestroyLocks(ss);
485 #ifdef DEBUG
486 PORT_Memset(ss, 0x1f, sizeof *ss);
487 #endif
488 PORT_Free(ss);
489 return;
492 /************************************************************************/
493 SECStatus
494 ssl_EnableNagleDelay(sslSocket *ss, PRBool enabled)
496 PRFileDesc * osfd = ss->fd->lower;
497 SECStatus rv = SECFailure;
498 PRSocketOptionData opt;
500 opt.option = PR_SockOpt_NoDelay;
501 opt.value.no_delay = (PRBool)!enabled;
503 if (osfd->methods->setsocketoption) {
504 rv = (SECStatus) osfd->methods->setsocketoption(osfd, &opt);
505 } else {
506 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
509 return rv;
512 static void
513 ssl_ChooseOps(sslSocket *ss)
515 ss->ops = ss->opt.useSecurity ? &ssl_secure_ops : &ssl_default_ops;
518 /* Called from SSL_Enable (immediately below) */
519 static SECStatus
520 PrepareSocket(sslSocket *ss)
522 SECStatus rv = SECSuccess;
524 ssl_ChooseOps(ss);
525 return rv;
528 SECStatus
529 SSL_Enable(PRFileDesc *fd, int which, PRBool on)
531 return SSL_OptionSet(fd, which, on);
534 #ifndef NO_PKCS11_BYPASS
535 static const PRCallOnceType pristineCallOnce;
536 static PRCallOnceType setupBypassOnce;
538 static SECStatus SSL_BypassShutdown(void* appData, void* nssData)
540 /* unload freeBL shared library from memory */
541 BL_Unload();
542 setupBypassOnce = pristineCallOnce;
543 return SECSuccess;
546 static PRStatus SSL_BypassRegisterShutdown(void)
548 SECStatus rv = NSS_RegisterShutdown(SSL_BypassShutdown, NULL);
549 PORT_Assert(SECSuccess == rv);
550 return SECSuccess == rv ? PR_SUCCESS : PR_FAILURE;
552 #endif
554 static PRStatus SSL_BypassSetup(void)
556 #ifdef NO_PKCS11_BYPASS
557 /* Guarantee binary compatibility */
558 return PR_SUCCESS;
559 #else
560 return PR_CallOnce(&setupBypassOnce, &SSL_BypassRegisterShutdown);
561 #endif
564 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_TLS, on) described in
565 * ssl.h in the section "SSL version range setting API".
567 static void
568 ssl_EnableTLS(SSLVersionRange *vrange, PRBool on)
570 if (SSL3_ALL_VERSIONS_DISABLED(vrange)) {
571 if (on) {
572 vrange->min = SSL_LIBRARY_VERSION_TLS_1_0;
573 vrange->max = SSL_LIBRARY_VERSION_TLS_1_0;
574 } /* else don't change anything */
575 return;
578 if (on) {
579 /* Expand the range of enabled version to include TLS 1.0 */
580 vrange->min = PR_MIN(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
581 vrange->max = PR_MAX(vrange->max, SSL_LIBRARY_VERSION_TLS_1_0);
582 } else {
583 /* Disable all TLS versions, leaving only SSL 3.0 if it was enabled */
584 if (vrange->min == SSL_LIBRARY_VERSION_3_0) {
585 vrange->max = SSL_LIBRARY_VERSION_3_0;
586 } else {
587 /* Only TLS was enabled, so now no versions are. */
588 vrange->min = SSL_LIBRARY_VERSION_NONE;
589 vrange->max = SSL_LIBRARY_VERSION_NONE;
594 /* Implements the semantics for SSL_OptionSet(SSL_ENABLE_SSL3, on) described in
595 * ssl.h in the section "SSL version range setting API".
597 static void
598 ssl_EnableSSL3(SSLVersionRange *vrange, PRBool on)
600 if (SSL3_ALL_VERSIONS_DISABLED(vrange)) {
601 if (on) {
602 vrange->min = SSL_LIBRARY_VERSION_3_0;
603 vrange->max = SSL_LIBRARY_VERSION_3_0;
604 } /* else don't change anything */
605 return;
608 if (on) {
609 /* Expand the range of enabled versions to include SSL 3.0. We know
610 * SSL 3.0 or some version of TLS is already enabled at this point, so
611 * we don't need to change vrange->max.
613 vrange->min = SSL_LIBRARY_VERSION_3_0;
614 } else {
615 /* Disable SSL 3.0, leaving TLS unaffected. */
616 if (vrange->max > SSL_LIBRARY_VERSION_3_0) {
617 vrange->min = PR_MAX(vrange->min, SSL_LIBRARY_VERSION_TLS_1_0);
618 } else {
619 /* Only SSL 3.0 was enabled, so now no versions are. */
620 vrange->min = SSL_LIBRARY_VERSION_NONE;
621 vrange->max = SSL_LIBRARY_VERSION_NONE;
626 SECStatus
627 SSL_OptionSet(PRFileDesc *fd, PRInt32 which, PRBool on)
629 sslSocket *ss = ssl_FindSocket(fd);
630 SECStatus rv = SECSuccess;
631 PRBool holdingLocks;
633 if (!ss) {
634 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
635 return SECFailure;
638 holdingLocks = (!ss->opt.noLocks);
639 ssl_Get1stHandshakeLock(ss);
640 ssl_GetSSL3HandshakeLock(ss);
642 switch (which) {
643 case SSL_SOCKS:
644 ss->opt.useSocks = PR_FALSE;
645 rv = PrepareSocket(ss);
646 if (on) {
647 PORT_SetError(SEC_ERROR_INVALID_ARGS);
648 rv = SECFailure;
650 break;
652 case SSL_SECURITY:
653 ss->opt.useSecurity = on;
654 rv = PrepareSocket(ss);
655 break;
657 case SSL_REQUEST_CERTIFICATE:
658 ss->opt.requestCertificate = on;
659 break;
661 case SSL_REQUIRE_CERTIFICATE:
662 ss->opt.requireCertificate = on;
663 break;
665 case SSL_HANDSHAKE_AS_CLIENT:
666 if ( ss->opt.handshakeAsServer && on ) {
667 PORT_SetError(SEC_ERROR_INVALID_ARGS);
668 rv = SECFailure;
669 break;
671 ss->opt.handshakeAsClient = on;
672 break;
674 case SSL_HANDSHAKE_AS_SERVER:
675 if ( ss->opt.handshakeAsClient && on ) {
676 PORT_SetError(SEC_ERROR_INVALID_ARGS);
677 rv = SECFailure;
678 break;
680 ss->opt.handshakeAsServer = on;
681 break;
683 case SSL_ENABLE_TLS:
684 if (IS_DTLS(ss)) {
685 if (on) {
686 PORT_SetError(SEC_ERROR_INVALID_ARGS);
687 rv = SECFailure; /* not allowed */
689 break;
691 ssl_EnableTLS(&ss->vrange, on);
692 ss->preferredCipher = NULL;
693 if (ss->cipherSpecs) {
694 PORT_Free(ss->cipherSpecs);
695 ss->cipherSpecs = NULL;
696 ss->sizeCipherSpecs = 0;
698 break;
700 case SSL_ENABLE_SSL3:
701 if (IS_DTLS(ss)) {
702 if (on) {
703 PORT_SetError(SEC_ERROR_INVALID_ARGS);
704 rv = SECFailure; /* not allowed */
706 break;
708 ssl_EnableSSL3(&ss->vrange, on);
709 ss->preferredCipher = NULL;
710 if (ss->cipherSpecs) {
711 PORT_Free(ss->cipherSpecs);
712 ss->cipherSpecs = NULL;
713 ss->sizeCipherSpecs = 0;
715 break;
717 case SSL_ENABLE_SSL2:
718 if (IS_DTLS(ss)) {
719 if (on) {
720 PORT_SetError(SEC_ERROR_INVALID_ARGS);
721 rv = SECFailure; /* not allowed */
723 break;
725 ss->opt.enableSSL2 = on;
726 if (on) {
727 ss->opt.v2CompatibleHello = on;
729 ss->preferredCipher = NULL;
730 if (ss->cipherSpecs) {
731 PORT_Free(ss->cipherSpecs);
732 ss->cipherSpecs = NULL;
733 ss->sizeCipherSpecs = 0;
735 break;
737 case SSL_NO_CACHE:
738 ss->opt.noCache = on;
739 break;
741 case SSL_ENABLE_FDX:
742 if (on && ss->opt.noLocks) {
743 PORT_SetError(SEC_ERROR_INVALID_ARGS);
744 rv = SECFailure;
746 ss->opt.fdx = on;
747 break;
749 case SSL_V2_COMPATIBLE_HELLO:
750 if (IS_DTLS(ss)) {
751 if (on) {
752 PORT_SetError(SEC_ERROR_INVALID_ARGS);
753 rv = SECFailure; /* not allowed */
755 break;
757 ss->opt.v2CompatibleHello = on;
758 if (!on) {
759 ss->opt.enableSSL2 = on;
761 break;
763 case SSL_ROLLBACK_DETECTION:
764 ss->opt.detectRollBack = on;
765 break;
767 case SSL_NO_STEP_DOWN:
768 ss->opt.noStepDown = on;
769 if (on)
770 SSL_DisableExportCipherSuites(fd);
771 break;
773 case SSL_BYPASS_PKCS11:
774 if (ss->handshakeBegun) {
775 PORT_SetError(PR_INVALID_STATE_ERROR);
776 rv = SECFailure;
777 } else {
778 if (PR_FALSE != on) {
779 if (PR_SUCCESS == SSL_BypassSetup() ) {
780 #ifdef NO_PKCS11_BYPASS
781 ss->opt.bypassPKCS11 = PR_FALSE;
782 #else
783 ss->opt.bypassPKCS11 = on;
784 #endif
785 } else {
786 rv = SECFailure;
788 } else {
789 ss->opt.bypassPKCS11 = PR_FALSE;
792 break;
794 case SSL_NO_LOCKS:
795 if (on && ss->opt.fdx) {
796 PORT_SetError(SEC_ERROR_INVALID_ARGS);
797 rv = SECFailure;
799 if (on && ssl_force_locks)
800 on = PR_FALSE; /* silent override */
801 ss->opt.noLocks = on;
802 if (on) {
803 locksEverDisabled = PR_TRUE;
804 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
805 } else if (!holdingLocks) {
806 rv = ssl_MakeLocks(ss);
807 if (rv != SECSuccess) {
808 ss->opt.noLocks = PR_TRUE;
811 break;
813 case SSL_ENABLE_SESSION_TICKETS:
814 ss->opt.enableSessionTickets = on;
815 break;
817 case SSL_ENABLE_DEFLATE:
818 ss->opt.enableDeflate = on;
819 break;
821 case SSL_ENABLE_RENEGOTIATION:
822 ss->opt.enableRenegotiation = on;
823 break;
825 case SSL_REQUIRE_SAFE_NEGOTIATION:
826 ss->opt.requireSafeNegotiation = on;
827 break;
829 case SSL_ENABLE_FALSE_START:
830 ss->opt.enableFalseStart = on;
831 break;
833 case SSL_CBC_RANDOM_IV:
834 ss->opt.cbcRandomIV = on;
835 break;
837 case SSL_ENABLE_OCSP_STAPLING:
838 ss->opt.enableOCSPStapling = on;
839 break;
841 default:
842 PORT_SetError(SEC_ERROR_INVALID_ARGS);
843 rv = SECFailure;
846 /* We can't use the macros for releasing the locks here,
847 * because ss->opt.noLocks might have changed just above.
848 * We must release these locks (monitors) here, if we aquired them above,
849 * regardless of the current value of ss->opt.noLocks.
851 if (holdingLocks) {
852 PZ_ExitMonitor((ss)->ssl3HandshakeLock);
853 PZ_ExitMonitor((ss)->firstHandshakeLock);
856 return rv;
859 SECStatus
860 SSL_OptionGet(PRFileDesc *fd, PRInt32 which, PRBool *pOn)
862 sslSocket *ss = ssl_FindSocket(fd);
863 SECStatus rv = SECSuccess;
864 PRBool on = PR_FALSE;
866 if (!pOn) {
867 PORT_SetError(SEC_ERROR_INVALID_ARGS);
868 return SECFailure;
870 if (!ss) {
871 SSL_DBG(("%d: SSL[%d]: bad socket in Enable", SSL_GETPID(), fd));
872 *pOn = PR_FALSE;
873 return SECFailure;
876 ssl_Get1stHandshakeLock(ss);
877 ssl_GetSSL3HandshakeLock(ss);
879 switch (which) {
880 case SSL_SOCKS: on = PR_FALSE; break;
881 case SSL_SECURITY: on = ss->opt.useSecurity; break;
882 case SSL_REQUEST_CERTIFICATE: on = ss->opt.requestCertificate; break;
883 case SSL_REQUIRE_CERTIFICATE: on = ss->opt.requireCertificate; break;
884 case SSL_HANDSHAKE_AS_CLIENT: on = ss->opt.handshakeAsClient; break;
885 case SSL_HANDSHAKE_AS_SERVER: on = ss->opt.handshakeAsServer; break;
886 case SSL_ENABLE_TLS:
887 on = ss->vrange.max >= SSL_LIBRARY_VERSION_TLS_1_0;
888 break;
889 case SSL_ENABLE_SSL3:
890 on = ss->vrange.min == SSL_LIBRARY_VERSION_3_0;
891 break;
892 case SSL_ENABLE_SSL2: on = ss->opt.enableSSL2; break;
893 case SSL_NO_CACHE: on = ss->opt.noCache; break;
894 case SSL_ENABLE_FDX: on = ss->opt.fdx; break;
895 case SSL_V2_COMPATIBLE_HELLO: on = ss->opt.v2CompatibleHello; break;
896 case SSL_ROLLBACK_DETECTION: on = ss->opt.detectRollBack; break;
897 case SSL_NO_STEP_DOWN: on = ss->opt.noStepDown; break;
898 case SSL_BYPASS_PKCS11: on = ss->opt.bypassPKCS11; break;
899 case SSL_NO_LOCKS: on = ss->opt.noLocks; break;
900 case SSL_ENABLE_SESSION_TICKETS:
901 on = ss->opt.enableSessionTickets;
902 break;
903 case SSL_ENABLE_DEFLATE: on = ss->opt.enableDeflate; break;
904 case SSL_ENABLE_RENEGOTIATION:
905 on = ss->opt.enableRenegotiation; break;
906 case SSL_REQUIRE_SAFE_NEGOTIATION:
907 on = ss->opt.requireSafeNegotiation; break;
908 case SSL_ENABLE_FALSE_START: on = ss->opt.enableFalseStart; break;
909 case SSL_CBC_RANDOM_IV: on = ss->opt.cbcRandomIV; break;
910 case SSL_ENABLE_OCSP_STAPLING: on = ss->opt.enableOCSPStapling; break;
912 default:
913 PORT_SetError(SEC_ERROR_INVALID_ARGS);
914 rv = SECFailure;
917 ssl_ReleaseSSL3HandshakeLock(ss);
918 ssl_Release1stHandshakeLock(ss);
920 *pOn = on;
921 return rv;
924 SECStatus
925 SSL_OptionGetDefault(PRInt32 which, PRBool *pOn)
927 SECStatus rv = SECSuccess;
928 PRBool on = PR_FALSE;
930 if (!pOn) {
931 PORT_SetError(SEC_ERROR_INVALID_ARGS);
932 return SECFailure;
935 ssl_SetDefaultsFromEnvironment();
937 switch (which) {
938 case SSL_SOCKS: on = PR_FALSE; break;
939 case SSL_SECURITY: on = ssl_defaults.useSecurity; break;
940 case SSL_REQUEST_CERTIFICATE: on = ssl_defaults.requestCertificate; break;
941 case SSL_REQUIRE_CERTIFICATE: on = ssl_defaults.requireCertificate; break;
942 case SSL_HANDSHAKE_AS_CLIENT: on = ssl_defaults.handshakeAsClient; break;
943 case SSL_HANDSHAKE_AS_SERVER: on = ssl_defaults.handshakeAsServer; break;
944 case SSL_ENABLE_TLS:
945 on = versions_defaults_stream.max >= SSL_LIBRARY_VERSION_TLS_1_0;
946 break;
947 case SSL_ENABLE_SSL3:
948 on = versions_defaults_stream.min == SSL_LIBRARY_VERSION_3_0;
949 break;
950 case SSL_ENABLE_SSL2: on = ssl_defaults.enableSSL2; break;
951 case SSL_NO_CACHE: on = ssl_defaults.noCache; break;
952 case SSL_ENABLE_FDX: on = ssl_defaults.fdx; break;
953 case SSL_V2_COMPATIBLE_HELLO: on = ssl_defaults.v2CompatibleHello; break;
954 case SSL_ROLLBACK_DETECTION: on = ssl_defaults.detectRollBack; break;
955 case SSL_NO_STEP_DOWN: on = ssl_defaults.noStepDown; break;
956 case SSL_BYPASS_PKCS11: on = ssl_defaults.bypassPKCS11; break;
957 case SSL_NO_LOCKS: on = ssl_defaults.noLocks; break;
958 case SSL_ENABLE_SESSION_TICKETS:
959 on = ssl_defaults.enableSessionTickets;
960 break;
961 case SSL_ENABLE_DEFLATE: on = ssl_defaults.enableDeflate; break;
962 case SSL_ENABLE_RENEGOTIATION:
963 on = ssl_defaults.enableRenegotiation; break;
964 case SSL_REQUIRE_SAFE_NEGOTIATION:
965 on = ssl_defaults.requireSafeNegotiation;
966 break;
967 case SSL_ENABLE_FALSE_START: on = ssl_defaults.enableFalseStart; break;
968 case SSL_CBC_RANDOM_IV: on = ssl_defaults.cbcRandomIV; break;
969 case SSL_ENABLE_OCSP_STAPLING:
970 on = ssl_defaults.enableOCSPStapling;
971 break;
973 default:
974 PORT_SetError(SEC_ERROR_INVALID_ARGS);
975 rv = SECFailure;
978 *pOn = on;
979 return rv;
982 /* XXX Use Global Lock to protect this stuff. */
983 SECStatus
984 SSL_EnableDefault(int which, PRBool on)
986 return SSL_OptionSetDefault(which, on);
989 SECStatus
990 SSL_OptionSetDefault(PRInt32 which, PRBool on)
992 SECStatus status = ssl_Init();
994 if (status != SECSuccess) {
995 return status;
998 ssl_SetDefaultsFromEnvironment();
1000 switch (which) {
1001 case SSL_SOCKS:
1002 ssl_defaults.useSocks = PR_FALSE;
1003 if (on) {
1004 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1005 return SECFailure;
1007 break;
1009 case SSL_SECURITY:
1010 ssl_defaults.useSecurity = on;
1011 break;
1013 case SSL_REQUEST_CERTIFICATE:
1014 ssl_defaults.requestCertificate = on;
1015 break;
1017 case SSL_REQUIRE_CERTIFICATE:
1018 ssl_defaults.requireCertificate = on;
1019 break;
1021 case SSL_HANDSHAKE_AS_CLIENT:
1022 if ( ssl_defaults.handshakeAsServer && on ) {
1023 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1024 return SECFailure;
1026 ssl_defaults.handshakeAsClient = on;
1027 break;
1029 case SSL_HANDSHAKE_AS_SERVER:
1030 if ( ssl_defaults.handshakeAsClient && on ) {
1031 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1032 return SECFailure;
1034 ssl_defaults.handshakeAsServer = on;
1035 break;
1037 case SSL_ENABLE_TLS:
1038 ssl_EnableTLS(&versions_defaults_stream, on);
1039 break;
1041 case SSL_ENABLE_SSL3:
1042 ssl_EnableSSL3(&versions_defaults_stream, on);
1043 break;
1045 case SSL_ENABLE_SSL2:
1046 ssl_defaults.enableSSL2 = on;
1047 if (on) {
1048 ssl_defaults.v2CompatibleHello = on;
1050 break;
1052 case SSL_NO_CACHE:
1053 ssl_defaults.noCache = on;
1054 break;
1056 case SSL_ENABLE_FDX:
1057 if (on && ssl_defaults.noLocks) {
1058 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1059 return SECFailure;
1061 ssl_defaults.fdx = on;
1062 break;
1064 case SSL_V2_COMPATIBLE_HELLO:
1065 ssl_defaults.v2CompatibleHello = on;
1066 if (!on) {
1067 ssl_defaults.enableSSL2 = on;
1069 break;
1071 case SSL_ROLLBACK_DETECTION:
1072 ssl_defaults.detectRollBack = on;
1073 break;
1075 case SSL_NO_STEP_DOWN:
1076 ssl_defaults.noStepDown = on;
1077 if (on)
1078 SSL_DisableDefaultExportCipherSuites();
1079 break;
1081 case SSL_BYPASS_PKCS11:
1082 if (PR_FALSE != on) {
1083 if (PR_SUCCESS == SSL_BypassSetup()) {
1084 #ifdef NO_PKCS11_BYPASS
1085 ssl_defaults.bypassPKCS11 = PR_FALSE;
1086 #else
1087 ssl_defaults.bypassPKCS11 = on;
1088 #endif
1089 } else {
1090 return SECFailure;
1092 } else {
1093 ssl_defaults.bypassPKCS11 = PR_FALSE;
1095 break;
1097 case SSL_NO_LOCKS:
1098 if (on && ssl_defaults.fdx) {
1099 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1100 return SECFailure;
1102 if (on && ssl_force_locks)
1103 on = PR_FALSE; /* silent override */
1104 ssl_defaults.noLocks = on;
1105 if (on) {
1106 locksEverDisabled = PR_TRUE;
1107 strcpy(lockStatus + LOCKSTATUS_OFFSET, "DISABLED.");
1109 break;
1111 case SSL_ENABLE_SESSION_TICKETS:
1112 ssl_defaults.enableSessionTickets = on;
1113 break;
1115 case SSL_ENABLE_DEFLATE:
1116 ssl_defaults.enableDeflate = on;
1117 break;
1119 case SSL_ENABLE_RENEGOTIATION:
1120 ssl_defaults.enableRenegotiation = on;
1121 break;
1123 case SSL_REQUIRE_SAFE_NEGOTIATION:
1124 ssl_defaults.requireSafeNegotiation = on;
1125 break;
1127 case SSL_ENABLE_FALSE_START:
1128 ssl_defaults.enableFalseStart = on;
1129 break;
1131 case SSL_CBC_RANDOM_IV:
1132 ssl_defaults.cbcRandomIV = on;
1133 break;
1135 case SSL_ENABLE_OCSP_STAPLING:
1136 ssl_defaults.enableOCSPStapling = on;
1137 break;
1139 default:
1140 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1141 return SECFailure;
1143 return SECSuccess;
1146 /* function tells us if the cipher suite is one that we no longer support. */
1147 static PRBool
1148 ssl_IsRemovedCipherSuite(PRInt32 suite)
1150 switch (suite) {
1151 case SSL_FORTEZZA_DMS_WITH_NULL_SHA:
1152 case SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA:
1153 case SSL_FORTEZZA_DMS_WITH_RC4_128_SHA:
1154 return PR_TRUE;
1155 default:
1156 return PR_FALSE;
1160 /* Part of the public NSS API.
1161 * Since this is a global (not per-socket) setting, we cannot use the
1162 * HandshakeLock to protect this. Probably want a global lock.
1164 SECStatus
1165 SSL_SetPolicy(long which, int policy)
1167 if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1168 /* one of the two old FIPS ciphers */
1169 if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1170 which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1171 else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1172 which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1174 if (ssl_IsRemovedCipherSuite(which))
1175 return SECSuccess;
1176 return SSL_CipherPolicySet(which, policy);
1179 SECStatus
1180 SSL_CipherPolicySet(PRInt32 which, PRInt32 policy)
1182 SECStatus rv = ssl_Init();
1184 if (rv != SECSuccess) {
1185 return rv;
1188 if (ssl_IsRemovedCipherSuite(which)) {
1189 rv = SECSuccess;
1190 } else if (SSL_IS_SSL2_CIPHER(which)) {
1191 rv = ssl2_SetPolicy(which, policy);
1192 } else {
1193 rv = ssl3_SetPolicy((ssl3CipherSuite)which, policy);
1195 return rv;
1198 SECStatus
1199 SSL_CipherPolicyGet(PRInt32 which, PRInt32 *oPolicy)
1201 SECStatus rv;
1203 if (!oPolicy) {
1204 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1205 return SECFailure;
1207 if (ssl_IsRemovedCipherSuite(which)) {
1208 *oPolicy = SSL_NOT_ALLOWED;
1209 rv = SECSuccess;
1210 } else if (SSL_IS_SSL2_CIPHER(which)) {
1211 rv = ssl2_GetPolicy(which, oPolicy);
1212 } else {
1213 rv = ssl3_GetPolicy((ssl3CipherSuite)which, oPolicy);
1215 return rv;
1218 /* Part of the public NSS API.
1219 * Since this is a global (not per-socket) setting, we cannot use the
1220 * HandshakeLock to protect this. Probably want a global lock.
1221 * These changes have no effect on any sslSockets already created.
1223 SECStatus
1224 SSL_EnableCipher(long which, PRBool enabled)
1226 if ((which & 0xfffe) == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA) {
1227 /* one of the two old FIPS ciphers */
1228 if (which == SSL_RSA_OLDFIPS_WITH_3DES_EDE_CBC_SHA)
1229 which = SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA;
1230 else if (which == SSL_RSA_OLDFIPS_WITH_DES_CBC_SHA)
1231 which = SSL_RSA_FIPS_WITH_DES_CBC_SHA;
1233 if (ssl_IsRemovedCipherSuite(which))
1234 return SECSuccess;
1235 return SSL_CipherPrefSetDefault(which, enabled);
1238 SECStatus
1239 SSL_CipherPrefSetDefault(PRInt32 which, PRBool enabled)
1241 SECStatus rv = ssl_Init();
1243 if (rv != SECSuccess) {
1244 return rv;
1247 if (ssl_IsRemovedCipherSuite(which))
1248 return SECSuccess;
1249 if (enabled && ssl_defaults.noStepDown && SSL_IsExportCipherSuite(which)) {
1250 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1251 return SECFailure;
1253 if (SSL_IS_SSL2_CIPHER(which)) {
1254 rv = ssl2_CipherPrefSetDefault(which, enabled);
1255 } else {
1256 rv = ssl3_CipherPrefSetDefault((ssl3CipherSuite)which, enabled);
1258 return rv;
1261 SECStatus
1262 SSL_CipherPrefGetDefault(PRInt32 which, PRBool *enabled)
1264 SECStatus rv;
1266 if (!enabled) {
1267 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1268 return SECFailure;
1270 if (ssl_IsRemovedCipherSuite(which)) {
1271 *enabled = PR_FALSE;
1272 rv = SECSuccess;
1273 } else if (SSL_IS_SSL2_CIPHER(which)) {
1274 rv = ssl2_CipherPrefGetDefault(which, enabled);
1275 } else {
1276 rv = ssl3_CipherPrefGetDefault((ssl3CipherSuite)which, enabled);
1278 return rv;
1281 SECStatus
1282 SSL_CipherPrefSet(PRFileDesc *fd, PRInt32 which, PRBool enabled)
1284 SECStatus rv;
1285 sslSocket *ss = ssl_FindSocket(fd);
1287 if (!ss) {
1288 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefSet", SSL_GETPID(), fd));
1289 return SECFailure;
1291 if (ssl_IsRemovedCipherSuite(which))
1292 return SECSuccess;
1293 if (enabled && ss->opt.noStepDown && SSL_IsExportCipherSuite(which)) {
1294 PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
1295 return SECFailure;
1297 if (SSL_IS_SSL2_CIPHER(which)) {
1298 rv = ssl2_CipherPrefSet(ss, which, enabled);
1299 } else {
1300 rv = ssl3_CipherPrefSet(ss, (ssl3CipherSuite)which, enabled);
1302 return rv;
1305 SECStatus
1306 SSL_CipherPrefGet(PRFileDesc *fd, PRInt32 which, PRBool *enabled)
1308 SECStatus rv;
1309 sslSocket *ss = ssl_FindSocket(fd);
1311 if (!enabled) {
1312 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1313 return SECFailure;
1315 if (!ss) {
1316 SSL_DBG(("%d: SSL[%d]: bad socket in CipherPrefGet", SSL_GETPID(), fd));
1317 *enabled = PR_FALSE;
1318 return SECFailure;
1320 if (ssl_IsRemovedCipherSuite(which)) {
1321 *enabled = PR_FALSE;
1322 rv = SECSuccess;
1323 } else if (SSL_IS_SSL2_CIPHER(which)) {
1324 rv = ssl2_CipherPrefGet(ss, which, enabled);
1325 } else {
1326 rv = ssl3_CipherPrefGet(ss, (ssl3CipherSuite)which, enabled);
1328 return rv;
1331 SECStatus
1332 NSS_SetDomesticPolicy(void)
1334 SECStatus status = SECSuccess;
1335 cipherPolicy * policy;
1337 for (policy = ssl_ciphers; policy->cipher != 0; ++policy) {
1338 status = SSL_SetPolicy(policy->cipher, SSL_ALLOWED);
1339 if (status != SECSuccess)
1340 break;
1342 return status;
1345 SECStatus
1346 NSS_SetExportPolicy(void)
1348 return NSS_SetDomesticPolicy();
1351 SECStatus
1352 NSS_SetFrancePolicy(void)
1354 return NSS_SetDomesticPolicy();
1357 SECStatus
1358 SSL_GetChannelBinding(PRFileDesc *fd,
1359 SSLChannelBindingType binding_type,
1360 unsigned char *out,
1361 unsigned int *outLen,
1362 unsigned int outLenMax) {
1363 sslSocket *ss = ssl_FindSocket(fd);
1365 if (!ss) {
1366 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetChannelBinding",
1367 SSL_GETPID(), fd));
1368 return SECFailure;
1371 if (binding_type != SSL_CHANNEL_BINDING_TLS_UNIQUE) {
1372 PORT_SetError(PR_INVALID_ARGUMENT_ERROR);
1373 return SECFailure;
1376 return ssl3_GetTLSUniqueChannelBinding(ss, out, outLen, outLenMax);
1380 /* LOCKS ??? XXX */
1381 static PRFileDesc *
1382 ssl_ImportFD(PRFileDesc *model, PRFileDesc *fd, SSLProtocolVariant variant)
1384 sslSocket * ns = NULL;
1385 PRStatus rv;
1386 PRNetAddr addr;
1387 SECStatus status = ssl_Init();
1389 if (status != SECSuccess) {
1390 return NULL;
1393 if (model == NULL) {
1394 /* Just create a default socket if we're given NULL for the model */
1395 ns = ssl_NewSocket((PRBool)(!ssl_defaults.noLocks), variant);
1396 } else {
1397 sslSocket * ss = ssl_FindSocket(model);
1398 if (ss == NULL || ss->protocolVariant != variant) {
1399 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ImportFD",
1400 SSL_GETPID(), model));
1401 return NULL;
1403 ns = ssl_DupSocket(ss);
1405 if (ns == NULL)
1406 return NULL;
1408 rv = ssl_PushIOLayer(ns, fd, PR_TOP_IO_LAYER);
1409 if (rv != PR_SUCCESS) {
1410 ssl_FreeSocket(ns);
1411 SET_ERROR_CODE
1412 return NULL;
1414 #ifdef _WIN32
1415 PR_Sleep(PR_INTERVAL_NO_WAIT); /* workaround NT winsock connect bug. */
1416 #endif
1417 ns = ssl_FindSocket(fd);
1418 PORT_Assert(ns);
1419 if (ns)
1420 ns->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ns, &addr));
1421 return fd;
1424 PRFileDesc *
1425 SSL_ImportFD(PRFileDesc *model, PRFileDesc *fd)
1427 return ssl_ImportFD(model, fd, ssl_variant_stream);
1430 PRFileDesc *
1431 DTLS_ImportFD(PRFileDesc *model, PRFileDesc *fd)
1433 return ssl_ImportFD(model, fd, ssl_variant_datagram);
1436 SECStatus
1437 SSL_SetNextProtoCallback(PRFileDesc *fd, SSLNextProtoCallback callback,
1438 void *arg)
1440 sslSocket *ss = ssl_FindSocket(fd);
1442 if (!ss) {
1443 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoCallback", SSL_GETPID(),
1444 fd));
1445 return SECFailure;
1448 ssl_GetSSL3HandshakeLock(ss);
1449 ss->nextProtoCallback = callback;
1450 ss->nextProtoArg = arg;
1451 ssl_ReleaseSSL3HandshakeLock(ss);
1453 return SECSuccess;
1456 /* ssl_NextProtoNegoCallback is set as an NPN callback for the case when
1457 * SSL_SetNextProtoNego is used.
1459 static SECStatus
1460 ssl_NextProtoNegoCallback(void *arg, PRFileDesc *fd,
1461 const unsigned char *protos, unsigned int protos_len,
1462 unsigned char *protoOut, unsigned int *protoOutLen,
1463 unsigned int protoMaxLen)
1465 unsigned int i, j;
1466 const unsigned char *result;
1467 sslSocket *ss = ssl_FindSocket(fd);
1469 if (!ss) {
1470 SSL_DBG(("%d: SSL[%d]: bad socket in ssl_NextProtoNegoCallback",
1471 SSL_GETPID(), fd));
1472 return SECFailure;
1475 if (protos_len == 0) {
1476 /* The server supports the extension, but doesn't have any protocols
1477 * configured. In this case we request our favoured protocol. */
1478 goto pick_first;
1481 /* For each protocol in server preference, see if we support it. */
1482 for (i = 0; i < protos_len; ) {
1483 for (j = 0; j < ss->opt.nextProtoNego.len; ) {
1484 if (protos[i] == ss->opt.nextProtoNego.data[j] &&
1485 PORT_Memcmp(&protos[i+1], &ss->opt.nextProtoNego.data[j+1],
1486 protos[i]) == 0) {
1487 /* We found a match. */
1488 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NEGOTIATED;
1489 result = &protos[i];
1490 goto found;
1492 j += 1 + (unsigned int)ss->opt.nextProtoNego.data[j];
1494 i += 1 + (unsigned int)protos[i];
1497 pick_first:
1498 ss->ssl3.nextProtoState = SSL_NEXT_PROTO_NO_OVERLAP;
1499 result = ss->opt.nextProtoNego.data;
1501 found:
1502 if (protoMaxLen < result[0]) {
1503 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1504 return SECFailure;
1506 memcpy(protoOut, result + 1, result[0]);
1507 *protoOutLen = result[0];
1508 return SECSuccess;
1511 SECStatus
1512 SSL_SetNextProtoNego(PRFileDesc *fd, const unsigned char *data,
1513 unsigned int length)
1515 sslSocket *ss;
1516 SECStatus rv;
1517 SECItem dataItem = { siBuffer, (unsigned char *) data, length };
1519 ss = ssl_FindSocket(fd);
1520 if (!ss) {
1521 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetNextProtoNego",
1522 SSL_GETPID(), fd));
1523 return SECFailure;
1526 if (ssl3_ValidateNextProtoNego(data, length) != SECSuccess)
1527 return SECFailure;
1529 ssl_GetSSL3HandshakeLock(ss);
1530 SECITEM_FreeItem(&ss->opt.nextProtoNego, PR_FALSE);
1531 rv = SECITEM_CopyItem(NULL, &ss->opt.nextProtoNego, &dataItem);
1532 ssl_ReleaseSSL3HandshakeLock(ss);
1534 if (rv != SECSuccess)
1535 return rv;
1537 return SSL_SetNextProtoCallback(fd, ssl_NextProtoNegoCallback, NULL);
1540 SECStatus
1541 SSL_GetNextProto(PRFileDesc *fd, SSLNextProtoState *state, unsigned char *buf,
1542 unsigned int *bufLen, unsigned int bufLenMax)
1544 sslSocket *ss = ssl_FindSocket(fd);
1546 if (!ss) {
1547 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetNextProto", SSL_GETPID(),
1548 fd));
1549 return SECFailure;
1552 if (!state || !buf || !bufLen) {
1553 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1554 return SECFailure;
1557 *state = ss->ssl3.nextProtoState;
1559 if (ss->ssl3.nextProtoState != SSL_NEXT_PROTO_NO_SUPPORT &&
1560 ss->ssl3.nextProto.data) {
1561 if (ss->ssl3.nextProto.len > bufLenMax) {
1562 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1563 return SECFailure;
1565 PORT_Memcpy(buf, ss->ssl3.nextProto.data, ss->ssl3.nextProto.len);
1566 *bufLen = ss->ssl3.nextProto.len;
1567 } else {
1568 *bufLen = 0;
1571 return SECSuccess;
1574 SECStatus SSL_SetSRTPCiphers(PRFileDesc *fd,
1575 const PRUint16 *ciphers,
1576 unsigned int numCiphers)
1578 sslSocket *ss;
1579 unsigned int i;
1581 ss = ssl_FindSocket(fd);
1582 if (!ss || !IS_DTLS(ss)) {
1583 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetSRTPCiphers",
1584 SSL_GETPID(), fd));
1585 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1586 return SECFailure;
1589 if (numCiphers > MAX_DTLS_SRTP_CIPHER_SUITES) {
1590 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1591 return SECFailure;
1594 ss->ssl3.dtlsSRTPCipherCount = 0;
1595 for (i = 0; i < numCiphers; i++) {
1596 const PRUint16 *srtpCipher = srtpCiphers;
1598 while (*srtpCipher) {
1599 if (ciphers[i] == *srtpCipher)
1600 break;
1601 srtpCipher++;
1603 if (*srtpCipher) {
1604 ss->ssl3.dtlsSRTPCiphers[ss->ssl3.dtlsSRTPCipherCount++] =
1605 ciphers[i];
1606 } else {
1607 SSL_DBG(("%d: SSL[%d]: invalid or unimplemented SRTP cipher "
1608 "suite specified: 0x%04hx", SSL_GETPID(), fd,
1609 ciphers[i]));
1613 if (ss->ssl3.dtlsSRTPCipherCount == 0) {
1614 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1615 return SECFailure;
1618 return SECSuccess;
1621 SECStatus
1622 SSL_GetSRTPCipher(PRFileDesc *fd, PRUint16 *cipher)
1624 sslSocket * ss;
1626 ss = ssl_FindSocket(fd);
1627 if (!ss) {
1628 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetSRTPCipher",
1629 SSL_GETPID(), fd));
1630 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1631 return SECFailure;
1634 if (!ss->ssl3.dtlsSRTPCipherSuite) {
1635 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1636 return SECFailure;
1639 *cipher = ss->ssl3.dtlsSRTPCipherSuite;
1640 return SECSuccess;
1643 PRFileDesc *
1644 SSL_ReconfigFD(PRFileDesc *model, PRFileDesc *fd)
1646 PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
1647 PR_NOT_REACHED("not implemented");
1648 return NULL;
1650 #if 0
1651 sslSocket * sm = NULL, *ss = NULL;
1652 int i;
1653 sslServerCerts * mc = NULL;
1654 sslServerCerts * sc = NULL;
1656 if (model == NULL) {
1657 PR_SetError(SEC_ERROR_INVALID_ARGS, 0);
1658 return NULL;
1660 sm = ssl_FindSocket(model);
1661 if (sm == NULL) {
1662 SSL_DBG(("%d: SSL[%d]: bad model socket in ssl_ReconfigFD",
1663 SSL_GETPID(), model));
1664 return NULL;
1666 ss = ssl_FindSocket(fd);
1667 PORT_Assert(ss);
1668 if (ss == NULL) {
1669 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1670 return NULL;
1673 ss->opt = sm->opt;
1674 ss->vrange = sm->vrange;
1675 PORT_Memcpy(ss->cipherSuites, sm->cipherSuites, sizeof sm->cipherSuites);
1676 PORT_Memcpy(ss->ssl3.dtlsSRTPCiphers, sm->ssl3.dtlsSRTPCiphers,
1677 sizeof(PRUint16) * sm->ssl3.dtlsSRTPCipherCount);
1678 ss->ssl3.dtlsSRTPCipherCount = sm->ssl3.dtlsSRTPCipherCount;
1680 if (!ss->opt.useSecurity) {
1681 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1682 return NULL;
1684 /* This int should be SSLKEAType, but CC on Irix complains,
1685 * during the for loop.
1687 for (i=kt_null; i < kt_kea_size; i++) {
1688 mc = &(sm->serverCerts[i]);
1689 sc = &(ss->serverCerts[i]);
1690 if (mc->serverCert && mc->serverCertChain) {
1691 if (sc->serverCert) {
1692 CERT_DestroyCertificate(sc->serverCert);
1694 sc->serverCert = CERT_DupCertificate(mc->serverCert);
1695 if (sc->serverCertChain) {
1696 CERT_DestroyCertificateList(sc->serverCertChain);
1698 sc->serverCertChain = CERT_DupCertList(mc->serverCertChain);
1699 if (!sc->serverCertChain)
1700 goto loser;
1702 if (mc->serverKeyPair) {
1703 if (sc->serverKeyPair) {
1704 ssl3_FreeKeyPair(sc->serverKeyPair);
1706 sc->serverKeyPair = ssl3_GetKeyPairRef(mc->serverKeyPair);
1707 sc->serverKeyBits = mc->serverKeyBits;
1710 if (sm->stepDownKeyPair) {
1711 if (ss->stepDownKeyPair) {
1712 ssl3_FreeKeyPair(ss->stepDownKeyPair);
1714 ss->stepDownKeyPair = ssl3_GetKeyPairRef(sm->stepDownKeyPair);
1716 if (sm->ephemeralECDHKeyPair) {
1717 if (ss->ephemeralECDHKeyPair) {
1718 ssl3_FreeKeyPair(ss->ephemeralECDHKeyPair);
1720 ss->ephemeralECDHKeyPair =
1721 ssl3_GetKeyPairRef(sm->ephemeralECDHKeyPair);
1723 /* copy trust anchor names */
1724 if (sm->ssl3.ca_list) {
1725 if (ss->ssl3.ca_list) {
1726 CERT_FreeDistNames(ss->ssl3.ca_list);
1728 ss->ssl3.ca_list = CERT_DupDistNames(sm->ssl3.ca_list);
1729 if (!ss->ssl3.ca_list) {
1730 goto loser;
1734 if (sm->authCertificate)
1735 ss->authCertificate = sm->authCertificate;
1736 if (sm->authCertificateArg)
1737 ss->authCertificateArg = sm->authCertificateArg;
1738 if (sm->getClientAuthData)
1739 ss->getClientAuthData = sm->getClientAuthData;
1740 if (sm->getClientAuthDataArg)
1741 ss->getClientAuthDataArg = sm->getClientAuthDataArg;
1742 #ifdef NSS_PLATFORM_CLIENT_AUTH
1743 if (sm->getPlatformClientAuthData)
1744 ss->getPlatformClientAuthData = sm->getPlatformClientAuthData;
1745 if (sm->getPlatformClientAuthDataArg)
1746 ss->getPlatformClientAuthDataArg = sm->getPlatformClientAuthDataArg;
1747 #endif
1748 if (sm->sniSocketConfig)
1749 ss->sniSocketConfig = sm->sniSocketConfig;
1750 if (sm->sniSocketConfigArg)
1751 ss->sniSocketConfigArg = sm->sniSocketConfigArg;
1752 if (sm->handleBadCert)
1753 ss->handleBadCert = sm->handleBadCert;
1754 if (sm->badCertArg)
1755 ss->badCertArg = sm->badCertArg;
1756 if (sm->handshakeCallback)
1757 ss->handshakeCallback = sm->handshakeCallback;
1758 if (sm->handshakeCallbackData)
1759 ss->handshakeCallbackData = sm->handshakeCallbackData;
1760 if (sm->pkcs11PinArg)
1761 ss->pkcs11PinArg = sm->pkcs11PinArg;
1762 if (sm->getChannelID)
1763 ss->getChannelID = sm->getChannelID;
1764 if (sm->getChannelIDArg)
1765 ss->getChannelIDArg = sm->getChannelIDArg;
1766 return fd;
1767 loser:
1768 return NULL;
1769 #endif
1772 PRBool
1773 ssl3_VersionIsSupported(SSLProtocolVariant protocolVariant,
1774 SSL3ProtocolVersion version)
1776 switch (protocolVariant) {
1777 case ssl_variant_stream:
1778 return (version >= SSL_LIBRARY_VERSION_3_0 &&
1779 version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
1780 case ssl_variant_datagram:
1781 return (version >= SSL_LIBRARY_VERSION_TLS_1_1 &&
1782 version <= SSL_LIBRARY_VERSION_MAX_SUPPORTED);
1783 default:
1784 /* Can't get here */
1785 PORT_Assert(PR_FALSE);
1786 return PR_FALSE;
1790 /* Returns PR_TRUE if the given version range is valid and
1791 ** fully supported; otherwise, returns PR_FALSE.
1793 static PRBool
1794 ssl3_VersionRangeIsValid(SSLProtocolVariant protocolVariant,
1795 const SSLVersionRange *vrange)
1797 return vrange &&
1798 vrange->min <= vrange->max &&
1799 ssl3_VersionIsSupported(protocolVariant, vrange->min) &&
1800 ssl3_VersionIsSupported(protocolVariant, vrange->max);
1803 SECStatus
1804 SSL_VersionRangeGetSupported(SSLProtocolVariant protocolVariant,
1805 SSLVersionRange *vrange)
1807 if (!vrange) {
1808 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1809 return SECFailure;
1812 switch (protocolVariant) {
1813 case ssl_variant_stream:
1814 vrange->min = SSL_LIBRARY_VERSION_3_0;
1815 vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
1816 break;
1817 case ssl_variant_datagram:
1818 vrange->min = SSL_LIBRARY_VERSION_TLS_1_1;
1819 vrange->max = SSL_LIBRARY_VERSION_MAX_SUPPORTED;
1820 break;
1821 default:
1822 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1823 return SECFailure;
1826 return SECSuccess;
1829 SECStatus
1830 SSL_VersionRangeGetDefault(SSLProtocolVariant protocolVariant,
1831 SSLVersionRange *vrange)
1833 if ((protocolVariant != ssl_variant_stream &&
1834 protocolVariant != ssl_variant_datagram) || !vrange) {
1835 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1836 return SECFailure;
1839 *vrange = *VERSIONS_DEFAULTS(protocolVariant);
1841 return SECSuccess;
1844 SECStatus
1845 SSL_VersionRangeSetDefault(SSLProtocolVariant protocolVariant,
1846 const SSLVersionRange *vrange)
1848 if (!ssl3_VersionRangeIsValid(protocolVariant, vrange)) {
1849 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
1850 return SECFailure;
1853 *VERSIONS_DEFAULTS(protocolVariant) = *vrange;
1855 return SECSuccess;
1858 SECStatus
1859 SSL_VersionRangeGet(PRFileDesc *fd, SSLVersionRange *vrange)
1861 sslSocket *ss = ssl_FindSocket(fd);
1863 if (!ss) {
1864 SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeGet",
1865 SSL_GETPID(), fd));
1866 return SECFailure;
1869 if (!vrange) {
1870 PORT_SetError(SEC_ERROR_INVALID_ARGS);
1871 return SECFailure;
1874 ssl_Get1stHandshakeLock(ss);
1875 ssl_GetSSL3HandshakeLock(ss);
1877 *vrange = ss->vrange;
1879 ssl_ReleaseSSL3HandshakeLock(ss);
1880 ssl_Release1stHandshakeLock(ss);
1882 return SECSuccess;
1885 SECStatus
1886 SSL_VersionRangeSet(PRFileDesc *fd, const SSLVersionRange *vrange)
1888 sslSocket *ss = ssl_FindSocket(fd);
1890 if (!ss) {
1891 SSL_DBG(("%d: SSL[%d]: bad socket in SSL3_VersionRangeSet",
1892 SSL_GETPID(), fd));
1893 return SECFailure;
1896 if (!ssl3_VersionRangeIsValid(ss->protocolVariant, vrange)) {
1897 PORT_SetError(SSL_ERROR_INVALID_VERSION_RANGE);
1898 return SECFailure;
1901 ssl_Get1stHandshakeLock(ss);
1902 ssl_GetSSL3HandshakeLock(ss);
1904 ss->vrange = *vrange;
1906 ssl_ReleaseSSL3HandshakeLock(ss);
1907 ssl_Release1stHandshakeLock(ss);
1909 return SECSuccess;
1912 SECStatus
1913 SSL_GetStapledOCSPResponse(PRFileDesc *fd, unsigned char *out_data,
1914 unsigned int *len) {
1915 sslSocket *ss = ssl_FindSocket(fd);
1917 if (!ss) {
1918 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_GetStapledOCSPResponse",
1919 SSL_GETPID(), fd));
1920 return SECFailure;
1923 ssl_Get1stHandshakeLock(ss);
1924 ssl_GetSSL3HandshakeLock(ss);
1926 if (ss->ssl3.hs.cert_status.data) {
1927 unsigned int todo = ss->ssl3.hs.cert_status.len;
1928 if (todo > *len)
1929 todo = *len;
1930 *len = ss->ssl3.hs.cert_status.len;
1931 PORT_Memcpy(out_data, ss->ssl3.hs.cert_status.data, todo);
1932 } else {
1933 *len = 0;
1936 ssl_ReleaseSSL3HandshakeLock(ss);
1937 ssl_Release1stHandshakeLock(ss);
1939 return SECSuccess;
1942 SECStatus
1943 SSL_HandshakeResumedSession(PRFileDesc *fd, PRBool *handshake_resumed) {
1944 sslSocket *ss = ssl_FindSocket(fd);
1946 if (!ss) {
1947 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_HandshakeResumedSession",
1948 SSL_GETPID(), fd));
1949 return SECFailure;
1952 *handshake_resumed = ss->ssl3.hs.isResuming;
1953 return SECSuccess;
1956 const SECItem *
1957 SSL_GetRequestedClientCertificateTypes(PRFileDesc *fd)
1959 sslSocket *ss = ssl_FindSocket(fd);
1961 if (!ss) {
1962 SSL_DBG(("%d: SSL[%d]: bad socket in "
1963 "SSL_GetRequestedClientCertificateTypes", SSL_GETPID(), fd));
1964 return NULL;
1967 return ss->requestedCertTypes;
1970 /************************************************************************/
1971 /* The following functions are the TOP LEVEL SSL functions.
1972 ** They all get called through the NSPRIOMethods table below.
1975 static PRFileDesc * PR_CALLBACK
1976 ssl_Accept(PRFileDesc *fd, PRNetAddr *sockaddr, PRIntervalTime timeout)
1978 sslSocket *ss;
1979 sslSocket *ns = NULL;
1980 PRFileDesc *newfd = NULL;
1981 PRFileDesc *osfd;
1982 PRStatus status;
1984 ss = ssl_GetPrivate(fd);
1985 if (!ss) {
1986 SSL_DBG(("%d: SSL[%d]: bad socket in accept", SSL_GETPID(), fd));
1987 return NULL;
1990 /* IF this is a listen socket, there shouldn't be any I/O going on */
1991 SSL_LOCK_READER(ss);
1992 SSL_LOCK_WRITER(ss);
1993 ssl_Get1stHandshakeLock(ss);
1994 ssl_GetSSL3HandshakeLock(ss);
1996 ss->cTimeout = timeout;
1998 osfd = ss->fd->lower;
2000 /* First accept connection */
2001 newfd = osfd->methods->accept(osfd, sockaddr, timeout);
2002 if (newfd == NULL) {
2003 SSL_DBG(("%d: SSL[%d]: accept failed, errno=%d",
2004 SSL_GETPID(), ss->fd, PORT_GetError()));
2005 } else {
2006 /* Create ssl module */
2007 ns = ssl_DupSocket(ss);
2010 ssl_ReleaseSSL3HandshakeLock(ss);
2011 ssl_Release1stHandshakeLock(ss);
2012 SSL_UNLOCK_WRITER(ss);
2013 SSL_UNLOCK_READER(ss); /* ss isn't used below here. */
2015 if (ns == NULL)
2016 goto loser;
2018 /* push ssl module onto the new socket */
2019 status = ssl_PushIOLayer(ns, newfd, PR_TOP_IO_LAYER);
2020 if (status != PR_SUCCESS)
2021 goto loser;
2023 /* Now start server connection handshake with client.
2024 ** Don't need locks here because nobody else has a reference to ns yet.
2026 if ( ns->opt.useSecurity ) {
2027 if ( ns->opt.handshakeAsClient ) {
2028 ns->handshake = ssl2_BeginClientHandshake;
2029 ss->handshaking = sslHandshakingAsClient;
2030 } else {
2031 ns->handshake = ssl2_BeginServerHandshake;
2032 ss->handshaking = sslHandshakingAsServer;
2035 ns->TCPconnected = 1;
2036 return newfd;
2038 loser:
2039 if (ns != NULL)
2040 ssl_FreeSocket(ns);
2041 if (newfd != NULL)
2042 PR_Close(newfd);
2043 return NULL;
2046 static PRStatus PR_CALLBACK
2047 ssl_Connect(PRFileDesc *fd, const PRNetAddr *sockaddr, PRIntervalTime timeout)
2049 sslSocket *ss;
2050 PRStatus rv;
2052 ss = ssl_GetPrivate(fd);
2053 if (!ss) {
2054 SSL_DBG(("%d: SSL[%d]: bad socket in connect", SSL_GETPID(), fd));
2055 return PR_FAILURE;
2058 /* IF this is a listen socket, there shouldn't be any I/O going on */
2059 SSL_LOCK_READER(ss);
2060 SSL_LOCK_WRITER(ss);
2062 ss->cTimeout = timeout;
2063 rv = (PRStatus)(*ss->ops->connect)(ss, sockaddr);
2064 #ifdef _WIN32
2065 PR_Sleep(PR_INTERVAL_NO_WAIT); /* workaround NT winsock connect bug. */
2066 #endif
2068 SSL_UNLOCK_WRITER(ss);
2069 SSL_UNLOCK_READER(ss);
2071 return rv;
2074 static PRStatus PR_CALLBACK
2075 ssl_Bind(PRFileDesc *fd, const PRNetAddr *addr)
2077 sslSocket * ss = ssl_GetPrivate(fd);
2078 PRStatus rv;
2080 if (!ss) {
2081 SSL_DBG(("%d: SSL[%d]: bad socket in bind", SSL_GETPID(), fd));
2082 return PR_FAILURE;
2084 SSL_LOCK_READER(ss);
2085 SSL_LOCK_WRITER(ss);
2087 rv = (PRStatus)(*ss->ops->bind)(ss, addr);
2089 SSL_UNLOCK_WRITER(ss);
2090 SSL_UNLOCK_READER(ss);
2091 return rv;
2094 static PRStatus PR_CALLBACK
2095 ssl_Listen(PRFileDesc *fd, PRIntn backlog)
2097 sslSocket * ss = ssl_GetPrivate(fd);
2098 PRStatus rv;
2100 if (!ss) {
2101 SSL_DBG(("%d: SSL[%d]: bad socket in listen", SSL_GETPID(), fd));
2102 return PR_FAILURE;
2104 SSL_LOCK_READER(ss);
2105 SSL_LOCK_WRITER(ss);
2107 rv = (PRStatus)(*ss->ops->listen)(ss, backlog);
2109 SSL_UNLOCK_WRITER(ss);
2110 SSL_UNLOCK_READER(ss);
2111 return rv;
2114 static PRStatus PR_CALLBACK
2115 ssl_Shutdown(PRFileDesc *fd, PRIntn how)
2117 sslSocket * ss = ssl_GetPrivate(fd);
2118 PRStatus rv;
2120 if (!ss) {
2121 SSL_DBG(("%d: SSL[%d]: bad socket in shutdown", SSL_GETPID(), fd));
2122 return PR_FAILURE;
2124 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
2125 SSL_LOCK_READER(ss);
2127 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
2128 SSL_LOCK_WRITER(ss);
2131 rv = (PRStatus)(*ss->ops->shutdown)(ss, how);
2133 if (how == PR_SHUTDOWN_SEND || how == PR_SHUTDOWN_BOTH) {
2134 SSL_UNLOCK_WRITER(ss);
2136 if (how == PR_SHUTDOWN_RCV || how == PR_SHUTDOWN_BOTH) {
2137 SSL_UNLOCK_READER(ss);
2139 return rv;
2142 static PRStatus PR_CALLBACK
2143 ssl_Close(PRFileDesc *fd)
2145 sslSocket *ss;
2146 PRStatus rv;
2148 ss = ssl_GetPrivate(fd);
2149 if (!ss) {
2150 SSL_DBG(("%d: SSL[%d]: bad socket in close", SSL_GETPID(), fd));
2151 return PR_FAILURE;
2154 /* There must not be any I/O going on */
2155 SSL_LOCK_READER(ss);
2156 SSL_LOCK_WRITER(ss);
2158 /* By the time this function returns,
2159 ** ss is an invalid pointer, and the locks to which it points have
2160 ** been unlocked and freed. So, this is the ONE PLACE in all of SSL
2161 ** where the LOCK calls and the corresponding UNLOCK calls are not in
2162 ** the same function scope. The unlock calls are in ssl_FreeSocket().
2164 rv = (PRStatus)(*ss->ops->close)(ss);
2166 return rv;
2169 static int PR_CALLBACK
2170 ssl_Recv(PRFileDesc *fd, void *buf, PRInt32 len, PRIntn flags,
2171 PRIntervalTime timeout)
2173 sslSocket *ss;
2174 int rv;
2176 ss = ssl_GetPrivate(fd);
2177 if (!ss) {
2178 SSL_DBG(("%d: SSL[%d]: bad socket in recv", SSL_GETPID(), fd));
2179 return SECFailure;
2181 SSL_LOCK_READER(ss);
2182 ss->rTimeout = timeout;
2183 if (!ss->opt.fdx)
2184 ss->wTimeout = timeout;
2185 rv = (*ss->ops->recv)(ss, (unsigned char*)buf, len, flags);
2186 SSL_UNLOCK_READER(ss);
2187 return rv;
2190 static int PR_CALLBACK
2191 ssl_Send(PRFileDesc *fd, const void *buf, PRInt32 len, PRIntn flags,
2192 PRIntervalTime timeout)
2194 sslSocket *ss;
2195 int rv;
2197 ss = ssl_GetPrivate(fd);
2198 if (!ss) {
2199 SSL_DBG(("%d: SSL[%d]: bad socket in send", SSL_GETPID(), fd));
2200 return SECFailure;
2202 SSL_LOCK_WRITER(ss);
2203 ss->wTimeout = timeout;
2204 if (!ss->opt.fdx)
2205 ss->rTimeout = timeout;
2206 rv = (*ss->ops->send)(ss, (const unsigned char*)buf, len, flags);
2207 SSL_UNLOCK_WRITER(ss);
2208 return rv;
2211 static int PR_CALLBACK
2212 ssl_Read(PRFileDesc *fd, void *buf, PRInt32 len)
2214 sslSocket *ss;
2215 int rv;
2217 ss = ssl_GetPrivate(fd);
2218 if (!ss) {
2219 SSL_DBG(("%d: SSL[%d]: bad socket in read", SSL_GETPID(), fd));
2220 return SECFailure;
2222 SSL_LOCK_READER(ss);
2223 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
2224 if (!ss->opt.fdx)
2225 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
2226 rv = (*ss->ops->read)(ss, (unsigned char*)buf, len);
2227 SSL_UNLOCK_READER(ss);
2228 return rv;
2231 static int PR_CALLBACK
2232 ssl_Write(PRFileDesc *fd, const void *buf, PRInt32 len)
2234 sslSocket *ss;
2235 int rv;
2237 ss = ssl_GetPrivate(fd);
2238 if (!ss) {
2239 SSL_DBG(("%d: SSL[%d]: bad socket in write", SSL_GETPID(), fd));
2240 return SECFailure;
2242 SSL_LOCK_WRITER(ss);
2243 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
2244 if (!ss->opt.fdx)
2245 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
2246 rv = (*ss->ops->write)(ss, (const unsigned char*)buf, len);
2247 SSL_UNLOCK_WRITER(ss);
2248 return rv;
2251 static PRStatus PR_CALLBACK
2252 ssl_GetPeerName(PRFileDesc *fd, PRNetAddr *addr)
2254 sslSocket *ss;
2256 ss = ssl_GetPrivate(fd);
2257 if (!ss) {
2258 SSL_DBG(("%d: SSL[%d]: bad socket in getpeername", SSL_GETPID(), fd));
2259 return PR_FAILURE;
2261 return (PRStatus)(*ss->ops->getpeername)(ss, addr);
2266 SECStatus
2267 ssl_GetPeerInfo(sslSocket *ss)
2269 PRFileDesc * osfd;
2270 int rv;
2271 PRNetAddr sin;
2273 osfd = ss->fd->lower;
2275 PORT_Memset(&sin, 0, sizeof(sin));
2276 rv = osfd->methods->getpeername(osfd, &sin);
2277 if (rv < 0) {
2278 return SECFailure;
2280 ss->TCPconnected = 1;
2281 if (sin.inet.family == PR_AF_INET) {
2282 PR_ConvertIPv4AddrToIPv6(sin.inet.ip, &ss->sec.ci.peer);
2283 ss->sec.ci.port = sin.inet.port;
2284 } else if (sin.ipv6.family == PR_AF_INET6) {
2285 ss->sec.ci.peer = sin.ipv6.ip;
2286 ss->sec.ci.port = sin.ipv6.port;
2287 } else {
2288 PORT_SetError(PR_ADDRESS_NOT_SUPPORTED_ERROR);
2289 return SECFailure;
2291 return SECSuccess;
2294 static PRStatus PR_CALLBACK
2295 ssl_GetSockName(PRFileDesc *fd, PRNetAddr *name)
2297 sslSocket *ss;
2299 ss = ssl_GetPrivate(fd);
2300 if (!ss) {
2301 SSL_DBG(("%d: SSL[%d]: bad socket in getsockname", SSL_GETPID(), fd));
2302 return PR_FAILURE;
2304 return (PRStatus)(*ss->ops->getsockname)(ss, name);
2307 SECStatus
2308 SSL_SetSockPeerID(PRFileDesc *fd, const char *peerID)
2310 sslSocket *ss;
2312 ss = ssl_FindSocket(fd);
2313 if (!ss) {
2314 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_SetCacheIndex",
2315 SSL_GETPID(), fd));
2316 return SECFailure;
2319 if (ss->peerID) {
2320 PORT_Free(ss->peerID);
2321 ss->peerID = NULL;
2323 if (peerID)
2324 ss->peerID = PORT_Strdup(peerID);
2325 return (ss->peerID || !peerID) ? SECSuccess : SECFailure;
2328 #define PR_POLL_RW (PR_POLL_WRITE | PR_POLL_READ)
2330 static PRInt16 PR_CALLBACK
2331 ssl_Poll(PRFileDesc *fd, PRInt16 how_flags, PRInt16 *p_out_flags)
2333 sslSocket *ss;
2334 PRInt16 new_flags = how_flags; /* should select on these flags. */
2335 PRNetAddr addr;
2337 *p_out_flags = 0;
2338 ss = ssl_GetPrivate(fd);
2339 if (!ss) {
2340 SSL_DBG(("%d: SSL[%d]: bad socket in SSL_Poll",
2341 SSL_GETPID(), fd));
2342 return 0; /* don't poll on this socket */
2345 if (ss->opt.useSecurity &&
2346 ss->handshaking != sslHandshakingUndetermined &&
2347 !ss->firstHsDone &&
2348 (how_flags & PR_POLL_RW)) {
2349 if (!ss->TCPconnected) {
2350 ss->TCPconnected = (PR_SUCCESS == ssl_DefGetpeername(ss, &addr));
2352 /* If it's not connected, then presumably the application is polling
2353 ** on read or write appropriately, so don't change it.
2355 if (ss->TCPconnected) {
2356 if (!ss->handshakeBegun) {
2357 /* If the handshake has not begun, poll on read or write
2358 ** based on the local application's role in the handshake,
2359 ** not based on what the application requested.
2361 new_flags &= ~PR_POLL_RW;
2362 if (ss->handshaking == sslHandshakingAsClient) {
2363 new_flags |= PR_POLL_WRITE;
2364 } else { /* handshaking as server */
2365 new_flags |= PR_POLL_READ;
2367 } else
2368 /* First handshake is in progress */
2369 if (ss->lastWriteBlocked) {
2370 if (new_flags & PR_POLL_READ) {
2371 /* The caller is waiting for data to be received,
2372 ** but the initial handshake is blocked on write, or the
2373 ** client's first handshake record has not been written.
2374 ** The code should select on write, not read.
2376 new_flags ^= PR_POLL_READ; /* don't select on read. */
2377 new_flags |= PR_POLL_WRITE; /* do select on write. */
2379 } else if (new_flags & PR_POLL_WRITE) {
2380 /* The caller is trying to write, but the handshake is
2381 ** blocked waiting for data to read, and the first
2382 ** handshake has been sent. so do NOT to poll on write.
2384 new_flags ^= PR_POLL_WRITE; /* don't select on write. */
2385 new_flags |= PR_POLL_READ; /* do select on read. */
2388 } else if ((new_flags & PR_POLL_READ) && (SSL_DataPending(fd) > 0)) {
2389 *p_out_flags = PR_POLL_READ; /* it's ready already. */
2390 return new_flags;
2391 } else if ((ss->lastWriteBlocked) && (how_flags & PR_POLL_READ) &&
2392 (ss->pendingBuf.len != 0)) { /* write data waiting to be sent */
2393 new_flags |= PR_POLL_WRITE; /* also select on write. */
2396 if (ss->version >= SSL_LIBRARY_VERSION_3_0 &&
2397 ss->ssl3.hs.restartTarget != NULL) {
2398 /* Read and write will block until the asynchronous callback completes
2399 * (e.g. until SSL_AuthCertificateComplete is called), so don't tell
2400 * the caller to poll the socket unless there is pending write data.
2402 if (ss->lastWriteBlocked && ss->pendingBuf.len != 0) {
2403 /* Ignore any newly-received data on the socket, but do wait for
2404 * the socket to become writable again. Here, it is OK for an error
2405 * to be detected, because our logic for sending pending write data
2406 * will allow us to report the error to the caller without the risk
2407 * of the application spinning.
2409 new_flags &= (PR_POLL_WRITE | PR_POLL_EXCEPT);
2410 } else {
2411 /* Unfortunately, clearing new_flags will make it impossible for
2412 * the application to detect errors that it would otherwise be
2413 * able to detect with PR_POLL_EXCEPT, until the asynchronous
2414 * callback completes. However, we must clear all the flags to
2415 * prevent the application from spinning (alternating between
2416 * calling PR_Poll that would return PR_POLL_EXCEPT, and send/recv
2417 * which won't actually report the I/O error while we are waiting
2418 * for the asynchronous callback to complete).
2420 new_flags = 0;
2424 if (new_flags && (fd->lower->methods->poll != NULL)) {
2425 PRInt16 lower_out_flags = 0;
2426 PRInt16 lower_new_flags;
2427 lower_new_flags = fd->lower->methods->poll(fd->lower, new_flags,
2428 &lower_out_flags);
2429 if ((lower_new_flags & lower_out_flags) && (how_flags != new_flags)) {
2430 PRInt16 out_flags = lower_out_flags & ~PR_POLL_RW;
2431 if (lower_out_flags & PR_POLL_READ)
2432 out_flags |= PR_POLL_WRITE;
2433 if (lower_out_flags & PR_POLL_WRITE)
2434 out_flags |= PR_POLL_READ;
2435 *p_out_flags = out_flags;
2436 new_flags = how_flags;
2437 } else {
2438 *p_out_flags = lower_out_flags;
2439 new_flags = lower_new_flags;
2443 return new_flags;
2446 static PRInt32 PR_CALLBACK
2447 ssl_TransmitFile(PRFileDesc *sd, PRFileDesc *fd,
2448 const void *headers, PRInt32 hlen,
2449 PRTransmitFileFlags flags, PRIntervalTime timeout)
2451 PRSendFileData sfd;
2453 sfd.fd = fd;
2454 sfd.file_offset = 0;
2455 sfd.file_nbytes = 0;
2456 sfd.header = headers;
2457 sfd.hlen = hlen;
2458 sfd.trailer = NULL;
2459 sfd.tlen = 0;
2461 return sd->methods->sendfile(sd, &sfd, flags, timeout);
2465 PRBool
2466 ssl_FdIsBlocking(PRFileDesc *fd)
2468 PRSocketOptionData opt;
2469 PRStatus status;
2471 opt.option = PR_SockOpt_Nonblocking;
2472 opt.value.non_blocking = PR_FALSE;
2473 status = PR_GetSocketOption(fd, &opt);
2474 if (status != PR_SUCCESS)
2475 return PR_FALSE;
2476 return (PRBool)!opt.value.non_blocking;
2479 PRBool
2480 ssl_SocketIsBlocking(sslSocket *ss)
2482 return ssl_FdIsBlocking(ss->fd);
2485 PRInt32 sslFirstBufSize = 8 * 1024;
2486 PRInt32 sslCopyLimit = 1024;
2488 static PRInt32 PR_CALLBACK
2489 ssl_WriteV(PRFileDesc *fd, const PRIOVec *iov, PRInt32 vectors,
2490 PRIntervalTime timeout)
2492 PRInt32 bufLen;
2493 PRInt32 left;
2494 PRInt32 rv;
2495 PRInt32 sent = 0;
2496 const PRInt32 first_len = sslFirstBufSize;
2497 const PRInt32 limit = sslCopyLimit;
2498 PRBool blocking;
2499 PRIOVec myIov = { 0, 0 };
2500 char buf[MAX_FRAGMENT_LENGTH];
2502 if (vectors > PR_MAX_IOVECTOR_SIZE) {
2503 PORT_SetError(PR_BUFFER_OVERFLOW_ERROR);
2504 return -1;
2506 blocking = ssl_FdIsBlocking(fd);
2508 #define K16 sizeof(buf)
2509 #define KILL_VECTORS while (vectors && !iov->iov_len) { ++iov; --vectors; }
2510 #define GET_VECTOR do { myIov = *iov++; --vectors; KILL_VECTORS } while (0)
2511 #define HANDLE_ERR(rv, len) \
2512 if (rv != len) { \
2513 if (rv < 0) { \
2514 if (!blocking \
2515 && (PR_GetError() == PR_WOULD_BLOCK_ERROR) \
2516 && (sent > 0)) { \
2517 return sent; \
2518 } else { \
2519 return -1; \
2522 /* Only a nonblocking socket can have partial sends */ \
2523 PR_ASSERT(!blocking); \
2524 return sent + rv; \
2526 #define SEND(bfr, len) \
2527 do { \
2528 rv = ssl_Send(fd, bfr, len, 0, timeout); \
2529 HANDLE_ERR(rv, len) \
2530 sent += len; \
2531 } while (0)
2533 /* Make sure the first write is at least 8 KB, if possible. */
2534 KILL_VECTORS
2535 if (!vectors)
2536 return ssl_Send(fd, 0, 0, 0, timeout);
2537 GET_VECTOR;
2538 if (!vectors) {
2539 return ssl_Send(fd, myIov.iov_base, myIov.iov_len, 0, timeout);
2541 if (myIov.iov_len < first_len) {
2542 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
2543 bufLen = myIov.iov_len;
2544 left = first_len - bufLen;
2545 while (vectors && left) {
2546 int toCopy;
2547 GET_VECTOR;
2548 toCopy = PR_MIN(left, myIov.iov_len);
2549 PORT_Memcpy(buf + bufLen, myIov.iov_base, toCopy);
2550 bufLen += toCopy;
2551 left -= toCopy;
2552 myIov.iov_base += toCopy;
2553 myIov.iov_len -= toCopy;
2555 SEND( buf, bufLen );
2558 while (vectors || myIov.iov_len) {
2559 PRInt32 addLen;
2560 if (!myIov.iov_len) {
2561 GET_VECTOR;
2563 while (myIov.iov_len >= K16) {
2564 SEND(myIov.iov_base, K16);
2565 myIov.iov_base += K16;
2566 myIov.iov_len -= K16;
2568 if (!myIov.iov_len)
2569 continue;
2571 if (!vectors || myIov.iov_len > limit) {
2572 addLen = 0;
2573 } else if ((addLen = iov->iov_len % K16) + myIov.iov_len <= limit) {
2574 /* Addlen is already computed. */;
2575 } else if (vectors > 1 &&
2576 iov[1].iov_len % K16 + addLen + myIov.iov_len <= 2 * limit) {
2577 addLen = limit - myIov.iov_len;
2578 } else
2579 addLen = 0;
2581 if (!addLen) {
2582 SEND( myIov.iov_base, myIov.iov_len );
2583 myIov.iov_len = 0;
2584 continue;
2586 PORT_Memcpy(buf, myIov.iov_base, myIov.iov_len);
2587 bufLen = myIov.iov_len;
2588 do {
2589 GET_VECTOR;
2590 PORT_Memcpy(buf + bufLen, myIov.iov_base, addLen);
2591 myIov.iov_base += addLen;
2592 myIov.iov_len -= addLen;
2593 bufLen += addLen;
2595 left = PR_MIN( limit, K16 - bufLen);
2596 if (!vectors /* no more left */
2597 || myIov.iov_len > 0 /* we didn't use that one all up */
2598 || bufLen >= K16 /* it's full. */
2600 addLen = 0;
2601 } else if ((addLen = iov->iov_len % K16) <= left) {
2602 /* Addlen is already computed. */;
2603 } else if (vectors > 1 &&
2604 iov[1].iov_len % K16 + addLen <= left + limit) {
2605 addLen = left;
2606 } else
2607 addLen = 0;
2609 } while (addLen);
2610 SEND( buf, bufLen );
2612 return sent;
2616 * These functions aren't implemented.
2619 static PRInt32 PR_CALLBACK
2620 ssl_Available(PRFileDesc *fd)
2622 PORT_Assert(0);
2623 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2624 return SECFailure;
2627 static PRInt64 PR_CALLBACK
2628 ssl_Available64(PRFileDesc *fd)
2630 PRInt64 res;
2632 PORT_Assert(0);
2633 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2634 LL_I2L(res, -1L);
2635 return res;
2638 static PRStatus PR_CALLBACK
2639 ssl_FSync(PRFileDesc *fd)
2641 PORT_Assert(0);
2642 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2643 return PR_FAILURE;
2646 static PRInt32 PR_CALLBACK
2647 ssl_Seek(PRFileDesc *fd, PRInt32 offset, PRSeekWhence how) {
2648 PORT_Assert(0);
2649 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2650 return SECFailure;
2653 static PRInt64 PR_CALLBACK
2654 ssl_Seek64(PRFileDesc *fd, PRInt64 offset, PRSeekWhence how) {
2655 PRInt64 res;
2657 PORT_Assert(0);
2658 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2659 LL_I2L(res, -1L);
2660 return res;
2663 static PRStatus PR_CALLBACK
2664 ssl_FileInfo(PRFileDesc *fd, PRFileInfo *info)
2666 PORT_Assert(0);
2667 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2668 return PR_FAILURE;
2671 static PRStatus PR_CALLBACK
2672 ssl_FileInfo64(PRFileDesc *fd, PRFileInfo64 *info)
2674 PORT_Assert(0);
2675 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2676 return PR_FAILURE;
2679 static PRInt32 PR_CALLBACK
2680 ssl_RecvFrom(PRFileDesc *fd, void *buf, PRInt32 amount, PRIntn flags,
2681 PRNetAddr *addr, PRIntervalTime timeout)
2683 PORT_Assert(0);
2684 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2685 return SECFailure;
2688 static PRInt32 PR_CALLBACK
2689 ssl_SendTo(PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
2690 const PRNetAddr *addr, PRIntervalTime timeout)
2692 PORT_Assert(0);
2693 PR_SetError(PR_NOT_IMPLEMENTED_ERROR, 0);
2694 return SECFailure;
2697 static const PRIOMethods ssl_methods = {
2698 PR_DESC_LAYERED,
2699 ssl_Close, /* close */
2700 ssl_Read, /* read */
2701 ssl_Write, /* write */
2702 ssl_Available, /* available */
2703 ssl_Available64, /* available64 */
2704 ssl_FSync, /* fsync */
2705 ssl_Seek, /* seek */
2706 ssl_Seek64, /* seek64 */
2707 ssl_FileInfo, /* fileInfo */
2708 ssl_FileInfo64, /* fileInfo64 */
2709 ssl_WriteV, /* writev */
2710 ssl_Connect, /* connect */
2711 ssl_Accept, /* accept */
2712 ssl_Bind, /* bind */
2713 ssl_Listen, /* listen */
2714 ssl_Shutdown, /* shutdown */
2715 ssl_Recv, /* recv */
2716 ssl_Send, /* send */
2717 ssl_RecvFrom, /* recvfrom */
2718 ssl_SendTo, /* sendto */
2719 ssl_Poll, /* poll */
2720 PR_EmulateAcceptRead, /* acceptread */
2721 ssl_TransmitFile, /* transmitfile */
2722 ssl_GetSockName, /* getsockname */
2723 ssl_GetPeerName, /* getpeername */
2724 NULL, /* getsockopt OBSOLETE */
2725 NULL, /* setsockopt OBSOLETE */
2726 NULL, /* getsocketoption */
2727 NULL, /* setsocketoption */
2728 PR_EmulateSendFile, /* Send a (partial) file with header/trailer*/
2729 NULL, /* reserved for future use */
2730 NULL, /* reserved for future use */
2731 NULL, /* reserved for future use */
2732 NULL, /* reserved for future use */
2733 NULL /* reserved for future use */
2737 static PRIOMethods combined_methods;
2739 static void
2740 ssl_SetupIOMethods(void)
2742 PRIOMethods *new_methods = &combined_methods;
2743 const PRIOMethods *nspr_methods = PR_GetDefaultIOMethods();
2744 const PRIOMethods *my_methods = &ssl_methods;
2746 *new_methods = *nspr_methods;
2748 new_methods->file_type = my_methods->file_type;
2749 new_methods->close = my_methods->close;
2750 new_methods->read = my_methods->read;
2751 new_methods->write = my_methods->write;
2752 new_methods->available = my_methods->available;
2753 new_methods->available64 = my_methods->available64;
2754 new_methods->fsync = my_methods->fsync;
2755 new_methods->seek = my_methods->seek;
2756 new_methods->seek64 = my_methods->seek64;
2757 new_methods->fileInfo = my_methods->fileInfo;
2758 new_methods->fileInfo64 = my_methods->fileInfo64;
2759 new_methods->writev = my_methods->writev;
2760 new_methods->connect = my_methods->connect;
2761 new_methods->accept = my_methods->accept;
2762 new_methods->bind = my_methods->bind;
2763 new_methods->listen = my_methods->listen;
2764 new_methods->shutdown = my_methods->shutdown;
2765 new_methods->recv = my_methods->recv;
2766 new_methods->send = my_methods->send;
2767 new_methods->recvfrom = my_methods->recvfrom;
2768 new_methods->sendto = my_methods->sendto;
2769 new_methods->poll = my_methods->poll;
2770 new_methods->acceptread = my_methods->acceptread;
2771 new_methods->transmitfile = my_methods->transmitfile;
2772 new_methods->getsockname = my_methods->getsockname;
2773 new_methods->getpeername = my_methods->getpeername;
2774 /* new_methods->getsocketoption = my_methods->getsocketoption; */
2775 /* new_methods->setsocketoption = my_methods->setsocketoption; */
2776 new_methods->sendfile = my_methods->sendfile;
2780 static PRCallOnceType initIoLayerOnce;
2782 static PRStatus
2783 ssl_InitIOLayer(void)
2785 ssl_layer_id = PR_GetUniqueIdentity("SSL");
2786 ssl_SetupIOMethods();
2787 ssl_inited = PR_TRUE;
2788 return PR_SUCCESS;
2791 static PRStatus
2792 ssl_PushIOLayer(sslSocket *ns, PRFileDesc *stack, PRDescIdentity id)
2794 PRFileDesc *layer = NULL;
2795 PRStatus status;
2797 if (!ssl_inited) {
2798 status = PR_CallOnce(&initIoLayerOnce, &ssl_InitIOLayer);
2799 if (status != PR_SUCCESS)
2800 goto loser;
2803 if (ns == NULL)
2804 goto loser;
2806 layer = PR_CreateIOLayerStub(ssl_layer_id, &combined_methods);
2807 if (layer == NULL)
2808 goto loser;
2809 layer->secret = (PRFilePrivate *)ns;
2811 /* Here, "stack" points to the PRFileDesc on the top of the stack.
2812 ** "layer" points to a new FD that is to be inserted into the stack.
2813 ** If layer is being pushed onto the top of the stack, then
2814 ** PR_PushIOLayer switches the contents of stack and layer, and then
2815 ** puts stack on top of layer, so that after it is done, the top of
2816 ** stack is the same "stack" as it was before, and layer is now the
2817 ** FD for the former top of stack.
2818 ** After this call, stack always points to the top PRFD on the stack.
2819 ** If this function fails, the contents of stack and layer are as
2820 ** they were before the call.
2822 status = PR_PushIOLayer(stack, id, layer);
2823 if (status != PR_SUCCESS)
2824 goto loser;
2826 ns->fd = (id == PR_TOP_IO_LAYER) ? stack : layer;
2827 return PR_SUCCESS;
2829 loser:
2830 if (layer) {
2831 layer->dtor(layer); /* free layer */
2833 return PR_FAILURE;
2836 /* if this fails, caller must destroy socket. */
2837 static SECStatus
2838 ssl_MakeLocks(sslSocket *ss)
2840 ss->firstHandshakeLock = PZ_NewMonitor(nssILockSSL);
2841 if (!ss->firstHandshakeLock)
2842 goto loser;
2843 ss->ssl3HandshakeLock = PZ_NewMonitor(nssILockSSL);
2844 if (!ss->ssl3HandshakeLock)
2845 goto loser;
2846 ss->specLock = NSSRWLock_New(SSL_LOCK_RANK_SPEC, NULL);
2847 if (!ss->specLock)
2848 goto loser;
2849 ss->recvBufLock = PZ_NewMonitor(nssILockSSL);
2850 if (!ss->recvBufLock)
2851 goto loser;
2852 ss->xmitBufLock = PZ_NewMonitor(nssILockSSL);
2853 if (!ss->xmitBufLock)
2854 goto loser;
2855 ss->writerThread = NULL;
2856 if (ssl_lock_readers) {
2857 ss->recvLock = PZ_NewLock(nssILockSSL);
2858 if (!ss->recvLock)
2859 goto loser;
2860 ss->sendLock = PZ_NewLock(nssILockSSL);
2861 if (!ss->sendLock)
2862 goto loser;
2864 return SECSuccess;
2865 loser:
2866 ssl_DestroyLocks(ss);
2867 return SECFailure;
2870 #if (defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS)) && !defined(_WIN32_WCE)
2871 #define NSS_HAVE_GETENV 1
2872 #endif
2874 #define LOWER(x) (x | 0x20) /* cheap ToLower function ignores LOCALE */
2876 static void
2877 ssl_SetDefaultsFromEnvironment(void)
2879 #if defined( NSS_HAVE_GETENV )
2880 static int firsttime = 1;
2882 if (firsttime) {
2883 char * ev;
2884 firsttime = 0;
2885 #ifdef DEBUG
2886 ev = getenv("SSLDEBUGFILE");
2887 if (ev && ev[0]) {
2888 ssl_trace_iob = fopen(ev, "w");
2890 if (!ssl_trace_iob) {
2891 ssl_trace_iob = stderr;
2893 #ifdef TRACE
2894 ev = getenv("SSLTRACE");
2895 if (ev && ev[0]) {
2896 ssl_trace = atoi(ev);
2897 SSL_TRACE(("SSL: tracing set to %d", ssl_trace));
2899 #endif /* TRACE */
2900 ev = getenv("SSLDEBUG");
2901 if (ev && ev[0]) {
2902 ssl_debug = atoi(ev);
2903 SSL_TRACE(("SSL: debugging set to %d", ssl_debug));
2905 #endif /* DEBUG */
2906 ev = getenv("SSLKEYLOGFILE");
2907 if (ev && ev[0]) {
2908 ssl_keylog_iob = fopen(ev, "a");
2909 if (!ssl_keylog_iob) {
2910 SSL_TRACE(("Failed to open key log file"));
2911 } else {
2912 if (ftell(ssl_keylog_iob) == 0) {
2913 fputs("# SSL/TLS secrets log file, generated by NSS\n",
2914 ssl_keylog_iob);
2916 SSL_TRACE(("SSL: logging SSL/TLS secrets to %s", ev));
2919 #ifndef NO_PKCS11_BYPASS
2920 ev = getenv("SSLBYPASS");
2921 if (ev && ev[0]) {
2922 ssl_defaults.bypassPKCS11 = (ev[0] == '1');
2923 SSL_TRACE(("SSL: bypass default set to %d", \
2924 ssl_defaults.bypassPKCS11));
2926 #endif /* NO_PKCS11_BYPASS */
2927 ev = getenv("SSLFORCELOCKS");
2928 if (ev && ev[0] == '1') {
2929 ssl_force_locks = PR_TRUE;
2930 ssl_defaults.noLocks = 0;
2931 strcpy(lockStatus + LOCKSTATUS_OFFSET, "FORCED. ");
2932 SSL_TRACE(("SSL: force_locks set to %d", ssl_force_locks));
2934 ev = getenv("NSS_SSL_ENABLE_RENEGOTIATION");
2935 if (ev) {
2936 if (ev[0] == '1' || LOWER(ev[0]) == 'u')
2937 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_UNRESTRICTED;
2938 else if (ev[0] == '0' || LOWER(ev[0]) == 'n')
2939 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_NEVER;
2940 else if (ev[0] == '2' || LOWER(ev[0]) == 'r')
2941 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_REQUIRES_XTN;
2942 else if (ev[0] == '3' || LOWER(ev[0]) == 't')
2943 ssl_defaults.enableRenegotiation = SSL_RENEGOTIATE_TRANSITIONAL;
2944 SSL_TRACE(("SSL: enableRenegotiation set to %d",
2945 ssl_defaults.enableRenegotiation));
2947 ev = getenv("NSS_SSL_REQUIRE_SAFE_NEGOTIATION");
2948 if (ev && ev[0] == '1') {
2949 ssl_defaults.requireSafeNegotiation = PR_TRUE;
2950 SSL_TRACE(("SSL: requireSafeNegotiation set to %d",
2951 PR_TRUE));
2953 ev = getenv("NSS_SSL_CBC_RANDOM_IV");
2954 if (ev && ev[0] == '0') {
2955 ssl_defaults.cbcRandomIV = PR_FALSE;
2956 SSL_TRACE(("SSL: cbcRandomIV set to 0"));
2959 #endif /* NSS_HAVE_GETENV */
2963 ** Create a newsocket structure for a file descriptor.
2965 static sslSocket *
2966 ssl_NewSocket(PRBool makeLocks, SSLProtocolVariant protocolVariant)
2968 sslSocket *ss;
2970 ssl_SetDefaultsFromEnvironment();
2972 if (ssl_force_locks)
2973 makeLocks = PR_TRUE;
2975 /* Make a new socket and get it ready */
2976 ss = (sslSocket*) PORT_ZAlloc(sizeof(sslSocket));
2977 if (ss) {
2978 /* This should be of type SSLKEAType, but CC on IRIX
2979 * complains during the for loop.
2981 int i;
2982 SECStatus status;
2984 ss->opt = ssl_defaults;
2985 ss->opt.useSocks = PR_FALSE;
2986 ss->opt.noLocks = !makeLocks;
2987 ss->vrange = *VERSIONS_DEFAULTS(protocolVariant);
2989 ss->peerID = NULL;
2990 ss->rTimeout = PR_INTERVAL_NO_TIMEOUT;
2991 ss->wTimeout = PR_INTERVAL_NO_TIMEOUT;
2992 ss->cTimeout = PR_INTERVAL_NO_TIMEOUT;
2993 ss->cipherSpecs = NULL;
2994 ss->sizeCipherSpecs = 0; /* produced lazily */
2995 ss->preferredCipher = NULL;
2996 ss->url = NULL;
2998 for (i=kt_null; i < kt_kea_size; i++) {
2999 sslServerCerts * sc = ss->serverCerts + i;
3000 sc->serverCert = NULL;
3001 sc->serverCertChain = NULL;
3002 sc->serverKeyPair = NULL;
3003 sc->serverKeyBits = 0;
3005 ss->requestedCertTypes = NULL;
3006 ss->stepDownKeyPair = NULL;
3007 ss->dbHandle = CERT_GetDefaultCertDB();
3009 /* Provide default implementation of hooks */
3010 ss->authCertificate = SSL_AuthCertificate;
3011 ss->authCertificateArg = (void *)ss->dbHandle;
3012 ss->sniSocketConfig = NULL;
3013 ss->sniSocketConfigArg = NULL;
3014 ss->getClientAuthData = NULL;
3015 #ifdef NSS_PLATFORM_CLIENT_AUTH
3016 ss->getPlatformClientAuthData = NULL;
3017 ss->getPlatformClientAuthDataArg = NULL;
3018 #endif /* NSS_PLATFORM_CLIENT_AUTH */
3019 ss->handleBadCert = NULL;
3020 ss->badCertArg = NULL;
3021 ss->pkcs11PinArg = NULL;
3022 ss->getChannelID = NULL;
3023 ss->getChannelIDArg = NULL;
3025 ssl_ChooseOps(ss);
3026 ssl2_InitSocketPolicy(ss);
3027 ssl3_InitSocketPolicy(ss);
3029 if (makeLocks) {
3030 status = ssl_MakeLocks(ss);
3031 if (status != SECSuccess)
3032 goto loser;
3034 status = ssl_CreateSecurityInfo(ss);
3035 if (status != SECSuccess)
3036 goto loser;
3037 status = ssl_InitGather(&ss->gs);
3038 if (status != SECSuccess) {
3039 loser:
3040 ssl_DestroySocketContents(ss);
3041 ssl_DestroyLocks(ss);
3042 PORT_Free(ss);
3043 ss = NULL;
3045 ss->protocolVariant = protocolVariant;
3047 return ss;