crypto.c 42 KB

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