flow.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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 the OpenSSL Licence and the
  25. * SSLeay license, the licensors of this Program grant you additional
  26. * permission to convey the resulting work. Corresponding Source for a
  27. * non-source form of such a combination shall include the source code
  28. * for the parts of the OpenSSL library used as well as that of the covered
  29. * work.
  30. */
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <stdint.h>
  34. #include <pthread.h>
  35. #include <errno.h>
  36. #include <semaphore.h>
  37. #include "flow.h"
  38. #include "crypto.h"
  39. #include "slitheen.h"
  40. #include "relay.h"
  41. #include "util.h"
  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(!incoming) {
  321. // We only care about incoming
  322. // Finished messages
  323. break;
  324. }
  325. if(mark_finished_hash(f, p)){
  326. fprintf(stderr, "Error marking finished hash\n");
  327. remove_flow(f);
  328. goto err;
  329. }
  330. //re-encrypt finished message
  331. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x16, 1, 1);
  332. #ifdef HS_DEBUG
  333. printf("New finished ciphertext:\n");
  334. for(int i=0; i< record_len; i++){
  335. printf("%02x ", record[i]);
  336. }
  337. printf("\n");
  338. #endif
  339. if(n<=0){
  340. printf("Error re-encrypting finished (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port),
  341. f->dst_ip.s_addr, ntohs(f->dst_port));
  342. }
  343. if((f->in_encrypted == 2) && (f->out_encrypted == 2)){
  344. f->application = 1;
  345. printf("Handshake complete!\n");
  346. }
  347. break;
  348. default:
  349. 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));
  350. remove_flow(f);
  351. goto err;
  352. }
  353. break;
  354. case APP:
  355. 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));
  356. break;
  357. case CCS:
  358. #ifdef DEBUG_HS
  359. 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));
  360. #endif
  361. /*Initialize ciphers */
  362. if ((!f->in_encrypted) && (!f->out_encrypted)){
  363. if(init_ciphers(f)){
  364. remove_flow(f);
  365. goto err;
  366. }
  367. }
  368. if(incoming){
  369. f->in_encrypted = 1;
  370. } else {
  371. f->out_encrypted = 1;
  372. }
  373. break;
  374. case ALERT:
  375. p = record;
  376. p += RECORD_HEADER_LEN;
  377. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  378. //decrypt alert
  379. encrypt(f, p, p, record_len - RECORD_HEADER_LEN, incoming, 0x16, 0, 0);
  380. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  381. }
  382. 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]);
  383. fflush(stdout);
  384. //re-encrypt alert
  385. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  386. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x16, 1, 1);
  387. if(n <= 0){
  388. printf("Error re-encrypting alert\n");
  389. }
  390. }
  391. break;
  392. case HB:
  393. printf("Heartbeat\n");
  394. break;
  395. default:
  396. 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));
  397. fflush(stdout);
  398. remove_flow(f);
  399. goto err;
  400. }
  401. return 0;
  402. err:
  403. return 1;
  404. }
  405. /** Removes the tagged flow from the flow table: happens when
  406. * the station receives a TCP RST or FIN packet
  407. *
  408. * Input:
  409. * index: the index into the flow table of the tagged flow
  410. *
  411. * Output:
  412. * 0 on success, 1 on failure
  413. */
  414. int remove_flow(flow *f) {
  415. sem_wait(&flow_table_lock);
  416. //decrement reference counter
  417. f->ref_ctr--;
  418. if(f->ref_ctr){ //if there are still references to f, wait to free it
  419. printf("Cannot free %p, still %d reference(s)\n", f, f->ref_ctr);
  420. f->removed = 1;
  421. sem_post(&flow_table_lock);
  422. return 0;
  423. }
  424. if(f->removed)
  425. printf("Trying again to free\n");
  426. frame *first_frame = f->us_frame_queue->first_frame;
  427. while(first_frame != NULL){
  428. printf("Injecting delayed frame (seq = %u )\n", first_frame->seq_num);
  429. inject_packet(first_frame->iargs, first_frame->header, first_frame->packet);
  430. frame *tmp = first_frame->next;
  431. free(first_frame);
  432. first_frame = tmp;
  433. }
  434. free(f->us_frame_queue);
  435. first_frame = f->ds_frame_queue->first_frame;
  436. while(first_frame != NULL){
  437. printf("Injecting delayed frame (seq = %u )\n", first_frame->seq_num);
  438. inject_packet(first_frame->iargs, first_frame->header, first_frame->packet);
  439. frame *tmp = first_frame->next;
  440. free(first_frame);
  441. first_frame = tmp;
  442. }
  443. free(f->ds_frame_queue);
  444. //Empty application data queues
  445. packet *tmp = f->upstream_app_data->first_packet;
  446. while(tmp != NULL){
  447. f->upstream_app_data->first_packet = tmp->next;
  448. free(tmp->data);
  449. free(tmp);
  450. tmp = f->upstream_app_data->first_packet;
  451. }
  452. free(f->upstream_app_data);
  453. tmp = f->downstream_app_data->first_packet;
  454. while(tmp != NULL){
  455. f->downstream_app_data->first_packet = tmp->next;
  456. free(tmp->data);
  457. free(tmp);
  458. tmp = f->downstream_app_data->first_packet;
  459. }
  460. free(f->downstream_app_data);
  461. if(f->ds_hs_queue != NULL){
  462. remove_queue(f->ds_hs_queue);
  463. }
  464. if(f->us_hs_queue != NULL){
  465. remove_queue(f->us_hs_queue);
  466. }
  467. //free partial record headers
  468. if(f->partial_record_header_len > 0){
  469. f->partial_record_header_len = 0;
  470. free(f->partial_record_header);
  471. }
  472. //Clean up cipher ctxs
  473. EVP_MD_CTX_cleanup(f->finish_md_ctx);
  474. if(f->finish_md_ctx != NULL){
  475. EVP_MD_CTX_destroy(f->finish_md_ctx);
  476. }
  477. if(f->clnt_read_ctx != NULL){
  478. EVP_CIPHER_CTX_cleanup(f->clnt_read_ctx);
  479. OPENSSL_free(f->clnt_read_ctx);
  480. f->clnt_read_ctx = NULL;
  481. }
  482. if(f->clnt_write_ctx != NULL){
  483. EVP_CIPHER_CTX_cleanup(f->clnt_write_ctx);
  484. OPENSSL_free(f->clnt_write_ctx);
  485. f->clnt_write_ctx = NULL;
  486. }
  487. if(f->srvr_read_ctx != NULL){
  488. EVP_CIPHER_CTX_free(f->srvr_read_ctx);
  489. }
  490. if(f->srvr_write_ctx != NULL){
  491. EVP_CIPHER_CTX_free(f->srvr_write_ctx);
  492. }
  493. if(f->ecdh != NULL){
  494. EC_KEY_free(f->ecdh);
  495. }
  496. if(f->dh != NULL){
  497. DH_free(f->dh);
  498. }
  499. if(f->current_session != NULL && f->resume_session == 1){
  500. if( f->current_session->session_ticket != NULL){
  501. free(f->current_session->session_ticket);
  502. }
  503. free(f->current_session);
  504. }
  505. if(f->ds_packet_chain != NULL){
  506. packet *tmp = f->ds_packet_chain->first_packet;
  507. while(tmp != NULL){
  508. f->ds_packet_chain->first_packet = tmp->next;
  509. printf("Freed data %p\n", tmp->data);
  510. printf("Freed packet %p\n", tmp);
  511. free(tmp->data);
  512. free(tmp);
  513. tmp = f->ds_packet_chain->first_packet;
  514. }
  515. }
  516. free(f->ds_packet_chain);
  517. if(f->us_packet_chain != NULL){
  518. packet *tmp = f->us_packet_chain->first_packet;
  519. while(tmp != NULL){
  520. f->us_packet_chain->first_packet = tmp->next;
  521. printf("Freed data %p\n", tmp->data);
  522. printf("Freed packet %p\n", tmp);
  523. free(tmp->data);
  524. free(tmp);
  525. tmp = f->us_packet_chain->first_packet;
  526. }
  527. }
  528. free(f->us_packet_chain);
  529. if(f->upstream_queue != NULL){
  530. queue_block *tmp = f->upstream_queue;
  531. while(tmp != NULL){
  532. f->upstream_queue = tmp->next;
  533. printf("Freed data %p\n", tmp->data);
  534. printf("Freed packet %p\n", tmp);
  535. free(tmp->data);
  536. free(tmp);
  537. tmp = f->upstream_queue;
  538. }
  539. }
  540. flow_entry *entry = table->first_entry;
  541. if(entry->f == f){
  542. table->first_entry = entry->next;
  543. free(entry->f);
  544. free(entry);
  545. table->len --;
  546. } else {
  547. flow_entry *next;
  548. for(int i=0; i< table->len; i++){
  549. if(entry->next != NULL){
  550. next = entry->next;
  551. } else {
  552. printf("Flow not in table\n");
  553. break;
  554. }
  555. if(next->f == f){
  556. entry->next = next->next;
  557. free(next->f);
  558. free(next);
  559. table->len --;
  560. break;
  561. }
  562. entry = next;
  563. }
  564. }
  565. sem_post(&flow_table_lock);
  566. return 1;
  567. }
  568. /** Returns the index of a flow in the flow table if
  569. * it exists, returns 0 if it is not present.
  570. *
  571. * Inputs:
  572. * observed: details for the observed flow
  573. *
  574. * Output:
  575. * flow struct from table or NULL if it doesn't exist
  576. */
  577. flow *check_flow(struct packet_info *info){
  578. /* Loop through flows in table and see if it exists */
  579. int i;
  580. flow_entry *entry = table->first_entry;
  581. flow *candidate;
  582. flow *found = NULL;
  583. if(entry == NULL)
  584. return NULL;
  585. sem_wait(&flow_table_lock);
  586. /* Check first in this direction */
  587. for(i=0; i<table->len; i++){
  588. if(entry == NULL){
  589. printf("Error: entry is null\n");
  590. break;
  591. }
  592. candidate = entry->f;
  593. if(candidate->src_ip.s_addr == info->ip_hdr->src.s_addr){
  594. if(candidate->dst_ip.s_addr == info->ip_hdr->dst.s_addr){
  595. if(candidate->src_port == info->tcp_hdr->src_port){
  596. if(candidate->dst_port == info->tcp_hdr->dst_port){
  597. found = candidate;
  598. }
  599. }
  600. }
  601. }
  602. entry = entry->next;
  603. }
  604. entry = table->first_entry;
  605. /* Then in the other direction */
  606. for(i=0; i<table->len; i++){
  607. if(entry == NULL){
  608. printf("Error: entry is null\n");
  609. break;
  610. }
  611. candidate = entry->f;
  612. if(candidate->src_ip.s_addr == info->ip_hdr->dst.s_addr){
  613. if(candidate->dst_ip.s_addr == info->ip_hdr->src.s_addr){
  614. if(candidate->src_port == info->tcp_hdr->dst_port){
  615. if(candidate->dst_port == info->tcp_hdr->src_port){
  616. found = candidate;
  617. }
  618. }
  619. }
  620. }
  621. entry = entry->next;
  622. }
  623. if(found != NULL){
  624. found->ref_ctr++;
  625. printf("Acquiring flow (%p ref ctr %d)\n", found, found->ref_ctr);
  626. }
  627. sem_post(&flow_table_lock);
  628. if(found != NULL && found->removed){
  629. remove_flow(found);
  630. found=NULL;
  631. }
  632. return found;
  633. }
  634. int init_session_cache(void){
  635. sessions = emalloc(sizeof(session_cache));
  636. sessions->length = 0;
  637. sessions->first_session = NULL;
  638. return 0;
  639. }
  640. /** Called from ServerHello, verifies that the session id returned matches
  641. * the session id requested from the client hello
  642. *
  643. * Input:
  644. * f: the tagged flow
  645. * hs: a pointer to the ServerHello message
  646. *
  647. * Output:
  648. * 0 if success, 1 if failed
  649. */
  650. int verify_session_id(flow *f, uint8_t *hs){
  651. if (f->current_session == NULL)
  652. return 1;
  653. //increment pointer to point to sessionid
  654. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  655. p += 2; //skip version
  656. p += SSL3_RANDOM_SIZE; //skip random
  657. uint8_t id_len = (uint8_t) p[0];
  658. p ++;
  659. //check to see if it matches flow's session id set by ClientHello
  660. if(f->current_session->session_id_len > 0 && !memcmp(f->current_session->session_id, p, id_len)){
  661. //if it matched, update flow with master secret :D
  662. #ifdef DEBUG_HS
  663. printf("Session id matched!\n");
  664. printf("First session id (%p->%p):", sessions, sessions->first_session);
  665. #endif
  666. session *last = sessions->first_session;
  667. int found = 0;
  668. for(int i=0; ((i<sessions->length) && (!found)); i++){
  669. #ifdef DEBUG_HS
  670. printf("Checking saved session id: ");
  671. for (int j=0; j< last->session_id_len; j++){
  672. printf("%02x ", last->session_id[j]);
  673. }
  674. printf("\n");
  675. #endif
  676. if(!memcmp(last->session_id, f->current_session->session_id, id_len)){
  677. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  678. found = 1;
  679. }
  680. last = last->next;
  681. }
  682. if((!found) && (f->current_session->session_ticket_len > 0)){
  683. last = sessions->first_session;
  684. for(int i=0; ((i<sessions->length) && (!found)); i++){
  685. if( (last->session_ticket != NULL) && (last->session_ticket_len == f->current_session->session_ticket_len)){
  686. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  687. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  688. found = 1;
  689. #ifdef DEBUG_HS
  690. 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);
  691. for(int i=0; i< last->session_ticket_len; i++){
  692. printf("%02x ", last->session_ticket[i]);
  693. }
  694. printf("\n");
  695. #endif
  696. }
  697. }
  698. last = last->next;
  699. }
  700. }
  701. } else if (f->current_session->session_id_len == 0){
  702. //search for session ticket in session cache
  703. printf("clnt session id was empty, looking for ticket\n");
  704. session *last = sessions->first_session;
  705. if(f->current_session->session_ticket_len > 0){
  706. last = sessions->first_session;
  707. for(int i=0; i<sessions->length; i++){
  708. if(last->session_ticket_len == f->current_session->session_ticket_len){
  709. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  710. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  711. #ifdef DEBUG_HS
  712. 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);
  713. for(int i=0; i< last->session_ticket_len; i++){
  714. printf("%02x ", last->session_ticket[i]);
  715. }
  716. printf("\n");
  717. break;
  718. #endif
  719. }
  720. }
  721. last = last->next;
  722. }
  723. }
  724. } else if (f->current_session->session_id_len > 0){
  725. //server refused resumption, save new session id
  726. printf("session ids did not match, saving new id\n");
  727. save_session_id(f, p);
  728. }
  729. return 0;
  730. }
  731. /* Called from ClientHello. Checks to see if the session id len is > 0. If so,
  732. * saves sessionid for later verification. Also checks to see if a session
  733. * ticket is included as an extension.
  734. *
  735. * Input:
  736. * f: the tagged flow
  737. * hs: a pointer to the ServerHello message
  738. *
  739. * Output:
  740. * 0 if success, 1 if failed
  741. */
  742. int check_session(flow *f, uint8_t *hs, uint32_t len){
  743. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  744. p += 2; //skip version
  745. p += SSL3_RANDOM_SIZE; //skip random
  746. session *new_session = emalloc(sizeof(session));
  747. new_session->session_id_len = (uint8_t) p[0];
  748. new_session->session_ticket_len = 0;
  749. new_session->session_ticket = NULL;
  750. p ++;
  751. if(new_session->session_id_len > 0){
  752. f->resume_session = 1;
  753. memcpy(new_session->session_id, p, new_session->session_id_len);
  754. new_session->next = NULL;
  755. #ifdef DEBUG_HS
  756. 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);
  757. printf("session id: \n");
  758. for(int i=0; i< new_session->session_id_len; i++){
  759. printf("%02x ", p[i]);
  760. }
  761. printf("\n");
  762. #endif
  763. f->current_session = new_session;
  764. }
  765. p += new_session->session_id_len;
  766. //check to see if there is a session ticket included
  767. //skip to extensions
  768. uint16_t ciphersuite_len = (p[0] << 8) + p[1];
  769. p += 2 + ciphersuite_len;
  770. uint8_t compress_meth_len = p[0];
  771. p += 1 + compress_meth_len;
  772. //search for SessionTicket TLS extension
  773. if(2 + SSL3_RANDOM_SIZE + new_session->session_id_len + 1 + 2 + ciphersuite_len + 1 + compress_meth_len > len){
  774. //no extension
  775. if(f->current_session == NULL)
  776. free(new_session);
  777. return 0;
  778. }
  779. uint16_t extensions_len = (p[0] << 8) + p[1];
  780. p += 2;
  781. while(extensions_len > 0){
  782. uint16_t type = (p[0] << 8) + p[1];
  783. p += 2;
  784. uint16_t ext_len = (p[0] << 8) + p[1];
  785. p += 2;
  786. if(type == 0x23){
  787. if(ext_len > 0){
  788. f->resume_session = 1;
  789. new_session->session_ticket_len = ext_len;
  790. new_session->session_ticket = ecalloc(1, ext_len);
  791. memcpy(new_session->session_ticket, p, ext_len);
  792. f->current_session = new_session;
  793. }
  794. }
  795. p += ext_len;
  796. extensions_len -= (4 + ext_len);
  797. }
  798. if(!f->resume_session){
  799. free(new_session);
  800. f->stall = 0; //unstall the next packet
  801. }
  802. return 0;
  803. }
  804. /* Called from ServerHello during full handshake. Adds the session id to the
  805. * cache for later resumptions
  806. *
  807. * Input:
  808. * f: the tagged flow
  809. * hs: a pointer to the ServerHello message
  810. *
  811. * Output:
  812. * 0 if success, 1 if failed
  813. */
  814. int save_session_id(flow *f, uint8_t *hs){
  815. //increment pointer to point to sessionid
  816. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  817. p += 2; //skip version
  818. p += SSL3_RANDOM_SIZE; //skip random
  819. session *new_session = emalloc(sizeof(session));
  820. new_session->session_id_len = (uint8_t) p[0];
  821. if((new_session->session_id_len <= 0) || (new_session->session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH)){
  822. //if this value is zero, the session is non-resumable or the
  823. //server will issue a NewSessionTicket handshake message
  824. free(new_session);
  825. return 0;
  826. }
  827. p++;
  828. memcpy(new_session->session_id, p, new_session->session_id_len);
  829. new_session->session_ticket_len = 0;
  830. new_session->session_ticket = NULL;
  831. new_session->next = NULL;
  832. if(f->current_session != NULL){
  833. free(f->current_session);
  834. }
  835. f->resume_session = 0;
  836. f->current_session = new_session;
  837. if(sessions->first_session == NULL){
  838. sessions->first_session = new_session;
  839. printf("First session id (%p->%p):", sessions, sessions->first_session);
  840. for(int i=0; i< new_session->session_id_len; i++){
  841. printf(" %02x", sessions->first_session->session_id[i]);
  842. }
  843. printf("\n");
  844. } else {
  845. session *last = sessions->first_session;
  846. for(int i=0; i< sessions->length -1; i++){
  847. if(last == NULL){
  848. printf("UH OH: last is null?\n");
  849. fflush(stdout);
  850. }
  851. last = last->next;
  852. }
  853. last->next = new_session;
  854. }
  855. sessions->length ++;
  856. #ifdef DEBUG_HS
  857. printf("Saved session id:");
  858. for(int i=0; i< new_session->session_id_len; i++){
  859. printf(" %02x", new_session->session_id[i]);
  860. }
  861. printf("\n");
  862. printf("THERE ARE NOW %d saved sessions\n", sessions->length);
  863. #endif
  864. return 0;
  865. }
  866. /* Called from NewSessionTicket. Adds the session ticket to the
  867. * cache for later resumptions
  868. *
  869. * Input:
  870. * f: the tagged flow
  871. * hs: a pointer to the ServerHello message
  872. *
  873. * Output:
  874. * 0 if success, 1 if failed
  875. */
  876. int save_session_ticket(flow *f, uint8_t *hs, uint32_t len){
  877. #ifdef DEBUG_HS
  878. printf("TICKET HDR:");
  879. for(int i=0; i< HANDSHAKE_HEADER_LEN; i++){
  880. printf("%02x ", hs[i]);
  881. }
  882. printf("\n");
  883. #endif
  884. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  885. p += 4;
  886. session *new_session = ecalloc(1, sizeof(session));
  887. new_session->session_id_len = 0;
  888. new_session->session_ticket_len = (p[0] << 8) + p[1];
  889. new_session->next = NULL;
  890. p += 2;
  891. uint8_t *ticket = emalloc(new_session->session_ticket_len);
  892. memcpy(ticket, p, new_session->session_ticket_len);
  893. new_session->session_ticket = ticket;
  894. memcpy(new_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  895. if(sessions->first_session == NULL){
  896. sessions->first_session = new_session;
  897. } else {
  898. session *last = sessions->first_session;
  899. for(int i=0; i< (sessions->length-1); i++){
  900. if(last == NULL){
  901. printf("UH OH: last is null?\n");
  902. fflush(stdout);
  903. }
  904. last = last->next;
  905. }
  906. last->next = new_session;
  907. }
  908. sessions->length ++;
  909. #ifdef DEBUG_HS
  910. printf("Saved session ticket:");
  911. for(int i=0; i< new_session->session_ticket_len; i++){
  912. printf(" %02x", p[i]);
  913. }
  914. printf("\n");
  915. fflush(stdout);
  916. printf("Saved session master secret:");
  917. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  918. printf(" %02x", new_session->master_secret[i]);
  919. }
  920. printf("\n");
  921. fflush(stdout);
  922. printf("THERE ARE NOW %d saved sessions (2)\n", sessions->length);
  923. fflush(stdout);
  924. #endif
  925. return 0;
  926. }
  927. /* Adds a (handshake) packet to the flow's packet chain. If it can complete a record, passes
  928. * this record to update_flow
  929. *
  930. * Note: the code in slitheen-proxy.c should ensure that this function only ever gets the next
  931. * expected sequence number
  932. */
  933. int add_packet(flow *f, struct packet_info *info){
  934. if (info->tcp_hdr == NULL || info->app_data_len <= 0){
  935. return 0;
  936. }
  937. packet *new_packet = emalloc(sizeof(packet));
  938. new_packet->seq_num = ntohl(info->tcp_hdr->sequence_num);
  939. new_packet->len = info->app_data_len;
  940. uint8_t *packet_data = emalloc(new_packet->len);
  941. memcpy(packet_data, info->app_data, new_packet->len);
  942. new_packet->data = packet_data;
  943. new_packet->next = NULL;
  944. uint8_t incoming = (info->ip_hdr->src.s_addr == f->src_ip.s_addr) ? 0 : 1;
  945. packet_chain *chain = (incoming) ? f->ds_packet_chain : f->us_packet_chain;
  946. queue *packet_queue = (incoming) ? f->ds_hs_queue : f->us_hs_queue;
  947. if(new_packet->seq_num < chain->expected_seq_num){
  948. //see if this packet contains any data we are missing
  949. //TODO: figure out how/why this happens and what should follow
  950. printf("ERROR: Received replayed packet O.o\n");
  951. free(new_packet->data);
  952. free(new_packet);
  953. remove_flow(f);
  954. return 1;
  955. }
  956. if(new_packet->seq_num > chain->expected_seq_num) {
  957. printf("ERROR: Received future packet O.o\n");
  958. free(new_packet->data);
  959. free(new_packet);
  960. remove_flow(f);
  961. return 1;
  962. }
  963. //temporary: see if it's the only packet, if so is new record
  964. if(peek(packet_queue, 0) == NULL){
  965. if(new_packet->seq_num == chain->expected_seq_num){
  966. const struct record_header *record_hdr = (struct record_header *) new_packet->data;
  967. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  968. chain->remaining_record_len = chain->record_len;
  969. }
  970. }
  971. //append packet to queue
  972. enqueue(packet_queue, new_packet);
  973. chain->expected_seq_num += new_packet->len;
  974. uint32_t record_offset = 0; //offset into record for updating info with any changes
  975. uint32_t info_offset = 0; //offset into info for updating with changes
  976. uint32_t info_len = 0; //number of bytes that possibly changed
  977. //while there is still data left:
  978. uint32_t available_data = new_packet->len;
  979. while(available_data > 0){
  980. //if full record, give to update_flow
  981. if(chain->remaining_record_len <= new_packet->len){//we have enough to make a record
  982. chain->remaining_record_len = 0;
  983. uint8_t *record = emalloc(chain->record_len);
  984. uint32_t record_len = chain->record_len;
  985. uint32_t tmp_len = chain->record_len;
  986. packet *next = peek(packet_queue, 0);
  987. while(tmp_len > 0){
  988. if(tmp_len >= next->len){
  989. memcpy(record+chain->record_len - tmp_len, next->data, next->len);
  990. if(next == new_packet){
  991. new_packet = NULL;//TODO: why?
  992. record_offset = chain->record_len - tmp_len;
  993. info_len = next->len;
  994. }
  995. tmp_len -= next->len;
  996. //remove packet from queue
  997. next = dequeue(packet_queue);
  998. free(next->data);
  999. free(next);
  1000. next = peek(packet_queue, 0); //TODO: Do we need this???
  1001. available_data = 0;
  1002. } else { //didn't use up entire packet
  1003. memcpy(record+chain->record_len - tmp_len, next->data, tmp_len);
  1004. if(next == new_packet){//TODO: opposite shouldn't happen?
  1005. record_offset = chain->record_len - tmp_len;
  1006. info_len = tmp_len;
  1007. }
  1008. memmove(next->data, next->data+tmp_len, next->len - tmp_len);
  1009. next->len -= tmp_len;
  1010. available_data -= tmp_len;
  1011. tmp_len = 0;
  1012. //Last part of packet is a new record
  1013. const struct record_header *record_hdr = (struct record_header *) next->data;
  1014. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  1015. chain->remaining_record_len = chain->record_len;
  1016. #ifdef DEBUG
  1017. printf("Found record of type %d\n", record_hdr->type);
  1018. fflush(stdout);
  1019. #endif
  1020. }
  1021. }
  1022. //if handshake is complete, send to relay code
  1023. if(f->application == 1){
  1024. //update packet info and send to replace_packet
  1025. struct packet_info *copy_info = copy_packet_info(info);
  1026. copy_info->app_data = record;
  1027. copy_info->app_data_len = record_len;
  1028. replace_packet(f, copy_info);
  1029. free(copy_info->app_data);
  1030. free(copy_info);
  1031. } else {
  1032. if(update_flow(f, record, incoming)){
  1033. free(record);
  1034. return 1;//error occurred and flow was removed
  1035. }
  1036. if(f->in_encrypted ==2){
  1037. //if server finished message was received, copy changes back to packet
  1038. #ifdef DEBUG
  1039. printf("Replacing info->data with finished message (%d bytes).\n", info_len);
  1040. printf("Previous bytes:\n");
  1041. for(int i=0; i<info_len; i++){
  1042. printf("%02x ", info->app_data[info_offset+i]);
  1043. }
  1044. printf("\n");
  1045. printf("New bytes:\n");
  1046. for(int i=0; i<info_len; i++){
  1047. printf("%02x ", record[record_offset+i]);
  1048. }
  1049. printf("\n");
  1050. printf("SLITHEEN: Previous packet contents:\n");
  1051. for(int i=0; i< info->app_data_len; i++){
  1052. printf("%02x ", info->app_data[i]);
  1053. }
  1054. printf("\n");
  1055. #endif
  1056. memcpy(info->app_data+info_offset, record+record_offset, info_len);
  1057. #ifdef DEBUG
  1058. printf("SLITHEEN: Current packet contents:\n");
  1059. for(int i=0; i< info->app_data_len; i++){
  1060. printf("%02x ", info->app_data[i]);
  1061. }
  1062. printf("\n");
  1063. #endif
  1064. //update TCP checksum
  1065. tcp_checksum(info);
  1066. }
  1067. free(record);
  1068. if(new_packet != NULL){
  1069. info_offset += info_len;
  1070. }
  1071. }
  1072. } else {//can't make a full record yet
  1073. chain->remaining_record_len -= new_packet->len;
  1074. available_data = 0;
  1075. }
  1076. } //exhausted new packet len
  1077. return 0;
  1078. }