crypto.c 41 KB

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