crypto.c 32 KB

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