crypto.c 32 KB

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