]> git.saurik.com Git - apple/security.git/blob - Security/libsecurity_ssl/lib/sslContext.c
Security-57031.1.35.tar.gz
[apple/security.git] / Security / libsecurity_ssl / lib / sslContext.c
1 /*
2 * Copyright (c) 1999-2001,2005-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 /*
25 * sslContext.c - SSLContext accessors
26 */
27
28 #include "SecureTransport.h"
29
30 #include "SSLRecordInternal.h"
31 #include "SecureTransportPriv.h"
32 #include "appleSession.h"
33 #include "ssl.h"
34 #include "sslCipherSpecs.h"
35 #include "sslContext.h"
36 #include "sslCrypto.h"
37 #include "sslDebug.h"
38 #include "sslDigests.h"
39 #include "sslKeychain.h"
40 #include "sslMemory.h"
41 #include "sslUtils.h"
42
43 #include "tlsCallbacks.h"
44
45 #include <AssertMacros.h>
46 #include <CoreFoundation/CFData.h>
47 #include <CoreFoundation/CFPreferences.h>
48 #include <Security/SecCertificate.h>
49 #include <Security/SecCertificatePriv.h>
50 #include <Security/SecTrust.h>
51 #include <Security/SecTrustSettingsPriv.h>
52 #include <Security/oidsalg.h>
53 #include "utilities/SecCFRelease.h"
54 #include "utilities/SecCFWrappers.h"
55 #include <pthread.h>
56 #include <string.h>
57
58 #if TARGET_OS_IPHONE
59 #include <Security/SecCertificateInternal.h>
60 #else
61 #include <Security/oidsalg.h>
62 #include <Security/oidscert.h>
63 #include <Security/SecTrustSettingsPriv.h>
64 #endif
65
66
67 static void sslFreeDnList(
68 SSLContext *ctx)
69 {
70 DNListElem *dn, *nextDN;
71
72 dn = ctx->acceptableDNList;
73 while (dn)
74 {
75 SSLFreeBuffer(&dn->derDN);
76 nextDN = dn->next;
77 sslFree(dn);
78 dn = nextDN;
79 }
80 ctx->acceptableDNList = NULL;
81 }
82
83
84 Boolean sslIsSessionActive(const SSLContext *ctx)
85 {
86 assert(ctx != NULL);
87
88
89 switch(ctx->state) {
90 case SSL_HdskStateUninit:
91 case SSL_HdskStateGracefulClose:
92 case SSL_HdskStateErrorClose:
93 return false;
94 default:
95 return true;
96 }
97
98 }
99
100 /*
101 * Minimum and maximum supported versions
102 */
103 //#define MINIMUM_STREAM_VERSION SSL_Version_2_0 /* Disabled */
104 #define MINIMUM_STREAM_VERSION SSL_Version_3_0
105 #define MAXIMUM_STREAM_VERSION TLS_Version_1_2
106 #define MINIMUM_DATAGRAM_VERSION DTLS_Version_1_0
107
108 /* This should be changed when we start supporting DTLS_Version_1_x */
109 #define MAXIMUM_DATAGRAM_VERSION DTLS_Version_1_0
110
111 #define SSL_ENABLE_ECDSA_SIGN_AUTH 0
112 #define SSL_ENABLE_RSA_FIXED_ECDH_AUTH 0
113 #define SSL_ENABLE_ECDSA_FIXED_ECDH_AUTH 0
114
115 #define DEFAULT_DTLS_TIMEOUT 1
116 #define DEFAULT_DTLS_MTU 1400
117 #define MIN_ALLOWED_DTLS_MTU 64 /* this ensure than there will be no integer
118 underflow when calculating max write size */
119
120 int kSplitDefaultValue;
121
122 static void _SSLContextReadDefault()
123 {
124 /* 0 = disabled, 1 = split every write, 2 = split second and subsequent writes */
125 /* Enabled by default, this may cause some interop issues, see <rdar://problem/12307662> and <rdar://problem/12323307> */
126 const int defaultSplitDefaultValue = 2;
127
128 CFTypeRef value = (CFTypeRef)CFPreferencesCopyValue(CFSTR("SSLWriteSplit"),
129 CFSTR("com.apple.security"),
130 kCFPreferencesAnyUser,
131 kCFPreferencesCurrentHost);
132 if (value) {
133 if (CFGetTypeID(value) == CFBooleanGetTypeID())
134 kSplitDefaultValue = CFBooleanGetValue((CFBooleanRef)value) ? 1 : 0;
135 else if (CFGetTypeID(value) == CFNumberGetTypeID()) {
136 if (!CFNumberGetValue((CFNumberRef)value, kCFNumberIntType, &kSplitDefaultValue))
137 kSplitDefaultValue = defaultSplitDefaultValue;
138 }
139 if (kSplitDefaultValue < 0 || kSplitDefaultValue > 2) {
140 kSplitDefaultValue = defaultSplitDefaultValue;
141 }
142 CFRelease(value);
143 }
144 else {
145 kSplitDefaultValue = defaultSplitDefaultValue;
146 }
147 }
148
149 CFGiblisWithHashFor(SSLContext)
150
151 OSStatus
152 SSLNewContext (Boolean isServer,
153 SSLContextRef *contextPtr) /* RETURNED */
154 {
155 if(contextPtr == NULL) {
156 return errSecParam;
157 }
158
159 *contextPtr = SSLCreateContext(kCFAllocatorDefault, isServer?kSSLServerSide:kSSLClientSide, kSSLStreamType);
160
161 if (*contextPtr == NULL)
162 return errSecAllocate;
163
164 return errSecSuccess;
165 }
166
167 SSLContextRef SSLCreateContext(CFAllocatorRef alloc, SSLProtocolSide protocolSide, SSLConnectionType connectionType)
168 {
169 SSLContextRef ctx;
170 SSLRecordContextRef recCtx;
171
172 ctx = SSLCreateContextWithRecordFuncs(alloc, protocolSide, connectionType, &SSLRecordLayerInternal);
173
174 if(ctx==NULL)
175 return NULL;
176
177 recCtx = SSLCreateInternalRecordLayer(connectionType);
178 if(recCtx==NULL) {
179 CFRelease(ctx);
180 return NULL;
181 }
182
183 SSLSetRecordContext(ctx, recCtx);
184
185 return ctx;
186 }
187
188 SSLContextRef SSLCreateContextWithRecordFuncs(CFAllocatorRef alloc, SSLProtocolSide protocolSide, SSLConnectionType connectionType, const struct SSLRecordFuncs *recFuncs)
189 {
190 OSStatus serr = errSecSuccess;
191 SSLContext *ctx = (SSLContext*) _CFRuntimeCreateInstance(alloc, SSLContextGetTypeID(), sizeof(SSLContext) - sizeof(CFRuntimeBase), NULL);
192
193 if(ctx == NULL) {
194 return NULL;
195 }
196
197 /* subsequent errors to errOut: */
198 memset(((uint8_t*) ctx) + sizeof(CFRuntimeBase), 0, sizeof(SSLContext) - sizeof(CFRuntimeBase));
199
200
201 ctx->hdsk = tls_handshake_create(connectionType==kSSLDatagramType, protocolSide==kSSLServerSide);
202
203
204 tls_handshake_set_callbacks(ctx->hdsk,
205 &tls_handshake_callbacks,
206 ctx);
207
208 ctx->isDTLS = (connectionType==kSSLDatagramType);
209
210 ctx->state = SSL_HdskStateUninit;
211 ctx->timeout_duration = DEFAULT_DTLS_TIMEOUT;
212 ctx->mtu = DEFAULT_DTLS_MTU;
213
214 if(ctx->isDTLS) {
215 ctx->minProtocolVersion = MINIMUM_DATAGRAM_VERSION;
216 ctx->maxProtocolVersion = MAXIMUM_DATAGRAM_VERSION;
217 } else {
218 ctx->minProtocolVersion = MINIMUM_STREAM_VERSION;
219 ctx->maxProtocolVersion = MAXIMUM_STREAM_VERSION;
220 }
221 tls_handshake_set_min_protocol_version(ctx->hdsk, ctx->minProtocolVersion);
222 tls_handshake_set_max_protocol_version(ctx->hdsk, ctx->maxProtocolVersion);
223
224 ctx->negProtocolVersion = SSL_Version_Undetermined;
225 ctx->protocolSide = protocolSide;
226 ctx->recFuncs = recFuncs;
227
228 /* Initial cert verify state: verify with default system roots */
229 ctx->enableCertVerify = true;
230
231 /* Default for RSA blinding is ENABLED */
232 ctx->rsaBlindingEnable = true;
233
234 /* Default for sending one-byte app data record is DISABLED */
235 ctx->oneByteRecordEnable = false;
236
237 /* Dont enable fallback behavior by default */
238 ctx->fallbackEnabled = false;
239
240 /* Consult global system preference for default behavior:
241 * 0 = disabled, 1 = split every write, 2 = split second and subsequent writes
242 * (caller can override by setting kSSLSessionOptionSendOneByteRecord)
243 */
244 static pthread_once_t sReadDefault = PTHREAD_ONCE_INIT;
245 pthread_once(&sReadDefault, _SSLContextReadDefault);
246 if (kSplitDefaultValue > 0)
247 ctx->oneByteRecordEnable = true;
248
249 /* default for anonymous ciphers is DISABLED */
250 ctx->anonCipherEnable = false;
251
252 ctx->breakOnServerAuth = false;
253 ctx->breakOnCertRequest = false;
254 ctx->breakOnClientAuth = false;
255 ctx->signalServerAuth = false;
256 ctx->signalCertRequest = false;
257 ctx->signalClientAuth = false;
258
259 ctx->negAuthType = SSLClientAuthNone; /* ditto */
260
261 if (serr != errSecSuccess) {
262 CFRelease(ctx);
263 ctx = NULL;
264 }
265 return ctx;
266 }
267
268 OSStatus
269 SSLNewDatagramContext (Boolean isServer,
270 SSLContextRef *contextPtr) /* RETURNED */
271 {
272 if (contextPtr == NULL)
273 return errSecParam;
274 *contextPtr = SSLCreateContext(kCFAllocatorDefault, isServer?kSSLServerSide:kSSLClientSide, kSSLDatagramType);
275 if (*contextPtr == NULL)
276 return errSecAllocate;
277 return errSecSuccess;
278 }
279
280 /*
281 * Dispose of an SSLContext. (private)
282 * This function is invoked after our dispatch queue is safely released,
283 * or directly from SSLDisposeContext if there is no dispatch queue.
284 */
285 OSStatus
286 SSLDisposeContext (SSLContextRef context)
287 {
288 if(context == NULL) {
289 return errSecParam;
290 }
291 CFRelease(context);
292 return errSecSuccess;
293 }
294
295 CFStringRef SSLContextCopyDescription(CFTypeRef arg)
296 {
297 SSLContext* ctx = (SSLContext*) arg;
298
299 if (ctx == NULL) {
300 return NULL;
301 } else {
302 CFStringRef result = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("<SSLContext(%p) { ... }>"), ctx);
303 return result;
304 }
305 }
306
307 Boolean SSLContextCompare(CFTypeRef a, CFTypeRef b)
308 {
309 return a == b;
310 }
311
312 CFHashCode SSLContextHash(CFTypeRef arg)
313 {
314 return (CFHashCode) arg;
315 }
316
317 void SSLContextDestroy(CFTypeRef arg)
318 {
319 SSLContext* ctx = (SSLContext*) arg;
320
321 /* destroy the coreTLS handshake object */
322 tls_handshake_destroy(ctx->hdsk);
323
324 /* Only destroy if we were using the internal record layer */
325 if(ctx->recFuncs==&SSLRecordLayerInternal)
326 SSLDestroyInternalRecordLayer(ctx->recCtx);
327
328 SSLFreeBuffer(&ctx->sessionTicket);
329 SSLFreeBuffer(&ctx->sessionID);
330 SSLFreeBuffer(&ctx->peerID);
331 SSLFreeBuffer(&ctx->resumableSession);
332 SSLFreeBuffer(&ctx->receivedDataBuffer);
333
334 sslFree(ctx->validCipherSuites);
335 ctx->validCipherSuites = NULL;
336 ctx->numValidCipherSuites = 0;
337
338 CFReleaseSafe(ctx->acceptableCAs);
339 CFReleaseSafe(ctx->trustedLeafCerts);
340 CFReleaseSafe(ctx->localCertArray);
341 CFReleaseSafe(ctx->encryptCertArray);
342 CFReleaseSafe(ctx->encryptCertArray);
343 CFReleaseSafe(ctx->peerCert);
344 CFReleaseSafe(ctx->trustedCerts);
345 CFReleaseSafe(ctx->peerSecTrust);
346
347 sslFreePrivKey(&ctx->signingPrivKeyRef);
348 sslFreePrivKey(&ctx->encryptPrivKeyRef);
349
350 sslFree(ctx->localCert);
351 sslFree(ctx->encryptCert);
352
353
354 sslFreeDnList(ctx);
355
356 SSLFreeBuffer(&ctx->ownVerifyData);
357 SSLFreeBuffer(&ctx->peerVerifyData);
358
359 SSLFreeBuffer(&ctx->pskIdentity);
360 SSLFreeBuffer(&ctx->pskSharedSecret);
361
362 SSLFreeBuffer(&ctx->dhParamsEncoded);
363
364 memset(((uint8_t*) ctx) + sizeof(CFRuntimeBase), 0, sizeof(SSLContext) - sizeof(CFRuntimeBase));
365
366 sslCleanupSession();
367 }
368
369 /*
370 * Determine the state of an SSL session.
371 */
372 OSStatus
373 SSLGetSessionState (SSLContextRef context,
374 SSLSessionState *state) /* RETURNED */
375 {
376 SSLSessionState rtnState = kSSLIdle;
377
378 if(context == NULL) {
379 return errSecParam;
380 }
381 *state = rtnState;
382 switch(context->state) {
383 case SSL_HdskStateUninit:
384 rtnState = kSSLIdle;
385 break;
386 case SSL_HdskStateGracefulClose:
387 rtnState = kSSLClosed;
388 break;
389 case SSL_HdskStateErrorClose:
390 case SSL_HdskStateNoNotifyClose:
391 rtnState = kSSLAborted;
392 break;
393 case SSL_HdskStateReady:
394 rtnState = kSSLConnected;
395 break;
396 case SSL_HdskStatePending:
397 rtnState = kSSLHandshake;
398 break;
399 }
400 *state = rtnState;
401 return errSecSuccess;
402 }
403
404 /*
405 * Set options for an SSL session.
406 */
407 OSStatus
408 SSLSetSessionOption (SSLContextRef context,
409 SSLSessionOption option,
410 Boolean value)
411 {
412 if(context == NULL) {
413 return errSecParam;
414 }
415 if(sslIsSessionActive(context)) {
416 /* can't do this with an active session */
417 return errSecBadReq;
418 }
419 switch(option) {
420 case kSSLSessionOptionBreakOnServerAuth:
421 context->breakOnServerAuth = value;
422 context->enableCertVerify = !value;
423 break;
424 case kSSLSessionOptionBreakOnCertRequested:
425 context->breakOnCertRequest = value;
426 break;
427 case kSSLSessionOptionBreakOnClientAuth:
428 context->breakOnClientAuth = value;
429 context->enableCertVerify = !value;
430 break;
431 case kSSLSessionOptionSendOneByteRecord:
432 /* Only call the record layer function if the value changed */
433 if(value != context->oneByteRecordEnable)
434 context->recFuncs->setOption(context->recCtx, kSSLRecordOptionSendOneByteRecord, value);
435 context->oneByteRecordEnable = value;
436 break;
437 case kSSLSessionOptionFalseStart:
438 context->falseStartEnabled = value;
439 break;
440 case kSSLSessionOptionFallback:
441 tls_handshake_set_fallback(context->hdsk, value);
442 context->fallbackEnabled = value;
443 break;
444 default:
445 return errSecParam;
446 }
447
448 return errSecSuccess;
449 }
450
451 /*
452 * Determine current value for the specified option in an SSL session.
453 */
454 OSStatus
455 SSLGetSessionOption (SSLContextRef context,
456 SSLSessionOption option,
457 Boolean *value)
458 {
459 if(context == NULL || value == NULL) {
460 return errSecParam;
461 }
462 switch(option) {
463 case kSSLSessionOptionBreakOnServerAuth:
464 *value = context->breakOnServerAuth;
465 break;
466 case kSSLSessionOptionBreakOnCertRequested:
467 *value = context->breakOnCertRequest;
468 break;
469 case kSSLSessionOptionBreakOnClientAuth:
470 *value = context->breakOnClientAuth;
471 break;
472 case kSSLSessionOptionSendOneByteRecord:
473 *value = context->oneByteRecordEnable;
474 break;
475 case kSSLSessionOptionFalseStart:
476 *value = context->falseStartEnabled;
477 break;
478 default:
479 return errSecParam;
480 }
481
482 return errSecSuccess;
483 }
484
485 OSStatus
486 SSLSetRecordContext (SSLContextRef ctx,
487 SSLRecordContextRef recCtx)
488 {
489 if(ctx == NULL) {
490 return errSecParam;
491 }
492 if(sslIsSessionActive(ctx)) {
493 /* can't do this with an active session */
494 return errSecBadReq;
495 }
496 ctx->recCtx = recCtx;
497 return errSecSuccess;
498 }
499
500 /* Those two trampolines are used to make the connetion between
501 the record layer IO callbacks and the user provided IO callbacks.
502 Those are currently necessary because the record layer read/write callbacks
503 have different prototypes that the user callbacks advertised in the API.
504 They have different prototypes because the record layer callback have to build in kernelland.
505
506 This situation is not desirable. So we should figure out a way to get rid of them.
507 */
508 static int IORead(SSLIOConnectionRef connection,
509 void *data,
510 size_t *dataLength)
511 {
512 OSStatus rc;
513 SSLContextRef ctx = connection;
514
515
516 rc = ctx->ioCtx.read(ctx->ioCtx.ioRef, data, dataLength);
517
518 /* We may need to translate error codes at this layer */
519 if(rc==errSSLWouldBlock) {
520 rc=errSSLRecordWouldBlock;
521 }
522
523 return rc;
524 }
525
526 static int IOWrite(SSLIOConnectionRef connection,
527 const void *data,
528 size_t *dataLength)
529 {
530 OSStatus rc;
531 SSLContextRef ctx = connection;
532
533 rc = ctx->ioCtx.write(ctx->ioCtx.ioRef, data, dataLength);
534
535 /* We may need to translate error codes at this layer */
536 if(rc==errSSLWouldBlock) {
537 rc=errSSLRecordWouldBlock;
538 }
539 return rc;
540 }
541
542
543 OSStatus
544 SSLSetIOFuncs (SSLContextRef ctx,
545 SSLReadFunc readFunc,
546 SSLWriteFunc writeFunc)
547 {
548 if(ctx == NULL) {
549 return errSecParam;
550 }
551 if(ctx->recFuncs!=&SSLRecordLayerInternal) {
552 /* Can Only do this with the internal record layer */
553 check(0);
554 return errSecBadReq;
555 }
556 if(sslIsSessionActive(ctx)) {
557 /* can't do this with an active session */
558 return errSecBadReq;
559 }
560
561 ctx->ioCtx.read=readFunc;
562 ctx->ioCtx.write=writeFunc;
563
564 return SSLSetInternalRecordLayerIOFuncs(ctx->recCtx, IORead, IOWrite);
565 }
566
567 void
568 SSLSetNPNFunc(SSLContextRef context,
569 SSLNPNFunc npnFunc,
570 void *info)
571 {
572 if (context == NULL) {
573 return;
574 }
575 if (sslIsSessionActive(context)) {
576 return;
577 }
578 context->npnFunc = npnFunc;
579 context->npnFuncInfo = info;
580 if(context->protocolSide==kSSLClientSide) {
581 tls_handshake_set_npn_enable(context->hdsk, npnFunc!=NULL);
582 }
583 }
584
585 OSStatus
586 SSLSetNPNData(SSLContextRef context,
587 const void *data,
588 size_t length)
589 {
590 if (context == NULL || data == NULL || length == 0) {
591 return errSecParam;
592 }
593
594 if (length > 255) {
595 return errSecParam;
596 }
597
598 tls_buffer npn_data;
599
600 npn_data.data = (uint8_t *)data;
601 npn_data.length = length;
602
603 return tls_handshake_set_npn_data(context->hdsk, npn_data);
604 }
605
606 const void *
607 SSLGetNPNData(SSLContextRef context,
608 size_t *length)
609 {
610 if (context == NULL || length == NULL)
611 return NULL;
612
613 const tls_buffer *npn_data;
614
615 npn_data = tls_handshake_get_peer_npn_data(context->hdsk);
616
617 if(npn_data) {
618 *length = npn_data->length;
619 return npn_data->data;
620 } else {
621 return NULL;
622 }
623 }
624
625 OSStatus
626 SSLSetConnection (SSLContextRef ctx,
627 SSLConnectionRef connection)
628 {
629 if(ctx == NULL) {
630 return errSecParam;
631 }
632 if(ctx->recFuncs!=&SSLRecordLayerInternal) {
633 /* Can Only do this with the internal record layer */
634 check(0);
635 return errSecBadReq;
636 }
637 if(sslIsSessionActive(ctx)) {
638 /* can't do this with an active session */
639 return errSecBadReq;
640 }
641
642 /* Need to keep a copy of it this layer for the Get function */
643 ctx->ioCtx.ioRef = connection;
644
645 return SSLSetInternalRecordLayerConnection(ctx->recCtx, ctx);
646 }
647
648 OSStatus
649 SSLGetConnection (SSLContextRef ctx,
650 SSLConnectionRef *connection)
651 {
652 if((ctx == NULL) || (connection == NULL)) {
653 return errSecParam;
654 }
655 *connection = ctx->ioCtx.ioRef;
656 return errSecSuccess;
657 }
658
659 OSStatus
660 SSLSetPeerDomainName (SSLContextRef ctx,
661 const char *peerName,
662 size_t peerNameLen)
663 {
664 if(ctx == NULL) {
665 return errSecParam;
666 }
667 if(sslIsSessionActive(ctx)) {
668 /* can't do this with an active session */
669 return errSecBadReq;
670 }
671
672 if(ctx->protocolSide == kSSLClientSide) {
673 return tls_handshake_set_peer_hostname(ctx->hdsk, peerName, peerNameLen);
674 } else {
675 return 0; // This should probably return an error, but historically didnt.
676 }
677 }
678
679 /*
680 * Determine the buffer size needed for SSLGetPeerDomainName().
681 */
682 OSStatus
683 SSLGetPeerDomainNameLength (SSLContextRef ctx,
684 size_t *peerNameLen) // RETURNED
685 {
686 if(ctx == NULL) {
687 return errSecParam;
688 }
689 const char *hostname;
690
691 return tls_handshake_get_peer_hostname(ctx->hdsk, &hostname, peerNameLen);
692 }
693
694 OSStatus
695 SSLGetPeerDomainName (SSLContextRef ctx,
696 char *peerName, // returned here
697 size_t *peerNameLen) // IN/OUT
698 {
699 const char *hostname;
700 size_t len;
701
702 int err;
703
704 if(ctx == NULL) {
705 return errSecParam;
706 }
707
708 err=tls_handshake_get_peer_hostname(ctx->hdsk, &hostname, &len);
709
710 if(err) {
711 return err;
712 } else if(*peerNameLen<len) {
713 return errSSLBufferOverflow;
714 } else {
715 memcpy(peerName, hostname, len);
716 *peerNameLen = len;
717 return 0;
718 }
719 }
720
721 OSStatus
722 SSLSetDatagramHelloCookie (SSLContextRef ctx,
723 const void *cookie,
724 size_t cookieLen)
725 {
726 OSStatus err;
727
728 if(ctx == NULL) {
729 return errSecParam;
730 }
731
732 if(!ctx->isDTLS) return errSecParam;
733
734 if((ctx == NULL) || (cookieLen>32)) {
735 return errSecParam;
736 }
737 if(sslIsSessionActive(ctx)) {
738 /* can't do this with an active session */
739 return errSecBadReq;
740 }
741
742 /* free possible existing cookie */
743 if(ctx->dtlsCookie.data) {
744 SSLFreeBuffer(&ctx->dtlsCookie);
745 }
746
747 /* copy in */
748 if((err=SSLAllocBuffer(&ctx->dtlsCookie, cookieLen)))
749 return err;
750
751 memmove(ctx->dtlsCookie.data, cookie, cookieLen);
752 return errSecSuccess;
753 }
754
755 OSStatus
756 SSLSetMaxDatagramRecordSize (SSLContextRef ctx,
757 size_t maxSize)
758 {
759
760 if(ctx == NULL) return errSecParam;
761 if(!ctx->isDTLS) return errSecParam;
762
763 tls_handshake_set_mtu(ctx->hdsk, maxSize);
764
765 return errSecSuccess;
766 }
767
768 OSStatus
769 SSLGetMaxDatagramRecordSize (SSLContextRef ctx,
770 size_t *maxSize)
771 {
772 if(ctx == NULL) return errSecParam;
773 if(!ctx->isDTLS) return errSecParam;
774
775 *maxSize = ctx->mtu;
776
777 return errSecSuccess;
778 }
779
780 /*
781
782 Keys to to math below:
783
784 A DTLS record looks like this: | header (13 bytes) | fragment |
785
786 For Null cipher, fragment is clear text as follows:
787 | Contents | Mac |
788
789 For block cipher, fragment size must be a multiple of the cipher block size, and is the
790 encryption of the following plaintext :
791 | IV (1 block) | content | MAC | padding (0 to 255 bytes) | Padlen (1 byte) |
792
793 The maximum content length in that case is achieved for 0 padding bytes.
794
795 */
796
797 OSStatus
798 SSLGetDatagramWriteSize (SSLContextRef ctx,
799 size_t *bufSize)
800 {
801 if(ctx == NULL) return errSecParam;
802 if(!ctx->isDTLS) return errSecParam;
803 if(bufSize == NULL) return errSecParam;
804
805 size_t max_fragment_size = ctx->mtu-13; /* 13 = dtls record header */
806
807 #warning <rdar://problem/16060896> SecureTransport: SSLGetDatagramWriteSize is wrong, need hookup with coreTLS
808 #if 0
809 SSLCipherSpecParams *currCipher = &ctx->selectedCipherSpecParams;
810
811 size_t blockSize = currCipher->blockSize;
812 size_t macSize = currCipher->macSize;
813 #else
814 size_t blockSize = 16;
815 size_t macSize = 32;
816 #endif
817
818 if (blockSize > 0) {
819 /* max_fragment_size must be a multiple of blocksize */
820 max_fragment_size = max_fragment_size & ~(blockSize-1);
821 max_fragment_size -= blockSize; /* 1 block for IV */
822 max_fragment_size -= 1; /* 1 byte for pad length */
823 }
824
825 /* less the mac size */
826 max_fragment_size -= macSize;
827
828 /* Thats just a sanity check */
829 assert(max_fragment_size<ctx->mtu);
830
831 *bufSize = max_fragment_size;
832
833 return errSecSuccess;
834 }
835
836 static SSLProtocolVersion SSLProtocolToProtocolVersion(SSLProtocol protocol) {
837 switch (protocol) {
838 case kSSLProtocol2: return SSL_Version_2_0;
839 case kSSLProtocol3: return SSL_Version_3_0;
840 case kTLSProtocol1: return TLS_Version_1_0;
841 case kTLSProtocol11: return TLS_Version_1_1;
842 case kTLSProtocol12: return TLS_Version_1_2;
843 case kDTLSProtocol1: return DTLS_Version_1_0;
844 default: return SSL_Version_Undetermined;
845 }
846 }
847
848 /* concert between private SSLProtocolVersion and public SSLProtocol */
849 static SSLProtocol SSLProtocolVersionToProtocol(SSLProtocolVersion version)
850 {
851 switch(version) {
852 case SSL_Version_2_0: return kSSLProtocol2;
853 case SSL_Version_3_0: return kSSLProtocol3;
854 case TLS_Version_1_0: return kTLSProtocol1;
855 case TLS_Version_1_1: return kTLSProtocol11;
856 case TLS_Version_1_2: return kTLSProtocol12;
857 case DTLS_Version_1_0: return kDTLSProtocol1;
858 default:
859 sslErrorLog("SSLProtocolVersionToProtocol: bad prot (%04x)\n",
860 version);
861 /* DROPTHROUGH */
862 case SSL_Version_Undetermined: return kSSLProtocolUnknown;
863 }
864 }
865
866 OSStatus
867 SSLSetProtocolVersionMin (SSLContextRef ctx,
868 SSLProtocol minVersion)
869 {
870 if(ctx == NULL) return errSecParam;
871
872 SSLProtocolVersion version = SSLProtocolToProtocolVersion(minVersion);
873 if (ctx->isDTLS) {
874 if (version > MINIMUM_DATAGRAM_VERSION ||
875 version < MAXIMUM_DATAGRAM_VERSION)
876 return errSSLIllegalParam;
877 if (version < ctx->maxProtocolVersion)
878 ctx->maxProtocolVersion = version;
879 } else {
880 if (version < MINIMUM_STREAM_VERSION || version > MAXIMUM_STREAM_VERSION)
881 return errSSLIllegalParam;
882 if (version > ctx->maxProtocolVersion)
883 ctx->maxProtocolVersion = version;
884 }
885 ctx->minProtocolVersion = version;
886
887 tls_handshake_set_min_protocol_version(ctx->hdsk, ctx->minProtocolVersion);
888 tls_handshake_set_max_protocol_version(ctx->hdsk, ctx->maxProtocolVersion);
889
890 return errSecSuccess;
891 }
892
893 OSStatus
894 SSLGetProtocolVersionMin (SSLContextRef ctx,
895 SSLProtocol *minVersion)
896 {
897 if(ctx == NULL) return errSecParam;
898
899 *minVersion = SSLProtocolVersionToProtocol(ctx->minProtocolVersion);
900 return errSecSuccess;
901 }
902
903 OSStatus
904 SSLSetProtocolVersionMax (SSLContextRef ctx,
905 SSLProtocol maxVersion)
906 {
907 if(ctx == NULL) return errSecParam;
908
909 SSLProtocolVersion version = SSLProtocolToProtocolVersion(maxVersion);
910 if (ctx->isDTLS) {
911 if (version > MINIMUM_DATAGRAM_VERSION ||
912 version < MAXIMUM_DATAGRAM_VERSION)
913 return errSSLIllegalParam;
914 if (version > ctx->minProtocolVersion)
915 ctx->minProtocolVersion = version;
916 } else {
917 if (version < MINIMUM_STREAM_VERSION || version > MAXIMUM_STREAM_VERSION)
918 return errSSLIllegalParam;
919 if (version < ctx->minProtocolVersion)
920 ctx->minProtocolVersion = version;
921 }
922 ctx->maxProtocolVersion = version;
923
924 tls_handshake_set_min_protocol_version(ctx->hdsk, ctx->minProtocolVersion);
925 tls_handshake_set_max_protocol_version(ctx->hdsk, ctx->maxProtocolVersion);
926
927 return errSecSuccess;
928 }
929
930 OSStatus
931 SSLGetProtocolVersionMax (SSLContextRef ctx,
932 SSLProtocol *maxVersion)
933 {
934 if(ctx == NULL) return errSecParam;
935
936 *maxVersion = SSLProtocolVersionToProtocol(ctx->maxProtocolVersion);
937 return errSecSuccess;
938 }
939
940 #define max(x,y) ((x)<(y)?(y):(x))
941
942 OSStatus
943 SSLSetProtocolVersionEnabled(SSLContextRef ctx,
944 SSLProtocol protocol,
945 Boolean enable)
946 {
947 if(ctx == NULL) {
948 return errSecParam;
949 }
950 if(sslIsSessionActive(ctx) || ctx->isDTLS) {
951 /* Can't do this with an active session, nor with a DTLS session */
952 return errSecBadReq;
953 }
954 if (protocol == kSSLProtocolAll) {
955 if (enable) {
956 ctx->minProtocolVersion = MINIMUM_STREAM_VERSION;
957 ctx->maxProtocolVersion = MAXIMUM_STREAM_VERSION;
958 } else {
959 ctx->minProtocolVersion = SSL_Version_Undetermined;
960 ctx->maxProtocolVersion = SSL_Version_Undetermined;
961 }
962 } else {
963 SSLProtocolVersion version = SSLProtocolToProtocolVersion(protocol);
964 if (enable) {
965 if (version < MINIMUM_STREAM_VERSION || version > MAXIMUM_STREAM_VERSION) {
966 return errSecParam;
967 }
968 if (version > ctx->maxProtocolVersion) {
969 ctx->maxProtocolVersion = version;
970 if (ctx->minProtocolVersion == SSL_Version_Undetermined)
971 ctx->minProtocolVersion = version;
972 }
973 if (version < ctx->minProtocolVersion) {
974 ctx->minProtocolVersion = version;
975 }
976 } else {
977 if (version < SSL_Version_2_0 || version > MAXIMUM_STREAM_VERSION) {
978 return errSecParam;
979 }
980 /* Disabling a protocol version now resets the minimum acceptable
981 * version to the next higher version. This means it's no longer
982 * possible to enable a discontiguous set of protocol versions.
983 */
984 SSLProtocolVersion nextVersion;
985 switch (version) {
986 case SSL_Version_2_0:
987 nextVersion = SSL_Version_3_0;
988 break;
989 case SSL_Version_3_0:
990 nextVersion = TLS_Version_1_0;
991 break;
992 case TLS_Version_1_0:
993 nextVersion = TLS_Version_1_1;
994 break;
995 case TLS_Version_1_1:
996 nextVersion = TLS_Version_1_2;
997 break;
998 case TLS_Version_1_2:
999 default:
1000 nextVersion = SSL_Version_Undetermined;
1001 break;
1002 }
1003 ctx->minProtocolVersion = max(ctx->minProtocolVersion, nextVersion);
1004 if (ctx->minProtocolVersion > ctx->maxProtocolVersion) {
1005 ctx->minProtocolVersion = SSL_Version_Undetermined;
1006 ctx->maxProtocolVersion = SSL_Version_Undetermined;
1007 }
1008 }
1009 }
1010
1011 tls_handshake_set_min_protocol_version(ctx->hdsk, ctx->minProtocolVersion);
1012 tls_handshake_set_max_protocol_version(ctx->hdsk, ctx->maxProtocolVersion);
1013
1014 return errSecSuccess;
1015 }
1016
1017 OSStatus
1018 SSLGetProtocolVersionEnabled(SSLContextRef ctx,
1019 SSLProtocol protocol,
1020 Boolean *enable) /* RETURNED */
1021 {
1022 if(ctx == NULL) {
1023 return errSecParam;
1024 }
1025 if(ctx->isDTLS) {
1026 /* Can't do this with a DTLS session */
1027 return errSecBadReq;
1028 }
1029 switch(protocol) {
1030 case kSSLProtocol2:
1031 case kSSLProtocol3:
1032 case kTLSProtocol1:
1033 case kTLSProtocol11:
1034 case kTLSProtocol12:
1035 {
1036 SSLProtocolVersion version = SSLProtocolToProtocolVersion(protocol);
1037 *enable = (ctx->minProtocolVersion <= version
1038 && ctx->maxProtocolVersion >= version);
1039 break;
1040 }
1041 case kSSLProtocolAll:
1042 *enable = (ctx->minProtocolVersion <= MINIMUM_STREAM_VERSION
1043 && ctx->maxProtocolVersion >= MAXIMUM_STREAM_VERSION);
1044 break;
1045 default:
1046 return errSecParam;
1047 }
1048 return errSecSuccess;
1049 }
1050
1051 /* deprecated */
1052 OSStatus
1053 SSLSetProtocolVersion (SSLContextRef ctx,
1054 SSLProtocol version)
1055 {
1056 if(ctx == NULL) {
1057 return errSecParam;
1058 }
1059 if(sslIsSessionActive(ctx) || ctx->isDTLS) {
1060 /* Can't do this with an active session, nor with a DTLS session */
1061 return errSecBadReq;
1062 }
1063
1064 switch(version) {
1065 case kSSLProtocol3:
1066 /* this tells us to do our best, up to 3.0 */
1067 ctx->minProtocolVersion = MINIMUM_STREAM_VERSION;
1068 ctx->maxProtocolVersion = SSL_Version_3_0;
1069 break;
1070 case kSSLProtocol3Only:
1071 ctx->minProtocolVersion = SSL_Version_3_0;
1072 ctx->maxProtocolVersion = SSL_Version_3_0;
1073 break;
1074 case kTLSProtocol1:
1075 /* this tells us to do our best, up to TLS, but allows 3.0 */
1076 ctx->minProtocolVersion = MINIMUM_STREAM_VERSION;
1077 ctx->maxProtocolVersion = TLS_Version_1_0;
1078 break;
1079 case kTLSProtocol1Only:
1080 ctx->minProtocolVersion = TLS_Version_1_0;
1081 ctx->maxProtocolVersion = TLS_Version_1_0;
1082 break;
1083 case kTLSProtocol11:
1084 /* This tells us to do our best, up to TLS 1.1, currently also
1085 allows 3.0 or TLS 1.0 */
1086 ctx->minProtocolVersion = MINIMUM_STREAM_VERSION;
1087 ctx->maxProtocolVersion = TLS_Version_1_1;
1088 break;
1089 case kTLSProtocol12:
1090 case kSSLProtocolAll:
1091 case kSSLProtocolUnknown:
1092 /* This tells us to do our best, up to TLS 1.2, currently also
1093 allows 3.0 or TLS 1.0 or TLS 1.1 */
1094 ctx->minProtocolVersion = MINIMUM_STREAM_VERSION;
1095 ctx->maxProtocolVersion = MAXIMUM_STREAM_VERSION;
1096 break;
1097 default:
1098 return errSecParam;
1099 }
1100
1101 tls_handshake_set_min_protocol_version(ctx->hdsk, ctx->minProtocolVersion);
1102 tls_handshake_set_max_protocol_version(ctx->hdsk, ctx->maxProtocolVersion);
1103
1104 return errSecSuccess;
1105 }
1106
1107 /* deprecated */
1108 OSStatus
1109 SSLGetProtocolVersion (SSLContextRef ctx,
1110 SSLProtocol *protocol) /* RETURNED */
1111 {
1112 if(ctx == NULL) {
1113 return errSecParam;
1114 }
1115 /* translate array of booleans to public value; not all combinations
1116 * are legal (i.e., meaningful) for this call */
1117 if (ctx->maxProtocolVersion == MAXIMUM_STREAM_VERSION) {
1118 if(ctx->minProtocolVersion == MINIMUM_STREAM_VERSION) {
1119 /* traditional 'all enabled' */
1120 *protocol = kSSLProtocolAll;
1121 return errSecSuccess;
1122 }
1123 } else if (ctx->maxProtocolVersion == TLS_Version_1_1) {
1124 if(ctx->minProtocolVersion == MINIMUM_STREAM_VERSION) {
1125 /* traditional 'all enabled' */
1126 *protocol = kTLSProtocol11;
1127 return errSecSuccess;
1128 }
1129 } else if (ctx->maxProtocolVersion == TLS_Version_1_0) {
1130 if(ctx->minProtocolVersion == MINIMUM_STREAM_VERSION) {
1131 /* TLS1.1 and below enabled */
1132 *protocol = kTLSProtocol1;
1133 return errSecSuccess;
1134 } else if(ctx->minProtocolVersion == TLS_Version_1_0) {
1135 *protocol = kTLSProtocol1Only;
1136 }
1137 } else if(ctx->maxProtocolVersion == SSL_Version_3_0) {
1138 if(ctx->minProtocolVersion == MINIMUM_STREAM_VERSION) {
1139 /* Could also return kSSLProtocol3Only since
1140 MINIMUM_STREAM_VERSION == SSL_Version_3_0. */
1141 *protocol = kSSLProtocol3;
1142 return errSecSuccess;
1143 }
1144 }
1145
1146 return errSecParam;
1147 }
1148
1149 OSStatus
1150 SSLGetNegotiatedProtocolVersion (SSLContextRef ctx,
1151 SSLProtocol *protocol) /* RETURNED */
1152 {
1153 if(ctx == NULL) {
1154 return errSecParam;
1155 }
1156 *protocol = SSLProtocolVersionToProtocol(ctx->negProtocolVersion);
1157 return errSecSuccess;
1158 }
1159
1160 OSStatus
1161 SSLSetEnableCertVerify (SSLContextRef ctx,
1162 Boolean enableVerify)
1163 {
1164 if(ctx == NULL) {
1165 return errSecParam;
1166 }
1167 sslCertDebug("SSLSetEnableCertVerify %s",
1168 enableVerify ? "true" : "false");
1169 if(sslIsSessionActive(ctx)) {
1170 /* can't do this with an active session */
1171 return errSecBadReq;
1172 }
1173 ctx->enableCertVerify = enableVerify;
1174 return errSecSuccess;
1175 }
1176
1177 OSStatus
1178 SSLGetEnableCertVerify (SSLContextRef ctx,
1179 Boolean *enableVerify)
1180 {
1181 if(ctx == NULL) {
1182 return errSecParam;
1183 }
1184 *enableVerify = ctx->enableCertVerify;
1185 return errSecSuccess;
1186 }
1187
1188 OSStatus
1189 SSLSetAllowsExpiredCerts(SSLContextRef ctx,
1190 Boolean allowExpired)
1191 {
1192 if(ctx == NULL) {
1193 return errSecParam;
1194 }
1195 sslCertDebug("SSLSetAllowsExpiredCerts %s",
1196 allowExpired ? "true" : "false");
1197 if(sslIsSessionActive(ctx)) {
1198 /* can't do this with an active session */
1199 return errSecBadReq;
1200 }
1201 ctx->allowExpiredCerts = allowExpired;
1202 return errSecSuccess;
1203 }
1204
1205 OSStatus
1206 SSLGetAllowsExpiredCerts (SSLContextRef ctx,
1207 Boolean *allowExpired)
1208 {
1209 if(ctx == NULL) {
1210 return errSecParam;
1211 }
1212 *allowExpired = ctx->allowExpiredCerts;
1213 return errSecSuccess;
1214 }
1215
1216 OSStatus
1217 SSLSetAllowsExpiredRoots(SSLContextRef ctx,
1218 Boolean allowExpired)
1219 {
1220 if(ctx == NULL) {
1221 return errSecParam;
1222 }
1223 sslCertDebug("SSLSetAllowsExpiredRoots %s",
1224 allowExpired ? "true" : "false");
1225 if(sslIsSessionActive(ctx)) {
1226 /* can't do this with an active session */
1227 return errSecBadReq;
1228 }
1229 ctx->allowExpiredRoots = allowExpired;
1230 return errSecSuccess;
1231 }
1232
1233 OSStatus
1234 SSLGetAllowsExpiredRoots (SSLContextRef ctx,
1235 Boolean *allowExpired)
1236 {
1237 if(ctx == NULL) {
1238 return errSecParam;
1239 }
1240 *allowExpired = ctx->allowExpiredRoots;
1241 return errSecSuccess;
1242 }
1243
1244 OSStatus SSLSetAllowsAnyRoot(
1245 SSLContextRef ctx,
1246 Boolean anyRoot)
1247 {
1248 if(ctx == NULL) {
1249 return errSecParam;
1250 }
1251 sslCertDebug("SSLSetAllowsAnyRoot %s", anyRoot ? "true" : "false");
1252 ctx->allowAnyRoot = anyRoot;
1253 return errSecSuccess;
1254 }
1255
1256 OSStatus
1257 SSLGetAllowsAnyRoot(
1258 SSLContextRef ctx,
1259 Boolean *anyRoot)
1260 {
1261 if(ctx == NULL) {
1262 return errSecParam;
1263 }
1264 *anyRoot = ctx->allowAnyRoot;
1265 return errSecSuccess;
1266 }
1267
1268 #if !TARGET_OS_IPHONE
1269 /* obtain the system roots sets for this app, policy SSL */
1270 static OSStatus sslDefaultSystemRoots(
1271 SSLContextRef ctx,
1272 CFArrayRef *systemRoots) // created and RETURNED
1273
1274 {
1275 const char *hostname;
1276 size_t len;
1277
1278 tls_handshake_get_peer_hostname(ctx->hdsk, &hostname, &len);
1279
1280 return SecTrustSettingsCopyQualifiedCerts(&CSSMOID_APPLE_TP_SSL,
1281 hostname,
1282 (uint32_t)len,
1283 (ctx->protocolSide == kSSLServerSide) ?
1284 /* server verifies, client encrypts */
1285 CSSM_KEYUSE_VERIFY : CSSM_KEYUSE_ENCRYPT,
1286 systemRoots);
1287 }
1288 #endif /* OS X only */
1289
1290 OSStatus
1291 SSLSetTrustedRoots (SSLContextRef ctx,
1292 CFArrayRef trustedRoots,
1293 Boolean replaceExisting)
1294 {
1295 #ifdef USE_CDSA_CRYPTO
1296 if(ctx == NULL) {
1297 return errSecParam;
1298 }
1299 if(sslIsSessionActive(ctx)) {
1300 /* can't do this with an active session */
1301 return errSecBadReq;
1302 }
1303
1304 if(replaceExisting) {
1305 /* trivial case - retain the new, throw out the old. */
1306 if (trustedRoots)
1307 CFRetain(trustedRoots);
1308 CFReleaseSafe(ctx->trustedCerts);
1309 ctx->trustedCerts = trustedRoots;
1310 return errSecSuccess;
1311 }
1312
1313 /* adding new trusted roots - to either our existing set, or the system set */
1314 CFArrayRef existingRoots = NULL;
1315 OSStatus ortn;
1316 if(ctx->trustedCerts != NULL) {
1317 /* we'll release these as we exit */
1318 existingRoots = ctx->trustedCerts;
1319 }
1320 else {
1321 /* get system set for this app, policy SSL */
1322 ortn = sslDefaultSystemRoots(ctx, &existingRoots);
1323 if(ortn) {
1324 CFReleaseSafe(existingRoots);
1325 return ortn;
1326 }
1327 }
1328
1329 /* Create a new root array with caller's roots first */
1330 CFMutableArrayRef newRoots = CFArrayCreateMutableCopy(NULL, 0, trustedRoots);
1331 CFRange existRange = { 0, CFArrayGetCount(existingRoots) };
1332 CFArrayAppendArray(newRoots, existingRoots, existRange);
1333 CFRelease(existingRoots);
1334 ctx->trustedCerts = newRoots;
1335 return errSecSuccess;
1336
1337 #else
1338 if (sslIsSessionActive(ctx)) {
1339 /* can't do this with an active session */
1340 return errSecBadReq;
1341 }
1342 sslCertDebug("SSLSetTrustedRoot numCerts %d replaceExist %s",
1343 (int)CFArrayGetCount(trustedRoots), replaceExisting ? "true" : "false");
1344
1345 if (replaceExisting) {
1346 ctx->trustedCertsOnly = true;
1347 CFReleaseNull(ctx->trustedCerts);
1348 }
1349
1350 if (ctx->trustedCerts) {
1351 CFIndex count = CFArrayGetCount(trustedRoots);
1352 CFRange range = { 0, count };
1353 CFArrayAppendArray(ctx->trustedCerts, trustedRoots, range);
1354 } else {
1355 require(ctx->trustedCerts =
1356 CFArrayCreateMutableCopy(kCFAllocatorDefault, 0, trustedRoots),
1357 errOut);
1358 }
1359
1360 return errSecSuccess;
1361
1362 errOut:
1363 return errSecAllocate;
1364 #endif /* !USE_CDSA_CRYPTO */
1365 }
1366
1367 OSStatus
1368 SSLCopyTrustedRoots (SSLContextRef ctx,
1369 CFArrayRef *trustedRoots) /* RETURNED */
1370 {
1371 if(ctx == NULL || trustedRoots == NULL) {
1372 return errSecParam;
1373 }
1374 if(ctx->trustedCerts != NULL) {
1375 *trustedRoots = ctx->trustedCerts;
1376 CFRetain(ctx->trustedCerts);
1377 return errSecSuccess;
1378 }
1379 #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
1380 /* use default system roots */
1381 return sslDefaultSystemRoots(ctx, trustedRoots);
1382 #else
1383 *trustedRoots = NULL;
1384 return errSecSuccess;
1385 #endif
1386 }
1387
1388 OSStatus
1389 SSLSetTrustedLeafCertificates (SSLContextRef ctx,
1390 CFArrayRef trustedCerts)
1391 {
1392 if(ctx == NULL) {
1393 return errSecParam;
1394 }
1395 if(sslIsSessionActive(ctx)) {
1396 /* can't do this with an active session */
1397 return errSecBadReq;
1398 }
1399
1400 if(ctx->trustedLeafCerts) {
1401 CFRelease(ctx->trustedLeafCerts);
1402 }
1403 ctx->trustedLeafCerts = trustedCerts;
1404 CFRetain(trustedCerts);
1405 return errSecSuccess;
1406 }
1407
1408 OSStatus
1409 SSLCopyTrustedLeafCertificates (SSLContextRef ctx,
1410 CFArrayRef *trustedCerts) /* RETURNED */
1411 {
1412 if(ctx == NULL) {
1413 return errSecParam;
1414 }
1415 if(ctx->trustedLeafCerts != NULL) {
1416 *trustedCerts = ctx->trustedLeafCerts;
1417 CFRetain(ctx->trustedCerts);
1418 return errSecSuccess;
1419 }
1420 *trustedCerts = NULL;
1421 return errSecSuccess;
1422 }
1423
1424 OSStatus
1425 SSLSetClientSideAuthenticate (SSLContext *ctx,
1426 SSLAuthenticate auth)
1427 {
1428 if(ctx == NULL) {
1429 return errSecParam;
1430 }
1431 if(sslIsSessionActive(ctx)) {
1432 /* can't do this with an active session */
1433 return errSecBadReq;
1434 }
1435 ctx->clientAuth = auth;
1436 switch(auth) {
1437 case kNeverAuthenticate:
1438 tls_handshake_set_client_auth(ctx->hdsk, false);
1439 break;
1440 case kAlwaysAuthenticate:
1441 case kTryAuthenticate:
1442 tls_handshake_set_client_auth(ctx->hdsk, true);
1443 break;
1444 }
1445 return errSecSuccess;
1446 }
1447
1448 OSStatus
1449 SSLGetClientSideAuthenticate (SSLContext *ctx,
1450 SSLAuthenticate *auth) /* RETURNED */
1451 {
1452 if(ctx == NULL || auth == NULL) {
1453 return errSecParam;
1454 }
1455 *auth = ctx->clientAuth;
1456 return errSecSuccess;
1457 }
1458
1459 OSStatus
1460 SSLGetClientCertificateState (SSLContextRef ctx,
1461 SSLClientCertificateState *clientState)
1462 {
1463 if(ctx == NULL) {
1464 return errSecParam;
1465 }
1466 *clientState = ctx->clientCertState;
1467 return errSecSuccess;
1468 }
1469
1470 OSStatus
1471 SSLSetCertificate (SSLContextRef ctx,
1472 CFArrayRef certRefs)
1473 {
1474 /*
1475 * -- free localCerts if we have any
1476 * -- Get raw cert data, convert to ctx->localCert
1477 * -- get pub, priv keys from certRef[0]
1478 * -- validate cert chain
1479 */
1480 if(ctx == NULL) {
1481 return errSecParam;
1482 }
1483
1484 /* can't do this with an active session */
1485 if(sslIsSessionActive(ctx) &&
1486 /* kSSLClientCertRequested implies client side */
1487 (ctx->clientCertState != kSSLClientCertRequested))
1488 {
1489 return errSecBadReq;
1490 }
1491
1492 CFReleaseNull(ctx->localCertArray);
1493 /* changing the client cert invalidates negotiated auth type */
1494 ctx->negAuthType = SSLClientAuthNone;
1495 if(certRefs == NULL) {
1496 return errSecSuccess; // we have cleared the cert, as requested
1497 }
1498 OSStatus ortn = parseIncomingCerts(ctx,
1499 certRefs,
1500 &ctx->localCert,
1501 &ctx->signingPrivKeyRef);
1502 if(ortn == errSecSuccess) {
1503 ctx->localCertArray = certRefs;
1504 CFRetain(certRefs);
1505 if(ctx->protocolSide==kSSLClientSide)
1506 SSLUpdateNegotiatedClientAuthType(ctx);
1507 tls_handshake_set_identity(ctx->hdsk, ctx->localCert, ctx->signingPrivKeyRef);
1508 }
1509 return ortn;
1510 }
1511
1512 OSStatus
1513 SSLSetEncryptionCertificate (SSLContextRef ctx,
1514 CFArrayRef certRefs)
1515 {
1516 /*
1517 * -- free encryptCert if we have any
1518 * -- Get raw cert data, convert to ctx->encryptCert
1519 * -- get pub, priv keys from certRef[0]
1520 * -- validate cert chain
1521 */
1522 if(ctx == NULL) {
1523 return errSecParam;
1524 }
1525 if(sslIsSessionActive(ctx)) {
1526 /* can't do this with an active session */
1527 return errSecBadReq;
1528 }
1529 CFReleaseNull(ctx->encryptCertArray);
1530 OSStatus ortn = parseIncomingCerts(ctx,
1531 certRefs,
1532 &ctx->encryptCert,
1533 &ctx->encryptPrivKeyRef);
1534 if(ortn == errSecSuccess) {
1535 ctx->encryptCertArray = certRefs;
1536 CFRetain(certRefs);
1537 }
1538 return ortn;
1539 }
1540
1541 OSStatus SSLGetCertificate(SSLContextRef ctx,
1542 CFArrayRef *certRefs)
1543 {
1544 if(ctx == NULL) {
1545 return errSecParam;
1546 }
1547 *certRefs = ctx->localCertArray;
1548 return errSecSuccess;
1549 }
1550
1551 OSStatus SSLGetEncryptionCertificate(SSLContextRef ctx,
1552 CFArrayRef *certRefs)
1553 {
1554 if(ctx == NULL) {
1555 return errSecParam;
1556 }
1557 *certRefs = ctx->encryptCertArray;
1558 return errSecSuccess;
1559 }
1560
1561 OSStatus
1562 SSLSetPeerID (SSLContext *ctx,
1563 const void *peerID,
1564 size_t peerIDLen)
1565 {
1566 OSStatus serr;
1567
1568 /* copy peerId to context->peerId */
1569 if((ctx == NULL) ||
1570 (peerID == NULL) ||
1571 (peerIDLen == 0)) {
1572 return errSecParam;
1573 }
1574 if(sslIsSessionActive(ctx) &&
1575 /* kSSLClientCertRequested implies client side */
1576 (ctx->clientCertState != kSSLClientCertRequested))
1577 {
1578 return errSecBadReq;
1579 }
1580 SSLFreeBuffer(&ctx->peerID);
1581 serr = SSLAllocBuffer(&ctx->peerID, peerIDLen);
1582 if(serr) {
1583 return serr;
1584 }
1585 tls_handshake_set_resumption(ctx->hdsk, true);
1586 memmove(ctx->peerID.data, peerID, peerIDLen);
1587 return errSecSuccess;
1588 }
1589
1590 OSStatus
1591 SSLGetPeerID (SSLContextRef ctx,
1592 const void **peerID,
1593 size_t *peerIDLen)
1594 {
1595 *peerID = ctx->peerID.data; // may be NULL
1596 *peerIDLen = ctx->peerID.length;
1597 return errSecSuccess;
1598 }
1599
1600 OSStatus
1601 SSLGetNegotiatedCipher (SSLContextRef ctx,
1602 SSLCipherSuite *cipherSuite)
1603 {
1604 if(ctx == NULL) {
1605 return errSecParam;
1606 }
1607
1608 if(!sslIsSessionActive(ctx)) {
1609 return errSecBadReq;
1610 }
1611
1612 *cipherSuite = (SSLCipherSuite)tls_handshake_get_negotiated_cipherspec(ctx->hdsk);
1613
1614 return errSecSuccess;
1615 }
1616
1617 /*
1618 * Add an acceptable distinguished name (client authentication only).
1619 */
1620 OSStatus
1621 SSLAddDistinguishedName(
1622 SSLContextRef ctx,
1623 const void *derDN,
1624 size_t derDNLen)
1625 {
1626 DNListElem *dn;
1627 OSStatus err;
1628
1629 if(ctx == NULL) {
1630 return errSecParam;
1631 }
1632 if(sslIsSessionActive(ctx)) {
1633 return errSecBadReq;
1634 }
1635
1636 dn = (DNListElem *)sslMalloc(sizeof(DNListElem));
1637 if(dn == NULL) {
1638 return errSecAllocate;
1639 }
1640 if ((err = SSLAllocBuffer(&dn->derDN, derDNLen)))
1641 return err;
1642 memcpy(dn->derDN.data, derDN, derDNLen);
1643 dn->next = ctx->acceptableDNList;
1644 ctx->acceptableDNList = dn;
1645
1646 tls_handshake_set_acceptable_dn_list(ctx->hdsk, dn);
1647
1648 return errSecSuccess;
1649 }
1650
1651 /* single-cert version of SSLSetCertificateAuthorities() */
1652 static OSStatus
1653 sslAddCA(SSLContextRef ctx,
1654 SecCertificateRef cert)
1655 {
1656 OSStatus ortn = errSecParam;
1657
1658 /* Get subject from certificate. */
1659 #if TARGET_OS_IPHONE
1660 CFDataRef subjectName = NULL;
1661 subjectName = SecCertificateCopySubjectSequence(cert);
1662 require(subjectName, errOut);
1663 #else
1664 CSSM_DATA_PTR subjectName = NULL;
1665 ortn = SecCertificateCopyFirstFieldValue(cert, &CSSMOID_X509V1SubjectNameStd, &subjectName);
1666 require_noerr(ortn, errOut);
1667 #endif
1668
1669 /* add to acceptableCAs as cert, creating array if necessary */
1670 if(ctx->acceptableCAs == NULL) {
1671 require(ctx->acceptableCAs = CFArrayCreateMutable(NULL, 0,
1672 &kCFTypeArrayCallBacks), errOut);
1673 if(ctx->acceptableCAs == NULL) {
1674 return errSecAllocate;
1675 }
1676 }
1677 CFArrayAppendValue(ctx->acceptableCAs, cert);
1678
1679 /* then add this cert's subject name to acceptableDNList */
1680 #if TARGET_OS_IPHONE
1681 ortn = SSLAddDistinguishedName(ctx,
1682 CFDataGetBytePtr(subjectName),
1683 CFDataGetLength(subjectName));
1684 #else
1685 ortn = SSLAddDistinguishedName(ctx, subjectName->Data, subjectName->Length);
1686 #endif
1687
1688 errOut:
1689 #if TARGET_OS_IPHONE
1690 CFReleaseSafe(subjectName);
1691 #endif
1692 return ortn;
1693 }
1694
1695 /*
1696 * Add a SecCertificateRef, or a CFArray of them, to a server's list
1697 * of acceptable Certificate Authorities (CAs) to present to the client
1698 * when client authentication is performed.
1699 */
1700 OSStatus
1701 SSLSetCertificateAuthorities(SSLContextRef ctx,
1702 CFTypeRef certificateOrArray,
1703 Boolean replaceExisting)
1704 {
1705 CFTypeID itemType;
1706 OSStatus ortn = errSecSuccess;
1707
1708 if((ctx == NULL) || sslIsSessionActive(ctx) ||
1709 (ctx->protocolSide != kSSLServerSide)) {
1710 return errSecParam;
1711 }
1712 if(replaceExisting) {
1713 sslFreeDnList(ctx);
1714 if(ctx->acceptableCAs) {
1715 CFRelease(ctx->acceptableCAs);
1716 ctx->acceptableCAs = NULL;
1717 }
1718 }
1719 /* else appending */
1720
1721 itemType = CFGetTypeID(certificateOrArray);
1722 if(itemType == SecCertificateGetTypeID()) {
1723 /* one cert */
1724 ortn = sslAddCA(ctx, (SecCertificateRef)certificateOrArray);
1725 }
1726 else if(itemType == CFArrayGetTypeID()) {
1727 CFArrayRef cfa = (CFArrayRef)certificateOrArray;
1728 CFIndex numCerts = CFArrayGetCount(cfa);
1729 CFIndex dex;
1730
1731 /* array of certs */
1732 for(dex=0; dex<numCerts; dex++) {
1733 SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(cfa, dex);
1734 if(CFGetTypeID(cert) != SecCertificateGetTypeID()) {
1735 return errSecParam;
1736 }
1737 ortn = sslAddCA(ctx, cert);
1738 if(ortn) {
1739 break;
1740 }
1741 }
1742 }
1743 else {
1744 ortn = errSecParam;
1745 }
1746 return ortn;
1747 }
1748
1749
1750 /*
1751 * Obtain the certificates specified in SSLSetCertificateAuthorities(),
1752 * if any. Returns a NULL array if SSLSetCertificateAuthorities() has not
1753 * been called.
1754 * Caller must CFRelease the returned array.
1755 */
1756 OSStatus
1757 SSLCopyCertificateAuthorities(SSLContextRef ctx,
1758 CFArrayRef *certificates) /* RETURNED */
1759 {
1760 if((ctx == NULL) || (certificates == NULL)) {
1761 return errSecParam;
1762 }
1763 if(ctx->acceptableCAs == NULL) {
1764 *certificates = NULL;
1765 return errSecSuccess;
1766 }
1767 *certificates = ctx->acceptableCAs;
1768 CFRetain(ctx->acceptableCAs);
1769 return errSecSuccess;
1770 }
1771
1772
1773 /*
1774 * Obtain the list of acceptable distinguished names as provided by
1775 * a server (if the SSLCotextRef is configured as a client), or as
1776 * specified by SSLSetCertificateAuthorities() (if the SSLContextRef
1777 * is configured as a server).
1778 */
1779 OSStatus
1780 SSLCopyDistinguishedNames (SSLContextRef ctx,
1781 CFArrayRef *names)
1782 {
1783 CFMutableArrayRef outArray = NULL;
1784 const DNListElem *dn;
1785
1786 if((ctx == NULL) || (names == NULL)) {
1787 return errSecParam;
1788 }
1789 if(ctx->protocolSide==kSSLServerSide) {
1790 dn = ctx->acceptableDNList;
1791 } else {
1792 dn = tls_handshake_get_peer_acceptable_dn_list(ctx->hdsk); // ctx->acceptableDNList;
1793 }
1794
1795 if(dn == NULL) {
1796 *names = NULL;
1797 return errSecSuccess;
1798 }
1799 outArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1800
1801 while (dn) {
1802 CFDataRef cfDn = CFDataCreate(NULL, dn->derDN.data, dn->derDN.length);
1803 CFArrayAppendValue(outArray, cfDn);
1804 CFRelease(cfDn);
1805 dn = dn->next;
1806 }
1807 *names = outArray;
1808 return errSecSuccess;
1809 }
1810
1811
1812 /*
1813 * Request peer certificates. Valid anytime, subsequent to
1814 * a handshake attempt.
1815 * Common code for SSLGetPeerCertificates() and SSLCopyPeerCertificates().
1816 * TODO: the 'legacy' argument is not used anymore.
1817 */
1818 static OSStatus
1819 sslCopyPeerCertificates (SSLContextRef ctx,
1820 CFArrayRef *certs,
1821 Boolean legacy)
1822 {
1823 if(ctx == NULL) {
1824 return errSecParam;
1825 }
1826
1827 if (!ctx->peerCert) {
1828 *certs = NULL;
1829 return errSecBadReq;
1830 }
1831
1832 CFArrayRef ca = CFArrayCreateCopy(kCFAllocatorDefault, ctx->peerCert);
1833 *certs = ca;
1834 if (ca == NULL) {
1835 return errSecAllocate;
1836 }
1837
1838 if (legacy) {
1839 CFIndex ix, count = CFArrayGetCount(ca);
1840 for (ix = 0; ix < count; ++ix) {
1841 CFRetain(CFArrayGetValueAtIndex(ca, ix));
1842 }
1843 }
1844
1845 return errSecSuccess;
1846 }
1847
1848 OSStatus
1849 SSLCopyPeerCertificates (SSLContextRef ctx,
1850 CFArrayRef *certs)
1851 {
1852 return sslCopyPeerCertificates(ctx, certs, false);
1853 }
1854
1855 #if !TARGET_OS_IPHONE
1856 // Permanently removing from iOS, keep for OSX (deprecated), removed from headers.
1857 // <rdar://problem/14215831> Mailsmith Crashes While Getting New Mail Under Mavericks Developer Preview
1858 OSStatus
1859 SSLGetPeerCertificates (SSLContextRef ctx,
1860 CFArrayRef *certs);
1861 OSStatus
1862 SSLGetPeerCertificates (SSLContextRef ctx,
1863 CFArrayRef *certs)
1864 {
1865 return sslCopyPeerCertificates(ctx, certs, true);
1866 }
1867 #endif
1868
1869 /*
1870 * Specify Diffie-Hellman parameters. Optional; if we are configured to allow
1871 * for D-H ciphers and a D-H cipher is negotiated, and this function has not
1872 * been called, a set of process-wide parameters will be calculated. However
1873 * that can take a long time (30 seconds).
1874 */
1875 OSStatus SSLSetDiffieHellmanParams(
1876 SSLContextRef ctx,
1877 const void *dhParams,
1878 size_t dhParamsLen)
1879 {
1880 #if APPLE_DH
1881 if(ctx == NULL) {
1882 return errSecParam;
1883 }
1884 if(sslIsSessionActive(ctx)) {
1885 return errSecBadReq;
1886 }
1887 SSLFreeBuffer(&ctx->dhParamsEncoded);
1888
1889 OSStatus ortn;
1890 ortn = SSLCopyBufferFromData(dhParams, dhParamsLen,
1891 &ctx->dhParamsEncoded);
1892
1893 return ortn;
1894
1895 #endif /* APPLE_DH */
1896 }
1897
1898 /*
1899 * Return parameter block specified in SSLSetDiffieHellmanParams.
1900 * Returned data is not copied and belongs to the SSLContextRef.
1901 */
1902 OSStatus SSLGetDiffieHellmanParams(
1903 SSLContextRef ctx,
1904 const void **dhParams,
1905 size_t *dhParamsLen)
1906 {
1907 #if APPLE_DH
1908 if(ctx == NULL) {
1909 return errSecParam;
1910 }
1911 *dhParams = ctx->dhParamsEncoded.data;
1912 *dhParamsLen = ctx->dhParamsEncoded.length;
1913 return errSecSuccess;
1914 #else
1915 return errSecUnimplemented;
1916 #endif /* APPLE_DH */
1917 }
1918
1919 OSStatus SSLSetRsaBlinding(
1920 SSLContextRef ctx,
1921 Boolean blinding)
1922 {
1923 if(ctx == NULL) {
1924 return errSecParam;
1925 }
1926 ctx->rsaBlindingEnable = blinding;
1927 return errSecSuccess;
1928 }
1929
1930 OSStatus SSLGetRsaBlinding(
1931 SSLContextRef ctx,
1932 Boolean *blinding)
1933 {
1934 if(ctx == NULL) {
1935 return errSecParam;
1936 }
1937 *blinding = ctx->rsaBlindingEnable;
1938 return errSecSuccess;
1939 }
1940
1941 OSStatus
1942 SSLCopyPeerTrust(
1943 SSLContextRef ctx,
1944 SecTrustRef *trust) /* RETURNED */
1945 {
1946 OSStatus status = errSecSuccess;
1947 if (ctx == NULL || trust == NULL)
1948 return errSecParam;
1949
1950 /* Create a SecTrustRef if this was a resumed session and we
1951 didn't have one yet. */
1952 if (!ctx->peerCert) {
1953 ctx->peerCert = tls_get_peer_certs(tls_handshake_get_peer_certificates(ctx->hdsk));
1954 }
1955 if (!ctx->peerSecTrust && ctx->peerCert) {
1956 status = sslCreateSecTrust(ctx, ctx->peerCert, true,
1957 &ctx->peerSecTrust);
1958 }
1959
1960 *trust = ctx->peerSecTrust;
1961 if (ctx->peerSecTrust)
1962 CFRetain(ctx->peerSecTrust);
1963
1964 return status;
1965 }
1966
1967 OSStatus SSLGetPeerSecTrust(
1968 SSLContextRef ctx,
1969 SecTrustRef *trust) /* RETURNED */
1970 {
1971 OSStatus status = errSecSuccess;
1972 if (ctx == NULL || trust == NULL)
1973 return errSecParam;
1974
1975 /* Create a SecTrustRef if this was a resumed session and we
1976 didn't have one yet. */
1977 if (!ctx->peerSecTrust && ctx->peerCert) {
1978 status = sslCreateSecTrust(ctx, ctx->peerCert, true,
1979 &ctx->peerSecTrust);
1980 }
1981
1982 *trust = ctx->peerSecTrust;
1983 return status;
1984 }
1985
1986 OSStatus SSLInternalMasterSecret(
1987 SSLContextRef ctx,
1988 void *secret, // mallocd by caller, SSL_MASTER_SECRET_SIZE
1989 size_t *secretSize) // in/out
1990 {
1991 if((ctx == NULL) || (secret == NULL) || (secretSize == NULL)) {
1992 return errSecParam;
1993 }
1994 return tls_handshake_internal_master_secret(ctx->hdsk, secret, secretSize);
1995 }
1996
1997 OSStatus SSLInternalServerRandom(
1998 SSLContextRef ctx,
1999 void *randBuf, // mallocd by caller, SSL_CLIENT_SRVR_RAND_SIZE
2000 size_t *randSize) // in/out
2001 {
2002 if((ctx == NULL) || (randBuf == NULL) || (randSize == NULL)) {
2003 return errSecParam;
2004 }
2005 return tls_handshake_internal_server_random(ctx->hdsk, randBuf, randSize);
2006 }
2007
2008 OSStatus SSLInternalClientRandom(
2009 SSLContextRef ctx,
2010 void *randBuf, // mallocd by caller, SSL_CLIENT_SRVR_RAND_SIZE
2011 size_t *randSize) // in/out
2012 {
2013 if((ctx == NULL) || (randBuf == NULL) || (randSize == NULL)) {
2014 return errSecParam;
2015 }
2016 return tls_handshake_internal_client_random(ctx->hdsk, randBuf, randSize);
2017 }
2018
2019 /* This is used by EAP 802.1x */
2020 OSStatus SSLGetCipherSizes(
2021 SSLContextRef ctx,
2022 size_t *digestSize,
2023 size_t *symmetricKeySize,
2024 size_t *ivSize)
2025 {
2026 if((ctx == NULL) || (digestSize == NULL) ||
2027 (symmetricKeySize == NULL) || (ivSize == NULL)) {
2028 return errSecParam;
2029 }
2030
2031 SSLCipherSuite cipher=tls_handshake_get_negotiated_cipherspec(ctx->hdsk);
2032
2033 *digestSize = sslCipherSuiteGetMacSize(cipher);
2034 *symmetricKeySize = sslCipherSuiteGetSymmetricCipherKeySize(cipher);
2035 *ivSize = sslCipherSuiteGetSymmetricCipherBlockIvSize(cipher);
2036 return errSecSuccess;
2037 }
2038
2039 OSStatus
2040 SSLGetResumableSessionInfo(
2041 SSLContextRef ctx,
2042 Boolean *sessionWasResumed, // RETURNED
2043 void *sessionID, // RETURNED, mallocd by caller
2044 size_t *sessionIDLength) // IN/OUT
2045 {
2046 if((ctx == NULL) || (sessionWasResumed == NULL) ||
2047 (sessionID == NULL) || (sessionIDLength == NULL) ||
2048 (*sessionIDLength < MAX_SESSION_ID_LENGTH)) {
2049 return errSecParam;
2050 }
2051
2052 SSLBuffer localSessionID;
2053 bool sessionMatch = tls_handshake_get_session_match(ctx->hdsk, &localSessionID);
2054
2055 if(sessionMatch) {
2056 *sessionWasResumed = true;
2057 if(localSessionID.length > *sessionIDLength) {
2058 /* really should never happen - means ID > 32 */
2059 return errSecParam;
2060 }
2061 if(localSessionID.length) {
2062 /*
2063 * Note PAC-based session resumption can result in sessionMatch
2064 * with no sessionID
2065 */
2066 memmove(sessionID, localSessionID.data, localSessionID.length);
2067 }
2068 *sessionIDLength = localSessionID.length;
2069 }
2070 else {
2071 *sessionWasResumed = false;
2072 *sessionIDLength = 0;
2073 }
2074 return errSecSuccess;
2075 }
2076
2077 /*
2078 * Get/set enable of anonymous ciphers. Default is enabled.
2079 */
2080 OSStatus
2081 SSLSetAllowAnonymousCiphers(
2082 SSLContextRef ctx,
2083 Boolean enable)
2084 {
2085 if(ctx == NULL) {
2086 return errSecParam;
2087 }
2088 if(sslIsSessionActive(ctx)) {
2089 return errSecBadReq;
2090 }
2091 if(ctx->validCipherSuites != NULL) {
2092 /* SSLSetEnabledCiphers() has already been called */
2093 return errSecBadReq;
2094 }
2095 ctx->anonCipherEnable = enable;
2096 return errSecSuccess;
2097 }
2098
2099 OSStatus
2100 SSLGetAllowAnonymousCiphers(
2101 SSLContextRef ctx,
2102 Boolean *enable)
2103 {
2104 if((ctx == NULL) || (enable == NULL)) {
2105 return errSecParam;
2106 }
2107 if(sslIsSessionActive(ctx)) {
2108 return errSecBadReq;
2109 }
2110 *enable = ctx->anonCipherEnable;
2111 return errSecSuccess;
2112 }
2113
2114 /*
2115 * Override the default session cache timeout for a cache entry created for
2116 * the current session.
2117 */
2118 OSStatus
2119 SSLSetSessionCacheTimeout(
2120 SSLContextRef ctx,
2121 uint32_t timeoutInSeconds)
2122 {
2123 if(ctx == NULL) {
2124 return errSecParam;
2125 }
2126 ctx->sessionCacheTimeout = timeoutInSeconds;
2127 return errSecSuccess;
2128 }
2129
2130
2131 static
2132 void tls_handshake_master_secret_function(const void *arg, /* opaque to coreTLS; app-specific */
2133 void *secret, /* mallocd by caller, SSL_MASTER_SECRET_SIZE */
2134 size_t *secretLength)
2135 {
2136 SSLContextRef ctx = (SSLContextRef) arg;
2137 ctx->masterSecretCallback(ctx, ctx->masterSecretArg, secret, secretLength);
2138 }
2139
2140
2141 /*
2142 * Register a callback for obtaining the master_secret when performing
2143 * PAC-based session resumption.
2144 */
2145 OSStatus
2146 SSLInternalSetMasterSecretFunction(
2147 SSLContextRef ctx,
2148 SSLInternalMasterSecretFunction mFunc,
2149 const void *arg) /* opaque to SecureTransport; app-specific */
2150 {
2151 if(ctx == NULL) {
2152 return errSecParam;
2153 }
2154
2155 ctx->masterSecretArg = arg;
2156 ctx->masterSecretCallback = mFunc;
2157
2158 return tls_handshake_internal_set_master_secret_function(ctx->hdsk, &tls_handshake_master_secret_function, ctx);
2159 }
2160
2161 /*
2162 * Provide an opaque SessionTicket for use in PAC-based session
2163 * resumption. Client side only. The provided ticket is sent in
2164 * the ClientHello message as a SessionTicket extension.
2165 *
2166 * We won't reject this on the server side, but server-side support
2167 * for PAC-based session resumption is currently enabled for
2168 * Development builds only. To fully support this for server side,
2169 * besides the rudimentary support that's here for Development builds,
2170 * we'd need a getter for the session ticket, so the app code can
2171 * access the SessionTicket when its SSLInternalMasterSecretFunction
2172 * callback is called.
2173 */
2174 OSStatus SSLInternalSetSessionTicket(
2175 SSLContextRef ctx,
2176 const void *ticket,
2177 size_t ticketLength)
2178 {
2179 if(ctx == NULL) {
2180 return errSecParam;
2181 }
2182 if(sslIsSessionActive(ctx)) {
2183 /* can't do this with an active session */
2184 return errSecBadReq;
2185 }
2186 return tls_handshake_internal_set_session_ticket(ctx->hdsk, ticket, ticketLength);
2187 }
2188
2189
2190 /*
2191 * ECDSA curve accessors.
2192 */
2193
2194 /*
2195 * Obtain the SSL_ECDSA_NamedCurve negotiated during a handshake.
2196 * Returns errSecParam if no ECDH-related ciphersuite was negotiated.
2197 */
2198 OSStatus SSLGetNegotiatedCurve(
2199 SSLContextRef ctx,
2200 SSL_ECDSA_NamedCurve *namedCurve) /* RETURNED */
2201 {
2202 if((ctx == NULL) || (namedCurve == NULL)) {
2203 return errSecParam;
2204 }
2205 unsigned int curve = tls_handshake_get_negotiated_curve(ctx->hdsk);
2206 if(curve == SSL_Curve_None) {
2207 return errSecParam;
2208 }
2209 *namedCurve = curve;
2210 return errSecSuccess;
2211 }
2212
2213 /*
2214 * Obtain the number of currently enabled SSL_ECDSA_NamedCurves.
2215 */
2216 OSStatus SSLGetNumberOfECDSACurves(
2217 SSLContextRef ctx,
2218 unsigned *numCurves) /* RETURNED */
2219 {
2220 if((ctx == NULL) || (numCurves == NULL)) {
2221 return errSecParam;
2222 }
2223 *numCurves = ctx->ecdhNumCurves;
2224 return errSecSuccess;
2225 }
2226
2227 /*
2228 * Obtain the ordered list of currently enabled SSL_ECDSA_NamedCurves.
2229 */
2230 OSStatus SSLGetECDSACurves(
2231 SSLContextRef ctx,
2232 SSL_ECDSA_NamedCurve *namedCurves, /* RETURNED */
2233 unsigned *numCurves) /* IN/OUT */
2234 {
2235 if((ctx == NULL) || (namedCurves == NULL) || (numCurves == NULL)) {
2236 return errSecParam;
2237 }
2238 if(*numCurves < ctx->ecdhNumCurves) {
2239 return errSecParam;
2240 }
2241 memmove(namedCurves, ctx->ecdhCurves,
2242 (ctx->ecdhNumCurves * sizeof(SSL_ECDSA_NamedCurve)));
2243 *numCurves = ctx->ecdhNumCurves;
2244 return errSecSuccess;
2245 }
2246
2247 /*
2248 * Specify ordered list of allowable named curves.
2249 */
2250 OSStatus SSLSetECDSACurves(
2251 SSLContextRef ctx,
2252 const SSL_ECDSA_NamedCurve *namedCurves,
2253 unsigned numCurves)
2254 {
2255 if((ctx == NULL) || (namedCurves == NULL) || (numCurves == 0)) {
2256 return errSecParam;
2257 }
2258 if(sslIsSessionActive(ctx)) {
2259 /* can't do this with an active session */
2260 return errSecBadReq;
2261 }
2262
2263 size_t size = numCurves * sizeof(uint16_t);
2264 ctx->ecdhCurves = (uint16_t *)sslMalloc(size);
2265 if(ctx->ecdhCurves == NULL) {
2266 ctx->ecdhNumCurves = 0;
2267 return errSecAllocate;
2268 }
2269
2270 for (unsigned i=0; i<numCurves; i++) {
2271 ctx->ecdhCurves[i] = namedCurves[i];
2272 }
2273
2274 ctx->ecdhNumCurves = numCurves;
2275
2276 tls_handshake_set_curves(ctx->hdsk, ctx->ecdhCurves, ctx->ecdhNumCurves);
2277 return errSecSuccess;
2278 }
2279
2280 /*
2281 * Obtain the number of client authentication mechanisms specified by
2282 * the server in its Certificate Request message.
2283 * Returns errSecParam if server hasn't sent a Certificate Request message
2284 * (i.e., client certificate state is kSSLClientCertNone).
2285 */
2286 OSStatus SSLGetNumberOfClientAuthTypes(
2287 SSLContextRef ctx,
2288 unsigned *numTypes)
2289 {
2290 if((ctx == NULL) || (ctx->clientCertState == kSSLClientCertNone)) {
2291 return errSecParam;
2292 }
2293 *numTypes = ctx->numAuthTypes;
2294 return errSecSuccess;
2295 }
2296
2297 /*
2298 * Obtain the client authentication mechanisms specified by
2299 * the server in its Certificate Request message.
2300 * Caller allocates returned array and specifies its size (in
2301 * SSLClientAuthenticationTypes) in *numType on entry; *numTypes
2302 * is the actual size of the returned array on successful return.
2303 */
2304 OSStatus SSLGetClientAuthTypes(
2305 SSLContextRef ctx,
2306 SSLClientAuthenticationType *authTypes, /* RETURNED */
2307 unsigned *numTypes) /* IN/OUT */
2308 {
2309 if((ctx == NULL) || (ctx->clientCertState == kSSLClientCertNone)) {
2310 return errSecParam;
2311 }
2312 memmove(authTypes, ctx->clientAuthTypes,
2313 ctx->numAuthTypes * sizeof(SSLClientAuthenticationType));
2314 *numTypes = ctx->numAuthTypes;
2315 return errSecSuccess;
2316 }
2317
2318 /*
2319 * Obtain the SSLClientAuthenticationType actually performed.
2320 * Only valid if client certificate state is kSSLClientCertSent
2321 * or kSSLClientCertRejected; returns errSecParam otherwise.
2322 */
2323 OSStatus SSLGetNegotiatedClientAuthType(
2324 SSLContextRef ctx,
2325 SSLClientAuthenticationType *authType) /* RETURNED */
2326 {
2327 if(ctx == NULL) {
2328 return errSecParam;
2329 }
2330
2331 *authType = ctx->negAuthType;
2332
2333 return errSecSuccess;
2334 }
2335
2336 /*
2337 * Update the negotiated client authentication type.
2338 * This function may be called at any time; however, note that
2339 * the negotiated authentication type will be SSLClientAuthNone
2340 * until both of the following have taken place (in either order):
2341 * - a CertificateRequest message from the server has been processed
2342 * - a client certificate has been specified
2343 * As such, this function (only) needs to be called from (both)
2344 * SSLProcessCertificateRequest and SSLSetCertificate.
2345 */
2346 OSStatus SSLUpdateNegotiatedClientAuthType(
2347 SSLContextRef ctx)
2348 {
2349 if(ctx == NULL) {
2350 return errSecParam;
2351 }
2352 assert(ctx->protocolSide==kSSLClientSide);
2353 /*
2354 * See if we have a signing cert that matches one of the
2355 * allowed auth types. The x509Requested flag indicates "we
2356 * have a cert that we think the server will accept".
2357 */
2358 ctx->x509Requested = 0;
2359 ctx->negAuthType = SSLClientAuthNone;
2360 if(ctx->signingPrivKeyRef != NULL) {
2361 CFIndex ourKeyAlg = sslPrivKeyGetAlgorithmID((SecKeyRef)tls_private_key_get_context(ctx->signingPrivKeyRef));
2362 assert(ourKeyAlg==kSecRSAAlgorithmID); /* We don't suport anything else */
2363
2364 unsigned i;
2365 for(i=0; i<ctx->numAuthTypes; i++) {
2366 switch(ctx->clientAuthTypes[i]) {
2367 case SSLClientAuth_RSASign:
2368 if(ourKeyAlg == kSecRSAAlgorithmID) {
2369 ctx->x509Requested = 1;
2370 ctx->negAuthType = SSLClientAuth_RSASign;
2371 }
2372 break;
2373 #if 0
2374 // The code below is hopelessly broken: ctx->ourSignerAlg is never set
2375 #if SSL_ENABLE_ECDSA_SIGN_AUTH
2376 case SSLClientAuth_ECDSASign:
2377 #endif
2378 #if SSL_ENABLE_ECDSA_FIXED_ECDH_AUTH
2379 case SSLClientAuth_ECDSAFixedECDH:
2380 #endif
2381 if((ourKeyAlg == kSecECDSAAlgorithmID) &&
2382 (ctx->ourSignerAlg == kSecECDSAAlgorithmID)) {
2383 ctx->x509Requested = 1;
2384 ctx->negAuthType = ctx->clientAuthTypes[i];
2385 }
2386 break;
2387 #if SSL_ENABLE_RSA_FIXED_ECDH_AUTH
2388 case SSLClientAuth_RSAFixedECDH:
2389 /* Odd case, we differ from our signer */
2390 if((ourKeyAlg == kSecECDSAAlgorithmID) &&
2391 (ctx->ourSignerAlg == kSecRSAAlgorithmID)) {
2392 ctx->x509Requested = 1;
2393 ctx->negAuthType = SSLClientAuth_RSAFixedECDH;
2394 }
2395 break;
2396 #endif
2397 #endif
2398 default:
2399 /* None others supported */
2400 break;
2401 }
2402 if(ctx->x509Requested) {
2403 sslLogNegotiateDebug("===CHOOSING authType %d", (int)ctx->negAuthType);
2404 break;
2405 }
2406 } /* parsing authTypes */
2407 } /* we have a signing key */
2408
2409 tls_handshake_set_client_auth_type(ctx->hdsk, ctx->negAuthType);
2410
2411 return errSecSuccess;
2412 }
2413
2414 OSStatus SSLGetNumberOfSignatureAlgorithms(
2415 SSLContextRef ctx,
2416 unsigned *numSigAlgs)
2417 {
2418 if(ctx == NULL){
2419 return errSecParam;
2420 }
2421
2422 tls_handshake_get_peer_signature_algorithms(ctx->hdsk, numSigAlgs);
2423 return errSecSuccess;
2424 }
2425
2426 _Static_assert(sizeof(SSLSignatureAndHashAlgorithm)==sizeof(tls_signature_and_hash_algorithm),
2427 "SSLSignatureAndHashAlgorithm and tls_signature_and_hash_algorithm do not match");
2428
2429 OSStatus SSLGetSignatureAlgorithms(
2430 SSLContextRef ctx,
2431 SSLSignatureAndHashAlgorithm *sigAlgs, /* RETURNED */
2432 unsigned *numSigAlgs) /* IN/OUT */
2433 {
2434 if(ctx == NULL) {
2435 return errSecParam;
2436 }
2437
2438 unsigned numPeerSigAlgs;
2439 const tls_signature_and_hash_algorithm *peerAlgs = tls_handshake_get_peer_signature_algorithms(ctx->hdsk, &numPeerSigAlgs);
2440
2441 memmove(sigAlgs, peerAlgs,
2442 numPeerSigAlgs * sizeof(SSLSignatureAndHashAlgorithm));
2443 *numSigAlgs = numPeerSigAlgs;
2444 return errSecSuccess;
2445 }
2446
2447 /* PSK SPIs */
2448 OSStatus SSLSetPSKSharedSecret(SSLContextRef ctx,
2449 const void *secret,
2450 size_t secretLen)
2451 {
2452 if(ctx == NULL) return errSecParam;
2453
2454 if(ctx->pskSharedSecret.data)
2455 SSLFreeBuffer(&ctx->pskSharedSecret);
2456
2457 if(SSLCopyBufferFromData(secret, secretLen, &ctx->pskSharedSecret))
2458 return errSecAllocate;
2459
2460 tls_handshake_set_psk_secret(ctx->hdsk, &ctx->pskSharedSecret);
2461
2462 return errSecSuccess;
2463 }
2464
2465 OSStatus SSLSetPSKIdentity(SSLContextRef ctx,
2466 const void *pskIdentity,
2467 size_t pskIdentityLen)
2468 {
2469 if((ctx == NULL) || (pskIdentity == NULL) || (pskIdentityLen == 0)) return errSecParam;
2470
2471 if(ctx->pskIdentity.data)
2472 SSLFreeBuffer(&ctx->pskIdentity);
2473
2474 if(SSLCopyBufferFromData(pskIdentity, pskIdentityLen, &ctx->pskIdentity))
2475 return errSecAllocate;
2476
2477 tls_handshake_set_psk_identity(ctx->hdsk, &ctx->pskIdentity);
2478
2479 return errSecSuccess;
2480
2481 }
2482
2483 OSStatus SSLGetPSKIdentity(SSLContextRef ctx,
2484 const void **pskIdentity,
2485 size_t *pskIdentityLen)
2486 {
2487 if((ctx == NULL) || (pskIdentity == NULL) || (pskIdentityLen == NULL)) return errSecParam;
2488
2489 *pskIdentity=ctx->pskIdentity.data;
2490 *pskIdentityLen=ctx->pskIdentity.length;
2491
2492 return errSecSuccess;
2493 }
2494
2495 OSStatus SSLInternal_PRF(
2496 SSLContext *ctx,
2497 const void *vsecret,
2498 size_t secretLen,
2499 const void *label, // optional, NULL implies that seed contains
2500 // the label
2501 size_t labelLen,
2502 const void *seed,
2503 size_t seedLen,
2504 void *vout, // mallocd by caller, length >= outLen
2505 size_t outLen)
2506 {
2507 return tls_handshake_internal_prf(ctx->hdsk,
2508 vsecret, secretLen,
2509 label, labelLen,
2510 seed, seedLen,
2511 vout, outLen);
2512 }
2513
2514