relay.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. /* Name: relay.c
  2. *
  3. * This file contains code that the relay station runs once the TLS handshake for
  4. * a tagged flow has been completed.
  5. *
  6. * These functions will extract covert data from the header
  7. * of HTTP GET requests and insert downstream data into leaf resources
  8. *
  9. * It is also responsible for keeping track of the HTTP state of the flow
  10. *
  11. * Slitheen - a decoy routing system for censorship resistance
  12. * Copyright (C) 2017 Cecylia Bocovich (cbocovic@uwaterloo.ca)
  13. *
  14. * This program is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation, version 3.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. *
  26. * Additional permission under GNU GPL version 3 section 7
  27. *
  28. * If you modify this Program, or any covered work, by linking or combining
  29. * it with the OpenSSL library (or a modified version of that library),
  30. * containing parts covered by the terms of the OpenSSL Licence and the
  31. * SSLeay license, the licensors of this Program grant you additional
  32. * permission to convey the resulting work. Corresponding Source for a
  33. * non-source form of such a combination shall include the source code
  34. * for the parts of the OpenSSL library used as well as that of the covered
  35. * work.
  36. */
  37. #include <stdio.h>
  38. #include <stdlib.h>
  39. #include <stdint.h>
  40. #include <regex.h>
  41. #include <sys/socket.h>
  42. #include <sys/types.h>
  43. #include <netinet/in.h>
  44. #include <netdb.h>
  45. #include <unistd.h>
  46. #include <pthread.h>
  47. #include <string.h>
  48. #include <openssl/bio.h>
  49. #include <openssl/evp.h>
  50. #include <openssl/rand.h>
  51. #include "relay.h"
  52. #include "packet.h"
  53. #include "flow.h"
  54. #include "crypto.h"
  55. #include "util.h"
  56. /* Data structures */
  57. struct proxy_thread_data {
  58. uint8_t *initial_data;
  59. uint16_t initial_len;
  60. uint16_t stream_id;
  61. int32_t pipefd;
  62. stream_table *streams;
  63. data_queue *downstream_queue;
  64. client *client;
  65. };
  66. struct socks_req {
  67. uint8_t version;
  68. uint8_t cmd;
  69. uint8_t rsvd;
  70. uint8_t addr_type;
  71. };
  72. struct __attribute__((__packed__)) sl_up_hdr {
  73. uint16_t stream_id;
  74. uint16_t len;
  75. };
  76. typedef struct stream_st {
  77. uint16_t stream_id;
  78. int32_t pipefd;
  79. struct stream_st *next;
  80. } stream;
  81. typedef struct stream_table_st {
  82. stream *first;
  83. } stream_table;
  84. static int process_downstream(flow *f, int32_t offset, struct packet_info *info);
  85. static int read_header(flow *f, struct packet_info *info);
  86. static int fill_with_downstream(flow *f, uint8_t *data, int32_t length);
  87. static void *proxy_covert_site(void *data);
  88. /** Called when a TLS application record is received for a
  89. * tagged flow. Upstream packets will be checked for covert
  90. * requests to censored sites, downstream packets will be
  91. * replaced with data from the censored queue or with garbage
  92. *
  93. * Inputs:
  94. * f: the tagged flow
  95. * info: the processed received application packet
  96. *
  97. * Output:
  98. * 0 on success, 1 on failure
  99. */
  100. int replace_packet(flow *f, struct packet_info *info){
  101. if (info == NULL || info->tcp_hdr == NULL){
  102. return 0;
  103. }
  104. #ifdef DEBUG
  105. fprintf(stdout,"Flow: %x:%d > %x:%d (%s)\n", info->ip_hdr->src.s_addr, ntohs(info->tcp_hdr->src_port), info->ip_hdr->dst.s_addr, ntohs(info->tcp_hdr->dst_port), (info->ip_hdr->src.s_addr != f->src_ip.s_addr)? "incoming":"outgoing");
  106. fprintf(stdout,"ID number: %u\n", htonl(info->ip_hdr->id));
  107. fprintf(stdout,"Sequence number: %u\n", htonl(info->tcp_hdr->sequence_num));
  108. fprintf(stdout,"Acknowledgement number: %u\n", htonl(info->tcp_hdr->ack_num));
  109. fflush(stdout);
  110. #endif
  111. if(info->app_data_len <= 0){
  112. return 0;
  113. }
  114. /* if outgoing, decrypt and look at header */
  115. if(info->ip_hdr->src.s_addr == f->src_ip.s_addr){
  116. read_header(f, info);
  117. return 0;
  118. } else {
  119. #ifdef DEBUG
  120. printf("Current sequence number: %d\n", f->downstream_seq_num);
  121. printf("Received sequence number: %d\n", htonl(info->tcp_hdr->sequence_num));
  122. #endif
  123. uint32_t offset = htonl(info->tcp_hdr->sequence_num) - f->downstream_seq_num;
  124. if(offset == 0)
  125. f->downstream_seq_num += info->app_data_len;
  126. /* if incoming, replace with data from queue */
  127. process_downstream(f, offset, info);
  128. #ifdef DEBUG2
  129. uint8_t *p = (uint8_t *) info->tcp_hdr;
  130. fprintf(stdout, "ip hdr length: %d\n", htons(info->ip_hdr->len));
  131. fprintf(stdout, "Injecting the following packet:\n");
  132. for(int i=0; i< htons(info->ip_hdr->len)-1; i++){
  133. fprintf(stdout, "%02x ", p[i]);
  134. }
  135. fprintf(stdout, "\n");
  136. fflush(stdout);
  137. #endif
  138. }
  139. return 0;
  140. }
  141. /** Reads the HTTP header of upstream data and searches for
  142. * a covert request in an x-slitheen header. Sends this
  143. * request to the indicated site and saves the response to
  144. * the censored queue
  145. *
  146. * Inputs:
  147. * f: the tagged flow
  148. * info: the processed received packet
  149. *
  150. * Ouput:
  151. * 0 on success, 1 on failure
  152. */
  153. static int read_header(flow *f, struct packet_info *info){
  154. uint8_t *p = info->app_data;
  155. if (info->tcp_hdr == NULL){
  156. return 0;
  157. }
  158. uint8_t *record_ptr = NULL;
  159. struct record_header *record_hdr;
  160. uint32_t record_length;
  161. if(f->upstream_remaining > 0){
  162. //check to see whether the previous record has finished
  163. if(f->upstream_remaining > info->app_data_len){
  164. //ignore entire packet for now
  165. queue_block *new_block = smalloc(sizeof(queue_block));
  166. uint8_t *block_data = smalloc(info->app_data_len);
  167. memcpy(block_data, p, info->app_data_len);
  168. new_block->len = info->app_data_len;
  169. new_block->offset = 0;
  170. new_block->data = block_data;
  171. new_block->next = NULL;
  172. //add block to upstream data chain
  173. if(f->upstream_queue == NULL){
  174. f->upstream_queue = new_block;
  175. } else {
  176. queue_block *last = f->upstream_queue;
  177. while(last->next != NULL){
  178. last = last->next;
  179. }
  180. last->next = new_block;
  181. }
  182. f->upstream_remaining -= info->app_data_len;
  183. return 0;
  184. } else {
  185. //process what we have
  186. record_hdr = (struct record_header*) f->upstream_queue->data;
  187. record_length = RECORD_LEN(record_hdr);
  188. record_ptr = smalloc(record_length+ RECORD_HEADER_LEN);
  189. queue_block *current = f->upstream_queue;
  190. int32_t offset =0;
  191. while(f->upstream_queue != NULL){
  192. memcpy(record_ptr+offset, current->data, current->len);
  193. offset += current->len;
  194. free(current->data);
  195. f->upstream_queue = current->next;
  196. free(current);
  197. current = f->upstream_queue;
  198. }
  199. memcpy(record_ptr+offset, p, f->upstream_remaining);
  200. p = record_ptr;
  201. record_hdr = (struct record_header*) p;
  202. f->upstream_remaining = 0;
  203. }
  204. } else {
  205. //check to see if the new record is too long
  206. record_hdr = (struct record_header*) p;
  207. record_length = RECORD_LEN(record_hdr);
  208. if(record_length + RECORD_HEADER_LEN > info->app_data_len){
  209. //add info to upstream queue
  210. queue_block *new_block = smalloc(sizeof(queue_block));
  211. uint8_t *block_data = smalloc(info->app_data_len);
  212. memcpy(block_data, p, info->app_data_len);
  213. new_block->len = info->app_data_len;
  214. new_block->data = block_data;
  215. new_block->next = NULL;
  216. //add block to upstream queue
  217. if(f->upstream_queue == NULL){
  218. f->upstream_queue = new_block;
  219. } else {
  220. queue_block *last = f->upstream_queue;
  221. while(last->next != NULL){
  222. last = last->next;
  223. }
  224. last->next = new_block;
  225. }
  226. f->upstream_remaining = record_length - new_block->len;
  227. return 0;
  228. }
  229. }
  230. p+= RECORD_HEADER_LEN;
  231. uint8_t *decrypted_data = smalloc(record_length);
  232. memcpy(decrypted_data, p, record_length);
  233. int32_t decrypted_len = encrypt(f, decrypted_data, decrypted_data, record_length, 0, record_hdr->type, 0, 0);
  234. if(decrypted_len<0){
  235. printf("US: decryption failed!\n");
  236. if(record_ptr != NULL)
  237. free(record_ptr);
  238. free(decrypted_data);
  239. return 0;
  240. }
  241. if(record_hdr->type == 0x15){
  242. printf("received alert %x:%d > %x:%d (%s)\n", info->ip_hdr->src.s_addr, ntohs(info->tcp_hdr->src_port), info->ip_hdr->dst.s_addr, ntohs(info->tcp_hdr->dst_port), (info->ip_hdr->src.s_addr != f->src_ip.s_addr)? "incoming":"outgoing");
  243. for(int i=0; i<decrypted_len; i++){
  244. printf("%02x ", decrypted_data[EVP_GCM_TLS_EXPLICIT_IV_LEN + i]);
  245. }
  246. printf("\n");
  247. fflush(stdout);
  248. //TODO: re-encrypt and return
  249. }
  250. #ifdef DEBUG_US
  251. printf("Upstream data: (%x:%d > %x:%d )\n",info->ip_hdr->src.s_addr,ntohs(info->tcp_hdr->src_port), info->ip_hdr->dst.s_addr, ntohs(info->tcp_hdr->dst_port));
  252. printf("%s\n", decrypted_data+EVP_GCM_TLS_EXPLICIT_IV_LEN);
  253. #endif
  254. /* search through decrypted data for x-ignore */
  255. char *header_ptr = strstr((const char *) decrypted_data+EVP_GCM_TLS_EXPLICIT_IV_LEN, "X-Slitheen");
  256. uint8_t *upstream_data;
  257. if(header_ptr == NULL){
  258. if(record_ptr != NULL)
  259. free(record_ptr);
  260. free(decrypted_data);
  261. return 0;
  262. }
  263. #ifdef DEBUG_US
  264. printf("UPSTREAM: Found x-slitheen header\n");
  265. fflush(stdout);
  266. fprintf(stdout,"UPSTREAM Flow: %x:%d > %x:%d (%s)\n", info->ip_hdr->src.s_addr,ntohs(info->tcp_hdr->src_port), info->ip_hdr->dst.s_addr, ntohs(info->tcp_hdr->dst_port) ,(info->ip_hdr->src.s_addr != f->src_ip.s_addr)? "incoming":"outgoing");
  267. fprintf(stdout, "Sequence number: %d\n", ntohs(info->tcp_hdr->sequence_num));
  268. #endif
  269. header_ptr += strlen("X-Slitheen: ");
  270. if(*header_ptr == '\r' || *header_ptr == '\0'){
  271. #ifdef DEBUG_US
  272. printf("No messages\n");
  273. #endif
  274. free(decrypted_data);
  275. return 0;
  276. }
  277. int32_t num_messages = 1;
  278. char *messages[50]; //TODO: grow this array
  279. messages[0] = header_ptr;
  280. char *c = header_ptr;
  281. while(*c != '\r' && *c != '\0'){
  282. if(*c == ' '){
  283. *c = '\0';
  284. messages[num_messages] = c+1;
  285. num_messages ++;
  286. }
  287. c++;
  288. }
  289. c++;
  290. *c = '\0';
  291. #ifdef DEBUG_US
  292. printf("UPSTREAM: Found %d messages\n", num_messages);
  293. #endif
  294. for(int i=0; i< num_messages; i++){
  295. char *message = messages[i];
  296. //b64 decode the data
  297. int32_t decode_len = strlen(message);
  298. if(message[decode_len-2] == '='){
  299. decode_len = decode_len*3/4 - 2;
  300. } else if(message[decode_len-1] == '='){
  301. decode_len = decode_len*3/4 - 1;
  302. } else {
  303. decode_len = decode_len*3/4;
  304. }
  305. upstream_data = smalloc(decode_len + 1);
  306. BIO *bio, *b64;
  307. bio = BIO_new_mem_buf(message, -1);
  308. b64 = BIO_new(BIO_f_base64());
  309. bio = BIO_push(b64, bio);
  310. BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
  311. int32_t output_len = BIO_read(bio, upstream_data, strlen(message));
  312. BIO_free_all(bio);
  313. #ifdef DEBUG_US
  314. printf("Decoded to get %d bytes:\n", output_len);
  315. for(int j=0; j< output_len; j++){
  316. printf("%02x ", upstream_data[j]);
  317. }
  318. printf("\n");
  319. fflush(stdout);
  320. #endif
  321. p = upstream_data;
  322. if(i== 0){
  323. //this is the Slitheen ID
  324. #ifdef DEBUG_US
  325. printf("Slitheen ID:");
  326. for(int j=0; j< output_len; j++){
  327. printf("%02x ", p[j]);
  328. }
  329. printf("\n");
  330. #endif
  331. //find stream table or create new one
  332. client *last = clients->first;
  333. while(last != NULL){
  334. if(!memcmp(last->slitheen_id, p, output_len)){
  335. f->downstream_queue = last->downstream_queue;
  336. f->client_ptr = last;
  337. break;
  338. #ifdef DEBUG_US
  339. } else {
  340. for(int j=0; j< output_len; j++){
  341. printf("%02x ", last->slitheen_id[j]);
  342. }
  343. printf(" != ");
  344. for(int j=0; j< output_len; j++){
  345. printf("%02x ", p[j]);
  346. }
  347. printf("\n");
  348. #endif
  349. }
  350. last = last->next;
  351. }
  352. if(f->client_ptr == NULL){
  353. //create new client
  354. printf("Creating a new client\n");
  355. client *new_client = smalloc(sizeof(client));
  356. memcpy(new_client->slitheen_id, p, output_len);
  357. new_client->streams = smalloc(sizeof(stream_table));
  358. new_client->streams->first = NULL;
  359. new_client->downstream_queue = smalloc(sizeof(data_queue));
  360. sem_init(&(new_client->queue_lock), 0, 1);
  361. new_client->downstream_queue->first_block = NULL;
  362. new_client->encryption_counter = 0;
  363. new_client->next = NULL;
  364. /* Now generate super encryption keys */
  365. generate_client_super_keys(new_client->slitheen_id, new_client);
  366. //add to client table
  367. if(clients->first == NULL){
  368. clients->first = new_client;
  369. } else {
  370. client *last = clients->first;
  371. while(last->next != NULL){
  372. last = last->next;
  373. }
  374. last->next = new_client;
  375. }
  376. //set f's stream table
  377. f->client_ptr = new_client;
  378. f->downstream_queue = new_client->downstream_queue;
  379. }
  380. free(upstream_data);
  381. continue;
  382. }
  383. while(output_len > 0){
  384. struct sl_up_hdr *sl_hdr = (struct sl_up_hdr *) p;
  385. uint16_t stream_id = sl_hdr->stream_id;
  386. uint16_t stream_len = ntohs(sl_hdr->len);
  387. p += sizeof(struct sl_up_hdr);
  388. output_len -= sizeof(struct sl_up_hdr);
  389. stream_table *streams = f->client_ptr->streams;
  390. //If a thread for this stream id exists, get the thread info and pipe data
  391. int32_t stream_pipe = -1;
  392. stream *last = streams->first;
  393. if(streams->first != NULL){
  394. if(last->stream_id == stream_id){
  395. stream_pipe = last->pipefd;
  396. } else {
  397. while(last->next != NULL){
  398. last = last->next;
  399. if(last->stream_id == stream_id){
  400. stream_pipe = last->pipefd;
  401. break;
  402. }
  403. }
  404. }
  405. }
  406. if(stream_pipe != -1){
  407. if(stream_len ==0){
  408. printf("Client closed. We are here\n");
  409. close(stream_pipe);
  410. break;
  411. }
  412. #ifdef DEBUG_US
  413. printf("Found stream id %d\n", last->stream_id);
  414. printf("Writing %d bytes to pipe\n", stream_len);
  415. #endif
  416. int32_t bytes_sent = write(stream_pipe, p, stream_len);
  417. if(bytes_sent < 0){
  418. printf("Error sending bytes to stream pipe\n");
  419. }
  420. } else if(stream_len > 0){
  421. /*Else, spawn a thread to handle the proxy to this site*/
  422. pthread_t proxy_thread;
  423. int32_t pipefd[2];
  424. if(pipe(pipefd) < 0){
  425. printf("Error creating pipe\n");
  426. free(decrypted_data);
  427. if(record_ptr != NULL)
  428. free(record_ptr);
  429. return 1;
  430. }
  431. uint8_t *initial_data = smalloc(stream_len);
  432. memcpy(initial_data, p, stream_len);
  433. struct proxy_thread_data *thread_data =
  434. smalloc(sizeof(struct proxy_thread_data));
  435. thread_data->initial_data = initial_data;
  436. thread_data->initial_len = stream_len;
  437. thread_data->stream_id = stream_id;
  438. thread_data->pipefd = pipefd[0];
  439. thread_data->downstream_queue = f->downstream_queue;
  440. thread_data->client = f->client_ptr;
  441. pthread_create(&proxy_thread, NULL, proxy_covert_site, (void *) thread_data);
  442. pthread_detach(proxy_thread);
  443. printf("Spawned thread for proxy\n");
  444. //add stream to table
  445. stream *new_stream = smalloc(sizeof(stream));
  446. new_stream->stream_id = stream_id;
  447. new_stream->pipefd = pipefd[1];
  448. new_stream->next = NULL;
  449. if(streams->first == NULL){
  450. streams->first = new_stream;
  451. } else {
  452. stream *last = streams->first;
  453. while(last->next != NULL){
  454. last = last->next;
  455. }
  456. last->next = new_stream;
  457. }
  458. } else{
  459. printf("Error, stream len 0\n");
  460. break;
  461. }
  462. output_len -= stream_len;
  463. p += stream_len;
  464. }
  465. free(upstream_data);
  466. }
  467. //save a reference to the proxy threads in a global table
  468. free(decrypted_data);
  469. if(record_ptr != NULL)
  470. free(record_ptr);
  471. return 0;
  472. }
  473. /** Called by spawned pthreads in read_header to send upstream
  474. * data to the censored site and receive responses. Downstream
  475. * data is stored in the slitheen id's downstream_queue. Function and
  476. * thread will terminate when the client closes the connection
  477. * to the covert destination
  478. *
  479. * Input:
  480. * A struct that contains the following information:
  481. * - the tagged flow
  482. * - the initial upstream data + len (including connect request)
  483. * - the read end of the pipe
  484. * - the downstream queue for the client
  485. *
  486. */
  487. static void *proxy_covert_site(void *data){
  488. struct proxy_thread_data *thread_data =
  489. (struct proxy_thread_data *) data;
  490. uint8_t *p = thread_data->initial_data;
  491. uint16_t data_len = thread_data->initial_len;
  492. uint16_t stream_id = thread_data->stream_id;
  493. int32_t bytes_sent;
  494. #ifdef DEBUG_PROXY
  495. printf("PROXY: created new thread for stream %d\n", stream_id);
  496. #endif
  497. data_queue *downstream_queue = thread_data->downstream_queue;
  498. client *clnt = thread_data->client;
  499. stream_table *streams = clnt->streams;
  500. struct socks_req *clnt_req = (struct socks_req *) p;
  501. p += 4;
  502. data_len -= 4;
  503. int32_t handle = -1;
  504. //see if it's a connect request
  505. if(clnt_req->cmd != 0x01){
  506. printf("PROXY: error not a connect request\n");
  507. goto err;
  508. }
  509. struct sockaddr_in dest;
  510. dest.sin_family = AF_INET;
  511. uint8_t domain_len;
  512. switch(clnt_req->addr_type){
  513. case 0x01:
  514. //IPv4
  515. dest.sin_addr.s_addr = *((uint32_t*) p);
  516. p += 4;
  517. data_len -= 4;
  518. break;
  519. case 0x03:
  520. //domain name
  521. domain_len = p[0];
  522. p++;
  523. data_len --;
  524. uint8_t *domain_name = smalloc(domain_len+1);
  525. memcpy(domain_name, p, domain_len);
  526. domain_name[domain_len] = '\0';
  527. struct hostent *host;
  528. host = gethostbyname((const char *) domain_name);
  529. dest.sin_addr = *((struct in_addr *) host->h_addr);
  530. p += domain_len;
  531. data_len -= domain_len;
  532. free(domain_name);
  533. break;
  534. case 0x04:
  535. //IPv6
  536. printf("PROXY: error IPv6\n");
  537. goto err;//TODO: add IPv6 functionality
  538. break;
  539. }
  540. //now set the port
  541. dest.sin_port = *((uint16_t *) p);
  542. p += 2;
  543. data_len -= 2;
  544. handle = socket(AF_INET, SOCK_STREAM, 0);
  545. if(handle < 0){
  546. printf("PROXY: error creating socket\n");
  547. goto err;
  548. }
  549. struct sockaddr_in my_addr;
  550. socklen_t my_addr_len = sizeof(my_addr);
  551. int32_t error = connect (handle, (struct sockaddr *) &dest, sizeof (struct sockaddr));
  552. #ifdef DEBUG_PROXY
  553. printf("PROXY: Connected to covert site for stream %d\n", stream_id);
  554. #endif
  555. fflush(stdout);
  556. if(error <0){
  557. goto err;
  558. }
  559. getsockname(handle, (struct sockaddr *) &my_addr, &my_addr_len);
  560. //see if there were extra upstream bytes
  561. if(data_len > 0){
  562. #ifdef DEBUG_PROXY
  563. printf("Data len is %d\n", data_len);
  564. printf("Upstream bytes: ");
  565. for(int i=0; i< data_len; i++){
  566. printf("%02x ", p[i]);
  567. }
  568. printf("\n");
  569. #endif
  570. bytes_sent = send(handle, p,
  571. data_len, 0);
  572. if( bytes_sent <= 0){
  573. goto err;
  574. }
  575. }
  576. uint8_t *buffer = smalloc(BUFSIZ);
  577. int32_t buffer_len = BUFSIZ;
  578. //now select on reading from the pipe and from the socket
  579. for(;;){
  580. fd_set readfds;
  581. fd_set writefds;
  582. int32_t nfds = (handle > thread_data->pipefd) ?
  583. handle +1 : thread_data->pipefd + 1;
  584. FD_ZERO(&readfds);
  585. FD_ZERO(&writefds);
  586. FD_SET(thread_data->pipefd, &readfds);
  587. FD_SET(handle, &readfds);
  588. FD_SET(handle, &writefds);
  589. if (select(nfds, &readfds, &writefds, NULL, NULL) < 0){
  590. printf("select error\n");
  591. break;
  592. }
  593. if(FD_ISSET(thread_data->pipefd, &readfds) && FD_ISSET(handle, &writefds)){
  594. //we have upstream data ready for writing
  595. int32_t bytes_read = read(thread_data->pipefd, buffer, buffer_len);
  596. if(bytes_read > 0){
  597. #ifdef DEBUG_PROXY
  598. printf("PROXY (id %d): read %d bytes from pipe\n", stream_id, bytes_read);
  599. for(int i=0; i< bytes_read; i++){
  600. printf("%02x ", buffer[i]);
  601. }
  602. printf("\n");
  603. printf("%s\n", buffer);
  604. #endif
  605. bytes_sent = send(handle, buffer,
  606. bytes_read, 0);
  607. if( bytes_sent <= 0){
  608. printf("Error sending bytes to covert site (stream %d)\n", stream_id);
  609. break;
  610. } else if (bytes_sent < bytes_read){
  611. printf("Sent less bytes than read to covert site (stream %d)\n", stream_id);
  612. break;
  613. }
  614. } else {
  615. //Client closed the connection, we can delete this stream from the downstream queue
  616. printf("Deleting stream %d from the downstream queue\n", stream_id);
  617. sem_wait(&clnt->queue_lock);
  618. queue_block *last = downstream_queue->first_block;
  619. queue_block *prev = last;
  620. while(last != NULL){
  621. if(last->stream_id == stream_id){
  622. //remove block from queue
  623. printf("removing a block!\n");
  624. fflush(stdout);
  625. if(last == downstream_queue->first_block){
  626. downstream_queue->first_block = last->next;
  627. free(last->data);
  628. free(last);
  629. last = downstream_queue->first_block;
  630. prev = last;
  631. } else {
  632. prev->next = last->next;
  633. free(last->data);
  634. free(last);
  635. last = prev->next;
  636. }
  637. } else {
  638. prev = last;
  639. last = last->next;
  640. }
  641. }
  642. sem_post(&clnt->queue_lock);
  643. printf("Finished deleting from downstream queue\n");
  644. fflush(stdout);
  645. break;
  646. }
  647. }
  648. if (FD_ISSET(handle, &readfds)){
  649. //we have downstream data read for saving
  650. int32_t bytes_read;
  651. bytes_read = recv(handle, buffer, buffer_len, 0);
  652. if(bytes_read > 0){
  653. uint8_t *new_data = smalloc(bytes_read);
  654. memcpy(new_data, buffer, bytes_read);
  655. #ifdef DEBUG_PROXY
  656. printf("PROXY (id %d): read %d bytes from censored site\n",stream_id, bytes_read);
  657. for(int i=0; i< bytes_read; i++){
  658. printf("%02x ", buffer[i]);
  659. }
  660. printf("\n");
  661. #endif
  662. //make a new queue block
  663. queue_block *new_block = smalloc(sizeof(queue_block));
  664. new_block->len = bytes_read;
  665. new_block->offset = 0;
  666. new_block->data = new_data;
  667. new_block->next = NULL;
  668. new_block->stream_id = stream_id;
  669. sem_wait(&clnt->queue_lock);
  670. if(downstream_queue->first_block == NULL){
  671. downstream_queue->first_block = new_block;
  672. }
  673. else{
  674. queue_block *last = downstream_queue->first_block;
  675. while(last->next != NULL)
  676. last = last->next;
  677. last->next = new_block;
  678. }
  679. sem_post(&clnt->queue_lock);
  680. } else {
  681. printf("PROXY (id %d): read %d bytes from censored site\n",stream_id, bytes_read);
  682. break;
  683. }
  684. }
  685. }
  686. printf("Closing connection for stream %d\n", stream_id);
  687. //remove self from list
  688. stream *last = streams->first;
  689. stream *prev = last;
  690. if(streams->first != NULL){
  691. if(last->stream_id == stream_id){
  692. streams->first = last->next;
  693. free(last);
  694. } else {
  695. while(last->next != NULL){
  696. prev = last;
  697. last = last->next;
  698. if(last->stream_id == stream_id){
  699. prev->next = last->next;
  700. free(last);
  701. break;
  702. }
  703. }
  704. }
  705. }
  706. if(thread_data->initial_data != NULL){
  707. free(thread_data->initial_data);
  708. }
  709. free(thread_data);
  710. free(buffer);
  711. close(handle);
  712. pthread_detach(pthread_self());
  713. pthread_exit(NULL);
  714. return 0;
  715. err:
  716. //remove self from list
  717. last = streams->first;
  718. prev = last;
  719. if(streams->first != NULL){
  720. if(last->stream_id == stream_id){
  721. streams->first = last->next;
  722. free(last);
  723. } else {
  724. while(last->next != NULL){
  725. prev = last;
  726. last = last->next;
  727. if(last->stream_id == stream_id){
  728. prev->next = last->next;
  729. free(last);
  730. break;
  731. }
  732. }
  733. }
  734. }
  735. if(thread_data->initial_data != NULL){
  736. free(thread_data->initial_data);
  737. }
  738. free(thread_data);
  739. if(handle > 0){
  740. close(handle);
  741. }
  742. pthread_detach(pthread_self());
  743. pthread_exit(NULL);
  744. return 0;
  745. }
  746. /** Replaces downstream record contents with data from the
  747. * censored queue, padding with garbage bytes if no more
  748. * censored data exists.
  749. *
  750. * Inputs:
  751. * f: the tagged flow
  752. * data: a pointer to the received packet's application
  753. * data
  754. * data_len: the length of the packet's application data
  755. * offset: if the packet is misordered, the number of
  756. * application-level bytes in missing packets
  757. *
  758. * Output:
  759. * Returns 0 on sucess
  760. */
  761. static int process_downstream(flow *f, int32_t offset, struct packet_info *info){
  762. uint8_t *p = info->app_data;
  763. uint32_t remaining_packet_len = info->app_data_len;
  764. uint32_t partial_offset;
  765. uint32_t remaining_record_len, record_len;
  766. uint8_t partial = 0, false_tag = 0, changed = 0;
  767. uint8_t *record, *record_ptr;
  768. int32_t n;
  769. struct record_header *record_hdr;
  770. while(remaining_packet_len > 0){ //while bytes remain in the packet
  771. if(f->partial_record != NULL){
  772. partial = 1;
  773. remaining_record_len = f->partial_record_total_len - f->partial_record_len;
  774. if(remaining_record_len > remaining_packet_len){ //ignore entire packet
  775. partial_offset = f->partial_record_len;
  776. f->partial_record_len += remaining_packet_len;
  777. memcpy(f->partial_record+ partial_offset, p, remaining_packet_len);
  778. remaining_record_len = remaining_packet_len;
  779. } else { // finishing out this record
  780. partial_offset = f->partial_record_len;
  781. f->partial_record_len += remaining_record_len;
  782. memcpy(f->partial_record+ partial_offset, p, remaining_record_len);
  783. }
  784. record_len = remaining_record_len;
  785. //copy record to temporary ptr
  786. record_ptr = malloc(f->partial_record_len);
  787. memcpy(record_ptr, f->partial_record, f->partial_record_len);
  788. } else { //new record
  789. if(remaining_packet_len < RECORD_HEADER_LEN){
  790. #ifdef DEBUG
  791. printf("partial record header: \n");
  792. for(int i= 0; i< remaining_packet_len; i++){
  793. printf("%02x ", p[i]);
  794. }
  795. printf("\n");
  796. fflush(stdout);
  797. #endif
  798. f->partial_record_header = smalloc(RECORD_HEADER_LEN);
  799. memcpy(f->partial_record_header, p, remaining_packet_len);
  800. f->partial_record_header_len = remaining_packet_len;
  801. remaining_packet_len -= remaining_packet_len;
  802. break;
  803. }
  804. if(f->partial_record_header_len > 0){
  805. memcpy(f->partial_record_header+ f->partial_record_header_len,
  806. p, RECORD_HEADER_LEN - f->partial_record_header_len);
  807. record_hdr = (struct record_header *) f->partial_record_header;
  808. } else {
  809. record_hdr = (struct record_header*) p;
  810. }
  811. record_len = RECORD_LEN(record_hdr);
  812. #ifdef DEBUG_DOWN
  813. fprintf(stdout,"Flow: %x > %x (%s)\n", info->ip_hdr->src.s_addr, info->ip_hdr->dst.s_addr, (info->ip_hdr->src.s_addr != f->src_ip.s_addr)? "incoming":"outgoing");
  814. fprintf(stdout,"ID number: %u\n", htonl(info->ip_hdr->id));
  815. fprintf(stdout,"Sequence number: %u\n", htonl(info->tcp_hdr->sequence_num));
  816. fprintf(stdout,"Acknowledgement number: %u\n", htonl(info->tcp_hdr->ack_num));
  817. fprintf(stdout, "Record:\n");
  818. for(int i=0; i< RECORD_HEADER_LEN; i++){
  819. printf("%02x ", ((uint8_t *) record_hdr)[i]);
  820. }
  821. printf("\n");
  822. printf("Text: ");
  823. printf("%s", ((uint8_t *) record_hdr) + RECORD_HEADER_LEN);
  824. printf("\n");
  825. fflush(stdout);
  826. #endif
  827. p += (RECORD_HEADER_LEN - f->partial_record_header_len);
  828. remaining_packet_len -= (RECORD_HEADER_LEN - f->partial_record_header_len);
  829. if(record_len > remaining_packet_len){
  830. partial = 1;
  831. f->partial_record = smalloc(record_len);
  832. f->partial_record_dec = smalloc(record_len);
  833. f->partial_record_total_len = record_len;
  834. f->partial_record_len = remaining_packet_len;
  835. partial_offset = 0;
  836. memcpy(f->partial_record, p, remaining_packet_len);
  837. }
  838. remaining_record_len = (record_len > remaining_packet_len) ? remaining_packet_len : record_len;
  839. record_len = remaining_record_len;
  840. //copy record to temporary ptr
  841. record_ptr = malloc(remaining_record_len);
  842. memcpy(record_ptr, p, remaining_record_len); //points to the beginning of record data
  843. }
  844. #ifdef DEBUG_DOWN
  845. printf("Received bytes (len %d)\n", remaining_record_len);
  846. for(int i=0; i< remaining_record_len; i++){
  847. printf("%02x ", p[i]);
  848. }
  849. printf("\n");
  850. #endif
  851. record = p; // save location of original data
  852. p = record_ptr;
  853. if(partial){
  854. //if we now have all of the record, decrypt full thing and check tag
  855. if(f->partial_record_len == f->partial_record_total_len){
  856. #ifdef DEBUG_DOWN
  857. printf("Received full partial record (len=%d):\n", f->partial_record_len);
  858. for(int i=0; i< f->partial_record_len; i ++){
  859. printf("%02x", record_ptr[i]);
  860. }
  861. printf("\n");
  862. #endif
  863. n = encrypt(f, record_ptr, record_ptr, f->partial_record_len, 1, 0x17, 0, 0);
  864. if(n <= 0){
  865. free(f->partial_record_dec);
  866. free(f->partial_record);
  867. f->partial_record = NULL;
  868. f->partial_record_dec = NULL;
  869. f->partial_record_total_len = 0;
  870. f->partial_record_len = 0;
  871. free(record_ptr);
  872. return 0; //TODO: goto err or return correctly
  873. }
  874. } else {
  875. //partially decrypt record
  876. n = partial_aes_gcm_tls_cipher(f, record_ptr, record_ptr, f->partial_record_len, 0);
  877. if(n <= 0){
  878. //do something smarter here
  879. printf("Decryption failed\n");
  880. if(f->partial_record_header_len > 0){
  881. f->partial_record_header_len = 0;
  882. free(f->partial_record_header);
  883. }
  884. free(record_ptr);
  885. return 0;//TODO: goto err to free record_ptr
  886. }
  887. }
  888. //copy already modified data
  889. memcpy(p, f->partial_record_dec, partial_offset);
  890. //now update pointer to past where we've already parsed
  891. if(partial_offset){
  892. p += partial_offset;
  893. if(n + EVP_GCM_TLS_EXPLICIT_IV_LEN >= partial_offset){
  894. remaining_record_len = n + EVP_GCM_TLS_EXPLICIT_IV_LEN - partial_offset;
  895. } else {//only received last part of tag
  896. remaining_record_len = 0;
  897. }
  898. } else {
  899. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  900. remaining_record_len = n;
  901. }
  902. } else {
  903. //now decrypt the record
  904. n = encrypt(f, record_ptr, record_ptr, remaining_record_len, 1,
  905. record_hdr->type, 0, 0);
  906. if(n < 0){
  907. //do something smarter here
  908. printf("Decryption failed\n");
  909. if(f->partial_record_header_len > 0){
  910. f->partial_record_header_len = 0;
  911. free(f->partial_record_header);
  912. }
  913. free(record_ptr);
  914. return 0;//TODO goto an err to free record_ptr
  915. }
  916. p += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  917. remaining_record_len = n;
  918. }
  919. changed = 1;
  920. #ifdef DEBUG_DOWN
  921. printf("Decrypted new record\n");
  922. printf("Bytes:\n");
  923. for(int i=0; i< n; i++){
  924. printf("%02x ", record_ptr[EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  925. }
  926. printf("\n");
  927. printf("Text:\n");
  928. printf("%s\n", record_ptr+EVP_GCM_TLS_EXPLICIT_IV_LEN);
  929. printf("Parseable text:\n");
  930. printf("%s\n", p);
  931. fflush(stdout);
  932. #endif
  933. char *len_ptr, *needle;
  934. while(remaining_record_len > 0){
  935. #ifdef RESOURCE_DEBUG
  936. printf("Current state (flow %p): %x\n", f, f->httpstate);
  937. printf("Remaining record len: %d\n", remaining_record_len);
  938. #endif
  939. switch(f->httpstate){
  940. case PARSE_HEADER:
  941. //determine whether it's transfer encoded or otherwise
  942. //figure out what the content-type is
  943. len_ptr = strstr((const char *) p, "Content-Type: image");
  944. if(len_ptr != NULL){
  945. f->replace_response = 1;
  946. memcpy(len_ptr + 14, "sli/theen", 9);
  947. char *c = len_ptr + 14+9;
  948. while(c[0] != '\r'){
  949. c[0] = ' ';
  950. c++;
  951. }
  952. #ifdef RESOURCE_DEBUG
  953. printf("Found and replaced leaf header\n");
  954. #endif
  955. } else {
  956. //check for video
  957. len_ptr = strstr((const char *) p, "Content-Type: video/webm");
  958. if(len_ptr != NULL){
  959. printf("Found webm resource!\n");
  960. f->replace_response = 1;
  961. memcpy(len_ptr + 14, "sli/theenv", 10);
  962. char *c = len_ptr + 14+10;
  963. while(c[0] != '\r'){
  964. c[0] = ' ';
  965. c++;
  966. }
  967. }
  968. else {
  969. f->replace_response = 0;
  970. }
  971. }
  972. //TODO: more cases for more status codes
  973. //TODO: better way of finding terminating string
  974. len_ptr = strstr((const char *) p, "304 Not Modified");
  975. if(len_ptr != NULL){
  976. //no message body, look for terminating string
  977. len_ptr = strstr((const char *) p, "\r\n\r\n");
  978. if(len_ptr != NULL){
  979. f->httpstate = PARSE_HEADER;
  980. remaining_record_len -= (((uint8_t *)len_ptr - p) + 4);
  981. p = (uint8_t *) len_ptr + 4;
  982. #ifdef RESOURCE_DEBUG
  983. printf("Found a 304 not modified, waiting for next header\n");
  984. printf("Remaining record len: %d\n", remaining_record_len);
  985. #endif
  986. } else {
  987. #ifdef RESOURCE_DEBUG
  988. printf("Missing end of header. Sending to FORFEIT_REST (%p)\n", f);
  989. #endif
  990. f->httpstate = FORFEIT_REST;
  991. }
  992. break;
  993. }
  994. //check for 200 OK message
  995. len_ptr = strstr((const char *) p, "200 OK");
  996. if(len_ptr == NULL){
  997. f->replace_response = 0;
  998. }
  999. len_ptr = strstr((const char *) p, "Transfer-Encoding");
  1000. if(len_ptr != NULL){
  1001. printf("Transfer encoding\n");
  1002. if(!memcmp(len_ptr + 19, "chunked", 7)){
  1003. printf("Chunked\n");
  1004. //now find end of header
  1005. len_ptr = strstr((const char *) p, "\r\n\r\n");
  1006. if(len_ptr != NULL){
  1007. f->httpstate = BEGIN_CHUNK;
  1008. remaining_record_len -= (((uint8_t *)len_ptr - p) + 4);
  1009. p = (uint8_t *) len_ptr + 4;
  1010. } else {
  1011. printf("Couldn't find end of header\n");
  1012. f->httpstate = FORFEIT_REST;
  1013. }
  1014. } else {// other encodings not yet implemented
  1015. f->httpstate = FORFEIT_REST;
  1016. }
  1017. } else {
  1018. len_ptr = strstr((const char *) p, "Content-Length:");
  1019. if(len_ptr != NULL){
  1020. len_ptr += 15;
  1021. f->remaining_response_len = strtol((const char *) len_ptr, NULL, 10);
  1022. #ifdef RESOURCE_DEBUG
  1023. printf("content-length: %d\n", f->remaining_response_len);
  1024. #endif
  1025. len_ptr = strstr((const char *) p, "\r\n\r\n");
  1026. if(len_ptr != NULL){
  1027. f->httpstate = MID_CONTENT;
  1028. remaining_record_len -= (((uint8_t *)len_ptr - p) + 4);
  1029. p = (uint8_t *) len_ptr + 4;
  1030. #ifdef RESOURCE_DEBUG
  1031. printf("Remaining record len: %d\n", remaining_record_len);
  1032. #endif
  1033. } else {
  1034. remaining_record_len = 0;
  1035. #ifdef RESOURCE_DEBUG
  1036. printf("Missing end of header. Sending to FORFEIT_REST (%p)\n", f);
  1037. #endif
  1038. f->httpstate = FORFEIT_REST;
  1039. }
  1040. } else {
  1041. #ifdef RESOURCE_DEBUG
  1042. printf("No content length of transfer encoding field, sending to FORFEIT_REST (%p)\n", f);
  1043. #endif
  1044. f->httpstate = FORFEIT_REST;
  1045. remaining_record_len = 0;
  1046. }
  1047. }
  1048. break;
  1049. case MID_CONTENT:
  1050. //check if content is replaceable
  1051. if(f->remaining_response_len > remaining_record_len){
  1052. if(f->replace_response){
  1053. fill_with_downstream(f, p, remaining_record_len);
  1054. #ifdef DEBUG_DOWN
  1055. printf("Replaced with:\n");
  1056. for(int i=0; i< remaining_record_len; i++){
  1057. printf("%02x ", p[i]);
  1058. }
  1059. printf("\n");
  1060. #endif
  1061. }
  1062. f->remaining_response_len -= remaining_record_len;
  1063. p += remaining_record_len;
  1064. remaining_record_len = 0;
  1065. } else {
  1066. if(f->replace_response){
  1067. fill_with_downstream(f, p, remaining_record_len);
  1068. #ifdef DEBUG_DOWN
  1069. printf("Replaced with:\n");
  1070. for(int i=0; i< remaining_record_len; i++){
  1071. printf("%02x ", p[i]);
  1072. }
  1073. printf("\n");
  1074. #endif
  1075. }
  1076. remaining_record_len -= f->remaining_response_len;
  1077. p += f->remaining_response_len;
  1078. #ifdef DEBUG_DOWN
  1079. printf("Change state %x --> PARSE_HEADER (%p)\n", f->httpstate, f);
  1080. #endif
  1081. f->httpstate = PARSE_HEADER;
  1082. f->remaining_response_len = 0;
  1083. }
  1084. break;
  1085. case BEGIN_CHUNK:
  1086. {
  1087. int32_t chunk_size = strtol((const char *) p, NULL, 16);
  1088. #ifdef RESOURCE_DEBUG
  1089. printf("BEGIN_CHUNK: chunk size is %d\n", chunk_size);
  1090. #endif
  1091. if(chunk_size == 0){
  1092. f->httpstate = END_BODY;
  1093. } else {
  1094. f->httpstate = MID_CHUNK;
  1095. }
  1096. f->remaining_response_len = chunk_size;
  1097. needle = strstr((const char *) p, "\r\n");
  1098. if(needle != NULL){
  1099. remaining_record_len -= ((uint8_t *) needle - p + 2);
  1100. p = (uint8_t *) needle + 2;
  1101. } else {
  1102. remaining_record_len = 0;
  1103. #ifdef RESOURCE_DEBUG
  1104. printf("Error parsing in BEGIN_CHUNK, FORFEIT (%p)\n", f);
  1105. #endif
  1106. f->httpstate = FORFEIT_REST;
  1107. }
  1108. }
  1109. break;
  1110. case MID_CHUNK:
  1111. if(f->remaining_response_len > remaining_record_len){
  1112. if(f->replace_response){
  1113. fill_with_downstream(f, p, remaining_record_len);
  1114. #ifdef DEBUG_DOWN
  1115. printf("Replaced with:\n");
  1116. for(int i=0; i< remaining_record_len; i++){
  1117. printf("%02x ", p[i]);
  1118. }
  1119. printf("\n");
  1120. #endif
  1121. }
  1122. f->remaining_response_len -= remaining_record_len;
  1123. p += remaining_record_len;
  1124. remaining_record_len = 0;
  1125. } else {
  1126. if(f->replace_response){
  1127. fill_with_downstream(f, p, f->remaining_response_len);
  1128. #ifdef DEBUG_DOWN
  1129. printf("Replaced with:\n");
  1130. for(int i=0; i< f->remaining_response_len; i++){
  1131. printf("%02x ", p[i]);
  1132. }
  1133. printf("\n");
  1134. #endif
  1135. }
  1136. remaining_record_len -= f->remaining_response_len;
  1137. p += f->remaining_response_len;
  1138. f->remaining_response_len = 0;
  1139. f->httpstate = END_CHUNK;
  1140. }
  1141. break;
  1142. case END_CHUNK:
  1143. needle = strstr((const char *) p, "\r\n");
  1144. if(needle != NULL){
  1145. f->httpstate = BEGIN_CHUNK;
  1146. p += 2;
  1147. remaining_record_len -= 2;
  1148. } else {
  1149. remaining_record_len = 0;
  1150. printf("Couldn't find end of chunk, sending to FORFEIT_REST (%p)\n", f);
  1151. f->httpstate = FORFEIT_REST;
  1152. }
  1153. break;
  1154. case END_BODY:
  1155. needle = strstr((const char *) p, "\r\n");
  1156. if(needle != NULL){
  1157. printf("Change state %x --> PARSE_HEADER (%p)\n", f->httpstate, f);
  1158. f->httpstate = PARSE_HEADER;
  1159. p += 2;
  1160. remaining_record_len -= 2;
  1161. } else {
  1162. remaining_record_len = 0;
  1163. printf("Couldn't find end of body, sending to FORFEIT_REST (%p)\n", f);
  1164. f->httpstate = FORFEIT_REST;
  1165. }
  1166. break;
  1167. case FORFEIT_REST:
  1168. case USE_REST:
  1169. remaining_record_len = 0;
  1170. break;
  1171. default:
  1172. break;
  1173. }
  1174. }
  1175. #ifdef DEBUG_DOWN
  1176. if(changed && f->replace_response){
  1177. printf("Resource is now\n");
  1178. printf("Bytes:\n");
  1179. for(int i=0; i< n; i++){
  1180. printf("%02x ", record_ptr[EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  1181. }
  1182. printf("\n");
  1183. printf("Text:\n");
  1184. printf("%s\n", record_ptr+EVP_GCM_TLS_EXPLICIT_IV_LEN);
  1185. fflush(stdout);
  1186. }
  1187. #endif
  1188. if(partial){
  1189. //partially encrypting data
  1190. //first copy plaintext to flow struct
  1191. if(n + EVP_GCM_TLS_EXPLICIT_IV_LEN >= partial_offset){
  1192. memcpy(f->partial_record_dec + partial_offset, record_ptr+partial_offset, n + EVP_GCM_TLS_EXPLICIT_IV_LEN - partial_offset);
  1193. } //otherwise, this packet contains only part of the tag
  1194. n = partial_aes_gcm_tls_cipher(f, record_ptr, record_ptr, n+ EVP_GCM_TLS_EXPLICIT_IV_LEN, 1);
  1195. if(n < 0){
  1196. printf("Partial decryption failed!\n");
  1197. free(record_ptr);
  1198. return 0;
  1199. }
  1200. #ifdef DEBUG_DOWN
  1201. printf("Partially encrypted bytes:\n");
  1202. for(int i=0; i < n + EVP_GCM_TLS_EXPLICIT_IV_LEN; i++){
  1203. printf("%02x ", record_ptr[i]);
  1204. }
  1205. printf("\n");
  1206. #endif
  1207. //if we received all of the partial packet, add tag and release it
  1208. if (f->partial_record_len == f->partial_record_total_len){
  1209. //compute tag
  1210. #ifdef DEBUG_DOWN
  1211. partial_aes_gcm_tls_tag(f, record_ptr + n + EVP_GCM_TLS_EXPLICIT_IV_LEN, n);
  1212. printf("tag: (%d bytes)\n", EVP_GCM_TLS_TAG_LEN);
  1213. for(int i=0; i< EVP_GCM_TLS_TAG_LEN; i++){
  1214. printf("%02x ", record_ptr[n + EVP_GCM_TLS_EXPLICIT_IV_LEN+i]);
  1215. }
  1216. printf("\n");
  1217. #endif
  1218. if(false_tag){//tag on original record was incorrect O.o add incorrect tag
  1219. } else {//compute correct tag TODO: fill in
  1220. }
  1221. free(f->partial_record_dec);
  1222. free(f->partial_record);
  1223. f->partial_record = NULL;
  1224. f->partial_record_dec = NULL;
  1225. f->partial_record_total_len = 0;
  1226. f->partial_record_len = 0;
  1227. partial = 0;
  1228. } else {
  1229. //compute tag just to clear out ctx
  1230. uint8_t *tag = smalloc(EVP_GCM_TLS_TAG_LEN);
  1231. partial_aes_gcm_tls_tag(f, tag, EVP_GCM_TLS_TAG_LEN);
  1232. free(tag);
  1233. }
  1234. p = record_ptr + partial_offset;
  1235. partial_offset += n + EVP_GCM_TLS_EXPLICIT_IV_LEN - partial_offset;
  1236. } else {
  1237. if((n = encrypt(f, record_ptr, record_ptr, n + EVP_GCM_TLS_EXPLICIT_IV_LEN,
  1238. 1, record_hdr->type, 1, 1)) < 0){
  1239. printf("UH OH, failed to re-encrypt record\n");
  1240. if(f->partial_record_header_len > 0){
  1241. f->partial_record_header_len = 0;
  1242. free(f->partial_record_header);
  1243. }
  1244. free(record_ptr);
  1245. return 0;
  1246. }
  1247. p = record_ptr;
  1248. }
  1249. #ifdef DEBUG_DOWN2
  1250. fprintf(stdout,"Flow: %x:%d > %x:%d (%s)\n", info->ip_hdr->src.s_addr, ntohs(info->tcp_hdr->src_port), info->ip_hdr->dst.s_addr, ntohs(info->tcp_hdr->dst_port), (info->ip_hdr->src.s_addr != f->src_ip.s_addr)? "incoming":"outgoing");
  1251. fprintf(stdout,"ID number: %u\n", htonl(info->ip_hdr->id));
  1252. fprintf(stdout,"Sequence number: %u\n", htonl(info->tcp_hdr->sequence_num));
  1253. fprintf(stdout,"Acknowledgement number: %u\n", htonl(info->tcp_hdr->ack_num));
  1254. printf("New ciphertext bytes:\n");
  1255. for(int i=0; i< n; i++){
  1256. printf("%02x ", record_ptr[i]);
  1257. }
  1258. printf("\n");
  1259. #endif
  1260. //Copy changed temporary data to original packet
  1261. memcpy(record, p, record_len);
  1262. p = record + record_len;
  1263. remaining_packet_len -= record_len;
  1264. if(f->partial_record_header_len > 0){
  1265. f->partial_record_header_len = 0;
  1266. free(f->partial_record_header);
  1267. }
  1268. free(record_ptr);//free temporary record
  1269. }
  1270. if(changed){
  1271. tcp_checksum(info);
  1272. }
  1273. return 0;
  1274. }
  1275. /** Fills a given pointer with downstream data of the specified length. If no downstream data
  1276. * exists, pads it with garbage bytes. All downstream data is accompanied by a stream id and
  1277. * lengths of both the downstream data and garbage data
  1278. *
  1279. * Inputs:
  1280. * data: a pointer to where the downstream data should be entered
  1281. * length: The length of the downstream data required
  1282. *
  1283. */
  1284. static int fill_with_downstream(flow *f, uint8_t *data, int32_t length){
  1285. printf("In fill_with_ds\n");
  1286. uint8_t *p = data;
  1287. int32_t remaining = length;
  1288. struct slitheen_header *sl_hdr;
  1289. data_queue *downstream_queue = f->downstream_queue;
  1290. client *client_ptr = f->client_ptr;
  1291. if(client_ptr == NULL){
  1292. //printf("ERROR: no client\n");
  1293. return 1;
  1294. }
  1295. //Fill as much as we can from the censored_queue
  1296. //Note: need enough for the header and one block of data (16 byte IV, 16 byte
  1297. // block, 16 byte MAC) = header_len + 48.
  1298. while((remaining > (SLITHEEN_HEADER_LEN + 48)) && downstream_queue != NULL && downstream_queue->first_block != NULL){
  1299. //amount of data we'll actualy fill with (16 byte IV and 16 byte MAC)
  1300. int32_t fill_amount = remaining - SLITHEEN_HEADER_LEN - 32;
  1301. fill_amount -= fill_amount % 16; //rounded down to nearest block size
  1302. sem_wait(&client_ptr->queue_lock);
  1303. queue_block *first_block = downstream_queue->first_block;
  1304. int32_t block_length = first_block->len;
  1305. int32_t offset = first_block->offset;
  1306. #ifdef DEBUG
  1307. printf("Censored queue is at %p.\n", first_block);
  1308. printf("This block has %d bytes left\n", block_length - offset);
  1309. printf("We need %d bytes\n", remaining - SLITHEEN_HEADER_LEN);
  1310. #endif
  1311. uint8_t *encrypted_data = p;
  1312. sl_hdr = (struct slitheen_header *) p;
  1313. sl_hdr->counter = ++(client_ptr->encryption_counter);
  1314. sl_hdr->stream_id = first_block->stream_id;
  1315. sl_hdr->len = 0x0000;
  1316. sl_hdr->garbage = 0x0000;
  1317. sl_hdr->zeros = 0x0000;
  1318. p += SLITHEEN_HEADER_LEN;
  1319. remaining -= SLITHEEN_HEADER_LEN;
  1320. p += 16; //iv length
  1321. remaining -= 16;
  1322. if(block_length > offset + fill_amount){
  1323. //use part of the block, update offset
  1324. memcpy(p, first_block->data+offset, fill_amount);
  1325. first_block->offset += fill_amount;
  1326. p += fill_amount;
  1327. sl_hdr->len = fill_amount;
  1328. remaining -= fill_amount;
  1329. } else {
  1330. //use all of the block and free it
  1331. memcpy(p, first_block->data+offset, block_length - offset);
  1332. free(first_block->data);
  1333. downstream_queue->first_block = first_block->next;
  1334. free(first_block);
  1335. p += (block_length - offset);
  1336. sl_hdr->len = (block_length - offset);
  1337. remaining -= (block_length - offset);
  1338. }
  1339. sem_post(&client_ptr->queue_lock);
  1340. //pad to 16 bytes if necessary
  1341. uint8_t padding = 0;
  1342. if(sl_hdr->len %16){
  1343. padding = 16 - (sl_hdr->len)%16;
  1344. memset(p, padding, padding);
  1345. remaining -= padding;
  1346. p += padding;
  1347. }
  1348. p += 16;
  1349. remaining -= 16;
  1350. //fill rest of packet with padding, if needed
  1351. if(remaining < SLITHEEN_HEADER_LEN){
  1352. RAND_bytes(p, remaining);
  1353. sl_hdr->garbage = htons(remaining);
  1354. p += remaining;
  1355. remaining -= remaining;
  1356. }
  1357. int16_t data_len = sl_hdr->len;
  1358. sl_hdr->len = htons(sl_hdr->len);
  1359. //now encrypt
  1360. super_encrypt(client_ptr, encrypted_data, data_len + padding);
  1361. #ifdef DEBUG_DOWN
  1362. printf("DWNSTRM: slitheen header: ");
  1363. for(int i=0; i< SLITHEEN_HEADER_LEN; i++){
  1364. printf("%02x ",((uint8_t *) sl_hdr)[i]);
  1365. }
  1366. printf("\n");
  1367. printf("Sending %d downstream bytes:", data_len);
  1368. for(int i=0; i< data_len+16+16; i++){
  1369. printf("%02x ", ((uint8_t *) sl_hdr)[i+SLITHEEN_HEADER_LEN]);
  1370. }
  1371. printf("\n");
  1372. #endif
  1373. }
  1374. //now, if we need more data, fill with garbage
  1375. if(remaining >= SLITHEEN_HEADER_LEN ){
  1376. sl_hdr = (struct slitheen_header *) p;
  1377. sl_hdr->counter = 0x00;
  1378. sl_hdr->stream_id = 0x00;
  1379. remaining -= SLITHEEN_HEADER_LEN;
  1380. sl_hdr->len = 0x00;
  1381. sl_hdr->garbage = htons(remaining);
  1382. sl_hdr->zeros = 0x0000;
  1383. #ifdef DEBUG_DOWN
  1384. printf("DWNSTRM: slitheen header: ");
  1385. for(int i=0; i< SLITHEEN_HEADER_LEN; i++){
  1386. printf("%02x ", p[i]);
  1387. }
  1388. printf("\n");
  1389. #endif
  1390. //encrypt slitheen header
  1391. super_encrypt(client_ptr, p, 0);
  1392. p += SLITHEEN_HEADER_LEN;
  1393. RAND_bytes(p, remaining);
  1394. } else if(remaining > 0){
  1395. //fill with random data
  1396. RAND_bytes(p, remaining);
  1397. }
  1398. return 0;
  1399. }
  1400. /** Computes the TCP checksum of the data according to RFC 793
  1401. * sum all 16-bit words in the segment, pad the last word if
  1402. * needed
  1403. *
  1404. * there is a pseudo-header prefixed to the segment and
  1405. * included in the checksum:
  1406. *
  1407. * +--------+--------+--------+--------+
  1408. * | Source Address |
  1409. * +--------+--------+--------+--------+
  1410. * | Destination Address |
  1411. * +--------+--------+--------+--------+
  1412. * | zero | PTCL | TCP Length |
  1413. * +--------+--------+--------+--------+
  1414. */
  1415. uint16_t tcp_checksum(struct packet_info *info){
  1416. uint16_t tcp_length = info->app_data_len + info->size_tcp_hdr;
  1417. struct in_addr src = info->ip_hdr->src;
  1418. struct in_addr dst = info->ip_hdr->dst;
  1419. uint8_t proto = IPPROTO_TCP;
  1420. //set the checksum to zero
  1421. info->tcp_hdr->chksum = 0;
  1422. //sum pseudoheader
  1423. uint32_t sum = (ntohl(src.s_addr)) >> 16;
  1424. sum += (ntohl(src.s_addr)) &0xFFFF;
  1425. sum += (ntohl(dst.s_addr)) >> 16;
  1426. sum += (ntohl(dst.s_addr)) & 0xFFFF;
  1427. sum += proto;
  1428. sum += tcp_length;
  1429. //sum tcp header (with zero-d checksum)
  1430. uint8_t *p = (uint8_t *) info->tcp_hdr;
  1431. for(int i=0; i < info->size_tcp_hdr; i+=2){
  1432. sum += (uint16_t) ((p[i] << 8) + p[i+1]);
  1433. }
  1434. //now sum the application data
  1435. p = info->app_data;
  1436. for(int i=0; i< info->app_data_len-1; i+=2){
  1437. sum += (uint16_t) ((p[i] << 8) + p[i+1]);
  1438. }
  1439. if(info->app_data_len %2 != 0){
  1440. sum += (uint16_t) (p[info->app_data_len - 1]) << 8;
  1441. }
  1442. //now add most significant to last significant bits
  1443. sum = (sum >> 16) + (sum & 0xFFFF);
  1444. sum += sum >>16;
  1445. //now subtract from 0xFF
  1446. sum = 0xFFFF - sum;
  1447. //set chksum to calculated value
  1448. info->tcp_hdr->chksum = ntohs(sum);
  1449. return (uint16_t) sum;
  1450. }