flow.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. /* Name: flow.c
  2. *
  3. * This file contains functions for manipulating tagged flows.
  4. *
  5. * Slitheen - a decoy routing system for censorship resistance
  6. * Copyright (C) 2017 Cecylia Bocovich (cbocovic@uwaterloo.ca)
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, version 3.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * Additional permission under GNU GPL version 3 section 7
  21. *
  22. * If you modify this Program, or any covered work, by linking or combining
  23. * it with the OpenSSL library (or a modified version of that library),
  24. * containing parts covered by the terms of the OpenSSL Licence and the
  25. * SSLeay license, the licensors of this Program grant you additional
  26. * permission to convey the resulting work. Corresponding Source for a
  27. * non-source form of such a combination shall include the source code
  28. * for the parts of the OpenSSL library used as well as that of the covered
  29. * work.
  30. */
  31. #include <stdio.h>
  32. #include <stdlib.h>
  33. #include <stdint.h>
  34. #include <pthread.h>
  35. #include <errno.h>
  36. #include <semaphore.h>
  37. #include <string.h>
  38. #include "flow.h"
  39. #include "crypto.h"
  40. #include "packet.h"
  41. #include "relay.h"
  42. #include "util.h"
  43. /* Data structures */
  44. typedef struct packet_chain_st {
  45. packet *first_packet;
  46. uint32_t expected_seq_num;
  47. uint32_t record_len;
  48. uint32_t remaining_record_len;
  49. } packet_chain;
  50. typedef struct session_cache_st {
  51. session *first_session;
  52. uint32_t length;
  53. } session_cache;
  54. typedef struct flow_entry_st {
  55. flow *f;
  56. struct flow_entry_st *next;
  57. } flow_entry;
  58. typedef struct flow_table_st {
  59. flow_entry *first_entry;
  60. int len;
  61. } flow_table;
  62. static flow_table *table;
  63. static session_cache *sessions;
  64. client_table *clients;
  65. sem_t flow_table_lock;
  66. #define TLS_HELLO_REQ 0x00
  67. #define TLS_CLNT_HELLO 0x01
  68. #define TLS_SERV_HELLO 0x02
  69. #define TLS_NEW_SESS 0x04
  70. #define TLS_CERT 0x0b
  71. #define TLS_SRVR_KEYEX 0x0c
  72. #define TLS_CERT_REQ 0x0d
  73. #define TLS_SRVR_HELLO_DONE 0x0e
  74. #define TLS_CERT_VERIFY 0x0f
  75. #define TLS_CLNT_KEYEX 0x10
  76. #define TLS_FINISHED 0x14
  77. #define TLS_CERT_STATUS 0x16
  78. static int update_flow(flow *f, uint8_t *record, uint8_t incoming);
  79. static int verify_session_id(flow *f, uint8_t *hs);
  80. static int check_extensions(flow *f, uint8_t *hs, uint32_t len);
  81. static int verify_extensions(flow *f, uint8_t *hs, uint32_t len);
  82. static int save_session_id(flow *f, uint8_t *hs);
  83. static int save_session_ticket(flow *f, uint8_t *hs, uint32_t len);
  84. /* Initialize the table of tagged flows */
  85. int init_tables(void) {
  86. table = smalloc(sizeof(flow_table));
  87. table->first_entry = NULL;
  88. table->len = 0;
  89. sem_init(&flow_table_lock, 0, 1);
  90. clients = smalloc(sizeof(client_table));
  91. clients->first = NULL;
  92. printf("initialized downstream queue\n");
  93. return 0;
  94. }
  95. /* Add a new flow to the tagged flow table */
  96. flow *add_flow(struct packet_info *info) {
  97. flow_entry *entry = smalloc(sizeof(flow_entry));
  98. flow *new_flow = smalloc(sizeof(flow));
  99. entry->f = new_flow;
  100. entry->next = NULL;
  101. new_flow->src_ip = info->ip_hdr->src;
  102. new_flow->dst_ip = info->ip_hdr->dst;
  103. new_flow->src_port = info->tcp_hdr->src_port;
  104. new_flow->dst_port = info->tcp_hdr->dst_port;
  105. new_flow->ref_ctr = 1;
  106. new_flow->removed = 0;
  107. new_flow->upstream_app_data = smalloc(sizeof(app_data_queue));
  108. new_flow->upstream_app_data->first_packet = NULL;
  109. new_flow->downstream_app_data = smalloc(sizeof(app_data_queue));
  110. new_flow->downstream_app_data->first_packet = NULL;
  111. new_flow->upstream_seq_num = ntohl(info->tcp_hdr->sequence_num);
  112. new_flow->downstream_seq_num = ntohl(info->tcp_hdr->ack_num);
  113. new_flow->us_frame_queue = smalloc(sizeof(frame_queue));
  114. new_flow->us_frame_queue->first_frame = NULL;
  115. new_flow->ds_frame_queue = smalloc(sizeof(frame_queue));
  116. new_flow->ds_frame_queue->first_frame = NULL;
  117. new_flow->streams=NULL;
  118. new_flow->downstream_queue=NULL;
  119. new_flow->client_ptr=NULL;
  120. sem_init(&(new_flow->flow_lock), 0, 1);
  121. new_flow->state = TLS_CLNT_HELLO;
  122. new_flow->in_encrypted = 0;
  123. new_flow->out_encrypted = 0;
  124. new_flow->application = 0;
  125. new_flow->stall = 0;
  126. new_flow->extended_master_secret = 0;
  127. new_flow->resume_session = 0;
  128. new_flow->current_session = NULL;
  129. new_flow->us_hs_queue = init_queue();
  130. new_flow->ds_hs_queue = init_queue();
  131. new_flow->us_packet_chain = smalloc(sizeof(packet_chain));
  132. new_flow->us_packet_chain->expected_seq_num = ntohl(info->tcp_hdr->sequence_num);
  133. new_flow->us_packet_chain->record_len = 0;
  134. new_flow->us_packet_chain->remaining_record_len = 0;
  135. new_flow->us_packet_chain->first_packet = NULL;
  136. new_flow->ds_packet_chain = smalloc(sizeof(packet_chain));
  137. new_flow->ds_packet_chain->expected_seq_num = ntohl(info->tcp_hdr->ack_num);
  138. new_flow->ds_packet_chain->record_len = 0;
  139. new_flow->ds_packet_chain->remaining_record_len = 0;
  140. new_flow->ds_packet_chain->first_packet = NULL;
  141. sem_init(&(new_flow->packet_chain_lock), 0, 1);
  142. new_flow->upstream_queue = NULL;
  143. new_flow->upstream_remaining = 0;
  144. sem_init(&(new_flow->upstream_queue_lock), 0, 1);
  145. new_flow->outbox = NULL;
  146. new_flow->outbox_len = 0;
  147. new_flow->outbox_offset = 0;
  148. new_flow->partial_record_header = NULL;
  149. new_flow->partial_record_header_len = 0;
  150. new_flow->partial_record = NULL;
  151. new_flow->partial_record_dec = NULL;
  152. new_flow->partial_record_len = 0;
  153. new_flow->partial_record_total_len = 0;
  154. new_flow->remaining_record_len = 0;
  155. new_flow->remaining_response_len = 0;
  156. new_flow->httpstate = PARSE_HEADER;
  157. new_flow->replace_response = 0;
  158. new_flow->ecdh = NULL;
  159. new_flow->srvr_key = NULL;
  160. new_flow->dh = NULL;
  161. new_flow->hs_md_ctx = EVP_MD_CTX_create();
  162. const EVP_MD *md = EVP_sha256();
  163. EVP_DigestInit_ex(new_flow->hs_md_ctx, md, NULL);
  164. new_flow->cipher = NULL;
  165. new_flow->clnt_read_ctx = NULL;
  166. new_flow->clnt_write_ctx = NULL;
  167. new_flow->srvr_read_ctx = NULL;
  168. new_flow->srvr_write_ctx = NULL;
  169. new_flow->gcm_ctx_out = NULL;
  170. new_flow->gcm_ctx_iv = NULL;
  171. new_flow->gcm_ctx_key = NULL;
  172. memset(new_flow->read_seq, 0, 8);
  173. memset(new_flow->write_seq, 0, 8);
  174. sem_wait(&flow_table_lock);
  175. flow_entry *last = table->first_entry;
  176. if(last == NULL){
  177. table->first_entry = entry;
  178. } else {
  179. for(int i=0; i< table->len-1; i++){
  180. last = last->next;
  181. }
  182. last->next = entry;
  183. }
  184. table->len ++;
  185. sem_post(&flow_table_lock);
  186. return new_flow;
  187. }
  188. /** Observes TLS handshake messages and updates the state of
  189. * the flow
  190. *
  191. * Inputs:
  192. * f: the tagged flow
  193. * record: a complete TLS record
  194. *
  195. * Output:
  196. * 0 on success, 1 on failure
  197. */
  198. static int update_flow(flow *f, uint8_t *record, uint8_t incoming) {
  199. const struct record_header *record_hdr;
  200. const struct handshake_header *handshake_hdr;
  201. uint8_t *p;
  202. record_hdr = (struct record_header*) record;
  203. int record_len;
  204. record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  205. switch(record_hdr->type){
  206. case HS:
  207. p = record;
  208. #ifdef DEBUG_HS_EXTRA
  209. printf("Received handshake packet (%x:%d -> %x:%d) (incoming: %d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port), incoming);
  210. for(int i=0; i< record_len; i++){
  211. printf("%02x ", p[i]);
  212. }
  213. printf("\n");
  214. #endif
  215. p += RECORD_HEADER_LEN;
  216. if((incoming && f->in_encrypted) || (!incoming && f->out_encrypted)){
  217. #ifdef DEBUG_HS
  218. printf("Decrypting finished (%d bytes) (%x:%d -> %x:%d) (incoming: %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), incoming);
  219. printf("Finished ciphertext:\n");
  220. for(int i=0; i< record_len; i++){
  221. printf("%02x ", record[i]);
  222. }
  223. printf("\n");
  224. #endif
  225. int32_t n = encrypt(f, p, p, record_len - RECORD_HEADER_LEN, incoming, 0x16, 0, 0);
  226. if(n<=0){
  227. printf("Error decrypting finished (%x:%d -> %x:%d) (incoming: %d)\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port), incoming);
  228. printf("record:\n");
  229. for(int i=0; i< 12; i++){
  230. printf("%02x ", p[i]);
  231. }
  232. }
  233. #ifdef DEBUG_HS
  234. 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));
  235. #endif
  236. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  237. #ifdef DEBUG_HS
  238. printf("record:\n");
  239. for(int i=0; i< n; i++){
  240. printf("%02x ", p[i]);
  241. }
  242. printf("\n");
  243. #endif
  244. if(p[0] != 0x14){
  245. p[0] = 0x20; //trigger error
  246. }
  247. if(incoming){
  248. f->in_encrypted = 2;
  249. } else {
  250. f->out_encrypted = 2;
  251. }
  252. }
  253. handshake_hdr = (struct handshake_header*) p;
  254. f->state = handshake_hdr->type;
  255. switch(f->state){
  256. case TLS_CLNT_HELLO:
  257. #ifdef DEBUG_HS
  258. 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));
  259. #endif
  260. if(check_extensions(f, p, HANDSHAKE_MESSAGE_LEN(handshake_hdr))){
  261. fprintf(stderr, "Error checking session, might cause problems\n");
  262. }
  263. if(update_handshake_hash(f, p)){
  264. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  265. remove_flow(f);
  266. goto err;
  267. }
  268. break;
  269. case TLS_SERV_HELLO:
  270. #ifdef DEBUG_HS
  271. 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));
  272. #endif
  273. if(f->resume_session){
  274. if(verify_session_id(f,p)){
  275. fprintf(stderr, "Failed to verify session id\n");
  276. }
  277. } else {
  278. if(save_session_id(f,p)){
  279. fprintf(stderr, "Failed to save session id\n");
  280. }
  281. }
  282. if(verify_extensions(f,p, HANDSHAKE_MESSAGE_LEN(handshake_hdr))){
  283. fprintf(stderr, "Failed to verify extensions\n");
  284. }
  285. if(extract_server_random(f, p)){
  286. fprintf(stderr, "Failed to extract server random nonce\n");
  287. remove_flow(f);
  288. goto err;
  289. }
  290. if(update_handshake_hash(f, p)){
  291. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  292. remove_flow(f);
  293. goto err;
  294. }
  295. break;
  296. case TLS_NEW_SESS:
  297. #ifdef DEBUG_HS
  298. printf("Received new session\n");
  299. #endif
  300. if(save_session_ticket(f, p, HANDSHAKE_MESSAGE_LEN(handshake_hdr))){
  301. fprintf(stderr, "Failed to save session ticket\n");
  302. }
  303. break;
  304. case TLS_CERT:
  305. #ifdef DEBUG_HS
  306. printf("Received cert\n");
  307. #endif
  308. if(update_handshake_hash(f, p)){
  309. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  310. remove_flow(f);
  311. goto err;
  312. }
  313. break;
  314. case TLS_CERT_STATUS:
  315. #ifdef DEBUG_HS
  316. printf("Received certificate status\n");
  317. #endif
  318. if(update_handshake_hash(f, p)){
  319. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  320. remove_flow(f);
  321. goto err;
  322. }
  323. break;
  324. case TLS_SRVR_KEYEX:
  325. #ifdef DEBUG_HS
  326. printf("Received server keyex\n");
  327. #endif
  328. if(extract_parameters(f, p)){
  329. printf("Error extracting params\n");
  330. remove_flow(f);
  331. goto err;
  332. }
  333. if(update_handshake_hash(f, p)){
  334. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  335. remove_flow(f);
  336. goto err;
  337. }
  338. break;
  339. case TLS_CERT_REQ:
  340. if(update_handshake_hash(f, p)){
  341. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  342. remove_flow(f);
  343. goto err;
  344. }
  345. break;
  346. case TLS_SRVR_HELLO_DONE:
  347. #ifdef DEBUG_HS
  348. printf("Received server hello done\n");
  349. #endif
  350. if(update_handshake_hash(f, p)){
  351. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  352. remove_flow(f);
  353. goto err;
  354. }
  355. break;
  356. case TLS_CERT_VERIFY:
  357. #ifdef DEBUG_HS
  358. printf("received cert verify\n");
  359. #endif
  360. if(update_handshake_hash(f, p)){
  361. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  362. remove_flow(f);
  363. goto err;
  364. }
  365. break;
  366. case TLS_CLNT_KEYEX:
  367. #ifdef DEBUG_HS
  368. printf("Received client key exchange\n");
  369. #endif
  370. if(update_handshake_hash(f, p)){
  371. fprintf(stderr, "Error updating finish has with CLNT_HELLO msg\n");
  372. remove_flow(f);
  373. goto err;
  374. }
  375. if(compute_master_secret(f)){
  376. printf("Error computing master secret\n");
  377. remove_flow(f);
  378. goto err;
  379. }
  380. break;
  381. case TLS_FINISHED:
  382. #ifdef DEBUG_HS
  383. 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));
  384. #endif
  385. if((f->in_encrypted == 2) && (f->out_encrypted == 2)){
  386. f->application = 1;
  387. printf("Handshake complete!\n");
  388. }
  389. if(!incoming) {
  390. // We only care about incoming
  391. // Finished messages
  392. break;
  393. }
  394. if(mark_finished_hash(f, p)){
  395. fprintf(stderr, "Error marking finished hash\n");
  396. remove_flow(f);
  397. goto err;
  398. }
  399. //re-encrypt finished message
  400. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x16, 1, 1);
  401. #ifdef HS_DEBUG
  402. printf("New finished ciphertext:\n");
  403. for(int i=0; i< record_len; i++){
  404. printf("%02x ", record[i]);
  405. }
  406. printf("\n");
  407. #endif
  408. if(n<=0){
  409. printf("Error re-encrypting finished (%x:%d -> %x:%d)\n", f->src_ip.s_addr, ntohs(f->src_port),
  410. f->dst_ip.s_addr, ntohs(f->dst_port));
  411. }
  412. break;
  413. default:
  414. printf("Error: unrecognized hs message? (%x:%d -> %x:%d)...\n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port));
  415. remove_flow(f);
  416. goto err;
  417. }
  418. break;
  419. case APP:
  420. 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));
  421. break;
  422. case CCS:
  423. #ifdef DEBUG_HS
  424. 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));
  425. #endif
  426. /*Initialize ciphers */
  427. if ((!f->in_encrypted) && (!f->out_encrypted)){
  428. if(init_ciphers(f)){
  429. remove_flow(f);
  430. goto err;
  431. }
  432. }
  433. if(incoming){
  434. f->in_encrypted = 1;
  435. } else {
  436. f->out_encrypted = 1;
  437. }
  438. break;
  439. case ALERT:
  440. p = record;
  441. p += RECORD_HEADER_LEN;
  442. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  443. //decrypt alert
  444. int32_t n = encrypt(f, p, p, record_len - RECORD_HEADER_LEN, incoming, 0x15, 0, 0);
  445. if(n <= 0){
  446. printf("Error decrypting Alert\n");
  447. }
  448. printf("Decrypted alert:\n");
  449. for(int i=0; i< n; i++){
  450. printf("%02x ", p[i]);
  451. }
  452. printf("\n");
  453. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  454. }
  455. printf("Alert (%x:%d -> %x:%d) (%s) %02x %02x \n", f->src_ip.s_addr, ntohs(f->src_port), f->dst_ip.s_addr, ntohs(f->dst_port), (incoming) ? "incoming" : "outgoing", p[0], p[1]);
  456. fflush(stdout);
  457. //re-encrypt alert
  458. if(((incoming) && (f->in_encrypted > 0)) || ((!incoming) && (f->out_encrypted > 0))){
  459. int32_t n = encrypt(f, record+RECORD_HEADER_LEN, record+RECORD_HEADER_LEN, record_len - (RECORD_HEADER_LEN+16), incoming, 0x15, 1, 1);
  460. if(n <= 0){
  461. printf("Error re-encrypting alert\n");
  462. }
  463. }
  464. break;
  465. case HB:
  466. printf("Heartbeat\n");
  467. break;
  468. default:
  469. 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));
  470. fflush(stdout);
  471. remove_flow(f);
  472. goto err;
  473. }
  474. return 0;
  475. err:
  476. return 1;
  477. }
  478. /** Removes the tagged flow from the flow table: happens when
  479. * the station receives a TCP RST or FIN packet
  480. *
  481. * Input:
  482. * index: the index into the flow table of the tagged flow
  483. *
  484. * Output:
  485. * 0 on success, 1 on failure
  486. */
  487. int remove_flow(flow *f) {
  488. sem_wait(&flow_table_lock);
  489. //decrement reference counter
  490. f->ref_ctr--;
  491. if(f->ref_ctr){ //if there are still references to f, wait to free it
  492. printf("Cannot free %p, still %d reference(s)\n", f, f->ref_ctr);
  493. f->removed = 1;
  494. sem_post(&flow_table_lock);
  495. return 0;
  496. }
  497. if(f->removed)
  498. printf("Trying again to free\n");
  499. frame *first_frame = f->us_frame_queue->first_frame;
  500. while(first_frame != NULL){
  501. printf("Injecting delayed frame (seq = %u )\n", first_frame->seq_num);
  502. inject_packet(first_frame->iargs, first_frame->header, first_frame->packet);
  503. frame *tmp = first_frame->next;
  504. free(first_frame);
  505. first_frame = tmp;
  506. }
  507. free(f->us_frame_queue);
  508. first_frame = f->ds_frame_queue->first_frame;
  509. while(first_frame != NULL){
  510. printf("Injecting delayed frame (seq = %u )\n", first_frame->seq_num);
  511. inject_packet(first_frame->iargs, first_frame->header, first_frame->packet);
  512. frame *tmp = first_frame->next;
  513. free(first_frame);
  514. first_frame = tmp;
  515. }
  516. free(f->ds_frame_queue);
  517. //Empty application data queues
  518. packet *tmp = f->upstream_app_data->first_packet;
  519. while(tmp != NULL){
  520. f->upstream_app_data->first_packet = tmp->next;
  521. free(tmp->data);
  522. free(tmp);
  523. tmp = f->upstream_app_data->first_packet;
  524. }
  525. free(f->upstream_app_data);
  526. tmp = f->downstream_app_data->first_packet;
  527. while(tmp != NULL){
  528. f->downstream_app_data->first_packet = tmp->next;
  529. free(tmp->data);
  530. free(tmp);
  531. tmp = f->downstream_app_data->first_packet;
  532. }
  533. free(f->downstream_app_data);
  534. if(f->ds_hs_queue != NULL){
  535. remove_queue(f->ds_hs_queue);
  536. }
  537. if(f->us_hs_queue != NULL){
  538. remove_queue(f->us_hs_queue);
  539. }
  540. //free partial record headers
  541. if(f->partial_record_header_len > 0){
  542. f->partial_record_header_len = 0;
  543. free(f->partial_record_header);
  544. }
  545. if(f->partial_record_dec != NULL){
  546. free(f->partial_record_dec);
  547. }
  548. if(f->partial_record != NULL){
  549. free(f->partial_record);
  550. }
  551. //Clean up cipher ctxs
  552. #if OPENSSL_VERSION_NUMBER >= 0x1010000eL
  553. EVP_MD_CTX_free(f->hs_md_ctx);
  554. #else
  555. EVP_MD_CTX_cleanup(f->hs_md_ctx);
  556. if(f->hs_md_ctx != NULL){
  557. EVP_MD_CTX_destroy(f->hs_md_ctx);
  558. }
  559. #endif
  560. if(f->clnt_read_ctx != NULL){
  561. EVP_CIPHER_CTX_cleanup(f->clnt_read_ctx);
  562. OPENSSL_free(f->clnt_read_ctx);
  563. f->clnt_read_ctx = NULL;
  564. }
  565. if(f->clnt_write_ctx != NULL){
  566. EVP_CIPHER_CTX_cleanup(f->clnt_write_ctx);
  567. OPENSSL_free(f->clnt_write_ctx);
  568. f->clnt_write_ctx = NULL;
  569. }
  570. if(f->srvr_read_ctx != NULL){
  571. EVP_CIPHER_CTX_free(f->srvr_read_ctx);
  572. }
  573. if(f->srvr_write_ctx != NULL){
  574. EVP_CIPHER_CTX_free(f->srvr_write_ctx);
  575. }
  576. if(f->ecdh != NULL){
  577. EC_KEY_free(f->ecdh);
  578. }
  579. if(f->gcm_ctx_out != NULL){
  580. CRYPTO_gcm128_release(f->gcm_ctx_out);
  581. }
  582. if(f->gcm_ctx_iv != NULL){
  583. free(f->gcm_ctx_iv);
  584. }
  585. if(f->gcm_ctx_key != NULL){
  586. free(f->gcm_ctx_key);
  587. }
  588. if(f->dh != NULL){
  589. DH_free(f->dh);
  590. }
  591. if(f->current_session != NULL && f->resume_session == 1){
  592. if( f->current_session->session_ticket != NULL){
  593. free(f->current_session->session_ticket);
  594. }
  595. free(f->current_session);
  596. }
  597. if(f->ds_packet_chain != NULL){
  598. packet *tmp = f->ds_packet_chain->first_packet;
  599. while(tmp != NULL){
  600. f->ds_packet_chain->first_packet = tmp->next;
  601. printf("Freed data %p\n", tmp->data);
  602. printf("Freed packet %p\n", tmp);
  603. free(tmp->data);
  604. free(tmp);
  605. tmp = f->ds_packet_chain->first_packet;
  606. }
  607. }
  608. free(f->ds_packet_chain);
  609. if(f->us_packet_chain != NULL){
  610. packet *tmp = f->us_packet_chain->first_packet;
  611. while(tmp != NULL){
  612. f->us_packet_chain->first_packet = tmp->next;
  613. printf("Freed data %p\n", tmp->data);
  614. printf("Freed packet %p\n", tmp);
  615. free(tmp->data);
  616. free(tmp);
  617. tmp = f->us_packet_chain->first_packet;
  618. }
  619. }
  620. free(f->us_packet_chain);
  621. if(f->upstream_queue != NULL){
  622. queue_block *tmp = f->upstream_queue;
  623. while(tmp != NULL){
  624. f->upstream_queue = tmp->next;
  625. printf("Freed data %p\n", tmp->data);
  626. printf("Freed packet %p\n", tmp);
  627. free(tmp->data);
  628. free(tmp);
  629. tmp = f->upstream_queue;
  630. }
  631. }
  632. flow_entry *entry = table->first_entry;
  633. if(entry->f == f){
  634. table->first_entry = entry->next;
  635. free(entry->f);
  636. free(entry);
  637. table->len --;
  638. } else {
  639. flow_entry *next;
  640. for(int i=0; i< table->len; i++){
  641. if(entry->next != NULL){
  642. next = entry->next;
  643. } else {
  644. printf("Flow not in table\n");
  645. break;
  646. }
  647. if(next->f == f){
  648. entry->next = next->next;
  649. free(next->f);
  650. free(next);
  651. table->len --;
  652. break;
  653. }
  654. entry = next;
  655. }
  656. }
  657. sem_post(&flow_table_lock);
  658. return 1;
  659. }
  660. /** Returns the index of a flow in the flow table if
  661. * it exists, returns 0 if it is not present.
  662. *
  663. * Inputs:
  664. * observed: details for the observed flow
  665. *
  666. * Output:
  667. * flow struct from table or NULL if it doesn't exist
  668. */
  669. flow *check_flow(struct packet_info *info){
  670. /* Loop through flows in table and see if it exists */
  671. int i;
  672. flow_entry *entry = table->first_entry;
  673. flow *candidate;
  674. flow *found = NULL;
  675. if(entry == NULL)
  676. return NULL;
  677. sem_wait(&flow_table_lock);
  678. /* Check first in this direction */
  679. for(i=0; i<table->len; i++){
  680. if(entry == NULL){
  681. printf("Error: entry is null\n");
  682. break;
  683. }
  684. candidate = entry->f;
  685. if(candidate->src_ip.s_addr == info->ip_hdr->src.s_addr){
  686. if(candidate->dst_ip.s_addr == info->ip_hdr->dst.s_addr){
  687. if(candidate->src_port == info->tcp_hdr->src_port){
  688. if(candidate->dst_port == info->tcp_hdr->dst_port){
  689. found = candidate;
  690. }
  691. }
  692. }
  693. }
  694. entry = entry->next;
  695. }
  696. entry = table->first_entry;
  697. /* Then in the other direction */
  698. for(i=0; i<table->len; i++){
  699. if(entry == NULL){
  700. printf("Error: entry is null\n");
  701. break;
  702. }
  703. candidate = entry->f;
  704. if(candidate->src_ip.s_addr == info->ip_hdr->dst.s_addr){
  705. if(candidate->dst_ip.s_addr == info->ip_hdr->src.s_addr){
  706. if(candidate->src_port == info->tcp_hdr->dst_port){
  707. if(candidate->dst_port == info->tcp_hdr->src_port){
  708. found = candidate;
  709. }
  710. }
  711. }
  712. }
  713. entry = entry->next;
  714. }
  715. if(found != NULL){
  716. found->ref_ctr++;
  717. }
  718. sem_post(&flow_table_lock);
  719. if(found != NULL && found->removed){
  720. remove_flow(found);
  721. found=NULL;
  722. }
  723. return found;
  724. }
  725. int init_session_cache(void){
  726. sessions = smalloc(sizeof(session_cache));
  727. sessions->length = 0;
  728. sessions->first_session = NULL;
  729. return 0;
  730. }
  731. /** Called from ServerHello, verifies that the session id returned matches
  732. * the session id requested from the client hello
  733. *
  734. * Input:
  735. * f: the tagged flow
  736. * hs: a pointer to the ServerHello message
  737. *
  738. * Output:
  739. * 0 if success, 1 if failed
  740. */
  741. static int verify_session_id(flow *f, uint8_t *hs){
  742. if (f->current_session == NULL)
  743. return 1;
  744. //increment pointer to point to sessionid
  745. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  746. p += 2; //skip version
  747. p += SSL3_RANDOM_SIZE; //skip random
  748. uint8_t id_len = (uint8_t) p[0];
  749. p ++;
  750. //check to see if it matches flow's session id set by ClientHello
  751. if(f->current_session->session_id_len > 0 && !memcmp(f->current_session->session_id, p, id_len)){
  752. //if it matched, update flow with master secret :D
  753. #ifdef DEBUG_HS
  754. printf("Session id matched!\n");
  755. printf("First session id (%p->%p):", sessions, sessions->first_session);
  756. #endif
  757. session *last = sessions->first_session;
  758. int found = 0;
  759. for(int i=0; ((i<sessions->length) && (!found)); i++){
  760. #ifdef DEBUG_HS_EXTRA
  761. printf("Checking saved session id: ");
  762. for (int j=0; j< last->session_id_len; j++){
  763. printf("%02x ", last->session_id[j]);
  764. }
  765. printf("\n");
  766. #endif
  767. if(!memcmp(last->session_id, f->current_session->session_id, id_len)){
  768. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  769. found = 1;
  770. }
  771. last = last->next;
  772. }
  773. if((!found) && (f->current_session->session_ticket_len > 0)){
  774. last = sessions->first_session;
  775. for(int i=0; ((i<sessions->length) && (!found)); i++){
  776. if( (last->session_ticket != NULL) && (last->session_ticket_len == f->current_session->session_ticket_len)){
  777. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  778. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  779. found = 1;
  780. #ifdef DEBUG_HS
  781. 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);
  782. for(int i=0; i< last->session_ticket_len; i++){
  783. printf("%02x ", last->session_ticket[i]);
  784. }
  785. printf("\n");
  786. #endif
  787. }
  788. }
  789. last = last->next;
  790. }
  791. }
  792. } else if (f->current_session->session_id_len == 0){
  793. //search for session ticket in session cache
  794. printf("clnt session id was empty, looking for ticket\n");
  795. session *last = sessions->first_session;
  796. if(f->current_session->session_ticket_len > 0){
  797. last = sessions->first_session;
  798. for(int i=0; i<sessions->length; i++){
  799. if(last->session_ticket_len == f->current_session->session_ticket_len){
  800. if(!memcmp(last->session_ticket, f->current_session->session_ticket, f->current_session->session_ticket_len)){
  801. memcpy(f->master_secret, last->master_secret, SSL3_MASTER_SECRET_SIZE);
  802. #ifdef DEBUG_HS
  803. 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);
  804. for(int i=0; i< last->session_ticket_len; i++){
  805. printf("%02x ", last->session_ticket[i]);
  806. }
  807. printf("\n");
  808. break;
  809. #endif
  810. }
  811. }
  812. last = last->next;
  813. }
  814. }
  815. } else if (f->current_session->session_id_len > 0){
  816. //server refused resumption, save new session id
  817. printf("session ids did not match, saving new id\n");
  818. save_session_id(f, p);
  819. }
  820. return 0;
  821. }
  822. /* Called from ClientHello. Checks to see if the session id len is > 0. If so,
  823. * saves sessionid for later verification. Also checks to see if a session
  824. * ticket is included as an extension.
  825. *
  826. * Input:
  827. * f: the tagged flow
  828. * hs: a pointer to the ServerHello message
  829. *
  830. * Output:
  831. * 0 if success, 1 if failed
  832. */
  833. static int check_extensions(flow *f, uint8_t *hs, uint32_t len){
  834. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  835. p += 2; //skip version
  836. p += SSL3_RANDOM_SIZE; //skip random
  837. session *new_session = smalloc(sizeof(session));
  838. new_session->session_id_len = (uint8_t) p[0];
  839. new_session->session_ticket_len = 0;
  840. new_session->session_ticket = NULL;
  841. p ++;
  842. if(new_session->session_id_len > 0){
  843. f->resume_session = 1;
  844. memcpy(new_session->session_id, p, new_session->session_id_len);
  845. new_session->next = NULL;
  846. #ifdef DEBUG_HS
  847. 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);
  848. printf("session id: \n");
  849. for(int i=0; i< new_session->session_id_len; i++){
  850. printf("%02x ", p[i]);
  851. }
  852. printf("\n");
  853. #endif
  854. f->current_session = new_session;
  855. }
  856. p += new_session->session_id_len;
  857. //check to see if there is a session ticket included
  858. //skip to extensions
  859. uint16_t ciphersuite_len = (p[0] << 8) + p[1];
  860. p += 2 + ciphersuite_len;
  861. uint8_t compress_meth_len = p[0];
  862. p += 1 + compress_meth_len;
  863. //search for SessionTicket TLS extension
  864. if(2 + SSL3_RANDOM_SIZE + new_session->session_id_len + 1 + 2 + ciphersuite_len + 1 + compress_meth_len > len){
  865. //no extension
  866. if(f->current_session == NULL)
  867. free(new_session);
  868. return 0;
  869. }
  870. uint16_t extensions_len = (p[0] << 8) + p[1];
  871. p += 2;
  872. while(extensions_len > 0){
  873. uint16_t type = (p[0] << 8) + p[1];
  874. p += 2;
  875. uint16_t ext_len = (p[0] << 8) + p[1];
  876. p += 2;
  877. if(type == 0x23){
  878. if(ext_len > 0){
  879. f->resume_session = 1;
  880. new_session->session_ticket_len = ext_len;
  881. new_session->session_ticket = scalloc(1, ext_len);
  882. memcpy(new_session->session_ticket, p, ext_len);
  883. f->current_session = new_session;
  884. }
  885. }
  886. if(type == 0x17){//Extended Master Secret
  887. f->extended_master_secret = 1;
  888. }
  889. p += ext_len;
  890. extensions_len -= (4 + ext_len);
  891. }
  892. if(!f->resume_session){
  893. free(new_session);
  894. f->stall = 0; //unstall the next packet
  895. }
  896. return 0;
  897. }
  898. /* Called from ServerHello. Cycles through extensions and verifies their use
  899. * in the flow.
  900. *
  901. * Input:
  902. * f: the tagged flow
  903. * hs: a pointer to the ServerHello message
  904. *
  905. * Output:
  906. * 0 if success, 1 if failed
  907. */
  908. static int verify_extensions(flow *f, uint8_t *hs, uint32_t len){
  909. uint8_t extended_master_secret = 0;
  910. uint32_t remaining_len = len;
  911. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  912. p += 2; //skip version
  913. p += SSL3_RANDOM_SIZE; //skip random
  914. remaining_len -= (2 + SSL3_RANDOM_SIZE);
  915. remaining_len -= (uint8_t) p[0] + 1;
  916. p += (uint8_t) p[0] + 1; //skip session id
  917. p += 2; //skip cipher suite
  918. remaining_len -= 2;
  919. p ++; //skip compression method
  920. remaining_len --;
  921. if(remaining_len < 2){
  922. return 0;
  923. }
  924. //cycle through extensions
  925. uint16_t extensions_len = (p[0] << 8) + p[1];
  926. p += 2;
  927. while(extensions_len > 0){
  928. uint16_t type = (p[0] << 8) + p[1];
  929. p += 2;
  930. uint16_t ext_len = (p[0] << 8) + p[1];
  931. p += 2;
  932. if(type == 0x17){
  933. extended_master_secret = 1;
  934. }
  935. p += ext_len;
  936. extensions_len -= (4 + ext_len);
  937. }
  938. //Check to make sure both client and server included extension
  939. if(!f->extended_master_secret || !extended_master_secret){
  940. f->extended_master_secret = 0;
  941. }
  942. #ifdef DEBUG_HS
  943. else {
  944. printf("Extended master secret extension\n");
  945. }
  946. #endif
  947. return 0;
  948. }
  949. /* Called from ServerHello during full handshake. Adds the session id to the
  950. * cache for later resumptions
  951. *
  952. * Input:
  953. * f: the tagged flow
  954. * hs: a pointer to the ServerHello message
  955. *
  956. * Output:
  957. * 0 if success, 1 if failed
  958. */
  959. static int save_session_id(flow *f, uint8_t *hs){
  960. //increment pointer to point to sessionid
  961. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  962. p += 2; //skip version
  963. p += SSL3_RANDOM_SIZE; //skip random
  964. session *new_session = smalloc(sizeof(session));
  965. new_session->session_id_len = (uint8_t) p[0];
  966. if((new_session->session_id_len <= 0) || (new_session->session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH)){
  967. //if this value is zero, the session is non-resumable or the
  968. //server will issue a NewSessionTicket handshake message
  969. free(new_session);
  970. return 0;
  971. }
  972. p++;
  973. memcpy(new_session->session_id, p, new_session->session_id_len);
  974. new_session->session_ticket_len = 0;
  975. new_session->session_ticket = NULL;
  976. new_session->next = NULL;
  977. if(f->current_session != NULL){
  978. free(f->current_session);
  979. }
  980. f->resume_session = 0;
  981. f->current_session = new_session;
  982. if(sessions->first_session == NULL){
  983. sessions->first_session = new_session;
  984. printf("First session id (%p->%p):", sessions, sessions->first_session);
  985. for(int i=0; i< new_session->session_id_len; i++){
  986. printf(" %02x", sessions->first_session->session_id[i]);
  987. }
  988. printf("\n");
  989. } else {
  990. session *last = sessions->first_session;
  991. for(int i=0; i< sessions->length -1; i++){
  992. if(last == NULL){
  993. printf("UH OH: last is null?\n");
  994. fflush(stdout);
  995. }
  996. last = last->next;
  997. }
  998. last->next = new_session;
  999. }
  1000. sessions->length ++;
  1001. #ifdef DEBUG_HS
  1002. printf("Saved session id:");
  1003. for(int i=0; i< new_session->session_id_len; i++){
  1004. printf(" %02x", new_session->session_id[i]);
  1005. }
  1006. printf("\n");
  1007. printf("THERE ARE NOW %d saved sessions\n", sessions->length);
  1008. #endif
  1009. return 0;
  1010. }
  1011. /* Called from NewSessionTicket. Adds the session ticket to the
  1012. * cache for later resumptions
  1013. *
  1014. * Input:
  1015. * f: the tagged flow
  1016. * hs: a pointer to the ServerHello message
  1017. *
  1018. * Output:
  1019. * 0 if success, 1 if failed
  1020. */
  1021. int save_session_ticket(flow *f, uint8_t *hs, uint32_t len){
  1022. #ifdef DEBUG_HS
  1023. printf("TICKET HDR:");
  1024. for(int i=0; i< HANDSHAKE_HEADER_LEN; i++){
  1025. printf("%02x ", hs[i]);
  1026. }
  1027. printf("\n");
  1028. #endif
  1029. uint8_t *p = hs + HANDSHAKE_HEADER_LEN;
  1030. p += 4;
  1031. session *new_session = scalloc(1, sizeof(session));
  1032. new_session->session_id_len = 0;
  1033. new_session->session_ticket_len = (p[0] << 8) + p[1];
  1034. new_session->next = NULL;
  1035. p += 2;
  1036. uint8_t *ticket = smalloc(new_session->session_ticket_len);
  1037. memcpy(ticket, p, new_session->session_ticket_len);
  1038. new_session->session_ticket = ticket;
  1039. memcpy(new_session->master_secret, f->master_secret, SSL3_MASTER_SECRET_SIZE);
  1040. if(sessions->first_session == NULL){
  1041. sessions->first_session = new_session;
  1042. } else {
  1043. session *last = sessions->first_session;
  1044. for(int i=0; i< (sessions->length-1); i++){
  1045. if(last == NULL){
  1046. printf("UH OH: last is null?\n");
  1047. fflush(stdout);
  1048. }
  1049. last = last->next;
  1050. }
  1051. last->next = new_session;
  1052. }
  1053. sessions->length ++;
  1054. #ifdef DEBUG_HS
  1055. printf("Saved session ticket:");
  1056. for(int i=0; i< new_session->session_ticket_len; i++){
  1057. printf(" %02x", p[i]);
  1058. }
  1059. printf("\n");
  1060. fflush(stdout);
  1061. printf("Saved session master secret:");
  1062. for(int i=0; i< SSL3_MASTER_SECRET_SIZE; i++){
  1063. printf(" %02x", new_session->master_secret[i]);
  1064. }
  1065. printf("\n");
  1066. fflush(stdout);
  1067. printf("THERE ARE NOW %d saved sessions (2)\n", sessions->length);
  1068. fflush(stdout);
  1069. #endif
  1070. return 0;
  1071. }
  1072. /* Adds a (handshake) packet to the flow's packet chain. If it can complete a record, passes
  1073. * this record to update_flow
  1074. *
  1075. * Note: the code in slitheen.c should ensure that this function only ever gets the next
  1076. * expected sequence number
  1077. */
  1078. int add_packet(flow *f, struct packet_info *info){
  1079. if (info->tcp_hdr == NULL || info->app_data_len <= 0){
  1080. return 0;
  1081. }
  1082. packet *new_packet = smalloc(sizeof(packet));
  1083. new_packet->seq_num = ntohl(info->tcp_hdr->sequence_num);
  1084. new_packet->len = info->app_data_len;
  1085. uint8_t *packet_data = smalloc(new_packet->len);
  1086. memcpy(packet_data, info->app_data, new_packet->len);
  1087. new_packet->data = packet_data;
  1088. new_packet->next = NULL;
  1089. uint8_t incoming = (info->ip_hdr->src.s_addr == f->src_ip.s_addr) ? 0 : 1;
  1090. packet_chain *chain = (incoming) ? f->ds_packet_chain : f->us_packet_chain;
  1091. queue *packet_queue = (incoming) ? f->ds_hs_queue : f->us_hs_queue;
  1092. if(new_packet->seq_num < chain->expected_seq_num){
  1093. //see if this packet contains any data we are missing
  1094. //TODO: figure out how/why this happens and what should follow
  1095. printf("ERROR: Received replayed packet O.o\n");
  1096. free(new_packet->data);
  1097. free(new_packet);
  1098. remove_flow(f);
  1099. return 1;
  1100. }
  1101. if(new_packet->seq_num > chain->expected_seq_num) {
  1102. printf("ERROR: Received future packet O.o\n");
  1103. free(new_packet->data);
  1104. free(new_packet);
  1105. remove_flow(f);
  1106. return 1;
  1107. }
  1108. //temporary: see if it's the only packet, if so is new record
  1109. if(peek(packet_queue, 0) == NULL){
  1110. if(new_packet->seq_num == chain->expected_seq_num){
  1111. const struct record_header *record_hdr = (struct record_header *) new_packet->data;
  1112. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  1113. chain->remaining_record_len = chain->record_len;
  1114. }
  1115. }
  1116. //append packet to queue
  1117. enqueue(packet_queue, new_packet);
  1118. chain->expected_seq_num += new_packet->len;
  1119. uint32_t record_offset = 0; //offset into record for updating info with any changes
  1120. uint32_t info_offset = 0; //offset into info for updating with changes
  1121. uint32_t info_len = 0; //number of bytes that possibly changed
  1122. //while there is still data left:
  1123. uint32_t available_data = new_packet->len;
  1124. while(available_data > 0){
  1125. //if full record, give to update_flow
  1126. if(chain->remaining_record_len <= new_packet->len){//we have enough to make a record
  1127. chain->remaining_record_len = 0;
  1128. uint8_t *record = smalloc(chain->record_len);
  1129. uint32_t record_len = chain->record_len;
  1130. uint32_t tmp_len = chain->record_len;
  1131. packet *next = peek(packet_queue, 0);
  1132. while(tmp_len > 0){
  1133. if(tmp_len >= next->len){
  1134. memcpy(record+chain->record_len - tmp_len, next->data, next->len);
  1135. if(next == new_packet){
  1136. new_packet = NULL;//TODO: why?
  1137. record_offset = chain->record_len - tmp_len;
  1138. info_len = next->len;
  1139. }
  1140. tmp_len -= next->len;
  1141. //remove packet from queue
  1142. next = dequeue(packet_queue);
  1143. free(next->data);
  1144. free(next);
  1145. next = peek(packet_queue, 0); //TODO: Do we need this???
  1146. available_data = 0;
  1147. } else { //didn't use up entire packet
  1148. memcpy(record+chain->record_len - tmp_len, next->data, tmp_len);
  1149. if(next == new_packet){//TODO: opposite shouldn't happen?
  1150. record_offset = chain->record_len - tmp_len;
  1151. info_len = tmp_len;
  1152. }
  1153. memmove(next->data, next->data+tmp_len, next->len - tmp_len);
  1154. next->len -= tmp_len;
  1155. available_data -= tmp_len;
  1156. tmp_len = 0;
  1157. //Last part of packet is a new record
  1158. const struct record_header *record_hdr = (struct record_header *) next->data;
  1159. chain->record_len = RECORD_LEN(record_hdr)+RECORD_HEADER_LEN;
  1160. chain->remaining_record_len = chain->record_len;
  1161. #ifdef DEBUG
  1162. printf("Found record of type %d\n", record_hdr->type);
  1163. fflush(stdout);
  1164. #endif
  1165. }
  1166. }
  1167. //if handshake is complete, send to relay code
  1168. if(f->application == 1){
  1169. //update packet info and send to replace_packet
  1170. struct packet_info *copy_info = copy_packet_info(info);
  1171. copy_info->app_data = record;
  1172. copy_info->app_data_len = record_len;
  1173. replace_packet(f, copy_info);
  1174. free(copy_info->app_data);
  1175. free(copy_info);
  1176. } else {
  1177. if(update_flow(f, record, incoming)){
  1178. free(record);
  1179. return 1;//error occurred and flow was removed
  1180. }
  1181. if(f->in_encrypted ==2 && incoming){
  1182. //if server finished message was received, copy changes back to packet
  1183. #ifdef DEBUG
  1184. printf("Replacing info->data with finished message (%d bytes).\n", info_len);
  1185. printf("Previous bytes:\n");
  1186. for(int i=0; i<info_len; i++){
  1187. printf("%02x ", info->app_data[info_offset+i]);
  1188. }
  1189. printf("\n");
  1190. printf("New bytes:\n");
  1191. for(int i=0; i<info_len; i++){
  1192. printf("%02x ", record[record_offset+i]);
  1193. }
  1194. printf("\n");
  1195. printf("SLITHEEN: Previous packet contents:\n");
  1196. for(int i=0; i< info->app_data_len; i++){
  1197. printf("%02x ", info->app_data[i]);
  1198. }
  1199. printf("\n");
  1200. #endif
  1201. memcpy(info->app_data+info_offset, record+record_offset, info_len);
  1202. #ifdef DEBUG
  1203. printf("SLITHEEN: Current packet contents:\n");
  1204. for(int i=0; i< info->app_data_len; i++){
  1205. printf("%02x ", info->app_data[i]);
  1206. }
  1207. printf("\n");
  1208. #endif
  1209. //update TCP checksum
  1210. tcp_checksum(info);
  1211. }
  1212. free(record);
  1213. if(new_packet != NULL){
  1214. info_offset += info_len;
  1215. }
  1216. }
  1217. } else {//can't make a full record yet
  1218. chain->remaining_record_len -= new_packet->len;
  1219. available_data = 0;
  1220. }
  1221. } //exhausted new packet len
  1222. return 0;
  1223. }