crypto.c 51 KB

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