crypto.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /* Name: crypto.c
  2. * Author: Cecylia Bocovich <cbocovic@uwaterloo.ca>
  3. *
  4. * This file contains code for checking tagged flows, processing handshake
  5. * messages, and computing the master secret for a TLS session.
  6. *
  7. * Some code in this document is based on the OpenSSL source files:
  8. * crypto/ec/ec_key.c
  9. * crypto/dh/dh_key.c
  10. * */
  11. /*TODO: openssl attribution */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <assert.h>
  15. #include <string.h>
  16. #include <openssl/evp.h>
  17. #include <openssl/dh.h>
  18. #include <openssl/bn.h>
  19. #include <openssl/err.h>
  20. #include <openssl/rand.h>
  21. #include <openssl/ssl.h>
  22. #include <openssl/sha.h>
  23. #include "ptwist.h"
  24. #include "crypto.h"
  25. #include "flow.h"
  26. #include "slitheen.h"
  27. #include "util.h"
  28. #define NID_sect163k1 721
  29. #define NID_sect163r1 722
  30. #define NID_sect163r2 723
  31. #define NID_sect193r1 724
  32. #define NID_sect193r2 725
  33. #define NID_sect233k1 726
  34. #define NID_sect233r1 727
  35. #define NID_sect239k1 728
  36. #define NID_sect283k1 729
  37. #define NID_sect283r1 730
  38. #define NID_sect409k1 731
  39. #define NID_sect409r1 732
  40. #define NID_sect571k1 733
  41. #define NID_sect571r1 734
  42. #define NID_secp160k1 708
  43. #define NID_secp160r1 709
  44. #define NID_secp160r2 710
  45. #define NID_secp192k1 711
  46. #define NID_X9_62_prime192v1 409
  47. #define NID_secp224k1 712
  48. #define NID_secp224r1 713
  49. #define NID_secp256k1 714
  50. #define NID_X9_62_prime256v1 415
  51. #define NID_secp384r1 715
  52. #define NID_secp521r1 716
  53. #define NID_brainpoolP256r1 927
  54. #define NID_brainpoolP384r1 931
  55. #define NID_brainpoolP512r1 933
  56. static int nid_list[] = {
  57. NID_sect163k1, /* sect163k1 (1) */
  58. NID_sect163r1, /* sect163r1 (2) */
  59. NID_sect163r2, /* sect163r2 (3) */
  60. NID_sect193r1, /* sect193r1 (4) */
  61. NID_sect193r2, /* sect193r2 (5) */
  62. NID_sect233k1, /* sect233k1 (6) */
  63. NID_sect233r1, /* sect233r1 (7) */
  64. NID_sect239k1, /* sect239k1 (8) */
  65. NID_sect283k1, /* sect283k1 (9) */
  66. NID_sect283r1, /* sect283r1 (10) */
  67. NID_sect409k1, /* sect409k1 (11) */
  68. NID_sect409r1, /* sect409r1 (12) */
  69. NID_sect571k1, /* sect571k1 (13) */
  70. NID_sect571r1, /* sect571r1 (14) */
  71. NID_secp160k1, /* secp160k1 (15) */
  72. NID_secp160r1, /* secp160r1 (16) */
  73. NID_secp160r2, /* secp160r2 (17) */
  74. NID_secp192k1, /* secp192k1 (18) */
  75. NID_X9_62_prime192v1, /* secp192r1 (19) */
  76. NID_secp224k1, /* secp224k1 (20) */
  77. NID_secp224r1, /* secp224r1 (21) */
  78. NID_secp256k1, /* secp256k1 (22) */
  79. NID_X9_62_prime256v1, /* secp256r1 (23) */
  80. NID_secp384r1, /* secp384r1 (24) */
  81. NID_secp521r1, /* secp521r1 (25) */
  82. NID_brainpoolP256r1, /* brainpoolP256r1 (26) */
  83. NID_brainpoolP384r1, /* brainpoolP384r1 (27) */
  84. NID_brainpoolP512r1 /* brainpool512r1 (28) */
  85. };
  86. /** Updates the hash of all TLS handshake messages upon the
  87. * receipt of a new message. This hash is eventually used
  88. * to verify the TLS Finished message
  89. *
  90. * Inputs:
  91. * f: the tagged flow
  92. * hs: A pointer to the start of the handshake message
  93. *
  94. * Output:
  95. * 0 on success, 1 on failure
  96. */
  97. int update_finish_hash(flow *f, uint8_t *hs){
  98. //find handshake length
  99. const struct handshake_header *hs_hdr;
  100. uint8_t *p = hs;
  101. hs_hdr = (struct handshake_header*) p;
  102. uint32_t hs_len = HANDSHAKE_MESSAGE_LEN(hs_hdr);
  103. EVP_DigestUpdate(f->finish_md_ctx, hs, hs_len+4);
  104. return 0;
  105. }
  106. /** Extracts the server parameters from the server key
  107. * exchange message
  108. *
  109. * Inputs:
  110. * f: the tagged flow
  111. * hs: the beginning of the server key exchange
  112. * handshake message
  113. *
  114. * Output:
  115. * 0 on success, 1 on failure
  116. */
  117. int extract_parameters(flow *f, uint8_t *hs){
  118. uint8_t *p;
  119. long i;
  120. int ok=1;
  121. p = hs + HANDSHAKE_HEADER_LEN;
  122. if(f->keyex_alg == 1){
  123. DH *dh;
  124. if((dh = DH_new()) == NULL){
  125. return 1;
  126. }
  127. /* Extract prime modulus */
  128. n2s(p,i);
  129. if(!(dh->p = BN_bin2bn(p,i,NULL))){
  130. return 1;
  131. }
  132. p += i;
  133. /* Extract generator */
  134. n2s(p,i);
  135. if(!(dh->g = BN_bin2bn(p,i,NULL))){
  136. return 1;
  137. }
  138. p += i;
  139. /* Extract server public value */
  140. n2s(p,i);
  141. if(!(dh->pub_key = BN_bin2bn(p,i,NULL))){
  142. return 1;
  143. }
  144. f->dh = dh;
  145. } else if (f->keyex_alg == 2){
  146. EC_KEY *ecdh;
  147. EC_GROUP *ngroup;
  148. const EC_GROUP *group;
  149. BN_CTX *bn_ctx = NULL;
  150. EC_POINT *srvr_ecpoint = NULL;
  151. int curve_nid = 0;
  152. int encoded_pt_len = 0;
  153. if((ecdh = EC_KEY_new()) == NULL) {
  154. SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
  155. goto err;
  156. }
  157. if(p[0] != 0x03){//not a named curve
  158. goto err;
  159. }
  160. //int curve_id = (p[1] << 8) + p[2];
  161. int curve_id = *(p+2);
  162. if((curve_id < 0) || ((unsigned int)curve_id >
  163. sizeof(nid_list) / sizeof(nid_list[0]))){
  164. goto err;
  165. }
  166. curve_nid = nid_list[curve_id-1];
  167. /* Extract curve
  168. if(!tls1_check_curve(s, p, 3)) {
  169. goto err;
  170. }
  171. if((*(p+2) < 1) || ((unsigned int) (*(p+2)) > sizeof(nid_list) / sizeof(nid_list[0]))){
  172. goto err;
  173. }
  174. curve_nid = nid_list[*(p+2)];
  175. */
  176. ngroup = EC_GROUP_new_by_curve_name(curve_nid);
  177. if(ngroup == NULL){
  178. goto err;
  179. }
  180. if(EC_KEY_set_group(ecdh, ngroup) == 0){
  181. goto err;
  182. }
  183. EC_GROUP_free(ngroup);
  184. group = EC_KEY_get0_group(ecdh);
  185. p += 3;
  186. /* Get EC point */
  187. if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
  188. ((bn_ctx = BN_CTX_new()) == NULL)) {
  189. goto err;
  190. }
  191. encoded_pt_len = *p;
  192. p += 1;
  193. if(EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len,
  194. bn_ctx) == 0){
  195. goto err;
  196. }
  197. p += encoded_pt_len;
  198. EC_KEY_set_public_key(ecdh, srvr_ecpoint);
  199. f->ecdh = ecdh;
  200. ecdh = NULL;
  201. BN_CTX_free(bn_ctx);
  202. bn_ctx = NULL;
  203. EC_POINT_free(srvr_ecpoint);
  204. srvr_ecpoint = NULL;
  205. ok=0;
  206. err:
  207. if(bn_ctx != NULL){
  208. BN_CTX_free(bn_ctx);
  209. }
  210. if(srvr_ecpoint != NULL){
  211. EC_POINT_free(srvr_ecpoint);
  212. }
  213. if(ecdh != NULL){
  214. EC_KEY_free(ecdh);
  215. }
  216. }
  217. return ok;
  218. }
  219. /* Encrypt/Decrypt a TLS record
  220. *
  221. * Inputs:
  222. * f: the tagged flow
  223. * input: a pointer to the data that is to be encrypted/
  224. * decrypted
  225. * output: a pointer to where the data should be written
  226. * after it is encrypted or decrypted
  227. * len: the length of the data
  228. * incoming: the direction of the record
  229. * type: the type of the TLS record
  230. * enc: 1 for encryption, 0 for decryption
  231. *
  232. * Output:
  233. * length of the output data
  234. */
  235. int encrypt(flow *f, uint8_t *input, uint8_t *output, int32_t len, int32_t incoming, int32_t type, int32_t enc){
  236. uint8_t *p = input;
  237. EVP_CIPHER_CTX *ds = (incoming) ? ((enc) ? f->srvr_write_ctx : f->clnt_read_ctx) : ((enc) ? f->clnt_write_ctx : f->srvr_read_ctx) ;
  238. if(ds == NULL){
  239. printf("FAIL\n");
  240. return 1;
  241. }
  242. uint8_t *seq;
  243. seq = (incoming) ? f->read_seq : f->write_seq;
  244. if(f->application && (ds->iv[EVP_GCM_TLS_FIXED_IV_LEN] == 0)){
  245. //fill in rest of iv
  246. for(int i = EVP_GCM_TLS_FIXED_IV_LEN; i< ds->cipher->iv_len; i++){
  247. ds->iv[i] = p[i- EVP_GCM_TLS_FIXED_IV_LEN];
  248. }
  249. }
  250. #ifdef DEBUG
  251. printf("\t\tiv: ");
  252. for(int i=0; i<ds->cipher->iv_len; i++){
  253. printf("%02X ", ds->iv[i]);
  254. }
  255. printf("\n");
  256. #endif
  257. uint8_t buf[13];
  258. memcpy(buf, seq, 8);
  259. for(int i=7; i>=0; i--){
  260. ++seq[i];
  261. if(seq[i] != 0)
  262. break;
  263. }
  264. buf[8] = type;
  265. buf[9] = 0x03;
  266. buf[10] = 0x03;
  267. buf[11] = len >> 8; //len >> 8;
  268. buf[12] = len & 0xff;//len *0xff;
  269. int32_t pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
  270. 13, buf); // = int32_t pad?
  271. if(enc)
  272. len += pad;
  273. int32_t n = EVP_Cipher(ds, p, p, len); //decrypt in place
  274. if(n<0) return 0;
  275. #ifdef DEBUG
  276. printf("decrypted data:\n");
  277. for(int i=0; i< len; i++){
  278. printf("%02x ", p[EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  279. }
  280. printf("\n");
  281. #endif
  282. if(!enc)
  283. p[EVP_GCM_TLS_EXPLICIT_IV_LEN+n] = '\0';
  284. return n;
  285. }
  286. /** Verifies the hash in a TLS finished message
  287. *
  288. * Inputs:
  289. * f: the tagged flow
  290. * p: a pointer to the TLS Finished handshake message
  291. * incoming: the direction of the flow
  292. *
  293. * Output:
  294. * 0 on success, 1 on failure
  295. */
  296. int verify_finish_hash(flow *f, uint8_t *p, int32_t incoming){
  297. EVP_MD_CTX ctx;
  298. uint8_t hash[EVP_MAX_MD_SIZE];
  299. uint32_t hash_len;
  300. EVP_MD_CTX_init(&ctx);
  301. //get header length
  302. struct handshake_header *hs_hdr;
  303. hs_hdr = (struct handshake_header*) p;
  304. uint32_t fin_length = HANDSHAKE_MESSAGE_LEN(hs_hdr);
  305. p += HANDSHAKE_HEADER_LEN;
  306. //finalize hash of handshake msgs
  307. EVP_MD_CTX_copy_ex(&ctx, f->finish_md_ctx);
  308. EVP_DigestFinal_ex(&ctx, hash, &hash_len);
  309. //now use pseudorandom function
  310. uint8_t *output = ecalloc(1, fin_length);
  311. if(incoming){
  312. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE, (uint8_t *) TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE , hash, hash_len, NULL, 0, NULL, 0, output, fin_length);
  313. } else {
  314. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE, (uint8_t *) TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE , hash, hash_len, NULL, 0, NULL, 0, output, fin_length);
  315. }
  316. //now compare
  317. if(CRYPTO_memcmp(p, output, fin_length) != 0){
  318. printf("VERIFY FAILED\n");
  319. goto err;
  320. }
  321. free(output);
  322. EVP_MD_CTX_cleanup(&ctx);
  323. return 0;
  324. err:
  325. if(output != NULL)
  326. free(output);
  327. EVP_MD_CTX_cleanup(&ctx);
  328. return 1;
  329. }
  330. /** Computes the TLS master secret from the decoy server's
  331. * public key parameters and the leaked secret from the
  332. * extracted Slitheen tag
  333. *
  334. * Input:
  335. * f: the tagged flow
  336. *
  337. * Output:
  338. * 0 on success, 1 on failure
  339. */
  340. int compute_master_secret(flow *f){
  341. #ifdef DEBUG_HS
  342. printf("Computing master secret (%x:%d -> %x:%d)...\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  343. #endif
  344. DH *dh_srvr = NULL;
  345. DH *dh_clnt = NULL;
  346. BN_CTX *ctx = NULL;
  347. BIGNUM *pub_key = NULL, *priv_key = NULL, *order = NULL;
  348. EC_KEY *clnt_ecdh = NULL;
  349. EC_POINT *e_pub_key = NULL;
  350. int ok =1;
  351. uint8_t *pre_master_secret = ecalloc(1, PRE_MASTER_MAX_LEN);//TODO: find right length
  352. int32_t pre_master_len;
  353. uint32_t l;
  354. int32_t bytes;
  355. uint8_t *buf = NULL;
  356. if(f->keyex_alg == 1){
  357. BN_MONT_CTX *mont = NULL;
  358. ctx = BN_CTX_new();
  359. dh_srvr = f->dh;
  360. dh_clnt = DHparams_dup(dh_srvr);
  361. l = dh_clnt->length ? dh_clnt->length : BN_num_bits(dh_clnt->p) - 1;
  362. bytes = (l+7) / 8;
  363. buf = (uint8_t *)OPENSSL_malloc(bytes);
  364. if (buf == NULL){
  365. BNerr(BN_F_BNRAND, ERR_R_MALLOC_FAILURE);
  366. goto err;
  367. }
  368. pub_key = BN_new();
  369. priv_key = BN_new();
  370. #ifdef DEBUG
  371. printf("key =");
  372. for(int i=0; i< 16; i++)
  373. printf(" %02x", f->key[i]);
  374. printf("\n");
  375. #endif
  376. PRF(f, f->key, 16,
  377. (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  378. NULL, 0, NULL, 0, NULL, 0,
  379. buf, bytes);
  380. #ifdef DEBUG
  381. printf("Generated the following rand bytes: ");
  382. for(int i=0; i< bytes; i++){
  383. printf(" %02x ", buf[i]);
  384. }
  385. printf("\n");
  386. #endif
  387. if (!BN_bin2bn(buf, bytes, priv_key))
  388. goto err;
  389. {
  390. BIGNUM *prk;
  391. prk = priv_key;
  392. if (!dh_clnt->meth->bn_mod_exp(dh_clnt, pub_key, dh_clnt->g, prk, dh_clnt->p, ctx, mont)){
  393. goto err;
  394. }
  395. }
  396. dh_clnt->pub_key = pub_key;
  397. dh_clnt->priv_key = priv_key;
  398. pre_master_len = DH_compute_key(pre_master_secret, dh_srvr->pub_key, dh_clnt);
  399. } else if(f->keyex_alg == 2){
  400. const EC_GROUP *srvr_group = NULL;
  401. const EC_POINT *srvr_ecpoint = NULL;
  402. EC_KEY *tkey;
  403. tkey = f->ecdh;
  404. if(tkey == NULL){
  405. return 1;
  406. }
  407. srvr_group = EC_KEY_get0_group(tkey);
  408. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  409. if((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
  410. return 1;
  411. }
  412. if((clnt_ecdh = EC_KEY_new()) == NULL) {
  413. goto err;
  414. }
  415. if(!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  416. goto err;
  417. }
  418. /* Now generate key from tag */
  419. if((order = BN_new()) == NULL){
  420. goto err;
  421. }
  422. if((ctx = BN_CTX_new()) == NULL){
  423. goto err;
  424. }
  425. if((priv_key = BN_new()) == NULL){
  426. goto err;
  427. }
  428. if(!EC_GROUP_get_order(srvr_group, order, ctx)){
  429. goto err;
  430. }
  431. l = BN_num_bits(order)-1;
  432. bytes = (l+7)/8;
  433. buf = (unsigned char *)OPENSSL_malloc(bytes);
  434. if(buf == NULL){
  435. goto err;
  436. }
  437. PRF(f, f->key, 16, (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  438. NULL, 0, NULL, 0, NULL, 0, buf, bytes);
  439. #ifdef DEBUG
  440. printf("Generated the following rand bytes: ");
  441. for(int i=0; i< bytes; i++){
  442. printf("%02x ", buf[i]);
  443. }
  444. printf("\n");
  445. #endif
  446. if(!BN_bin2bn(buf, bytes, priv_key)){
  447. goto err;
  448. }
  449. if((e_pub_key = EC_POINT_new(srvr_group)) == NULL){
  450. goto err;
  451. }
  452. if(!EC_POINT_mul(EC_KEY_get0_group(clnt_ecdh), e_pub_key, priv_key, NULL, NULL, ctx)){
  453. goto err;
  454. }
  455. EC_KEY_set_private_key(clnt_ecdh, priv_key);
  456. EC_KEY_set_public_key(clnt_ecdh, e_pub_key);
  457. /*Compute the master secret */
  458. int32_t field_size = EC_GROUP_get_degree(srvr_group);
  459. if(field_size <= 0){
  460. goto err;
  461. }
  462. pre_master_len = ECDH_compute_key(pre_master_secret, (field_size + 7) / 8,
  463. srvr_ecpoint, clnt_ecdh, NULL);
  464. if(pre_master_len <= 0) {
  465. goto err;
  466. }
  467. }
  468. /*Generate master secret */
  469. PRF(f, pre_master_secret, pre_master_len, (uint8_t *) TLS_MD_MASTER_SECRET_CONST, TLS_MD_MASTER_SECRET_CONST_SIZE, f->client_random, SSL3_RANDOM_SIZE, f->server_random, SSL3_RANDOM_SIZE, NULL, 0, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  470. if(f->current_session != NULL){
  471. memcpy(f->current_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  472. }
  473. #ifdef DEBUG
  474. fprintf(stdout, "Premaster Secret:\n");
  475. BIO_dump_fp(stdout, (char *)pre_master_secret, pre_master_len);
  476. fprintf(stdout, "Client Random:\n");
  477. BIO_dump_fp(stdout, (char *)f->client_random, SSL3_RANDOM_SIZE);
  478. fprintf(stdout, "Server Random:\n");
  479. BIO_dump_fp(stdout, (char *)f->server_random, SSL3_RANDOM_SIZE);
  480. fprintf(stdout, "Master Secret:\n");
  481. BIO_dump_fp(stdout, (char *)f->master_secret, SSL3_MASTER_SECRET_SIZE);
  482. #endif
  483. //remove pre_master_secret from memory
  484. memset(pre_master_secret, 0, PRE_MASTER_MAX_LEN);
  485. ok = 0;
  486. err:
  487. if((pub_key != NULL) && (dh_srvr == NULL)){
  488. BN_free(pub_key);
  489. }
  490. if((priv_key != NULL) && (dh_clnt == NULL) && (EC_KEY_get0_private_key(clnt_ecdh) == NULL)){
  491. BN_free(priv_key);
  492. }
  493. if(ctx != NULL){
  494. BN_CTX_free(ctx);
  495. }
  496. OPENSSL_free(buf);
  497. free(pre_master_secret);
  498. if(dh_srvr != NULL){
  499. DH_free(dh_srvr);
  500. }
  501. if(dh_clnt != NULL) {
  502. DH_free(dh_clnt);
  503. }
  504. if(order){
  505. BN_free(order);
  506. }
  507. if(clnt_ecdh != NULL){
  508. EC_KEY_free(clnt_ecdh);
  509. }
  510. if(e_pub_key != NULL){
  511. EC_POINT_free(e_pub_key);
  512. }
  513. //TODO:
  514. //This is causing seg faults sometimes O.o commenting out atm (might cause memleaks)
  515. /*if(priv_key != NULL){
  516. BN_free(priv_key);
  517. }*/
  518. return ok;
  519. }
  520. /** Saves the random none from the server hello message
  521. *
  522. * Inputs:
  523. * f: the tagged flow
  524. * hs: a pointer to the beginning of the server hello msg
  525. *
  526. * Output:
  527. * 0 on success, 1 on failure
  528. */
  529. int extract_server_random(flow *f, uint8_t *hs){
  530. uint8_t *p;
  531. p = hs + HANDSHAKE_HEADER_LEN;
  532. p+=2; //skip version
  533. memcpy(f->server_random, p, SSL3_RANDOM_SIZE);
  534. p += SSL3_RANDOM_SIZE;
  535. //skip session id
  536. uint8_t id_len = (uint8_t) p[0];
  537. p ++;
  538. p += id_len;
  539. //now extract ciphersuite
  540. #ifdef DEBUG_HS
  541. printf("Checking cipher\n");
  542. #endif
  543. if(((p[0] <<8) + p[1]) == 0x9E){
  544. #ifdef DEBUG_HS
  545. printf("USING DHE-RSA-AES128-GCM-SHA256\n");
  546. fflush(stdout);
  547. #endif
  548. f->keyex_alg = 1;
  549. f->cipher = EVP_aes_128_gcm();
  550. f->message_digest = EVP_sha256();
  551. } else if(((p[0] <<8) + p[1]) == 0x9F){
  552. #ifdef DEBUG_HS
  553. printf("USING DHE-RSA-AES256-GCM-SHA384\n");
  554. fflush(stdout);
  555. #endif
  556. f->keyex_alg = 1;
  557. f->cipher = EVP_aes_256_gcm();
  558. f->message_digest = EVP_sha384();
  559. } else if(((p[0] <<8) + p[1]) == 0xC02F){
  560. #ifdef DEBUG_HS
  561. printf("USING ECDHE-RSA-AES128-GCM-SHA256\n");
  562. fflush(stdout);
  563. #endif
  564. f->keyex_alg = 2;
  565. f->cipher = EVP_aes_128_gcm();
  566. f->message_digest = EVP_sha256();
  567. } else if(((p[0] <<8) + p[1]) == 0xC030){
  568. #ifdef DEBUG_HS
  569. printf("USING ECDHE-RSA-AES256-GCM-SHA384\n");
  570. fflush(stdout);
  571. #endif
  572. f->keyex_alg = 2;
  573. f->cipher = EVP_aes_256_gcm();
  574. f->message_digest = EVP_sha384();
  575. } else {
  576. printf("%x %x = %x\n", p[0], p[1], ((p[0] <<8) + p[1]));
  577. printf("Error: unsupported cipher\n");
  578. fflush(stdout);
  579. return 1;
  580. }
  581. return 0;
  582. }
  583. /** PRF using sha384, as defined in RFC 5246
  584. *
  585. * Inputs:
  586. * secret: the master secret used to sign the hash
  587. * secret_len: the length of the master secret
  588. * seed{1, ..., 4}: seed values that are virtually
  589. * concatenated
  590. * seed{1,...4}_len: length of the seeds
  591. * output: a pointer to the output of the PRF
  592. * output_len: the number of desired bytes
  593. *
  594. * Output:
  595. * 0 on success, 1 on failure
  596. */
  597. int PRF(flow *f, uint8_t *secret, int32_t secret_len,
  598. uint8_t *seed1, int32_t seed1_len,
  599. uint8_t *seed2, int32_t seed2_len,
  600. uint8_t *seed3, int32_t seed3_len,
  601. uint8_t *seed4, int32_t seed4_len,
  602. uint8_t *output, int32_t output_len){
  603. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  604. EVP_PKEY *mac_key;
  605. const EVP_MD *md = f->message_digest;
  606. uint8_t A[EVP_MAX_MD_SIZE];
  607. size_t len, A_len;
  608. int chunk = EVP_MD_size(md);
  609. int remaining = output_len;
  610. uint8_t *out = output;
  611. EVP_MD_CTX_init(&ctx);
  612. EVP_MD_CTX_init(&ctx_tmp);
  613. EVP_MD_CTX_init(&ctx_init);
  614. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  615. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
  616. /* Calculate first A value */
  617. EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key);
  618. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  619. if(seed1 != NULL && seed1_len > 0){
  620. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  621. }
  622. if(seed2 != NULL && seed2_len > 0){
  623. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  624. }
  625. if(seed3 != NULL && seed3_len > 0){
  626. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  627. }
  628. if(seed4 != NULL && seed4_len > 0){
  629. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  630. }
  631. EVP_DigestSignFinal(&ctx, A, &A_len);
  632. //iterate until desired length is achieved
  633. while(remaining > 0){
  634. /* Now compute SHA384(secret, A+seed) */
  635. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  636. EVP_DigestSignUpdate(&ctx, A, A_len);
  637. EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx);
  638. if(seed1 != NULL && seed1_len > 0){
  639. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  640. }
  641. if(seed2 != NULL && seed2_len > 0){
  642. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  643. }
  644. if(seed3 != NULL && seed3_len > 0){
  645. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  646. }
  647. if(seed4 != NULL && seed4_len > 0){
  648. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  649. }
  650. if(remaining > chunk){
  651. EVP_DigestSignFinal(&ctx, out, &len);
  652. out += len;
  653. remaining -= len;
  654. /* Next A value */
  655. EVP_DigestSignFinal(&ctx_tmp, A, &A_len);
  656. } else {
  657. EVP_DigestSignFinal(&ctx, A, &A_len);
  658. memcpy(out, A, remaining);
  659. remaining -= remaining;
  660. }
  661. }
  662. EVP_PKEY_free(mac_key);
  663. EVP_MD_CTX_cleanup(&ctx);
  664. EVP_MD_CTX_cleanup(&ctx_tmp);
  665. EVP_MD_CTX_cleanup(&ctx_init);
  666. OPENSSL_cleanse(A, sizeof(A));
  667. return 0;
  668. }
  669. /** After receiving change cipher spec, calculate keys from master secret
  670. *
  671. * Input:
  672. * f: the tagged flow
  673. *
  674. * Output:
  675. * 0 on success, 1 on failure
  676. */
  677. int init_ciphers(flow *f){
  678. EVP_CIPHER_CTX *r_ctx;
  679. EVP_CIPHER_CTX *w_ctx;
  680. EVP_CIPHER_CTX *w_ctx_srvr;
  681. EVP_CIPHER_CTX *r_ctx_srvr;
  682. const EVP_CIPHER *c = f->cipher;
  683. if(c == NULL){
  684. /*This *shouldn't* happen, but might if a serverHello msg isn't received
  685. * or if a session is resumed in a strange way */
  686. remove_flow(f);
  687. return 0;
  688. }
  689. /* Generate Keys */
  690. uint8_t *write_key, *write_iv;
  691. uint8_t *read_key, *read_iv;
  692. int32_t mac_len, key_len, iv_len;
  693. key_len = EVP_CIPHER_key_length(c);
  694. iv_len = EVP_CIPHER_iv_length(c); //EVP_GCM_TLS_FIXED_IV_LEN;
  695. mac_len = EVP_MD_size(f->message_digest);
  696. int32_t total_len = key_len + iv_len + mac_len;
  697. total_len *= 2;
  698. uint8_t *key_block = ecalloc(1, total_len);
  699. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  700. (uint8_t *) TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
  701. f->server_random, SSL3_RANDOM_SIZE,
  702. f->client_random, SSL3_RANDOM_SIZE,
  703. NULL, 0,
  704. key_block, total_len);
  705. #ifdef DEBUG
  706. printf("master secret: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  707. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  708. printf("%02x ", f->master_secret[i]);
  709. }
  710. printf("\n");
  711. printf("client random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  712. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  713. printf("%02x ", f->client_random[i]);
  714. }
  715. printf("\n");
  716. printf("server random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  717. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  718. printf("%02x ", f->server_random[i]);
  719. }
  720. printf("\n");
  721. printf("keyblock: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  722. for(int i=0; i< total_len; i++){
  723. printf("%02x ", key_block[i]);
  724. }
  725. printf("\n");
  726. #endif
  727. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  728. write_key = key_block;
  729. read_key = key_block + key_len;
  730. write_iv = key_block + 2*key_len;
  731. read_iv = key_block + 2*key_len + iv_len;
  732. /* Initialize Cipher Contexts */
  733. r_ctx = EVP_CIPHER_CTX_new();
  734. w_ctx = EVP_CIPHER_CTX_new();
  735. EVP_CIPHER_CTX_init(r_ctx);
  736. EVP_CIPHER_CTX_init(w_ctx);
  737. w_ctx_srvr = EVP_CIPHER_CTX_new();
  738. r_ctx_srvr = EVP_CIPHER_CTX_new();
  739. EVP_CIPHER_CTX_init(w_ctx_srvr);
  740. EVP_CIPHER_CTX_init(r_ctx_srvr);
  741. /* Initialize MACs --- not needed for aes_256_gcm
  742. write_mac = key_block + 2*key_len + 2*iv_len;
  743. read_mac = key_block + 2*key_len + 2*iv_len + mac_len;
  744. read_mac_ctx = EVP_MD_CTX_create();
  745. write_mac_ctx = EVP_MD_CTX_create();
  746. read_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, read_mac, mac_len);
  747. write_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, write_mac, mac_len);
  748. EVP_DigestSignInit(read_mac_ctx, NULL, EVP_sha384(), NULL, read_mac_key);
  749. EVP_DigestSignInit(write_mac_ctx, NULL, EVP_sha384(), NULL, write_mac_key);
  750. EVP_PKEY_free(read_mac_key);
  751. EVP_PKEY_free(write_mac_key);*/
  752. #ifdef DEBUG
  753. {
  754. int i;
  755. fprintf(stderr, "EVP_CipherInit_ex(r_ctx,c,key=,iv=,which)\n");
  756. fprintf(stderr, "\tkey= ");
  757. for (i = 0; i < c->key_len; i++)
  758. fprintf(stderr, "%02x", read_key[i]);
  759. fprintf(stderr, "\n");
  760. fprintf(stderr, "\t iv= ");
  761. for (i = 0; i < c->iv_len; i++)
  762. fprintf(stderr, "%02x", read_iv[i]);
  763. fprintf(stderr, "\n");
  764. }
  765. {
  766. int i;
  767. fprintf(stderr, "EVP_CipherInit_ex(w_ctx,c,key=,iv=,which)\n");
  768. fprintf(stderr, "\tkey= ");
  769. for (i = 0; i < c->key_len; i++)
  770. fprintf(stderr, "%02x", write_key[i]);
  771. fprintf(stderr, "\n");
  772. fprintf(stderr, "\t iv= ");
  773. for (i = 0; i < c->iv_len; i++)
  774. fprintf(stderr, "%02x", write_iv[i]);
  775. fprintf(stderr, "\n");
  776. }
  777. #endif
  778. if(!EVP_CipherInit_ex(r_ctx, c, NULL, read_key, NULL, 0)){
  779. printf("FAIL r_ctx\n");
  780. }
  781. if(!EVP_CipherInit_ex(w_ctx, c, NULL, write_key, NULL, 1)){
  782. printf("FAIL w_ctx\n");
  783. }
  784. if(!EVP_CipherInit_ex(w_ctx_srvr, c, NULL, read_key, NULL, 1)){
  785. printf("FAIL w_ctx_srvr\n");
  786. }
  787. if(!EVP_CipherInit_ex(r_ctx_srvr, c, NULL, write_key, NULL, 0)){
  788. printf("FAIL r_ctx_srvr\n");
  789. }
  790. EVP_CIPHER_CTX_ctrl(r_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  791. EVP_CIPHER_CTX_ctrl(w_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  792. EVP_CIPHER_CTX_ctrl(w_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  793. EVP_CIPHER_CTX_ctrl(r_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  794. f->clnt_read_ctx = r_ctx;
  795. f->clnt_write_ctx = w_ctx;
  796. f->srvr_read_ctx = r_ctx_srvr;
  797. f->srvr_write_ctx = w_ctx_srvr;
  798. free(key_block);
  799. return 0;
  800. }
  801. // To avoid warnings about MAC paddings, use this to update contexts
  802. void update_context(flow *f, uint8_t *input, int32_t len, int32_t incoming, int32_t type, int32_t enc){
  803. uint8_t *output = ecalloc(1, len+16+8);
  804. memcpy(output + EVP_GCM_TLS_EXPLICIT_IV_LEN, input, len);
  805. //If the original message was a decryption, this will be an necryption.
  806. //Incoming field stays the same
  807. encrypt(f, output, output, len+8, incoming, type, !enc);
  808. //revert the sequence number
  809. uint8_t *seq = incoming ? f->read_seq : f->write_seq;
  810. for(int i=7; i>=0; i--){
  811. --seq[i];
  812. if(seq[i] >= 0)
  813. break;
  814. else
  815. seq[i] = 0;
  816. }
  817. free(output);
  818. }
  819. /** Checks a handshake message to see if it is tagged or a
  820. * recognized flow. If the client random nonce is tagged,
  821. * adds the flow to the flow table to be tracked.
  822. *
  823. * Inputs:
  824. * info: the processed packet
  825. * f: the tagged flow
  826. *
  827. * Output:
  828. * none
  829. */
  830. void check_handshake(struct packet_info *info){
  831. FILE *fp;
  832. int res, code;
  833. uint8_t *hello_rand;
  834. const struct handshake_header *handshake_hdr;
  835. byte privkey[PTWIST_BYTES];
  836. byte key[16];
  837. uint8_t *p = info->app_data + RECORD_HEADER_LEN;
  838. handshake_hdr = (struct handshake_header*) p;
  839. code = handshake_hdr->type;
  840. if (code == 0x01){
  841. p += CLIENT_HELLO_HEADER_LEN;
  842. //now pointing to hello random :D
  843. hello_rand = p;
  844. p += 4; //skipping time bytes
  845. /* Load the private key */
  846. fp = fopen("privkey", "rb");
  847. if (fp == NULL) {
  848. perror("fopen");
  849. exit(1);
  850. }
  851. res = fread(privkey, PTWIST_BYTES, 1, fp);
  852. if (res < 1) {
  853. perror("fread");
  854. exit(1);
  855. }
  856. fclose(fp);
  857. /* check tag*/
  858. res = check_tag(key, privkey, p, (const byte *)"context", 7);
  859. if (!res) {
  860. #ifdef DEBUG
  861. printf("Received tagged flow! (key =");
  862. for(i=0; i<16;i++){
  863. printf(" %02x", key[i]);
  864. }
  865. printf(")\n");
  866. #endif
  867. /* Save flow in table */
  868. flow *flow_ptr = add_flow(info);
  869. if(flow_ptr == NULL){
  870. fprintf(stderr, "Memory failure\n");
  871. return;
  872. }
  873. for(int i=0; i<16; i++){
  874. flow_ptr->key[i] = key[i];
  875. }
  876. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  877. #ifdef DEBUG
  878. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  879. printf("%02x ", hello_rand[i]);
  880. }
  881. printf("\n");
  882. printf("Saved new flow\n");
  883. #endif
  884. }
  885. }
  886. }
  887. /* Check the given tag with the given context and private key. Return 0
  888. if the tag is properly formed, non-0 if not. If the tag is correct,
  889. set key to the resulting secret key. */
  890. int check_tag(byte key[16], const byte privkey[PTWIST_BYTES],
  891. const byte tag[PTWIST_TAG_BYTES], const byte *context,
  892. size_t context_len)
  893. {
  894. int ret = -1;
  895. byte sharedsec[PTWIST_BYTES+context_len];
  896. byte taghashout[32];
  897. #if PTWIST_PUZZLE_STRENGTH > 0
  898. byte hashout[32];
  899. size_t puzzle_len = 16+PTWIST_RESP_BYTES;
  900. byte value_to_hash[puzzle_len];
  901. unsigned int firstbits;
  902. int firstpass = 0;
  903. #endif
  904. /* Compute the shared secret privkey*TAG */
  905. ptwist_pointmul(sharedsec, tag, privkey);
  906. /* Create the hash tag keys */
  907. memmove(sharedsec+PTWIST_BYTES, context, context_len);
  908. SHA256(sharedsec, PTWIST_BYTES, taghashout);
  909. #if PTWIST_PUZZLE_STRENGTH > 0
  910. /* Construct the proposed solution to the puzzle */
  911. memmove(value_to_hash, taghashout, 16);
  912. memmove(value_to_hash+16, tag+PTWIST_BYTES, PTWIST_RESP_BYTES);
  913. value_to_hash[16+PTWIST_RESP_BYTES-1] &= PTWIST_RESP_MASK;
  914. /* Hash the proposed solution and see if it is correct; that is, the
  915. * hash should start with PTWIST_PUZZLE_STRENGTH bits of 0s,
  916. * followed by the last PTWIST_HASH_SHOWBITS of the tag. */
  917. md_map_sh256(hashout, value_to_hash, puzzle_len);
  918. #if PTWIST_PUZZLE_STRENGTH < 32
  919. /* This assumes that you're on an architecture that doesn't care
  920. * about alignment, and is little endian. */
  921. firstbits = *(unsigned int*)hashout;
  922. if ((firstbits & PTWIST_PUZZLE_MASK) == 0) {
  923. firstpass = 1;
  924. }
  925. #else
  926. #error "Code assumes PTWIST_PUZZLE_STRENGTH < 32"
  927. #endif
  928. if (firstpass) {
  929. bn_t Hbn, Tbn;
  930. bn_new(Hbn);
  931. bn_new(Tbn);
  932. hashout[PTWIST_HASH_TOTBYTES-1] &= PTWIST_HASH_MASK;
  933. bn_read_bin(Hbn, hashout, PTWIST_HASH_TOTBYTES, BN_POS);
  934. bn_rsh(Hbn, Hbn, PTWIST_PUZZLE_STRENGTH);
  935. bn_read_bin(Tbn, tag+PTWIST_BYTES, PTWIST_TAG_BYTES-PTWIST_BYTES,
  936. BN_POS);
  937. bn_rsh(Tbn, Tbn, PTWIST_RESP_BITS);
  938. ret = (bn_cmp(Tbn,Hbn) != CMP_EQ);
  939. bn_free(Hbn);
  940. bn_free(Tbn);
  941. }
  942. #else
  943. /* We're not using a client puzzle, so just check that the first
  944. * PTWIST_HASH_SHOWBITS bits of the above hash fill out the rest
  945. * of the tag. If there's no puzzle, PTWIST_HASH_SHOWBITS must be
  946. * a multiple of 8. */
  947. ret = (memcmp(tag+PTWIST_BYTES, taghashout, PTWIST_HASH_SHOWBITS/8) != 0);
  948. #endif
  949. if (ret == 0) {
  950. memmove(key, taghashout+16, 16);
  951. }
  952. return ret;
  953. }