crypto.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. /* Name: crypto.c
  2. * Author: Cecylia Bocovich <cbocovic@uwaterloo.ca>
  3. *
  4. * This file contains code for checking tagged flows, processing handshake
  5. * messages, and computing the master secret for a TLS session.
  6. *
  7. * Some code in this document is based on the OpenSSL source files:
  8. * crypto/ec/ec_key.c
  9. * crypto/dh/dh_key.c
  10. * */
  11. /*
  12. * Written by Nils Larsch for the OpenSSL project.
  13. */
  14. /* ====================================================================
  15. * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
  16. *
  17. * Redistribution and use in source and binary forms, with or without
  18. * modification, are permitted provided that the following conditions
  19. * are met:
  20. *
  21. * 1. Redistributions of source code must retain the above copyright
  22. * notice, this list of conditions and the following disclaimer.
  23. *
  24. * 2. Redistributions in binary form must reproduce the above copyright
  25. * notice, this list of conditions and the following disclaimer in
  26. * the documentation and/or other materials provided with the
  27. * distribution.
  28. *
  29. * 3. All advertising materials mentioning features or use of this
  30. * software must display the following acknowledgment:
  31. * "This product includes software developed by the OpenSSL Project
  32. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  33. *
  34. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  35. * endorse or promote products derived from this software without
  36. * prior written permission. For written permission, please contact
  37. * openssl-core@openssl.org.
  38. *
  39. * 5. Products derived from this software may not be called "OpenSSL"
  40. * nor may "OpenSSL" appear in their names without prior written
  41. * permission of the OpenSSL Project.
  42. *
  43. * 6. Redistributions of any form whatsoever must retain the following
  44. * acknowledgment:
  45. * "This product includes software developed by the OpenSSL Project
  46. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  47. *
  48. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  49. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  52. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  54. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  55. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  56. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  57. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  58. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  59. * OF THE POSSIBILITY OF SUCH DAMAGE.
  60. * ====================================================================
  61. *
  62. * This product includes cryptographic software written by Eric Young
  63. * (eay@cryptsoft.com). This product includes software written by Tim
  64. * Hudson (tjh@cryptsoft.com).
  65. *
  66. */
  67. /* ====================================================================
  68. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  69. * Portions originally developed by SUN MICROSYSTEMS, INC., and
  70. * contributed to the OpenSSL project.
  71. */
  72. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  73. * All rights reserved.
  74. *
  75. * This package is an SSL implementation written
  76. * by Eric Young (eay@cryptsoft.com).
  77. * The implementation was written so as to conform with Netscapes SSL.
  78. *
  79. * This library is free for commercial and non-commercial use as long as
  80. * the following conditions are aheared to. The following conditions
  81. * apply to all code found in this distribution, be it the RC4, RSA,
  82. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  83. * included with this distribution is covered by the same copyright terms
  84. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  85. *
  86. * Copyright remains Eric Young's, and as such any Copyright notices in
  87. * the code are not to be removed.
  88. * If this package is used in a product, Eric Young should be given attribution
  89. * as the author of the parts of the library used.
  90. * This can be in the form of a textual message at program startup or
  91. * in documentation (online or textual) provided with the package.
  92. *
  93. * Redistribution and use in source and binary forms, with or without
  94. * modification, are permitted provided that the following conditions
  95. * are met:
  96. * 1. Redistributions of source code must retain the copyright
  97. * notice, this list of conditions and the following disclaimer.
  98. * 2. Redistributions in binary form must reproduce the above copyright
  99. * notice, this list of conditions and the following disclaimer in the
  100. * documentation and/or other materials provided with the distribution.
  101. * 3. All advertising materials mentioning features or use of this software
  102. * must display the following acknowledgement:
  103. * "This product includes cryptographic software written by
  104. * Eric Young (eay@cryptsoft.com)"
  105. * The word 'cryptographic' can be left out if the rouines from the library
  106. * being used are not cryptographic related :-).
  107. * 4. If you include any Windows specific code (or a derivative thereof) from
  108. * the apps directory (application code) you must include an acknowledgement:
  109. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  110. *
  111. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  112. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  113. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  114. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  115. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  116. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  117. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  118. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  119. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  120. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  121. * SUCH DAMAGE.
  122. *
  123. * The licence and distribution terms for any publically available version or
  124. * derivative of this code cannot be changed. i.e. this code cannot simply be
  125. * copied and put under another distribution licence
  126. * [including the GNU Public Licence.]
  127. */
  128. #include <stdio.h>
  129. #include <stdlib.h>
  130. #include <assert.h>
  131. #include <string.h>
  132. #include <openssl/evp.h>
  133. #include <openssl/dh.h>
  134. #include <openssl/bn.h>
  135. #include <openssl/err.h>
  136. #include <openssl/rand.h>
  137. #include <openssl/ssl.h>
  138. #include <openssl/sha.h>
  139. #include "ptwist.h"
  140. #include "crypto.h"
  141. #include "flow.h"
  142. #include "slitheen.h"
  143. #include "util.h"
  144. #include "relay.h"
  145. #define NID_sect163k1 721
  146. #define NID_sect163r1 722
  147. #define NID_sect163r2 723
  148. #define NID_sect193r1 724
  149. #define NID_sect193r2 725
  150. #define NID_sect233k1 726
  151. #define NID_sect233r1 727
  152. #define NID_sect239k1 728
  153. #define NID_sect283k1 729
  154. #define NID_sect283r1 730
  155. #define NID_sect409k1 731
  156. #define NID_sect409r1 732
  157. #define NID_sect571k1 733
  158. #define NID_sect571r1 734
  159. #define NID_secp160k1 708
  160. #define NID_secp160r1 709
  161. #define NID_secp160r2 710
  162. #define NID_secp192k1 711
  163. #define NID_X9_62_prime192v1 409
  164. #define NID_secp224k1 712
  165. #define NID_secp224r1 713
  166. #define NID_secp256k1 714
  167. #define NID_X9_62_prime256v1 415
  168. #define NID_secp384r1 715
  169. #define NID_secp521r1 716
  170. #define NID_brainpoolP256r1 927
  171. #define NID_brainpoolP384r1 931
  172. #define NID_brainpoolP512r1 933
  173. static int nid_list[] = {
  174. NID_sect163k1, /* sect163k1 (1) */
  175. NID_sect163r1, /* sect163r1 (2) */
  176. NID_sect163r2, /* sect163r2 (3) */
  177. NID_sect193r1, /* sect193r1 (4) */
  178. NID_sect193r2, /* sect193r2 (5) */
  179. NID_sect233k1, /* sect233k1 (6) */
  180. NID_sect233r1, /* sect233r1 (7) */
  181. NID_sect239k1, /* sect239k1 (8) */
  182. NID_sect283k1, /* sect283k1 (9) */
  183. NID_sect283r1, /* sect283r1 (10) */
  184. NID_sect409k1, /* sect409k1 (11) */
  185. NID_sect409r1, /* sect409r1 (12) */
  186. NID_sect571k1, /* sect571k1 (13) */
  187. NID_sect571r1, /* sect571r1 (14) */
  188. NID_secp160k1, /* secp160k1 (15) */
  189. NID_secp160r1, /* secp160r1 (16) */
  190. NID_secp160r2, /* secp160r2 (17) */
  191. NID_secp192k1, /* secp192k1 (18) */
  192. NID_X9_62_prime192v1, /* secp192r1 (19) */
  193. NID_secp224k1, /* secp224k1 (20) */
  194. NID_secp224r1, /* secp224r1 (21) */
  195. NID_secp256k1, /* secp256k1 (22) */
  196. NID_X9_62_prime256v1, /* secp256r1 (23) */
  197. NID_secp384r1, /* secp384r1 (24) */
  198. NID_secp521r1, /* secp521r1 (25) */
  199. NID_brainpoolP256r1, /* brainpoolP256r1 (26) */
  200. NID_brainpoolP384r1, /* brainpoolP384r1 (27) */
  201. NID_brainpoolP512r1 /* brainpool512r1 (28) */
  202. };
  203. /** Updates the hash of all TLS handshake messages upon the
  204. * receipt of a new message. This hash is eventually used
  205. * to verify the TLS Finished message
  206. *
  207. * Inputs:
  208. * f: the tagged flow
  209. * hs: A pointer to the start of the handshake message
  210. *
  211. * Output:
  212. * 0 on success, 1 on failure
  213. */
  214. int update_finish_hash(flow *f, uint8_t *hs){
  215. //find handshake length
  216. const struct handshake_header *hs_hdr;
  217. uint8_t *p = hs;
  218. hs_hdr = (struct handshake_header*) p;
  219. uint32_t hs_len = HANDSHAKE_MESSAGE_LEN(hs_hdr);
  220. EVP_DigestUpdate(f->finish_md_ctx, hs, hs_len+4);
  221. #ifdef DEBUG
  222. printf("SLITHEEN: adding to finish mac computation:\n");
  223. for(int i=0; i< hs_len + 4; i++){
  224. printf("%02x ", hs[i]);
  225. }
  226. printf("\n");
  227. #endif
  228. return 0;
  229. }
  230. /** Extracts the server parameters from the server key
  231. * exchange message
  232. *
  233. * Inputs:
  234. * f: the tagged flow
  235. * hs: the beginning of the server key exchange
  236. * handshake message
  237. *
  238. * Output:
  239. * 0 on success, 1 on failure
  240. */
  241. int extract_parameters(flow *f, uint8_t *hs){
  242. uint8_t *p;
  243. long i;
  244. int ok=1;
  245. p = hs + HANDSHAKE_HEADER_LEN;
  246. if(f->keyex_alg == 1){
  247. DH *dh;
  248. if((dh = DH_new()) == NULL){
  249. return 1;
  250. }
  251. /* Extract prime modulus */
  252. n2s(p,i);
  253. if(!(dh->p = BN_bin2bn(p,i,NULL))){
  254. return 1;
  255. }
  256. p += i;
  257. /* Extract generator */
  258. n2s(p,i);
  259. if(!(dh->g = BN_bin2bn(p,i,NULL))){
  260. return 1;
  261. }
  262. p += i;
  263. /* Extract server public value */
  264. n2s(p,i);
  265. if(!(dh->pub_key = BN_bin2bn(p,i,NULL))){
  266. return 1;
  267. }
  268. f->dh = dh;
  269. } else if (f->keyex_alg == 2){
  270. EC_KEY *ecdh;
  271. EC_GROUP *ngroup;
  272. const EC_GROUP *group;
  273. BN_CTX *bn_ctx = NULL;
  274. EC_POINT *srvr_ecpoint = NULL;
  275. int curve_nid = 0;
  276. int encoded_pt_len = 0;
  277. if((ecdh = EC_KEY_new()) == NULL) {
  278. SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
  279. goto err;
  280. }
  281. if(p[0] != 0x03){//not a named curve
  282. goto err;
  283. }
  284. //int curve_id = (p[1] << 8) + p[2];
  285. int curve_id = *(p+2);
  286. if((curve_id < 0) || ((unsigned int)curve_id >
  287. sizeof(nid_list) / sizeof(nid_list[0]))){
  288. goto err;
  289. }
  290. curve_nid = nid_list[curve_id-1];
  291. /* Extract curve
  292. if(!tls1_check_curve(s, p, 3)) {
  293. goto err;
  294. }
  295. if((*(p+2) < 1) || ((unsigned int) (*(p+2)) > sizeof(nid_list) / sizeof(nid_list[0]))){
  296. goto err;
  297. }
  298. curve_nid = nid_list[*(p+2)];
  299. */
  300. ngroup = EC_GROUP_new_by_curve_name(curve_nid);
  301. if(ngroup == NULL){
  302. goto err;
  303. }
  304. if(EC_KEY_set_group(ecdh, ngroup) == 0){
  305. goto err;
  306. }
  307. EC_GROUP_free(ngroup);
  308. group = EC_KEY_get0_group(ecdh);
  309. p += 3;
  310. /* Get EC point */
  311. if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
  312. ((bn_ctx = BN_CTX_new()) == NULL)) {
  313. goto err;
  314. }
  315. encoded_pt_len = *p;
  316. p += 1;
  317. if(EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len,
  318. bn_ctx) == 0){
  319. goto err;
  320. }
  321. p += encoded_pt_len;
  322. EC_KEY_set_public_key(ecdh, srvr_ecpoint);
  323. f->ecdh = ecdh;
  324. ecdh = NULL;
  325. BN_CTX_free(bn_ctx);
  326. bn_ctx = NULL;
  327. EC_POINT_free(srvr_ecpoint);
  328. srvr_ecpoint = NULL;
  329. ok=0;
  330. err:
  331. if(bn_ctx != NULL){
  332. BN_CTX_free(bn_ctx);
  333. }
  334. if(srvr_ecpoint != NULL){
  335. EC_POINT_free(srvr_ecpoint);
  336. }
  337. if(ecdh != NULL){
  338. EC_KEY_free(ecdh);
  339. }
  340. }
  341. return ok;
  342. }
  343. /* Encrypt/Decrypt a TLS record
  344. *
  345. * Inputs:
  346. * f: the tagged flow
  347. * input: a pointer to the data that is to be encrypted/
  348. * decrypted
  349. * output: a pointer to where the data should be written
  350. * after it is encrypted or decrypted
  351. * len: the length of the data
  352. * incoming: the direction of the record
  353. * type: the type of the TLS record
  354. * enc: 1 for encryption, 0 for decryption
  355. *
  356. * Output:
  357. * length of the output data
  358. */
  359. int encrypt(flow *f, uint8_t *input, uint8_t *output, int32_t len, int32_t incoming, int32_t type, int32_t enc){
  360. uint8_t *p = input;
  361. EVP_CIPHER_CTX *ds = (incoming) ? ((enc) ? f->srvr_write_ctx : f->clnt_read_ctx) : ((enc) ? f->clnt_write_ctx : f->srvr_read_ctx) ;
  362. if(ds == NULL){
  363. printf("FAIL\n");
  364. return 1;
  365. }
  366. uint8_t *seq;
  367. seq = (incoming) ? f->read_seq : f->write_seq;
  368. if(f->application && (ds->iv[EVP_GCM_TLS_FIXED_IV_LEN] == 0)){
  369. //printf("MERP\n");
  370. //fill in rest of iv
  371. for(int i = EVP_GCM_TLS_FIXED_IV_LEN; i< ds->cipher->iv_len; i++){
  372. ds->iv[i] = p[i- EVP_GCM_TLS_FIXED_IV_LEN];
  373. }
  374. }
  375. #ifdef DEBUG
  376. printf("\t\tiv: ");
  377. for(int i=0; i<ds->cipher->iv_len; i++){
  378. printf("%02X ", ds->iv[i]);
  379. }
  380. printf("\n");
  381. #endif
  382. uint8_t buf[13];
  383. memcpy(buf, seq, 8);
  384. for(int i=7; i>=0; i--){
  385. ++seq[i];
  386. if(seq[i] != 0)
  387. break;
  388. }
  389. buf[8] = type;
  390. buf[9] = 0x03;
  391. buf[10] = 0x03;
  392. buf[11] = len >> 8; //len >> 8;
  393. buf[12] = len & 0xff;//len *0xff;
  394. int32_t pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
  395. 13, buf); // = int32_t pad?
  396. if(enc)
  397. len += pad;
  398. int32_t n = EVP_Cipher(ds, p, p, len); //decrypt in place
  399. if(n<0) return 0;
  400. #ifdef DEBUG
  401. printf("decrypted data:\n");
  402. for(int i=0; i< len; i++){
  403. printf("%02x ", p[EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  404. }
  405. printf("\n");
  406. #endif
  407. if(!enc)
  408. p[EVP_GCM_TLS_EXPLICIT_IV_LEN+n] = '\0';
  409. return n;
  410. }
  411. /** Verifies the hash in a TLS finished message
  412. *
  413. * Adds string derived from the client-relay shared secret to the finished hash.
  414. * This feature detects and prevents suspicious behaviour in the event of a MiTM
  415. * or RAD attack.
  416. *
  417. * Inputs:
  418. * f: the tagged flow
  419. * p: a pointer to the TLS Finished handshake message
  420. * incoming: the direction of the flow
  421. *
  422. * Output:
  423. * 0 on success, 1 on failure
  424. */
  425. int verify_finish_hash(flow *f, uint8_t *hs, int32_t incoming){
  426. EVP_MD_CTX ctx;
  427. uint8_t hash[EVP_MAX_MD_SIZE];
  428. uint32_t hash_len;
  429. uint8_t *p = hs;
  430. EVP_MD_CTX_init(&ctx);
  431. //get header length
  432. struct handshake_header *hs_hdr;
  433. hs_hdr = (struct handshake_header*) p;
  434. uint32_t fin_length = HANDSHAKE_MESSAGE_LEN(hs_hdr);
  435. //save old finished to update finished mac hash
  436. uint8_t *old_finished = ecalloc(1, fin_length);
  437. old_finished = malloc(fin_length+ HANDSHAKE_HEADER_LEN);
  438. memcpy(old_finished, p, fin_length+HANDSHAKE_HEADER_LEN);
  439. p += HANDSHAKE_HEADER_LEN;
  440. //finalize hash of handshake msgs (have not yet added this one)
  441. EVP_MD_CTX_copy_ex(&ctx, f->finish_md_ctx);
  442. EVP_DigestFinal_ex(&ctx, hash, &hash_len);
  443. //now use pseudorandom function
  444. uint8_t *output = ecalloc(1, fin_length);
  445. if(incoming){
  446. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE, (uint8_t *) TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE , hash, hash_len, NULL, 0, NULL, 0, output, fin_length);
  447. } else {
  448. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE, (uint8_t *) TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE , hash, hash_len, NULL, 0, NULL, 0, output, fin_length);
  449. }
  450. //now compare
  451. if(CRYPTO_memcmp(p, output, fin_length) != 0){
  452. printf("VERIFY FAILED\n");
  453. goto err;
  454. }
  455. #ifdef DEBUG_HS
  456. printf("Old finished:\n");
  457. for(int i=0; i< fin_length; i++){
  458. printf("%02x ", p[i]);
  459. }
  460. printf("\n");
  461. #endif
  462. //now add extra input seeded with client-relay shared secret
  463. if(incoming){
  464. uint32_t extra_input_len = SSL3_RANDOM_SIZE;
  465. uint8_t *extra_input = calloc(1, extra_input_len);
  466. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  467. (uint8_t *) SLITHEEN_FINISHED_INPUT_CONST, SLITHEEN_FINISHED_INPUT_CONST_SIZE,
  468. NULL, 0, NULL, 0, NULL, 0,
  469. extra_input, extra_input_len);
  470. EVP_MD_CTX_copy_ex(&ctx, f->finish_md_ctx);
  471. EVP_DigestUpdate(&ctx, extra_input, extra_input_len);
  472. EVP_DigestFinal_ex(&ctx, hash, &hash_len);
  473. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  474. (uint8_t *) TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE ,
  475. hash, hash_len, NULL, 0, NULL, 0,
  476. output, fin_length);
  477. //replace existing MAC with modified one
  478. memcpy(p, output, fin_length);
  479. #ifdef DEBUG_HS
  480. printf("New finished:\n");
  481. for(int i=0; i< fin_length; i++){
  482. printf("%02x ", p[i]);
  483. }
  484. printf("\n");
  485. #endif
  486. free(extra_input);
  487. }
  488. if(update_finish_hash(f, old_finished)){
  489. fprintf(stderr, "Error updating finish hash with FINISHED msg\n");
  490. remove_flow(f);
  491. goto err;
  492. }
  493. free(old_finished);
  494. free(output);
  495. EVP_MD_CTX_cleanup(&ctx);
  496. return 0;
  497. err:
  498. if(output != NULL)
  499. free(output);
  500. if(old_finished != NULL)
  501. free(old_finished);
  502. EVP_MD_CTX_cleanup(&ctx);
  503. return 1;
  504. }
  505. /** Computes the TLS master secret from the decoy server's
  506. * public key parameters and the leaked secret from the
  507. * extracted Slitheen tag
  508. *
  509. * Input:
  510. * f: the tagged flow
  511. *
  512. * Output:
  513. * 0 on success, 1 on failure
  514. */
  515. int compute_master_secret(flow *f){
  516. #ifdef DEBUG_HS
  517. 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);
  518. #endif
  519. DH *dh_srvr = NULL;
  520. DH *dh_clnt = NULL;
  521. BN_CTX *ctx = NULL;
  522. BIGNUM *pub_key = NULL, *priv_key = NULL, *order = NULL;
  523. EC_KEY *clnt_ecdh = NULL;
  524. EC_POINT *e_pub_key = NULL;
  525. int ok =1;
  526. uint8_t *pre_master_secret = ecalloc(1, PRE_MASTER_MAX_LEN);
  527. int32_t pre_master_len;
  528. uint32_t l;
  529. int32_t bytes;
  530. uint8_t *buf = NULL;
  531. if(f->keyex_alg == 1){
  532. BN_MONT_CTX *mont = NULL;
  533. ctx = BN_CTX_new();
  534. dh_srvr = f->dh;
  535. dh_clnt = DHparams_dup(dh_srvr);
  536. l = dh_clnt->length ? dh_clnt->length : BN_num_bits(dh_clnt->p) - 1;
  537. bytes = (l+7) / 8;
  538. buf = (uint8_t *)OPENSSL_malloc(bytes);
  539. if (buf == NULL){
  540. BNerr(BN_F_BNRAND, ERR_R_MALLOC_FAILURE);
  541. goto err;
  542. }
  543. pub_key = BN_new();
  544. priv_key = BN_new();
  545. #ifdef DEBUG
  546. printf("key =");
  547. for(int i=0; i< 16; i++)
  548. printf(" %02x", f->key[i]);
  549. printf("\n");
  550. #endif
  551. PRF(f, f->key, 16,
  552. (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  553. NULL, 0, NULL, 0, NULL, 0,
  554. buf, bytes);
  555. #ifdef DEBUG
  556. printf("Generated the following rand bytes: ");
  557. for(int i=0; i< bytes; i++){
  558. printf(" %02x ", buf[i]);
  559. }
  560. printf("\n");
  561. #endif
  562. if (!BN_bin2bn(buf, bytes, priv_key))
  563. goto err;
  564. {
  565. BIGNUM *prk;
  566. prk = priv_key;
  567. if (!dh_clnt->meth->bn_mod_exp(dh_clnt, pub_key, dh_clnt->g, prk, dh_clnt->p, ctx, mont)){
  568. goto err;
  569. }
  570. }
  571. dh_clnt->pub_key = pub_key;
  572. dh_clnt->priv_key = priv_key;
  573. pre_master_len = DH_compute_key(pre_master_secret, dh_srvr->pub_key, dh_clnt);
  574. } else if(f->keyex_alg == 2){
  575. const EC_GROUP *srvr_group = NULL;
  576. const EC_POINT *srvr_ecpoint = NULL;
  577. EC_KEY *tkey;
  578. tkey = f->ecdh;
  579. if(tkey == NULL){
  580. return 1;
  581. }
  582. srvr_group = EC_KEY_get0_group(tkey);
  583. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  584. if((srvr_group == NULL) || (srvr_ecpoint == NULL)) {
  585. return 1;
  586. }
  587. if((clnt_ecdh = EC_KEY_new()) == NULL) {
  588. goto err;
  589. }
  590. if(!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  591. goto err;
  592. }
  593. /* Now generate key from tag */
  594. if((order = BN_new()) == NULL){
  595. goto err;
  596. }
  597. if((ctx = BN_CTX_new()) == NULL){
  598. goto err;
  599. }
  600. if((priv_key = BN_new()) == NULL){
  601. goto err;
  602. }
  603. if(!EC_GROUP_get_order(srvr_group, order, ctx)){
  604. goto err;
  605. }
  606. l = BN_num_bits(order)-1;
  607. bytes = (l+7)/8;
  608. buf = (unsigned char *)OPENSSL_malloc(bytes);
  609. if(buf == NULL){
  610. goto err;
  611. }
  612. PRF(f, f->key, 16, (uint8_t *) SLITHEEN_KEYGEN_CONST, SLITHEEN_KEYGEN_CONST_SIZE,
  613. NULL, 0, NULL, 0, NULL, 0, buf, bytes);
  614. #ifdef DEBUG
  615. printf("Generated the following rand bytes: ");
  616. for(int i=0; i< bytes; i++){
  617. printf("%02x ", buf[i]);
  618. }
  619. printf("\n");
  620. #endif
  621. if(!BN_bin2bn(buf, bytes, priv_key)){
  622. goto err;
  623. }
  624. if((e_pub_key = EC_POINT_new(srvr_group)) == NULL){
  625. goto err;
  626. }
  627. if(!EC_POINT_mul(EC_KEY_get0_group(clnt_ecdh), e_pub_key, priv_key, NULL, NULL, ctx)){
  628. goto err;
  629. }
  630. EC_KEY_set_private_key(clnt_ecdh, priv_key);
  631. EC_KEY_set_public_key(clnt_ecdh, e_pub_key);
  632. /*Compute the master secret */
  633. int32_t field_size = EC_GROUP_get_degree(srvr_group);
  634. if(field_size <= 0){
  635. goto err;
  636. }
  637. pre_master_len = ECDH_compute_key(pre_master_secret, (field_size + 7) / 8,
  638. srvr_ecpoint, clnt_ecdh, NULL);
  639. if(pre_master_len <= 0) {
  640. goto err;
  641. }
  642. }
  643. /*Generate master secret */
  644. 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);
  645. if(f->current_session != NULL){
  646. memcpy(f->current_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  647. }
  648. #ifdef DEBUG
  649. fprintf(stdout, "Premaster Secret:\n");
  650. BIO_dump_fp(stdout, (char *)pre_master_secret, pre_master_len);
  651. fprintf(stdout, "Client Random:\n");
  652. BIO_dump_fp(stdout, (char *)f->client_random, SSL3_RANDOM_SIZE);
  653. fprintf(stdout, "Server Random:\n");
  654. BIO_dump_fp(stdout, (char *)f->server_random, SSL3_RANDOM_SIZE);
  655. fprintf(stdout, "Master Secret:\n");
  656. BIO_dump_fp(stdout, (char *)f->master_secret, SSL3_MASTER_SECRET_SIZE);
  657. #endif
  658. //remove pre_master_secret from memory
  659. memset(pre_master_secret, 0, PRE_MASTER_MAX_LEN);
  660. ok = 0;
  661. err:
  662. if((pub_key != NULL) && (dh_srvr == NULL)){
  663. BN_free(pub_key);
  664. }
  665. if((priv_key != NULL) && ((dh_clnt == NULL) || (EC_KEY_get0_private_key(clnt_ecdh) == NULL))){
  666. BN_free(priv_key);
  667. }
  668. if(ctx != NULL){
  669. BN_CTX_free(ctx);
  670. }
  671. OPENSSL_free(buf);
  672. free(pre_master_secret);
  673. if(dh_srvr != NULL){
  674. DH_free(dh_srvr);
  675. }
  676. if(dh_clnt != NULL) {
  677. DH_free(dh_clnt);
  678. }
  679. if(order){
  680. BN_free(order);
  681. }
  682. if(clnt_ecdh != NULL){
  683. EC_KEY_free(clnt_ecdh);
  684. }
  685. if(e_pub_key != NULL){
  686. EC_POINT_free(e_pub_key);
  687. }
  688. return ok;
  689. }
  690. /** Saves the random none from the server hello message
  691. *
  692. * Inputs:
  693. * f: the tagged flow
  694. * hs: a pointer to the beginning of the server hello msg
  695. *
  696. * Output:
  697. * 0 on success, 1 on failure
  698. */
  699. int extract_server_random(flow *f, uint8_t *hs){
  700. uint8_t *p;
  701. p = hs + HANDSHAKE_HEADER_LEN;
  702. p+=2; //skip version
  703. memcpy(f->server_random, p, SSL3_RANDOM_SIZE);
  704. p += SSL3_RANDOM_SIZE;
  705. //skip session id
  706. uint8_t id_len = (uint8_t) p[0];
  707. p ++;
  708. p += id_len;
  709. //now extract ciphersuite
  710. #ifdef DEBUG_HS
  711. printf("Checking cipher\n");
  712. #endif
  713. if(((p[0] <<8) + p[1]) == 0x9E){
  714. #ifdef DEBUG_HS
  715. printf("USING DHE-RSA-AES128-GCM-SHA256\n");
  716. fflush(stdout);
  717. #endif
  718. f->keyex_alg = 1;
  719. f->cipher = EVP_aes_128_gcm();
  720. f->message_digest = EVP_sha256();
  721. } else if(((p[0] <<8) + p[1]) == 0x9F){
  722. #ifdef DEBUG_HS
  723. printf("USING DHE-RSA-AES256-GCM-SHA384\n");
  724. fflush(stdout);
  725. #endif
  726. f->keyex_alg = 1;
  727. f->cipher = EVP_aes_256_gcm();
  728. f->message_digest = EVP_sha384();
  729. } else if(((p[0] <<8) + p[1]) == 0xC02F){
  730. #ifdef DEBUG_HS
  731. printf("USING ECDHE-RSA-AES128-GCM-SHA256\n");
  732. fflush(stdout);
  733. #endif
  734. f->keyex_alg = 2;
  735. f->cipher = EVP_aes_128_gcm();
  736. f->message_digest = EVP_sha256();
  737. } else if(((p[0] <<8) + p[1]) == 0xC030){
  738. #ifdef DEBUG_HS
  739. printf("USING ECDHE-RSA-AES256-GCM-SHA384\n");
  740. fflush(stdout);
  741. #endif
  742. f->keyex_alg = 2;
  743. f->cipher = EVP_aes_256_gcm();
  744. f->message_digest = EVP_sha384();
  745. } else {
  746. printf("%x %x = %x\n", p[0], p[1], ((p[0] <<8) + p[1]));
  747. printf("Error: unsupported cipher\n");
  748. fflush(stdout);
  749. return 1;
  750. }
  751. return 0;
  752. }
  753. /** PRF using sha384, as defined in RFC 5246
  754. *
  755. * Inputs:
  756. * secret: the master secret used to sign the hash
  757. * secret_len: the length of the master secret
  758. * seed{1, ..., 4}: seed values that are virtually
  759. * concatenated
  760. * seed{1,...4}_len: length of the seeds
  761. * output: a pointer to the output of the PRF
  762. * output_len: the number of desired bytes
  763. *
  764. * Output:
  765. * 0 on success, 1 on failure
  766. */
  767. int PRF(flow *f, uint8_t *secret, int32_t secret_len,
  768. uint8_t *seed1, int32_t seed1_len,
  769. uint8_t *seed2, int32_t seed2_len,
  770. uint8_t *seed3, int32_t seed3_len,
  771. uint8_t *seed4, int32_t seed4_len,
  772. uint8_t *output, int32_t output_len){
  773. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  774. EVP_PKEY *mac_key;
  775. const EVP_MD *md;
  776. if(f == NULL){
  777. md = EVP_sha256();
  778. } else {
  779. md = f->message_digest;
  780. }
  781. uint8_t A[EVP_MAX_MD_SIZE];
  782. size_t len, A_len;
  783. int chunk = EVP_MD_size(md);
  784. int remaining = output_len;
  785. uint8_t *out = output;
  786. EVP_MD_CTX_init(&ctx);
  787. EVP_MD_CTX_init(&ctx_tmp);
  788. EVP_MD_CTX_init(&ctx_init);
  789. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  790. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
  791. /* Calculate first A value */
  792. EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key);
  793. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  794. if(seed1 != NULL && seed1_len > 0){
  795. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  796. }
  797. if(seed2 != NULL && seed2_len > 0){
  798. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  799. }
  800. if(seed3 != NULL && seed3_len > 0){
  801. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  802. }
  803. if(seed4 != NULL && seed4_len > 0){
  804. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  805. }
  806. EVP_DigestSignFinal(&ctx, A, &A_len);
  807. //iterate until desired length is achieved
  808. while(remaining > 0){
  809. /* Now compute SHA384(secret, A+seed) */
  810. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  811. EVP_DigestSignUpdate(&ctx, A, A_len);
  812. EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx);
  813. if(seed1 != NULL && seed1_len > 0){
  814. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  815. }
  816. if(seed2 != NULL && seed2_len > 0){
  817. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  818. }
  819. if(seed3 != NULL && seed3_len > 0){
  820. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  821. }
  822. if(seed4 != NULL && seed4_len > 0){
  823. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  824. }
  825. if(remaining > chunk){
  826. EVP_DigestSignFinal(&ctx, out, &len);
  827. out += len;
  828. remaining -= len;
  829. /* Next A value */
  830. EVP_DigestSignFinal(&ctx_tmp, A, &A_len);
  831. } else {
  832. EVP_DigestSignFinal(&ctx, A, &A_len);
  833. memcpy(out, A, remaining);
  834. remaining -= remaining;
  835. }
  836. }
  837. EVP_PKEY_free(mac_key);
  838. EVP_MD_CTX_cleanup(&ctx);
  839. EVP_MD_CTX_cleanup(&ctx_tmp);
  840. EVP_MD_CTX_cleanup(&ctx_init);
  841. OPENSSL_cleanse(A, sizeof(A));
  842. return 0;
  843. }
  844. /** After receiving change cipher spec, calculate keys from master secret
  845. *
  846. * Input:
  847. * f: the tagged flow
  848. *
  849. * Output:
  850. * 0 on success, 1 on failure
  851. */
  852. int init_ciphers(flow *f){
  853. EVP_CIPHER_CTX *r_ctx;
  854. EVP_CIPHER_CTX *w_ctx;
  855. EVP_CIPHER_CTX *w_ctx_srvr;
  856. EVP_CIPHER_CTX *r_ctx_srvr;
  857. const EVP_CIPHER *c = f->cipher;
  858. if(c == NULL){
  859. /*This *shouldn't* happen, but might if a serverHello msg isn't received
  860. * or if a session is resumed in a strange way */
  861. return 1;
  862. }
  863. /* Generate Keys */
  864. uint8_t *write_key, *write_iv;
  865. uint8_t *read_key, *read_iv;
  866. int32_t mac_len, key_len, iv_len;
  867. key_len = EVP_CIPHER_key_length(c);
  868. iv_len = EVP_CIPHER_iv_length(c); //EVP_GCM_TLS_FIXED_IV_LEN;
  869. mac_len = EVP_MD_size(f->message_digest);
  870. int32_t total_len = key_len + iv_len + mac_len;
  871. total_len *= 2;
  872. uint8_t *key_block = ecalloc(1, total_len);
  873. PRF(f, f->master_secret, SSL3_MASTER_SECRET_SIZE,
  874. (uint8_t *) TLS_MD_KEY_EXPANSION_CONST, TLS_MD_KEY_EXPANSION_CONST_SIZE,
  875. f->server_random, SSL3_RANDOM_SIZE,
  876. f->client_random, SSL3_RANDOM_SIZE,
  877. NULL, 0,
  878. key_block, total_len);
  879. #ifdef DEBUG
  880. printf("master secret: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  881. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  882. printf("%02x ", f->master_secret[i]);
  883. }
  884. printf("\n");
  885. printf("client random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  886. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  887. printf("%02x ", f->client_random[i]);
  888. }
  889. printf("\n");
  890. printf("server random: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  891. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  892. printf("%02x ", f->server_random[i]);
  893. }
  894. printf("\n");
  895. printf("keyblock: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  896. for(int i=0; i< total_len; i++){
  897. printf("%02x ", key_block[i]);
  898. }
  899. printf("\n");
  900. #endif
  901. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  902. write_key = key_block;
  903. read_key = key_block + key_len;
  904. write_iv = key_block + 2*key_len;
  905. read_iv = key_block + 2*key_len + iv_len;
  906. /* Initialize Cipher Contexts */
  907. r_ctx = EVP_CIPHER_CTX_new();
  908. w_ctx = EVP_CIPHER_CTX_new();
  909. EVP_CIPHER_CTX_init(r_ctx);
  910. EVP_CIPHER_CTX_init(w_ctx);
  911. w_ctx_srvr = EVP_CIPHER_CTX_new();
  912. r_ctx_srvr = EVP_CIPHER_CTX_new();
  913. EVP_CIPHER_CTX_init(w_ctx_srvr);
  914. EVP_CIPHER_CTX_init(r_ctx_srvr);
  915. /* Initialize MACs --- not needed for aes_256_gcm
  916. write_mac = key_block + 2*key_len + 2*iv_len;
  917. read_mac = key_block + 2*key_len + 2*iv_len + mac_len;
  918. read_mac_ctx = EVP_MD_CTX_create();
  919. write_mac_ctx = EVP_MD_CTX_create();
  920. read_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, read_mac, mac_len);
  921. write_mac_key =EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, write_mac, mac_len);
  922. EVP_DigestSignInit(read_mac_ctx, NULL, EVP_sha384(), NULL, read_mac_key);
  923. EVP_DigestSignInit(write_mac_ctx, NULL, EVP_sha384(), NULL, write_mac_key);
  924. EVP_PKEY_free(read_mac_key);
  925. EVP_PKEY_free(write_mac_key);*/
  926. #ifdef DEBUG
  927. {
  928. int i;
  929. fprintf(stderr, "EVP_CipherInit_ex(r_ctx,c,key=,iv=,which)\n");
  930. fprintf(stderr, "\tkey= ");
  931. for (i = 0; i < c->key_len; i++)
  932. fprintf(stderr, "%02x", read_key[i]);
  933. fprintf(stderr, "\n");
  934. fprintf(stderr, "\t iv= ");
  935. for (i = 0; i < c->iv_len; i++)
  936. fprintf(stderr, "%02x", read_iv[i]);
  937. fprintf(stderr, "\n");
  938. }
  939. {
  940. int i;
  941. fprintf(stderr, "EVP_CipherInit_ex(w_ctx,c,key=,iv=,which)\n");
  942. fprintf(stderr, "\tkey= ");
  943. for (i = 0; i < c->key_len; i++)
  944. fprintf(stderr, "%02x", write_key[i]);
  945. fprintf(stderr, "\n");
  946. fprintf(stderr, "\t iv= ");
  947. for (i = 0; i < c->iv_len; i++)
  948. fprintf(stderr, "%02x", write_iv[i]);
  949. fprintf(stderr, "\n");
  950. }
  951. #endif
  952. if(!EVP_CipherInit_ex(r_ctx, c, NULL, read_key, NULL, 0)){
  953. printf("FAIL r_ctx\n");
  954. }
  955. if(!EVP_CipherInit_ex(w_ctx, c, NULL, write_key, NULL, 1)){
  956. printf("FAIL w_ctx\n");
  957. }
  958. if(!EVP_CipherInit_ex(w_ctx_srvr, c, NULL, read_key, NULL, 1)){
  959. printf("FAIL w_ctx_srvr\n");
  960. }
  961. if(!EVP_CipherInit_ex(r_ctx_srvr, c, NULL, write_key, NULL, 0)){
  962. printf("FAIL r_ctx_srvr\n");
  963. }
  964. EVP_CIPHER_CTX_ctrl(r_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  965. EVP_CIPHER_CTX_ctrl(w_ctx, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  966. EVP_CIPHER_CTX_ctrl(w_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, read_iv);
  967. EVP_CIPHER_CTX_ctrl(r_ctx_srvr, EVP_CTRL_GCM_SET_IV_FIXED, EVP_GCM_TLS_FIXED_IV_LEN, write_iv);
  968. f->clnt_read_ctx = r_ctx;
  969. f->clnt_write_ctx = w_ctx;
  970. f->srvr_read_ctx = r_ctx_srvr;
  971. f->srvr_write_ctx = w_ctx_srvr;
  972. free(key_block);
  973. return 0;
  974. }
  975. // To avoid warnings about MAC paddings, use this to update contexts
  976. void update_context(flow *f, uint8_t *input, int32_t len, int32_t incoming, int32_t type, int32_t enc){
  977. uint8_t *output = ecalloc(1, len+16+8);
  978. memcpy(output + EVP_GCM_TLS_EXPLICIT_IV_LEN, input, len);
  979. //If the original message was a decryption, this will be an necryption.
  980. //Incoming field stays the same
  981. encrypt(f, output, output, len+8, incoming, type, !enc);
  982. //revert the sequence number
  983. uint8_t *seq = incoming ? f->read_seq : f->write_seq;
  984. for(int i=7; i>=0; i--){
  985. --seq[i];
  986. if(seq[i] >= 0)
  987. break;
  988. else
  989. seq[i] = 0;
  990. }
  991. free(output);
  992. }
  993. /* Generate the keys for a client's super encryption layer
  994. *
  995. * The header of each downstream slitheen data chunk is 16 bytes and encrypted with
  996. * a 256 bit AES key
  997. *
  998. * The body of each downstream chunk is CBC encrypted with a 256 bit AES key
  999. *
  1000. * The last 16 bytes of the body is a MAC over the body
  1001. *
  1002. */
  1003. void generate_client_super_keys(uint8_t *secret, client *c){
  1004. EVP_MD_CTX *mac_ctx;
  1005. const EVP_MD *md = EVP_sha256();
  1006. FILE *fp;
  1007. //extract shared secret from SLITHEEN_ID
  1008. uint8_t shared_secret[16];
  1009. byte privkey[PTWIST_BYTES];
  1010. fp = fopen("privkey", "rb");
  1011. if (fp == NULL) {
  1012. perror("fopen");
  1013. exit(1);
  1014. }
  1015. if(fread(privkey, PTWIST_BYTES, 1, fp) < 1){
  1016. perror("fread");
  1017. exit(1);
  1018. }
  1019. fclose(fp);
  1020. /* check tag*/
  1021. if(check_tag(shared_secret, privkey, secret, (const byte *)"context", 7)){
  1022. //something went wrong O.o
  1023. printf("Error extracting secret from tag\n");
  1024. return;
  1025. }
  1026. #ifdef DEBUG
  1027. printf("Shared secret: ");
  1028. for(int i=0; i< 16; i++){
  1029. printf("%02x ", shared_secret[i]);
  1030. }
  1031. printf("\n");
  1032. #endif
  1033. /* Generate Keys */
  1034. uint8_t *hdr_key, *bdy_key;
  1035. uint8_t *mac_secret;
  1036. EVP_PKEY *mac_key;
  1037. int32_t mac_len, key_len;
  1038. key_len = EVP_CIPHER_key_length(EVP_aes_256_cbc());
  1039. mac_len = EVP_MD_size(md);
  1040. int32_t total_len = 2*key_len + mac_len;
  1041. uint8_t *key_block = ecalloc(1, total_len);
  1042. PRF(NULL, shared_secret, SLITHEEN_SUPER_SECRET_SIZE,
  1043. (uint8_t *) SLITHEEN_SUPER_CONST, SLITHEEN_SUPER_CONST_SIZE,
  1044. NULL, 0,
  1045. NULL, 0,
  1046. NULL, 0,
  1047. key_block, total_len);
  1048. #ifdef DEBUG
  1049. printf("slitheend id: \n");
  1050. for(int i=0; i< SLITHEEN_ID_LEN; i++){
  1051. printf("%02x ", secret[i]);
  1052. }
  1053. printf("\n");
  1054. printf("keyblock: \n");
  1055. for(int i=0; i< total_len; i++){
  1056. printf("%02x ", key_block[i]);
  1057. }
  1058. printf("\n");
  1059. #endif
  1060. hdr_key = key_block;
  1061. bdy_key = key_block + key_len;
  1062. mac_secret = key_block + 2*key_len;
  1063. /* Initialize MAC Context */
  1064. mac_ctx = EVP_MD_CTX_create();
  1065. EVP_DigestInit_ex(mac_ctx, md, NULL);
  1066. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, mac_secret, mac_len);
  1067. EVP_DigestSignInit(mac_ctx, NULL, md, NULL, mac_key);
  1068. c->header_key = emalloc(key_len);
  1069. c->body_key = emalloc(key_len);
  1070. memcpy(c->header_key, hdr_key, key_len);
  1071. memcpy(c->body_key, bdy_key, key_len);
  1072. c->mac_ctx = mac_ctx;
  1073. //Free everything
  1074. free(key_block);
  1075. EVP_PKEY_free(mac_key);
  1076. return;
  1077. }
  1078. int super_encrypt(client *c, uint8_t *data, uint32_t len){
  1079. int retval = 1;
  1080. EVP_CIPHER_CTX *hdr_ctx = NULL;
  1081. EVP_CIPHER_CTX *bdy_ctx = NULL;
  1082. int32_t out_len;
  1083. size_t mac_len;
  1084. uint8_t *p = data;
  1085. uint8_t output[EVP_MAX_MD_SIZE];
  1086. //first encrypt the header
  1087. #ifdef DEBUG
  1088. printf("Plaintext Header:\n");
  1089. for(int i=0; i< SLITHEEN_HEADER_LEN; i++){
  1090. printf("%02x ", p[i]);
  1091. }
  1092. printf("\n");
  1093. #endif
  1094. hdr_ctx = EVP_CIPHER_CTX_new();
  1095. EVP_CipherInit_ex(hdr_ctx, EVP_aes_256_cbc(), NULL, c->header_key, NULL, 1);
  1096. if(!EVP_CipherUpdate(hdr_ctx, p, &out_len, p, SLITHEEN_HEADER_LEN)){
  1097. printf("Failed!\n");
  1098. retval = 0;
  1099. goto end;
  1100. }
  1101. #ifdef DEBUG
  1102. printf("Encrypted Header (%d bytes)\n", out_len);
  1103. for(int i=0; i< out_len; i++){
  1104. printf("%02x ", p[i]);
  1105. }
  1106. printf("\n");
  1107. #endif
  1108. if(len == 0){ //only encrypt header: body contains garbage bytes
  1109. retval = 1;
  1110. goto end;
  1111. }
  1112. //encrypt the body
  1113. p += SLITHEEN_HEADER_LEN;
  1114. //generate IV
  1115. RAND_bytes(p, 16);
  1116. //set up cipher ctx
  1117. bdy_ctx = EVP_CIPHER_CTX_new();
  1118. EVP_CipherInit_ex(bdy_ctx, EVP_aes_256_cbc(), NULL, c->body_key, p, 1);
  1119. p+= 16;
  1120. #ifdef DEBUG
  1121. printf("Plaintext:\n");
  1122. for(int i=0; i< len; i++){
  1123. printf("%02x ", p[i]);
  1124. }
  1125. printf("\n");
  1126. #endif
  1127. if(!EVP_CipherUpdate(bdy_ctx, p, &out_len, p, len)){
  1128. printf("Failed!\n");
  1129. goto end;
  1130. retval = 0;
  1131. }
  1132. #ifdef DEBUG
  1133. printf("Encrypted %d bytes\n", out_len);
  1134. printf("Encrypted data:\n");
  1135. for(int i=0; i< out_len; i++){
  1136. printf("%02x ", p[i]);
  1137. }
  1138. printf("\n");
  1139. #endif
  1140. //MAC at the end
  1141. EVP_MD_CTX mac_ctx;
  1142. EVP_MD_CTX_init(&mac_ctx);
  1143. EVP_MD_CTX_copy_ex(&mac_ctx, c->mac_ctx);
  1144. EVP_DigestSignUpdate(&mac_ctx, p, out_len);
  1145. EVP_DigestSignFinal(&mac_ctx, output, &mac_len);
  1146. EVP_MD_CTX_cleanup(&mac_ctx);
  1147. p += out_len;
  1148. memcpy(p, output, 16);
  1149. #ifdef DEBUG_PARSE
  1150. printf("Computed mac:\n");
  1151. for(int i=0; i< 16; i++){
  1152. printf("%02x ", output[i]);
  1153. }
  1154. printf("\n");
  1155. fflush(stdout);
  1156. #endif
  1157. end:
  1158. if(hdr_ctx != NULL){
  1159. EVP_CIPHER_CTX_cleanup(hdr_ctx);
  1160. OPENSSL_free(hdr_ctx);
  1161. }
  1162. if(bdy_ctx != NULL){
  1163. EVP_CIPHER_CTX_cleanup(bdy_ctx);
  1164. OPENSSL_free(bdy_ctx);
  1165. }
  1166. return retval;
  1167. }
  1168. /** Checks a handshake message to see if it is tagged or a
  1169. * recognized flow. If the client random nonce is tagged,
  1170. * adds the flow to the flow table to be tracked.
  1171. *
  1172. * Inputs:
  1173. * info: the processed packet
  1174. * f: the tagged flow
  1175. *
  1176. * Output:
  1177. * none
  1178. */
  1179. void check_handshake(struct packet_info *info){
  1180. FILE *fp;
  1181. int res, code;
  1182. uint8_t *hello_rand;
  1183. const struct handshake_header *handshake_hdr;
  1184. byte privkey[PTWIST_BYTES];
  1185. byte key[16];
  1186. uint8_t *p = info->app_data + RECORD_HEADER_LEN;
  1187. handshake_hdr = (struct handshake_header*) p;
  1188. code = handshake_hdr->type;
  1189. if (code == 0x01){
  1190. p += CLIENT_HELLO_HEADER_LEN;
  1191. //now pointing to hello random :D
  1192. hello_rand = p;
  1193. p += 4; //skipping time bytes
  1194. /* Load the private key */
  1195. fp = fopen("privkey", "rb");
  1196. if (fp == NULL) {
  1197. perror("fopen");
  1198. exit(1);
  1199. }
  1200. res = fread(privkey, PTWIST_BYTES, 1, fp);
  1201. if (res < 1) {
  1202. perror("fread");
  1203. exit(1);
  1204. }
  1205. fclose(fp);
  1206. /* check tag*/
  1207. res = check_tag(key, privkey, p, (const byte *)"context", 7);
  1208. if (!res) {
  1209. #ifdef DEBUG
  1210. printf("Received tagged flow! (key =");
  1211. for(i=0; i<16;i++){
  1212. printf(" %02x", key[i]);
  1213. }
  1214. printf(")\n");
  1215. #endif
  1216. /* Save flow in table */
  1217. flow *flow_ptr = add_flow(info);
  1218. if(flow_ptr == NULL){
  1219. fprintf(stderr, "Memory failure\n");
  1220. return;
  1221. }
  1222. for(int i=0; i<16; i++){
  1223. flow_ptr->key[i] = key[i];
  1224. }
  1225. memcpy(flow_ptr->client_random, hello_rand, SSL3_RANDOM_SIZE);
  1226. #ifdef DEBUG
  1227. for(int i=0; i< SSL3_RANDOM_SIZE; i++){
  1228. printf("%02x ", hello_rand[i]);
  1229. }
  1230. printf("\n");
  1231. printf("Saved new flow\n");
  1232. #endif
  1233. }
  1234. }
  1235. }
  1236. /* Check the given tag with the given context and private key. Return 0
  1237. if the tag is properly formed, non-0 if not. If the tag is correct,
  1238. set key to the resulting secret key. */
  1239. int check_tag(byte key[16], const byte privkey[PTWIST_BYTES],
  1240. const byte tag[PTWIST_TAG_BYTES], const byte *context,
  1241. size_t context_len)
  1242. {
  1243. int ret = -1;
  1244. byte sharedsec[PTWIST_BYTES+context_len];
  1245. byte taghashout[32];
  1246. #if PTWIST_PUZZLE_STRENGTH > 0
  1247. byte hashout[32];
  1248. size_t puzzle_len = 16+PTWIST_RESP_BYTES;
  1249. byte value_to_hash[puzzle_len];
  1250. unsigned int firstbits;
  1251. int firstpass = 0;
  1252. #endif
  1253. /* Compute the shared secret privkey*TAG */
  1254. ptwist_pointmul(sharedsec, tag, privkey);
  1255. /* Create the hash tag keys */
  1256. memmove(sharedsec+PTWIST_BYTES, context, context_len);
  1257. SHA256(sharedsec, PTWIST_BYTES, taghashout);
  1258. #if PTWIST_PUZZLE_STRENGTH > 0
  1259. /* Construct the proposed solution to the puzzle */
  1260. memmove(value_to_hash, taghashout, 16);
  1261. memmove(value_to_hash+16, tag+PTWIST_BYTES, PTWIST_RESP_BYTES);
  1262. value_to_hash[16+PTWIST_RESP_BYTES-1] &= PTWIST_RESP_MASK;
  1263. /* Hash the proposed solution and see if it is correct; that is, the
  1264. * hash should start with PTWIST_PUZZLE_STRENGTH bits of 0s,
  1265. * followed by the last PTWIST_HASH_SHOWBITS of the tag. */
  1266. md_map_sh256(hashout, value_to_hash, puzzle_len);
  1267. #if PTWIST_PUZZLE_STRENGTH < 32
  1268. /* This assumes that you're on an architecture that doesn't care
  1269. * about alignment, and is little endian. */
  1270. firstbits = *(unsigned int*)hashout;
  1271. if ((firstbits & PTWIST_PUZZLE_MASK) == 0) {
  1272. firstpass = 1;
  1273. }
  1274. #else
  1275. #error "Code assumes PTWIST_PUZZLE_STRENGTH < 32"
  1276. #endif
  1277. if (firstpass) {
  1278. bn_t Hbn, Tbn;
  1279. bn_new(Hbn);
  1280. bn_new(Tbn);
  1281. hashout[PTWIST_HASH_TOTBYTES-1] &= PTWIST_HASH_MASK;
  1282. bn_read_bin(Hbn, hashout, PTWIST_HASH_TOTBYTES, BN_POS);
  1283. bn_rsh(Hbn, Hbn, PTWIST_PUZZLE_STRENGTH);
  1284. bn_read_bin(Tbn, tag+PTWIST_BYTES, PTWIST_TAG_BYTES-PTWIST_BYTES,
  1285. BN_POS);
  1286. bn_rsh(Tbn, Tbn, PTWIST_RESP_BITS);
  1287. ret = (bn_cmp(Tbn,Hbn) != CMP_EQ);
  1288. bn_free(Hbn);
  1289. bn_free(Tbn);
  1290. }
  1291. #else
  1292. /* We're not using a client puzzle, so just check that the first
  1293. * PTWIST_HASH_SHOWBITS bits of the above hash fill out the rest
  1294. * of the tag. If there's no puzzle, PTWIST_HASH_SHOWBITS must be
  1295. * a multiple of 8. */
  1296. ret = (memcmp(tag+PTWIST_BYTES, taghashout, PTWIST_HASH_SHOWBITS/8) != 0);
  1297. #endif
  1298. if (ret == 0) {
  1299. memmove(key, taghashout+16, 16);
  1300. }
  1301. return ret;
  1302. }