crypto.c 53 KB

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