flow.c 30 KB

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