flow.c 33 KB

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