relay.c 57 KB

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