flow.c 36 KB

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