crypto.c 25 KB

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