crypto.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  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->key, 16,
  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. #ifdef DEBUG_HS
  470. printf("Extra input:\n");
  471. for(int i=0; i< extra_input_len; i++){
  472. printf("%02x ", extra_input[i]);
  473. }
  474. printf("\n");
  475. #endif
  476. EVP_MD_CTX_copy_ex(&ctx, f->finish_md_ctx);
  477. EVP_DigestUpdate(&ctx, extra_input, extra_input_len);
  478. EVP_DigestFinal_ex(&ctx, hash, &hash_len);
  479. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  480. (uint8_t *) TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE ,
  481. hash, hash_len, NULL, 0, NULL, 0,
  482. output, fin_length);
  483. //replace existing MAC with modified one
  484. memcpy(p, output, fin_length);
  485. #ifdef DEBUG_HS
  486. printf("New finished:\n");
  487. for(int i=0; i< fin_length; i++){
  488. printf("%02x ", p[i]);
  489. }
  490. printf("\n");
  491. #endif
  492. free(extra_input);
  493. }
  494. if(update_finish_hash(f, old_finished)){
  495. fprintf(stderr, "Error updating finish hash with FINISHED msg\n");
  496. remove_flow(f);
  497. goto err;
  498. }
  499. free(old_finished);
  500. free(output);
  501. EVP_MD_CTX_cleanup(&ctx);
  502. return 0;
  503. err:
  504. if(output != NULL)
  505. free(output);
  506. if(old_finished != NULL)
  507. free(old_finished);
  508. EVP_MD_CTX_cleanup(&ctx);
  509. return 1;
  510. }
  511. /** Computes the TLS master secret from the decoy server's
  512. * public key parameters and the leaked secret from the
  513. * extracted Slitheen tag
  514. *
  515. * Input:
  516. * f: the tagged flow
  517. *
  518. * Output:
  519. * 0 on success, 1 on failure
  520. */
  521. int compute_master_secret(flow *f){
  522. #ifdef DEBUG_HS
  523. 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);
  524. #endif
  525. DH *dh_srvr = NULL;
  526. DH *dh_clnt = NULL;
  527. BN_CTX *ctx = NULL;
  528. BIGNUM *pub_key = NULL, *priv_key = NULL, *order = NULL;
  529. EC_KEY *clnt_ecdh = NULL;
  530. EC_POINT *e_pub_key = NULL;
  531. int ok =1;
  532. uint8_t *pre_master_secret = ecalloc(1, PRE_MASTER_MAX_LEN);
  533. int32_t pre_master_len;
  534. uint32_t l;
  535. int32_t bytes;
  536. uint8_t *buf = NULL;
  537. if(f->keyex_alg == 1){
  538. BN_MONT_CTX *mont = NULL;
  539. ctx = BN_CTX_new();
  540. dh_srvr = f->dh;
  541. dh_clnt = DHparams_dup(dh_srvr);
  542. l = dh_clnt->length ? dh_clnt->length : BN_num_bits(dh_clnt->p) - 1;
  543. bytes = (l+7) / 8;
  544. buf = (uint8_t *)OPENSSL_malloc(bytes);
  545. if (buf == NULL){
  546. BNerr(BN_F_BNRAND, ERR_R_MALLOC_FAILURE);
  547. goto err;
  548. }
  549. pub_key = BN_new();
  550. priv_key = BN_new();
  551. #ifdef DEBUG
  552. printf("key =");
  553. for(int i=0; i< 16; i++)
  554. printf(" %02x", f->key[i]);
  555. printf("\n");
  556. #endif
  557. PRF(f, f->key, 16,
  558. (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  559. NULL, 0, NULL, 0, NULL, 0,
  560. buf, bytes);
  561. #ifdef DEBUG
  562. printf("Generated the following rand bytes: ");
  563. for(int i=0; i< bytes; i++){
  564. printf(" %02x ", buf[i]);
  565. }
  566. printf("\n");
  567. #endif
  568. if (!BN_bin2bn(buf, bytes, priv_key))
  569. goto err;
  570. {
  571. BIGNUM *prk;
  572. prk = priv_key;
  573. if (!dh_clnt->meth->bn_mod_exp(dh_clnt, pub_key, dh_clnt->g, prk, dh_clnt->p, ctx, mont)){
  574. goto err;
  575. }
  576. }
  577. dh_clnt->pub_key = pub_key;
  578. dh_clnt->priv_key = priv_key;
  579. pre_master_len = DH_compute_key(pre_master_secret, dh_srvr->pub_key, dh_clnt);
  580. } else if(f->keyex_alg == 2){
  581. const EC_GROUP *srvr_group = NULL;
  582. const EC_POINT *srvr_ecpoint = NULL;
  583. EC_KEY *tkey;
  584. tkey = f->ecdh;
  585. if(tkey == NULL){
  586. return 1;
  587. }
  588. srvr_group = EC_KEY_get0_group(tkey);
  589. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  590. if((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
  591. return 1;
  592. }
  593. if((clnt_ecdh = EC_KEY_new()) == NULL) {
  594. goto err;
  595. }
  596. if(!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  597. goto err;
  598. }
  599. /* Now generate key from tag */
  600. if((order = BN_new()) == NULL){
  601. goto err;
  602. }
  603. if((ctx = BN_CTX_new()) == NULL){
  604. goto err;
  605. }
  606. if((priv_key = BN_new()) == NULL){
  607. goto err;
  608. }
  609. if(!EC_GROUP_get_order(srvr_group, order, ctx)){
  610. goto err;
  611. }
  612. l = BN_num_bits(order)-1;
  613. bytes = (l+7)/8;
  614. buf = (unsigned char *)OPENSSL_malloc(bytes);
  615. if(buf == NULL){
  616. goto err;
  617. }
  618. PRF(f, f->key, 16, (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  619. NULL, 0, NULL, 0, NULL, 0, buf, bytes);
  620. #ifdef DEBUG
  621. printf("Generated the following rand bytes: ");
  622. for(int i=0; i< bytes; i++){
  623. printf("%02x ", buf[i]);
  624. }
  625. printf("\n");
  626. #endif
  627. if(!BN_bin2bn(buf, bytes, priv_key)){
  628. goto err;
  629. }
  630. if((e_pub_key = EC_POINT_new(srvr_group)) == NULL){
  631. goto err;
  632. }
  633. if(!EC_POINT_mul(EC_KEY_get0_group(clnt_ecdh), e_pub_key, priv_key, NULL, NULL, ctx)){
  634. goto err;
  635. }
  636. EC_KEY_set_private_key(clnt_ecdh, priv_key);
  637. EC_KEY_set_public_key(clnt_ecdh, e_pub_key);
  638. /*Compute the master secret */
  639. int32_t field_size = EC_GROUP_get_degree(srvr_group);
  640. if(field_size <= 0){
  641. goto err;
  642. }
  643. pre_master_len = ECDH_compute_key(pre_master_secret, (field_size + 7) / 8,
  644. srvr_ecpoint, clnt_ecdh, NULL);
  645. if(pre_master_len <= 0) {
  646. goto err;
  647. }
  648. }
  649. /*Generate master secret */
  650. 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);
  651. if(f->current_session != NULL){
  652. memcpy(f->current_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  653. }
  654. #ifdef DEBUG
  655. fprintf(stdout, "Premaster Secret:\n");
  656. BIO_dump_fp(stdout, (char *)pre_master_secret, pre_master_len);
  657. fprintf(stdout, "Client Random:\n");
  658. BIO_dump_fp(stdout, (char *)f->client_random, SSL3_RANDOM_SIZE);
  659. fprintf(stdout, "Server Random:\n");
  660. BIO_dump_fp(stdout, (char *)f->server_random, SSL3_RANDOM_SIZE);
  661. fprintf(stdout, "Master Secret:\n");
  662. BIO_dump_fp(stdout, (char *)f->master_secret, SSL3_MASTER_SECRET_SIZE);
  663. #endif
  664. //remove pre_master_secret from memory
  665. memset(pre_master_secret, 0, PRE_MASTER_MAX_LEN);
  666. ok = 0;
  667. err:
  668. if((pub_key != NULL) && (dh_srvr == NULL)){
  669. BN_free(pub_key);
  670. }
  671. if((priv_key != NULL) && ((dh_clnt == NULL) || (EC_KEY_get0_private_key(clnt_ecdh) == NULL))){
  672. BN_free(priv_key);
  673. }
  674. if(ctx != NULL){
  675. BN_CTX_free(ctx);
  676. }
  677. OPENSSL_free(buf);
  678. free(pre_master_secret);
  679. if(dh_srvr != NULL){
  680. DH_free(dh_srvr);
  681. }
  682. if(dh_clnt != NULL) {
  683. DH_free(dh_clnt);
  684. }
  685. if(order){
  686. BN_free(order);
  687. }
  688. if(clnt_ecdh != NULL){
  689. EC_KEY_free(clnt_ecdh);
  690. }
  691. if(e_pub_key != NULL){
  692. EC_POINT_free(e_pub_key);
  693. }
  694. return ok;
  695. }
  696. /** Saves the random none from the server hello message
  697. *
  698. * Inputs:
  699. * f: the tagged flow
  700. * hs: a pointer to the beginning of the server hello msg
  701. *
  702. * Output:
  703. * 0 on success, 1 on failure
  704. */
  705. int extract_server_random(flow *f, uint8_t *hs){
  706. uint8_t *p;
  707. p = hs + HANDSHAKE_HEADER_LEN;
  708. p+=2; //skip version
  709. memcpy(f->server_random, p, SSL3_RANDOM_SIZE);
  710. p += SSL3_RANDOM_SIZE;
  711. //skip session id
  712. uint8_t id_len = (uint8_t) p[0];
  713. p ++;
  714. p += id_len;
  715. //now extract ciphersuite
  716. #ifdef DEBUG_HS
  717. printf("Checking cipher\n");
  718. #endif
  719. if(((p[0] <<8) + p[1]) == 0x9E){
  720. #ifdef DEBUG_HS
  721. printf("USING DHE-RSA-AES128-GCM-SHA256\n");
  722. fflush(stdout);
  723. #endif
  724. f->keyex_alg = 1;
  725. f->cipher = EVP_aes_128_gcm();
  726. f->message_digest = EVP_sha256();
  727. } else if(((p[0] <<8) + p[1]) == 0x9F){
  728. #ifdef DEBUG_HS
  729. printf("USING DHE-RSA-AES256-GCM-SHA384\n");
  730. fflush(stdout);
  731. #endif
  732. f->keyex_alg = 1;
  733. f->cipher = EVP_aes_256_gcm();
  734. f->message_digest = EVP_sha384();
  735. } else if(((p[0] <<8) + p[1]) == 0xC02F){
  736. #ifdef DEBUG_HS
  737. printf("USING ECDHE-RSA-AES128-GCM-SHA256\n");
  738. fflush(stdout);
  739. #endif
  740. f->keyex_alg = 2;
  741. f->cipher = EVP_aes_128_gcm();
  742. f->message_digest = EVP_sha256();
  743. } else if(((p[0] <<8) + p[1]) == 0xC030){
  744. #ifdef DEBUG_HS
  745. printf("USING ECDHE-RSA-AES256-GCM-SHA384\n");
  746. fflush(stdout);
  747. #endif
  748. f->keyex_alg = 2;
  749. f->cipher = EVP_aes_256_gcm();
  750. f->message_digest = EVP_sha384();
  751. } else {
  752. printf("%x %x = %x\n", p[0], p[1], ((p[0] <<8) + p[1]));
  753. printf("Error: unsupported cipher\n");
  754. fflush(stdout);
  755. return 1;
  756. }
  757. return 0;
  758. }
  759. /** PRF using sha384, as defined in RFC 5246
  760. *
  761. * Inputs:
  762. * secret: the master secret used to sign the hash
  763. * secret_len: the length of the master secret
  764. * seed{1, ..., 4}: seed values that are virtually
  765. * concatenated
  766. * seed{1,...4}_len: length of the seeds
  767. * output: a pointer to the output of the PRF
  768. * output_len: the number of desired bytes
  769. *
  770. * Output:
  771. * 0 on success, 1 on failure
  772. */
  773. int PRF(flow *f, uint8_t *secret, int32_t secret_len,
  774. uint8_t *seed1, int32_t seed1_len,
  775. uint8_t *seed2, int32_t seed2_len,
  776. uint8_t *seed3, int32_t seed3_len,
  777. uint8_t *seed4, int32_t seed4_len,
  778. uint8_t *output, int32_t output_len){
  779. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  780. EVP_PKEY *mac_key;
  781. const EVP_MD *md;
  782. if(f == NULL){
  783. md = EVP_sha256();
  784. } else {
  785. md = f->message_digest;
  786. }
  787. uint8_t A[EVP_MAX_MD_SIZE];
  788. size_t len, A_len;
  789. int chunk = EVP_MD_size(md);
  790. int remaining = output_len;
  791. uint8_t *out = output;
  792. EVP_MD_CTX_init(&ctx);
  793. EVP_MD_CTX_init(&ctx_tmp);
  794. EVP_MD_CTX_init(&ctx_init);
  795. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  796. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
  797. /* Calculate first A value */
  798. EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key);
  799. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  800. if(seed1 != NULL && seed1_len > 0){
  801. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  802. }
  803. if(seed2 != NULL && seed2_len > 0){
  804. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  805. }
  806. if(seed3 != NULL && seed3_len > 0){
  807. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  808. }
  809. if(seed4 != NULL && seed4_len > 0){
  810. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  811. }
  812. EVP_DigestSignFinal(&ctx, A, &A_len);
  813. //iterate until desired length is achieved
  814. while(remaining > 0){
  815. /* Now compute SHA384(secret, A+seed) */
  816. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  817. EVP_DigestSignUpdate(&ctx, A, A_len);
  818. EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx);
  819. if(seed1 != NULL && seed1_len > 0){
  820. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  821. }
  822. if(seed2 != NULL && seed2_len > 0){
  823. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  824. }
  825. if(seed3 != NULL && seed3_len > 0){
  826. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  827. }
  828. if(seed4 != NULL && seed4_len > 0){
  829. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  830. }
  831. if(remaining > chunk){
  832. EVP_DigestSignFinal(&ctx, out, &len);
  833. out += len;
  834. remaining -= len;
  835. /* Next A value */
  836. EVP_DigestSignFinal(&ctx_tmp, A, &A_len);
  837. } else {
  838. EVP_DigestSignFinal(&ctx, A, &A_len);
  839. memcpy(out, A, remaining);
  840. remaining -= remaining;
  841. }
  842. }
  843. EVP_PKEY_free(mac_key);
  844. EVP_MD_CTX_cleanup(&ctx);
  845. EVP_MD_CTX_cleanup(&ctx_tmp);
  846. EVP_MD_CTX_cleanup(&ctx_init);
  847. OPENSSL_cleanse(A, sizeof(A));
  848. return 0;
  849. }
  850. /** After receiving change cipher spec, calculate keys from master secret
  851. *
  852. * Input:
  853. * f: the tagged flow
  854. *
  855. * Output:
  856. * 0 on success, 1 on failure
  857. */
  858. int init_ciphers(flow *f){
  859. EVP_CIPHER_CTX *r_ctx;
  860. EVP_CIPHER_CTX *w_ctx;
  861. EVP_CIPHER_CTX *w_ctx_srvr;
  862. EVP_CIPHER_CTX *r_ctx_srvr;
  863. const EVP_CIPHER *c = f->cipher;
  864. if(c == NULL){
  865. /*This *shouldn't* happen, but might if a serverHello msg isn't received
  866. * or if a session is resumed in a strange way */
  867. return 1;
  868. }
  869. /* Generate Keys */
  870. uint8_t *write_key, *write_iv;
  871. uint8_t *read_key, *read_iv;
  872. int32_t mac_len, key_len, iv_len;
  873. key_len = EVP_CIPHER_key_length(c);
  874. iv_len = EVP_CIPHER_iv_length(c); //EVP_GCM_TLS_FIXED_IV_LEN;
  875. mac_len = EVP_MD_size(f->message_digest);
  876. int32_t total_len = key_len + iv_len + mac_len;
  877. total_len *= 2;
  878. uint8_t *key_block = ecalloc(1, total_len);
  879. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  880. (uint8_t *) TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
  881. f->server_random, SSL3_RANDOM_SIZE,
  882. f->client_random, SSL3_RANDOM_SIZE,
  883. NULL, 0,
  884. key_block, total_len);
  885. #ifdef DEBUG
  886. printf("master secret: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  887. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  888. printf("%02x ", f->master_secret[i]);
  889. }
  890. printf("\n");
  891. printf("client random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  892. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  893. printf("%02x ", f->client_random[i]);
  894. }
  895. printf("\n");
  896. printf("server random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  897. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  898. printf("%02x ", f->server_random[i]);
  899. }
  900. printf("\n");
  901. printf("keyblock: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  902. for(int i=0; i< total_len; i++){
  903. printf("%02x ", key_block[i]);
  904. }
  905. printf("\n");
  906. #endif
  907. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  908. write_key = key_block;
  909. read_key = key_block + key_len;
  910. write_iv = key_block + 2*key_len;
  911. read_iv = key_block + 2*key_len + iv_len;
  912. /* Initialize Cipher Contexts */
  913. r_ctx = EVP_CIPHER_CTX_new();
  914. w_ctx = EVP_CIPHER_CTX_new();
  915. EVP_CIPHER_CTX_init(r_ctx);
  916. EVP_CIPHER_CTX_init(w_ctx);
  917. w_ctx_srvr = EVP_CIPHER_CTX_new();
  918. r_ctx_srvr = EVP_CIPHER_CTX_new();
  919. EVP_CIPHER_CTX_init(w_ctx_srvr);
  920. EVP_CIPHER_CTX_init(r_ctx_srvr);
  921. /* Initialize MACs --- not needed for aes_256_gcm
  922. write_mac = key_block + 2*key_len + 2*iv_len;
  923. read_mac = key_block + 2*key_len + 2*iv_len + mac_len;
  924. read_mac_ctx = EVP_MD_CTX_create();
  925. write_mac_ctx = EVP_MD_CTX_create();
  926. read_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, read_mac, mac_len);
  927. write_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, write_mac, mac_len);
  928. EVP_DigestSignInit(read_mac_ctx, NULL, EVP_sha384(), NULL, read_mac_key);
  929. EVP_DigestSignInit(write_mac_ctx, NULL, EVP_sha384(), NULL, write_mac_key);
  930. EVP_PKEY_free(read_mac_key);
  931. EVP_PKEY_free(write_mac_key);*/
  932. #ifdef DEBUG
  933. {
  934. int i;
  935. fprintf(stderr, "EVP_CipherInit_ex(r_ctx,c,key=,iv=,which)\n");
  936. fprintf(stderr, "\tkey= ");
  937. for (i = 0; i < c->key_len; i++)
  938. fprintf(stderr, "%02x", read_key[i]);
  939. fprintf(stderr, "\n");
  940. fprintf(stderr, "\t iv= ");
  941. for (i = 0; i < c->iv_len; i++)
  942. fprintf(stderr, "%02x", read_iv[i]);
  943. fprintf(stderr, "\n");
  944. }
  945. {
  946. int i;
  947. fprintf(stderr, "EVP_CipherInit_ex(w_ctx,c,key=,iv=,which)\n");
  948. fprintf(stderr, "\tkey= ");
  949. for (i = 0; i < c->key_len; i++)
  950. fprintf(stderr, "%02x", write_key[i]);
  951. fprintf(stderr, "\n");
  952. fprintf(stderr, "\t iv= ");
  953. for (i = 0; i < c->iv_len; i++)
  954. fprintf(stderr, "%02x", write_iv[i]);
  955. fprintf(stderr, "\n");
  956. }
  957. #endif
  958. if(!EVP_CipherInit_ex(r_ctx, c, NULL, read_key, NULL, 0)){
  959. printf("FAIL r_ctx\n");
  960. }
  961. if(!EVP_CipherInit_ex(w_ctx, c, NULL, write_key, NULL, 1)){
  962. printf("FAIL w_ctx\n");
  963. }
  964. if(!EVP_CipherInit_ex(w_ctx_srvr, c, NULL, read_key, NULL, 1)){
  965. printf("FAIL w_ctx_srvr\n");
  966. }
  967. if(!EVP_CipherInit_ex(r_ctx_srvr, c, NULL, write_key, NULL, 0)){
  968. printf("FAIL r_ctx_srvr\n");
  969. }
  970. EVP_CIPHER_CTX_ctrl(r_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  971. EVP_CIPHER_CTX_ctrl(w_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  972. EVP_CIPHER_CTX_ctrl(w_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  973. EVP_CIPHER_CTX_ctrl(r_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  974. f->clnt_read_ctx = r_ctx;
  975. f->clnt_write_ctx = w_ctx;
  976. f->srvr_read_ctx = r_ctx_srvr;
  977. f->srvr_write_ctx = w_ctx_srvr;
  978. free(key_block);
  979. return 0;
  980. }
  981. // To avoid warnings about MAC paddings, use this to update contexts
  982. void update_context(flow *f, uint8_t *input, int32_t len, int32_t incoming, int32_t type, int32_t enc){
  983. uint8_t *output = ecalloc(1, len+16+8);
  984. memcpy(output + EVP_GCM_TLS_EXPLICIT_IV_LEN, input, len);
  985. //If the original message was a decryption, this will be an necryption.
  986. //Incoming field stays the same
  987. encrypt(f, output, output, len+8, incoming, type, !enc);
  988. //revert the sequence number
  989. uint8_t *seq = incoming ? f->read_seq : f->write_seq;
  990. for(int i=7; i>=0; i--){
  991. --seq[i];
  992. if(seq[i] >= 0)
  993. break;
  994. else
  995. seq[i] = 0;
  996. }
  997. free(output);
  998. }
  999. /* Generate the keys for a client's super encryption layer
  1000. *
  1001. * The header of each downstream slitheen data chunk is 16 bytes and encrypted with
  1002. * a 256 bit AES key
  1003. *
  1004. * The body of each downstream chunk is CBC encrypted with a 256 bit AES key
  1005. *
  1006. * The last 16 bytes of the body is a MAC over the body
  1007. *
  1008. */
  1009. void generate_client_super_keys(uint8_t *secret, client *c){
  1010. EVP_MD_CTX *mac_ctx;
  1011. const EVP_MD *md = EVP_sha256();
  1012. FILE *fp;
  1013. //extract shared secret from SLITHEEN_ID
  1014. uint8_t shared_secret[16];
  1015. byte privkey[PTWIST_BYTES];
  1016. fp = fopen("privkey", "rb");
  1017. if (fp == NULL) {
  1018. perror("fopen");
  1019. exit(1);
  1020. }
  1021. if(fread(privkey, PTWIST_BYTES, 1, fp) < 1){
  1022. perror("fread");
  1023. exit(1);
  1024. }
  1025. fclose(fp);
  1026. /* check tag*/
  1027. if(check_tag(shared_secret, privkey, secret, (const byte *)"context", 7)){
  1028. //something went wrong O.o
  1029. printf("Error extracting secret from tag\n");
  1030. return;
  1031. }
  1032. #ifdef DEBUG
  1033. printf("Shared secret: ");
  1034. for(int i=0; i< 16; i++){
  1035. printf("%02x ", shared_secret[i]);
  1036. }
  1037. printf("\n");
  1038. #endif
  1039. /* Generate Keys */
  1040. uint8_t *hdr_key, *bdy_key;
  1041. uint8_t *mac_secret;
  1042. EVP_PKEY *mac_key;
  1043. int32_t mac_len, key_len;
  1044. key_len = EVP_CIPHER_key_length(EVP_aes_256_cbc());
  1045. mac_len = EVP_MD_size(md);
  1046. int32_t total_len = 2*key_len + mac_len;
  1047. uint8_t *key_block = ecalloc(1, total_len);
  1048. PRF(NULL, shared_secret, SLITHEEN_SUPER_SECRET_SIZE,
  1049. (uint8_t *) SLITHEEN_SUPER_CONST, SLITHEEN_SUPER_CONST_SIZE,
  1050. NULL, 0,
  1051. NULL, 0,
  1052. NULL, 0,
  1053. key_block, total_len);
  1054. #ifdef DEBUG
  1055. printf("slitheend id: \n");
  1056. for(int i=0; i< SLITHEEN_ID_LEN; i++){
  1057. printf("%02x ", secret[i]);
  1058. }
  1059. printf("\n");
  1060. printf("keyblock: \n");
  1061. for(int i=0; i< total_len; i++){
  1062. printf("%02x ", key_block[i]);
  1063. }
  1064. printf("\n");
  1065. #endif
  1066. hdr_key = key_block;
  1067. bdy_key = key_block + key_len;
  1068. mac_secret = key_block + 2*key_len;
  1069. /* Initialize MAC Context */
  1070. mac_ctx = EVP_MD_CTX_create();
  1071. EVP_DigestInit_ex(mac_ctx, md, NULL);
  1072. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, mac_secret, mac_len);
  1073. EVP_DigestSignInit(mac_ctx, NULL, md, NULL, mac_key);
  1074. c->header_key = emalloc(key_len);
  1075. c->body_key = emalloc(key_len);
  1076. memcpy(c->header_key, hdr_key, key_len);
  1077. memcpy(c->body_key, bdy_key, key_len);
  1078. c->mac_ctx = mac_ctx;
  1079. //Free everything
  1080. free(key_block);
  1081. EVP_PKEY_free(mac_key);
  1082. return;
  1083. }
  1084. int super_encrypt(client *c, uint8_t *data, uint32_t len){
  1085. int retval = 1;
  1086. EVP_CIPHER_CTX *hdr_ctx = NULL;
  1087. EVP_CIPHER_CTX *bdy_ctx = NULL;
  1088. int32_t out_len;
  1089. size_t mac_len;
  1090. uint8_t *p = data;
  1091. uint8_t output[EVP_MAX_MD_SIZE];
  1092. //first encrypt the header
  1093. #ifdef DEBUG
  1094. printf("Plaintext Header:\n");
  1095. for(int i=0; i< SLITHEEN_HEADER_LEN; i++){
  1096. printf("%02x ", p[i]);
  1097. }
  1098. printf("\n");
  1099. #endif
  1100. hdr_ctx = EVP_CIPHER_CTX_new();
  1101. EVP_CipherInit_ex(hdr_ctx, EVP_aes_256_cbc(), NULL, c->header_key, NULL, 1);
  1102. if(!EVP_CipherUpdate(hdr_ctx, p, &out_len, p, SLITHEEN_HEADER_LEN)){
  1103. printf("Failed!\n");
  1104. retval = 0;
  1105. goto end;
  1106. }
  1107. #ifdef DEBUG
  1108. printf("Encrypted Header (%d bytes)\n", out_len);
  1109. for(int i=0; i< out_len; i++){
  1110. printf("%02x ", p[i]);
  1111. }
  1112. printf("\n");
  1113. #endif
  1114. if(len == 0){ //only encrypt header: body contains garbage bytes
  1115. retval = 1;
  1116. goto end;
  1117. }
  1118. //encrypt the body
  1119. p += SLITHEEN_HEADER_LEN;
  1120. //generate IV
  1121. RAND_bytes(p, 16);
  1122. //set up cipher ctx
  1123. bdy_ctx = EVP_CIPHER_CTX_new();
  1124. EVP_CipherInit_ex(bdy_ctx, EVP_aes_256_cbc(), NULL, c->body_key, p, 1);
  1125. p+= 16;
  1126. #ifdef DEBUG
  1127. printf("Plaintext:\n");
  1128. for(int i=0; i< len; i++){
  1129. printf("%02x ", p[i]);
  1130. }
  1131. printf("\n");
  1132. #endif
  1133. if(!EVP_CipherUpdate(bdy_ctx, p, &out_len, p, len)){
  1134. printf("Failed!\n");
  1135. goto end;
  1136. retval = 0;
  1137. }
  1138. #ifdef DEBUG
  1139. printf("Encrypted %d bytes\n", out_len);
  1140. printf("Encrypted data:\n");
  1141. for(int i=0; i< out_len; i++){
  1142. printf("%02x ", p[i]);
  1143. }
  1144. printf("\n");
  1145. #endif
  1146. //MAC at the end
  1147. EVP_MD_CTX mac_ctx;
  1148. EVP_MD_CTX_init(&mac_ctx);
  1149. EVP_MD_CTX_copy_ex(&mac_ctx, c->mac_ctx);
  1150. EVP_DigestSignUpdate(&mac_ctx, p, out_len);
  1151. EVP_DigestSignFinal(&mac_ctx, output, &mac_len);
  1152. EVP_MD_CTX_cleanup(&mac_ctx);
  1153. p += out_len;
  1154. memcpy(p, output, 16);
  1155. #ifdef DEBUG_PARSE
  1156. printf("Computed mac:\n");
  1157. for(int i=0; i< 16; i++){
  1158. printf("%02x ", output[i]);
  1159. }
  1160. printf("\n");
  1161. fflush(stdout);
  1162. #endif
  1163. end:
  1164. if(hdr_ctx != NULL){
  1165. EVP_CIPHER_CTX_cleanup(hdr_ctx);
  1166. OPENSSL_free(hdr_ctx);
  1167. }
  1168. if(bdy_ctx != NULL){
  1169. EVP_CIPHER_CTX_cleanup(bdy_ctx);
  1170. OPENSSL_free(bdy_ctx);
  1171. }
  1172. return retval;
  1173. }
  1174. /** Checks a handshake message to see if it is tagged or a
  1175. * recognized flow. If the client random nonce is tagged,
  1176. * adds the flow to the flow table to be tracked.
  1177. *
  1178. * Inputs:
  1179. * info: the processed packet
  1180. * f: the tagged flow
  1181. *
  1182. * Output:
  1183. * none
  1184. */
  1185. void check_handshake(struct packet_info *info){
  1186. FILE *fp;
  1187. int res, code;
  1188. uint8_t *hello_rand;
  1189. const struct handshake_header *handshake_hdr;
  1190. byte privkey[PTWIST_BYTES];
  1191. byte key[16];
  1192. uint8_t *p = info->app_data + RECORD_HEADER_LEN;
  1193. handshake_hdr = (struct handshake_header*) p;
  1194. code = handshake_hdr->type;
  1195. if (code == 0x01){
  1196. p += CLIENT_HELLO_HEADER_LEN;
  1197. //now pointing to hello random :D
  1198. hello_rand = p;
  1199. p += 4; //skipping time bytes
  1200. /* Load the private key */
  1201. fp = fopen("privkey", "rb");
  1202. if (fp == NULL) {
  1203. perror("fopen");
  1204. exit(1);
  1205. }
  1206. res = fread(privkey, PTWIST_BYTES, 1, fp);
  1207. if (res < 1) {
  1208. perror("fread");
  1209. exit(1);
  1210. }
  1211. fclose(fp);
  1212. /* check tag*/
  1213. res = check_tag(key, privkey, p, (const byte *)"context", 7);
  1214. if (!res) {
  1215. #ifdef DEBUG
  1216. printf("Received tagged flow! (key =");
  1217. for(i=0; i<16;i++){
  1218. printf(" %02x", key[i]);
  1219. }
  1220. printf(")\n");
  1221. #endif
  1222. /* Save flow in table */
  1223. flow *flow_ptr = add_flow(info);
  1224. if(flow_ptr == NULL){
  1225. fprintf(stderr, "Memory failure\n");
  1226. return;
  1227. }
  1228. for(int i=0; i<16; i++){
  1229. flow_ptr->key[i] = key[i];
  1230. }
  1231. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  1232. #ifdef DEBUG
  1233. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  1234. printf("%02x ", hello_rand[i]);
  1235. }
  1236. printf("\n");
  1237. printf("Saved new flow\n");
  1238. #endif
  1239. }
  1240. }
  1241. }
  1242. /* Check the given tag with the given context and private key. Return 0
  1243. if the tag is properly formed, non-0 if not. If the tag is correct,
  1244. set key to the resulting secret key. */
  1245. int check_tag(byte key[16], const byte privkey[PTWIST_BYTES],
  1246. const byte tag[PTWIST_TAG_BYTES], const byte *context,
  1247. size_t context_len)
  1248. {
  1249. int ret = -1;
  1250. byte sharedsec[PTWIST_BYTES+context_len];
  1251. byte taghashout[32];
  1252. #if PTWIST_PUZZLE_STRENGTH > 0
  1253. byte hashout[32];
  1254. size_t puzzle_len = 16+PTWIST_RESP_BYTES;
  1255. byte value_to_hash[puzzle_len];
  1256. unsigned int firstbits;
  1257. int firstpass = 0;
  1258. #endif
  1259. /* Compute the shared secret privkey*TAG */
  1260. ptwist_pointmul(sharedsec, tag, privkey);
  1261. /* Create the hash tag keys */
  1262. memmove(sharedsec+PTWIST_BYTES, context, context_len);
  1263. SHA256(sharedsec, PTWIST_BYTES, taghashout);
  1264. #if PTWIST_PUZZLE_STRENGTH > 0
  1265. /* Construct the proposed solution to the puzzle */
  1266. memmove(value_to_hash, taghashout, 16);
  1267. memmove(value_to_hash+16, tag+PTWIST_BYTES, PTWIST_RESP_BYTES);
  1268. value_to_hash[16+PTWIST_RESP_BYTES-1] &= PTWIST_RESP_MASK;
  1269. /* Hash the proposed solution and see if it is correct; that is, the
  1270. * hash should start with PTWIST_PUZZLE_STRENGTH bits of 0s,
  1271. * followed by the last PTWIST_HASH_SHOWBITS of the tag. */
  1272. md_map_sh256(hashout, value_to_hash, puzzle_len);
  1273. #if PTWIST_PUZZLE_STRENGTH < 32
  1274. /* This assumes that you're on an architecture that doesn't care
  1275. * about alignment, and is little endian. */
  1276. firstbits = *(unsigned int*)hashout;
  1277. if ((firstbits & PTWIST_PUZZLE_MASK) == 0) {
  1278. firstpass = 1;
  1279. }
  1280. #else
  1281. #error "Code assumes PTWIST_PUZZLE_STRENGTH < 32"
  1282. #endif
  1283. if (firstpass) {
  1284. bn_t Hbn, Tbn;
  1285. bn_new(Hbn);
  1286. bn_new(Tbn);
  1287. hashout[PTWIST_HASH_TOTBYTES-1] &= PTWIST_HASH_MASK;
  1288. bn_read_bin(Hbn, hashout, PTWIST_HASH_TOTBYTES, BN_POS);
  1289. bn_rsh(Hbn, Hbn, PTWIST_PUZZLE_STRENGTH);
  1290. bn_read_bin(Tbn, tag+PTWIST_BYTES, PTWIST_TAG_BYTES-PTWIST_BYTES,
  1291. BN_POS);
  1292. bn_rsh(Tbn, Tbn, PTWIST_RESP_BITS);
  1293. ret = (bn_cmp(Tbn,Hbn) != CMP_EQ);
  1294. bn_free(Hbn);
  1295. bn_free(Tbn);
  1296. }
  1297. #else
  1298. /* We're not using a client puzzle, so just check that the first
  1299. * PTWIST_HASH_SHOWBITS bits of the above hash fill out the rest
  1300. * of the tag. If there's no puzzle, PTWIST_HASH_SHOWBITS must be
  1301. * a multiple of 8. */
  1302. ret = (memcmp(tag+PTWIST_BYTES, taghashout, PTWIST_HASH_SHOWBITS/8) != 0);
  1303. #endif
  1304. if (ret == 0) {
  1305. memmove(key, taghashout+16, 16);
  1306. }
  1307. return ret;
  1308. }