-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathredshell.py
1113 lines (830 loc) · 41.2 KB
/
redshell.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
# Copyright Verizon.
# Licensed under the terms of the Apache 2.0 license. See LICENSE file in project root for terms.
#!/bin/env python3
import argparse
import csv
import fileinput
import functools
import getpass
import os
import re
import shlex
import shutil
import socket
import struct
import sys
import textwrap
from datetime import datetime, timezone
import pexpect
from cmd2 import Cmd, Settable, ansi, with_argparser
from rich import box
from rich.console import Console
from rich.prompt import Prompt
from rich.table import Table
# define colors
green = functools.partial(ansi.style, fg=ansi.RgbFg(65, 255, 0))
red = functools.partial(ansi.style, fg=ansi.RgbFg(239, 41, 41))
def xstr(s):
"""return empty string if input is none/false"""
return '' if not s else s
class Logger():
logs = []
logfile_csv = None
csv_writer = None
def __init__(self, command, ip=None, dns_name=None, netbios_name=None, user_name=None, pid=None, ttps=None):
self.timestamp = datetime.now(timezone.utc)
self.command = command
self.ip = ip
self.dns_name = dns_name
self.netbios_name = netbios_name
self.user_name = user_name
self.pid = pid
self.ttps = ttps
self.write_log_entry()
Logger.logs.append(self)
@classmethod
def open_logfile(cls, basefilename):
logfile_csv = f"{basefilename}.csv"
print(f"Logging to: {logfile_csv}\n")
cls.logfile_csv = open(logfile_csv, 'w', newline='')
fieldnames = ['Datetime', 'IP Address', 'DNS Name', 'NetBIOS Name', 'User', 'PID', 'Activity', 'TTPs']
cls.csv_writer = csv.DictWriter(cls.logfile_csv, fieldnames=fieldnames)
cls.csv_writer.writeheader()
cls.logfile_csv.flush()
def asdict(self):
return {'Datetime': self.timestamp.strftime("%Y/%m/%d %H:%M:%S %z"),
'IP Address': xstr(self.ip),
'DNS Name': xstr(self.dns_name),
'NetBIOS Name': xstr(self.netbios_name),
'User': xstr(self.user_name),
'PID': xstr(self.pid),
'Activity': self.command,
'TTPs': self.ttps}
def write_log_entry(self):
Logger.csv_writer.writerow(self.asdict())
Logger.logfile_csv.flush()
@classmethod
def close_logfile(cls):
cls.logfile_csv.close()
class CSProxyPivots():
instances = {}
by_hash = {}
count = 0
def __init__(self, socks_type, socks_port, bid, beacon_pid, beacon_user, beacon_computer, beacon_ip, beacon_alive, beacon_last, socks5_auth=None):
self.socks_type = socks_type
self.socks_port = socks_port
self.socks5_auth = socks5_auth
self.socks5_user = None
self.socks5_pass = None
self.bid = bid
self.beacon_pid = beacon_pid
self.beacon_user = beacon_user
self.beacon_computer = beacon_computer
self.beacon_ip = beacon_ip
self.beacon_alive = beacon_alive
self.beacon_last = beacon_last
self.beacon_hash = hash(f"{bid}-{beacon_pid}-{socks_port}")
CSProxyPivots.count += 1
self.id = CSProxyPivots.count
CSProxyPivots.instances[self.id] = self
CSProxyPivots.by_hash[self.beacon_hash] = self
@classmethod
def get_pivots(cls):
data = []
data.append(['ID', 'Alive', 'Socks Type', 'Socks Port', 'Socks5 Auth', 'Beacon PID', 'Beacon User', 'Beacon Computer', 'Beacon Last'])
for pivot in CSProxyPivots.instances.values():
data.append([str(pivot.id), str(pivot.beacon_alive), pivot.socks_type, pivot.socks_port, pivot.socks5_auth, pivot.beacon_pid, pivot.beacon_user, pivot.beacon_computer, pivot.beacon_last])
return data
class RedShell(Cmd):
prompt = 'redshell > '
def __init__(self):
super().__init__()
# remove built-in commands
try:
del Cmd.do_alias
del Cmd.do_edit
del Cmd.do_macro
del Cmd.do_run_pyscript
del Cmd.do_run_script
del Cmd.do_shortcuts
del Cmd.do_py
except AttributeError:
pass
# remove built-in settings
for key in ['allow_style', 'always_show_hint', 'editor', 'echo', 'feedback_to_output', 'quiet', 'timing', 'max_completion_items']:
try:
self.remove_settable(key)
except:
pass
self.display_intro()
# check/create redshell user dir
home_dir = os.path.expanduser("~")
self.redshell_user_directory = f"{home_dir}/.redshell/"
if not os.path.exists(self.redshell_user_directory):
os.makedirs(self.redshell_user_directory)
# set cobalt strike directory, if exists
if os.path.exists('/opt/cobaltstrike'):
self.cs_directory = '/opt/cobaltstrike'
else:
self.cs_directory = ''
# set config variables
self.redshell_directory = os.getcwd()
self.proxychains_config = f"{self.redshell_directory}/proxychains_redshell.conf"
self.cs_host = ''
self.cs_port = ''
self.cs_user = ''
self.cs_pass = ''
self.cs_process = None
self.cs_beacon_pid = ''
self.cs_beacon_id = ''
self.cs_beacon_user = ''
self.cs_beacon_computer = ''
self.cs_beacon_ip = ''
self.context_ip = ''
self.context_dns_name = ''
self.context_netbios_name = ''
self.context_user_name = ''
self.context_pid = ''
self.socks_host = ''
self.socks_port = ''
self.socks_type = ''
self.socks5_auth = ''
self.socks5_user = ''
self.socks5_pass = ''
self.socks_port_connected = False
self.password = ''
self.check_socks = True
# initialze user settable options
self.add_settable(Settable('redshell_directory', str, 'redshell install directory', self, completer=Cmd.path_complete, onchange_cb=self._onchange_redshell_directory))
self.add_settable(Settable('proxychains_config', str, 'proxychains config file', self, completer=Cmd.path_complete))
self.add_settable(Settable('cs_directory', str, 'Cobalt Strike install directory', self, completer=Cmd.path_complete))
self.add_settable(Settable('cs_host', str, 'Cobalt Strike team server host', self))
self.add_settable(Settable('cs_port', str, 'Cobalt Strike team server port', self))
self.add_settable(Settable('cs_user', str, 'Cobalt Strike user', self, onchange_cb=self._onchange_cs_user))
self.add_settable(Settable('password', str, 'Password for beacon_exec commands. Invoke with $password.', self))
self.add_settable(Settable('check_socks', bool, 'Validate connections/authentication to SOCKS servers', self))
# start logger
now = datetime.now()
timestamp = now.strftime("%Y_%m_%d_%H_%M_%S")
basefilename = f"{self.redshell_user_directory}redshell_{timestamp}"
Logger.open_logfile(basefilename)
def _set_prompt(self):
if self.socks_port_connected == True:
color = green
else:
color = red
# set prompt with context vars
if self.context_user_name and self.context_netbios_name:
self.prompt = f"redshell ({color(f'{self.context_user_name}@{self.context_netbios_name}')}) > "
elif self.context_user_name and self.context_dns_name:
self.prompt = f"redshell ({color(f'{self.context_user_name}@{self.context_dns_name}')}) > "
elif self.context_dns_name:
self.prompt = f"redshell ({color(f'@{self.context_dns_name}')}) > "
elif self.context_ip:
self.prompt = f"redshell ({color(f'@{self.context_ip}')}) > "
def postcmd(self, stop, line):
self._set_prompt()
return stop
def display_intro(self):
intro = """
____ _______ __ ____
/ __ \___ ____/ / ___// /_ ___ / / /
/ /_/ / _ \/ __ /\__ \/ __ \/ _ \/ / /
/ _, _/ __/ /_/ /___/ / / / / __/ / /
/_/ |_|\___/\__,_//____/_/ /_/\___/_/_/
"""
self.poutput(green(intro))
def _onchange_redshell_directory(self, param_name, old, new):
self.proxychains_config = f"{self.redshell_directory}/proxychains_redshell.conf"
# append '_redshell' to CS username
def _onchange_cs_user(self, param_name, old, new):
self.cs_user += '_redshell'
def print_table(self, data, header=False):
"""print all tables in console output"""
if header:
table = Table(show_lines=True, show_header=header)
else:
table = Table(show_lines=True, show_header=header, box=box.SQUARE)
column_count = range(0, len(data[0]))
for i in column_count:
if header:
table.add_column(data[0][i])
else:
table.add_column()
for row in data:
if header and data.index(row) == 0:
continue
table.add_row(*row)
console = Console()
console.print(table)
def update_proxychains_conf(self, socks_type, ip, socks_port, socks5_auth=None, socks5_user=None, socks5_pass=None):
for line in fileinput.input(self.proxychains_config, inplace=True):
if line.startswith('socks'):
if socks_type == 'socks5' and socks5_auth:
print(f"{socks_type} {ip} {socks_port} {socks5_user} {socks5_pass}", end="\n")
else:
print(f"{socks_type} {ip} {socks_port}", end="\n")
else:
print(line, end = '')
def clear_context(self, clear_socks=False, clear_cs=False):
# clear existing connection
self.cs_beacon_id = ''
self.cs_beacon_pid = ''
self.cs_beacon_user = ''
self.cs_beacon_computer = ''
self.cs_beacon_ip = ''
self.context_ip = ''
self.context_dns_name = ''
self.context_netbios_name = ''
self.context_user_name = ''
self.context_pid = ''
# clear socks port if user is applying a new one
if clear_socks:
self.socks_host = ''
self.socks_port = ''
self.socks_type = ''
self.socks5_auth = ''
self.socks5_user = ''
self.socks5_pass = ''
self.socks_port_connected = False
# if connected to cs team server, kill connection
if clear_cs:
# close the agscript process
if self.cs_process:
self.cs_process.close()
self.cs_process = None
argparser = argparse.ArgumentParser()
argparser.add_argument('-d', '--dnsname', type=str, help="DNS Name")
argparser.add_argument('-n', '--netbiosname', type=str, help="NetBIOS Name")
argparser.add_argument('-u', '--username', type=str, help="User Name")
argparser.add_argument('-p', '--pid', type=str, help="Process ID")
argparser.add_argument(type=str, dest="ip_address", help="Source IP Address")
@with_argparser(argparser)
def do_context(self, args):
"""Set a custom context (Source IP/DNS/NetBIOS/User/PID) for logging"""
if self.context_ip:
self.poutput("Context changed!")
self.pwarning("WARNING: If moving to a new socks port, be sure to update your socks connection accordingly.")
else:
self.poutput("New context applied!")
# if connected to cs team server, kill connection and socks. else clear context values only
if self.cs_process:
self.clear_context(clear_socks=True, clear_cs=True)
else:
self.clear_context()
self.context_ip = args.ip_address
if args.dnsname:
self.context_dns_name = args.dnsname
if args.netbiosname:
self.context_netbios_name = args.netbiosname
if args.username:
self.context_user_name = args.username
if args.pid:
self.context_pid = args.pid
argparser = argparse.ArgumentParser()
argparser.add_argument(type=str, dest="socks_type", choices=['socks4', 'socks5'])
argparser.add_argument(type=str, dest="ip_address")
argparser.add_argument(type=str, dest="socks_port")
argparser.add_argument('-u', type=str, dest="socks5_user")
argparser.add_argument('-p', type=str, dest="socks5_pass")
@with_argparser(argparser)
def do_socks(self, args):
"""Use a custom socks4/5 server"""
# clear any existing context, socks port, and cobalt strike connections
self.clear_context(clear_socks=True, clear_cs=True)
self.socks_type = args.socks_type
self.socks_host = args.ip_address
self.socks_port = args.socks_port
self.socks_port_connected = True
if args.socks_type == 'socks5':
if (args.socks5_user and not args.socks5_pass) or (args.socks5_pass and not args.socks5_user):
if args.socks_user:
self.perror("ERROR: SOCKS5 user set but missing password!")
else:
self.perror("ERROR: SOCKS5 password set but missing user!")
return
elif args.socks5_user and args.socks5_pass:
self.socks5_auth = 'UserAndPwd'
self.socks5_user = args.socks5_user
self.socks5_pass = args.socks5_pass
else:
self.socks5_auth = ''
self.socks5_user = ''
self.socks5_pass = ''
if self.check_socks:
if self.validate_socks(self.socks_type, self.socks_host, self.socks_port, self.socks5_auth, self.socks5_user, self.socks5_pass):
self.update_proxychains_conf(self.socks_type, self.socks_host, self.socks_port, self.socks5_auth, self.socks5_user, self.socks5_pass)
self.socks_port_connected = True
else:
self.clear_context(clear_socks=True)
return
else:
self.update_proxychains_conf(self.socks_type, self.cs_host, self.socks_port, self.socks5_auth, self.socks5_user, self.socks5_pass)
self.socks_port_connected = True
self.poutput("Socks port updated.")
self.pwarning("WARNING: Be sure to update your context accordingly with the 'context' command.")
def do_cs_connect(self, args):
"""Connect to Cobalt Strike team server"""
self.clear_context(clear_socks=True)
# check config directories before attempting connection
if not os.path.exists(f"{self.redshell_directory}/agscript.sh"):
self.perror("Error: redshell install directory not found! Set the directory with this command: 'set redshell_directory'")
return
if not os.path.exists(f"{self.cs_directory}/agscript"):
self.perror("Error: Cobalt Strike install directory not found! Set the directory with this command: 'set cs_directory'")
return
# check permissions on agscript.sh
if not shutil.which(f"{self.redshell_directory}/agscript.sh"):
self.perror("Error: agscript.sh does not appear to be executable! Fix it with this command: 'chmod +x agscript.sh'")
return
# prompt user for team server password
self.cs_pass = getpass.getpass("Enter Cobalt Strike password: ")
# spawn agscript process
self.cs_process = pexpect.spawn(f"{self.redshell_directory}/agscript.sh {self.cs_directory} {self.cs_host} {self.cs_port} {self.cs_user} {self.cs_pass}")
# check if process is alive
if not self.cs_process.isalive():
self.perror("Error connecting to CS team server! Check config and try again.")
return
# look for the aggressor prompt
try:
self.cs_process.expect('.*aggressor.*> ')
except:
self.perror("Error connecting to CS team server! Check config and try again.")
return
self.poutput("Connecting...")
# upon successful connection, display status
self.do_cs_status('')
def do_cs_disconnect(self, args):
"""Disconnect from CS team server"""
self.clear_context(clear_socks=True, clear_cs=True)
def do_cs_status(self, args):
"""Display CS team server and beacon socks port connection status"""
if self.cs_process and self.cs_process.isalive():
cs_server_status = f"[#41FF00]Connected via {self.cs_user}@{self.cs_host}:{self.cs_port}[/]"
else:
cs_server_status = "[#EF2929]Disconnected[/]"
if self.cs_process and self.cs_process.isalive() and self.socks_port_connected:
socks_port_status = f"[#41FF00]Connected via {self.socks_type} port {self.socks_port} @ beacon PID {self.cs_beacon_pid}[/]"
else:
socks_port_status = "[#EF2929]Disconnected[/]"
data = [
["[i]CS Team Server Status[/]", cs_server_status],
["[i]Socks Port Status[/]", socks_port_status]
]
self.print_table(data)
argparser = argparse.ArgumentParser()
argparser.add_argument('-s', action='store_true', dest='show_secrets', help="Show secrets")
@with_argparser(argparser)
def do_config(self, args):
"""Display current config"""
data = [
["[i]Redshell Install Directory[/]", self.redshell_directory],
["[i]Proxychains Config[/]", self.proxychains_config],
["[i]Log File[/]", Logger.logfile_csv.name],
["[i]CS Install Directory[/]", self.cs_directory],
]
if self.cs_host:
data.append(["[i]CS Team Server[/]", self.cs_host])
data.append(["[i]CS Team Server Port[/]", self.cs_port])
data.append(["[i]CS User[/]", self.cs_user])
if self.socks_port:
data.append(["[i]Socks Connection", f"{self.socks_type}://{self.socks_host}:{self.socks_port}"])
if self.socks5_auth:
data.append(["[i]Socks5 User", self.socks5_user])
data.append(["[i]Socks5 Password", self.socks5_pass if args.show_secrets else '*' * len(self.socks5_pass)])
else:
data.append(["[i]Socks Connection", ''])
context = ''
if self.context_ip:
context += f"[i]IP:[/] {self.context_ip}"
if self.context_dns_name:
context += f" [i]DNS:[/] {self.context_dns_name}"
if self.context_netbios_name:
context += f" [i]NetBIOS:[/] {self.context_netbios_name}"
if self.context_user_name:
context += f" [i]User:[/] {self.context_user_name}"
if self.context_pid:
context += f" [i]PID:[/] {self.context_pid}"
data.append(["[i]Context[/]", context])
if self.password:
data.append(["[i]Password[/]", self.password if args.show_secrets else '*' * len(self.password)])
self.print_table(data)
argparser = argparse.ArgumentParser()
argparser.add_argument(type=str, dest="file_name", completer=Cmd.path_complete)
@with_argparser(argparser)
def do_cs_load_config(self, args):
"""Load Cobalt Strike team server config (host, port, and user) from file"""
self.clear_context(clear_socks=True)
try:
with open(args.file_name, 'r') as cf:
for line in cf.readlines():
cs_host = re.search('cs_host=(.*)', line)
if cs_host:
self.cs_host = cs_host.group(1)
cs_port = re.search('cs_port=(.*)', line)
if cs_port:
self.cs_port = cs_port.group(1)
cs_directory = re.search('cs_directory=(.*)', line)
if cs_directory:
self.cs_directory = cs_directory.group(1).strip(' ')
cs_user = re.search('cs_user=(.*)', line)
if cs_user:
self.cs_user = cs_user.group(1)
self.cs_user += '_redshell'
self.poutput("Config applied:")
self.do_config('')
self.do_cs_connect('')
except FileNotFoundError:
self.perror("Error: config file not found!")
def do_cs_pivots(self, args):
"""Show Cobalt Strike proxy pivots available on the team server"""
# check for active connection to the team server
if not self.cs_process or not self.cs_process.isalive():
self.perror("Error: not connected to CS team server. Connect first and then select a pivot.")
self.clear_context(clear_socks=True)
return
# ask agscript for pivots
self.cs_process.sendline('x pivots()')
self.cs_process.expect('.*aggressor.*> ')
if self.cs_process.after:
# copy instance containers and clear them to reset
pivot_instances = CSProxyPivots.instances.copy()
pivot_instances_by_hash = CSProxyPivots.by_hash.copy()
CSProxyPivots.instances.clear()
CSProxyPivots.by_hash.clear()
CSProxyPivots.count = 0
# parse through results
for result in re.findall('%\([^()]*\)', self.cs_process.after.decode()):
pivot_socks_type = None
pivot_socks_port = None
pivot_socks5_auth = None
pivot_bid = None
pivot_pid = None
pivot_user = None
pivot_computer = None
pivot_alive = None
pivot_last = None
# get socks type
result_socks_type = re.search("type => '(SOCKS[5|4a]).*?'", result)
if result_socks_type:
pivot_socks_type = result_socks_type.group(1).lower()
# get socks5 auth
result_socks_info = re.search("socks_info => '(.*?)'", result)
if result_socks_info:
socks_info = result_socks_info.group(1).lower()
if 'userandpwd' in socks_info and not 'noauth' in socks_info:
pivot_socks5_auth = 'userandpwd'
# get socks port
result_port = re.search("port => '([0-9]+)'", result)
if result_port:
pivot_socks_port = result_port.group(1)
# get beacon ID
result_bid = re.search("bid => '([0-9]+)'", result)
if result_bid:
pivot_bid = result_bid.group(1)
if pivot_bid:
# get full beacon info for beacon ID
self.cs_process.sendline(f"x beacon_info({pivot_bid})")
self.cs_process.expect('.*aggressor.*> ')
if self.cs_process.after:
beacon_info = self.cs_process.after.decode()
# check if beacon is alive or dead
result_alive = re.search("alive => 'true'", beacon_info)
if result_alive:
pivot_alive = True
# get beacon user
result_user = re.search("user => '(.*?)'", beacon_info)
if result_user:
pivot_user = result_user.group(1)
# get beacon computer
result_computer = re.search("computer => '(.*?)'", beacon_info)
if result_computer:
pivot_computer = result_computer.group(1)
# get beacon ip
result_ip = re.search("internal => '(.*?)'", beacon_info)
if result_ip:
pivot_ip = result_ip.group(1)
# get beacon pid
result_pid = re.search("pid => '([0-9]+)'", beacon_info)
if result_pid:
pivot_pid = result_pid.group(1)
# get beacon last
result_last = re.search("lastf => '(.*?)'", beacon_info)
if result_last:
pivot_last = result_last.group(1)
# intialize ProxyPivot instance if we have all the necessary details
if pivot_socks_type and pivot_socks_port and pivot_bid and pivot_pid and pivot_user and pivot_computer and pivot_alive and pivot_last:
# look for existing pivot instance
pivot_hash = hash(f"{pivot_bid}-{pivot_pid}-{pivot_socks_port}")
cs_pivot = pivot_instances_by_hash.get(pivot_hash)
# if we have an existing pivot, just update alive and last values
if cs_pivot:
cs_pivot.beacon_alive = pivot_alive
cs_pivot.beacon_last = pivot_last
CSProxyPivots.count += 1
cs_pivot.id = CSProxyPivots.count
# add existing instance back into class containers
CSProxyPivots.instances[cs_pivot.id] = cs_pivot
CSProxyPivots.by_hash[pivot_hash] = cs_pivot
# none found, make a new instance
else:
CSProxyPivots(pivot_socks_type, pivot_socks_port, pivot_bid, pivot_pid, pivot_user, pivot_computer, pivot_ip, pivot_alive, pivot_last, pivot_socks5_auth)
# display ProxyPivot table
if CSProxyPivots.instances.items():
self.print_table(CSProxyPivots.get_pivots(), header=True)
else:
self.pwarning("No proxy pivots found!")
def do_cs_use_pivot(self, arg_pivot_id):
"""Set RedShell to use Cobalt Strike pivot ID"""
self.clear_context(clear_socks=True)
# check for active connection to the team server
if not self.cs_process or not self.cs_process.isalive():
self.perror("Error: not connected to CS team server. Connect first and then select a pivot.")
return
if not CSProxyPivots.instances:
self.perror("No pivots found! Run 'cs_pivots' to query them on the team server")
return
# convert arg to int
try:
pivot_id = int(arg_pivot_id)
except ValueError:
self.perror('Invalid pivot ID, must be int!')
return
# get pivot instance by specified ID
proxy_pivot = CSProxyPivots.instances.get(pivot_id)
if proxy_pivot:
if proxy_pivot.beacon_alive:
# set config vars from selected ProxyPiot instance
self.cs_beacon_id = proxy_pivot.bid
self.cs_beacon_pid = proxy_pivot.beacon_pid
self.cs_beacon_user = proxy_pivot.beacon_user.replace(' *', '')
self.cs_beacon_computer = proxy_pivot.beacon_computer
self.cs_beacon_ip = proxy_pivot.beacon_ip
self.context_pid = proxy_pivot.beacon_pid
self.context_user_name = proxy_pivot.beacon_user.replace(' *', '')
self.context_netbios_name = proxy_pivot.beacon_computer
self.context_ip = proxy_pivot.beacon_ip
self.socks_host = self.cs_host
self.socks_port = proxy_pivot.socks_port
self.socks_type = proxy_pivot.socks_type
self.socks5_auth = proxy_pivot.socks5_auth
# collect socks5 creds
if self.socks_type == 'socks5' and self.socks5_auth:
if not proxy_pivot.socks5_user and not proxy_pivot.socks5_pass:
self.poutput("SOCKS5 pivot requires authentication.\n")
proxy_pivot.socks5_user = self.read_input("Enter SOCKS5 user: ")
self.socks5_user = proxy_pivot.socks5_user
proxy_pivot.socks5_pass = getpass.getpass("Enter SOCKS5 password: ")
self.socks5_pass = proxy_pivot.socks5_pass
else:
self.socks5_user = proxy_pivot.socks5_user
self.socks5_pass = proxy_pivot.socks5_pass
if self.check_socks:
if self.validate_socks(self.socks_type, self.socks_host, self.socks_port, self.socks5_auth, self.socks5_user, self.socks5_pass, proxy_pivot):
self.update_proxychains_conf(self.socks_type, self.cs_host, self.socks_port, self.socks5_auth, self.socks5_user, self.socks5_pass)
self.socks_port_connected = True
else:
self.clear_context(clear_socks=True)
return
else:
self.update_proxychains_conf(self.socks_type, self.cs_host, self.socks_port, self.socks5_auth, self.socks5_user, self.socks5_pass)
self.socks_port_connected = True
self.do_cs_status('')
return
else:
self.pwarning('Specified pivot ID is not alive!')
return
else:
self.perror('Invalid pivot ID!')
return
def validate_socks(self, socks_type, ip, port, socks5_auth=None, socks5_user=None, socks5_pass=None, cs_proxy_pivot=None):
"""checks connectivity and authentication to SOCKS servers"""
# initialize socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect to the IP and port
try:
s.connect((ip, int(port)))
except ConnectionRefusedError:
self.perror("Error connecting to SOCKS proxy: Connection refused!")
# if it's socks4 then we're all done
if socks_type == 'socks4':
s.close()
return True
# test socks5 with no auth
elif socks_type == 'socks5' and not socks5_auth:
# 0x05 = SOCKS5, 0x01 = client supports one auth type, 0x00 = no auth
handshake = struct.pack('BBB', 0x05, 0x01, 0x00)
s.sendall(handshake)
try:
data = s.recv(2)
version, auth = struct.unpack('BB', data)
except:
self.perror("Error connecting to SOCKS proxy!")
s.close()
return False
if version == 5 and auth == 0:
s.close()
return True
# test socks5 with user/pass auth
elif socks_type == 'socks5' and socks5_auth:
# 0x05 = SOCKS5, 0x01 = client supports one auth type, 0x01 = user/pass auth
handshake = struct.pack('BBB', 0x05, 0x01, 0x02)
s.sendall(handshake)
try:
data = s.recv(2)
version, auth = struct.unpack('BB', data)
except:
self.perror("Error connecting to SOCKS proxy!")
s.close()
return False
if version == 5 and auth == 2:
auth = b"\x01" + struct.pack("B", len(socks5_user)) + socks5_user.encode() + struct.pack("B", len(socks5_pass)) + socks5_pass.encode()
s.sendall(auth)
try:
data = s.recv(2)
version, status = struct.unpack('BB', data)
except:
self.perror("Error connecting to SOCKS5 proxy!")
s.close()
return False
if status == 0:
s.close()
return True
else:
self.perror("Error authenticating to SOCKS5 proxy!")
s.close()
# reset creds on the pivot instance since auth failed
if cs_proxy_pivot:
cs_proxy_pivot.socks5_user = None
cs_proxy_pivot.socks5_pass = None
return False
else:
self.perror("Error connecting to SOCKS5 proxy!")
s.close()
return False
def do_cd(self, args):
"""Change directory"""
os.chdir(args)
# configure auto complete on the cd command
complete_cd = Cmd.path_complete
def do_pwd(self, args):
"""Print working directory"""
self.poutput(os.getcwd())
def do_exit(self, args):
"""Exit RedShell"""
Logger.close_logfile()
return True
def validate_ttps(self, ttps):
ttps_valid = []
ttps_check = ttps.split(',')
for ttp in ttps_check:
if re.match('^(T[0-9]{4})(\.[0-9]{3})?$', ttp):
ttps_valid.append(ttp)
else:
self.pwarning(f"Invalid TTP specified: {ttp}. Not including in log.")
validated_ttps = ', '.join(ttps_valid)
return validated_ttps
argparser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
argparser.description = "Execute a command through beacon socks proxy and simultaneously log it to the teamserver."
argparser.epilog = textwrap.dedent('''
example:
beacon_exec -t T1550.002,T1003.002 cme smb 192.168.1.1 --local-auth -u Administrator -H C713B1D611657D0687A568122193F230 --sam
''')
argparser.add_argument('-t', '--ttp', type=str, help="MITRE ATT&CK Tactic IDs. Comma delimited to specify multiple.")
argparser.add_argument('command', nargs=argparse.REMAINDER, help="Command to execute through the beacon proxy and log.", completer=Cmd.shell_cmd_complete)
@with_argparser(argparser)
def do_beacon_exec(self, args):
# check if agscript process is alive
if not self.cs_process or not self.cs_process.isalive():
self.perror("Error: not connected to CS team server. Connect first and then select a pivot.")
return
# check if socks port is connected
elif not self.socks_port_connected:
self.perror("Error: socks port not connected!")
return
else:
# make a copy of the user-specified command
command_list = args.command
# add proxychains to the command if user didn't include it
if 'proxychains' not in command_list:
id = 0
if 'sudo' in command_list:
id = 1
for item in ['proxychains', '-f', self.proxychains_config]:
command_list.insert(id, item)
id += 1
# convert command list into a string
command = shlex.join(command_list)
if '$password' in command and not self.password:
self.perror("Error: $password invoked, but password is not set. Add it with command: set password <password>")
return
command = re.sub("\$password", self.password, command)
# only log the command (minus sudo and proxychains)
cs_log_command = re.sub("proxychains.*?conf |sudo ", '', command)
cs_log_command = re.sub("\\\\", "\\\\\\\\", cs_log_command)
cs_log_command = re.sub("\$", "\$", cs_log_command) # escape $ char
cs_log_command = cs_log_command.replace('"', '\\"') # escape " char
cs_log_command = f"[PROXY] {cs_log_command}" # append [PROXY] to logged command
log_command = re.sub("proxychains.*?conf |sudo ", '', command)
log_command = f"[PROXY] {log_command}" # append [PROXY] to logged command
ttps = ''
if args.ttp:
ttps = self.validate_ttps(args.ttp)
if ttps:
# log command with TTPs to team server
self.cs_process.sendline(f'x btask({self.cs_beacon_id}, "{cs_log_command}", "{ttps}")')
self.cs_process.expect('.*aggressor.*> ')
else:
# log command without TTPs to team server
self.cs_process.sendline(f'x btask({self.cs_beacon_id}, "{cs_log_command}")')
self.cs_process.expect('.*aggressor.*> ')
Logger(log_command, ip=self.cs_beacon_ip, netbios_name=self.cs_beacon_computer, user_name=self.cs_beacon_user, pid=self.cs_beacon_pid, ttps=ttps.replace(' ', ''))
# run the command
self.do_shell(command)
argparser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
argparser.description = "Execute a command through custom socks proxy and simultaneously log it to the local file."
argparser.epilog = textwrap.dedent('''
example:
proxy_exec -t T1550.002,T1003.002 cme smb 192.168.1.1 --local-auth -u Administrator -H C713B1D611657D0687A568122193F230 --sam
''')