flow.c 35 KB

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