crypto.c 42 KB

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