flow.c 29 KB

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