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