crypto.c 34 KB

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