crypto.c 26 KB

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