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