crypto.c 41 KB

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