flow.c 30 KB

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