crypto.c 33 KB

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