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