]> git.saurik.com Git - apple/security.git/blob - libsecurity_ssl/lib/sslKeyExchange.c
7d92517c4560825928839a9aabc7dd8d5a97e259
[apple/security.git] / libsecurity_ssl / lib / sslKeyExchange.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 * sslKeyExchange.c - Support for key exchange and server key exchange
26 */
27
28 #include "ssl.h"
29 #include "sslContext.h"
30 #include "sslHandshake.h"
31 #include "sslMemory.h"
32 #include "sslDebug.h"
33 #include "sslUtils.h"
34 #include "sslCrypto.h"
35 #include "sslRand.h"
36 #include "sslDigests.h"
37
38 #include <assert.h>
39 #include <string.h>
40
41 #include <stdio.h>
42 #include <utilities/SecCFRelease.h>
43 #include <corecrypto/ccdh_gp.h>
44
45 #ifdef USE_CDSA_CRYPTO
46 //#include <utilities/globalizer.h>
47 //#include <utilities/threading.h>
48 #include <Security/cssmapi.h>
49 #include <Security/SecKeyPriv.h>
50 #include "ModuleAttacher.h"
51 #else
52 #include <AssertMacros.h>
53 #include <Security/oidsalg.h>
54 #if APPLE_DH
55
56 #if TARGET_OS_IPHONE
57 #include <Security/SecRSAKey.h>
58 #endif
59
60 static OSStatus SSLGenServerDHParamsAndKey(SSLContext *ctx);
61 static size_t SSLEncodedDHKeyParamsLen(SSLContext *ctx);
62 static OSStatus SSLEncodeDHKeyParams(SSLContext *ctx, uint8_t *charPtr);
63
64 #endif /* APPLE_DH */
65 #endif /* USE_CDSA_CRYPTO */
66
67 // MARK: -
68 // MARK: Forward Static Declarations
69
70 #if APPLE_DH
71 #if USE_CDSA_CRYPTO
72 static OSStatus SSLGenServerDHParamsAndKey(SSLContext *ctx);
73 static OSStatus SSLEncodeDHKeyParams(SSLContext *ctx, uint8_t *charPtr);
74 #endif
75 static OSStatus SSLDecodeDHKeyParams(SSLContext *ctx, uint8_t **charPtr,
76 size_t length);
77 #endif
78 static OSStatus SSLDecodeECDHKeyParams(SSLContext *ctx, uint8_t **charPtr,
79 size_t length);
80
81 #define DH_PARAM_DUMP 0
82 #if DH_PARAM_DUMP
83
84 static void dumpBuf(const char *name, SSLBuffer *buf)
85 {
86 printf("%s:\n", name);
87 uint8_t *cp = buf->data;
88 uint8_t *endCp = cp + buf->length;
89
90 do {
91 unsigned i;
92 for(i=0; i<16; i++) {
93 printf("%02x ", *cp++);
94 if(cp == endCp) {
95 break;
96 }
97 }
98 if(cp == endCp) {
99 break;
100 }
101 printf("\n");
102 } while(cp < endCp);
103 printf("\n");
104 }
105 #else
106 #define dumpBuf(n, b)
107 #endif /* DH_PARAM_DUMP */
108
109 #if APPLE_DH
110
111 // MARK: -
112 // MARK: Local Diffie-Hellman Parameter Generator
113
114 /*
115 * Process-wide server-supplied Diffie-Hellman parameters.
116 * This might be overridden by some API_supplied parameters
117 * in the future.
118 */
119 struct ServerDhParams
120 {
121 /* these two for sending over the wire */
122 SSLBuffer prime;
123 SSLBuffer generator;
124 /* this one for sending to the CSP at key gen time */
125 SSLBuffer paramBlock;
126 };
127
128
129 #endif /* APPLE_DH */
130
131 // MARK: -
132 // MARK: RSA Key Exchange
133
134 /*
135 * Client RSA Key Exchange msgs actually start with a two-byte
136 * length field, contrary to the first version of RFC 2246, dated
137 * January 1999. See RFC 2246, March 2002, section 7.4.7.1 for
138 * updated requirements.
139 */
140 #define RSA_CLIENT_KEY_ADD_LENGTH 1
141
142 static OSStatus
143 SSLEncodeRSAKeyParams(SSLBuffer *keyParams, SSLPubKey *key, SSLContext *ctx)
144 {
145 #if 0
146 SSLBuffer modulus, exponent;
147 uint8_t *charPtr;
148
149 #ifdef USE_CDSA_CRYPTO
150 if(err = attachToCsp(ctx)) {
151 return err;
152 }
153
154 /* Note currently ALL public keys are raw, obtained from the CL... */
155 assert((*key)->KeyHeader.BlobType == CSSM_KEYBLOB_RAW);
156 #endif /* USE_CDSA_CRYPTO */
157
158 err = sslGetPubKeyBits(ctx,
159 key,
160 &modulus,
161 &exponent);
162 if(err) {
163 SSLFreeBuffer(&modulus);
164 SSLFreeBuffer(&exponent);
165 return err;
166 }
167
168 if ((err = SSLAllocBuffer(keyParams,
169 modulus.length + exponent.length + 4, ctx)) != 0) {
170 return err;
171 }
172 charPtr = keyParams->data;
173 charPtr = SSLEncodeInt(charPtr, modulus.length, 2);
174 memcpy(charPtr, modulus.data, modulus.length);
175 charPtr += modulus.length;
176 charPtr = SSLEncodeInt(charPtr, exponent.length, 2);
177 memcpy(charPtr, exponent.data, exponent.length);
178
179 /* these were mallocd by sslGetPubKeyBits() */
180 SSLFreeBuffer(&modulus);
181 SSLFreeBuffer(&exponent);
182 return errSecSuccess;
183 #else
184 CFDataRef modulus = SecKeyCopyModulus(SECKEYREF(key));
185 if (!modulus) {
186 sslErrorLog("SSLEncodeRSAKeyParams: SecKeyCopyModulus failed\n");
187 return errSSLCrypto;
188 }
189 CFDataRef exponent = SecKeyCopyExponent(SECKEYREF(key));
190 if (!exponent) {
191 sslErrorLog("SSLEncodeRSAKeyParams: SecKeyCopyExponent failed\n");
192 CFRelease(modulus);
193 return errSSLCrypto;
194 }
195
196 CFIndex modulusLength = CFDataGetLength(modulus);
197 CFIndex exponentLength = CFDataGetLength(exponent);
198 sslDebugLog("SSLEncodeRSAKeyParams: modulus len=%ld, exponent len=%ld\n",
199 modulusLength, exponentLength);
200 OSStatus err;
201 if ((err = SSLAllocBuffer(keyParams,
202 modulusLength + exponentLength + 4)) != 0) {
203 CFReleaseSafe(exponent);
204 CFReleaseSafe(modulus);
205 return err;
206 }
207 uint8_t *charPtr = keyParams->data;
208 charPtr = SSLEncodeSize(charPtr, modulusLength, 2);
209 memcpy(charPtr, CFDataGetBytePtr(modulus), modulusLength);
210 charPtr += modulusLength;
211 charPtr = SSLEncodeSize(charPtr, exponentLength, 2);
212 memcpy(charPtr, CFDataGetBytePtr(exponent), exponentLength);
213 CFRelease(modulus);
214 CFRelease(exponent);
215 return errSecSuccess;
216 #endif
217 }
218
219 static OSStatus
220 SSLEncodeRSAPremasterSecret(SSLContext *ctx)
221 { SSLBuffer randData;
222 OSStatus err;
223
224 if ((err = SSLAllocBuffer(&ctx->preMasterSecret,
225 SSL_RSA_PREMASTER_SECRET_SIZE)) != 0)
226 return err;
227
228 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
229
230 SSLEncodeInt(ctx->preMasterSecret.data, ctx->clientReqProtocol, 2);
231 randData.data = ctx->preMasterSecret.data+2;
232 randData.length = SSL_RSA_PREMASTER_SECRET_SIZE - 2;
233 if ((err = sslRand(&randData)) != 0)
234 return err;
235 return errSecSuccess;
236 }
237
238 /*
239 * Generate a server key exchange message signed by our RSA or DSA private key.
240 */
241
242 static OSStatus
243 SSLSignServerKeyExchangeTls12(SSLContext *ctx, SSLSignatureAndHashAlgorithm sigAlg, SSLBuffer exchangeParams, SSLBuffer signature, size_t *actSigLen)
244 {
245 OSStatus err;
246 SSLBuffer hashOut, hashCtx, clientRandom, serverRandom;
247 uint8_t hashes[SSL_MAX_DIGEST_LEN];
248 SSLBuffer signedHashes;
249 uint8_t *dataToSign;
250 size_t dataToSignLen;
251 const HashReference *hashRef;
252 SecAsn1AlgId algId;
253
254 signedHashes.data = 0;
255 hashCtx.data = 0;
256
257 clientRandom.data = ctx->clientRandom;
258 clientRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
259 serverRandom.data = ctx->serverRandom;
260 serverRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
261
262 switch (sigAlg.hash) {
263 case SSL_HashAlgorithmSHA1:
264 hashRef = &SSLHashSHA1;
265 algId.algorithm = CSSMOID_SHA1WithRSA;
266 break;
267 case SSL_HashAlgorithmSHA256:
268 hashRef = &SSLHashSHA256;
269 algId.algorithm = CSSMOID_SHA256WithRSA;
270 break;
271 case SSL_HashAlgorithmSHA384:
272 hashRef = &SSLHashSHA384;
273 algId.algorithm = CSSMOID_SHA384WithRSA;
274 break;
275 default:
276 sslErrorLog("SSLVerifySignedServerKeyExchangeTls12: unsupported hash %d\n", sigAlg.hash);
277 return errSSLProtocol;
278 }
279
280
281 dataToSign = hashes;
282 dataToSignLen = hashRef->digestSize;
283 hashOut.data = hashes;
284 hashOut.length = hashRef->digestSize;
285
286 if ((err = ReadyHash(hashRef, &hashCtx)) != 0)
287 goto fail;
288 if ((err = hashRef->update(&hashCtx, &clientRandom)) != 0)
289 goto fail;
290 if ((err = hashRef->update(&hashCtx, &serverRandom)) != 0)
291 goto fail;
292 if ((err = hashRef->update(&hashCtx, &exchangeParams)) != 0)
293 goto fail;
294 if ((err = hashRef->final(&hashCtx, &hashOut)) != 0)
295 goto fail;
296
297 if(sigAlg.signature==SSL_SignatureAlgorithmRSA) {
298 err = sslRsaSign(ctx,
299 ctx->signingPrivKeyRef,
300 &algId,
301 dataToSign,
302 dataToSignLen,
303 signature.data,
304 signature.length,
305 actSigLen);
306 } else {
307 err = sslRawSign(ctx,
308 ctx->signingPrivKeyRef,
309 dataToSign, // one or two hashes
310 dataToSignLen,
311 signature.data,
312 signature.length,
313 actSigLen);
314 }
315
316 if(err) {
317 sslErrorLog("SSLDecodeSignedServerKeyExchangeTls12: sslRawVerify "
318 "returned %d\n", (int)err);
319 goto fail;
320 }
321
322 fail:
323 SSLFreeBuffer(&signedHashes);
324 SSLFreeBuffer(&hashCtx);
325 return err;
326 }
327
328 static OSStatus
329 SSLSignServerKeyExchange(SSLContext *ctx, bool isRsa, SSLBuffer exchangeParams, SSLBuffer signature, size_t *actSigLen)
330 {
331 OSStatus err;
332 uint8_t hashes[SSL_SHA1_DIGEST_LEN + SSL_MD5_DIGEST_LEN];
333 SSLBuffer clientRandom,serverRandom,hashCtx, hash;
334 uint8_t *dataToSign;
335 size_t dataToSignLen;
336
337 hashCtx.data = 0;
338
339 /* cook up hash(es) for raw sign */
340 clientRandom.data = ctx->clientRandom;
341 clientRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
342 serverRandom.data = ctx->serverRandom;
343 serverRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
344
345 if(isRsa) {
346 /* skip this if signing with DSA */
347 dataToSign = hashes;
348 dataToSignLen = SSL_SHA1_DIGEST_LEN + SSL_MD5_DIGEST_LEN;
349 hash.data = &hashes[0];
350 hash.length = SSL_MD5_DIGEST_LEN;
351
352 if ((err = ReadyHash(&SSLHashMD5, &hashCtx)) != 0)
353 goto fail;
354 if ((err = SSLHashMD5.update(&hashCtx, &clientRandom)) != 0)
355 goto fail;
356 if ((err = SSLHashMD5.update(&hashCtx, &serverRandom)) != 0)
357 goto fail;
358 if ((err = SSLHashMD5.update(&hashCtx, &exchangeParams)) != 0)
359 goto fail;
360 if ((err = SSLHashMD5.final(&hashCtx, &hash)) != 0)
361 goto fail;
362 if ((err = SSLFreeBuffer(&hashCtx)) != 0)
363 goto fail;
364 }
365 else {
366 /* DSA - just use the SHA1 hash */
367 dataToSign = &hashes[SSL_MD5_DIGEST_LEN];
368 dataToSignLen = SSL_SHA1_DIGEST_LEN;
369 }
370 hash.data = &hashes[SSL_MD5_DIGEST_LEN];
371 hash.length = SSL_SHA1_DIGEST_LEN;
372 if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
373 goto fail;
374 if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
375 goto fail;
376 if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
377 goto fail;
378 if ((err = SSLHashSHA1.update(&hashCtx, &exchangeParams)) != 0)
379 goto fail;
380 if ((err = SSLHashSHA1.final(&hashCtx, &hash)) != 0)
381 goto fail;
382 if ((err = SSLFreeBuffer(&hashCtx)) != 0)
383 goto fail;
384
385
386 err = sslRawSign(ctx,
387 ctx->signingPrivKeyRef,
388 dataToSign, // one or two hashes
389 dataToSignLen,
390 signature.data,
391 signature.length,
392 actSigLen);
393 if(err) {
394 goto fail;
395 }
396
397 fail:
398 SSLFreeBuffer(&hashCtx);
399
400 return err;
401 }
402
403 static
404 OSStatus FindSigAlg(SSLContext *ctx,
405 SSLSignatureAndHashAlgorithm *alg)
406 {
407 unsigned i;
408
409 assert(ctx->protocolSide == kSSLServerSide);
410 assert(ctx->negProtocolVersion >= TLS_Version_1_2);
411 assert(!ctx->isDTLS);
412
413 if((ctx->numClientSigAlgs==0) ||(ctx->clientSigAlgs==NULL))
414 return errSSLInternal;
415
416 //FIXME: Need a better way to select here
417 for(i=0; i<ctx->numClientSigAlgs; i++) {
418 alg->hash = ctx->clientSigAlgs[i].hash;
419 alg->signature = ctx->clientSigAlgs[i].signature;
420 //We only support RSA for certs on the server side - but we should test against the cert type
421 if(ctx->clientSigAlgs[i].signature != SSL_SignatureAlgorithmRSA)
422 continue;
423 //Let's only support SHA1 and SHA256. SHA384 does not work with 512 bits keys.
424 // We should actually test against what the cert can do.
425 if((alg->hash==SSL_HashAlgorithmSHA1) || (alg->hash==SSL_HashAlgorithmSHA256)) {
426 return errSecSuccess;
427 }
428 }
429 // We could not find a supported signature and hash algorithm
430 return errSSLProtocol;
431 }
432
433 static OSStatus
434 SSLEncodeSignedServerKeyExchange(SSLRecord *keyExch, SSLContext *ctx)
435 { OSStatus err;
436 uint8_t *charPtr;
437 size_t outputLen;
438 bool isRsa = true;
439 size_t maxSigLen;
440 size_t actSigLen;
441 SSLBuffer signature;
442 int head = 4;
443 SSLBuffer exchangeParams;
444
445 assert(ctx->protocolSide == kSSLServerSide);
446 assert(ctx->signingPubKey != NULL);
447 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
448 exchangeParams.data = 0;
449 signature.data = 0;
450
451 #if ENABLE_DTLS
452 if(ctx->negProtocolVersion == DTLS_Version_1_0) {
453 head+=8;
454 }
455 #endif
456
457
458 /* Set up parameter block to hash ==> exchangeParams */
459 switch(ctx->selectedCipherSpecParams.keyExchangeMethod) {
460 case SSL_RSA:
461 case SSL_RSA_EXPORT:
462 /*
463 * Parameter block = encryption public key.
464 * If app hasn't supplied a separate encryption cert, abort.
465 */
466 if(ctx->encryptPubKey == NULL) {
467 sslErrorLog("RSAServerKeyExchange: no encrypt cert\n");
468 return errSSLBadConfiguration;
469 }
470 err = SSLEncodeRSAKeyParams(&exchangeParams,
471 ctx->encryptPubKey, ctx);
472 break;
473
474 #if APPLE_DH
475
476 case SSL_DHE_DSS:
477 case SSL_DHE_DSS_EXPORT:
478 isRsa = false;
479 /* and fall through */
480 case SSL_DHE_RSA:
481 case SSL_DHE_RSA_EXPORT:
482 {
483 /*
484 * Parameter block = {prime, generator, public key}
485 * Obtain D-H parameters (if we don't have them) and a key pair.
486 */
487 err = SSLGenServerDHParamsAndKey(ctx);
488 if(err) {
489 return err;
490 }
491 size_t len = SSLEncodedDHKeyParamsLen(ctx);
492 err = SSLAllocBuffer(&exchangeParams, len);
493 if(err) {
494 goto fail;
495 }
496 err = SSLEncodeDHKeyParams(ctx, exchangeParams.data);
497 break;
498 }
499
500 #endif /* APPLE_DH */
501
502 default:
503 /* shouldn't be here */
504 assert(0);
505 return errSSLInternal;
506 }
507
508 SSLSignatureAndHashAlgorithm sigAlg;
509
510
511 /* preallocate a buffer for signing */
512 err = sslGetMaxSigSize(ctx->signingPrivKeyRef, &maxSigLen);
513 if(err) {
514 goto fail;
515 }
516 err = SSLAllocBuffer(&signature, maxSigLen);
517 if(err) {
518 goto fail;
519 }
520
521 outputLen = exchangeParams.length + 2;
522
523 if (sslVersionIsLikeTls12(ctx))
524 {
525 err=FindSigAlg(ctx, &sigAlg);
526 if(err)
527 goto fail;
528
529 outputLen += 2;
530 err = SSLSignServerKeyExchangeTls12(ctx, sigAlg, exchangeParams,
531 signature, &actSigLen);
532 } else {
533 err = SSLSignServerKeyExchange(ctx, isRsa, exchangeParams,
534 signature, &actSigLen);
535 }
536
537 if(err)
538 goto fail;
539
540 assert(actSigLen <= maxSigLen);
541
542 outputLen += actSigLen;
543
544 /* package it all up */
545 keyExch->protocolVersion = ctx->negProtocolVersion;
546 keyExch->contentType = SSL_RecordTypeHandshake;
547 if ((err = SSLAllocBuffer(&keyExch->contents, outputLen+head)) != 0)
548 goto fail;
549
550 charPtr = SSLEncodeHandshakeHeader(ctx, keyExch, SSL_HdskServerKeyExchange, outputLen);
551
552 memcpy(charPtr, exchangeParams.data, exchangeParams.length);
553 charPtr += exchangeParams.length;
554
555 if (sslVersionIsLikeTls12(ctx))
556 {
557 *charPtr++=sigAlg.hash;
558 *charPtr++=sigAlg.signature;
559 }
560
561 charPtr = SSLEncodeInt(charPtr, actSigLen, 2);
562 memcpy(charPtr, signature.data, actSigLen);
563 assert((charPtr + actSigLen) ==
564 (keyExch->contents.data + keyExch->contents.length));
565
566 err = errSecSuccess;
567
568 fail:
569 SSLFreeBuffer(&exchangeParams);
570 SSLFreeBuffer(&signature);
571 return err;
572 }
573
574 static OSStatus
575 SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa, SSLBuffer signedParams,
576 uint8_t *signature, UInt16 signatureLen)
577 {
578 OSStatus err;
579 SSLBuffer hashOut, hashCtx, clientRandom, serverRandom;
580 uint8_t hashes[SSL_SHA1_DIGEST_LEN + SSL_MD5_DIGEST_LEN];
581 SSLBuffer signedHashes;
582 uint8_t *dataToSign;
583 size_t dataToSignLen;
584
585 signedHashes.data = 0;
586 hashCtx.data = 0;
587
588 clientRandom.data = ctx->clientRandom;
589 clientRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
590 serverRandom.data = ctx->serverRandom;
591 serverRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
592
593
594 if(isRsa) {
595 /* skip this if signing with DSA */
596 dataToSign = hashes;
597 dataToSignLen = SSL_SHA1_DIGEST_LEN + SSL_MD5_DIGEST_LEN;
598 hashOut.data = hashes;
599 hashOut.length = SSL_MD5_DIGEST_LEN;
600
601 if ((err = ReadyHash(&SSLHashMD5, &hashCtx)) != 0)
602 goto fail;
603 if ((err = SSLHashMD5.update(&hashCtx, &clientRandom)) != 0)
604 goto fail;
605 if ((err = SSLHashMD5.update(&hashCtx, &serverRandom)) != 0)
606 goto fail;
607 if ((err = SSLHashMD5.update(&hashCtx, &signedParams)) != 0)
608 goto fail;
609 if ((err = SSLHashMD5.final(&hashCtx, &hashOut)) != 0)
610 goto fail;
611 }
612 else {
613 /* DSA, ECDSA - just use the SHA1 hash */
614 dataToSign = &hashes[SSL_MD5_DIGEST_LEN];
615 dataToSignLen = SSL_SHA1_DIGEST_LEN;
616 }
617
618 hashOut.data = hashes + SSL_MD5_DIGEST_LEN;
619 hashOut.length = SSL_SHA1_DIGEST_LEN;
620 if ((err = SSLFreeBuffer(&hashCtx)) != 0)
621 goto fail;
622
623 if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
624 goto fail;
625 if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
626 goto fail;
627 if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
628 goto fail;
629 if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
630 goto fail;
631 goto fail;
632 if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
633 goto fail;
634
635 err = sslRawVerify(ctx,
636 ctx->peerPubKey,
637 dataToSign, /* plaintext */
638 dataToSignLen, /* plaintext length */
639 signature,
640 signatureLen);
641 if(err) {
642 sslErrorLog("SSLDecodeSignedServerKeyExchange: sslRawVerify "
643 "returned %d\n", (int)err);
644 goto fail;
645 }
646
647 fail:
648 SSLFreeBuffer(&signedHashes);
649 SSLFreeBuffer(&hashCtx);
650 return err;
651
652 }
653
654 static OSStatus
655 SSLVerifySignedServerKeyExchangeTls12(SSLContext *ctx, SSLSignatureAndHashAlgorithm sigAlg, SSLBuffer signedParams,
656 uint8_t *signature, UInt16 signatureLen)
657 {
658 OSStatus err;
659 SSLBuffer hashOut, hashCtx, clientRandom, serverRandom;
660 uint8_t hashes[SSL_MAX_DIGEST_LEN];
661 SSLBuffer signedHashes;
662 uint8_t *dataToSign;
663 size_t dataToSignLen;
664 const HashReference *hashRef;
665 SecAsn1AlgId algId;
666
667 signedHashes.data = 0;
668 hashCtx.data = 0;
669
670 clientRandom.data = ctx->clientRandom;
671 clientRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
672 serverRandom.data = ctx->serverRandom;
673 serverRandom.length = SSL_CLIENT_SRVR_RAND_SIZE;
674
675 switch (sigAlg.hash) {
676 case SSL_HashAlgorithmSHA1:
677 hashRef = &SSLHashSHA1;
678 algId.algorithm = CSSMOID_SHA1WithRSA;
679 break;
680 case SSL_HashAlgorithmSHA256:
681 hashRef = &SSLHashSHA256;
682 algId.algorithm = CSSMOID_SHA256WithRSA;
683 break;
684 case SSL_HashAlgorithmSHA384:
685 hashRef = &SSLHashSHA384;
686 algId.algorithm = CSSMOID_SHA384WithRSA;
687 break;
688 default:
689 sslErrorLog("SSLVerifySignedServerKeyExchangeTls12: unsupported hash %d\n", sigAlg.hash);
690 return errSSLProtocol;
691 }
692
693
694 dataToSign = hashes;
695 dataToSignLen = hashRef->digestSize;
696 hashOut.data = hashes;
697 hashOut.length = hashRef->digestSize;
698
699 if ((err = ReadyHash(hashRef, &hashCtx)) != 0)
700 goto fail;
701 if ((err = hashRef->update(&hashCtx, &clientRandom)) != 0)
702 goto fail;
703 if ((err = hashRef->update(&hashCtx, &serverRandom)) != 0)
704 goto fail;
705 if ((err = hashRef->update(&hashCtx, &signedParams)) != 0)
706 goto fail;
707 if ((err = hashRef->final(&hashCtx, &hashOut)) != 0)
708 goto fail;
709
710 if(sigAlg.signature==SSL_SignatureAlgorithmRSA) {
711 err = sslRsaVerify(ctx,
712 ctx->peerPubKey,
713 &algId,
714 dataToSign,
715 dataToSignLen,
716 signature,
717 signatureLen);
718 } else {
719 err = sslRawVerify(ctx,
720 ctx->peerPubKey,
721 dataToSign, /* plaintext */
722 dataToSignLen, /* plaintext length */
723 signature,
724 signatureLen);
725 }
726
727 if(err) {
728 sslErrorLog("SSLDecodeSignedServerKeyExchangeTls12: sslRawVerify "
729 "returned %d\n", (int)err);
730 goto fail;
731 }
732
733 fail:
734 SSLFreeBuffer(&signedHashes);
735 SSLFreeBuffer(&hashCtx);
736 return err;
737
738 }
739
740 /*
741 * Decode and verify a server key exchange message signed by server's
742 * public key.
743 */
744 static OSStatus
745 SSLDecodeSignedServerKeyExchange(SSLBuffer message, SSLContext *ctx)
746 {
747 OSStatus err;
748 UInt16 modulusLen = 0, exponentLen = 0, signatureLen;
749 uint8_t *modulus = NULL, *exponent = NULL, *signature;
750 bool isRsa = true;
751
752 assert(ctx->protocolSide == kSSLClientSide);
753
754 if (message.length < 2) {
755 sslErrorLog("SSLDecodeSignedServerKeyExchange: msg len error 1\n");
756 return errSSLProtocol;
757 }
758
759 /* first extract the key-exchange-method-specific parameters */
760 uint8_t *charPtr = message.data;
761 uint8_t *endCp = charPtr + message.length;
762 switch(ctx->selectedCipherSpecParams.keyExchangeMethod) {
763 case SSL_RSA:
764 case SSL_RSA_EXPORT:
765 modulusLen = SSLDecodeInt(charPtr, 2);
766 charPtr += 2;
767 if((charPtr + modulusLen) > endCp) {
768 sslErrorLog("signedServerKeyExchange: msg len error 2\n");
769 return errSSLProtocol;
770 }
771 modulus = charPtr;
772 charPtr += modulusLen;
773
774 exponentLen = SSLDecodeInt(charPtr, 2);
775 charPtr += 2;
776 if((charPtr + exponentLen) > endCp) {
777 sslErrorLog("signedServerKeyExchange: msg len error 3\n");
778 return errSSLProtocol;
779 }
780 exponent = charPtr;
781 charPtr += exponentLen;
782 break;
783 #if APPLE_DH
784 case SSL_DHE_DSS:
785 case SSL_DHE_DSS_EXPORT:
786 isRsa = false;
787 /* and fall through */
788 case SSL_DHE_RSA:
789 case SSL_DHE_RSA_EXPORT:
790 err = SSLDecodeDHKeyParams(ctx, &charPtr, message.length);
791 if(err) {
792 return err;
793 }
794 break;
795 #endif /* APPLE_DH */
796
797 case SSL_ECDHE_ECDSA:
798 isRsa = false;
799 /* and fall through */
800 case SSL_ECDHE_RSA:
801 err = SSLDecodeECDHKeyParams(ctx, &charPtr, message.length);
802 if(err) {
803 return err;
804 }
805 break;
806 default:
807 assert(0);
808 return errSSLInternal;
809 }
810
811 /* this is what's hashed */
812 SSLBuffer signedParams;
813 signedParams.data = message.data;
814 signedParams.length = charPtr - message.data;
815
816 SSLSignatureAndHashAlgorithm sigAlg;
817
818 if (sslVersionIsLikeTls12(ctx)) {
819 /* Parse the algorithm field added in TLS1.2 */
820 if((charPtr + 2) > endCp) {
821 sslErrorLog("signedServerKeyExchange: msg len error 499\n");
822 return errSSLProtocol;
823 }
824 sigAlg.hash = *charPtr++;
825 sigAlg.signature = *charPtr++;
826 }
827
828 signatureLen = SSLDecodeInt(charPtr, 2);
829 charPtr += 2;
830 if((charPtr + signatureLen) != endCp) {
831 sslErrorLog("signedServerKeyExchange: msg len error 4\n");
832 return errSSLProtocol;
833 }
834 signature = charPtr;
835
836 if (sslVersionIsLikeTls12(ctx))
837 {
838 err = SSLVerifySignedServerKeyExchangeTls12(ctx, sigAlg, signedParams,
839 signature, signatureLen);
840 } else {
841 err = SSLVerifySignedServerKeyExchange(ctx, isRsa, signedParams,
842 signature, signatureLen);
843 }
844
845 if(err)
846 goto fail;
847
848 /* Signature matches; now replace server key with new key (RSA only) */
849 switch(ctx->selectedCipherSpecParams.keyExchangeMethod) {
850 case SSL_RSA:
851 case SSL_RSA_EXPORT:
852 {
853 SSLBuffer modBuf;
854 SSLBuffer expBuf;
855
856 /* first free existing peerKey */
857 sslFreePubKey(&ctx->peerPubKey); /* no KCItem */
858
859 /* and cook up a new one from raw bits */
860 modBuf.data = modulus;
861 modBuf.length = modulusLen;
862 expBuf.data = exponent;
863 expBuf.length = exponentLen;
864 err = sslGetPubKeyFromBits(ctx,
865 &modBuf,
866 &expBuf,
867 &ctx->peerPubKey);
868 break;
869 }
870 case SSL_DHE_RSA:
871 case SSL_DHE_RSA_EXPORT:
872 case SSL_DHE_DSS:
873 case SSL_DHE_DSS_EXPORT:
874 case SSL_ECDHE_ECDSA:
875 case SSL_ECDHE_RSA:
876 break; /* handled above */
877 default:
878 assert(0);
879 }
880 fail:
881 return err;
882 }
883
884 static OSStatus
885 SSLDecodeRSAKeyExchange(SSLBuffer keyExchange, SSLContext *ctx)
886 { OSStatus err;
887 size_t outputLen, localKeyModulusLen;
888 SSLProtocolVersion version;
889 Boolean useEncryptKey = false;
890 uint8_t *src = NULL;
891 SSLPrivKey *keyRef = NULL;
892
893 assert(ctx->protocolSide == kSSLServerSide);
894 if (ctx->encryptPrivKeyRef) {
895 useEncryptKey = true;
896 }
897 if (useEncryptKey) {
898 keyRef = ctx->encryptPrivKeyRef;
899 /* FIXME: when 3420180 is implemented, pick appropriate creds here */
900 }
901 else {
902 keyRef = ctx->signingPrivKeyRef;
903 /* FIXME: when 3420180 is implemented, pick appropriate creds here */
904 }
905
906 localKeyModulusLen = sslPrivKeyLengthInBytes(keyRef);
907 if (localKeyModulusLen == 0) {
908 sslErrorLog("SSLDecodeRSAKeyExchange: private key modulus is 0\n");
909 return errSSLCrypto;
910 }
911
912 /*
913 * We have to tolerate incoming key exchange msgs with and without the
914 * two-byte "encrypted length" field.
915 */
916 if (keyExchange.length == localKeyModulusLen) {
917 /* no length encoded */
918 src = keyExchange.data;
919 }
920 else if((keyExchange.length == (localKeyModulusLen + 2)) &&
921 (ctx->negProtocolVersion >= TLS_Version_1_0)) {
922 /* TLS only - skip the length bytes */
923 src = keyExchange.data + 2;
924 }
925 else {
926 sslErrorLog("SSLDecodeRSAKeyExchange: length error (exp %u got %u)\n",
927 (unsigned)localKeyModulusLen, (unsigned)keyExchange.length);
928 return errSSLProtocol;
929 }
930 err = SSLAllocBuffer(&ctx->preMasterSecret, SSL_RSA_PREMASTER_SECRET_SIZE);
931 if(err != 0) {
932 return err;
933 }
934
935 /*
936 * From this point on, to defend against the Bleichenbacher attack
937 * and its Klima-Pokorny-Rosa variant, any errors we detect are *not*
938 * reported to the caller or the peer. If we detect any error during
939 * decryption (e.g., bad PKCS1 padding) or in the testing of the version
940 * number in the premaster secret, we proceed by generating a random
941 * premaster secret, with the correct version number, and tell our caller
942 * that everything is fine. This session will fail as soon as the
943 * finished messages are sent, since we will be using a bogus premaster
944 * secret (and hence bogus session and MAC keys). Meanwhile we have
945 * not provided any side channel information relating to the cause of
946 * the failure.
947 *
948 * See http://eprint.iacr.org/2003/052/ for more info.
949 */
950 err = sslRsaDecrypt(ctx,
951 keyRef,
952 #if USE_CDSA_CRYPTO
953 CSSM_PADDING_PKCS1,
954 #else
955 kSecPaddingPKCS1,
956 #endif
957 src,
958 localKeyModulusLen, // ciphertext len
959 ctx->preMasterSecret.data,
960 SSL_RSA_PREMASTER_SECRET_SIZE, // plaintext buf available
961 &outputLen);
962
963 if(err != errSecSuccess) {
964 /* possible Bleichenbacher attack */
965 sslLogNegotiateDebug("SSLDecodeRSAKeyExchange: RSA decrypt fail");
966 }
967 else if(outputLen != SSL_RSA_PREMASTER_SECRET_SIZE) {
968 sslLogNegotiateDebug("SSLDecodeRSAKeyExchange: premaster secret size error");
969 err = errSSLProtocol; // not passed back to caller
970 }
971
972 if(err == errSecSuccess) {
973 /*
974 * Two legal values here - the one we actually negotiated (which is
975 * technically incorrect but not uncommon), and the one the client
976 * sent as its preferred version in the client hello msg.
977 */
978 version = (SSLProtocolVersion)SSLDecodeInt(ctx->preMasterSecret.data, 2);
979 if((version != ctx->negProtocolVersion) &&
980 (version != ctx->clientReqProtocol)) {
981 /* possible Klima-Pokorny-Rosa attack */
982 sslLogNegotiateDebug("SSLDecodeRSAKeyExchange: version error");
983 err = errSSLProtocol;
984 }
985 }
986 if(err != errSecSuccess) {
987 /*
988 * Obfuscate failures for defense against Bleichenbacher and
989 * Klima-Pokorny-Rosa attacks.
990 */
991 SSLEncodeInt(ctx->preMasterSecret.data, ctx->negProtocolVersion, 2);
992 SSLBuffer tmpBuf;
993 tmpBuf.data = ctx->preMasterSecret.data + 2;
994 tmpBuf.length = SSL_RSA_PREMASTER_SECRET_SIZE - 2;
995 /* must ignore failures here */
996 sslRand(&tmpBuf);
997 }
998
999 /* in any case, save premaster secret (good or bogus) and proceed */
1000 return errSecSuccess;
1001 }
1002
1003 static OSStatus
1004 SSLEncodeRSAKeyExchange(SSLRecord *keyExchange, SSLContext *ctx)
1005 { OSStatus err;
1006 size_t outputLen, peerKeyModulusLen;
1007 size_t bufLen;
1008 uint8_t *dst;
1009 bool encodeLen = false;
1010 uint8_t *p;
1011 int head;
1012 size_t msglen;
1013
1014 assert(ctx->protocolSide == kSSLClientSide);
1015 if ((err = SSLEncodeRSAPremasterSecret(ctx)) != 0)
1016 return err;
1017
1018 keyExchange->contentType = SSL_RecordTypeHandshake;
1019 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
1020 keyExchange->protocolVersion = ctx->negProtocolVersion;
1021
1022 peerKeyModulusLen = sslPubKeyLengthInBytes(ctx->peerPubKey);
1023 if (peerKeyModulusLen == 0) {
1024 sslErrorLog("SSLEncodeRSAKeyExchange: peer key modulus is 0\n");
1025 /* FIXME: we don't return an error here... is this condition ever expected? */
1026 }
1027 #if SSL_DEBUG
1028 sslDebugLog("SSLEncodeRSAKeyExchange: peer key modulus length = %lu\n", peerKeyModulusLen);
1029 #endif
1030 msglen = peerKeyModulusLen;
1031 #if RSA_CLIENT_KEY_ADD_LENGTH
1032 if(ctx->negProtocolVersion >= TLS_Version_1_0) {
1033 msglen += 2;
1034 encodeLen = true;
1035 }
1036 #endif
1037 head = SSLHandshakeHeaderSize(keyExchange);
1038 bufLen = msglen + head;
1039 if ((err = SSLAllocBuffer(&keyExchange->contents,
1040 bufLen)) != 0)
1041 {
1042 return err;
1043 }
1044 dst = keyExchange->contents.data + head;
1045 if(encodeLen) {
1046 dst += 2;
1047 }
1048
1049 /* FIXME: can this line be removed? */
1050 p = keyExchange->contents.data;
1051
1052 p = SSLEncodeHandshakeHeader(ctx, keyExchange, SSL_HdskClientKeyExchange, msglen);
1053
1054 if(encodeLen) {
1055 /* the length of the encrypted pre_master_secret */
1056 SSLEncodeSize(keyExchange->contents.data + head,
1057 peerKeyModulusLen, 2);
1058 }
1059 err = sslRsaEncrypt(ctx,
1060 ctx->peerPubKey,
1061 #if USE_CDSA_CRYPTO
1062 CSSM_PADDING_PKCS1,
1063 #else
1064 kSecPaddingPKCS1,
1065 #endif
1066 ctx->preMasterSecret.data,
1067 SSL_RSA_PREMASTER_SECRET_SIZE,
1068 dst,
1069 peerKeyModulusLen,
1070 &outputLen);
1071 if(err) {
1072 sslErrorLog("SSLEncodeRSAKeyExchange: error %d\n", (int)err);
1073 return err;
1074 }
1075
1076 assert(outputLen == (encodeLen ? msglen - 2 : msglen));
1077
1078 return errSecSuccess;
1079 }
1080
1081
1082 #if APPLE_DH
1083
1084 // MARK: -
1085 // MARK: Diffie-Hellman Key Exchange
1086
1087 /*
1088 * Diffie-Hellman setup, server side. On successful return, the
1089 * following SSLContext members are valid:
1090 *
1091 * dhParamsPrime
1092 * dhParamsGenerator
1093 * dhPrivate
1094 * dhExchangePublic
1095 */
1096 static OSStatus
1097 SSLGenServerDHParamsAndKey(
1098 SSLContext *ctx)
1099 {
1100 OSStatus ortn;
1101 assert(ctx->protocolSide == kSSLServerSide);
1102
1103
1104 /*
1105 * Obtain D-H parameters if we don't have them.
1106 */
1107 if(ctx->dhParamsEncoded.data == NULL) {
1108 /* TODO: Pick appropriate group based on cipher suite */
1109 ccdh_const_gp_t gp = ccdh_gp_rfc5114_MODP_2048_256();
1110 cc_size n = ccdh_gp_n(gp);
1111 size_t s = ccdh_gp_prime_size(gp);
1112 uint8_t p[s];
1113 uint8_t g[s];
1114
1115 ccn_write_uint(n, ccdh_gp_prime(gp), s, p);
1116 ccn_write_uint(n, ccdh_gp_g(gp), s, g);
1117
1118 const SSLBuffer prime = {
1119 .data = p,
1120 .length = s,
1121 };
1122 const SSLBuffer generator = {
1123 .data = g,
1124 .length = s,
1125 };
1126
1127 ortn=sslEncodeDhParams(&ctx->dhParamsEncoded, /* data mallocd and RETURNED PKCS-3 encoded */
1128 &prime, /* Wire format */
1129 &generator); /* Wire format */
1130
1131 if(ortn)
1132 return ortn;
1133 }
1134
1135 #if USE_CDSA_CRYPTO
1136 /* generate per-session D-H key pair */
1137 sslFreeKey(ctx->cspHand, &ctx->dhPrivate, NULL);
1138 SSLFreeBuffer(&ctx->dhExchangePublic);
1139 ctx->dhPrivate = (CSSM_KEY *)sslMalloc(sizeof(CSSM_KEY));
1140 CSSM_KEY pubKey;
1141 ortn = sslDhGenerateKeyPair(ctx,
1142 &ctx->dhParamsEncoded,
1143 ctx->dhParamsPrime.length * 8,
1144 &pubKey, ctx->dhPrivate);
1145 if(ortn) {
1146 return ortn;
1147 }
1148 CSSM_TO_SSLBUF(&pubKey.KeyData, &ctx->dhExchangePublic);
1149 #else
1150 if (!ctx->secDHContext) {
1151 ortn = sslDhCreateKey(ctx);
1152 if(ortn)
1153 return ortn;
1154 }
1155 return sslDhGenerateKeyPair(ctx);
1156 #endif
1157 return errSecSuccess;
1158 }
1159
1160 /*
1161 * size of DH param and public key, in wire format
1162 */
1163 static size_t
1164 SSLEncodedDHKeyParamsLen(SSLContext *ctx)
1165 {
1166 SSLBuffer prime;
1167 SSLBuffer generator;
1168
1169 sslDecodeDhParams(&ctx->dhParamsEncoded, &prime, &generator);
1170
1171 return (2+prime.length+2+generator.length+2+ctx->dhExchangePublic.length);
1172 }
1173
1174 /*
1175 * Encode DH params and public key, in wire format, in caller-supplied buffer.
1176 */
1177 static OSStatus
1178 SSLEncodeDHKeyParams(
1179 SSLContext *ctx,
1180 uint8_t *charPtr)
1181 {
1182 assert(ctx->protocolSide == kSSLServerSide);
1183 assert(ctx->dhParamsEncoded.data != NULL);
1184 assert(ctx->dhExchangePublic.data != NULL);
1185
1186 SSLBuffer prime;
1187 SSLBuffer generator;
1188
1189 sslDecodeDhParams(&ctx->dhParamsEncoded, &prime, &generator);
1190
1191 charPtr = SSLEncodeInt(charPtr, prime.length, 2);
1192 memcpy(charPtr, prime.data, prime.length);
1193 charPtr += prime.length;
1194
1195 charPtr = SSLEncodeInt(charPtr, generator.length, 2);
1196 memcpy(charPtr, generator.data,
1197 generator.length);
1198 charPtr += generator.length;
1199
1200 /* TODO: hum.... sounds like this one should be in the SecDHContext */
1201 charPtr = SSLEncodeInt(charPtr, ctx->dhExchangePublic.length, 2);
1202 memcpy(charPtr, ctx->dhExchangePublic.data,
1203 ctx->dhExchangePublic.length);
1204
1205 dumpBuf("server prime", &prime);
1206 dumpBuf("server generator", &generator);
1207 dumpBuf("server pub key", &ctx->dhExchangePublic);
1208
1209 return errSecSuccess;
1210 }
1211
1212 /*
1213 * Decode DH params and server public key.
1214 */
1215 static OSStatus
1216 SSLDecodeDHKeyParams(
1217 SSLContext *ctx,
1218 uint8_t **charPtr, // IN/OUT
1219 size_t length)
1220 {
1221 OSStatus err = errSecSuccess;
1222 SSLBuffer prime;
1223 SSLBuffer generator;
1224
1225 assert(ctx->protocolSide == kSSLClientSide);
1226 uint8_t *endCp = *charPtr + length;
1227
1228 /* Allow reuse via renegotiation */
1229 SSLFreeBuffer(&ctx->dhPeerPublic);
1230
1231 /* Prime, with a two-byte length */
1232 UInt32 len = SSLDecodeInt(*charPtr, 2);
1233 (*charPtr) += 2;
1234 if((*charPtr + len) > endCp) {
1235 return errSSLProtocol;
1236 }
1237
1238 prime.data = *charPtr;
1239 prime.length = len;
1240
1241 (*charPtr) += len;
1242
1243 /* Generator, with a two-byte length */
1244 len = SSLDecodeInt(*charPtr, 2);
1245 (*charPtr) += 2;
1246 if((*charPtr + len) > endCp) {
1247 return errSSLProtocol;
1248 }
1249
1250 generator.data = *charPtr;
1251 generator.length = len;
1252
1253 (*charPtr) += len;
1254
1255 sslEncodeDhParams(&ctx->dhParamsEncoded, &prime, &generator);
1256
1257 /* peer public key, with a two-byte length */
1258 len = SSLDecodeInt(*charPtr, 2);
1259 (*charPtr) += 2;
1260 err = SSLAllocBuffer(&ctx->dhPeerPublic, len);
1261 if(err) {
1262 return err;
1263 }
1264 memmove(ctx->dhPeerPublic.data, *charPtr, len);
1265 (*charPtr) += len;
1266
1267 dumpBuf("client peer pub", &ctx->dhPeerPublic);
1268 // dumpBuf("client prime", &ctx->dhParamsPrime);
1269 // dumpBuf("client generator", &ctx->dhParamsGenerator);
1270
1271 return err;
1272 }
1273
1274 /*
1275 * Given the server's Diffie-Hellman parameters, generate our
1276 * own DH key pair, and perform key exchange using the server's
1277 * public key and our private key. The result is the premaster
1278 * secret.
1279 *
1280 * SSLContext members valid on entry:
1281 * dhParamsPrime
1282 * dhParamsGenerator
1283 * dhPeerPublic
1284 *
1285 * SSLContext members valid on successful return:
1286 * dhPrivate
1287 * dhExchangePublic
1288 * preMasterSecret
1289 */
1290 static OSStatus
1291 SSLGenClientDHKeyAndExchange(SSLContext *ctx)
1292 {
1293 OSStatus ortn;
1294
1295 #if USE_CDSA_CRYPTO
1296
1297 if((ctx->dhParamsPrime.data == NULL) ||
1298 (ctx->dhParamsGenerator.data == NULL) ||
1299 (ctx->dhPeerPublic.data == NULL)) {
1300 sslErrorLog("SSLGenClientDHKeyAndExchange: incomplete server params\n");
1301 return errSSLProtocol;
1302 }
1303
1304 /* generate two keys */
1305 CSSM_KEY pubKey;
1306 ctx->dhPrivate = (CSSM_KEY *)sslMalloc(sizeof(CSSM_KEY));
1307 ortn = sslDhGenKeyPairClient(ctx,
1308 &ctx->dhParamsPrime,
1309 &ctx->dhParamsGenerator,
1310 &pubKey, ctx->dhPrivate);
1311 if(ortn) {
1312 sslFree(ctx->dhPrivate);
1313 ctx->dhPrivate = NULL;
1314 return ortn;
1315 }
1316
1317 /* do the exchange, size of prime */
1318 ortn = sslDhKeyExchange(ctx, ctx->dhParamsPrime.length * 8,
1319 &ctx->preMasterSecret);
1320 if(ortn) {
1321 return ortn;
1322 }
1323 CSSM_TO_SSLBUF(&pubKey.KeyData, &ctx->dhExchangePublic);
1324 #else
1325 ortn=errSSLProtocol;
1326 require(ctx->dhParamsEncoded.data, out);
1327 require_noerr(ortn = sslDhCreateKey(ctx), out);
1328 require_noerr(ortn = sslDhGenerateKeyPair(ctx), out);
1329 require_noerr(ortn = sslDhKeyExchange(ctx), out);
1330 out:
1331 #endif
1332 return ortn;
1333 }
1334
1335
1336 static OSStatus
1337 SSLEncodeDHanonServerKeyExchange(SSLRecord *keyExch, SSLContext *ctx)
1338 {
1339 OSStatus ortn = errSecSuccess;
1340 int head;
1341
1342 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
1343 assert(ctx->protocolSide == kSSLServerSide);
1344
1345 /*
1346 * Obtain D-H parameters (if we don't have them) and a key pair.
1347 */
1348 ortn = SSLGenServerDHParamsAndKey(ctx);
1349 if(ortn) {
1350 return ortn;
1351 }
1352
1353 size_t length = SSLEncodedDHKeyParamsLen(ctx);
1354
1355 keyExch->protocolVersion = ctx->negProtocolVersion;
1356 keyExch->contentType = SSL_RecordTypeHandshake;
1357 head = SSLHandshakeHeaderSize(keyExch);
1358 if ((ortn = SSLAllocBuffer(&keyExch->contents, length+head)))
1359 return ortn;
1360
1361 uint8_t *charPtr = SSLEncodeHandshakeHeader(ctx, keyExch, SSL_HdskServerKeyExchange, length);
1362
1363 /* encode prime, generator, our public key */
1364 return SSLEncodeDHKeyParams(ctx, charPtr);
1365 }
1366
1367 static OSStatus
1368 SSLDecodeDHanonServerKeyExchange(SSLBuffer message, SSLContext *ctx)
1369 {
1370 OSStatus err = errSecSuccess;
1371
1372 assert(ctx->protocolSide == kSSLClientSide);
1373 if (message.length < 6) {
1374 sslErrorLog("SSLDecodeDHanonServerKeyExchange error: msg len %u\n",
1375 (unsigned)message.length);
1376 return errSSLProtocol;
1377 }
1378 uint8_t *charPtr = message.data;
1379 err = SSLDecodeDHKeyParams(ctx, &charPtr, message.length);
1380 if(err == errSecSuccess) {
1381 if((message.data + message.length) != charPtr) {
1382 err = errSSLProtocol;
1383 }
1384 }
1385 return err;
1386 }
1387
1388 static OSStatus
1389 SSLDecodeDHClientKeyExchange(SSLBuffer keyExchange, SSLContext *ctx)
1390 {
1391 OSStatus ortn = errSecSuccess;
1392 unsigned int publicLen;
1393
1394 assert(ctx->protocolSide == kSSLServerSide);
1395 if(ctx->dhParamsEncoded.data == NULL) {
1396 /* should never happen */
1397 assert(0);
1398 return errSSLInternal;
1399 }
1400
1401 /* this message simply contains the client's public DH key */
1402 uint8_t *charPtr = keyExchange.data;
1403 publicLen = SSLDecodeInt(charPtr, 2);
1404 charPtr += 2;
1405 /* TODO : Check the len here ? Will fail in sslDhKeyExchange anyway */
1406 /*
1407 if((keyExchange.length != publicLen + 2) ||
1408 (publicLen > ctx->dhParamsPrime.length)) {
1409 return errSSLProtocol;
1410 }
1411 */
1412 SSLFreeBuffer(&ctx->dhPeerPublic); // allow reuse via renegotiation
1413 ortn = SSLAllocBuffer(&ctx->dhPeerPublic, publicLen);
1414 if(ortn) {
1415 return ortn;
1416 }
1417 memmove(ctx->dhPeerPublic.data, charPtr, publicLen);
1418
1419 /* DH Key exchange, result --> premaster secret */
1420 SSLFreeBuffer(&ctx->preMasterSecret);
1421 #if USE_CDSA_CRYPTO
1422 ortn = sslDhKeyExchange(ctx, ctx->dhParamsPrime.length * 8,
1423 &ctx->preMasterSecret);
1424 #else
1425 ortn = sslDhKeyExchange(ctx);
1426 #endif
1427 dumpBuf("server peer pub", &ctx->dhPeerPublic);
1428 dumpBuf("server premaster", &ctx->preMasterSecret);
1429 return ortn;
1430 }
1431
1432 static OSStatus
1433 SSLEncodeDHClientKeyExchange(SSLRecord *keyExchange, SSLContext *ctx)
1434 { OSStatus err;
1435 size_t outputLen;
1436 int head;
1437
1438 assert(ctx->protocolSide == kSSLClientSide);
1439 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
1440
1441 keyExchange->contentType = SSL_RecordTypeHandshake;
1442 keyExchange->protocolVersion = ctx->negProtocolVersion;
1443
1444 if ((err = SSLGenClientDHKeyAndExchange(ctx)) != 0)
1445 return err;
1446
1447 outputLen = ctx->dhExchangePublic.length + 2;
1448 head = SSLHandshakeHeaderSize(keyExchange);
1449 if ((err = SSLAllocBuffer(&keyExchange->contents,outputLen + head)))
1450 return err;
1451
1452 uint8_t *charPtr = SSLEncodeHandshakeHeader(ctx, keyExchange, SSL_HdskClientKeyExchange, outputLen);
1453
1454 charPtr = SSLEncodeSize(charPtr, ctx->dhExchangePublic.length, 2);
1455 memcpy(charPtr, ctx->dhExchangePublic.data, ctx->dhExchangePublic.length);
1456
1457 dumpBuf("client pub key", &ctx->dhExchangePublic);
1458 dumpBuf("client premaster", &ctx->preMasterSecret);
1459
1460 return errSecSuccess;
1461 }
1462
1463 #endif /* APPLE_DH */
1464
1465 // MARK: -
1466 // MARK: ECDSA Key Exchange
1467
1468 /*
1469 * Given the server's ECDH curve params and public key, generate our
1470 * own ECDH key pair, and perform key exchange using the server's
1471 * public key and our private key. The result is the premaster
1472 * secret.
1473 *
1474 * SSLContext members valid on entry:
1475 * if keyExchangeMethod == SSL_ECDHE_ECDSA or SSL_ECDHE_RSA:
1476 * ecdhPeerPublic
1477 * ecdhPeerCurve
1478 * if keyExchangeMethod == SSL_ECDH_ECDSA or SSL_ECDH_RSA:
1479 * peerPubKey, from which we infer ecdhPeerCurve
1480 *
1481 * SSLContext members valid on successful return:
1482 * ecdhPrivate
1483 * ecdhExchangePublic
1484 * preMasterSecret
1485 */
1486 static OSStatus
1487 SSLGenClientECDHKeyAndExchange(SSLContext *ctx)
1488 {
1489 OSStatus ortn;
1490
1491 assert(ctx->protocolSide == kSSLClientSide);
1492
1493 switch(ctx->selectedCipherSpecParams.keyExchangeMethod) {
1494 case SSL_ECDHE_ECDSA:
1495 case SSL_ECDHE_RSA:
1496 /* Server sent us an ephemeral key with peer curve specified */
1497 if(ctx->ecdhPeerPublic.data == NULL) {
1498 sslErrorLog("SSLGenClientECDHKeyAndExchange: incomplete server params\n");
1499 return errSSLProtocol;
1500 }
1501 break;
1502 case SSL_ECDH_ECDSA:
1503 case SSL_ECDH_RSA:
1504 {
1505 /* No server key exchange; we have to get the curve from the key */
1506 if(ctx->peerPubKey == NULL) {
1507 sslErrorLog("SSLGenClientECDHKeyAndExchange: no peer key\n");
1508 return errSSLInternal;
1509 }
1510
1511 /* The peer curve is in the key's CSSM_X509_ALGORITHM_IDENTIFIER... */
1512 ortn = sslEcdsaPeerCurve(ctx->peerPubKey, &ctx->ecdhPeerCurve);
1513 if(ortn) {
1514 return ortn;
1515 }
1516 sslEcdsaDebug("SSLGenClientECDHKeyAndExchange: derived peerCurve %u",
1517 (unsigned)ctx->ecdhPeerCurve);
1518 break;
1519 }
1520 default:
1521 /* shouldn't be here */
1522 assert(0);
1523 return errSSLInternal;
1524 }
1525
1526 /* Generate our (ephemeral) pair, or extract it from our signing identity */
1527 if((ctx->negAuthType == SSLClientAuth_RSAFixedECDH) ||
1528 (ctx->negAuthType == SSLClientAuth_ECDSAFixedECDH)) {
1529 /*
1530 * Client auth with a fixed ECDH key in the cert. Convert private key
1531 * from SecKeyRef to CSSM format. We don't need ecdhExchangePublic
1532 * because the server gets that from our cert.
1533 */
1534 assert(ctx->signingPrivKeyRef != NULL);
1535 #if USE_CDSA_CRYPTO
1536 //assert(ctx->cspHand != 0);
1537 sslFreeKey(ctx->cspHand, &ctx->ecdhPrivate, NULL);
1538 SSLFreeBuffer(&ctx->ecdhExchangePublic);
1539 ortn = SecKeyGetCSSMKey(ctx->signingPrivKeyRef, (const CSSM_KEY **)&ctx->ecdhPrivate);
1540 if(ortn) {
1541 return ortn;
1542 }
1543 ortn = SecKeyGetCSPHandle(ctx->signingPrivKeyRef, &ctx->ecdhPrivCspHand);
1544 if(ortn) {
1545 sslErrorLog("SSLGenClientECDHKeyAndExchange: SecKeyGetCSPHandle err %d\n",
1546 (int)ortn);
1547 }
1548 #endif
1549 sslEcdsaDebug("+++ Extracted ECDH private key");
1550 }
1551 else {
1552 /* generate a new pair */
1553 ortn = sslEcdhGenerateKeyPair(ctx, ctx->ecdhPeerCurve);
1554 if(ortn) {
1555 return ortn;
1556 }
1557 #if USE_CDSA_CRYPTO
1558 sslEcdsaDebug("+++ Generated %u bit (%u byte) ECDH key pair",
1559 (unsigned)ctx->ecdhPrivate->KeyHeader.LogicalKeySizeInBits,
1560 (unsigned)((ctx->ecdhPrivate->KeyHeader.LogicalKeySizeInBits + 7) / 8));
1561 #endif
1562 }
1563
1564
1565 /* do the exchange --> premaster secret */
1566 ortn = sslEcdhKeyExchange(ctx, &ctx->preMasterSecret);
1567 if(ortn) {
1568 return ortn;
1569 }
1570 return errSecSuccess;
1571 }
1572
1573
1574 /*
1575 * Decode ECDH params and server public key.
1576 */
1577 static OSStatus
1578 SSLDecodeECDHKeyParams(
1579 SSLContext *ctx,
1580 uint8_t **charPtr, // IN/OUT
1581 size_t length)
1582 {
1583 OSStatus err = errSecSuccess;
1584
1585 sslEcdsaDebug("+++ Decoding ECDH Server Key Exchange");
1586
1587 assert(ctx->protocolSide == kSSLClientSide);
1588 uint8_t *endCp = *charPtr + length;
1589
1590 /* Allow reuse via renegotiation */
1591 SSLFreeBuffer(&ctx->ecdhPeerPublic);
1592
1593 /*** ECParameters - just a curveType and a named curve ***/
1594
1595 /* 1-byte curveType, we only allow one type */
1596 uint8_t curveType = **charPtr;
1597 if(curveType != SSL_CurveTypeNamed) {
1598 sslEcdsaDebug("+++ SSLDecodeECDHKeyParams: Bad curveType (%u)\n", (unsigned)curveType);
1599 return errSSLProtocol;
1600 }
1601 (*charPtr)++;
1602 if(*charPtr > endCp) {
1603 return errSSLProtocol;
1604 }
1605
1606 /* two-byte curve */
1607 ctx->ecdhPeerCurve = SSLDecodeInt(*charPtr, 2);
1608 (*charPtr) += 2;
1609 if(*charPtr > endCp) {
1610 return errSSLProtocol;
1611 }
1612 switch(ctx->ecdhPeerCurve) {
1613 case SSL_Curve_secp256r1:
1614 case SSL_Curve_secp384r1:
1615 case SSL_Curve_secp521r1:
1616 break;
1617 default:
1618 sslEcdsaDebug("+++ SSLDecodeECDHKeyParams: Bad curve (%u)\n",
1619 (unsigned)ctx->ecdhPeerCurve);
1620 return errSSLProtocol;
1621 }
1622
1623 sslEcdsaDebug("+++ SSLDecodeECDHKeyParams: ecdhPeerCurve %u",
1624 (unsigned)ctx->ecdhPeerCurve);
1625
1626 /*** peer public key as an ECPoint ***/
1627
1628 /*
1629 * The spec says the the max length of an ECPoint is 255 bytes, limiting
1630 * this whole mechanism to a max modulus size of 1020 bits, which I find
1631 * hard to believe...
1632 */
1633 UInt32 len = SSLDecodeInt(*charPtr, 1);
1634 (*charPtr)++;
1635 if((*charPtr + len) > endCp) {
1636 return errSSLProtocol;
1637 }
1638 err = SSLAllocBuffer(&ctx->ecdhPeerPublic, len);
1639 if(err) {
1640 return err;
1641 }
1642 memmove(ctx->ecdhPeerPublic.data, *charPtr, len);
1643 (*charPtr) += len;
1644
1645 dumpBuf("client peer pub", &ctx->ecdhPeerPublic);
1646
1647 return err;
1648 }
1649
1650
1651 static OSStatus
1652 SSLEncodeECDHClientKeyExchange(SSLRecord *keyExchange, SSLContext *ctx)
1653 { OSStatus err;
1654 size_t outputLen;
1655 int head;
1656
1657 assert(ctx->protocolSide == kSSLClientSide);
1658 if ((err = SSLGenClientECDHKeyAndExchange(ctx)) != 0)
1659 return err;
1660
1661 /*
1662 * Per RFC 4492 5.7, if we're doing ECDSA_fixed_ECDH or RSA_fixed_ECDH
1663 * client auth, we still send this message, but it's empty (because the
1664 * server gets our public key from our cert).
1665 */
1666 bool emptyMsg = false;
1667 switch(ctx->negAuthType) {
1668 case SSLClientAuth_RSAFixedECDH:
1669 case SSLClientAuth_ECDSAFixedECDH:
1670 emptyMsg = true;
1671 break;
1672 default:
1673 break;
1674 }
1675 if(emptyMsg) {
1676 outputLen = 0;
1677 }
1678 else {
1679 outputLen = ctx->ecdhExchangePublic.length + 1;
1680 }
1681
1682 keyExchange->contentType = SSL_RecordTypeHandshake;
1683 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
1684 keyExchange->protocolVersion = ctx->negProtocolVersion;
1685 head = SSLHandshakeHeaderSize(keyExchange);
1686 if ((err = SSLAllocBuffer(&keyExchange->contents,outputLen + head)))
1687 return err;
1688
1689 uint8_t *charPtr = SSLEncodeHandshakeHeader(ctx, keyExchange, SSL_HdskClientKeyExchange, outputLen);
1690 if(emptyMsg) {
1691 sslEcdsaDebug("+++ Sending EMPTY ECDH Client Key Exchange");
1692 }
1693 else {
1694 /* just a 1-byte length here... */
1695 charPtr = SSLEncodeSize(charPtr, ctx->ecdhExchangePublic.length, 1);
1696 memcpy(charPtr, ctx->ecdhExchangePublic.data, ctx->ecdhExchangePublic.length);
1697 sslEcdsaDebug("+++ Encoded ECDH Client Key Exchange");
1698 }
1699
1700 dumpBuf("client pub key", &ctx->ecdhExchangePublic);
1701 dumpBuf("client premaster", &ctx->preMasterSecret);
1702 return errSecSuccess;
1703 }
1704
1705
1706
1707 static OSStatus
1708 SSLDecodePSKClientKeyExchange(SSLBuffer keyExchange, SSLContext *ctx)
1709 {
1710 OSStatus ortn = errSecSuccess;
1711 unsigned int identityLen;
1712
1713 assert(ctx->protocolSide == kSSLServerSide);
1714
1715 /* this message simply contains the client's PSK identity */
1716 uint8_t *charPtr = keyExchange.data;
1717 identityLen = SSLDecodeInt(charPtr, 2);
1718 charPtr += 2;
1719
1720 SSLFreeBuffer(&ctx->pskIdentity); // allow reuse via renegotiation
1721 ortn = SSLAllocBuffer(&ctx->pskIdentity, identityLen);
1722 if(ortn) {
1723 return ortn;
1724 }
1725 memmove(ctx->pskIdentity.data, charPtr, identityLen);
1726
1727 /* TODO: At this point we know the identity of the PSK client,
1728 we should break out of the handshake, so we can select the appropriate
1729 PreShared secret. As this stands, the preshared secret needs to be known
1730 before the handshake starts. */
1731
1732 size_t n=ctx->pskSharedSecret.length;
1733
1734 if(n==0) return errSSLBadConfiguration;
1735
1736 if ((ortn = SSLAllocBuffer(&ctx->preMasterSecret, 2*(n+2))) != 0)
1737 return ortn;
1738
1739 uint8_t *p=ctx->preMasterSecret.data;
1740
1741 p = SSLEncodeInt(p, n, 2);
1742 memset(p, 0, n); p+=n;
1743 p = SSLEncodeInt(p, n, 2);
1744 memcpy(p, ctx->pskSharedSecret.data, n);
1745
1746 dumpBuf("server premaster (PSK)", &ctx->preMasterSecret);
1747
1748 return ortn;
1749 }
1750
1751
1752 static OSStatus
1753 SSLEncodePSKClientKeyExchange(SSLRecord *keyExchange, SSLContext *ctx)
1754 {
1755 OSStatus err;
1756 size_t outputLen;
1757 int head;
1758
1759 assert(ctx->protocolSide == kSSLClientSide);
1760
1761 outputLen = ctx->pskIdentity.length+2;
1762
1763 keyExchange->contentType = SSL_RecordTypeHandshake;
1764 assert(ctx->negProtocolVersion >= SSL_Version_3_0);
1765 keyExchange->protocolVersion = ctx->negProtocolVersion;
1766 head = SSLHandshakeHeaderSize(keyExchange);
1767 if ((err = SSLAllocBuffer(&keyExchange->contents,outputLen + head)))
1768 return err;
1769
1770 uint8_t *charPtr = SSLEncodeHandshakeHeader(ctx, keyExchange, SSL_HdskClientKeyExchange, outputLen);
1771
1772 charPtr = SSLEncodeSize(charPtr, ctx->pskIdentity.length, 2);
1773 memcpy(charPtr, ctx->pskIdentity.data, ctx->pskIdentity.length);
1774
1775
1776 /* We better have a pskSharedSecret already */
1777 size_t n=ctx->pskSharedSecret.length;
1778
1779 if(n==0) return errSSLBadConfiguration;
1780
1781 if ((err = SSLAllocBuffer(&ctx->preMasterSecret, 2*(n+2))) != 0)
1782 return err;
1783
1784 uint8_t *p=ctx->preMasterSecret.data;
1785
1786 p = SSLEncodeInt(p, n, 2);
1787 memset(p, 0, n); p+=n;
1788 p = SSLEncodeInt(p, n, 2);
1789 memcpy(p, ctx->pskSharedSecret.data, n);
1790
1791 dumpBuf("client premaster (PSK)", &ctx->preMasterSecret);
1792
1793 return errSecSuccess;
1794 }
1795
1796
1797 // MARK: -
1798 // MARK: Public Functions
1799 OSStatus
1800 SSLEncodeServerKeyExchange(SSLRecord *keyExch, SSLContext *ctx)
1801 { OSStatus err;
1802
1803 switch (ctx->selectedCipherSpecParams.keyExchangeMethod)
1804 { case SSL_RSA:
1805 case SSL_RSA_EXPORT:
1806 #if APPLE_DH
1807 case SSL_DHE_RSA:
1808 case SSL_DHE_RSA_EXPORT:
1809 case SSL_DHE_DSS:
1810 case SSL_DHE_DSS_EXPORT:
1811 #endif /* APPLE_DH */
1812 if ((err = SSLEncodeSignedServerKeyExchange(keyExch, ctx)) != 0)
1813 return err;
1814 break;
1815 #if APPLE_DH
1816 case SSL_DH_anon:
1817 case SSL_DH_anon_EXPORT:
1818 if ((err = SSLEncodeDHanonServerKeyExchange(keyExch, ctx)) != 0)
1819 return err;
1820 break;
1821 #endif
1822 default:
1823 return errSecUnimplemented;
1824 }
1825
1826 return errSecSuccess;
1827 }
1828
1829 OSStatus
1830 SSLProcessServerKeyExchange(SSLBuffer message, SSLContext *ctx)
1831 {
1832 OSStatus err;
1833
1834 switch (ctx->selectedCipherSpecParams.keyExchangeMethod) {
1835 case SSL_RSA:
1836 case SSL_RSA_EXPORT:
1837 #if APPLE_DH
1838 case SSL_DHE_RSA:
1839 case SSL_DHE_RSA_EXPORT:
1840 case SSL_DHE_DSS:
1841 case SSL_DHE_DSS_EXPORT:
1842 #endif
1843 case SSL_ECDHE_ECDSA:
1844 case SSL_ECDHE_RSA:
1845 err = SSLDecodeSignedServerKeyExchange(message, ctx);
1846 break;
1847 #if APPLE_DH
1848 case SSL_DH_anon:
1849 case SSL_DH_anon_EXPORT:
1850 err = SSLDecodeDHanonServerKeyExchange(message, ctx);
1851 break;
1852 #endif
1853 default:
1854 err = errSecUnimplemented;
1855 break;
1856 }
1857
1858 return err;
1859 }
1860
1861 OSStatus
1862 SSLEncodeKeyExchange(SSLRecord *keyExchange, SSLContext *ctx)
1863 { OSStatus err;
1864
1865 assert(ctx->protocolSide == kSSLClientSide);
1866
1867 switch (ctx->selectedCipherSpecParams.keyExchangeMethod) {
1868 case SSL_RSA:
1869 case SSL_RSA_EXPORT:
1870 sslDebugLog("SSLEncodeKeyExchange: RSA method\n");
1871 err = SSLEncodeRSAKeyExchange(keyExchange, ctx);
1872 break;
1873 #if APPLE_DH
1874 case SSL_DHE_RSA:
1875 case SSL_DHE_RSA_EXPORT:
1876 case SSL_DHE_DSS:
1877 case SSL_DHE_DSS_EXPORT:
1878 case SSL_DH_anon:
1879 case SSL_DH_anon_EXPORT:
1880 sslDebugLog("SSLEncodeKeyExchange: DH method\n");
1881 err = SSLEncodeDHClientKeyExchange(keyExchange, ctx);
1882 break;
1883 #endif
1884 case SSL_ECDH_ECDSA:
1885 case SSL_ECDHE_ECDSA:
1886 case SSL_ECDH_RSA:
1887 case SSL_ECDHE_RSA:
1888 case SSL_ECDH_anon:
1889 sslDebugLog("SSLEncodeKeyExchange: ECDH method\n");
1890 err = SSLEncodeECDHClientKeyExchange(keyExchange, ctx);
1891 break;
1892 case TLS_PSK:
1893 err = SSLEncodePSKClientKeyExchange(keyExchange, ctx);
1894 break;
1895 default:
1896 sslErrorLog("SSLEncodeKeyExchange: unknown method (%d)\n",
1897 ctx->selectedCipherSpecParams.keyExchangeMethod);
1898 err = errSecUnimplemented;
1899 }
1900
1901 return err;
1902 }
1903
1904 OSStatus
1905 SSLProcessKeyExchange(SSLBuffer keyExchange, SSLContext *ctx)
1906 { OSStatus err;
1907
1908 switch (ctx->selectedCipherSpecParams.keyExchangeMethod)
1909 { case SSL_RSA:
1910 case SSL_RSA_EXPORT:
1911 if ((err = SSLDecodeRSAKeyExchange(keyExchange, ctx)) != 0)
1912 return err;
1913 break;
1914 #if APPLE_DH
1915 case SSL_DH_anon:
1916 case SSL_DHE_DSS:
1917 case SSL_DHE_DSS_EXPORT:
1918 case SSL_DHE_RSA:
1919 case SSL_DHE_RSA_EXPORT:
1920 case SSL_DH_anon_EXPORT:
1921 sslDebugLog("SSLProcessKeyExchange: processing DH key exchange (%d)\n",
1922 ctx->selectedCipherSpecParams.keyExchangeMethod);
1923 if ((err = SSLDecodeDHClientKeyExchange(keyExchange, ctx)) != 0)
1924 return err;
1925 break;
1926 #endif
1927 case TLS_PSK:
1928 if ((err = SSLDecodePSKClientKeyExchange(keyExchange, ctx)) != 0)
1929 return err;
1930 break;
1931 default:
1932 sslErrorLog("SSLProcessKeyExchange: unknown keyExchangeMethod (%d)\n",
1933 ctx->selectedCipherSpecParams.keyExchangeMethod);
1934 return errSecUnimplemented;
1935 }
1936
1937 return errSecSuccess;
1938 }
1939
1940 OSStatus
1941 SSLInitPendingCiphers(SSLContext *ctx)
1942 { OSStatus err;
1943 SSLBuffer key;
1944 int keyDataLen;
1945
1946 err = errSecSuccess;
1947 key.data = 0;
1948
1949 keyDataLen = ctx->selectedCipherSpecParams.macSize +
1950 ctx->selectedCipherSpecParams.keySize +
1951 ctx->selectedCipherSpecParams.ivSize;
1952 keyDataLen *= 2; /* two of everything */
1953
1954 if ((err = SSLAllocBuffer(&key, keyDataLen)))
1955 return err;
1956 assert(ctx->sslTslCalls != NULL);
1957 if ((err = ctx->sslTslCalls->generateKeyMaterial(key, ctx)) != 0)
1958 goto fail;
1959
1960 if((err = ctx->recFuncs->initPendingCiphers(ctx->recCtx, ctx->selectedCipher, (ctx->protocolSide==kSSLServerSide), key)) != 0)
1961 goto fail;
1962
1963 ctx->writePending_ready = 1;
1964 ctx->readPending_ready = 1;
1965
1966 fail:
1967 SSLFreeBuffer(&key);
1968 return err;
1969 }