]> git.saurik.com Git - apple/security.git/blob - libsecurity_ssl/lib/sslTransport.c
Security-55178.0.1.tar.gz
[apple/security.git] / libsecurity_ssl / lib / sslTransport.c
1 /*
2 * Copyright (c) 1999-2001,2005-2012 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 "sslAlertMessage.h"
33 #include "sslSession.h"
34 #include "sslDebug.h"
35 #include "cipherSpecs.h"
36 #include "sslUtils.h"
37
38 #include <assert.h>
39 #include <string.h>
40
41 #ifndef NDEBUG
42 static inline void sslIoTrace(
43 const char *op,
44 size_t req,
45 size_t moved,
46 OSStatus stat)
47 {
48 sslLogRecordIo("===%s: req %4lu moved %4lu status %ld",
49 op, req, moved, stat);
50 }
51 #else
52 #define sslIoTrace(op, req, moved, stat)
53 #endif /* NDEBUG */
54
55 extern int kSplitDefaultValue;
56
57 static OSStatus SSLProcessProtocolMessage(SSLRecord *rec, SSLContext *ctx);
58 static OSStatus SSLHandshakeProceed(SSLContext *ctx);
59 static OSStatus SSLInitConnection(SSLContext *ctx);
60 static OSStatus SSLServiceWriteQueue(SSLContext *ctx);
61
62 OSStatus
63 SSLWrite(
64 SSLContext *ctx,
65 const void * data,
66 size_t dataLength,
67 size_t *bytesWritten) /* RETURNED */
68 {
69 OSStatus err;
70 SSLRecord rec;
71 size_t dataLen, processed;
72 Boolean split;
73
74 sslLogRecordIo("SSLWrite top");
75 if((ctx == NULL) || (bytesWritten == NULL)) {
76 return paramErr;
77 }
78 dataLen = dataLength;
79 processed = 0; /* Initialize in case we return with errSSLWouldBlock */
80 *bytesWritten = 0;
81
82 switch(ctx->state) {
83 case SSL_HdskStateGracefulClose:
84 err = errSSLClosedGraceful;
85 goto abort;
86 case SSL_HdskStateErrorClose:
87 err = errSSLClosedAbort;
88 goto abort;
89 case SSL_HdskStateServerReady:
90 case SSL_HdskStateClientReady:
91 break;
92 default:
93 if(ctx->state < SSL_HdskStateServerHello) {
94 /* not ready for I/O, and handshake not in progress */
95 sslIoTrace("SSLWrite", dataLength, 0, badReqErr);
96 return badReqErr;
97 }
98 /* handshake in progress; will call SSLHandshakeProceed below */
99 break;
100 }
101
102 /* First, we have to wait until the session is ready to send data,
103 so the encryption keys and such have been established. */
104 err = noErr;
105 while (ctx->writeCipher.ready == 0)
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 /* Check if we should split the data into 1/n-1 to avoid known-IV issue */
115 split = (ctx->oneByteRecordEnable && ctx->negProtocolVersion <= TLS_Version_1_0);
116 if (split) {
117 /* Only split if cipher algorithm uses CBC mode */
118 SSL_CipherAlgorithm cipherAlg = sslCipherSuiteGetSymmetricCipherAlgorithm(ctx->selectedCipher);
119 split = (cipherAlg > SSL_CipherAlgorithmRC4_128 &&
120 cipherAlg < SSL_CipherAlgorithmAES_128_GCM);
121 if (split) {
122 /* Determine whether we start splitting on second write */
123 split = (kSplitDefaultValue == 2 && !ctx->wroteAppData) ? false : true;
124 }
125 }
126 processed = 0;
127
128 /*
129 * Fragment, package and encrypt the data and queue the resulting data
130 * for sending
131 */
132 while (dataLen > 0)
133 { rec.contentType = SSL_RecordTypeAppData;
134 rec.protocolVersion = ctx->negProtocolVersion;
135 rec.contents.data = ((uint8_t *)data) + processed;
136
137 if (processed == 0 && split)
138 rec.contents.length = 1;
139 else if (dataLen < MAX_RECORD_LENGTH)
140 rec.contents.length = dataLen;
141 else
142 rec.contents.length = MAX_RECORD_LENGTH;
143
144 assert(ctx->sslTslCalls != NULL);
145 if ((err = ctx->sslTslCalls->writeRecord(rec, ctx)) != 0)
146 goto exit;
147 processed += rec.contents.length;
148 dataLen -= rec.contents.length;
149 ctx->wroteAppData = 1;
150 }
151
152 /* All the data has been advanced to the write queue */
153 *bytesWritten = processed;
154 if ((err = SSLServiceWriteQueue(ctx)) == 0) {
155 err = noErr;
156 }
157 exit:
158 switch(err) {
159 case noErr:
160 case errSSLWouldBlock:
161 case errSSLServerAuthCompleted: /* == errSSLClientAuthCompleted */
162 case errSSLClientCertRequested:
163 case errSSLClosedGraceful:
164 break;
165 default:
166 sslErrorLog("SSLWrite: going to state errorClose due to err %d\n",
167 (int)err);
168 SSLChangeHdskState(ctx, SSL_HdskStateErrorClose);
169 break;
170 }
171 abort:
172 sslIoTrace("SSLWrite", dataLength, *bytesWritten, err);
173 return err;
174 }
175
176 OSStatus
177 SSLRead (
178 SSLContext *ctx,
179 void * data,
180 size_t dataLength,
181 size_t *processed) /* RETURNED */
182 {
183 OSStatus err;
184 uint8_t *charPtr;
185 size_t bufSize, remaining, count;
186 SSLRecord rec;
187
188 sslLogRecordIo("SSLRead top");
189 if((ctx == NULL) || (data == NULL) || (processed == NULL)) {
190 return paramErr;
191 }
192 bufSize = dataLength;
193 *processed = 0; /* Initialize in case we return with errSSLWouldBlock */
194
195 readRetry:
196 /* first handle cases in which we know we're finished */
197 switch(ctx->state) {
198 case SSL_HdskStateGracefulClose:
199 err = errSSLClosedGraceful;
200 goto abort;
201 case SSL_HdskStateErrorClose:
202 err = errSSLClosedAbort;
203 goto abort;
204 case SSL_HdskStateNoNotifyClose:
205 err = errSSLClosedNoNotify;
206 goto abort;
207 default:
208 break;
209 }
210
211 /* First, we have to wait until the session is ready to receive data,
212 so the encryption keys and such have been established. */
213 err = noErr;
214 while (ctx->readCipher.ready == 0) {
215 if ((err = SSLHandshakeProceed(ctx)) != 0) {
216 goto exit;
217 }
218 }
219
220 /* Attempt to service the write queue */
221 if ((err = SSLServiceWriteQueue(ctx)) != 0) {
222 if (err != errSSLWouldBlock) {
223 goto exit;
224 }
225 err = noErr; /* Write blocking shouldn't stop attempts to read */
226 }
227
228 remaining = bufSize;
229 charPtr = (uint8_t *)data;
230 if (ctx->receivedDataBuffer.data)
231 { count = ctx->receivedDataBuffer.length - ctx->receivedDataPos;
232 if (count > bufSize)
233 count = bufSize;
234 memcpy(data, ctx->receivedDataBuffer.data + ctx->receivedDataPos, count);
235 remaining -= count;
236 charPtr += count;
237 *processed += count;
238 ctx->receivedDataPos += count;
239 }
240
241 assert(ctx->receivedDataPos <= ctx->receivedDataBuffer.length);
242 assert(*processed + remaining == bufSize);
243 assert(charPtr == ((uint8_t *)data) + *processed);
244
245 if (ctx->receivedDataBuffer.data != 0 &&
246 ctx->receivedDataPos >= ctx->receivedDataBuffer.length)
247 { SSLFreeBuffer(&ctx->receivedDataBuffer, ctx);
248 ctx->receivedDataBuffer.data = 0;
249 ctx->receivedDataPos = 0;
250 }
251
252 /*
253 * This while statement causes a hang when using nonblocking low-level I/O!
254 while (remaining > 0 && ctx->state != SSL_HdskStateGracefulClose)
255 ..what we really have to do is just return as soon as we read one
256 record. A performance hit in the nonblocking case, but that is
257 the only way this code can work in both modes...
258 */
259 if (remaining > 0 && ctx->state != SSL_HdskStateGracefulClose)
260 { assert(ctx->receivedDataBuffer.data == 0);
261 if ((err = SSLReadRecord(&rec, ctx)) != 0) {
262 goto exit;
263 }
264 if (rec.contentType == SSL_RecordTypeAppData ||
265 rec.contentType == SSL_RecordTypeV2_0)
266 { if (rec.contents.length <= remaining)
267 { memcpy(charPtr, rec.contents.data, rec.contents.length);
268 remaining -= rec.contents.length;
269 charPtr += rec.contents.length;
270 *processed += rec.contents.length;
271 /* COMPILER BUG!
272 * This:
273 * if ((err = SSLFreeBuffer(rec.contents, ctx)) != 0)
274 * passes the address of rec to SSLFreeBuffer, not the address
275 * of the contents field (which should be offset 8 from the start
276 * of rec).
277 */
278 {
279 SSLBuffer *b = &rec.contents;
280 if ((err = SSLFreeBuffer(b, ctx)) != 0) {
281 goto exit;
282 }
283 }
284 }
285 else
286 { memcpy(charPtr, rec.contents.data, remaining);
287 charPtr += remaining;
288 *processed += remaining;
289 ctx->receivedDataBuffer = rec.contents;
290 ctx->receivedDataPos = remaining;
291 remaining = 0;
292 }
293 }
294 else {
295 if ((err = SSLProcessProtocolMessage(&rec, ctx)) != 0) {
296 goto exit;
297 }
298 if ((err = SSLFreeBuffer(&rec.contents, ctx)) != 0) {
299 goto exit;
300 }
301 }
302 }
303
304 err = noErr;
305
306 exit:
307 /* test for renegotiate: loop until something useful happens */
308 if((err == noErr) && (*processed == 0) && !(dataLength == 0)) {
309 sslLogNegotiateDebug("SSLRead recursion");
310 goto readRetry;
311 }
312 /* shut down on serious errors */
313 switch(err) {
314 case noErr:
315 case errSSLWouldBlock:
316 case errSSLServerAuthCompleted: /* == errSSLClientAuthCompleted */
317 case errSSLClientCertRequested:
318 case errSSLClosedGraceful:
319 case errSSLClosedNoNotify:
320 break;
321 default:
322 sslErrorLog("SSLRead: going to state errorClose due to err %d\n",
323 (int)err);
324 SSLChangeHdskState(ctx, SSL_HdskStateErrorClose);
325 break;
326 }
327 abort:
328 sslIoTrace("SSLRead ", dataLength, *processed, err);
329 return err;
330 }
331
332 #if SSL_DEBUG
333 #include "sslCrypto.h"
334 #endif
335
336 OSStatus
337 SSLHandshake(SSLContext *ctx)
338 {
339 OSStatus err;
340
341 if(ctx == NULL) {
342 return paramErr;
343 }
344 if (ctx->state == SSL_HdskStateGracefulClose)
345 return errSSLClosedGraceful;
346 if (ctx->state == SSL_HdskStateErrorClose)
347 return errSSLClosedAbort;
348
349 #if SSL_ECDSA_HACK
350 /* Because of Radar 6133465, we have to disable this to allow the sending
351 of client hello extensions for ECDSA... */
352 ctx->versionSsl2Enable = false;
353 #endif
354
355 if(ctx->validCipherSuites == NULL) {
356 /* build list of legal cipherSpecs */
357 err = sslBuildCipherSuiteArray(ctx);
358 if(err) {
359 return err;
360 }
361 }
362 err = noErr;
363
364 if(ctx->isDTLS) {
365 if (ctx->timeout_deadline<CFAbsoluteTimeGetCurrent()) {
366 DTLSRetransmit(ctx);
367 }
368 }
369
370 while (ctx->readCipher.ready == 0 || ctx->writeCipher.ready == 0)
371 { if ((err = SSLHandshakeProceed(ctx)) != 0)
372 return err;
373 }
374
375 /* one more flush at completion of successful handshake */
376 if ((err = SSLServiceWriteQueue(ctx)) != 0) {
377 return err;
378 }
379 return noErr;
380 }
381
382
383 static OSStatus
384 SSLHandshakeProceed(SSLContext *ctx)
385 { OSStatus err;
386 SSLRecord rec;
387
388 if (ctx->signalServerAuth) {
389 ctx->signalServerAuth = false;
390 return errSSLServerAuthCompleted;
391 }
392 if (ctx->signalCertRequest) {
393 ctx->signalCertRequest = false;
394 return errSSLClientCertRequested;
395 }
396 if (ctx->signalClientAuth) {
397 ctx->signalClientAuth = false;
398 return errSSLClientAuthCompleted;
399 }
400
401 if (ctx->state == SSL_HdskStateUninit)
402 if ((err = SSLInitConnection(ctx)) != 0)
403 return err;
404
405 /* This is our cue that we dropped out of the handshake
406 * to let the client pick an identity, move state back
407 * to server hello done and continue processing.
408 */
409 if ((ctx->protocolSide == kSSLClientSide) &&
410 (ctx->state == SSL_HdskStateClientCert))
411 if ((err = SSLAdvanceHandshake(SSL_HdskServerHelloDone, ctx)) != 0)
412 return err;
413
414 if ((err = SSLServiceWriteQueue(ctx)) != 0)
415 return err;
416 assert(ctx->readCipher.ready == 0);
417 if ((err = SSLReadRecord(&rec, ctx)) != 0)
418 return err;
419 if ((err = SSLProcessProtocolMessage(&rec, ctx)) != 0)
420 { SSLFreeBuffer(&rec.contents, ctx);
421 return err;
422 }
423 if ((err = SSLFreeBuffer(&rec.contents, ctx)) != 0)
424 return err;
425
426 return noErr;
427 }
428
429 static OSStatus
430 SSLInitConnection(SSLContext *ctx)
431 { OSStatus err = noErr;
432
433 if (ctx->protocolSide == kSSLClientSide) {
434 SSLChangeHdskState(ctx, SSL_HdskStateClientUninit);
435 }
436 else
437 { assert(ctx->protocolSide == kSSLServerSide);
438 SSLChangeHdskState(ctx, SSL_HdskStateServerUninit);
439 }
440
441 if (ctx->peerID.data != 0)
442 { SSLGetSessionData(&ctx->resumableSession, ctx);
443 /* Ignore errors; just treat as uncached session */
444 }
445
446 /*
447 * If we have a cached resumable session, blow it off if it's a version
448 * which is not currently enabled.
449 */
450 Boolean cachedV3OrTls1 = ctx->isDTLS;
451
452 if (ctx->resumableSession.data != 0) {
453 SSLProtocolVersion savedVersion;
454 if ((err = SSLRetrieveSessionProtocolVersion(ctx->resumableSession,
455 &savedVersion, ctx)) != 0)
456 return err;
457
458 if (ctx->isDTLS
459 ? (savedVersion <= ctx->minProtocolVersion &&
460 savedVersion >= ctx->maxProtocolVersion)
461 : (savedVersion >= ctx->minProtocolVersion &&
462 savedVersion <= ctx->maxProtocolVersion)) {
463 cachedV3OrTls1 = savedVersion != SSL_Version_2_0;
464 sslLogResumSessDebug("===attempting to resume session");
465 } else {
466 sslLogResumSessDebug("===Resumable session protocol mismatch");
467 SSLFreeBuffer(&ctx->resumableSession, ctx);
468 }
469 }
470
471 /*
472 * If we're the client & handshake hasn't yet begun, start it by
473 * pretending we just received a hello request
474 */
475 if (ctx->state == SSL_HdskStateClientUninit && ctx->writeCipher.ready == 0)
476 {
477 assert(ctx->negProtocolVersion == SSL_Version_Undetermined);
478 #if ENABLE_SSLV2
479 if(!cachedV3OrTls1) {
480 /* SSL2 client hello with possible upgrade */
481 err = SSL2AdvanceHandshake(SSL2_MsgKickstart, ctx);
482 }
483 else
484 #endif
485 {
486 err = SSLAdvanceHandshake(SSL_HdskHelloRequest, ctx);
487 }
488 }
489
490 return err;
491 }
492
493 static OSStatus
494 SSLServiceWriteQueue(SSLContext *ctx)
495 { OSStatus err = noErr, werr = noErr;
496 size_t written = 0;
497 SSLBuffer buf;
498 WaitingRecord *rec;
499
500 while (!werr && ((rec = ctx->recordWriteQueue) != 0))
501 { buf.data = rec->data + rec->sent;
502 buf.length = rec->length - rec->sent;
503 werr = sslIoWrite(buf, &written, ctx);
504 rec->sent += written;
505 if (rec->sent >= rec->length)
506 { assert(rec->sent == rec->length);
507 assert(err == 0);
508 ctx->recordWriteQueue = rec->next;
509 sslFree(rec);
510 }
511 if (err)
512 return err;
513 }
514
515 return werr;
516 }
517
518 static OSStatus
519 SSLProcessProtocolMessage(SSLRecord *rec, SSLContext *ctx)
520 { OSStatus err;
521
522 switch (rec->contentType)
523 { case SSL_RecordTypeHandshake:
524 sslLogRxProtocolDebug("Handshake");
525 if(ctx->isDTLS)
526 err = DTLSProcessHandshakeRecord(*rec, ctx);
527 else
528 err = SSLProcessHandshakeRecord(*rec, ctx);
529 break;
530 case SSL_RecordTypeAlert:
531 sslLogRxProtocolDebug("Alert");
532 err = SSLProcessAlert(*rec, ctx);
533 break;
534 case SSL_RecordTypeChangeCipher:
535 sslLogRxProtocolDebug("ChangeCipher");
536 err = SSLProcessChangeCipherSpec(*rec, ctx);
537 break;
538 #if ENABLE_SSLV2
539 case SSL_RecordTypeV2_0:
540 sslLogRxProtocolDebug("RecordTypeV2_0");
541 err = SSL2ProcessMessage(rec, ctx);
542 break;
543 #endif
544 default:
545 sslLogRxProtocolDebug("Bad msg");
546 return errSSLProtocol;
547 }
548
549 return err;
550 }
551
552 OSStatus
553 SSLClose(SSLContext *ctx)
554 {
555 OSStatus err = noErr;
556
557 sslHdskStateDebug("SSLClose");
558 if(ctx == NULL) {
559 return paramErr;
560 }
561 if (ctx->negProtocolVersion >= SSL_Version_3_0)
562 err = SSLSendAlert(SSL_AlertLevelWarning, SSL_AlertCloseNotify, ctx);
563 if (err == 0)
564 err = SSLServiceWriteQueue(ctx);
565 SSLChangeHdskState(ctx, SSL_HdskStateGracefulClose);
566 if (err == ioErr)
567 err = noErr; /* Ignore errors related to closed streams */
568 return err;
569 }
570
571 /*
572 * Determine how much data the client can be guaranteed to
573 * obtain via SSLRead() without blocking or causing any low-level
574 * read operations to occur.
575 *
576 * Implemented here because the relevant info in SSLContext (receivedDataBuffer
577 * and receivedDataPos) are only used in this file.
578 */
579 OSStatus
580 SSLGetBufferedReadSize(SSLContextRef ctx,
581 size_t *bufSize) /* RETURNED */
582 {
583 if(ctx == NULL) {
584 return paramErr;
585 }
586 if(ctx->receivedDataBuffer.data == NULL) {
587 *bufSize = 0;
588 }
589 else {
590 assert(ctx->receivedDataBuffer.length >= ctx->receivedDataPos);
591 *bufSize = ctx->receivedDataBuffer.length - ctx->receivedDataPos;
592 }
593 return noErr;
594 }