crypto.c 34 KB

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