flow.c 31 KB

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