flow.c 30 KB

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