crypto.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  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. /** Extracts the server parameters from the server key
  203. * exchange message
  204. *
  205. * Inputs:
  206. * f: the tagged flow
  207. * hs: the beginning of the server key exchange
  208. * handshake message
  209. *
  210. * Output:
  211. * 0 on success, 1 on failure
  212. */
  213. int extract_parameters(flow *f, uint8_t *hs){
  214. uint8_t *p;
  215. long i;
  216. int ok=1;
  217. p = hs + HANDSHAKE_HEADER_LEN;
  218. if(f->keyex_alg == 1){
  219. DH *dh;
  220. if((dh = DH_new()) == NULL){
  221. return 1;
  222. }
  223. /* Extract prime modulus */
  224. n2s(p,i);
  225. if(!(dh->p = BN_bin2bn(p,i,NULL))){
  226. return 1;
  227. }
  228. p += i;
  229. /* Extract generator */
  230. n2s(p,i);
  231. if(!(dh->g = BN_bin2bn(p,i,NULL))){
  232. return 1;
  233. }
  234. p += i;
  235. /* Extract server public value */
  236. n2s(p,i);
  237. if(!(dh->pub_key = BN_bin2bn(p,i,NULL))){
  238. return 1;
  239. }
  240. f->dh = dh;
  241. } else if (f->keyex_alg == 2){
  242. EC_KEY *ecdh;
  243. EC_GROUP *ngroup;
  244. const EC_GROUP *group;
  245. BN_CTX *bn_ctx = NULL;
  246. EC_POINT *srvr_ecpoint = NULL;
  247. int curve_nid = 0;
  248. int encoded_pt_len = 0;
  249. if((ecdh = EC_KEY_new()) == NULL) {
  250. SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
  251. goto err;
  252. }
  253. if(p[0] != 0x03){//not a named curve
  254. goto err;
  255. }
  256. //int curve_id = (p[1] << 8) + p[2];
  257. int curve_id = *(p+2);
  258. if((curve_id < 0) || ((unsigned int)curve_id >
  259. sizeof(nid_list) / sizeof(nid_list[0]))){
  260. goto err;
  261. }
  262. curve_nid = nid_list[curve_id-1];
  263. /* Extract curve
  264. if(!tls1_check_curve(s, p, 3)) {
  265. goto err;
  266. }
  267. if((*(p+2) < 1) || ((unsigned int) (*(p+2)) > sizeof(nid_list) / sizeof(nid_list[0]))){
  268. goto err;
  269. }
  270. curve_nid = nid_list[*(p+2)];
  271. */
  272. ngroup = EC_GROUP_new_by_curve_name(curve_nid);
  273. if(ngroup == NULL){
  274. goto err;
  275. }
  276. if(EC_KEY_set_group(ecdh, ngroup) == 0){
  277. goto err;
  278. }
  279. EC_GROUP_free(ngroup);
  280. group = EC_KEY_get0_group(ecdh);
  281. p += 3;
  282. /* Get EC point */
  283. if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
  284. ((bn_ctx = BN_CTX_new()) == NULL)) {
  285. goto err;
  286. }
  287. encoded_pt_len = *p;
  288. p += 1;
  289. if(EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len,
  290. bn_ctx) == 0){
  291. goto err;
  292. }
  293. p += encoded_pt_len;
  294. EC_KEY_set_public_key(ecdh, srvr_ecpoint);
  295. f->ecdh = ecdh;
  296. ecdh = NULL;
  297. BN_CTX_free(bn_ctx);
  298. bn_ctx = NULL;
  299. EC_POINT_free(srvr_ecpoint);
  300. srvr_ecpoint = NULL;
  301. ok=0;
  302. err:
  303. if(bn_ctx != NULL){
  304. BN_CTX_free(bn_ctx);
  305. }
  306. if(srvr_ecpoint != NULL){
  307. EC_POINT_free(srvr_ecpoint);
  308. }
  309. if(ecdh != NULL){
  310. EC_KEY_free(ecdh);
  311. }
  312. }
  313. return ok;
  314. }
  315. /* Encrypt/Decrypt a TLS record
  316. *
  317. * Inputs:
  318. * f: the tagged flow
  319. * input: a pointer to the data that is to be encrypted/
  320. * decrypted
  321. * output: a pointer to where the data should be written
  322. * after it is encrypted or decrypted
  323. * len: the length of the data
  324. * incoming: the direction of the record
  325. * type: the type of the TLS record
  326. * enc: 1 for encryption, 0 for decryption
  327. * re: 1 if this is a re-encryption (counters are reset), 0 otherwise
  328. * Note: is only checked during encryption
  329. *
  330. * Output:
  331. * length of the output data
  332. */
  333. 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){
  334. uint8_t *p = input;
  335. EVP_CIPHER_CTX *ds = (incoming) ? ((enc) ? f->srvr_write_ctx : f->clnt_read_ctx) : ((enc) ? f->clnt_write_ctx : f->srvr_read_ctx);
  336. if(ds == NULL){
  337. printf("FAIL\n");
  338. return 1;
  339. }
  340. uint8_t *seq;
  341. seq = (incoming) ? f->read_seq : f->write_seq;
  342. if(enc && re){
  343. for(int i=7; i>=0; i--){
  344. --seq[i];
  345. if(seq[i] != 0xff)
  346. break;
  347. }
  348. }
  349. if(f->application && (ds->iv[EVP_GCM_TLS_FIXED_IV_LEN] == 0)){
  350. //fill in rest of iv
  351. for(int i = EVP_GCM_TLS_FIXED_IV_LEN; i< ds->cipher->iv_len; i++){
  352. ds->iv[i] = p[i- EVP_GCM_TLS_FIXED_IV_LEN];
  353. }
  354. }
  355. #ifdef DEBUG
  356. printf("\t\tiv: ");
  357. for(int i=0; i<ds->cipher->iv_len; i++){
  358. printf("%02X ", ds->iv[i]);
  359. }
  360. printf("\n");
  361. #endif
  362. uint8_t buf[13];
  363. memcpy(buf, seq, 8);
  364. for(int i=7; i>=0; i--){
  365. ++seq[i];
  366. if(seq[i] != 0)
  367. break;
  368. }
  369. buf[8] = type;
  370. buf[9] = 0x03;
  371. buf[10] = 0x03;
  372. buf[11] = len >> 8; //len >> 8;
  373. buf[12] = len & 0xff;//len *0xff;
  374. int32_t pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
  375. 13, buf); // = int32_t pad?
  376. if(enc)
  377. len += pad;
  378. int32_t n = EVP_Cipher(ds, p, p, len); //decrypt in place
  379. if(n<0) return 0;
  380. #ifdef DEBUG
  381. printf("decrypted data:\n");
  382. for(int i=0; i< len; i++){
  383. printf("%02x ", p[EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  384. }
  385. printf("\n");
  386. #endif
  387. if(!enc)
  388. p[EVP_GCM_TLS_EXPLICIT_IV_LEN+n] = '\0';
  389. return n;
  390. }
  391. /** Increases the GCM counter when we don't decrypt a record to produce the correct tag in the next
  392. * re-encrypted record
  393. *
  394. * Inputs:
  395. * f: the tagged flow
  396. * incoming: the direction of the flow
  397. *
  398. * Output:
  399. * 0 on success, 1 on failure
  400. */
  401. int fake_encrypt(flow *f, int32_t incoming){
  402. uint8_t *seq = (incoming) ? f->read_seq : f->write_seq;
  403. for(int i=7; i>=0; i--){
  404. ++seq[i];
  405. if(seq[i] != 0)
  406. break;
  407. }
  408. return 0;
  409. }
  410. /** Mark the hash in a downstream TLS finished message
  411. *
  412. * Changes the finished hash to
  413. * SHA256_HMAC_96(shared_key, "SLITHEEN_FINISHED" || old_finished_hash)
  414. *
  415. * This feature detects and prevents suspicious behaviour in the event
  416. * of a MiTM or RAD attack.
  417. *
  418. * Inputs:
  419. * f: the tagged flow
  420. * hs: a pointer to the TLS Finished handshake message
  421. *
  422. * Output:
  423. * 0 on success, 1 on failure
  424. * if success, the message pointed to by hs will have
  425. * been updated
  426. */
  427. int mark_finished_hash(flow *f, uint8_t *hs){
  428. HMAC_CTX ctx;
  429. uint8_t hmac_output[EVP_MAX_MD_SIZE];
  430. unsigned int hmac_output_len;
  431. // Ensure this is a Finished message, of length 12 bytes
  432. if (memcmp(hs, "\x14\x00\x00\x0c", 4)) {
  433. return 1;
  434. }
  435. HMAC_CTX_init(&ctx);
  436. HMAC_Init_ex(&ctx, f->key, 16, EVP_sha256(), NULL);
  437. HMAC_Update(&ctx, (const unsigned char *)SLITHEEN_FINISHED_INPUT_CONST, SLITHEEN_FINISHED_INPUT_CONST_SIZE);
  438. HMAC_Update(&ctx, hs+4, 12);
  439. HMAC_Final(&ctx, hmac_output, &hmac_output_len);
  440. HMAC_CTX_cleanup(&ctx);
  441. if (hmac_output_len != 32) {
  442. return 1;
  443. }
  444. memmove(hs+4, hmac_output, 12);
  445. return 0;
  446. }
  447. /** Computes the TLS master secret from the decoy server's
  448. * public key parameters and the leaked secret from the
  449. * extracted Slitheen tag
  450. *
  451. * Input:
  452. * f: the tagged flow
  453. *
  454. * Output:
  455. * 0 on success, 1 on failure
  456. */
  457. int compute_master_secret(flow *f){
  458. #ifdef DEBUG_HS
  459. 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);
  460. #endif
  461. DH *dh_srvr = NULL;
  462. DH *dh_clnt = NULL;
  463. BN_CTX *ctx = NULL;
  464. BIGNUM *pub_key = NULL, *priv_key = NULL, *order = NULL;
  465. EC_KEY *clnt_ecdh = NULL;
  466. EC_POINT *e_pub_key = NULL;
  467. int ok =1;
  468. uint8_t *pre_master_secret = ecalloc(1, PRE_MASTER_MAX_LEN);
  469. int32_t pre_master_len;
  470. uint32_t l;
  471. int32_t bytes;
  472. uint8_t *buf = NULL;
  473. if(f->keyex_alg == 1){
  474. BN_MONT_CTX *mont = NULL;
  475. ctx = BN_CTX_new();
  476. dh_srvr = f->dh;
  477. dh_clnt = DHparams_dup(dh_srvr);
  478. l = dh_clnt->length ? dh_clnt->length : BN_num_bits(dh_clnt->p) - 1;
  479. bytes = (l+7) / 8;
  480. buf = (uint8_t *)OPENSSL_malloc(bytes);
  481. if (buf == NULL){
  482. BNerr(BN_F_BNRAND, ERR_R_MALLOC_FAILURE);
  483. goto err;
  484. }
  485. pub_key = BN_new();
  486. priv_key = BN_new();
  487. #ifdef DEBUG
  488. printf("key =");
  489. for(int i=0; i< 16; i++)
  490. printf(" %02x", f->key[i]);
  491. printf("\n");
  492. #endif
  493. PRF(f, f->key, 16,
  494. (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  495. NULL, 0, NULL, 0, NULL, 0,
  496. buf, bytes);
  497. #ifdef DEBUG_HS
  498. printf("Generated the client private key [len: %d]: ", bytes);
  499. for(int i=0; i< bytes; i++){
  500. printf(" %02x ", buf[i]);
  501. }
  502. printf("\n");
  503. #endif
  504. if (!BN_bin2bn(buf, bytes, priv_key))
  505. goto err;
  506. {
  507. BIGNUM *prk;
  508. prk = priv_key;
  509. if (!dh_clnt->meth->bn_mod_exp(dh_clnt, pub_key, dh_clnt->g, prk, dh_clnt->p, ctx, mont)){
  510. goto err;
  511. }
  512. }
  513. dh_clnt->pub_key = pub_key;
  514. dh_clnt->priv_key = priv_key;
  515. pre_master_len = DH_compute_key(pre_master_secret, dh_srvr->pub_key, dh_clnt);
  516. } else if(f->keyex_alg == 2){
  517. const EC_GROUP *srvr_group = NULL;
  518. const EC_POINT *srvr_ecpoint = NULL;
  519. EC_KEY *tkey;
  520. tkey = f->ecdh;
  521. if(tkey == NULL){
  522. return 1;
  523. }
  524. srvr_group = EC_KEY_get0_group(tkey);
  525. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  526. if((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
  527. return 1;
  528. }
  529. if((clnt_ecdh = EC_KEY_new()) == NULL) {
  530. goto err;
  531. }
  532. if(!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  533. goto err;
  534. }
  535. /* Now generate key from tag */
  536. if((order = BN_new()) == NULL){
  537. goto err;
  538. }
  539. if((ctx = BN_CTX_new()) == NULL){
  540. goto err;
  541. }
  542. if((priv_key = BN_new()) == NULL){
  543. goto err;
  544. }
  545. if(!EC_GROUP_get_order(srvr_group, order, ctx)){
  546. goto err;
  547. }
  548. l = BN_num_bits(order)-1;
  549. bytes = (l+7)/8;
  550. buf = (unsigned char *)OPENSSL_malloc(bytes);
  551. if(buf == NULL){
  552. goto err;
  553. }
  554. PRF(f, f->key, 16, (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  555. NULL, 0, NULL, 0, NULL, 0, buf, bytes);
  556. #ifdef DEBUG
  557. printf("Generated the following rand bytes: ");
  558. for(int i=0; i< bytes; i++){
  559. printf("%02x ", buf[i]);
  560. }
  561. printf("\n");
  562. #endif
  563. if(!BN_bin2bn(buf, bytes, priv_key)){
  564. goto err;
  565. }
  566. if((e_pub_key = EC_POINT_new(srvr_group)) == NULL){
  567. goto err;
  568. }
  569. if(!EC_POINT_mul(EC_KEY_get0_group(clnt_ecdh), e_pub_key, priv_key, NULL, NULL, ctx)){
  570. goto err;
  571. }
  572. EC_KEY_set_private_key(clnt_ecdh, priv_key);
  573. EC_KEY_set_public_key(clnt_ecdh, e_pub_key);
  574. /*Compute the master secret */
  575. int32_t field_size = EC_GROUP_get_degree(srvr_group);
  576. if(field_size <= 0){
  577. goto err;
  578. }
  579. pre_master_len = ECDH_compute_key(pre_master_secret, (field_size + 7) / 8,
  580. srvr_ecpoint, clnt_ecdh, NULL);
  581. if(pre_master_len <= 0) {
  582. goto err;
  583. }
  584. }
  585. /*Generate master secret */
  586. 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);
  587. if(f->current_session != NULL){
  588. memcpy(f->current_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  589. }
  590. #ifdef DEBUG
  591. fprintf(stdout, "Premaster Secret:\n");
  592. BIO_dump_fp(stdout, (char *)pre_master_secret, pre_master_len);
  593. fprintf(stdout, "Client Random:\n");
  594. BIO_dump_fp(stdout, (char *)f->client_random, SSL3_RANDOM_SIZE);
  595. fprintf(stdout, "Server Random:\n");
  596. BIO_dump_fp(stdout, (char *)f->server_random, SSL3_RANDOM_SIZE);
  597. fprintf(stdout, "Master Secret:\n");
  598. BIO_dump_fp(stdout, (char *)f->master_secret, SSL3_MASTER_SECRET_SIZE);
  599. #endif
  600. //remove pre_master_secret from memory
  601. memset(pre_master_secret, 0, PRE_MASTER_MAX_LEN);
  602. ok = 0;
  603. err:
  604. if((pub_key != NULL) && (dh_srvr == NULL)){
  605. BN_free(pub_key);
  606. }
  607. if((priv_key != NULL) && ((dh_clnt == NULL) || (EC_KEY_get0_private_key(clnt_ecdh) == NULL))){
  608. BN_free(priv_key);
  609. }
  610. if(ctx != NULL){
  611. BN_CTX_free(ctx);
  612. }
  613. OPENSSL_free(buf);
  614. free(pre_master_secret);
  615. if(dh_srvr != NULL){
  616. DH_free(dh_srvr);
  617. f->dh = NULL;
  618. }
  619. if(dh_clnt != NULL) {
  620. DH_free(dh_clnt);
  621. }
  622. if(order){
  623. BN_free(order);
  624. }
  625. if(clnt_ecdh != NULL){
  626. EC_KEY_free(clnt_ecdh);
  627. }
  628. if(e_pub_key != NULL){
  629. EC_POINT_free(e_pub_key);
  630. }
  631. return ok;
  632. }
  633. /** Saves the random none from the server hello message
  634. *
  635. * Inputs:
  636. * f: the tagged flow
  637. * hs: a pointer to the beginning of the server hello msg
  638. *
  639. * Output:
  640. * 0 on success, 1 on failure
  641. */
  642. int extract_server_random(flow *f, uint8_t *hs){
  643. uint8_t *p;
  644. p = hs + HANDSHAKE_HEADER_LEN;
  645. p+=2; //skip version
  646. memcpy(f->server_random, p, SSL3_RANDOM_SIZE);
  647. p += SSL3_RANDOM_SIZE;
  648. //skip session id
  649. uint8_t id_len = (uint8_t) p[0];
  650. p ++;
  651. p += id_len;
  652. //now extract ciphersuite
  653. #ifdef DEBUG_HS
  654. printf("Checking cipher\n");
  655. #endif
  656. if(((p[0] <<8) + p[1]) == 0x9E){
  657. #ifdef DEBUG_HS
  658. printf("USING DHE-RSA-AES128-GCM-SHA256\n");
  659. fflush(stdout);
  660. #endif
  661. f->keyex_alg = 1;
  662. f->cipher = EVP_aes_128_gcm();
  663. f->message_digest = EVP_sha256();
  664. } else if(((p[0] <<8) + p[1]) == 0x9F){
  665. #ifdef DEBUG_HS
  666. printf("USING DHE-RSA-AES256-GCM-SHA384\n");
  667. fflush(stdout);
  668. #endif
  669. f->keyex_alg = 1;
  670. f->cipher = EVP_aes_256_gcm();
  671. f->message_digest = EVP_sha384();
  672. } else if(((p[0] <<8) + p[1]) == 0xC02F){
  673. #ifdef DEBUG_HS
  674. printf("USING ECDHE-RSA-AES128-GCM-SHA256\n");
  675. fflush(stdout);
  676. #endif
  677. f->keyex_alg = 2;
  678. f->cipher = EVP_aes_128_gcm();
  679. f->message_digest = EVP_sha256();
  680. } else if(((p[0] <<8) + p[1]) == 0xC030){
  681. #ifdef DEBUG_HS
  682. printf("USING ECDHE-RSA-AES256-GCM-SHA384\n");
  683. fflush(stdout);
  684. #endif
  685. f->keyex_alg = 2;
  686. f->cipher = EVP_aes_256_gcm();
  687. f->message_digest = EVP_sha384();
  688. } else {
  689. printf("%x %x = %x\n", p[0], p[1], ((p[0] <<8) + p[1]));
  690. printf("Error: unsupported cipher\n");
  691. fflush(stdout);
  692. return 1;
  693. }
  694. return 0;
  695. }
  696. /** PRF using sha384, as defined in RFC 5246
  697. *
  698. * Inputs:
  699. * secret: the master secret used to sign the hash
  700. * secret_len: the length of the master secret
  701. * seed{1, ..., 4}: seed values that are virtually
  702. * concatenated
  703. * seed{1,...4}_len: length of the seeds
  704. * output: a pointer to the output of the PRF
  705. * output_len: the number of desired bytes
  706. *
  707. * Output:
  708. * 0 on success, 1 on failure
  709. */
  710. int PRF(flow *f, uint8_t *secret, int32_t secret_len,
  711. uint8_t *seed1, int32_t seed1_len,
  712. uint8_t *seed2, int32_t seed2_len,
  713. uint8_t *seed3, int32_t seed3_len,
  714. uint8_t *seed4, int32_t seed4_len,
  715. uint8_t *output, int32_t output_len){
  716. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  717. EVP_PKEY *mac_key;
  718. const EVP_MD *md;
  719. if(f == NULL){
  720. md = EVP_sha256();
  721. } else {
  722. md = f->message_digest;
  723. }
  724. uint8_t A[EVP_MAX_MD_SIZE];
  725. size_t len, A_len;
  726. int chunk = EVP_MD_size(md);
  727. int remaining = output_len;
  728. uint8_t *out = output;
  729. EVP_MD_CTX_init(&ctx);
  730. EVP_MD_CTX_init(&ctx_tmp);
  731. EVP_MD_CTX_init(&ctx_init);
  732. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  733. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
  734. /* Calculate first A value */
  735. EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key);
  736. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  737. if(seed1 != NULL && seed1_len > 0){
  738. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  739. }
  740. if(seed2 != NULL && seed2_len > 0){
  741. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  742. }
  743. if(seed3 != NULL && seed3_len > 0){
  744. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  745. }
  746. if(seed4 != NULL && seed4_len > 0){
  747. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  748. }
  749. EVP_DigestSignFinal(&ctx, A, &A_len);
  750. //iterate until desired length is achieved
  751. while(remaining > 0){
  752. /* Now compute SHA384(secret, A+seed) */
  753. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  754. EVP_DigestSignUpdate(&ctx, A, A_len);
  755. EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx);
  756. if(seed1 != NULL && seed1_len > 0){
  757. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  758. }
  759. if(seed2 != NULL && seed2_len > 0){
  760. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  761. }
  762. if(seed3 != NULL && seed3_len > 0){
  763. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  764. }
  765. if(seed4 != NULL && seed4_len > 0){
  766. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  767. }
  768. if(remaining > chunk){
  769. EVP_DigestSignFinal(&ctx, out, &len);
  770. out += len;
  771. remaining -= len;
  772. /* Next A value */
  773. EVP_DigestSignFinal(&ctx_tmp, A, &A_len);
  774. } else {
  775. EVP_DigestSignFinal(&ctx, A, &A_len);
  776. memcpy(out, A, remaining);
  777. remaining -= remaining;
  778. }
  779. }
  780. EVP_PKEY_free(mac_key);
  781. EVP_MD_CTX_cleanup(&ctx);
  782. EVP_MD_CTX_cleanup(&ctx_tmp);
  783. EVP_MD_CTX_cleanup(&ctx_init);
  784. OPENSSL_cleanse(A, sizeof(A));
  785. return 0;
  786. }
  787. /** After receiving change cipher spec, calculate keys from master secret
  788. *
  789. * Input:
  790. * f: the tagged flow
  791. *
  792. * Output:
  793. * 0 on success, 1 on failure
  794. */
  795. int init_ciphers(flow *f){
  796. EVP_CIPHER_CTX *r_ctx;
  797. EVP_CIPHER_CTX *w_ctx;
  798. EVP_CIPHER_CTX *w_ctx_srvr;
  799. EVP_CIPHER_CTX *r_ctx_srvr;
  800. const EVP_CIPHER *c = f->cipher;
  801. if(c == NULL){
  802. /*This *shouldn't* happen, but might if a serverHello msg isn't received
  803. * or if a session is resumed in a strange way */
  804. return 1;
  805. }
  806. /* Generate Keys */
  807. uint8_t *write_key, *write_iv;
  808. uint8_t *read_key, *read_iv;
  809. int32_t mac_len, key_len, iv_len;
  810. key_len = EVP_CIPHER_key_length(c);
  811. iv_len = EVP_CIPHER_iv_length(c); //EVP_GCM_TLS_FIXED_IV_LEN;
  812. mac_len = EVP_MD_size(f->message_digest);
  813. int32_t total_len = key_len + iv_len + mac_len;
  814. total_len *= 2;
  815. uint8_t *key_block = ecalloc(1, total_len);
  816. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  817. (uint8_t *) TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
  818. f->server_random, SSL3_RANDOM_SIZE,
  819. f->client_random, SSL3_RANDOM_SIZE,
  820. NULL, 0,
  821. key_block, total_len);
  822. #ifdef DEBUG
  823. printf("master secret: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  824. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  825. printf("%02x ", f->master_secret[i]);
  826. }
  827. printf("\n");
  828. printf("client random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  829. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  830. printf("%02x ", f->client_random[i]);
  831. }
  832. printf("\n");
  833. printf("server random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  834. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  835. printf("%02x ", f->server_random[i]);
  836. }
  837. printf("\n");
  838. printf("keyblock: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  839. for(int i=0; i< total_len; i++){
  840. printf("%02x ", key_block[i]);
  841. }
  842. printf("\n");
  843. #endif
  844. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  845. write_key = key_block;
  846. read_key = key_block + key_len;
  847. write_iv = key_block + 2*key_len;
  848. read_iv = key_block + 2*key_len + iv_len;
  849. /* Initialize Cipher Contexts */
  850. r_ctx = EVP_CIPHER_CTX_new();
  851. w_ctx = EVP_CIPHER_CTX_new();
  852. EVP_CIPHER_CTX_init(r_ctx);
  853. EVP_CIPHER_CTX_init(w_ctx);
  854. w_ctx_srvr = EVP_CIPHER_CTX_new();
  855. r_ctx_srvr = EVP_CIPHER_CTX_new();
  856. EVP_CIPHER_CTX_init(w_ctx_srvr);
  857. EVP_CIPHER_CTX_init(r_ctx_srvr);
  858. /* Initialize MACs --- not needed for aes_256_gcm
  859. write_mac = key_block + 2*key_len + 2*iv_len;
  860. read_mac = key_block + 2*key_len + 2*iv_len + mac_len;
  861. read_mac_ctx = EVP_MD_CTX_create();
  862. write_mac_ctx = EVP_MD_CTX_create();
  863. read_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, read_mac, mac_len);
  864. write_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, write_mac, mac_len);
  865. EVP_DigestSignInit(read_mac_ctx, NULL, EVP_sha384(), NULL, read_mac_key);
  866. EVP_DigestSignInit(write_mac_ctx, NULL, EVP_sha384(), NULL, write_mac_key);
  867. EVP_PKEY_free(read_mac_key);
  868. EVP_PKEY_free(write_mac_key);*/
  869. #ifdef DEBUG
  870. {
  871. int i;
  872. fprintf(stderr, "EVP_CipherInit_ex(r_ctx,c,key=,iv=,which)\n");
  873. fprintf(stderr, "\tkey= ");
  874. for (i = 0; i < c->key_len; i++)
  875. fprintf(stderr, "%02x", read_key[i]);
  876. fprintf(stderr, "\n");
  877. fprintf(stderr, "\t iv= ");
  878. for (i = 0; i < c->iv_len; i++)
  879. fprintf(stderr, "%02x", read_iv[i]);
  880. fprintf(stderr, "\n");
  881. }
  882. {
  883. int i;
  884. fprintf(stderr, "EVP_CipherInit_ex(w_ctx,c,key=,iv=,which)\n");
  885. fprintf(stderr, "\tkey= ");
  886. for (i = 0; i < c->key_len; i++)
  887. fprintf(stderr, "%02x", write_key[i]);
  888. fprintf(stderr, "\n");
  889. fprintf(stderr, "\t iv= ");
  890. for (i = 0; i < c->iv_len; i++)
  891. fprintf(stderr, "%02x", write_iv[i]);
  892. fprintf(stderr, "\n");
  893. }
  894. #endif
  895. if(!EVP_CipherInit_ex(r_ctx, c, NULL, read_key, NULL, 0)){
  896. printf("FAIL r_ctx\n");
  897. }
  898. if(!EVP_CipherInit_ex(w_ctx, c, NULL, write_key, NULL, 1)){
  899. printf("FAIL w_ctx\n");
  900. }
  901. if(!EVP_CipherInit_ex(w_ctx_srvr, c, NULL, read_key, NULL, 1)){
  902. printf("FAIL w_ctx_srvr\n");
  903. }
  904. if(!EVP_CipherInit_ex(r_ctx_srvr, c, NULL, write_key, NULL, 0)){
  905. printf("FAIL r_ctx_srvr\n");
  906. }
  907. EVP_CIPHER_CTX_ctrl(r_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  908. EVP_CIPHER_CTX_ctrl(w_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  909. EVP_CIPHER_CTX_ctrl(w_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  910. EVP_CIPHER_CTX_ctrl(r_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  911. f->clnt_read_ctx = r_ctx;
  912. f->clnt_write_ctx = w_ctx;
  913. f->srvr_read_ctx = r_ctx_srvr;
  914. f->srvr_write_ctx = w_ctx_srvr;
  915. free(key_block);
  916. return 0;
  917. }
  918. /* Generate the keys for a client's super encryption layer
  919. *
  920. * The header of each downstream slitheen data chunk is 16 bytes and encrypted with
  921. * a 256 bit AES key
  922. *
  923. * The body of each downstream chunk is CBC encrypted with a 256 bit AES key
  924. *
  925. * The last 16 bytes of the body is a MAC over the body
  926. *
  927. */
  928. void generate_client_super_keys(uint8_t *secret, client *c){
  929. EVP_MD_CTX *mac_ctx;
  930. const EVP_MD *md = EVP_sha256();
  931. FILE *fp;
  932. //extract shared secret from SLITHEEN_ID
  933. uint8_t shared_secret[16];
  934. byte privkey[PTWIST_BYTES];
  935. fp = fopen("privkey", "rb");
  936. if (fp == NULL) {
  937. perror("fopen");
  938. exit(1);
  939. }
  940. if(fread(privkey, PTWIST_BYTES, 1, fp) < 1){
  941. perror("fread");
  942. exit(1);
  943. }
  944. fclose(fp);
  945. /* check tag*/
  946. if(check_tag(shared_secret, privkey, secret, (const byte *)"context", 7)){
  947. //something went wrong O.o
  948. printf("Error extracting secret from tag\n");
  949. return;
  950. }
  951. #ifdef DEBUG
  952. printf("Shared secret: ");
  953. for(int i=0; i< 16; i++){
  954. printf("%02x ", shared_secret[i]);
  955. }
  956. printf("\n");
  957. #endif
  958. /* Generate Keys */
  959. uint8_t *hdr_key, *bdy_key;
  960. uint8_t *mac_secret;
  961. EVP_PKEY *mac_key;
  962. int32_t mac_len, key_len;
  963. key_len = EVP_CIPHER_key_length(EVP_aes_256_cbc());
  964. mac_len = EVP_MD_size(md);
  965. int32_t total_len = 2*key_len + mac_len;
  966. uint8_t *key_block = ecalloc(1, total_len);
  967. PRF(NULL, shared_secret, SLITHEEN_SUPER_SECRET_SIZE,
  968. (uint8_t *) SLITHEEN_SUPER_CONST, SLITHEEN_SUPER_CONST_SIZE,
  969. NULL, 0,
  970. NULL, 0,
  971. NULL, 0,
  972. key_block, total_len);
  973. #ifdef DEBUG
  974. printf("slitheend id: \n");
  975. for(int i=0; i< SLITHEEN_ID_LEN; i++){
  976. printf("%02x ", secret[i]);
  977. }
  978. printf("\n");
  979. printf("keyblock: \n");
  980. for(int i=0; i< total_len; i++){
  981. printf("%02x ", key_block[i]);
  982. }
  983. printf("\n");
  984. #endif
  985. hdr_key = key_block;
  986. bdy_key = key_block + key_len;
  987. mac_secret = key_block + 2*key_len;
  988. /* Initialize MAC Context */
  989. mac_ctx = EVP_MD_CTX_create();
  990. EVP_DigestInit_ex(mac_ctx, md, NULL);
  991. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, mac_secret, mac_len);
  992. EVP_DigestSignInit(mac_ctx, NULL, md, NULL, mac_key);
  993. c->header_key = emalloc(key_len);
  994. c->body_key = emalloc(key_len);
  995. memcpy(c->header_key, hdr_key, key_len);
  996. memcpy(c->body_key, bdy_key, key_len);
  997. c->mac_ctx = mac_ctx;
  998. //Free everything
  999. free(key_block);
  1000. EVP_PKEY_free(mac_key);
  1001. return;
  1002. }
  1003. int super_encrypt(client *c, uint8_t *data, uint32_t len){
  1004. int retval = 1;
  1005. EVP_CIPHER_CTX *hdr_ctx = NULL;
  1006. EVP_CIPHER_CTX *bdy_ctx = NULL;
  1007. int32_t out_len;
  1008. size_t mac_len;
  1009. uint8_t *p = data;
  1010. uint8_t output[EVP_MAX_MD_SIZE];
  1011. //first encrypt the header
  1012. #ifdef DEBUG
  1013. printf("Plaintext Header:\n");
  1014. for(int i=0; i< SLITHEEN_HEADER_LEN; i++){
  1015. printf("%02x ", p[i]);
  1016. }
  1017. printf("\n");
  1018. #endif
  1019. hdr_ctx = EVP_CIPHER_CTX_new();
  1020. if(c->header_key == NULL){
  1021. retval = 0;
  1022. goto end;
  1023. }
  1024. EVP_CipherInit_ex(hdr_ctx, EVP_aes_256_cbc(), NULL, c->header_key, NULL, 1);
  1025. if(!EVP_CipherUpdate(hdr_ctx, p, &out_len, p, SLITHEEN_HEADER_LEN)){
  1026. printf("Failed!\n");
  1027. retval = 0;
  1028. goto end;
  1029. }
  1030. #ifdef DEBUG
  1031. printf("Encrypted Header (%d bytes)\n", out_len);
  1032. for(int i=0; i< out_len; i++){
  1033. printf("%02x ", p[i]);
  1034. }
  1035. printf("\n");
  1036. #endif
  1037. if(len == 0){ //only encrypt header: body contains garbage bytes
  1038. retval = 1;
  1039. goto end;
  1040. }
  1041. //encrypt the body
  1042. p += SLITHEEN_HEADER_LEN;
  1043. //generate IV
  1044. RAND_bytes(p, 16);
  1045. //set up cipher ctx
  1046. bdy_ctx = EVP_CIPHER_CTX_new();
  1047. EVP_CipherInit_ex(bdy_ctx, EVP_aes_256_cbc(), NULL, c->body_key, p, 1);
  1048. p+= 16;
  1049. #ifdef DEBUG
  1050. printf("Plaintext:\n");
  1051. for(int i=0; i< len; i++){
  1052. printf("%02x ", p[i]);
  1053. }
  1054. printf("\n");
  1055. #endif
  1056. if(!EVP_CipherUpdate(bdy_ctx, p, &out_len, p, len)){
  1057. printf("Failed!\n");
  1058. retval = 0;
  1059. goto end;
  1060. }
  1061. #ifdef DEBUG
  1062. printf("Encrypted %d bytes\n", out_len);
  1063. printf("Encrypted data:\n");
  1064. for(int i=0; i< out_len; i++){
  1065. printf("%02x ", p[i]);
  1066. }
  1067. printf("\n");
  1068. #endif
  1069. //MAC at the end
  1070. EVP_MD_CTX mac_ctx;
  1071. EVP_MD_CTX_init(&mac_ctx);
  1072. EVP_MD_CTX_copy_ex(&mac_ctx, c->mac_ctx);
  1073. EVP_DigestSignUpdate(&mac_ctx, p, out_len);
  1074. EVP_DigestSignFinal(&mac_ctx, output, &mac_len);
  1075. EVP_MD_CTX_cleanup(&mac_ctx);
  1076. p += out_len;
  1077. memcpy(p, output, 16);
  1078. #ifdef DEBUG_PARSE
  1079. printf("Computed mac:\n");
  1080. for(int i=0; i< 16; i++){
  1081. printf("%02x ", output[i]);
  1082. }
  1083. printf("\n");
  1084. fflush(stdout);
  1085. #endif
  1086. end:
  1087. if(hdr_ctx != NULL){
  1088. EVP_CIPHER_CTX_cleanup(hdr_ctx);
  1089. OPENSSL_free(hdr_ctx);
  1090. }
  1091. if(bdy_ctx != NULL){
  1092. EVP_CIPHER_CTX_cleanup(bdy_ctx);
  1093. OPENSSL_free(bdy_ctx);
  1094. }
  1095. return retval;
  1096. }
  1097. /** Checks a handshake message to see if it is tagged or a
  1098. * recognized flow. If the client random nonce is tagged,
  1099. * adds the flow to the flow table to be tracked.
  1100. *
  1101. * Inputs:
  1102. * info: the processed packet
  1103. * f: the tagged flow
  1104. *
  1105. * Output:
  1106. * none
  1107. */
  1108. void check_handshake(struct packet_info *info){
  1109. FILE *fp;
  1110. int res, code;
  1111. uint8_t *hello_rand;
  1112. const struct handshake_header *handshake_hdr;
  1113. byte privkey[PTWIST_BYTES];
  1114. byte key[16];
  1115. uint8_t *p = info->app_data + RECORD_HEADER_LEN;
  1116. handshake_hdr = (struct handshake_header*) p;
  1117. code = handshake_hdr->type;
  1118. if (code == 0x01){
  1119. p += CLIENT_HELLO_HEADER_LEN;
  1120. //now pointing to hello random :D
  1121. hello_rand = p;
  1122. p += 4; //skipping time bytes
  1123. /* Load the private key */
  1124. fp = fopen("privkey", "rb");
  1125. if (fp == NULL) {
  1126. perror("fopen");
  1127. exit(1);
  1128. }
  1129. res = fread(privkey, PTWIST_BYTES, 1, fp);
  1130. if (res < 1) {
  1131. perror("fread");
  1132. exit(1);
  1133. }
  1134. fclose(fp);
  1135. /* check tag*/
  1136. uint8_t context[4 + SSL3_RANDOM_SIZE - PTWIST_TAG_BYTES];
  1137. memcpy(context, &info->ip_hdr->dst.s_addr, 4);
  1138. memcpy(context + 4, hello_rand, SSL3_RANDOM_SIZE - PTWIST_TAG_BYTES);
  1139. res = check_tag(key, privkey, p, (const byte *)context, sizeof(context));
  1140. if (!res) {
  1141. #ifdef DEBUG_HS
  1142. printf("Received tagged flow! (key =");
  1143. for(int i=0; i<16;i++){
  1144. printf(" %02x", key[i]);
  1145. }
  1146. printf(")\n");
  1147. #endif
  1148. /* If flow is not in table, save it */
  1149. flow *flow_ptr = check_flow(info);
  1150. if(flow_ptr == NULL){
  1151. flow_ptr = add_flow(info);
  1152. if(flow_ptr == NULL){
  1153. fprintf(stderr, "Memory failure\n");
  1154. return;
  1155. }
  1156. for(int i=0; i<16; i++){
  1157. flow_ptr->key[i] = key[i];
  1158. }
  1159. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  1160. #ifdef DEBUG
  1161. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  1162. printf("%02x ", hello_rand[i]);
  1163. }
  1164. printf("\n");
  1165. printf("Saved new flow\n");
  1166. #endif
  1167. flow_ptr->ref_ctr--;
  1168. printf("Flow added. %p ref_ctr %d\n", flow_ptr, flow_ptr->ref_ctr);
  1169. } else { /* else update saved flow with new key and random nonce */
  1170. for(int i=0; i<16; i++){
  1171. flow_ptr->key[i] = key[i];
  1172. }
  1173. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  1174. flow_ptr->ref_ctr--;
  1175. printf("Flow updated in check_flow. %p ref_ctr %d\n", flow_ptr, flow_ptr->ref_ctr);
  1176. }
  1177. }
  1178. }
  1179. }
  1180. /* Check the given tag with the given context and private key. Return 0
  1181. if the tag is properly formed, non-0 if not. If the tag is correct,
  1182. set key to the resulting secret key. */
  1183. int check_tag(byte key[16], const byte privkey[PTWIST_BYTES],
  1184. const byte tag[PTWIST_TAG_BYTES], const byte *context,
  1185. size_t context_len)
  1186. {
  1187. int ret = -1;
  1188. byte sharedsec[PTWIST_BYTES+context_len];
  1189. byte taghashout[32];
  1190. #if PTWIST_PUZZLE_STRENGTH > 0
  1191. byte hashout[32];
  1192. size_t puzzle_len = 16+PTWIST_RESP_BYTES;
  1193. byte value_to_hash[puzzle_len];
  1194. unsigned int firstbits;
  1195. int firstpass = 0;
  1196. #endif
  1197. /* Compute the shared secret privkey*TAG */
  1198. ptwist_pointmul(sharedsec, tag, privkey);
  1199. /* Create the hash tag keys */
  1200. memmove(sharedsec+PTWIST_BYTES, context, context_len);
  1201. SHA256(sharedsec, PTWIST_BYTES + context_len, taghashout);
  1202. #if PTWIST_PUZZLE_STRENGTH > 0
  1203. /* Construct the proposed solution to the puzzle */
  1204. memmove(value_to_hash, taghashout, 16);
  1205. memmove(value_to_hash+16, tag+PTWIST_BYTES, PTWIST_RESP_BYTES);
  1206. value_to_hash[16+PTWIST_RESP_BYTES-1] &= PTWIST_RESP_MASK;
  1207. /* Hash the proposed solution and see if it is correct; that is, the
  1208. * hash should start with PTWIST_PUZZLE_STRENGTH bits of 0s,
  1209. * followed by the last PTWIST_HASH_SHOWBITS of the tag. */
  1210. md_map_sh256(hashout, value_to_hash, puzzle_len);
  1211. #if PTWIST_PUZZLE_STRENGTH < 32
  1212. /* This assumes that you're on an architecture that doesn't care
  1213. * about alignment, and is little endian. */
  1214. firstbits = *(unsigned int*)hashout;
  1215. if ((firstbits & PTWIST_PUZZLE_MASK) == 0) {
  1216. firstpass = 1;
  1217. }
  1218. #else
  1219. #error "Code assumes PTWIST_PUZZLE_STRENGTH < 32"
  1220. #endif
  1221. if (firstpass) {
  1222. bn_t Hbn, Tbn;
  1223. bn_new(Hbn);
  1224. bn_new(Tbn);
  1225. hashout[PTWIST_HASH_TOTBYTES-1] &= PTWIST_HASH_MASK;
  1226. bn_read_bin(Hbn, hashout, PTWIST_HASH_TOTBYTES, BN_POS);
  1227. bn_rsh(Hbn, Hbn, PTWIST_PUZZLE_STRENGTH);
  1228. bn_read_bin(Tbn, tag+PTWIST_BYTES, PTWIST_TAG_BYTES-PTWIST_BYTES,
  1229. BN_POS);
  1230. bn_rsh(Tbn, Tbn, PTWIST_RESP_BITS);
  1231. ret = (bn_cmp(Tbn,Hbn) != CMP_EQ);
  1232. bn_free(Hbn);
  1233. bn_free(Tbn);
  1234. }
  1235. #else
  1236. /* We're not using a client puzzle, so just check that the first
  1237. * PTWIST_HASH_SHOWBITS bits of the above hash fill out the rest
  1238. * of the tag. If there's no puzzle, PTWIST_HASH_SHOWBITS must be
  1239. * a multiple of 8. */
  1240. ret = (memcmp(tag+PTWIST_BYTES, taghashout, PTWIST_HASH_SHOWBITS/8) != 0);
  1241. #endif
  1242. if (ret == 0) {
  1243. memmove(key, taghashout+16, 16);
  1244. }
  1245. return ret;
  1246. }