crypto.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  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 <openssl/aes.h>
  139. #include <openssl/modes.h>
  140. #include "ptwist.h"
  141. #include "crypto.h"
  142. #include "flow.h"
  143. #include "packet.h"
  144. #include "util.h"
  145. #include "relay.h"
  146. #define NID_sect163k1 721
  147. #define NID_sect163r1 722
  148. #define NID_sect163r2 723
  149. #define NID_sect193r1 724
  150. #define NID_sect193r2 725
  151. #define NID_sect233k1 726
  152. #define NID_sect233r1 727
  153. #define NID_sect239k1 728
  154. #define NID_sect283k1 729
  155. #define NID_sect283r1 730
  156. #define NID_sect409k1 731
  157. #define NID_sect409r1 732
  158. #define NID_sect571k1 733
  159. #define NID_sect571r1 734
  160. #define NID_secp160k1 708
  161. #define NID_secp160r1 709
  162. #define NID_secp160r2 710
  163. #define NID_secp192k1 711
  164. #define NID_X9_62_prime192v1 409
  165. #define NID_secp224k1 712
  166. #define NID_secp224r1 713
  167. #define NID_secp256k1 714
  168. #define NID_X9_62_prime256v1 415
  169. #define NID_secp384r1 715
  170. #define NID_secp521r1 716
  171. #define NID_brainpoolP256r1 927
  172. #define NID_brainpoolP384r1 931
  173. #define NID_brainpoolP512r1 933
  174. #define NID_X25519 1034
  175. static int nid_list[] = {
  176. NID_sect163k1, /* sect163k1 (1) */
  177. NID_sect163r1, /* sect163r1 (2) */
  178. NID_sect163r2, /* sect163r2 (3) */
  179. NID_sect193r1, /* sect193r1 (4) */
  180. NID_sect193r2, /* sect193r2 (5) */
  181. NID_sect233k1, /* sect233k1 (6) */
  182. NID_sect233r1, /* sect233r1 (7) */
  183. NID_sect239k1, /* sect239k1 (8) */
  184. NID_sect283k1, /* sect283k1 (9) */
  185. NID_sect283r1, /* sect283r1 (10) */
  186. NID_sect409k1, /* sect409k1 (11) */
  187. NID_sect409r1, /* sect409r1 (12) */
  188. NID_sect571k1, /* sect571k1 (13) */
  189. NID_sect571r1, /* sect571r1 (14) */
  190. NID_secp160k1, /* secp160k1 (15) */
  191. NID_secp160r1, /* secp160r1 (16) */
  192. NID_secp160r2, /* secp160r2 (17) */
  193. NID_secp192k1, /* secp192k1 (18) */
  194. NID_X9_62_prime192v1, /* secp192r1 (19) */
  195. NID_secp224k1, /* secp224k1 (20) */
  196. NID_secp224r1, /* secp224r1 (21) */
  197. NID_secp256k1, /* secp256k1 (22) */
  198. NID_X9_62_prime256v1, /* secp256r1 (23) */
  199. NID_secp384r1, /* secp384r1 (24) */
  200. NID_secp521r1, /* secp521r1 (25) */
  201. NID_brainpoolP256r1, /* brainpoolP256r1 (26) */
  202. NID_brainpoolP384r1, /* brainpoolP384r1 (27) */
  203. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  204. NID_brainpoolP512r1, /* brainpool512r1 (28) */
  205. NID_X25519 /* X25519 (29) */
  206. #else
  207. NID_brainpoolP512r1 /* brainpool512r1 (28) */
  208. #endif
  209. };
  210. /** Updates the hash of all TLS handshake messages up to and
  211. * including the ClientKeyExchange. This hash is eventually used
  212. * to compute the TLS extended master secret.
  213. *
  214. * Inputs:
  215. * f: the tagged flow
  216. * hs: A pointer to the start of the handshake message
  217. *
  218. * Output:
  219. * 0 on success, 1 on failure
  220. */
  221. int update_handshake_hash(flow *f, uint8_t *hs){
  222. //find handshake length
  223. const struct handshake_header *hs_hdr;
  224. uint8_t *p = hs;
  225. hs_hdr = (struct handshake_header*) p;
  226. uint32_t hs_len = HANDSHAKE_MESSAGE_LEN(hs_hdr);
  227. EVP_DigestUpdate(f->hs_md_ctx, hs, hs_len+4);
  228. #ifdef DEBUG_HS_EXTRA
  229. printf("SLITHEEN: adding to handshake hash:\n");
  230. for(int i=0; i< hs_len + 4; i++){
  231. printf("%02x ", hs[i]);
  232. }
  233. printf("\n");
  234. #endif
  235. return 0;
  236. }
  237. /** Extracts the server parameters from the server key
  238. * exchange message
  239. *
  240. * Inputs:
  241. * f: the tagged flow
  242. * hs: the beginning of the server key exchange
  243. * handshake message
  244. *
  245. * Output:
  246. * 0 on success, 1 on failure
  247. */
  248. int extract_parameters(flow *f, uint8_t *hs){
  249. uint8_t *p;
  250. long i;
  251. int ok=1;
  252. p = hs + HANDSHAKE_HEADER_LEN;
  253. if(f->keyex_alg == 1){
  254. DH *dh;
  255. if((dh = DH_new()) == NULL){
  256. return 1;
  257. }
  258. /* Extract prime modulus */
  259. n2s(p,i);
  260. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  261. BIGNUM *prime = NULL;
  262. if(!(prime = BN_bin2bn(p,i,NULL))){
  263. return 1;
  264. }
  265. #else
  266. if(!(dh->p = BN_bin2bn(p,i,NULL))){
  267. return 1;
  268. }
  269. #endif
  270. p += i;
  271. /* Extract generator */
  272. n2s(p,i);
  273. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  274. BIGNUM *group = NULL;
  275. if(!(group = BN_bin2bn(p,i,NULL))){
  276. return 1;
  277. }
  278. if(!DH_set0_pqg(dh, prime, NULL, group)){
  279. return 1;
  280. }
  281. #else
  282. if(!(dh->g = BN_bin2bn(p,i,NULL))){
  283. return 1;
  284. }
  285. #endif
  286. p += i;
  287. /* Extract server public value */
  288. n2s(p,i);
  289. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  290. BIGNUM *pub = NULL;
  291. if(!(pub = BN_bin2bn(p,i,NULL))){
  292. return 1;
  293. }
  294. if(!DH_set0_key(dh, pub, NULL)){
  295. return 1;
  296. }
  297. #else
  298. if(!(dh->pub_key = BN_bin2bn(p,i,NULL))){
  299. return 1;
  300. }
  301. #endif
  302. f->dh = dh;
  303. } else if (f->keyex_alg == 2){
  304. EC_KEY *ecdh;
  305. EC_GROUP *ngroup;
  306. const EC_GROUP *group;
  307. BN_CTX *bn_ctx = NULL;
  308. EC_POINT *srvr_ecpoint = NULL;
  309. int curve_nid = 0;
  310. int encoded_pt_len = 0;
  311. if(p[0] != 0x03){//not a named curve
  312. goto err;
  313. }
  314. //int curve_id = (p[1] << 8) + p[2];
  315. int curve_id = *(p+2);
  316. #ifdef DEBUG_HS
  317. printf("Using curve number %d\n", curve_id);
  318. #endif
  319. if((curve_id < 0) || ((unsigned int)curve_id >
  320. sizeof(nid_list) / sizeof(nid_list[0]))){
  321. goto err;
  322. }
  323. curve_nid = nid_list[curve_id-1];
  324. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  325. if(curve_nid == NID_X25519){
  326. //this is a custom curve and must be handled differently
  327. EVP_PKEY *key = EVP_PKEY_new();
  328. if (key == NULL || !EVP_PKEY_set_type(key, curve_nid)){
  329. EVP_PKEY_free(key);
  330. goto err;
  331. }
  332. p += 3;
  333. encoded_pt_len = *p;
  334. p += 1;
  335. EVP_PKEY_set1_tls_encodedpoint(key, p, encoded_pt_len);
  336. f->srvr_key = key;
  337. } else {
  338. #endif
  339. if((ecdh = EC_KEY_new()) == NULL) {
  340. goto err;
  341. }
  342. ngroup = EC_GROUP_new_by_curve_name(curve_nid);
  343. if(ngroup == NULL){
  344. printf("couldn't get curve by name (%d)\n", curve_nid);
  345. goto err;
  346. }
  347. if(EC_KEY_set_group(ecdh, ngroup) == 0){
  348. printf("couldn't set group\n");
  349. goto err;
  350. }
  351. EC_GROUP_free(ngroup);
  352. group = EC_KEY_get0_group(ecdh);
  353. p += 3;
  354. /* Get EC point */
  355. if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
  356. ((bn_ctx = BN_CTX_new()) == NULL)) {
  357. goto err;
  358. }
  359. encoded_pt_len = *p;
  360. p += 1;
  361. if(EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len,
  362. bn_ctx) == 0){
  363. goto err;
  364. }
  365. EC_KEY_set_public_key(ecdh, srvr_ecpoint);
  366. f->ecdh = ecdh;
  367. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  368. }
  369. #endif
  370. ecdh = NULL;
  371. BN_CTX_free(bn_ctx);
  372. bn_ctx = NULL;
  373. EC_POINT_free(srvr_ecpoint);
  374. srvr_ecpoint = NULL;
  375. ok=0;
  376. err:
  377. if(bn_ctx != NULL){
  378. BN_CTX_free(bn_ctx);
  379. }
  380. if(srvr_ecpoint != NULL){
  381. EC_POINT_free(srvr_ecpoint);
  382. }
  383. if(ecdh != NULL){
  384. EC_KEY_free(ecdh);
  385. }
  386. }
  387. return ok;
  388. }
  389. /* Encrypt/Decrypt a TLS record
  390. *
  391. * Inputs:
  392. * f: the tagged flow
  393. * input: a pointer to the data that is to be encrypted/
  394. * decrypted
  395. * output: a pointer to where the data should be written
  396. * after it is encrypted or decrypted
  397. * len: the length of the data
  398. * incoming: the direction of the record
  399. * type: the type of the TLS record
  400. * enc: 1 for encryption, 0 for decryption
  401. * re: 1 if this is a re-encryption (counters are reset), 0 otherwise
  402. * Note: is only checked during encryption
  403. *
  404. * Output:
  405. * length of the output data
  406. */
  407. 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){
  408. uint8_t *p = input;
  409. EVP_CIPHER_CTX *ds = (incoming) ? ((enc) ? f->srvr_write_ctx : f->clnt_read_ctx) : ((enc) ? f->clnt_write_ctx : f->srvr_read_ctx);
  410. if(ds == NULL){
  411. printf("FAIL\n");
  412. return 1;
  413. }
  414. uint8_t *seq;
  415. seq = (incoming) ? f->read_seq : f->write_seq;
  416. if(enc && re){
  417. for(int i=7; i>=0; i--){
  418. --seq[i];
  419. if(seq[i] != 0xff)
  420. break;
  421. }
  422. }
  423. /*if(f->application && (ds->iv[EVP_GCM_TLS_FIXED_IV_LEN] == 0)){
  424. //fill in rest of iv
  425. for(int i = EVP_GCM_TLS_FIXED_IV_LEN; i< ds->cipher->iv_len; i++){
  426. ds->iv[i] = p[i- EVP_GCM_TLS_FIXED_IV_LEN];
  427. }
  428. }*/
  429. #ifdef DEBUG_HS_EXTRA
  430. printf("\t\tiv: ");
  431. for(int i=0; i<ds->cipher->iv_len; i++){
  432. printf("%02X ", ds->iv[i]);
  433. }
  434. printf("\n");
  435. #endif
  436. uint8_t buf[13];
  437. memcpy(buf, seq, 8);
  438. for(int i=7; i>=0; i--){
  439. ++seq[i];
  440. if(seq[i] != 0)
  441. break;
  442. }
  443. buf[8] = type;
  444. buf[9] = 0x03;
  445. buf[10] = 0x03;
  446. buf[11] = len >> 8; //len >> 8;
  447. buf[12] = len & 0xff;//len *0xff;
  448. int32_t pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
  449. 13, buf); // = int32_t pad?
  450. if(enc)
  451. len += pad;
  452. int32_t n = EVP_Cipher(ds, p, p, len); //decrypt in place
  453. if(n<0) return 0;
  454. #ifdef DEBUG
  455. printf("decrypted data:\n");
  456. for(int i=0; i< len; i++){
  457. printf("%02x ", p[EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  458. }
  459. printf("\n");
  460. #endif
  461. if(!enc)
  462. p[EVP_GCM_TLS_EXPLICIT_IV_LEN+n] = '\0';
  463. return n;
  464. }
  465. /** Increases the GCM counter when we don't decrypt a record to produce the correct tag in the next
  466. * re-encrypted record
  467. *
  468. * Inputs:
  469. * f: the tagged flow
  470. * incoming: the direction of the flow
  471. *
  472. * Output:
  473. * 0 on success, 1 on failure
  474. */
  475. int fake_encrypt(flow *f, int32_t incoming){
  476. uint8_t *seq = (incoming) ? f->read_seq : f->write_seq;
  477. for(int i=7; i>=0; i--){
  478. ++seq[i];
  479. if(seq[i] != 0)
  480. break;
  481. }
  482. return 0;
  483. }
  484. /** Mark the hash in a downstream TLS finished message
  485. *
  486. * Changes the finished hash to
  487. * SHA256_HMAC_96(shared_key, "SLITHEEN_FINISHED" || old_finished_hash)
  488. *
  489. * This feature detects and prevents suspicious behaviour in the event
  490. * of a MiTM or RAD attack.
  491. *
  492. * Inputs:
  493. * f: the tagged flow
  494. * hs: a pointer to the TLS Finished handshake message
  495. *
  496. * Output:
  497. * 0 on success, 1 on failure
  498. * if success, the message pointed to by hs will have
  499. * been updated
  500. */
  501. int mark_finished_hash(flow *f, uint8_t *hs){
  502. HMAC_CTX *ctx = NULL;
  503. uint8_t hmac_output[EVP_MAX_MD_SIZE];
  504. unsigned int hmac_output_len;
  505. // Ensure this is a Finished message, of length 12 bytes
  506. if (memcmp(hs, "\x14\x00\x00\x0c", 4)) {
  507. return 1;
  508. }
  509. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  510. ctx = HMAC_CTX_new();
  511. #else
  512. ctx = scalloc(1, sizeof(HMAC_CTX));
  513. HMAC_CTX_init(ctx);
  514. #endif
  515. HMAC_Init_ex(ctx, f->key, 16, EVP_sha256(), NULL);
  516. HMAC_Update(ctx, (const unsigned char *)SLITHEEN_FINISHED_INPUT_CONST, SLITHEEN_FINISHED_INPUT_CONST_SIZE);
  517. HMAC_Update(ctx, hs+4, 12);
  518. HMAC_Final(ctx, hmac_output, &hmac_output_len);
  519. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  520. HMAC_CTX_free(ctx);
  521. #else
  522. HMAC_CTX_cleanup(ctx);
  523. free(ctx);
  524. #endif
  525. if (hmac_output_len != 32) {
  526. return 1;
  527. }
  528. memmove(hs+4, hmac_output, 12);
  529. return 0;
  530. }
  531. /** Computes the TLS master secret from the decoy server's
  532. * public key parameters and the leaked secret from the
  533. * extracted Slitheen tag
  534. *
  535. * Input:
  536. * f: the tagged flow
  537. *
  538. * Output:
  539. * 0 on success, 1 on failure
  540. */
  541. int compute_master_secret(flow *f){
  542. #ifdef DEBUG_HS
  543. 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);
  544. #endif
  545. DH *dh_srvr = NULL;
  546. DH *dh_clnt = NULL;
  547. BN_CTX *ctx = NULL;
  548. BIGNUM *pub_key = NULL, *priv_key = NULL, *order = NULL;
  549. EC_KEY *clnt_ecdh = NULL;
  550. EC_POINT *e_pub_key = NULL;
  551. int ok =1;
  552. uint8_t *pre_master_secret = scalloc(1, PRE_MASTER_MAX_LEN);
  553. int32_t pre_master_len;
  554. uint32_t l;
  555. int32_t bytes;
  556. uint8_t *buf = NULL;
  557. if(f->keyex_alg == 1){
  558. BN_MONT_CTX *mont = NULL;
  559. ctx = BN_CTX_new();
  560. dh_srvr = f->dh;
  561. if(dh_srvr == NULL){
  562. goto err;
  563. }
  564. dh_clnt = DHparams_dup(dh_srvr);
  565. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  566. const BIGNUM *p, *q, *g;
  567. DH_get0_pqg(dh_clnt, &p, &q, &g);
  568. l = DH_get_length(dh_clnt) ? DH_get_length(dh_clnt) : BN_num_bits(p) - 1;
  569. #else
  570. l = dh_clnt->length ? dh_clnt->length : BN_num_bits(dh_clnt->p) - 1;
  571. #endif
  572. bytes = (l+7) / 8;
  573. buf = (uint8_t *)OPENSSL_malloc(bytes);
  574. if (buf == NULL){
  575. BNerr(BN_F_BNRAND, ERR_R_MALLOC_FAILURE);
  576. goto err;
  577. }
  578. pub_key = BN_new();
  579. priv_key = BN_new();
  580. #ifdef DEBUG
  581. printf("key =");
  582. for(int i=0; i< 16; i++)
  583. printf(" %02x", f->key[i]);
  584. printf("\n");
  585. #endif
  586. PRF(f, f->key, 16,
  587. (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  588. NULL, 0, NULL, 0, NULL, 0,
  589. buf, bytes);
  590. #ifdef DEBUG_HS
  591. printf("Generated the client private key [len: %d]: ", bytes);
  592. for(int i=0; i< bytes; i++){
  593. printf(" %02x ", buf[i]);
  594. }
  595. printf("\n");
  596. #endif
  597. if (!BN_bin2bn(buf, bytes, priv_key))
  598. goto err;
  599. {
  600. BIGNUM *prk;
  601. prk = priv_key;
  602. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  603. if (!BN_mod_exp_mont(pub_key, g, prk, p, ctx, mont)){
  604. goto err;
  605. }
  606. #else
  607. if (!dh_clnt->meth->bn_mod_exp(dh_clnt, pub_key, dh_clnt->g, prk, dh_clnt->p, ctx, mont)){
  608. goto err;
  609. }
  610. #endif
  611. }
  612. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  613. if(!DH_set0_key(dh_clnt, pub_key, priv_key)){
  614. goto err;
  615. }
  616. const BIGNUM *srvr_pub, *srvr_priv;
  617. DH_get0_key(dh_srvr, &srvr_pub, &srvr_priv);
  618. pre_master_len = DH_compute_key(pre_master_secret, srvr_pub, dh_clnt);
  619. #else
  620. dh_clnt->pub_key = pub_key;
  621. dh_clnt->priv_key = priv_key;
  622. pre_master_len = DH_compute_key(pre_master_secret, dh_srvr->pub_key, dh_clnt);
  623. #endif
  624. } else if(f->keyex_alg == 2){
  625. const EC_GROUP *srvr_group = NULL;
  626. const EC_POINT *srvr_ecpoint = NULL;
  627. EC_KEY *tkey;
  628. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  629. if(f->srvr_key != NULL){
  630. EVP_PKEY *ckey, *skey;
  631. EVP_PKEY_CTX *pctx;
  632. skey = f->srvr_key;
  633. /* Generate client key from tag */
  634. X25519_KEY *xkey = OPENSSL_zalloc(sizeof(*xkey));
  635. xkey->privkey = OPENSSL_secure_malloc(X25519_KEYLEN);
  636. if(xkey->privkey == NULL){
  637. goto err;
  638. }
  639. PRF(f, f->key, 16, (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  640. NULL, 0, NULL, 0, NULL, 0, xkey->privkey, X25519_KEYLEN);
  641. #ifdef DEBUG_HS
  642. printf("Generated the X25519 client private key [len: %d]: ", X25519_KEYLEN);
  643. for(int i=0; i< X25519_KEYLEN; i++){
  644. printf("%02x ", xkey->privkey[i]);
  645. }
  646. printf("\n");
  647. #endif
  648. //X25519_public_from_private(xkey->pubkey, xkey->privkey);
  649. ckey = EVP_PKEY_new();
  650. EVP_PKEY_assign(ckey, NID_X25519, xkey);
  651. pctx = EVP_PKEY_CTX_new(ckey, NULL);
  652. if (EVP_PKEY_derive_init(pctx) <= 0
  653. || EVP_PKEY_derive_set_peer(pctx, skey) <= 0
  654. || EVP_PKEY_derive(pctx, NULL, (uint64_t *) &pre_master_len) <= 0) {
  655. goto err;
  656. }
  657. if (EVP_PKEY_derive(pctx, pre_master_secret, (uint64_t *) &pre_master_len) <= 0)
  658. goto err;
  659. EVP_PKEY_CTX_free(pctx);
  660. EVP_PKEY_free(ckey);
  661. } else { /* TODO: need to generate client key in a special way too :S */
  662. #endif
  663. tkey = f->ecdh;
  664. if(tkey == NULL){
  665. goto err;
  666. }
  667. srvr_group = EC_KEY_get0_group(tkey);
  668. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  669. if((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
  670. goto err;
  671. }
  672. if((clnt_ecdh = EC_KEY_new()) == NULL) {
  673. goto err;
  674. }
  675. if(!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  676. goto err;
  677. }
  678. /* Now generate key from tag */
  679. if((order = BN_new()) == NULL){
  680. goto err;
  681. }
  682. if((ctx = BN_CTX_new()) == NULL){
  683. goto err;
  684. }
  685. if((priv_key = BN_new()) == NULL){
  686. goto err;
  687. }
  688. if(!EC_GROUP_get_order(srvr_group, order, ctx)){
  689. goto err;
  690. }
  691. l = BN_num_bits(order);
  692. bytes = (l+7)/8;
  693. buf = (unsigned char *)OPENSSL_malloc(bytes);
  694. if(buf == NULL){
  695. goto err;
  696. }
  697. PRF(f, f->key, 16, (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  698. NULL, 0, NULL, 0, NULL, 0, buf, bytes);
  699. #ifdef DEBUG_HS
  700. printf("Generated the client private key [len: %d]: ", bytes);
  701. for(int i=0; i< bytes; i++){
  702. printf("%02x ", buf[i]);
  703. }
  704. printf("\n");
  705. #endif
  706. if(!BN_bin2bn(buf, bytes, priv_key)){
  707. goto err;
  708. }
  709. if((e_pub_key = EC_POINT_new(srvr_group)) == NULL){
  710. goto err;
  711. }
  712. if(!EC_POINT_mul(EC_KEY_get0_group(clnt_ecdh), e_pub_key, priv_key, NULL, NULL, ctx)){
  713. goto err;
  714. }
  715. EC_KEY_set_private_key(clnt_ecdh, priv_key);
  716. EC_KEY_set_public_key(clnt_ecdh, e_pub_key);
  717. /*Compute the master secret */
  718. int32_t field_size = EC_GROUP_get_degree(srvr_group);
  719. if(field_size <= 0){
  720. goto err;
  721. }
  722. pre_master_len = ECDH_compute_key(pre_master_secret, (field_size + 7) / 8,
  723. srvr_ecpoint, clnt_ecdh, NULL);
  724. if(pre_master_len <= 0) {
  725. goto err;
  726. }
  727. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  728. }
  729. #endif
  730. }
  731. /*Generate master secret */
  732. if(f->extended_master_secret){
  733. //compute session hash
  734. EVP_MD_CTX *md_ctx = NULL;
  735. uint8_t hash[EVP_MAX_MD_SIZE*2];
  736. uint32_t hash_len;
  737. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  738. md_ctx = EVP_MD_CTX_new();
  739. #else
  740. md_ctx = scalloc(1, sizeof(EVP_MD_CTX));
  741. EVP_MD_CTX_init(md_ctx);
  742. #endif
  743. EVP_MD_CTX_copy_ex(md_ctx, f->hs_md_ctx);
  744. EVP_DigestFinal_ex(md_ctx, hash, &hash_len);
  745. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  746. EVP_MD_CTX_free(md_ctx);
  747. #else
  748. EVP_MD_CTX_cleanup(md_ctx);
  749. free(md_ctx);
  750. #endif
  751. PRF(f, pre_master_secret, pre_master_len, (uint8_t *) TLS_MD_EXTENDED_MASTER_SECRET_CONST, TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE, hash, hash_len, NULL, 0, NULL, 0, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  752. #ifdef DEBUG_HS
  753. fprintf(stdout, "Premaster Secret:\n");
  754. BIO_dump_fp(stdout, (char *)pre_master_secret, pre_master_len);
  755. fprintf(stdout, "Handshake hash:\n");
  756. BIO_dump_fp(stdout, (char *)hash, hash_len);
  757. fprintf(stdout, "Master Secret:\n");
  758. BIO_dump_fp(stdout, (char *)f->master_secret, SSL3_MASTER_SECRET_SIZE);
  759. #endif
  760. } else {
  761. 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);
  762. #ifdef DEBUG_HS
  763. fprintf(stdout, "Premaster Secret:\n");
  764. BIO_dump_fp(stdout, (char *)pre_master_secret, pre_master_len);
  765. fprintf(stdout, "Client Random:\n");
  766. BIO_dump_fp(stdout, (char *)f->client_random, SSL3_RANDOM_SIZE);
  767. fprintf(stdout, "Server Random:\n");
  768. BIO_dump_fp(stdout, (char *)f->server_random, SSL3_RANDOM_SIZE);
  769. fprintf(stdout, "Master Secret:\n");
  770. BIO_dump_fp(stdout, (char *)f->master_secret, SSL3_MASTER_SECRET_SIZE);
  771. #endif
  772. }
  773. if(f->current_session != NULL){
  774. memcpy(f->current_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  775. }
  776. //remove pre_master_secret from memory
  777. memset(pre_master_secret, 0, PRE_MASTER_MAX_LEN);
  778. ok = 0;
  779. err:
  780. if((pub_key != NULL) && (dh_srvr == NULL)){
  781. BN_free(pub_key);
  782. }
  783. if((priv_key != NULL) && ((dh_clnt == NULL) || (EC_KEY_get0_private_key(clnt_ecdh) == NULL))){
  784. BN_free(priv_key);
  785. }
  786. if(ctx != NULL){
  787. BN_CTX_free(ctx);
  788. }
  789. OPENSSL_free(buf);
  790. free(pre_master_secret);
  791. if(dh_srvr != NULL){
  792. DH_free(dh_srvr);
  793. f->dh = NULL;
  794. }
  795. if(dh_clnt != NULL) {
  796. DH_free(dh_clnt);
  797. }
  798. if(order){
  799. BN_free(order);
  800. }
  801. if(clnt_ecdh != NULL){
  802. EC_KEY_free(clnt_ecdh);
  803. }
  804. if(e_pub_key != NULL){
  805. EC_POINT_free(e_pub_key);
  806. }
  807. return ok;
  808. }
  809. /** Saves the random none from the server hello message
  810. *
  811. * Inputs:
  812. * f: the tagged flow
  813. * hs: a pointer to the beginning of the server hello msg
  814. *
  815. * Output:
  816. * 0 on success, 1 on failure
  817. */
  818. int extract_server_random(flow *f, uint8_t *hs){
  819. uint8_t *p;
  820. p = hs + HANDSHAKE_HEADER_LEN;
  821. p+=2; //skip version
  822. memcpy(f->server_random, p, SSL3_RANDOM_SIZE);
  823. p += SSL3_RANDOM_SIZE;
  824. //skip session id
  825. uint8_t id_len = (uint8_t) p[0];
  826. p ++;
  827. p += id_len;
  828. //now extract ciphersuite
  829. #ifdef DEBUG_HS
  830. printf("Checking cipher\n");
  831. #endif
  832. if(((p[0] <<8) + p[1]) == 0x9E){
  833. #ifdef DEBUG_HS
  834. printf("USING DHE-RSA-AES128-GCM-SHA256\n");
  835. fflush(stdout);
  836. #endif
  837. f->keyex_alg = 1;
  838. f->cipher = EVP_aes_128_gcm();
  839. f->message_digest = EVP_sha256();
  840. } else if(((p[0] <<8) + p[1]) == 0x9F){
  841. #ifdef DEBUG_HS
  842. printf("USING DHE-RSA-AES256-GCM-SHA384\n");
  843. fflush(stdout);
  844. #endif
  845. f->keyex_alg = 1;
  846. f->cipher = EVP_aes_256_gcm();
  847. f->message_digest = EVP_sha384();
  848. } else if(((p[0] <<8) + p[1]) == 0xC02F){
  849. #ifdef DEBUG_HS
  850. printf("USING ECDHE-RSA-AES128-GCM-SHA256\n");
  851. fflush(stdout);
  852. #endif
  853. f->keyex_alg = 2;
  854. f->cipher = EVP_aes_128_gcm();
  855. f->message_digest = EVP_sha256();
  856. } else if(((p[0] <<8) + p[1]) == 0xC030){
  857. #ifdef DEBUG_HS
  858. printf("USING ECDHE-RSA-AES256-GCM-SHA384\n");
  859. fflush(stdout);
  860. #endif
  861. f->keyex_alg = 2;
  862. f->cipher = EVP_aes_256_gcm();
  863. f->message_digest = EVP_sha384();
  864. } else {
  865. #ifdef DEBUG_HS
  866. printf("%x %x = %x\n", p[0], p[1], ((p[0] <<8) + p[1]));
  867. printf("Error: unsupported cipher\n");
  868. fflush(stdout);
  869. #endif
  870. return 1;
  871. }
  872. return 0;
  873. }
  874. /** PRF using sha384, as defined in RFC 5246
  875. *
  876. * Inputs:
  877. * secret: the master secret used to sign the hash
  878. * secret_len: the length of the master secret
  879. * seed{1, ..., 4}: seed values that are virtually
  880. * concatenated
  881. * seed{1,...4}_len: length of the seeds
  882. * output: a pointer to the output of the PRF
  883. * output_len: the number of desired bytes
  884. *
  885. * Output:
  886. * 0 on success, 1 on failure
  887. */
  888. int PRF(flow *f, uint8_t *secret, int32_t secret_len,
  889. uint8_t *seed1, int32_t seed1_len,
  890. uint8_t *seed2, int32_t seed2_len,
  891. uint8_t *seed3, int32_t seed3_len,
  892. uint8_t *seed4, int32_t seed4_len,
  893. uint8_t *output, int32_t output_len){
  894. int ret = 1;
  895. EVP_MD_CTX *ctx = NULL, *ctx_tmp = NULL, *ctx_init = NULL;
  896. EVP_PKEY *mac_key;
  897. const EVP_MD *md;
  898. if(f == NULL){
  899. md = EVP_sha256();
  900. } else {
  901. md = f->message_digest;
  902. }
  903. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  904. ctx = EVP_MD_CTX_new();
  905. ctx_tmp = EVP_MD_CTX_new();
  906. ctx_init = EVP_MD_CTX_new();
  907. #else
  908. ctx = scalloc(1, sizeof(EVP_MD_CTX));
  909. EVP_MD_CTX_init(ctx);
  910. ctx_tmp = scalloc(1, sizeof(EVP_MD_CTX));
  911. EVP_MD_CTX_init(ctx_tmp);
  912. ctx_init = scalloc(1, sizeof(EVP_MD_CTX));
  913. EVP_MD_CTX_init(ctx_init);
  914. #endif
  915. if (ctx == NULL || ctx_tmp == NULL || ctx_init == NULL)
  916. goto err;
  917. uint8_t A[EVP_MAX_MD_SIZE];
  918. size_t len, A_len;
  919. int chunk = EVP_MD_size(md);
  920. int remaining = output_len;
  921. uint8_t *out = output;
  922. EVP_MD_CTX_set_flags(ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  923. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
  924. /* Calculate first A value */
  925. EVP_DigestSignInit(ctx_init, NULL, md, NULL, mac_key);
  926. EVP_MD_CTX_copy_ex(ctx, ctx_init);
  927. if(seed1 != NULL && seed1_len > 0){
  928. EVP_DigestSignUpdate(ctx, seed1, seed1_len);
  929. }
  930. if(seed2 != NULL && seed2_len > 0){
  931. EVP_DigestSignUpdate(ctx, seed2, seed2_len);
  932. }
  933. if(seed3 != NULL && seed3_len > 0){
  934. EVP_DigestSignUpdate(ctx, seed3, seed3_len);
  935. }
  936. if(seed4 != NULL && seed4_len > 0){
  937. EVP_DigestSignUpdate(ctx, seed4, seed4_len);
  938. }
  939. EVP_DigestSignFinal(ctx, A, &A_len);
  940. //iterate until desired length is achieved
  941. while(remaining > 0){
  942. /* Now compute SHA384(secret, A+seed) */
  943. EVP_MD_CTX_copy_ex(ctx, ctx_init);
  944. EVP_DigestSignUpdate(ctx, A, A_len);
  945. EVP_MD_CTX_copy_ex(ctx_tmp, ctx);
  946. if(seed1 != NULL && seed1_len > 0){
  947. EVP_DigestSignUpdate(ctx, seed1, seed1_len);
  948. }
  949. if(seed2 != NULL && seed2_len > 0){
  950. EVP_DigestSignUpdate(ctx, seed2, seed2_len);
  951. }
  952. if(seed3 != NULL && seed3_len > 0){
  953. EVP_DigestSignUpdate(ctx, seed3, seed3_len);
  954. }
  955. if(seed4 != NULL && seed4_len > 0){
  956. EVP_DigestSignUpdate(ctx, seed4, seed4_len);
  957. }
  958. if(remaining > chunk){
  959. EVP_DigestSignFinal(ctx, out, &len);
  960. out += len;
  961. remaining -= len;
  962. /* Next A value */
  963. EVP_DigestSignFinal(ctx_tmp, A, &A_len);
  964. } else {
  965. EVP_DigestSignFinal(ctx, A, &A_len);
  966. memcpy(out, A, remaining);
  967. remaining -= remaining;
  968. }
  969. }
  970. ret = 0;
  971. err:
  972. EVP_PKEY_free(mac_key);
  973. //Check to see if version is greater than OpenSSL 1.1.0e
  974. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  975. EVP_MD_CTX_free(ctx);
  976. EVP_MD_CTX_free(ctx_tmp);
  977. EVP_MD_CTX_free(ctx_init);
  978. #else
  979. EVP_MD_CTX_cleanup(ctx);
  980. EVP_MD_CTX_cleanup(ctx_tmp);
  981. EVP_MD_CTX_cleanup(ctx_init);
  982. free(ctx);
  983. free(ctx_tmp);
  984. free(ctx_init);
  985. #endif
  986. OPENSSL_cleanse(A, sizeof(A));
  987. return ret;
  988. }
  989. /** After receiving change cipher spec, calculate keys from master secret
  990. *
  991. * Input:
  992. * f: the tagged flow
  993. *
  994. * Output:
  995. * 0 on success, 1 on failure
  996. */
  997. int init_ciphers(flow *f){
  998. EVP_CIPHER_CTX *r_ctx;
  999. EVP_CIPHER_CTX *w_ctx;
  1000. EVP_CIPHER_CTX *w_ctx_srvr;
  1001. EVP_CIPHER_CTX *r_ctx_srvr;
  1002. GCM128_CONTEXT *o_gcm;
  1003. const EVP_CIPHER *c = f->cipher;
  1004. if(c == NULL){
  1005. /*This *shouldn't* happen, but might if a serverHello msg isn't received
  1006. * or if a session is resumed in a strange way */
  1007. return 1;
  1008. }
  1009. /* Generate Keys */
  1010. uint8_t *write_key, *write_iv;
  1011. uint8_t *read_key, *read_iv;
  1012. int32_t mac_len, key_len, iv_len;
  1013. key_len = EVP_CIPHER_key_length(c);
  1014. iv_len = EVP_CIPHER_iv_length(c); //EVP_GCM_TLS_FIXED_IV_LEN;
  1015. mac_len = EVP_MD_size(f->message_digest);
  1016. int32_t total_len = key_len + iv_len + mac_len;
  1017. total_len *= 2;
  1018. uint8_t *key_block = scalloc(1, total_len);
  1019. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  1020. (uint8_t *) TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
  1021. f->server_random, SSL3_RANDOM_SIZE,
  1022. f->client_random, SSL3_RANDOM_SIZE,
  1023. NULL, 0,
  1024. key_block, total_len);
  1025. #ifdef DEBUG
  1026. printf("master secret: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  1027. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  1028. printf("%02x ", f->master_secret[i]);
  1029. }
  1030. printf("\n");
  1031. printf("client random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  1032. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  1033. printf("%02x ", f->client_random[i]);
  1034. }
  1035. printf("\n");
  1036. printf("server random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  1037. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  1038. printf("%02x ", f->server_random[i]);
  1039. }
  1040. printf("\n");
  1041. printf("keyblock: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  1042. for(int i=0; i< total_len; i++){
  1043. printf("%02x ", key_block[i]);
  1044. }
  1045. printf("\n");
  1046. #endif
  1047. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  1048. write_key = key_block;
  1049. read_key = key_block + key_len;
  1050. write_iv = key_block + 2*key_len;
  1051. read_iv = key_block + 2*key_len + iv_len;
  1052. /* Initialize Cipher Contexts */
  1053. r_ctx = EVP_CIPHER_CTX_new();
  1054. w_ctx = EVP_CIPHER_CTX_new();
  1055. EVP_CIPHER_CTX_init(r_ctx);
  1056. EVP_CIPHER_CTX_init(w_ctx);
  1057. w_ctx_srvr = EVP_CIPHER_CTX_new();
  1058. r_ctx_srvr = EVP_CIPHER_CTX_new();
  1059. EVP_CIPHER_CTX_init(w_ctx_srvr);
  1060. EVP_CIPHER_CTX_init(r_ctx_srvr);
  1061. /* Initialize MACs --- not needed for aes_256_gcm
  1062. write_mac = key_block + 2*key_len + 2*iv_len;
  1063. read_mac = key_block + 2*key_len + 2*iv_len + mac_len;
  1064. read_mac_ctx = EVP_MD_CTX_create();
  1065. write_mac_ctx = EVP_MD_CTX_create();
  1066. read_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, read_mac, mac_len);
  1067. write_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, write_mac, mac_len);
  1068. EVP_DigestSignInit(read_mac_ctx, NULL, EVP_sha384(), NULL, read_mac_key);
  1069. EVP_DigestSignInit(write_mac_ctx, NULL, EVP_sha384(), NULL, write_mac_key);
  1070. EVP_PKEY_free(read_mac_key);
  1071. EVP_PKEY_free(write_mac_key);*/
  1072. #ifdef DEBUG_HS_EXTRA
  1073. {
  1074. int i;
  1075. fprintf(stderr, "EVP_CipherInit_ex(r_ctx,c,key=,iv=,which)\n");
  1076. fprintf(stderr, "\tkey= ");
  1077. for (i = 0; i < c->key_len; i++)
  1078. fprintf(stderr, "%02x", read_key[i]);
  1079. fprintf(stderr, "\n");
  1080. fprintf(stderr, "\t iv= ");
  1081. for (i = 0; i < c->iv_len; i++)
  1082. fprintf(stderr, "%02x", read_iv[i]);
  1083. fprintf(stderr, "\n");
  1084. }
  1085. {
  1086. int i;
  1087. fprintf(stderr, "EVP_CipherInit_ex(w_ctx,c,key=,iv=,which)\n");
  1088. fprintf(stderr, "\tkey= ");
  1089. for (i = 0; i < c->key_len; i++)
  1090. fprintf(stderr, "%02x", write_key[i]);
  1091. fprintf(stderr, "\n");
  1092. fprintf(stderr, "\t iv= ");
  1093. for (i = 0; i < c->iv_len; i++)
  1094. fprintf(stderr, "%02x", write_iv[i]);
  1095. fprintf(stderr, "\n");
  1096. }
  1097. #endif
  1098. if(!EVP_CipherInit_ex(r_ctx, c, NULL, read_key, NULL, 0)){
  1099. printf("FAIL r_ctx\n");
  1100. }
  1101. if(!EVP_CipherInit_ex(w_ctx, c, NULL, write_key, NULL, 1)){
  1102. printf("FAIL w_ctx\n");
  1103. }
  1104. if(!EVP_CipherInit_ex(w_ctx_srvr, c, NULL, read_key, NULL, 1)){
  1105. printf("FAIL w_ctx_srvr\n");
  1106. }
  1107. if(!EVP_CipherInit_ex(r_ctx_srvr, c, NULL, write_key, NULL, 0)){
  1108. printf("FAIL r_ctx_srvr\n");
  1109. }
  1110. EVP_CIPHER_CTX_ctrl(r_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  1111. EVP_CIPHER_CTX_ctrl(w_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  1112. EVP_CIPHER_CTX_ctrl(w_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  1113. EVP_CIPHER_CTX_ctrl(r_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  1114. /* Set up gcm cipher ctx for partial decryption */
  1115. AES_KEY *key = scalloc(1, sizeof(AES_KEY));
  1116. AES_set_encrypt_key(read_key, EVP_CIPHER_CTX_key_length(r_ctx)*8, key);
  1117. o_gcm = CRYPTO_gcm128_new( key, (block128_f) AES_encrypt);
  1118. f->gcm_ctx_key = key;
  1119. iv_len = EVP_CIPHER_CTX_iv_length(r_ctx);
  1120. f->gcm_ctx_iv = smalloc(iv_len);
  1121. f->gcm_ctx_ivlen = iv_len;
  1122. memcpy(f->gcm_ctx_iv, read_iv, EVP_GCM_TLS_FIXED_IV_LEN);
  1123. /* Assign ctxs to flow structure */
  1124. f->clnt_read_ctx = r_ctx;
  1125. f->clnt_write_ctx = w_ctx;
  1126. f->srvr_read_ctx = r_ctx_srvr;
  1127. f->srvr_write_ctx = w_ctx_srvr;
  1128. f->gcm_ctx_out = o_gcm;
  1129. free(key_block);
  1130. return 0;
  1131. }
  1132. /* Generate the keys for a client's super encryption layer
  1133. *
  1134. * The header of each downstream slitheen data chunk is 16 bytes and encrypted with
  1135. * a 256 bit AES key
  1136. *
  1137. * The body of each downstream chunk is CBC encrypted with a 256 bit AES key
  1138. *
  1139. * The last 16 bytes of the body is a MAC over the body
  1140. *
  1141. */
  1142. void generate_client_super_keys(uint8_t *secret, client *c){
  1143. EVP_MD_CTX *mac_ctx;
  1144. const EVP_MD *md = EVP_sha256();
  1145. FILE *fp;
  1146. //extract shared secret from SLITHEEN_ID
  1147. uint8_t shared_secret[16];
  1148. byte privkey[PTWIST_BYTES];
  1149. fp = fopen("privkey", "rb");
  1150. if (fp == NULL) {
  1151. perror("fopen");
  1152. exit(1);
  1153. }
  1154. if(fread(privkey, PTWIST_BYTES, 1, fp) < 1){
  1155. perror("fread");
  1156. exit(1);
  1157. }
  1158. fclose(fp);
  1159. /* check tag*/
  1160. if(check_tag(shared_secret, privkey, secret, (const byte *)"context", 7)){
  1161. //something went wrong O.o
  1162. printf("Error extracting secret from tag\n");
  1163. return;
  1164. }
  1165. #ifdef DEBUG
  1166. printf("Shared secret: ");
  1167. for(int i=0; i< 16; i++){
  1168. printf("%02x ", shared_secret[i]);
  1169. }
  1170. printf("\n");
  1171. #endif
  1172. /* Generate Keys */
  1173. uint8_t *hdr_key, *bdy_key;
  1174. uint8_t *mac_secret;
  1175. EVP_PKEY *mac_key;
  1176. int32_t mac_len, key_len;
  1177. key_len = EVP_CIPHER_key_length(EVP_aes_256_cbc());
  1178. mac_len = EVP_MD_size(md);
  1179. int32_t total_len = 2*key_len + mac_len;
  1180. uint8_t *key_block = scalloc(1, total_len);
  1181. PRF(NULL, shared_secret, SLITHEEN_SUPER_SECRET_SIZE,
  1182. (uint8_t *) SLITHEEN_SUPER_CONST, SLITHEEN_SUPER_CONST_SIZE,
  1183. NULL, 0,
  1184. NULL, 0,
  1185. NULL, 0,
  1186. key_block, total_len);
  1187. #ifdef DEBUG
  1188. printf("slitheend id: \n");
  1189. for(int i=0; i< SLITHEEN_ID_LEN; i++){
  1190. printf("%02x ", secret[i]);
  1191. }
  1192. printf("\n");
  1193. printf("keyblock: \n");
  1194. for(int i=0; i< total_len; i++){
  1195. printf("%02x ", key_block[i]);
  1196. }
  1197. printf("\n");
  1198. #endif
  1199. hdr_key = key_block;
  1200. bdy_key = key_block + key_len;
  1201. mac_secret = key_block + 2*key_len;
  1202. /* Initialize MAC Context */
  1203. mac_ctx = EVP_MD_CTX_create();
  1204. EVP_DigestInit_ex(mac_ctx, md, NULL);
  1205. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, mac_secret, mac_len);
  1206. EVP_DigestSignInit(mac_ctx, NULL, md, NULL, mac_key);
  1207. c->header_key = smalloc(key_len);
  1208. c->body_key = smalloc(key_len);
  1209. memcpy(c->header_key, hdr_key, key_len);
  1210. memcpy(c->body_key, bdy_key, key_len);
  1211. c->mac_ctx = mac_ctx;
  1212. //Free everything
  1213. free(key_block);
  1214. EVP_PKEY_free(mac_key);
  1215. return;
  1216. }
  1217. int super_encrypt(client *c, uint8_t *data, uint32_t len){
  1218. int retval = 1;
  1219. EVP_CIPHER_CTX *hdr_ctx = NULL;
  1220. EVP_CIPHER_CTX *bdy_ctx = NULL;
  1221. int32_t out_len;
  1222. size_t mac_len;
  1223. uint8_t *p = data;
  1224. uint8_t output[EVP_MAX_MD_SIZE];
  1225. //first encrypt the header
  1226. #ifdef DEBUG_DOWN
  1227. printf("Plaintext Header:\n");
  1228. for(int i=0; i< SLITHEEN_HEADER_LEN; i++){
  1229. printf("%02x ", p[i]);
  1230. }
  1231. printf("\n");
  1232. #endif
  1233. hdr_ctx = EVP_CIPHER_CTX_new();
  1234. if(c->header_key == NULL){
  1235. printf("c->header_key is null\n");
  1236. retval = 0;
  1237. goto end;
  1238. }
  1239. EVP_CipherInit_ex(hdr_ctx, EVP_aes_256_cbc(), NULL, c->header_key, NULL, 1);
  1240. if(!EVP_CipherUpdate(hdr_ctx, p, &out_len, p, SLITHEEN_HEADER_LEN)){
  1241. printf("Failed!\n");
  1242. retval = 0;
  1243. goto end;
  1244. }
  1245. #ifdef DEBUG_DOWN
  1246. printf("Encrypted Header (%d bytes)\n", out_len);
  1247. for(int i=0; i< out_len; i++){
  1248. printf("%02x ", p[i]);
  1249. }
  1250. printf("\n");
  1251. #endif
  1252. if(len == 0){ //only encrypt header: body contains garbage bytes
  1253. retval = 1;
  1254. goto end;
  1255. }
  1256. //encrypt the body
  1257. p += SLITHEEN_HEADER_LEN;
  1258. //generate IV
  1259. RAND_bytes(p, 16);
  1260. //set up cipher ctx
  1261. bdy_ctx = EVP_CIPHER_CTX_new();
  1262. EVP_CipherInit_ex(bdy_ctx, EVP_aes_256_cbc(), NULL, c->body_key, p, 1);
  1263. p+= 16;
  1264. #ifdef DEBUG
  1265. printf("Plaintext:\n");
  1266. for(int i=0; i< len; i++){
  1267. printf("%02x ", p[i]);
  1268. }
  1269. printf("\n");
  1270. #endif
  1271. if(!EVP_CipherUpdate(bdy_ctx, p, &out_len, p, len)){
  1272. printf("Failed!\n");
  1273. retval = 0;
  1274. goto end;
  1275. }
  1276. #ifdef DEBUG
  1277. printf("Encrypted %d bytes\n", out_len);
  1278. printf("Encrypted data:\n");
  1279. for(int i=0; i< out_len; i++){
  1280. printf("%02x ", p[i]);
  1281. }
  1282. printf("\n");
  1283. #endif
  1284. //MAC at the end
  1285. EVP_MD_CTX *mac_ctx = NULL;
  1286. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  1287. mac_ctx = EVP_MD_CTX_new();
  1288. #else
  1289. mac_ctx = scalloc(1, sizeof(EVP_MD_CTX));
  1290. EVP_MD_CTX_init(mac_ctx);
  1291. #endif
  1292. EVP_MD_CTX_copy_ex(mac_ctx, c->mac_ctx);
  1293. EVP_DigestSignUpdate(mac_ctx, p, out_len);
  1294. EVP_DigestSignFinal(mac_ctx, output, &mac_len);
  1295. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  1296. EVP_MD_CTX_free(mac_ctx);
  1297. #else
  1298. EVP_MD_CTX_cleanup(mac_ctx);
  1299. free(mac_ctx);
  1300. #endif
  1301. p += out_len;
  1302. memcpy(p, output, 16);
  1303. #ifdef DEBUG_PARSE
  1304. printf("Computed mac:\n");
  1305. for(int i=0; i< 16; i++){
  1306. printf("%02x ", output[i]);
  1307. }
  1308. printf("\n");
  1309. fflush(stdout);
  1310. #endif
  1311. end:
  1312. if(hdr_ctx != NULL){
  1313. EVP_CIPHER_CTX_cleanup(hdr_ctx);
  1314. OPENSSL_free(hdr_ctx);
  1315. }
  1316. if(bdy_ctx != NULL){
  1317. EVP_CIPHER_CTX_cleanup(bdy_ctx);
  1318. OPENSSL_free(bdy_ctx);
  1319. }
  1320. return retval;
  1321. }
  1322. /** Checks a handshake message to see if it is tagged or a
  1323. * recognized flow. If the client random nonce is tagged,
  1324. * adds the flow to the flow table to be tracked.
  1325. *
  1326. * Inputs:
  1327. * info: the processed packet
  1328. * f: the tagged flow
  1329. *
  1330. * Output:
  1331. * none
  1332. */
  1333. int check_handshake(struct packet_info *info){
  1334. FILE *fp;
  1335. int res, code;
  1336. uint8_t *hello_rand;
  1337. const struct handshake_header *handshake_hdr;
  1338. byte privkey[PTWIST_BYTES];
  1339. byte key[16];
  1340. uint8_t *p = info->app_data + RECORD_HEADER_LEN;
  1341. handshake_hdr = (struct handshake_header*) p;
  1342. code = handshake_hdr->type;
  1343. res = 1;
  1344. if (code == 0x01){
  1345. p += CLIENT_HELLO_HEADER_LEN;
  1346. //now pointing to hello random :D
  1347. hello_rand = p;
  1348. p += 4; //skipping time bytes
  1349. /* Load the private key */
  1350. fp = fopen("privkey", "rb");
  1351. if (fp == NULL) {
  1352. perror("fopen");
  1353. exit(1);
  1354. }
  1355. res = fread(privkey, PTWIST_BYTES, 1, fp);
  1356. if (res < 1) {
  1357. perror("fread");
  1358. exit(1);
  1359. }
  1360. fclose(fp);
  1361. /* check tag*/
  1362. uint8_t context[4 + SSL3_RANDOM_SIZE - PTWIST_TAG_BYTES];
  1363. memcpy(context, &info->ip_hdr->dst.s_addr, 4);
  1364. memcpy(context + 4, hello_rand, SSL3_RANDOM_SIZE - PTWIST_TAG_BYTES);
  1365. res = check_tag(key, privkey, p, (const byte *)context, sizeof(context));
  1366. //res = check_tag(key, privkey, p, (const byte *)"context", 7);//for phantomjs testing
  1367. if (!res) {
  1368. #ifdef DEBUG_HS
  1369. printf("Received tagged flow! (key =");
  1370. for(int i=0; i<16;i++){
  1371. printf(" %02x", key[i]);
  1372. }
  1373. printf(")\n");
  1374. #endif
  1375. /* If flow is not in table, save it */
  1376. flow *flow_ptr = check_flow(info);
  1377. if(flow_ptr == NULL){
  1378. flow_ptr = add_flow(info);
  1379. if(flow_ptr == NULL){
  1380. fprintf(stderr, "Memory failure\n");
  1381. return 0;
  1382. }
  1383. for(int i=0; i<16; i++){
  1384. flow_ptr->key[i] = key[i];
  1385. }
  1386. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  1387. #ifdef DEBUG
  1388. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  1389. printf("%02x ", hello_rand[i]);
  1390. }
  1391. printf("\n");
  1392. printf("Saved new flow\n");
  1393. #endif
  1394. flow_ptr->ref_ctr--;
  1395. } else { /* else update saved flow with new key and random nonce */
  1396. for(int i=0; i<16; i++){
  1397. flow_ptr->key[i] = key[i];
  1398. }
  1399. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  1400. flow_ptr->ref_ctr--;
  1401. printf("Flow updated in check_flow. %p ref_ctr %d\n", flow_ptr, flow_ptr->ref_ctr);
  1402. }
  1403. }
  1404. }
  1405. return !res;
  1406. }
  1407. /* Check the given tag with the given context and private key. Return 0
  1408. if the tag is properly formed, non-0 if not. If the tag is correct,
  1409. set key to the resulting secret key. */
  1410. int check_tag(byte key[16], const byte privkey[PTWIST_BYTES],
  1411. const byte tag[PTWIST_TAG_BYTES], const byte *context,
  1412. size_t context_len)
  1413. {
  1414. int ret = -1;
  1415. byte sharedsec[PTWIST_BYTES+context_len];
  1416. byte taghashout[32];
  1417. #if PTWIST_PUZZLE_STRENGTH > 0
  1418. byte hashout[32];
  1419. size_t puzzle_len = 16+PTWIST_RESP_BYTES;
  1420. byte value_to_hash[puzzle_len];
  1421. unsigned int firstbits;
  1422. int firstpass = 0;
  1423. #endif
  1424. /* Compute the shared secret privkey*TAG */
  1425. ptwist_pointmul(sharedsec, tag, privkey);
  1426. /* Create the hash tag keys */
  1427. memmove(sharedsec+PTWIST_BYTES, context, context_len);
  1428. SHA256(sharedsec, PTWIST_BYTES + context_len, taghashout);
  1429. #if PTWIST_PUZZLE_STRENGTH > 0
  1430. /* Construct the proposed solution to the puzzle */
  1431. memmove(value_to_hash, taghashout, 16);
  1432. memmove(value_to_hash+16, tag+PTWIST_BYTES, PTWIST_RESP_BYTES);
  1433. value_to_hash[16+PTWIST_RESP_BYTES-1] &= PTWIST_RESP_MASK;
  1434. /* Hash the proposed solution and see if it is correct; that is, the
  1435. * hash should start with PTWIST_PUZZLE_STRENGTH bits of 0s,
  1436. * followed by the last PTWIST_HASH_SHOWBITS of the tag. */
  1437. md_map_sh256(hashout, value_to_hash, puzzle_len);
  1438. #if PTWIST_PUZZLE_STRENGTH < 32
  1439. /* This assumes that you're on an architecture that doesn't care
  1440. * about alignment, and is little endian. */
  1441. firstbits = *(unsigned int*)hashout;
  1442. if ((firstbits & PTWIST_PUZZLE_MASK) == 0) {
  1443. firstpass = 1;
  1444. }
  1445. #else
  1446. #error "Code assumes PTWIST_PUZZLE_STRENGTH < 32"
  1447. #endif
  1448. if (firstpass) {
  1449. bn_t Hbn, Tbn;
  1450. bn_new(Hbn);
  1451. bn_new(Tbn);
  1452. hashout[PTWIST_HASH_TOTBYTES-1] &= PTWIST_HASH_MASK;
  1453. bn_read_bin(Hbn, hashout, PTWIST_HASH_TOTBYTES, BN_POS);
  1454. bn_rsh(Hbn, Hbn, PTWIST_PUZZLE_STRENGTH);
  1455. bn_read_bin(Tbn, tag+PTWIST_BYTES, PTWIST_TAG_BYTES-PTWIST_BYTES,
  1456. BN_POS);
  1457. bn_rsh(Tbn, Tbn, PTWIST_RESP_BITS);
  1458. ret = (bn_cmp(Tbn,Hbn) != CMP_EQ);
  1459. bn_free(Hbn);
  1460. bn_free(Tbn);
  1461. }
  1462. #else
  1463. /* We're not using a client puzzle, so just check that the first
  1464. * PTWIST_HASH_SHOWBITS bits of the above hash fill out the rest
  1465. * of the tag. If there's no puzzle, PTWIST_HASH_SHOWBITS must be
  1466. * a multiple of 8. */
  1467. ret = (memcmp(tag+PTWIST_BYTES, taghashout, PTWIST_HASH_SHOWBITS/8) != 0);
  1468. #endif
  1469. if (ret == 0) {
  1470. memmove(key, taghashout+16, 16);
  1471. }
  1472. return ret;
  1473. }
  1474. /* Modified GCM cipher function */
  1475. /*
  1476. * Handle TLS GCM packet format. This consists of the last portion of the IV
  1477. * followed by the payload and finally the tag. On encrypt generate IV,
  1478. * encrypt payload and write the tag. On verify retrieve IV, decrypt payload
  1479. * and verify tag.
  1480. */
  1481. #define EVP_C_DATA(kstruct, ctx) \
  1482. ((kstruct *)EVP_CIPHER_CTX_get_cipher_data(ctx))
  1483. /*
  1484. * Handle TLS GCM packet format. This consists of the last portion of the IV
  1485. * followed by the payload and finally the tag. On encrypt generate IV,
  1486. * encrypt payload and write the tag. On verify retrieve IV, decrypt payload
  1487. * and verify tag.
  1488. */
  1489. #define GCM_CTX_LEN 380 + sizeof(block128_f)
  1490. int partial_aes_gcm_tls_cipher(flow *f, unsigned char *out,
  1491. const unsigned char *in, size_t len, uint8_t enc)
  1492. {
  1493. // Encrypt/decrypt must be performed in place
  1494. int rv = -1;
  1495. if (out != in
  1496. || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN))
  1497. return -1;
  1498. //set IV
  1499. uint8_t *iv = smalloc(f->gcm_ctx_ivlen);
  1500. memcpy(iv, f->gcm_ctx_iv, EVP_GCM_TLS_FIXED_IV_LEN);
  1501. if(enc){
  1502. memcpy(iv + f->gcm_ctx_ivlen - EVP_GCM_TLS_EXPLICIT_IV_LEN , out, EVP_GCM_TLS_EXPLICIT_IV_LEN);
  1503. memcpy(out, iv + f->gcm_ctx_ivlen - EVP_GCM_TLS_EXPLICIT_IV_LEN, EVP_GCM_TLS_EXPLICIT_IV_LEN);
  1504. } else {
  1505. memcpy(iv + f->gcm_ctx_ivlen - EVP_GCM_TLS_EXPLICIT_IV_LEN , f->partial_record, EVP_GCM_TLS_EXPLICIT_IV_LEN);
  1506. }
  1507. CRYPTO_gcm128_setiv(f->gcm_ctx_out, iv, f->gcm_ctx_ivlen);
  1508. // Fix buffer and length to point to payload
  1509. in += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1510. out += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1511. len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1512. //set AAD
  1513. uint8_t buf[13], seq[8];
  1514. memcpy(seq, f->read_seq, 8);
  1515. for(int i=7; i>=0; i--){
  1516. --seq[i];
  1517. if(seq[i] != 0xff)
  1518. break;
  1519. }
  1520. memcpy(buf, seq, 8);
  1521. buf[8] = 0x17;
  1522. buf[9] = 0x03;
  1523. buf[10] = 0x03;
  1524. buf[11] = len >> 8; //len >> 8;
  1525. buf[12] = len & 0xff;//len *0xff;
  1526. CRYPTO_gcm128_aad(f->gcm_ctx_out, buf, 13);
  1527. if(enc){
  1528. if ((len > 16) && CRYPTO_gcm128_encrypt(f->gcm_ctx_out, in, out, len))
  1529. goto err;
  1530. } else {
  1531. if ((len > 16) && CRYPTO_gcm128_decrypt(f->gcm_ctx_out, in, out, len))
  1532. goto err;
  1533. }
  1534. rv = len;
  1535. err:
  1536. free(iv);
  1537. return rv;
  1538. }
  1539. /*
  1540. * Computes the tag for a (now full) record that was split in multiple parts across
  1541. * two or more packets.
  1542. *
  1543. * Input:
  1544. * f: The corresponding flow
  1545. * tag: a pointer to where the tag will be placed
  1546. * len: the length of the original encryption
  1547. */
  1548. void partial_aes_gcm_tls_tag(flow *f, unsigned char *tag, size_t len){
  1549. CRYPTO_gcm128_tag(f->gcm_ctx_out, tag, EVP_GCM_TLS_TAG_LEN);
  1550. }