flow.c 45 KB

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