public
Last active

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