flow.c 34 KB

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