flow.c 34 KB

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