]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_ssl/lib/sslTransport.c
Security-59754.60.13.tar.gz
[apple/security.git] / OSX / libsecurity_ssl / lib / sslTransport.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 * sslTransport.c - SSL transport layer
26 */
27
28 #include "ssl.h"
29 #include "sslMemory.h"
30 #include "sslContext.h"
31 #include "sslRecord.h"
32 #include "sslDebug.h"
33 #include "sslCipherSpecs.h"
34
35 #include <utilities/simulatecrash_assert.h>
36 #include <string.h>
37
38 #include <utilities/SecIOFormat.h>
39 #include <utilities/SecCFWrappers.h>
40 #import <utilities/SecCoreAnalytics.h>
41
42 #include <CommonCrypto/CommonDigest.h>
43 #include <Security/SecCertificatePriv.h>
44
45 #ifndef NDEBUG
46 static inline void sslIoTrace(
47 SSLContext *ctx,
48 const char *op,
49 size_t req,
50 size_t moved,
51 OSStatus stat)
52 {
53 sslLogRecordIo("[%p] ===%s: req %4lu moved %4lu status %d",
54 ctx, op, req, moved, (int)stat);
55 }
56 #else
57 #define sslIoTrace(ctx, op, req, moved, stat)
58 #endif /* NDEBUG */
59
60 extern int kSplitDefaultValue;
61
62 static OSStatus SSLProcessProtocolMessage(SSLRecord *rec, SSLContext *ctx);
63 static OSStatus SSLHandshakeProceed(SSLContext *ctx);
64 static OSStatus SSLSendAlert(SSLContext *ctx, tls_alert_level_t level, tls_alert_t description);
65
66 OSStatus
67 SSLWrite(
68 SSLContext *ctx,
69 const void * data,
70 size_t dataLength,
71 size_t *bytesWritten) /* RETURNED */
72 {
73 OSStatus err;
74 SSLRecord rec;
75 size_t dataLen, processed;
76
77 sslLogRecordIo("[%p] SSLWrite top", ctx);
78 if((ctx == NULL) || (bytesWritten == NULL)) {
79 return errSecParam;
80 }
81 dataLen = dataLength;
82 *bytesWritten = 0;
83
84 switch(ctx->state) {
85 case SSL_HdskStateGracefulClose:
86 err = errSSLClosedGraceful;
87 goto abort;
88 case SSL_HdskStateErrorClose:
89 case SSL_HdskStateOutOfBandError:
90 err = errSSLClosedAbort;
91 goto abort;
92 case SSL_HdskStateReady:
93 break;
94 case SSL_HdskStateUninit:
95 /* not ready for I/O, and handshake not in progress */
96 sslIoTrace(ctx, "SSLWrite(1)", dataLength, 0, errSecBadReq);
97 return errSecBadReq;
98 default:
99 /* handshake in progress or done. Will call SSLHandshakeProceed below if necessary */
100 break;
101 }
102
103 /* First, we have to wait until the session is ready to send data,
104 so the encryption keys and such have been established. */
105 while (!(ctx->writeCipher_ready))
106 { if ((err = SSLHandshakeProceed(ctx)) != 0)
107 goto exit;
108 }
109
110 /* Attempt to empty the write queue before queueing more data */
111 if ((err = SSLServiceWriteQueue(ctx)) != 0)
112 goto abort;
113
114 processed = 0;
115
116 /* Skip empty writes, fragmentation is done at the coreTLS layer */
117 if(dataLen) {
118 rec.contentType = SSL_RecordTypeAppData;
119 rec.contents.data = ((uint8_t *)data) + processed;
120 rec.contents.length = dataLen;
121 if ((err = SSLWriteRecord(rec, ctx)) != 0)
122 goto exit;
123 processed += rec.contents.length;
124 }
125
126 /* All the data has been advanced to the write queue */
127 *bytesWritten = processed;
128 if ((err = SSLServiceWriteQueue(ctx)) == 0) {
129 err = errSecSuccess;
130 }
131 exit:
132 switch(err) {
133 case errSecSuccess:
134 case errSSLWouldBlock:
135 case errSSLUnexpectedRecord:
136 case errSSLServerAuthCompleted: /* == errSSLClientAuthCompleted */
137 case errSSLClientCertRequested:
138 case errSSLClientHelloReceived:
139 case errSSLClosedGraceful:
140 break;
141 default:
142 sslErrorLog("SSLWrite: going to state errorClose due to err %d\n",
143 (int)err);
144 SSLChangeHdskState(ctx, SSL_HdskStateErrorClose);
145 break;
146 }
147 abort:
148 sslIoTrace(ctx, "SSLWrite(2)", dataLength, *bytesWritten, err);
149 return err;
150 }
151
152 OSStatus
153 SSLRead (
154 SSLContext *ctx,
155 void * data,
156 size_t dataLength,
157 size_t *processed) /* RETURNED */
158 {
159 OSStatus err;
160 uint8_t *charPtr;
161 size_t bufSize, remaining, count;
162 SSLRecord rec;
163
164 sslLogRecordIo("[%p] SSLRead top (dataLength=%ld)", ctx, dataLength);
165 if((ctx == NULL) || (data == NULL) || (processed == NULL)) {
166 return errSecParam;
167 }
168 bufSize = dataLength;
169 *processed = 0; /* Initialize in case we return with errSSLWouldBlock */
170
171 readRetry:
172 /* first handle cases in which we know we're finished */
173 switch(ctx->state) {
174 case SSL_HdskStateGracefulClose:
175 err = errSSLClosedGraceful;
176 goto abort;
177 case SSL_HdskStateErrorClose:
178 case SSL_HdskStateOutOfBandError:
179 err = errSSLClosedAbort;
180 goto abort;
181 case SSL_HdskStateNoNotifyClose:
182 err = errSSLClosedNoNotify;
183 goto abort;
184 default:
185 break;
186 }
187
188 /* First, we have to wait until the session is ready to receive data,
189 so the encryption keys and such have been established. */
190 while (ctx->readCipher_ready == 0) {
191 if ((err = SSLHandshakeProceed(ctx)) != 0) {
192 goto exit;
193 }
194 }
195
196 /* Need this to handle the case were SSLRead returned
197 errSSLClientHelloReceived as readCipher_ready is not set yet in that case */
198 if ((err = tls_handshake_continue(ctx->hdsk)) != 0)
199 return err;
200
201 /* Attempt to service the write queue */
202 if ((err = SSLServiceWriteQueue(ctx)) != 0) {
203 if (err != errSSLWouldBlock) {
204 goto exit;
205 }
206 }
207
208 remaining = bufSize;
209 charPtr = (uint8_t *)data;
210
211 /* If we have data in the buffer, use that first */
212 if (ctx->receivedDataBuffer.data)
213 {
214 count = ctx->receivedDataBuffer.length - ctx->receivedDataPos;
215 if (count > bufSize)
216 count = bufSize;
217 memcpy(data, ctx->receivedDataBuffer.data + ctx->receivedDataPos, count);
218 remaining -= count;
219 charPtr += count;
220 *processed += count;
221 ctx->receivedDataPos += count;
222 }
223
224 assert(ctx->receivedDataPos <= ctx->receivedDataBuffer.length);
225 assert(*processed + remaining == bufSize);
226 assert(charPtr == ((uint8_t *)data) + *processed);
227
228 if (ctx->receivedDataBuffer.data != 0 &&
229 ctx->receivedDataPos >= ctx->receivedDataBuffer.length)
230 {
231 SSLFreeBuffer(&ctx->receivedDataBuffer);
232 ctx->receivedDataBuffer.data = 0;
233 ctx->receivedDataPos = 0;
234 }
235
236 /*
237 * If we didnt fill up the users buffer, get some more data
238 */
239 if (remaining > 0 && ctx->state != SSL_HdskStateGracefulClose)
240 {
241 assert(ctx->receivedDataBuffer.data == 0);
242 if ((err = SSLReadRecord(&rec, ctx)) != 0) {
243 goto exit;
244 }
245 if (rec.contentType == SSL_RecordTypeAppData ||
246 rec.contentType == SSL_RecordTypeV2_0)
247 {
248 if (rec.contents.length <= remaining)
249 { /* Copy all we got in the user's buffer */
250 memcpy(charPtr, rec.contents.data, rec.contents.length);
251 *processed += rec.contents.length;
252 {
253 if ((err = SSLFreeRecord(rec, ctx))) {
254 goto exit;
255 }
256 }
257 }
258 else
259 { /* Copy what we can in the user's buffer, keep the rest for next SSLRead. */
260 memcpy(charPtr, rec.contents.data, remaining);
261 *processed += remaining;
262 ctx->receivedDataBuffer = rec.contents;
263 ctx->receivedDataPos = remaining;
264 }
265 }
266 else {
267 if ((err = SSLProcessProtocolMessage(&rec, ctx)) != 0) {
268 /* This may not make much sense, but this is required so that we
269 process the write queue. This replicate exactly the behavior
270 before the coreTLS adoption */
271 if(err == errSSLClosedGraceful) {
272 SSLClose(ctx);
273 } else {
274 goto exit;
275 }
276 }
277 if ((err = SSLFreeRecord(rec, ctx))) {
278 goto exit;
279 }
280 }
281 }
282
283 err = errSecSuccess;
284
285 exit:
286 /* test for renegotiate: loop until something useful happens */
287 if(((err == errSecSuccess) && (*processed == 0) && dataLength) || (err == errSSLUnexpectedRecord)) {
288 sslLogNegotiateDebug("SSLRead recursion");
289 goto readRetry;
290 }
291 /* shut down on serious errors */
292 switch(err) {
293 case errSecSuccess:
294 case errSSLWouldBlock:
295 case errSSLUnexpectedRecord:
296 case errSSLServerAuthCompleted: /* == errSSLClientAuthCompleted */
297 case errSSLClientCertRequested:
298 case errSSLClientHelloReceived:
299 case errSSLClosedGraceful:
300 case errSSLClosedNoNotify:
301 break;
302 default:
303 sslErrorLog("SSLRead: going to state errorClose due to err %d\n",
304 (int)err);
305 SSLChangeHdskState(ctx, SSL_HdskStateErrorClose);
306 break;
307 }
308 abort:
309 sslIoTrace(ctx, "SSLRead returns", dataLength, *processed, err);
310 return err;
311 }
312
313 #if SSL_DEBUG
314 #include "sslCrypto.h"
315 #endif
316
317
318
319 static void get_extended_peer_id(SSLContext *ctx, tls_buffer *extended_peer_id)
320 {
321 uint8_t md[CC_SHA256_DIGEST_LENGTH];
322 __block CC_SHA256_CTX hash_ctx;
323
324 CC_SHA256_Init(&hash_ctx);
325
326 CC_SHA256_Update(&hash_ctx, &ctx->allowAnyRoot, sizeof(ctx->allowAnyRoot));
327
328 #if !TARGET_OS_IPHONE
329 if(ctx->trustedLeafCerts) {
330 CFArrayForEach(ctx->trustedLeafCerts, ^(const void *value) {
331 SecCertificateRef cert = (SecCertificateRef) value;
332 CC_SHA256_Update(&hash_ctx, SecCertificateGetBytePtr(cert), (CC_LONG)SecCertificateGetLength(cert));
333 });
334 }
335 #endif
336
337 CC_SHA256_Update(&hash_ctx, &ctx->trustedCertsOnly, sizeof(ctx->trustedCertsOnly));
338
339
340 if(ctx->trustedCerts) {
341 CFArrayForEach(ctx->trustedCerts, ^(const void *value) {
342 SecCertificateRef cert = (SecCertificateRef) value;
343 CC_SHA256_Update(&hash_ctx, SecCertificateGetBytePtr(cert), (CC_LONG)SecCertificateGetLength(cert));
344 });
345 }
346
347 CC_SHA256_Final(md, &hash_ctx);
348
349 extended_peer_id->length = ctx->peerID.length + sizeof(md);
350 extended_peer_id->data = sslMalloc(extended_peer_id->length);
351 memcpy(extended_peer_id->data, ctx->peerID.data, ctx->peerID.length);
352 memcpy(extended_peer_id->data+ctx->peerID.length, md, sizeof(md));
353 }
354
355 /* Send the initial client hello */
356 static OSStatus
357 SSLHandshakeStart(SSLContext *ctx)
358 {
359 int err;
360 tls_buffer extended_peer_id;
361 get_extended_peer_id(ctx, &extended_peer_id);
362 err = tls_handshake_negotiate(ctx->hdsk, &extended_peer_id);
363 free(extended_peer_id.data);
364 if(err)
365 return err;
366
367 ctx->readCipher_ready = 0;
368 ctx->writeCipher_ready = 0;
369 SSLChangeHdskState(ctx, SSL_HdskStatePending);
370
371 return noErr;
372 }
373
374 OSStatus
375 SSLReHandshake(SSLContext *ctx)
376 {
377 if(ctx == NULL) {
378 return errSecParam;
379 }
380
381 switch (ctx->state) {
382 case SSL_HdskStateGracefulClose:
383 return errSSLClosedGraceful;
384 case SSL_HdskStateErrorClose:
385 case SSL_HdskStateOutOfBandError:
386 return errSSLClosedAbort;
387 case SSL_HdskStatePending:
388 return errSecBadReq;
389 default:
390 break;
391 }
392
393 /* If we are the client, we start the negotiation */
394 if(ctx->protocolSide == kSSLClientSide) {
395 return SSLHandshakeStart(ctx);
396 } else {
397 return tls_handshake_request_renegotiation(ctx->hdsk);
398 }
399 }
400
401 OSStatus
402 SSLHandshake(SSLContext *ctx)
403 {
404 OSStatus err;
405
406 if(ctx == NULL) {
407 return errSecParam;
408 }
409
410 switch (ctx->state) {
411 case SSL_HdskStateGracefulClose:
412 return errSSLClosedGraceful;
413 case SSL_HdskStateErrorClose:
414 return errSSLClosedAbort;
415 default:
416 break;
417 }
418
419 if(ctx->isDTLS && ctx->timeout_deadline) {
420 CFAbsoluteTime current = CFAbsoluteTimeGetCurrent();
421
422 if (ctx->timeout_deadline<current) {
423 sslDebugLog("%p, retransmition deadline expired\n", ctx);
424 err = tls_handshake_retransmit_timer_expired(ctx->hdsk);
425 if(err) {
426 return err;
427 }
428 }
429 }
430
431 /* Initial Client Hello */
432 if(ctx->state==SSL_HdskStateUninit) {
433 /* If we are the client, we start the negotiation */
434 if(ctx->protocolSide == kSSLClientSide) {
435 err = SSLHandshakeStart(ctx);
436 if(err) {
437 return err;
438 }
439 }
440 SSLChangeHdskState(ctx, SSL_HdskStatePending);
441 }
442
443 /* If an out-of-band error occurred, handle it here and then terminate
444 the connection as needed. */
445 if (ctx->state == SSL_HdskStateOutOfBandError) {
446 bool shouldClose = true;
447 switch (ctx->outOfBandError) {
448 case errSecCertificateExpired:
449 SSLSendAlert(ctx, tls_handshake_alert_level_fatal, tls_handshake_alert_CertExpired);
450 break;
451 case errSecCertificateRevoked:
452 SSLSendAlert(ctx, tls_handshake_alert_level_fatal, tls_handshake_alert_CertRevoked);
453 break;
454 default:
455 shouldClose = false;
456 break;
457 }
458
459 if (shouldClose) {
460 return SSLClose(ctx);
461 }
462 }
463
464 do {
465 err = SSLHandshakeProceed(ctx);
466 if((err != 0) && (err != errSSLUnexpectedRecord))
467 return err;
468 } while (ctx->readCipher_ready == 0 || ctx->writeCipher_ready == 0);
469
470 /* one more flush at completion of successful handshake */
471 if ((err = SSLServiceWriteQueue(ctx)) != 0) {
472 return err;
473 }
474
475 return errSecSuccess;
476 }
477
478 #if (TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
479
480 static void ad_log_SecureTransport_early_fail(long signature)
481 {
482 CFStringRef key = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("com.apple.SecureTransport.early_fail.%ld"), signature);
483
484 if (key) {
485 SecCoreAnalyticsSendValue(key, 1);
486 CFRelease(key);
487 }
488 }
489
490 #endif
491
492
493 #if (!TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
494
495 #include <msgtracer_client.h>
496
497 static void mt_log_SecureTransport_early_fail(long signature)
498 {
499 char signature_string[16];
500
501 snprintf(signature_string, sizeof(signature_string), "%ld", signature);
502
503 msgtracer_log_with_keys("com.apple.SecureTransport.early_fail", ASL_LEVEL_NOTICE,
504 "com.apple.message.signature", signature_string,
505 "com.apple.message.summarize", "YES",
506 NULL);
507 }
508
509 #endif
510
511
512 static void log_SecureTransport_early_fail(long signature)
513 {
514 #if (!TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
515 mt_log_SecureTransport_early_fail(signature);
516 #endif
517
518 #if (TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR)
519 ad_log_SecureTransport_early_fail(signature);
520 #endif
521 }
522
523
524 static OSStatus
525 SSLHandshakeProceed(SSLContext *ctx)
526 {
527 OSStatus err;
528
529 if ((err = tls_handshake_continue(ctx->hdsk)) != 0)
530 return err;
531
532 if ((err = SSLServiceWriteQueue(ctx)) != 0)
533 return err;
534
535 SSLRecord rec;
536
537 err = SSLReadRecord(&rec, ctx);
538
539 if(!err) {
540 sslDebugLog("%p going to process a record (rec.len=%zd, ct=%d)\n", ctx, rec.contents.length, rec.contentType);
541 err = tls_handshake_process(ctx->hdsk, rec.contents, rec.contentType);
542 sslDebugLog("%p processed a record (rec.len=%zd, ct=%d, err=%d)\n", ctx, rec.contents.length, rec.contentType, (int)err);
543 SSLFreeRecord(rec, ctx);
544 } else if(err!=errSSLWouldBlock) {
545 sslDebugLog("%p Read error err=%d\n\n", ctx, (int)err);
546 }
547
548 if(ctx->protocolSide == kSSLClientSide &&
549 ctx->dheEnabled == false &&
550 !ctx->serverHelloReceived &&
551 err && err != errSSLWouldBlock)
552 {
553 log_SecureTransport_early_fail(err);
554 }
555
556 return err;
557 }
558
559 static OSStatus
560 SSLProcessProtocolMessage(SSLRecord *rec, SSLContext *ctx)
561 {
562 return tls_handshake_process(ctx->hdsk, rec->contents, rec->contentType);
563 }
564
565 OSStatus
566 SSLClose(SSLContext *ctx)
567 {
568 OSStatus err = errSecSuccess;
569
570 sslHdskStateDebug("SSLClose");
571 if(ctx == NULL) {
572 return errSecParam;
573 }
574
575 err = tls_handshake_close(ctx->hdsk);
576
577 if (err == 0)
578 err = SSLServiceWriteQueue(ctx);
579
580 SSLChangeHdskState(ctx, SSL_HdskStateGracefulClose);
581 if (err == errSecIO)
582 err = errSecSuccess; /* Ignore errors related to closed streams */
583 return err;
584 }
585
586 static OSStatus
587 SSLSendAlert(SSLContext *ctx, tls_alert_level_t alertLevel, tls_alert_t alert)
588 {
589 sslHdskStateDebug("SSLSendAlert");
590 if (ctx == NULL) {
591 return errSecParam;
592 }
593
594 return tls_handshake_send_alert(ctx->hdsk, alertLevel, alert);
595 }
596
597 OSStatus
598 SSLSetError(SSLContext *ctx, OSStatus error)
599 {
600 ctx->state = SSL_HdskStateOutOfBandError;
601 ctx->outOfBandError = error;
602 return errSecSuccess;
603 }
604
605 /*
606 * Determine how much data the client can be guaranteed to
607 * obtain via SSLRead() without blocking or causing any low-level
608 * read operations to occur.
609 *
610 * Implemented here because the relevant info in SSLContext (receivedDataBuffer
611 * and receivedDataPos) are only used in this file.
612 */
613 OSStatus
614 SSLGetBufferedReadSize(SSLContextRef ctx,
615 size_t *bufSize) /* RETURNED */
616 {
617 if(ctx == NULL) {
618 return errSecParam;
619 }
620 if(ctx->receivedDataBuffer.data == NULL) {
621 *bufSize = 0;
622 }
623 else {
624 assert(ctx->receivedDataBuffer.length >= ctx->receivedDataPos);
625 *bufSize = ctx->receivedDataBuffer.length - ctx->receivedDataPos;
626 }
627 return errSecSuccess;
628 }