flow.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. /* Name: flow.c
  2. *
  3. * This file contains functions for manipulating tagged flows.
  4. *
  5. * Slitheen - a decoy routing system for censorship resistance
  6. * Copyright (C) 2017 Cecylia Bocovich (cbocovic@uwaterloo.ca)
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, version 3.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * Additional permission under GNU GPL version 3 section 7
  21. *
  22. * If you modify this Program, or any covered work, by linking or combining
  23. * it with the OpenSSL library (or a modified version of that library),
  24. * containing parts covered by the terms of [name of library's license],
  25. * the licensors of this Program grant you additional permission to convey
  26. * the resulting work. {Corresponding Source for a non-source form of such
  27. * a combination shall include the source code for the parts of the OpenSSL
  28. * library used as well as that of the covered work.}
  29. */
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <stdint.h>
  33. #include <pthread.h>
  34. #include <errno.h>
  35. #include <semaphore.h>
  36. #include "flow.h"
  37. #include "crypto.h"
  38. #include "slitheen.h"
  39. #include "relay.h"
  40. #include "util.h"
  41. #define DEBUG_HS
  42. static flow_table *table;
  43. static session_cache *sessions;
  44. client_table *clients;
  45. sem_t flow_table_lock;
  46. /* Initialize the table of tagged flows */
  47. int init_tables(void) {
  48. table = emalloc(sizeof(flow_table));
  49. table->first_entry = NULL;
  50. table->len = 0;
  51. sem_init(&flow_table_lock, 0, 1);
  52. clients = emalloc(sizeof(client_table));
  53. clients->first = NULL;
  54. printf("initialized downstream queue\n");
  55. return 0;
  56. }
  57. /* Add a new flow to the tagged flow table */
  58. flow *add_flow(struct packet_info *info) {
  59. flow_entry *entry = emalloc(sizeof(flow_entry));
  60. flow *new_flow = emalloc(sizeof(flow));
  61. entry->f = new_flow;
  62. entry->next = NULL;
  63. new_flow->src_ip = info->ip_hdr->src;
  64. new_flow->dst_ip = info->ip_hdr->dst;
  65. new_flow->src_port = info->tcp_hdr->src_port;
  66. new_flow->dst_port = info->tcp_hdr->dst_port;
  67. new_flow->ref_ctr = 1;
  68. printf("Adding new flow (%p ref ctr %d)\n", new_flow, 1);
  69. new_flow->removed = 0;
  70. new_flow->upstream_app_data = emalloc(sizeof(app_data_queue));
  71. new_flow->upstream_app_data->first_packet = NULL;
  72. new_flow->downstream_app_data = emalloc(sizeof(app_data_queue));
  73. new_flow->downstream_app_data->first_packet = NULL;
  74. new_flow->upstream_seq_num = ntohl(info->tcp_hdr->sequence_num);
  75. new_flow->downstream_seq_num = ntohl(info->tcp_hdr->ack_num);
  76. new_flow->us_frame_queue = emalloc(sizeof(frame_queue));
  77. new_flow->us_frame_queue->first_frame = NULL;
  78. new_flow->ds_frame_queue = emalloc(sizeof(frame_queue));
  79. new_flow->ds_frame_queue->first_frame = NULL;
  80. new_flow->streams=NULL;
  81. new_flow->downstream_queue=NULL;
  82. new_flow->client_ptr=NULL;
  83. sem_init(&(new_flow->flow_lock), 0, 1);
  84. new_flow->state = TLS_CLNT_HELLO;
  85. new_flow->in_encrypted = 0;
  86. new_flow->out_encrypted = 0;
  87. new_flow->application = 0;
  88. new_flow->stall = 0;
  89. new_flow->resume_session = 0;
  90. new_flow->current_session = NULL;
  91. new_flow->us_hs_queue = init_queue();
  92. new_flow->ds_hs_queue = init_queue();
  93. new_flow->us_packet_chain = emalloc(sizeof(packet_chain));
  94. new_flow->us_packet_chain->expected_seq_num = ntohl(info->tcp_hdr->sequence_num);
  95. new_flow->us_packet_chain->record_len = 0;
  96. new_flow->us_packet_chain->remaining_record_len = 0;
  97. new_flow->us_packet_chain->first_packet = NULL;
  98. new_flow->ds_packet_chain = emalloc(sizeof(packet_chain));
  99. new_flow->ds_packet_chain->expected_seq_num = ntohl(info->tcp_hdr->ack_num);
  100. new_flow->ds_packet_chain->record_len = 0;
  101. new_flow->ds_packet_chain->remaining_record_len = 0;
  102. new_flow->ds_packet_chain->first_packet = NULL;
  103. sem_init(&(new_flow->packet_chain_lock), 0, 1);
  104. new_flow->upstream_queue = NULL;
  105. new_flow->upstream_remaining = 0;
  106. sem_init(&(new_flow->upstream_queue_lock), 0, 1);
  107. new_flow->outbox = NULL;
  108. new_flow->outbox_len = 0;
  109. new_flow->outbox_offset = 0;
  110. new_flow->partial_record_header = NULL;
  111. new_flow->partial_record_header_len = 0;
  112. new_flow->remaining_record_len = 0;
  113. new_flow->remaining_response_len = 0;
  114. new_flow->httpstate = PARSE_HEADER;
  115. new_flow->replace_response = 0;
  116. new_flow->ecdh = NULL;
  117. new_flow->dh = NULL;
  118. new_flow->finish_md_ctx = EVP_MD_CTX_create();
  119. const EVP_MD *md = EVP_sha384();
  120. EVP_DigestInit_ex(new_flow->finish_md_ctx, md, NULL);
  121. new_flow->cipher = NULL;
  122. new_flow->clnt_read_ctx = NULL;
  123. new_flow->clnt_write_ctx = NULL;
  124. new_flow->srvr_read_ctx = NULL;
  125. new_flow->srvr_write_ctx = NULL;
  126. memset(new_flow->read_seq, 0, 8);
  127. memset(new_flow->write_seq, 0, 8);
  128. sem_wait(&flow_table_lock);
  129. flow_entry *last = table->first_entry;
  130. if(last == NULL){
  131. table->first_entry = entry;
  132. } else {
  133. for(int i=0; i< table->len-1; i++){
  134. last = last->next;
  135. }
  136. last->next = entry;
  137. }
  138. table->len ++;
  139. sem_post(&flow_table_lock);
  140. return new_flow;
  141. }
  142. /** Observes TLS handshake messages and updates the state of
  143. * the flow
  144. *
  145. * Inputs:
  146. * f: the tagged flow
  147. * record: a complete TLS record
  148. *
  149. * Output:
  150. * 0 on success, 1 on failure
  151. */
  152. int update_flow(flow *f, uint8_t *record, uint8_t incoming) {
  153. const struct record_header *record_hdr;
  154. const struct handshake_header *handshake_hdr;
  155. uint8_t *p;
  156. record_hdr = (struct record_header*) record;
  157. int record_len;
  158. record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  159. switch(record_hdr->type){
  160. case HS:
  161. p = record;
  162. p += RECORD_HEADER_LEN;
  163. if((incoming && f->in_encrypted) || (!incoming && f->out_encrypted)){
  164. #ifdef DEBUG_HS
  165. printf("Decrypting finished (%d bytes) (%x:%d -> %x:%d)\n", record_len - RECORD_HEADER_LEN, f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  166. printf("Finished ciphertext:\n");
  167. for(int i=0; i< record_len; i++){
  168. printf("%02x ", record[i]);
  169. }
  170. printf("\n");
  171. #endif
  172. int32_t n = encrypt(f, p, p, record_len - RECORD_HEADER_LEN, incoming, 0x16, 0, 0);
  173. if(n<=0){
  174. printf("Error decrypting finished (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  175. }
  176. #ifdef DEBUG_HS
  177. printf("Finished decrypted: (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  178. #endif
  179. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  180. #ifdef DEBUG_HS
  181. printf("record:\n");
  182. for(int i=0; i< n; i++){
  183. printf("%02x ", p[i]);
  184. }
  185. printf("\n");
  186. #endif
  187. if(p[0] != 0x14){
  188. p[0] = 0x20; //trigger error
  189. }
  190. if(incoming){
  191. f->in_encrypted = 2;
  192. } else {
  193. f->out_encrypted = 2;
  194. }
  195. }
  196. handshake_hdr = (struct handshake_header*) p;
  197. f->state = handshake_hdr->type;
  198. switch(f->state){
  199. case TLS_CLNT_HELLO:
  200. #ifdef DEBUG_HS
  201. printf("Received tagged client hello (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  202. #endif
  203. if(update_finish_hash(f, p)){
  204. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  205. remove_flow(f);
  206. goto err;
  207. }
  208. if(check_session(f, p, HANDSHAKE_MESSAGE_LEN(handshake_hdr))){
  209. fprintf(stderr, "Error checking session, might cause problems\n");
  210. }
  211. break;
  212. case TLS_SERV_HELLO:
  213. #ifdef DEBUG_HS
  214. printf("Received server hello (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  215. #endif
  216. if(f->resume_session){
  217. if(verify_session_id(f,p)){
  218. fprintf(stderr, "Failed to verify session id\n");
  219. }
  220. } else {
  221. if(save_session_id(f,p)){
  222. fprintf(stderr, "Failed to save session id\n");
  223. }
  224. }
  225. if(extract_server_random(f, p)){
  226. fprintf(stderr, "Failed to extract server random nonce\n");
  227. remove_flow(f);
  228. goto err;
  229. }
  230. if(update_finish_hash(f, p)){
  231. fprintf(stderr, "Error updating finish hash with SRVR_HELLO msg\n");
  232. remove_flow(f);
  233. goto err;
  234. }
  235. break;
  236. case TLS_NEW_SESS:
  237. #ifdef DEBUG_HS
  238. printf("Received new session\n");
  239. #endif
  240. if(save_session_ticket(f, p, HANDSHAKE_MESSAGE_LEN(handshake_hdr))){
  241. fprintf(stderr, "Failed to save session ticket\n");
  242. }
  243. if(update_finish_hash(f, p)){
  244. fprintf(stderr, "Error updating finish hash with NEW_SESS msg\n");
  245. remove_flow(f);
  246. goto err;
  247. }
  248. break;
  249. case TLS_CERT:
  250. #ifdef DEBUG_HS
  251. printf("Received cert\n");
  252. #endif
  253. if(update_finish_hash(f, p)){
  254. fprintf(stderr, "Error updating finish hash with CERT msg\n");
  255. remove_flow(f);
  256. goto err;
  257. }
  258. break;
  259. case TLS_SRVR_KEYEX:
  260. #ifdef DEBUG_HS
  261. printf("Received server keyex\n");
  262. #endif
  263. if(update_finish_hash(f, p)){
  264. fprintf(stderr, "Error updating finish hash with SRVR_KEYEX msg\n");
  265. remove_flow(f);
  266. goto err;
  267. }
  268. if(extract_parameters(f, p)){
  269. printf("Error extracting params\n");
  270. remove_flow(f);
  271. goto err;
  272. }
  273. if(compute_master_secret(f)){
  274. printf("Error computing master secret\n");
  275. remove_flow(f);
  276. goto err;
  277. }
  278. break;
  279. case TLS_CERT_REQ:
  280. if(update_finish_hash(f, p)){
  281. fprintf(stderr, "Error updating finish hash with CERT_REQ msg\n");
  282. remove_flow(f);
  283. goto err;
  284. }
  285. break;
  286. case TLS_SRVR_HELLO_DONE:
  287. #ifdef DEBUG_HS
  288. printf("Received server hello done\n");
  289. #endif
  290. if(update_finish_hash(f, p)){
  291. fprintf(stderr, "Error updating finish hash with HELLO_DONE msg\n");
  292. remove_flow(f);
  293. goto err;
  294. }
  295. break;
  296. case TLS_CERT_VERIFY:
  297. #ifdef DEBUG_HS
  298. printf("received cert verify\n");
  299. #endif
  300. if(update_finish_hash(f, p)){
  301. fprintf(stderr, "Error updating finish hash with CERT_VERIFY msg\n");
  302. remove_flow(f);
  303. goto err;
  304. }
  305. break;
  306. case TLS_CLNT_KEYEX:
  307. #ifdef DEBUG_HS
  308. printf("Received client key exchange\n");
  309. #endif
  310. if(update_finish_hash(f, p)){
  311. fprintf(stderr, "Error updating finish hash with CLNT_KEYEX msg\n");
  312. remove_flow(f);
  313. goto err;
  314. }
  315. break;
  316. case TLS_FINISHED:
  317. #ifdef DEBUG_HS
  318. printf("Received finished (%d) (%x:%d -> %x:%d)\n", incoming, f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  319. #endif
  320. if(verify_finish_hash(f,p, incoming)){
  321. fprintf(stderr, "Error verifying finished hash\n");
  322. remove_flow(f);
  323. goto err;
  324. }
  325. //re-encrypt finished message
  326. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x16, 1, 1);
  327. #ifdef HS_DEBUG
  328. printf("New finished ciphertext:\n");
  329. for(int i=0; i< record_len; i++){
  330. printf("%02x ", record[i]);
  331. }
  332. printf("\n");
  333. #endif
  334. if(n<=0){
  335. printf("Error re-encrypting finished (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port),
  336. f->dst_ip.s_addr, ntohs(f->dst_port));
  337. }
  338. if((f->in_encrypted == 2) && (f->out_encrypted == 2)){
  339. f->application = 1;
  340. printf("Handshake complete!\n");
  341. }
  342. break;
  343. default:
  344. printf("Error? (%x:%d -> %x:%d)...\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  345. remove_flow(f);
  346. goto err;
  347. }
  348. break;
  349. case APP:
  350. printf("Application Data (%x:%d -> %x:%d)...\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  351. break;
  352. case CCS:
  353. #ifdef DEBUG_HS
  354. printf("CCS (%x:%d -> %x:%d) \n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  355. #endif
  356. /*Initialize ciphers */
  357. if ((!f->in_encrypted) && (!f->out_encrypted)){
  358. if(init_ciphers(f)){
  359. remove_flow(f);
  360. goto err;
  361. }
  362. }
  363. if(incoming){
  364. f->in_encrypted = 1;
  365. } else {
  366. f->out_encrypted = 1;
  367. }
  368. break;
  369. case ALERT:
  370. p = record;
  371. p += RECORD_HEADER_LEN;
  372. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  373. //decrypt alert
  374. encrypt(f, p, p, record_len - RECORD_HEADER_LEN, incoming, 0x16, 0, 0);
  375. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  376. }
  377. printf("Alert (%x:%d -> %x:%d) %02x %02x \n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port), p[0], p[1]);
  378. fflush(stdout);
  379. //re-encrypt alert
  380. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  381. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x16, 1, 1);
  382. if(n <= 0){
  383. printf("Error re-encrypting alert\n");
  384. }
  385. }
  386. break;
  387. case HB:
  388. printf("Heartbeat\n");
  389. break;
  390. default:
  391. printf("Error: Not a Record (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  392. fflush(stdout);
  393. remove_flow(f);
  394. goto err;
  395. }
  396. return 0;
  397. err:
  398. return 1;
  399. }
  400. /** Removes the tagged flow from the flow table: happens when
  401. * the station receives a TCP RST or FIN packet
  402. *
  403. * Input:
  404. * index: the index into the flow table of the tagged flow
  405. *
  406. * Output:
  407. * 0 on success, 1 on failure
  408. */
  409. int remove_flow(flow *f) {
  410. sem_wait(&flow_table_lock);
  411. //decrement reference counter
  412. f->ref_ctr--;
  413. if(f->ref_ctr){ //if there are still references to f, wait to free it
  414. printf("Cannot free %p, still %d reference(s)\n", f, f->ref_ctr);
  415. f->removed = 1;
  416. sem_post(&flow_table_lock);
  417. return 0;
  418. }
  419. if(f->removed)
  420. printf("Trying again to free\n");
  421. frame *first_frame = f->us_frame_queue->first_frame;
  422. while(first_frame != NULL){
  423. printf("Injecting delayed frame (seq = %u )\n", first_frame->seq_num);
  424. inject_packet(first_frame->iargs, first_frame->header, first_frame->packet);
  425. frame *tmp = first_frame->next;
  426. free(first_frame);
  427. first_frame = tmp;
  428. }
  429. free(f->us_frame_queue);
  430. first_frame = f->ds_frame_queue->first_frame;
  431. while(first_frame != NULL){
  432. printf("Injecting delayed frame (seq = %u )\n", first_frame->seq_num);
  433. inject_packet(first_frame->iargs, first_frame->header, first_frame->packet);
  434. frame *tmp = first_frame->next;
  435. free(first_frame);
  436. first_frame = tmp;
  437. }
  438. free(f->ds_frame_queue);
  439. //Empty application data queues
  440. packet *tmp = f->upstream_app_data->first_packet;
  441. while(tmp != NULL){
  442. f->upstream_app_data->first_packet = tmp->next;
  443. free(tmp->data);
  444. free(tmp);
  445. tmp = f->upstream_app_data->first_packet;
  446. }
  447. free(f->upstream_app_data);
  448. tmp = f->downstream_app_data->first_packet;
  449. while(tmp != NULL){
  450. f->downstream_app_data->first_packet = tmp->next;
  451. free(tmp->data);
  452. free(tmp);
  453. tmp = f->downstream_app_data->first_packet;
  454. }
  455. free(f->downstream_app_data);
  456. if(f->ds_hs_queue != NULL){
  457. remove_queue(f->ds_hs_queue);
  458. }
  459. if(f->us_hs_queue != NULL){
  460. remove_queue(f->us_hs_queue);
  461. }
  462. //free partial record headers
  463. if(f->partial_record_header_len > 0){
  464. f->partial_record_header_len = 0;
  465. free(f->partial_record_header);
  466. }
  467. //Clean up cipher ctxs
  468. EVP_MD_CTX_cleanup(f->finish_md_ctx);
  469. if(f->finish_md_ctx != NULL){
  470. EVP_MD_CTX_destroy(f->finish_md_ctx);
  471. }
  472. if(f->clnt_read_ctx != NULL){
  473. EVP_CIPHER_CTX_cleanup(f->clnt_read_ctx);
  474. OPENSSL_free(f->clnt_read_ctx);
  475. f->clnt_read_ctx = NULL;
  476. }
  477. if(f->clnt_write_ctx != NULL){
  478. EVP_CIPHER_CTX_cleanup(f->clnt_write_ctx);
  479. OPENSSL_free(f->clnt_write_ctx);
  480. f->clnt_write_ctx = NULL;
  481. }
  482. if(f->srvr_read_ctx != NULL){
  483. EVP_CIPHER_CTX_free(f->srvr_read_ctx);
  484. }
  485. if(f->srvr_write_ctx != NULL){
  486. EVP_CIPHER_CTX_free(f->srvr_write_ctx);
  487. }
  488. if(f->ecdh != NULL){
  489. EC_KEY_free(f->ecdh);
  490. }
  491. if(f->dh != NULL){
  492. DH_free(f->dh);
  493. }
  494. if(f->current_session != NULL && f->resume_session == 1){
  495. if( f->current_session->session_ticket != NULL){
  496. free(f->current_session->session_ticket);
  497. }
  498. free(f->current_session);
  499. }
  500. if(f->ds_packet_chain != NULL){
  501. packet *tmp = f->ds_packet_chain->first_packet;
  502. while(tmp != NULL){
  503. f->ds_packet_chain->first_packet = tmp->next;
  504. printf("Freed data %p\n", tmp->data);
  505. printf("Freed packet %p\n", tmp);
  506. free(tmp->data);
  507. free(tmp);
  508. tmp = f->ds_packet_chain->first_packet;
  509. }
  510. }
  511. free(f->ds_packet_chain);
  512. if(f->us_packet_chain != NULL){
  513. packet *tmp = f->us_packet_chain->first_packet;
  514. while(tmp != NULL){
  515. f->us_packet_chain->first_packet = tmp->next;
  516. printf("Freed data %p\n", tmp->data);
  517. printf("Freed packet %p\n", tmp);
  518. free(tmp->data);
  519. free(tmp);
  520. tmp = f->us_packet_chain->first_packet;
  521. }
  522. }
  523. free(f->us_packet_chain);
  524. if(f->upstream_queue != NULL){
  525. queue_block *tmp = f->upstream_queue;
  526. while(tmp != NULL){
  527. f->upstream_queue = tmp->next;
  528. printf("Freed data %p\n", tmp->data);
  529. printf("Freed packet %p\n", tmp);
  530. free(tmp->data);
  531. free(tmp);
  532. tmp = f->upstream_queue;
  533. }
  534. }
  535. flow_entry *entry = table->first_entry;
  536. if(entry->f == f){
  537. table->first_entry = entry->next;
  538. free(entry->f);
  539. free(entry);
  540. table->len --;
  541. } else {
  542. flow_entry *next;
  543. for(int i=0; i< table->len; i++){
  544. if(entry->next != NULL){
  545. next = entry->next;
  546. } else {
  547. printf("Flow not in table\n");
  548. break;
  549. }
  550. if(next->f == f){
  551. entry->next = next->next;
  552. free(next->f);
  553. free(next);
  554. table->len --;
  555. break;
  556. }
  557. entry = next;
  558. }
  559. }
  560. sem_post(&flow_table_lock);
  561. return 1;
  562. }
  563. /** Returns the index of a flow in the flow table if
  564. * it exists, returns 0 if it is not present.
  565. *
  566. * Inputs:
  567. * observed: details for the observed flow
  568. *
  569. * Output:
  570. * flow struct from table or NULL if it doesn't exist
  571. */
  572. flow *check_flow(struct packet_info *info){
  573. /* Loop through flows in table and see if it exists */
  574. int i;
  575. flow_entry *entry = table->first_entry;
  576. flow *candidate;
  577. flow *found = NULL;
  578. if(entry == NULL)
  579. return NULL;
  580. sem_wait(&flow_table_lock);
  581. /* Check first in this direction */
  582. for(i=0; i<table->len; i++){
  583. if(entry == NULL){
  584. printf("Error: entry is null\n");
  585. break;
  586. }
  587. candidate = entry->f;
  588. if(candidate->src_ip.s_addr == info->ip_hdr->src.s_addr){
  589. if(candidate->dst_ip.s_addr == info->ip_hdr->dst.s_addr){
  590. if(candidate->src_port == info->tcp_hdr->src_port){
  591. if(candidate->dst_port == info->tcp_hdr->dst_port){
  592. found = candidate;
  593. }
  594. }
  595. }
  596. }
  597. entry = entry->next;
  598. }
  599. entry = table->first_entry;
  600. /* Then in the other direction */
  601. for(i=0; i<table->len; i++){
  602. if(entry == NULL){
  603. printf("Error: entry is null\n");
  604. break;
  605. }
  606. candidate = entry->f;
  607. if(candidate->src_ip.s_addr == info->ip_hdr->dst.s_addr){
  608. if(candidate->dst_ip.s_addr == info->ip_hdr->src.s_addr){
  609. if(candidate->src_port == info->tcp_hdr->dst_port){
  610. if(candidate->dst_port == info->tcp_hdr->src_port){
  611. found = candidate;
  612. }
  613. }
  614. }
  615. }
  616. entry = entry->next;
  617. }
  618. if(found != NULL){
  619. found->ref_ctr++;
  620. printf("Acquiring flow (%p ref ctr %d)\n", found, found->ref_ctr);
  621. }
  622. sem_post(&flow_table_lock);
  623. if(found != NULL && found->removed){
  624. remove_flow(found);
  625. found=NULL;
  626. }
  627. return found;
  628. }
  629. int init_session_cache(void){
  630. sessions = emalloc(sizeof(session_cache));
  631. sessions->length = 0;
  632. sessions->first_session = NULL;
  633. return 0;
  634. }
  635. /** Called from ServerHello, verifies that the session id returned matches
  636. * the session id requested from the client hello
  637. *
  638. * Input:
  639. * f: the tagged flow
  640. * hs: a pointer to the ServerHello message
  641. *
  642. * Output:
  643. * 0 if success, 1 if failed
  644. */
  645. int verify_session_id(flow *f, uint8_t *hs){
  646. if (f->current_session == NULL)
  647. return 1;
  648. //increment pointer to point to sessionid
  649. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  650. p += 2; //skip version
  651. p += SSL3_RANDOM_SIZE; //skip random
  652. uint8_t id_len = (uint8_t) p[0];
  653. p ++;
  654. //check to see if it matches flow's session id set by ClientHello
  655. if(f->current_session->session_id_len > 0 && !memcmp(f->current_session->session_id, p, id_len)){
  656. //if it matched, update flow with master secret :D
  657. #ifdef DEBUG_HS
  658. printf("Session id matched!\n");
  659. printf("First session id (%p->%p):", sessions, sessions->first_session);
  660. #endif
  661. session *last = sessions->first_session;
  662. int found = 0;
  663. for(int i=0; ((i<sessions->length) && (!found)); i++){
  664. #ifdef DEBUG_HS
  665. printf("Checking saved session id: ");
  666. for (int j=0; j< last->session_id_len; j++){
  667. printf("%02x ", last->session_id[j]);
  668. }
  669. printf("\n");
  670. #endif
  671. if(!memcmp(last->session_id, f->current_session->session_id, id_len)){
  672. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  673. found = 1;
  674. }
  675. last = last->next;
  676. }
  677. if((!found) && (f->current_session->session_ticket_len > 0)){
  678. last = sessions->first_session;
  679. for(int i=0; ((i<sessions->length) && (!found)); i++){
  680. if( (last->session_ticket != NULL) && (last->session_ticket_len == f->current_session->session_ticket_len)){
  681. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  682. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  683. found = 1;
  684. #ifdef DEBUG_HS
  685. printf("Found new session ticket (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  686. for(int i=0; i< last->session_ticket_len; i++){
  687. printf("%02x ", last->session_ticket[i]);
  688. }
  689. printf("\n");
  690. #endif
  691. }
  692. }
  693. last = last->next;
  694. }
  695. }
  696. } else if (f->current_session->session_id_len == 0){
  697. //search for session ticket in session cache
  698. printf("clnt session id was empty, looking for ticket\n");
  699. session *last = sessions->first_session;
  700. if(f->current_session->session_ticket_len > 0){
  701. last = sessions->first_session;
  702. for(int i=0; i<sessions->length; i++){
  703. if(last->session_ticket_len == f->current_session->session_ticket_len){
  704. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  705. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  706. #ifdef DEBUG_HS
  707. printf("Found new session ticket (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  708. for(int i=0; i< last->session_ticket_len; i++){
  709. printf("%02x ", last->session_ticket[i]);
  710. }
  711. printf("\n");
  712. break;
  713. #endif
  714. }
  715. }
  716. last = last->next;
  717. }
  718. }
  719. } else if (f->current_session->session_id_len > 0){
  720. //server refused resumption, save new session id
  721. printf("session ids did not match, saving new id\n");
  722. save_session_id(f, p);
  723. }
  724. return 0;
  725. }
  726. /* Called from ClientHello. Checks to see if the session id len is > 0. If so,
  727. * saves sessionid for later verification. Also checks to see if a session
  728. * ticket is included as an extension.
  729. *
  730. * Input:
  731. * f: the tagged flow
  732. * hs: a pointer to the ServerHello message
  733. *
  734. * Output:
  735. * 0 if success, 1 if failed
  736. */
  737. int check_session(flow *f, uint8_t *hs, uint32_t len){
  738. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  739. p += 2; //skip version
  740. p += SSL3_RANDOM_SIZE; //skip random
  741. session *new_session = emalloc(sizeof(session));
  742. new_session->session_id_len = (uint8_t) p[0];
  743. new_session->session_ticket_len = 0;
  744. new_session->session_ticket = NULL;
  745. p ++;
  746. if(new_session->session_id_len > 0){
  747. f->resume_session = 1;
  748. memcpy(new_session->session_id, p, new_session->session_id_len);
  749. new_session->next = NULL;
  750. #ifdef DEBUG_HS
  751. printf("Requested new session (%x:%d -> %x:%d)\n", f->src_ip.s_addr, f->src_port, f->dst_ip.s_addr, f->dst_port);
  752. printf("session id: \n");
  753. for(int i=0; i< new_session->session_id_len; i++){
  754. printf("%02x ", p[i]);
  755. }
  756. printf("\n");
  757. #endif
  758. f->current_session = new_session;
  759. }
  760. p += new_session->session_id_len;
  761. //check to see if there is a session ticket included
  762. //skip to extensions
  763. uint16_t ciphersuite_len = (p[0] << 8) + p[1];
  764. p += 2 + ciphersuite_len;
  765. uint8_t compress_meth_len = p[0];
  766. p += 1 + compress_meth_len;
  767. //search for SessionTicket TLS extension
  768. if(2 + SSL3_RANDOM_SIZE + new_session->session_id_len + 1 + 2 + ciphersuite_len + 1 + compress_meth_len > len){
  769. //no extension
  770. if(f->current_session == NULL)
  771. free(new_session);
  772. return 0;
  773. }
  774. uint16_t extensions_len = (p[0] << 8) + p[1];
  775. p += 2;
  776. while(extensions_len > 0){
  777. uint16_t type = (p[0] << 8) + p[1];
  778. p += 2;
  779. uint16_t ext_len = (p[0] << 8) + p[1];
  780. p += 2;
  781. if(type == 0x23){
  782. if(ext_len > 0){
  783. f->resume_session = 1;
  784. new_session->session_ticket_len = ext_len;
  785. new_session->session_ticket = ecalloc(1, ext_len);
  786. memcpy(new_session->session_ticket, p, ext_len);
  787. f->current_session = new_session;
  788. }
  789. }
  790. p += ext_len;
  791. extensions_len -= (4 + ext_len);
  792. }
  793. if(!f->resume_session){
  794. free(new_session);
  795. f->stall = 0; //unstall the next packet
  796. }
  797. return 0;
  798. }
  799. /* Called from ServerHello during full handshake. Adds the session id to the
  800. * cache for later resumptions
  801. *
  802. * Input:
  803. * f: the tagged flow
  804. * hs: a pointer to the ServerHello message
  805. *
  806. * Output:
  807. * 0 if success, 1 if failed
  808. */
  809. int save_session_id(flow *f, uint8_t *hs){
  810. //increment pointer to point to sessionid
  811. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  812. p += 2; //skip version
  813. p += SSL3_RANDOM_SIZE; //skip random
  814. session *new_session = emalloc(sizeof(session));
  815. new_session->session_id_len = (uint8_t) p[0];
  816. if((new_session->session_id_len <= 0) || (new_session->session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH)){
  817. //if this value is zero, the session is non-resumable or the
  818. //server will issue a NewSessionTicket handshake message
  819. free(new_session);
  820. return 0;
  821. }
  822. p++;
  823. memcpy(new_session->session_id, p, new_session->session_id_len);
  824. new_session->session_ticket_len = 0;
  825. new_session->session_ticket = NULL;
  826. new_session->next = NULL;
  827. if(f->current_session != NULL){
  828. free(f->current_session);
  829. }
  830. f->resume_session = 0;
  831. f->current_session = new_session;
  832. if(sessions->first_session == NULL){
  833. sessions->first_session = new_session;
  834. printf("First session id (%p->%p):", sessions, sessions->first_session);
  835. for(int i=0; i< new_session->session_id_len; i++){
  836. printf(" %02x", sessions->first_session->session_id[i]);
  837. }
  838. printf("\n");
  839. } else {
  840. session *last = sessions->first_session;
  841. for(int i=0; i< sessions->length -1; i++){
  842. if(last == NULL){
  843. printf("UH OH: last is null?\n");
  844. fflush(stdout);
  845. }
  846. last = last->next;
  847. }
  848. last->next = new_session;
  849. }
  850. sessions->length ++;
  851. #ifdef DEBUG_HS
  852. printf("Saved session id:");
  853. for(int i=0; i< new_session->session_id_len; i++){
  854. printf(" %02x", new_session->session_id[i]);
  855. }
  856. printf("\n");
  857. printf("THERE ARE NOW %d saved sessions\n", sessions->length);
  858. #endif
  859. return 0;
  860. }
  861. /* Called from NewSessionTicket. Adds the session ticket to the
  862. * cache for later resumptions
  863. *
  864. * Input:
  865. * f: the tagged flow
  866. * hs: a pointer to the ServerHello message
  867. *
  868. * Output:
  869. * 0 if success, 1 if failed
  870. */
  871. int save_session_ticket(flow *f, uint8_t *hs, uint32_t len){
  872. #ifdef DEBUG_HS
  873. printf("TICKET HDR:");
  874. for(int i=0; i< HANDSHAKE_HEADER_LEN; i++){
  875. printf("%02x ", hs[i]);
  876. }
  877. printf("\n");
  878. #endif
  879. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  880. p += 4;
  881. session *new_session = ecalloc(1, sizeof(session));
  882. new_session->session_id_len = 0;
  883. new_session->session_ticket_len = (p[0] << 8) + p[1];
  884. new_session->next = NULL;
  885. p += 2;
  886. uint8_t *ticket = emalloc(new_session->session_ticket_len);
  887. memcpy(ticket, p, new_session->session_ticket_len);
  888. new_session->session_ticket = ticket;
  889. memcpy(new_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  890. if(sessions->first_session == NULL){
  891. sessions->first_session = new_session;
  892. } else {
  893. session *last = sessions->first_session;
  894. for(int i=0; i< (sessions->length-1); i++){
  895. if(last == NULL){
  896. printf("UH OH: last is null?\n");
  897. fflush(stdout);
  898. }
  899. last = last->next;
  900. }
  901. last->next = new_session;
  902. }
  903. sessions->length ++;
  904. #ifdef DEBUG_HS
  905. printf("Saved session ticket:");
  906. for(int i=0; i< new_session->session_ticket_len; i++){
  907. printf(" %02x", p[i]);
  908. }
  909. printf("\n");
  910. fflush(stdout);
  911. printf("Saved session master secret:");
  912. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  913. printf(" %02x", new_session->master_secret[i]);
  914. }
  915. printf("\n");
  916. fflush(stdout);
  917. printf("THERE ARE NOW %d saved sessions (2)\n", sessions->length);
  918. fflush(stdout);
  919. #endif
  920. return 0;
  921. }
  922. /* Adds a (handshake) packet to the flow's packet chain. If it can complete a record, passes
  923. * this record to update_flow
  924. *
  925. * Note: the code in slitheen-proxy.c should ensure that this function only ever gets the next
  926. * expected sequence number
  927. */
  928. int add_packet(flow *f, struct packet_info *info){
  929. if (info->tcp_hdr == NULL || info->app_data_len <= 0){
  930. return 0;
  931. }
  932. packet *new_packet = emalloc(sizeof(packet));
  933. new_packet->seq_num = ntohl(info->tcp_hdr->sequence_num);
  934. new_packet->len = info->app_data_len;
  935. uint8_t *packet_data = emalloc(new_packet->len);
  936. memcpy(packet_data, info->app_data, new_packet->len);
  937. new_packet->data = packet_data;
  938. new_packet->next = NULL;
  939. uint8_t incoming = (info->ip_hdr->src.s_addr == f->src_ip.s_addr) ? 0 : 1;
  940. packet_chain *chain = (incoming) ? f->ds_packet_chain : f->us_packet_chain;
  941. queue *packet_queue = (incoming) ? f->ds_hs_queue : f->us_hs_queue;
  942. if(new_packet->seq_num < chain->expected_seq_num){
  943. //see if this packet contains any data we are missing
  944. //TODO: figure out how/why this happens and what should follow
  945. printf("ERROR: Received replayed packet O.o\n");
  946. free(new_packet->data);
  947. free(new_packet);
  948. remove_flow(f);
  949. return 1;
  950. }
  951. if(new_packet->seq_num > chain->expected_seq_num) {
  952. printf("ERROR: Received future packet O.o\n");
  953. free(new_packet->data);
  954. free(new_packet);
  955. remove_flow(f);
  956. return 1;
  957. }
  958. //temporary: see if it's the only packet, if so is new record
  959. if(peek(packet_queue, 0) == NULL){
  960. if(new_packet->seq_num == chain->expected_seq_num){
  961. const struct record_header *record_hdr = (struct record_header *) new_packet->data;
  962. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  963. chain->remaining_record_len = chain->record_len;
  964. }
  965. }
  966. //append packet to queue
  967. enqueue(packet_queue, new_packet);
  968. chain->expected_seq_num += new_packet->len;
  969. uint32_t record_offset = 0; //offset into record for updating info with any changes
  970. uint32_t info_offset = 0; //offset into info for updating with changes
  971. uint32_t info_len = 0; //number of bytes that possibly changed
  972. //while there is still data left:
  973. uint32_t available_data = new_packet->len;
  974. while(available_data > 0){
  975. //if full record, give to update_flow
  976. if(chain->remaining_record_len <= new_packet->len){//we have enough to make a record
  977. chain->remaining_record_len = 0;
  978. uint8_t *record = emalloc(chain->record_len);
  979. uint32_t record_len = chain->record_len;
  980. uint32_t tmp_len = chain->record_len;
  981. packet *next = peek(packet_queue, 0);
  982. while(tmp_len > 0){
  983. if(tmp_len >= next->len){
  984. memcpy(record+chain->record_len - tmp_len, next->data, next->len);
  985. if(next == new_packet){
  986. new_packet = NULL;//TODO: why?
  987. record_offset = chain->record_len - tmp_len;
  988. info_len = next->len;
  989. }
  990. tmp_len -= next->len;
  991. //remove packet from queue
  992. next = dequeue(packet_queue);
  993. free(next->data);
  994. free(next);
  995. next = peek(packet_queue, 0); //TODO: Do we need this???
  996. available_data = 0;
  997. } else { //didn't use up entire packet
  998. memcpy(record+chain->record_len - tmp_len, next->data, tmp_len);
  999. if(next == new_packet){//TODO: opposite shouldn't happen?
  1000. record_offset = chain->record_len - tmp_len;
  1001. info_len = tmp_len;
  1002. }
  1003. memmove(next->data, next->data+tmp_len, next->len - tmp_len);
  1004. next->len -= tmp_len;
  1005. available_data -= tmp_len;
  1006. tmp_len = 0;
  1007. //Last part of packet is a new record
  1008. const struct record_header *record_hdr = (struct record_header *) next->data;
  1009. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  1010. chain->remaining_record_len = chain->record_len;
  1011. #ifdef DEBUG
  1012. printf("Found record of type %d\n", record_hdr->type);
  1013. fflush(stdout);
  1014. #endif
  1015. }
  1016. }
  1017. //if handshake is complete, send to relay code
  1018. if(f->application == 1){
  1019. //update packet info and send to replace_packet
  1020. struct packet_info *copy_info = copy_packet_info(info);
  1021. copy_info->app_data = record;
  1022. copy_info->app_data_len = record_len;
  1023. replace_packet(f, copy_info);
  1024. free(copy_info->app_data);
  1025. free(copy_info);
  1026. } else {
  1027. if(update_flow(f, record, incoming)){
  1028. free(record);
  1029. return 1;//error occurred and flow was removed
  1030. }
  1031. if(f->in_encrypted ==2){
  1032. //if server finished message was received, copy changes back to packet
  1033. #ifdef DEBUG
  1034. printf("Replacing info->data with finished message (%d bytes).\n", info_len);
  1035. printf("Previous bytes:\n");
  1036. for(int i=0; i<info_len; i++){
  1037. printf("%02x ", info->app_data[info_offset+i]);
  1038. }
  1039. printf("\n");
  1040. printf("New bytes:\n");
  1041. for(int i=0; i<info_len; i++){
  1042. printf("%02x ", record[record_offset+i]);
  1043. }
  1044. printf("\n");
  1045. printf("SLITHEEN: Previous packet contents:\n");
  1046. for(int i=0; i< info->app_data_len; i++){
  1047. printf("%02x ", info->app_data[i]);
  1048. }
  1049. printf("\n");
  1050. #endif
  1051. memcpy(info->app_data+info_offset, record+record_offset, info_len);
  1052. #ifdef DEBUG
  1053. printf("SLITHEEN: Current packet contents:\n");
  1054. for(int i=0; i< info->app_data_len; i++){
  1055. printf("%02x ", info->app_data[i]);
  1056. }
  1057. printf("\n");
  1058. #endif
  1059. //update TCP checksum
  1060. tcp_checksum(info);
  1061. }
  1062. free(record);
  1063. if(new_packet != NULL){
  1064. info_offset += info_len;
  1065. }
  1066. }
  1067. } else {//can't make a full record yet
  1068. chain->remaining_record_len -= new_packet->len;
  1069. available_data = 0;
  1070. }
  1071. } //exhausted new packet len
  1072. return 0;
  1073. }