crypto.c 40 KB

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