flow.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. memset(f->read_seq, 0, 8);
  302. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x16, 1);
  303. #ifdef HS_DEBUG
  304. printf("New finished ciphertext:\n");
  305. for(int i=0; i< record_len; i++){
  306. printf("%02x ", record[i]);
  307. }
  308. printf("\n");
  309. #endif
  310. if(n<=0){
  311. printf("Error re-encrypting finished (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port),
  312. f->dst_ip.s_addr, ntohs(f->dst_port));
  313. }
  314. if((f->in_encrypted == 2) && (f->out_encrypted == 2)){
  315. 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. }
  324. break;
  325. case APP:
  326. printf("Application Data (%x:%d -> %x:%d)...\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  327. break;
  328. case CCS:
  329. #ifdef DEBUG_HS
  330. printf("CCS (%x:%d -> %x:%d) \n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  331. #endif
  332. /*Initialize ciphers */
  333. if ((!f->in_encrypted) && (!f->out_encrypted)){
  334. if(init_ciphers(f)){
  335. fprintf(stderr, "Failed to initialize ciphers\n");
  336. remove_flow(f);
  337. goto err;
  338. }
  339. }
  340. if(incoming){
  341. f->in_encrypted = 1;
  342. } else {
  343. f->out_encrypted = 1;
  344. }
  345. break;
  346. case ALERT:
  347. p = record;
  348. p += RECORD_HEADER_LEN;
  349. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  350. encrypt(f, p, p, record_len - RECORD_HEADER_LEN, incoming, 0x16, 0);
  351. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  352. }
  353. printf("Alert (%x:%d -> %x:%d) %02x %02x \n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port), p[0], p[1]);
  354. fflush(stdout);
  355. break;
  356. case HB:
  357. printf("Heartbeat\n");
  358. break;
  359. default:
  360. 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));
  361. fflush(stdout);
  362. remove_flow(f);
  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. //Empty application data queues
  380. packet *tmp = f->upstream_app_data->first_packet;
  381. while(tmp != NULL){
  382. f->upstream_app_data->first_packet = tmp->next;
  383. free(tmp->data);
  384. free(tmp);
  385. tmp = f->upstream_app_data->first_packet;
  386. }
  387. free(f->upstream_app_data);
  388. tmp = f->downstream_app_data->first_packet;
  389. while(tmp != NULL){
  390. f->downstream_app_data->first_packet = tmp->next;
  391. free(tmp->data);
  392. free(tmp);
  393. tmp = f->downstream_app_data->first_packet;
  394. }
  395. free(f->downstream_app_data);
  396. //Clean up cipher ctxs
  397. EVP_MD_CTX_cleanup(f->finish_md_ctx);
  398. if(f->finish_md_ctx != NULL){
  399. EVP_MD_CTX_destroy(f->finish_md_ctx);
  400. }
  401. if(f->clnt_read_ctx != NULL){
  402. EVP_CIPHER_CTX_cleanup(f->clnt_read_ctx);
  403. OPENSSL_free(f->clnt_read_ctx);
  404. f->clnt_read_ctx = NULL;
  405. }
  406. if(f->clnt_write_ctx != NULL){
  407. EVP_CIPHER_CTX_cleanup(f->clnt_write_ctx);
  408. OPENSSL_free(f->clnt_write_ctx);
  409. f->clnt_write_ctx = NULL;
  410. }
  411. if(f->srvr_read_ctx != NULL){
  412. EVP_CIPHER_CTX_free(f->srvr_read_ctx);
  413. }
  414. if(f->srvr_write_ctx != NULL){
  415. EVP_CIPHER_CTX_free(f->srvr_write_ctx);
  416. }
  417. if(f->ecdh != NULL){
  418. EC_KEY_free(f->ecdh);
  419. }
  420. if(f->resume_session == 1){
  421. if(f->current_session->session_ticket != NULL){
  422. free(f->current_session->session_ticket);
  423. }
  424. free(f->current_session);
  425. }
  426. if(f->ds_packet_chain != NULL){
  427. packet *tmp = f->ds_packet_chain->first_packet;
  428. while(tmp != NULL){
  429. f->ds_packet_chain->first_packet = tmp->next;
  430. printf("Freed data %p\n", tmp->data);
  431. printf("Freed packet %p\n", tmp);
  432. free(tmp->data);
  433. free(tmp);
  434. tmp = f->ds_packet_chain->first_packet;
  435. }
  436. }
  437. free(f->ds_packet_chain);
  438. if(f->us_packet_chain != NULL){
  439. packet *tmp = f->us_packet_chain->first_packet;
  440. while(tmp != NULL){
  441. f->us_packet_chain->first_packet = tmp->next;
  442. printf("Freed data %p\n", tmp->data);
  443. printf("Freed packet %p\n", tmp);
  444. free(tmp->data);
  445. free(tmp);
  446. tmp = f->us_packet_chain->first_packet;
  447. }
  448. }
  449. free(f->us_packet_chain);
  450. if(f->upstream_queue != NULL){
  451. queue_block *tmp = f->upstream_queue;
  452. while(tmp != NULL){
  453. f->upstream_queue = tmp->next;
  454. printf("Freed data %p\n", tmp->data);
  455. printf("Freed packet %p\n", tmp);
  456. free(tmp->data);
  457. free(tmp);
  458. tmp = f->upstream_queue;
  459. }
  460. }
  461. sem_wait(&flow_table_lock);
  462. flow_entry *entry = table->first_entry;
  463. if(entry->f == f){
  464. table->first_entry = entry->next;
  465. free(entry->f);
  466. free(entry);
  467. printf("flow removed!\n");
  468. fflush(stdout);
  469. table->len --;
  470. } else {
  471. flow_entry *next;
  472. for(int i=0; i< table->len; i++){
  473. if(entry->next != NULL){
  474. next = entry->next;
  475. } else {
  476. printf("Flow not in table\n");
  477. break;
  478. }
  479. if(next->f == f){
  480. entry->next = next->next;
  481. free(next->f);
  482. free(next);
  483. printf("flow removed!\n");
  484. table->len --;
  485. break;
  486. }
  487. entry = next;
  488. }
  489. }
  490. sem_post(&flow_table_lock);
  491. return 1;
  492. }
  493. /** Returns the index of a flow in the flow table if
  494. * it exists, returns 0 if it is not present.
  495. *
  496. * Inputs:
  497. * observed: details for the observed flow
  498. *
  499. * Output:
  500. * flow struct from table or NULL if it doesn't exist
  501. */
  502. flow *check_flow(struct packet_info *info){
  503. /* Loop through flows in table and see if it exists */
  504. int i;
  505. flow_entry *entry = table->first_entry;
  506. flow *candidate;
  507. flow *found = NULL;
  508. if(entry == NULL)
  509. return NULL;
  510. sem_wait(&flow_table_lock);
  511. /* Check first in this direction */
  512. for(i=0; i<table->len; i++){
  513. if(entry == NULL){
  514. printf("Error: entry is null\n");
  515. break;
  516. }
  517. candidate = entry->f;
  518. if(candidate->src_ip.s_addr == info->ip_hdr->src.s_addr){
  519. if(candidate->dst_ip.s_addr == info->ip_hdr->dst.s_addr){
  520. if(candidate->src_port == info->tcp_hdr->src_port){
  521. if(candidate->dst_port == info->tcp_hdr->dst_port){
  522. found = candidate;
  523. }
  524. }
  525. }
  526. }
  527. entry = entry->next;
  528. }
  529. entry = table->first_entry;
  530. /* Then in the other direction */
  531. for(i=0; i<table->len; i++){
  532. if(entry == NULL){
  533. printf("Error: entry is null\n");
  534. break;
  535. }
  536. candidate = entry->f;
  537. if(candidate->src_ip.s_addr == info->ip_hdr->dst.s_addr){
  538. if(candidate->dst_ip.s_addr == info->ip_hdr->src.s_addr){
  539. if(candidate->src_port == info->tcp_hdr->dst_port){
  540. if(candidate->dst_port == info->tcp_hdr->src_port){
  541. found = candidate;
  542. }
  543. }
  544. }
  545. }
  546. entry = entry->next;
  547. }
  548. sem_post(&flow_table_lock);
  549. return found;
  550. }
  551. int init_session_cache(void){
  552. sessions = emalloc(sizeof(session_cache));
  553. sessions->length = 0;
  554. sessions->first_session = NULL;
  555. return 0;
  556. }
  557. /** Called from ServerHello, verifies that the session id returned matches
  558. * the session id requested from the client hello
  559. *
  560. * Input:
  561. * f: the tagged flow
  562. * hs: a pointer to the ServerHello message
  563. *
  564. * Output:
  565. * 0 if success, 1 if failed
  566. */
  567. int verify_session_id(flow *f, uint8_t *hs){
  568. //increment pointer to point to sessionid
  569. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  570. p += 2; //skip version
  571. p += SSL3_RANDOM_SIZE; //skip random
  572. uint8_t id_len = (uint8_t) p[0];
  573. p ++;
  574. //check to see if it matches flow's session id set by ClientHello
  575. if(f->current_session != NULL && f->current_session->session_id_len > 0 && !memcmp(f->current_session->session_id, p, id_len)){
  576. //if it matched, update flow with master secret :D
  577. #ifdef DEBUG_HS
  578. printf("Session id matched!\n");
  579. printf("First session id (%p->%p):", sessions, sessions->first_session);
  580. #endif
  581. session *last = sessions->first_session;
  582. int found = 0;
  583. for(int i=0; ((i<sessions->length) && (!found)); i++){
  584. #ifdef DEBUG_HS
  585. printf("Checking saved session id: ");
  586. for (int j=0; j< last->session_id_len; j++){
  587. printf("%02x ", last->session_id[j]);
  588. }
  589. printf("\n");
  590. #endif
  591. if(!memcmp(last->session_id, f->current_session->session_id, id_len)){
  592. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  593. found = 1;
  594. }
  595. last = last->next;
  596. }
  597. if((!found) && (f->current_session->session_ticket_len > 0)){
  598. last = sessions->first_session;
  599. for(int i=0; ((i<sessions->length) && (!found)); i++){
  600. if(last->session_ticket_len == f->current_session->session_ticket_len){
  601. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  602. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  603. found = 1;
  604. #ifdef DEBUG_HS
  605. 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);
  606. for(int i=0; i< last->session_ticket_len; i++){
  607. printf("%02x ", last->session_ticket[i]);
  608. }
  609. printf("\n");
  610. #endif
  611. }
  612. }
  613. last = last->next;
  614. }
  615. }
  616. } else if (f->current_session != NULL && f->current_session->session_id_len > 0){
  617. //check to see if server's hello extension matches the ticket
  618. save_session_id(f, p);
  619. }
  620. return 0;
  621. }
  622. /* Called from ClientHello. Checks to see if the session id len is > 0. If so,
  623. * saves sessionid for later verification. Also checks to see if a session
  624. * ticket is included as an extension.
  625. *
  626. * Input:
  627. * f: the tagged flow
  628. * hs: a pointer to the ServerHello message
  629. *
  630. * Output:
  631. * 0 if success, 1 if failed
  632. */
  633. int check_session(flow *f, uint8_t *hs, uint32_t len){
  634. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  635. p += 2; //skip version
  636. p += SSL3_RANDOM_SIZE; //skip random
  637. session *new_session = emalloc(sizeof(session));
  638. new_session->session_id_len = (uint8_t) p[0];
  639. new_session->session_ticket_len = 0;
  640. p ++;
  641. if(new_session->session_id_len > 0){
  642. f->resume_session = 1;
  643. memcpy(new_session->session_id, p, new_session->session_id_len);
  644. new_session->next = NULL;
  645. #ifdef DEBUG_HS
  646. 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);
  647. printf("session id: \n");
  648. for(int i=0; i< new_session->session_id_len; i++){
  649. printf("%02x ", p[i]);
  650. }
  651. printf("\n");
  652. #endif
  653. f->current_session = new_session;
  654. }
  655. p += new_session->session_id_len;
  656. //check to see if there is a session ticket included
  657. //skip to extensions
  658. uint16_t ciphersuite_len = (p[0] << 8) + p[1];
  659. p += 2 + ciphersuite_len;
  660. uint8_t compress_meth_len = p[0];
  661. p += 1 + compress_meth_len;
  662. //search for SessionTicket TLS extension
  663. if(2 + SSL3_RANDOM_SIZE + new_session->session_id_len + 1 + 2 + ciphersuite_len + 1 + compress_meth_len > len){
  664. //no extension
  665. if(f->current_session == NULL)
  666. free(new_session);
  667. return 0;
  668. }
  669. uint16_t extensions_len = (p[0] << 8) + p[1];
  670. p += 2;
  671. while(extensions_len > 0){
  672. uint16_t type = (p[0] << 8) + p[1];
  673. p += 2;
  674. uint16_t ext_len = (p[0] << 8) + p[1];
  675. p += 2;
  676. if(type == 0x23){
  677. if(ext_len > 0){
  678. f->resume_session = 1;
  679. new_session->session_ticket_len = ext_len;
  680. new_session->session_ticket = emalloc(ext_len);
  681. memcpy(new_session->session_ticket, p, ext_len);
  682. f->current_session = new_session;
  683. }
  684. }
  685. p += ext_len;
  686. extensions_len -= (4 + ext_len);
  687. }
  688. if(!f->resume_session){
  689. //see if a ticket is incuded
  690. free(new_session);
  691. }
  692. return 0;
  693. }
  694. /* Called from ServerHello during full handshake. Adds the session id to the
  695. * cache for later resumptions
  696. *
  697. * Input:
  698. * f: the tagged flow
  699. * hs: a pointer to the ServerHello message
  700. *
  701. * Output:
  702. * 0 if success, 1 if failed
  703. */
  704. int save_session_id(flow *f, uint8_t *hs){
  705. //increment pointer to point to sessionid
  706. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  707. p += 2; //skip version
  708. p += SSL3_RANDOM_SIZE; //skip random
  709. session *new_session = emalloc(sizeof(session));
  710. new_session->session_id_len = (uint8_t) p[0];
  711. if(new_session->session_id_len <= 0){
  712. //if this value is zero, the session is non-resumable or the
  713. //server will issue a NewSessionTicket handshake message
  714. free(new_session);
  715. return 0;
  716. }
  717. p++;
  718. memcpy(new_session->session_id, p, new_session->session_id_len);
  719. new_session->next = NULL;
  720. if(f->current_session != NULL){
  721. free(f->current_session);
  722. }
  723. f->resume_session = 0;
  724. f->current_session = new_session;
  725. if(sessions->first_session == NULL){
  726. sessions->first_session = new_session;
  727. printf("First session id (%p->%p):", sessions, sessions->first_session);
  728. for(int i=0; i< new_session->session_id_len; i++){
  729. printf(" %02x", sessions->first_session->session_id[i]);
  730. }
  731. printf("\n");
  732. } else {
  733. session *last = sessions->first_session;
  734. for(int i=0; i< sessions->length -1; i++){
  735. if(last == NULL){
  736. printf("UH OH: last is null?\n");
  737. fflush(stdout);
  738. }
  739. last = last->next;
  740. }
  741. last->next = new_session;
  742. }
  743. sessions->length ++;
  744. printf("Saved session id:");
  745. for(int i=0; i< new_session->session_id_len; i++){
  746. printf(" %02x", new_session->session_id[i]);
  747. }
  748. printf("\n");
  749. printf("THERE ARE NOW %d saved sessions\n", sessions->length);
  750. return 0;
  751. }
  752. /* Called from NewSessionTicket. Adds the session ticket to the
  753. * cache for later resumptions
  754. *
  755. * Input:
  756. * f: the tagged flow
  757. * hs: a pointer to the ServerHello message
  758. *
  759. * Output:
  760. * 0 if success, 1 if failed
  761. */
  762. int save_session_ticket(flow *f, uint8_t *hs, uint32_t len){
  763. #ifdef DEBUG_HS
  764. printf("TICKET HDR:");
  765. for(int i=0; i< HANDSHAKE_HEADER_LEN; i++){
  766. printf("%02x ", hs[i]);
  767. }
  768. printf("\n");
  769. #endif
  770. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  771. p += 4;
  772. session *new_session = ecalloc(1, sizeof(session));
  773. new_session->session_id_len = 0;
  774. new_session->session_ticket_len = (p[0] << 8) + p[1];
  775. p += 2;
  776. uint8_t *ticket = emalloc(new_session->session_ticket_len);
  777. memcpy(ticket, p, new_session->session_ticket_len);
  778. new_session->session_ticket = ticket;
  779. memcpy(new_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  780. if(sessions->first_session == NULL){
  781. sessions->first_session = new_session;
  782. } else {
  783. session *last = sessions->first_session;
  784. for(int i=0; i< (sessions->length-1); i++){
  785. if(last == NULL){
  786. printf("UH OH: last is null?\n");
  787. fflush(stdout);
  788. }
  789. last = last->next;
  790. }
  791. last->next = new_session;
  792. }
  793. sessions->length ++;
  794. #ifdef DEBUG_HS
  795. printf("Saved session ticket:");
  796. for(int i=0; i< new_session->session_ticket_len; i++){
  797. printf(" %02x", p[i]);
  798. }
  799. printf("\n");
  800. fflush(stdout);
  801. printf("Saved session master secret:");
  802. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  803. printf(" %02x", new_session->master_secret[i]);
  804. }
  805. printf("\n");
  806. fflush(stdout);
  807. printf("THERE ARE NOW %d saved sessions\n", sessions->length);
  808. fflush(stdout);
  809. #endif
  810. return 0;
  811. }
  812. /* Adds a packet the flow's packet chain. If it can complete a record, gives
  813. * this record to update_flow */
  814. int add_packet(flow *f, struct packet_info *info){
  815. if (info->tcp_hdr == NULL || info->app_data_len <= 0){
  816. return 0;
  817. }
  818. packet *new_packet = emalloc(sizeof(packet));
  819. new_packet->seq_num = ntohl(info->tcp_hdr->sequence_num);
  820. new_packet->len = info->app_data_len;
  821. uint8_t *packet_data = emalloc(new_packet->len);
  822. memcpy(packet_data, info->app_data, new_packet->len);
  823. new_packet->data = packet_data;
  824. new_packet->next = NULL;
  825. uint8_t incoming = (info->ip_hdr->src.s_addr == f->src_ip.s_addr) ? 0 : 1;
  826. packet_chain *chain =
  827. (info->ip_hdr->src.s_addr == f->src_ip.s_addr) ? f->us_packet_chain : f->ds_packet_chain;
  828. if(new_packet->seq_num < chain->expected_seq_num){
  829. //see if this packet contains any data we are missing
  830. printf("Received replayed packet O.o\n");
  831. free(new_packet->data);
  832. free(new_packet);
  833. } else {//new_packet->seq_num >= chain->expected_seq_num
  834. //Find appropriate place in chain
  835. packet *previous = NULL;
  836. packet *next = chain->first_packet;
  837. while(next != NULL && (next->seq_num <= new_packet->seq_num)){
  838. previous = next;
  839. next = next->next;
  840. }
  841. //place packet after current
  842. if(previous == NULL){
  843. //goes at the beginning of chain
  844. new_packet->next = chain->first_packet;
  845. chain->first_packet = new_packet;
  846. //if this is a new record, find lengths
  847. if(new_packet->seq_num == chain->expected_seq_num){
  848. const struct record_header *record_hdr = (struct record_header *) new_packet->data;
  849. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  850. chain->remaining_record_len = chain->record_len;
  851. }
  852. } else {
  853. new_packet->next = next;
  854. previous->next = new_packet;
  855. }
  856. if(new_packet->seq_num == chain->expected_seq_num){
  857. chain->expected_seq_num += new_packet->len;
  858. uint32_t record_offset = 0; //offset into record for updating info with any changes
  859. uint32_t info_offset = 0; //offset into info for updating with changes
  860. uint32_t info_len = 0; //number of bytes that possibly changed
  861. //while there is still data left:
  862. uint32_t available_data = new_packet->len;
  863. while(available_data > 0){
  864. //if full record, give to update_flow
  865. if(chain->remaining_record_len <= new_packet->len){
  866. chain->remaining_record_len = 0;
  867. uint8_t *record = emalloc(chain->record_len);
  868. uint32_t record_len = chain->record_len;
  869. uint32_t tmp_len = chain->record_len;
  870. packet *next = chain->first_packet;
  871. while(tmp_len > 0){
  872. if(tmp_len >= next->len){
  873. memcpy(record+chain->record_len - tmp_len, next->data, next->len);
  874. if(next == new_packet){
  875. new_packet = NULL;
  876. record_offset = chain->record_len - tmp_len;
  877. info_len = next->len;
  878. }
  879. tmp_len -= next->len;
  880. chain->first_packet = next->next;
  881. free(next->data);
  882. free(next);
  883. next = chain->first_packet;
  884. available_data = 0;
  885. } else {
  886. memcpy(record+chain->record_len - tmp_len, next->data, tmp_len);
  887. if(next == new_packet){
  888. record_offset = chain->record_len - tmp_len;
  889. info_len = tmp_len;
  890. }
  891. memmove(next->data, next->data+tmp_len, next->len - tmp_len);
  892. next->len -= tmp_len;
  893. available_data -= tmp_len;
  894. tmp_len = 0;
  895. //this is going to be a new record
  896. const struct record_header *record_hdr = (struct record_header *) next->data;
  897. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  898. chain->remaining_record_len = chain->record_len;
  899. #ifdef DEBUG
  900. printf("Found record of type %d\n", record_hdr->type);
  901. fflush(stdout);
  902. #endif
  903. }
  904. }
  905. //if handshake is complete, send to relay code
  906. if(f->application == 1){
  907. //update packet info and send to replace_packet
  908. struct packet_info *copy_info = copy_packet_info(info);
  909. copy_info->app_data = record;
  910. copy_info->app_data_len = record_len;
  911. replace_packet(f, copy_info);
  912. free(copy_info->app_data);
  913. free(copy_info);
  914. } else {
  915. if(update_flow(f, record, incoming)){
  916. free(record);
  917. return 1;//error occurred and flow was removed
  918. }
  919. //check to see if last finished message received
  920. if(f->in_encrypted ==2){
  921. #ifdef DEBUG
  922. printf("Replacing info->data with finished message (%d bytes).\n", info_len);
  923. printf("Previous bytes:\n");
  924. for(int i=0; i<info_len; i++){
  925. printf("%02x ", info->app_data[info_offset+i]);
  926. }
  927. printf("\n");
  928. printf("New bytes:\n");
  929. for(int i=0; i<info_len; i++){
  930. printf("%02x ", record[record_offset+i]);
  931. }
  932. printf("\n");
  933. printf("SLITHEEN: Previous packet contents:\n");
  934. for(int i=0; i< info->app_data_len; i++){
  935. printf("%02x ", info->app_data[i]);
  936. }
  937. printf("\n");
  938. #endif
  939. memcpy(info->app_data+info_offset, record+record_offset, info_len);
  940. #ifdef DEBUG
  941. printf("SLITHEEN: Current packet contents:\n");
  942. for(int i=0; i< info->app_data_len; i++){
  943. printf("%02x ", info->app_data[i]);
  944. }
  945. printf("\n");
  946. #endif
  947. //update TCP checksum
  948. tcp_checksum(info);
  949. }
  950. free(record);
  951. if(new_packet != NULL){
  952. info_offset += info_len;
  953. }
  954. }
  955. } else {
  956. chain->remaining_record_len -= new_packet->len;
  957. //see if this packet filled a hole
  958. new_packet = new_packet->next;
  959. if(new_packet != NULL &&
  960. new_packet->seq_num == chain->expected_seq_num){
  961. available_data = new_packet->len;
  962. chain->expected_seq_num += new_packet->len;
  963. } else {
  964. available_data = 0;
  965. }
  966. }
  967. }
  968. } else {//
  969. //add to end of packet_chain
  970. printf("Missing packet (expected %d, received %d)\n", chain->expected_seq_num, new_packet->seq_num);
  971. }
  972. }
  973. return 0;
  974. }