crypto.c 40 KB

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