crypto.c 49 KB

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