socks5proxy.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. /** SOCKSv5 proxy that listens on port 1080.
  2. *
  3. *
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <stdint.h>
  9. #include <errno.h>
  10. #include <string.h>
  11. #include <sys/socket.h>
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <netinet/in.h>
  15. #include <netdb.h>
  16. #include <pthread.h>
  17. #include <fcntl.h>
  18. #include <openssl/bio.h>
  19. #include <openssl/evp.h>
  20. #include <openssl/buffer.h>
  21. #define SLITHEEN_ID_LEN 10
  22. #define SLITHEEN_SUPER_SECRET_SIZE 10
  23. #define SLITHEEN_SUPER_CONST "SLITHEEN_SUPER_ENCRYPT"
  24. #define SLITHEEN_SUPER_CONST_SIZE 22
  25. #define NEW
  26. int proxy_data(int sockfd, uint16_t stream_id, int32_t pipefd);
  27. void *demultiplex_data();
  28. struct __attribute__ ((__packed__)) slitheen_hdr {
  29. uint64_t counter;
  30. uint16_t stream_id;
  31. uint16_t len;
  32. uint16_t garbage;
  33. uint16_t zeros;
  34. };
  35. #define SLITHEEN_HEADER_LEN 16
  36. struct __attribute__ ((__packed__)) slitheen_up_hdr{
  37. uint16_t stream_id;
  38. uint16_t len;
  39. };
  40. typedef struct connection_st{
  41. int32_t pipe_fd;
  42. uint16_t stream_id;
  43. struct connection_st *next;
  44. } connection;
  45. typedef struct connection_table_st{
  46. connection *first;
  47. } connection_table;
  48. static connection_table *connections;
  49. typedef struct super_data_st {
  50. //EVP_CIPHER_CTX *header_ctx;
  51. //EVP_CIPHER_CTX *body_ctx;
  52. uint8_t *header_key;
  53. uint8_t *body_key;
  54. EVP_MD_CTX *body_mac_ctx;
  55. } super_data;
  56. static super_data *super;
  57. int main(void){
  58. int listen_socket;
  59. struct sockaddr_in address;
  60. struct sockaddr_in remote_addr;
  61. socklen_t addr_size;
  62. mkfifo("OUS_out", 0666);
  63. //randomly generate slitheen id
  64. uint8_t slitheen_id[SLITHEEN_ID_LEN];
  65. RAND_bytes(slitheen_id, SLITHEEN_ID_LEN);
  66. printf("Randomly generated slitheen id: ");
  67. int i;
  68. for(i=0; i< SLITHEEN_ID_LEN; i++){
  69. printf("%02x ", slitheen_id[i]);
  70. }
  71. printf("\n");
  72. // Calculate super encryption keys
  73. generate_super_keys(slitheen_id);
  74. //b64 encode slitheen ID
  75. const char *encoded_bytes;
  76. BUF_MEM *buffer_ptr;
  77. BIO *bio, *b64;
  78. b64 = BIO_new(BIO_f_base64());
  79. bio = BIO_new(BIO_s_mem());
  80. bio = BIO_push(b64, bio);
  81. BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
  82. BIO_write(bio, slitheen_id, SLITHEEN_ID_LEN);
  83. BIO_flush(bio);
  84. BIO_get_mem_ptr(bio, &buffer_ptr);
  85. BIO_set_close(bio, BIO_NOCLOSE);
  86. BIO_free_all(bio);
  87. encoded_bytes = (*buffer_ptr).data;
  88. //give encoded slitheen ID to ous
  89. struct sockaddr_in ous_addr;
  90. ous_addr.sin_family = AF_INET;
  91. inet_pton(AF_INET, "127.0.0.1", &(ous_addr.sin_addr));
  92. ous_addr.sin_port = htons(8888);
  93. int32_t ous_in = socket(AF_INET, SOCK_STREAM, 0);
  94. if(ous_in < 0){
  95. printf("Failed to make ous_in socket\n");
  96. return 1;
  97. }
  98. int32_t error = connect(ous_in, (struct sockaddr *) &ous_addr, sizeof (struct sockaddr));
  99. if(error < 0){
  100. printf("Error connecting\n");
  101. return 1;
  102. }
  103. uint8_t *message = calloc(1, BUFSIZ);
  104. sprintf(message, "POST / HTTP/1.1\r\nContent-Length: %zd\r\n\r\n%s ", strlen(encoded_bytes), encoded_bytes);
  105. int32_t bytes_sent = send(ous_in, message, strlen(message), 0);
  106. printf("Wrote %d bytes to OUS_in: %s\n", bytes_sent, message);
  107. free(message);
  108. /* Spawn process to listen for incoming data from OUS
  109. int32_t demux_pipe[2];
  110. if(pipe(demux_pipe) < 0){
  111. printf("Failed to create pipe for new thread\n");
  112. return 1;
  113. }*/
  114. connections = calloc(1, sizeof(connection_table));
  115. connections->first = NULL;
  116. pthread_t *demux_thread = calloc(1, sizeof(pthread_t));
  117. pthread_create(demux_thread, NULL, demultiplex_data, NULL);
  118. if (!(listen_socket = socket(AF_INET, SOCK_STREAM, 0))){
  119. printf("Error creating socket\n");
  120. fflush(stdout);
  121. return 1;
  122. }
  123. address.sin_family = AF_INET;
  124. address.sin_addr.s_addr = INADDR_ANY;
  125. address.sin_port = htons(1080);
  126. int enable = 1;
  127. if (setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) <0 ){
  128. printf("Error setting sockopt\n");
  129. return 1;
  130. }
  131. if(bind(listen_socket, (struct sockaddr *) &address, sizeof(address))){
  132. printf("Error binding socket\n");
  133. fflush(stdout);
  134. return 1;
  135. }
  136. if(listen(listen_socket, 10) < 0){
  137. printf("Error listening\n");
  138. fflush(stdout);
  139. close(listen_socket);
  140. exit(1);
  141. }
  142. uint8_t last_id = 1;
  143. printf("Ready for listening\n");
  144. for(;;){
  145. addr_size = sizeof(remote_addr);
  146. int new_socket;
  147. new_socket = accept(listen_socket, (struct sockaddr *) &remote_addr,
  148. &addr_size);
  149. if(new_socket < 0){
  150. perror("accept");
  151. exit(1);
  152. }
  153. printf("New connection\n");
  154. //assign a new stream_id and create a pipe for the session
  155. connection *new_conn = calloc(1, sizeof(connection));
  156. new_conn->stream_id = last_id++;
  157. int32_t pipefd[2];
  158. if(pipe(pipefd) < 0){
  159. printf("Failed to create pipe\n");
  160. continue;
  161. }
  162. new_conn->pipe_fd = pipefd[1];
  163. new_conn->next = NULL;
  164. if(connections->first == NULL){
  165. connections->first = new_conn;
  166. printf("Added first connection with id: %d\n", new_conn->stream_id);
  167. printf("Connection table (%p) has entry %p\n", connections, connections->first);
  168. fflush(stdout);
  169. } else {
  170. connection *last = connections->first;
  171. printf("New incoming connection\n");
  172. fflush(stdout);
  173. while(last->next != NULL){
  174. last = last->next;
  175. }
  176. last->next = new_conn;
  177. printf("Added connection with id: %d at %p\n", new_conn->stream_id, last->next);
  178. fflush(stdout);
  179. }
  180. int pid = fork();
  181. if(pid == 0){ //child
  182. close(listen_socket);
  183. printf("demux reads from pipe fd %d", pipefd[1]);
  184. fflush(stdout);
  185. proxy_data(new_socket, new_conn->stream_id, pipefd[0]);
  186. exit(0);
  187. }
  188. close(new_socket);
  189. }
  190. return 0;
  191. }
  192. int PRF(uint8_t *secret, int32_t secret_len,
  193. uint8_t *seed1, int32_t seed1_len,
  194. uint8_t *seed2, int32_t seed2_len,
  195. uint8_t *seed3, int32_t seed3_len,
  196. uint8_t *seed4, int32_t seed4_len,
  197. uint8_t *output, int32_t output_len){
  198. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  199. EVP_PKEY *mac_key;
  200. const EVP_MD *md = EVP_sha256();
  201. uint8_t A[EVP_MAX_MD_SIZE];
  202. size_t len, A_len;
  203. int chunk = EVP_MD_size(md);
  204. int remaining = output_len;
  205. uint8_t *out = output;
  206. EVP_MD_CTX_init(&ctx);
  207. EVP_MD_CTX_init(&ctx_tmp);
  208. EVP_MD_CTX_init(&ctx_init);
  209. EVP_MD_CTX_set_flags(&ctx_init, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
  210. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, secret, secret_len);
  211. /* Calculate first A value */
  212. EVP_DigestSignInit(&ctx_init, NULL, md, NULL, mac_key);
  213. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  214. if(seed1 != NULL && seed1_len > 0){
  215. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  216. }
  217. if(seed2 != NULL && seed2_len > 0){
  218. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  219. }
  220. if(seed3 != NULL && seed3_len > 0){
  221. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  222. }
  223. if(seed4 != NULL && seed4_len > 0){
  224. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  225. }
  226. EVP_DigestSignFinal(&ctx, A, &A_len);
  227. //iterate until desired length is achieved
  228. while(remaining > 0){
  229. /* Now compute SHA384(secret, A+seed) */
  230. EVP_MD_CTX_copy_ex(&ctx, &ctx_init);
  231. EVP_DigestSignUpdate(&ctx, A, A_len);
  232. EVP_MD_CTX_copy_ex(&ctx_tmp, &ctx);
  233. if(seed1 != NULL && seed1_len > 0){
  234. EVP_DigestSignUpdate(&ctx, seed1, seed1_len);
  235. }
  236. if(seed2 != NULL && seed2_len > 0){
  237. EVP_DigestSignUpdate(&ctx, seed2, seed2_len);
  238. }
  239. if(seed3 != NULL && seed3_len > 0){
  240. EVP_DigestSignUpdate(&ctx, seed3, seed3_len);
  241. }
  242. if(seed4 != NULL && seed4_len > 0){
  243. EVP_DigestSignUpdate(&ctx, seed4, seed4_len);
  244. }
  245. if(remaining > chunk){
  246. EVP_DigestSignFinal(&ctx, out, &len);
  247. out += len;
  248. remaining -= len;
  249. /* Next A value */
  250. EVP_DigestSignFinal(&ctx_tmp, A, &A_len);
  251. } else {
  252. EVP_DigestSignFinal(&ctx, A, &A_len);
  253. memcpy(out, A, remaining);
  254. remaining -= remaining;
  255. }
  256. }
  257. EVP_PKEY_free(mac_key);
  258. EVP_MD_CTX_cleanup(&ctx);
  259. EVP_MD_CTX_cleanup(&ctx_tmp);
  260. EVP_MD_CTX_cleanup(&ctx_init);
  261. OPENSSL_cleanse(A, sizeof(A));
  262. return 0;
  263. }
  264. /*
  265. * Generate the keys for the super encryption layer, based on the slitheen ID
  266. */
  267. int generate_super_keys(uint8_t *secret){
  268. super = calloc(1, sizeof(super_data));
  269. //need 2 encryption keys, 2 ivs, and a mac
  270. //EVP_CIPHER_CTX *hdr_ctx;
  271. //EVP_CIPHER_CTX *bdy_ctx;
  272. EVP_MD_CTX *mac_ctx;
  273. const EVP_MD *md = EVP_sha256();
  274. /* Generate Keys */
  275. uint8_t *hdr_key, *hdr_iv;
  276. uint8_t *bdy_key, *bdy_iv;
  277. uint8_t *mac_secret;
  278. EVP_PKEY *mac_key;
  279. int32_t mac_len, key_len, iv_len;
  280. key_len = EVP_CIPHER_key_length(EVP_aes_256_cbc());
  281. iv_len = EVP_CIPHER_iv_length(EVP_aes_256_cbc());
  282. mac_len = EVP_MD_size(md);
  283. int32_t total_len = 2*key_len + 2*iv_len + mac_len;
  284. uint8_t *key_block = calloc(1, total_len);
  285. PRF(secret, SLITHEEN_SUPER_SECRET_SIZE,
  286. (uint8_t *) SLITHEEN_SUPER_CONST, SLITHEEN_SUPER_CONST_SIZE,
  287. NULL, 0,
  288. NULL, 0,
  289. NULL, 0,
  290. key_block, total_len);
  291. //#ifdef DEBUG
  292. int i;
  293. printf("secret: \n");
  294. for(i=0; i< SLITHEEN_SUPER_SECRET_SIZE; i++){
  295. printf("%02x ", secret[i]);
  296. }
  297. printf("\n");
  298. printf("keyblock: \n");
  299. for(i=0; i< total_len; i++){
  300. printf("%02x ", key_block[i]);
  301. }
  302. printf("\n");
  303. //#endif
  304. hdr_key = key_block;
  305. bdy_key = key_block + key_len;
  306. hdr_iv = key_block + 2*key_len;
  307. bdy_iv = key_block + 2*key_len + iv_len;
  308. mac_secret = key_block + 2*key_len + 2*iv_len;
  309. /* Initialize Cipher Contexts */
  310. //hdr_ctx = EVP_CIPHER_CTX_new();
  311. //bdy_ctx = EVP_CIPHER_CTX_new();
  312. //EVP_CipherInit_ex(hdr_ctx, EVP_aes_128_ecb(), NULL, hdr_key, NULL, 0);
  313. //EVP_CipherInit_ex(bdy_ctx, EVP_aes_256_cbc(), NULL, bdy_key, bdy_iv, 0);
  314. /* Initialize MAC Context */
  315. mac_ctx = EVP_MD_CTX_create();
  316. EVP_DigestInit_ex(mac_ctx, md, NULL);
  317. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, mac_secret, mac_len);
  318. EVP_DigestSignInit(mac_ctx, NULL, md, NULL, mac_key);
  319. //super->header_ctx = hdr_ctx;
  320. //super->body_ctx = bdy_ctx;
  321. super->header_key = malloc(key_len);
  322. super->body_key = malloc(key_len);
  323. memcpy(super->header_key, hdr_key, key_len);
  324. memcpy(super->body_key, bdy_key, key_len);
  325. super->body_mac_ctx = mac_ctx;
  326. //Free everything
  327. free(key_block);
  328. EVP_PKEY_free(mac_key);
  329. return 0;
  330. }
  331. struct socks_method_req {
  332. uint8_t version;
  333. uint8_t num_methods;
  334. };
  335. struct socks_req {
  336. uint8_t version;
  337. uint8_t cmd;
  338. uint8_t rsvd;
  339. uint8_t addr_type;
  340. };
  341. //continuously read from the socket and look for a CONNECT message
  342. int proxy_data(int sockfd, uint16_t stream_id, int32_t ous_out){
  343. uint8_t *buffer = calloc(1, BUFSIZ);
  344. uint8_t *response = calloc(1, BUFSIZ);
  345. printf("ous out pipe fd: %d\n", ous_out);
  346. fflush(stdout);
  347. int bytes_read = recv(sockfd, buffer, BUFSIZ-1, 0);
  348. if (bytes_read < 0){
  349. printf("Error reading from socket (fd = %d)\n", sockfd);
  350. fflush(stdout);
  351. goto err;
  352. }
  353. printf("Received %d bytes (id %d):\n", bytes_read, stream_id);
  354. int i;
  355. for(i=0; i< bytes_read; i++){
  356. printf("%02x ", buffer[i]);
  357. }
  358. printf("\n");
  359. fflush(stdout);
  360. //Respond to methods negotiation
  361. struct socks_method_req *clnt_meth = (struct socks_method_req *) buffer;
  362. uint8_t *p = buffer + 2;
  363. if(clnt_meth->version != 0x05){
  364. printf("Client supplied invalid version: %02x\n", clnt_meth->version);
  365. fflush(stdout);
  366. }
  367. int responded = 0;
  368. int bytes_sent;
  369. for(i=0; i< clnt_meth->num_methods; i++){
  370. if(p[0] == 0x00){//send response with METH= 0x00
  371. response[0] = 0x05;
  372. response[1] = 0x00;
  373. send(sockfd, response, 2, 0);
  374. responded = 1;
  375. }
  376. p++;
  377. }
  378. if(!responded){//respond with METH= 0xFF
  379. response[0] = 0x05;
  380. response[1] = 0xFF;
  381. send(sockfd, response, 2, 0);
  382. goto err;
  383. }
  384. //Now wait for a connect request
  385. bytes_read = recv(sockfd, buffer, BUFSIZ-1, 0);
  386. if (bytes_read < 0){
  387. printf("Error reading from socket\n");
  388. fflush(stdout);
  389. goto err;
  390. }
  391. printf("Received %d bytes (id %d):\n", bytes_read, stream_id);
  392. for(i=0; i< bytes_read; i++){
  393. printf("%02x ", buffer[i]);
  394. }
  395. printf("\n");
  396. fflush(stdout);
  397. //Now respond
  398. response[0] = 0x05;
  399. response[1] = 0x00;
  400. response[2] = 0x00;
  401. response[3] = 0x01;
  402. *((uint32_t *) (response + 4)) = 0;
  403. *((uint16_t *) (response + 8)) = 0;
  404. send(sockfd, response, 10, 0);
  405. //wait for first upstream bytes
  406. bytes_read += recv(sockfd, buffer+bytes_read, BUFSIZ-bytes_read-3, 0);
  407. if (bytes_read < 0){
  408. printf("Error reading from socket\n");
  409. fflush(stdout);
  410. goto err;
  411. }
  412. printf("Received %d bytes (id %d):\n", bytes_read, stream_id);
  413. for(i=0; i< bytes_read; i++){
  414. printf("%02x ", buffer[i]);
  415. }
  416. printf("\n");
  417. fflush(stdout);
  418. //pre-pend stream_id and length
  419. memmove(buffer+sizeof(struct slitheen_up_hdr), buffer, bytes_read+1);
  420. struct slitheen_up_hdr *up_hdr = (struct slitheen_up_hdr *) buffer;
  421. up_hdr->stream_id = stream_id;
  422. up_hdr->len = htons(bytes_read);
  423. bytes_read+= sizeof(struct slitheen_up_hdr);
  424. //encode bytes for safe transport (b64)
  425. const char *encoded_bytes;
  426. BUF_MEM *buffer_ptr;
  427. BIO *bio, *b64;
  428. b64 = BIO_new(BIO_f_base64());
  429. bio = BIO_new(BIO_s_mem());
  430. bio = BIO_push(b64, bio);
  431. BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
  432. BIO_write(bio, buffer, bytes_read);
  433. BIO_flush(bio);
  434. BIO_get_mem_ptr(bio, &buffer_ptr);
  435. BIO_set_close(bio, BIO_NOCLOSE);
  436. BIO_free_all(bio);
  437. encoded_bytes = (*buffer_ptr).data;
  438. #ifdef NEW
  439. struct sockaddr_in ous_addr;
  440. ous_addr.sin_family = AF_INET;
  441. inet_pton(AF_INET, "127.0.0.1", &(ous_addr.sin_addr));
  442. ous_addr.sin_port = htons(8888);
  443. int32_t ous_in = socket(AF_INET, SOCK_STREAM, 0);
  444. if(ous_in < 0){
  445. printf("Failed to make ous_in socket\n");
  446. return 1;
  447. }
  448. int32_t error = connect(ous_in, (struct sockaddr *) &ous_addr, sizeof (struct sockaddr));
  449. if(error < 0){
  450. printf("Error connecting\n");
  451. return 1;
  452. }
  453. #endif
  454. //send connect request to OUS
  455. #ifdef OLD
  456. int ous_in = open("OUS_in", O_CREAT | O_WRONLY, 0666);
  457. if(ous_in < 0){
  458. printf("Error opening file OUS_in\n");
  459. fflush(stdout);
  460. goto err;
  461. }
  462. lseek(ous_in, 0, SEEK_END);
  463. #endif
  464. #ifdef NEW
  465. uint8_t *message = calloc(1, BUFSIZ);
  466. sprintf(message, "POST / HTTP/1.1\r\nContent-Length: %zd\r\n\r\n%s ", strlen(encoded_bytes)+1, encoded_bytes);
  467. bytes_sent = send(ous_in, message, strlen(message), 0);
  468. printf("Wrote %d bytes to OUS_in: %s\n", bytes_sent, message);
  469. #endif
  470. #ifdef OLD
  471. bytes_sent = write(ous_in, encoded_bytes, strlen(encoded_bytes));
  472. bytes_sent += write(ous_in, " ", 1);
  473. #endif
  474. if(bytes_sent < 0){
  475. printf("Error writing to websocket\n");
  476. fflush(stdout);
  477. goto err;
  478. } else {
  479. close(ous_in);
  480. }
  481. p = buffer+sizeof(struct slitheen_up_hdr);
  482. for(i=0; i< bytes_read; i++){
  483. printf("%02x ", p[i]);
  484. }
  485. printf("\n");
  486. fflush(stdout);
  487. struct socks_req *clnt_req = (struct socks_req *) p;
  488. p += 4;
  489. //see if it's a connect request
  490. if(clnt_req->cmd != 0x01){
  491. printf("Error: issued a non-connect command\n");
  492. fflush(stdout);
  493. goto err;
  494. }
  495. printf("Received a connect request from stream id %d\n", stream_id);
  496. fflush(stdout);
  497. //now select on pipe (for downstream data) and the socket (for upstream data)
  498. for(;;){
  499. fd_set readfds;
  500. fd_set writefds;
  501. int32_t nfds = (sockfd > ous_out) ? sockfd +1 : ous_out + 1;
  502. //if(sockfd > ous_out){
  503. // nfds = (sockfd > ous_in) ? sockfd +1 : ous_in + 1;
  504. //} else {
  505. // nfds = (ous_out > ous_in) ? ous_out +1 : ous_in + 1;
  506. //}
  507. FD_ZERO(&readfds);
  508. FD_ZERO(&writefds);
  509. FD_SET(sockfd, &readfds);
  510. FD_SET(ous_out, &readfds);
  511. FD_SET(sockfd, &writefds);
  512. //FD_SET(ous_in, &writefds);
  513. if(select(nfds, &readfds, &writefds, NULL, NULL) <0){
  514. printf("Select error\n");
  515. fflush(stdout);
  516. continue;
  517. }
  518. if(FD_ISSET(sockfd, &readfds)){// && FD_ISSET(ous_in, &writefds)){
  519. bytes_read = recv(sockfd, buffer, BUFSIZ-1, 0);
  520. if (bytes_read < 0){
  521. printf("Error reading from socket (in for loop)\n");
  522. fflush(stdout);
  523. goto err;
  524. }
  525. if(bytes_read == 0){
  526. //socket is closed
  527. printf("Closing connection for stream %d sockfd.\n", stream_id);
  528. fflush(stdout);
  529. //Send close message to slitheen proxy
  530. up_hdr = (struct slitheen_up_hdr *) buffer;
  531. up_hdr->stream_id = stream_id;
  532. up_hdr->len = 0;
  533. bio = BIO_new(BIO_s_mem());
  534. b64 = BIO_new(BIO_f_base64());
  535. bio = BIO_push(b64, bio);
  536. BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
  537. BIO_write(bio, buffer, 20);
  538. BIO_flush(bio);
  539. BIO_get_mem_ptr(bio, &buffer_ptr);
  540. BIO_set_close(bio, BIO_NOCLOSE);
  541. BIO_free_all(bio);
  542. encoded_bytes = (*buffer_ptr).data;
  543. ous_in = socket(AF_INET, SOCK_STREAM, 0);
  544. if(ous_in < 0){
  545. printf("Failed to make ous_in socket\n");
  546. fflush(stdout);
  547. goto err;
  548. }
  549. error = connect(ous_in, (struct sockaddr *) &ous_addr, sizeof (struct sockaddr));
  550. if(error < 0){
  551. printf("Error connecting\n");
  552. fflush(stdout);
  553. goto err;
  554. }
  555. sprintf(message, "POST / HTTP/1.1\r\nContent-Length: %zd\r\n\r\n%s ", strlen(encoded_bytes)+1, encoded_bytes);
  556. bytes_sent = send(ous_in, message, strlen(message), 0);
  557. close(ous_in);
  558. goto err;
  559. }
  560. if(bytes_read > 0){
  561. printf("Received %d data bytes from sockfd (id %d):\n", bytes_read, stream_id);
  562. for(i=0; i< bytes_read; i++){
  563. printf("%02x ", buffer[i]);
  564. }
  565. printf("\n");
  566. printf("%s\n", buffer);
  567. fflush(stdout);
  568. memmove(buffer+sizeof(struct slitheen_up_hdr), buffer, bytes_read);
  569. up_hdr = (struct slitheen_up_hdr *) buffer;
  570. up_hdr->stream_id = stream_id;
  571. up_hdr->len = htons(bytes_read);
  572. bytes_read+= sizeof(struct slitheen_up_hdr);
  573. bio = BIO_new(BIO_s_mem());
  574. b64 = BIO_new(BIO_f_base64());
  575. bio = BIO_push(b64, bio);
  576. printf("HERE\n");
  577. fflush(stdout);
  578. BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
  579. BIO_write(bio, buffer, bytes_read);
  580. BIO_flush(bio);
  581. BIO_get_mem_ptr(bio, &buffer_ptr);
  582. BIO_set_close(bio, BIO_NOCLOSE);
  583. BIO_free_all(bio);
  584. encoded_bytes = (*buffer_ptr).data;
  585. #ifdef OLD
  586. int ous_in = open("OUS_in", O_CREAT | O_WRONLY, 0666);
  587. if(ous_in < 0){
  588. printf("Error opening file OUS_in\n");
  589. fflush(stdout);
  590. goto err;
  591. }
  592. lseek(ous_in, 0, SEEK_END);
  593. #endif
  594. #ifdef NEW
  595. ous_in = socket(AF_INET, SOCK_STREAM, 0);
  596. if(ous_in < 0){
  597. printf("Failed to make ous_in socket\n");
  598. return 1;
  599. }
  600. error = connect(ous_in, (struct sockaddr *) &ous_addr, sizeof (struct sockaddr));
  601. if(error < 0){
  602. printf("Error connecting\n");
  603. return 1;
  604. }
  605. sprintf(message, "POST / HTTP/1.1\r\nContent-Length: %zd\r\n\r\n%s ", strlen(encoded_bytes)+1, encoded_bytes);
  606. bytes_sent = send(ous_in, message, strlen(message), 0);
  607. printf("Sent to OUS (%d bytes):%s\n",bytes_sent, message);
  608. close(ous_in);
  609. #endif
  610. #ifdef OLD
  611. bytes_sent = write(ous_in, encoded_bytes, strlen(encoded_bytes));
  612. bytes_sent += write(ous_in, " ", 1);
  613. printf("Sent to OUS (%d bytes):%s\n",bytes_sent, encoded_bytes);
  614. close(ous_in);
  615. #endif
  616. }
  617. } else if(FD_ISSET(ous_out, &readfds) && FD_ISSET(sockfd, &writefds)){
  618. bytes_read = read(ous_out, buffer, BUFSIZ-1);
  619. if (bytes_read <= 0){
  620. printf("Error reading from ous_out (in for loop)\n");
  621. fflush(stdout);
  622. goto err;
  623. }
  624. if(bytes_read > 0){
  625. printf("Stream id %d received %d bytes from ous_out:\n", stream_id, bytes_read);
  626. for(i=0; i< bytes_read; i++){
  627. printf("%02x ", buffer[i]);
  628. }
  629. printf("\n");
  630. printf("%s\n", buffer);
  631. fflush(stdout);
  632. bytes_sent = send(sockfd, buffer, bytes_read, 0);
  633. if(bytes_sent <= 0){
  634. printf("Error sending bytes to browser for stream id %d\n", stream_id);
  635. }
  636. printf("Sent to browser (%d bytes from stream id %d):\n", bytes_sent, stream_id);
  637. for(i=0; i< bytes_sent; i++){
  638. printf("%02x ", buffer[i]);
  639. }
  640. printf("\n");
  641. fflush(stdout);
  642. }
  643. }
  644. }
  645. err:
  646. //should also remove stream from table
  647. close(sockfd);
  648. free(buffer);
  649. free(response);
  650. exit(0);
  651. }
  652. /* Read blocks of covert data from OUS_out. Determine the stream id and the length of
  653. * the block and then write the data to the correct thread to be passed to the browser
  654. */
  655. void *demultiplex_data(){
  656. int32_t buffer_len = BUFSIZ;
  657. uint8_t *buffer = calloc(1, buffer_len);
  658. uint8_t *p;
  659. printf("Opening OUS_out\n");
  660. int32_t ous_fd = open("OUS_out", O_RDONLY);
  661. printf("Opened.\n");
  662. uint8_t *partial_block;
  663. uint32_t partial_block_len = 0;
  664. uint32_t resource_remaining = 0;
  665. for(;;){
  666. int32_t bytes_read = read(ous_fd, buffer, buffer_len-partial_block_len);
  667. if(bytes_read > 0){
  668. int32_t bytes_remaining = bytes_read;
  669. printf("Read in %d bytes from OUS_out\n", bytes_remaining);
  670. p = buffer;
  671. //the first value for a new resource will be the resource length,
  672. //followed by a newline
  673. if(resource_remaining > 0){
  674. printf("Completing previously started resource. Reading in %d out of %d bytes remaining in resource\n", bytes_remaining, resource_remaining);
  675. resource_remaining -= bytes_remaining;
  676. if((bytes_remaining > 0) && (partial_block_len > 0)){
  677. //process first part of slitheen info
  678. printf("Completing previously read Slitheen block\n");
  679. memmove(buffer+partial_block_len, buffer, bytes_read);
  680. memcpy(buffer, partial_block, partial_block_len);
  681. bytes_remaining += partial_block_len;
  682. free(partial_block);
  683. partial_block_len = 0;
  684. }
  685. } else {
  686. uint8_t *end_ptr;
  687. resource_remaining = strtol((const char *) p, (char **) &end_ptr, 10);
  688. if(resource_remaining == 0){
  689. printf("UH OH, resource_remaining is zero or there was an error O.o\n");
  690. } else {
  691. bytes_remaining -= (end_ptr - p) + 1;
  692. p += (end_ptr - p) + 1;
  693. printf("Reading in %d out of %d bytes of new resource\n",
  694. bytes_remaining, resource_remaining);
  695. if(resource_remaining < bytes_remaining){
  696. resource_remaining = 0;
  697. printf("UH OH, shouldn't be here\n");
  698. } else {
  699. resource_remaining -= bytes_remaining;
  700. }
  701. }
  702. }
  703. while(bytes_remaining > 0){
  704. if(bytes_remaining + resource_remaining < SLITHEEN_HEADER_LEN){
  705. printf("Resource is padded out with garbage\n");
  706. bytes_remaining = 0;
  707. break;
  708. }
  709. if((bytes_remaining < SLITHEEN_HEADER_LEN)){
  710. printf("Partial header: ");
  711. int i;
  712. for(i = 0; i< bytes_remaining; i++){
  713. printf("%02x ", p[i]);
  714. }
  715. printf("\n");
  716. partial_block = calloc(1, bytes_remaining);
  717. memcpy(partial_block, p, bytes_remaining);
  718. partial_block_len = bytes_remaining;
  719. bytes_remaining = 0;
  720. break;
  721. }
  722. super_decrypt(p);
  723. struct slitheen_hdr *sl_hdr = (struct slitheen_hdr *) p;
  724. //first see if sl_hdr corresponds to a valid stream. If not, ignore rest of read bytes
  725. //#ifdef DEBUG
  726. printf("Slitheen header:\n");
  727. int i;
  728. for(i = 0; i< SLITHEEN_HEADER_LEN; i++){
  729. printf("%02x ", p[i]);
  730. }
  731. printf("\n");
  732. //#endif
  733. if(ntohs(sl_hdr->len) > bytes_remaining){
  734. printf("Received partial block\n");
  735. partial_block = calloc(1, ntohs(sl_hdr->len));
  736. memcpy(partial_block, p, bytes_remaining);
  737. partial_block_len = bytes_remaining;
  738. bytes_remaining = 0;
  739. break;
  740. }
  741. p += SLITHEEN_HEADER_LEN;
  742. bytes_remaining -= SLITHEEN_HEADER_LEN;
  743. if((!sl_hdr->len) && (sl_hdr->garbage)){
  744. //#ifdef DEBUG
  745. printf("%d Garbage bytes\n", ntohs(sl_hdr->garbage));
  746. //#endif
  747. p += ntohs(sl_hdr->garbage);
  748. bytes_remaining -= ntohs(sl_hdr->garbage);
  749. continue;
  750. }
  751. int32_t pipe_fd =-1;
  752. if(connections->first == NULL){
  753. printf("There are no connections\n");
  754. } else {
  755. connection *last = connections->first;
  756. if (last->stream_id == sl_hdr->stream_id){
  757. printf("Found stream id %d!\n", sl_hdr->stream_id);
  758. pipe_fd = last->pipe_fd;
  759. printf("Pipe fd: %d\n", pipe_fd);
  760. }
  761. while(last->next != NULL){
  762. last = last->next;
  763. if (last->stream_id == sl_hdr->stream_id){
  764. printf("Found stream id %d!\n", sl_hdr->stream_id);
  765. pipe_fd = last->pipe_fd;
  766. printf("Pipe fd: %d\n", pipe_fd);
  767. }
  768. }
  769. }
  770. if(pipe_fd == -1){
  771. printf("No stream id exists. Possibly invalid header\n");
  772. break;
  773. }
  774. printf("Received information for stream id: %d of length: %u\n", sl_hdr->stream_id, ntohs(sl_hdr->len));
  775. //figure out how much to skip
  776. int32_t padding = 0;
  777. if(ntohs(sl_hdr->len) %16){
  778. padding = 16 - ntohs(sl_hdr->len)%16;
  779. }
  780. p += 16; //IV
  781. int32_t bytes_sent = write(pipe_fd, p, ntohs(sl_hdr->len) - padding);
  782. if(bytes_sent <= 0){
  783. printf("Error reading to pipe for stream id %d\n", sl_hdr->stream_id);
  784. }
  785. p += ntohs(sl_hdr->len); //encrypted data
  786. p += 16; //mac
  787. p += padding;
  788. p += ntohs(sl_hdr->garbage);
  789. printf("Skipped %d garbage bytes\n", ntohs(sl_hdr->garbage));
  790. fflush(stdout);
  791. bytes_remaining -=
  792. ntohs(sl_hdr->len) + 16 + padding + 16 + ntohs(sl_hdr->garbage);
  793. printf("Bytes remaining: %d, padding: %d\n", bytes_remaining, padding);
  794. }
  795. } else {
  796. printf("Error: read %d bytes from OUS_out\n", bytes_read);
  797. printf("Opening OUS_out\n");
  798. close(ous_fd);
  799. ous_fd = open("OUS_out", O_RDONLY);
  800. printf("Opened.\n");
  801. }
  802. }
  803. close(ous_fd);
  804. }
  805. int super_decrypt(uint8_t *data){
  806. EVP_CIPHER_CTX *bdy_ctx;
  807. uint8_t *p = data;
  808. int32_t out_len, len;
  809. uint8_t output[EVP_MAX_MD_SIZE];
  810. size_t mac_len;
  811. int i;
  812. /*decrypt header
  813. printf("Encrypted header:\n");
  814. for(i=0; i< SLITHEEN_HEADER_LEN; i++){
  815. printf("%02x ", p[i]);
  816. }
  817. printf("\n");
  818. if(!EVP_CipherUpdate(super->header_ctx, p, &out_len, p, SLITHEEN_HEADER_LEN)){
  819. printf("Decryption failed!");
  820. return 0;
  821. }
  822. */
  823. printf("Decrypted header (%d bytes):\n", SLITHEEN_HEADER_LEN);
  824. for(i=0; i< SLITHEEN_HEADER_LEN; i++){
  825. printf("%02x ", p[i]);
  826. }
  827. printf("\n");
  828. fflush(stdout);
  829. struct slitheen_hdr *sl_hdr = (struct slitheen_hdr *) p;
  830. len = htons(sl_hdr->len);
  831. if(!sl_hdr->len){//there are no data to be decrypted
  832. return 1;
  833. }
  834. p += SLITHEEN_HEADER_LEN;
  835. //compute mac
  836. EVP_DigestSignUpdate(super->body_mac_ctx, p, len);
  837. EVP_DigestSignFinal(super->body_mac_ctx, output, &mac_len);
  838. #ifdef DEBUG
  839. printf("Received mac:\n");
  840. for(i=0; i< 16; i++){
  841. printf("%02x ", p[len+i]);
  842. }
  843. printf("\n");
  844. fflush(stdout);
  845. if(memcmp(p+len, output, 16)){
  846. printf("MAC verification failed\n");
  847. return 0;
  848. }
  849. #endif
  850. //decrypt body
  851. bdy_ctx = EVP_CIPHER_CTX_new();
  852. EVP_CipherInit_ex(bdy_ctx, EVP_aes_256_cbc(), NULL, super->body_key, p, 0);
  853. p+=16;//skip IV
  854. printf("Encrypted data (%d bytes):\n", len);
  855. for(i=0; i< len; i++){
  856. printf("%02x ", p[i]);
  857. }
  858. printf("\n");
  859. if(!EVP_CipherUpdate(bdy_ctx, p, &out_len, p, len+16)){
  860. printf("Decryption failed!");
  861. return 0;
  862. }
  863. EVP_CIPHER_CTX_free(bdy_ctx);
  864. printf("Decrypted data (%d bytes):\n", out_len);
  865. for(i=0; i< out_len; i++){
  866. printf("%02x ", p[i]);
  867. }
  868. printf("\n");
  869. fflush(stdout);
  870. p += out_len;
  871. return 1;
  872. }