forked from EmpireProject/Empire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathempire.py
4523 lines (3423 loc) · 169 KB
/
empire.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
"""
The main controller class for Empire.
This is what's launched from ./empire.
Contains the Main, Listener, Agents, Agent, and Module
menu loops.
"""
# make version for Empire
VERSION = "2.5"
from pydispatch import dispatcher
import sys
import cmd
import sqlite3
import os
import hashlib
import time
import fnmatch
import shlex
import marshal
import pkgutil
import importlib
import base64
import threading
import json
# Empire imports
import helpers
import messages
import agents
import listeners
import modules
import stagers
import credentials
import plugins
from events import log_event
from zlib_wrapper import compress
from zlib_wrapper import decompress
# custom exceptions used for nested menu navigation
class NavMain(Exception):
"""
Custom exception class used to navigate to the 'main' menu.
"""
pass
class NavAgents(Exception):
"""
Custom exception class used to navigate to the 'agents' menu.
"""
pass
class NavListeners(Exception):
"""
Custom exception class used to navigate to the 'listeners' menu.
"""
pass
class MainMenu(cmd.Cmd):
"""
The main class used by Empire to drive the 'main' menu
displayed when Empire starts.
"""
def __init__(self, args=None):
cmd.Cmd.__init__(self)
# set up the event handling system
dispatcher.connect(self.handle_event, sender=dispatcher.Any)
# globalOptions[optionName] = (value, required, description)
self.globalOptions = {}
# currently active plugins:
# {'pluginName': classObject}
self.loadedPlugins = {}
# empty database object
self.conn = self.database_connect()
time.sleep(1)
self.lock = threading.Lock()
# pull out some common configuration information
(self.isroot, self.installPath, self.ipWhiteList, self.ipBlackList, self.obfuscate, self.obfuscateCommand) = helpers.get_config('rootuser, install_path,ip_whitelist,ip_blacklist,obfuscate,obfuscate_command')
# change the default prompt for the user
self.prompt = '(Empire) > '
self.do_help.__func__.__doc__ = '''Displays the help menu.'''
self.doc_header = 'Commands'
# Main, Agents, or
self.menu_state = 'Main'
# parse/handle any passed command line arguments
self.args = args
# instantiate the agents, listeners, and stagers objects
self.agents = agents.Agents(self, args=args)
self.credentials = credentials.Credentials(self, args=args)
self.stagers = stagers.Stagers(self, args=args)
self.modules = modules.Modules(self, args=args)
self.listeners = listeners.Listeners(self, args=args)
self.resourceQueue = []
#A hashtable of autruns based on agent language
self.autoRuns = {}
self.handle_args()
message = "[*] Empire starting up..."
signal = json.dumps({
'print': True,
'message': message
})
dispatcher.send(signal, sender="empire")
# print the loading menu
messages.loading()
def get_db_connection(self):
"""
Returns the
"""
self.lock.acquire()
self.conn.row_factory = None
self.lock.release()
return self.conn
def handle_event(self, signal, sender):
"""
Whenver an event is received from the dispatcher, log it to the DB,
decide whether it should be printed, and if so, print it.
If self.args.debug, also log all events to a file.
"""
# load up the signal so we can inspect it
try:
signal_data = json.loads(signal)
except ValueError:
print(helpers.color("[!] Error: bad signal recieved {} from sender {}".format(signal, sender)))
return
# this should probably be set in the event itself but we can check
# here (and for most the time difference won't matter so it's fine)
if 'timestamp' not in signal_data:
signal_data['timestamp'] = helpers.get_datetime()
# if this is related to a task, set task_id; this is its own column in
# the DB (else the column will be set to None/null)
task_id = None
if 'task_id' in signal_data:
task_id = signal_data['task_id']
if 'event_type' in signal_data:
event_type = signal_data['event_type']
else:
event_type = 'dispatched_event'
event_data = json.dumps({'signal': signal_data, 'sender': sender})
# print any signal that indicates we should
if('print' in signal_data and signal_data['print']):
print(helpers.color(signal_data['message']))
# get a db cursor, log this event to the DB, then close the cursor
cur = self.conn.cursor()
# TODO instead of "dispatched_event" put something useful in the "event_type" column
log_event(cur, sender, event_type, json.dumps(signal_data), signal_data['timestamp'], task_id=task_id)
cur.close()
# if --debug X is passed, log out all dispatcher signals
if self.args.debug:
with open('empire.debug', 'a') as debug_file:
debug_file.write("%s %s : %s\n" % (helpers.get_datetime(), sender, signal))
if self.args.debug == '2':
# if --debug 2, also print the output to the screen
print " %s : %s" % (sender, signal)
def check_root(self):
"""
Check if Empire has been run as root, and alert user.
"""
try:
if os.geteuid() != 0:
if self.isroot:
messages.title(VERSION)
print "[!] Warning: Running Empire as non-root, after running as root will likely fail to access prior agents!"
while True:
a = raw_input(helpers.color("[>] Are you sure you want to continue (y) or (n): "))
if a.startswith("y"):
return
if a.startswith("n"):
self.shutdown()
sys.exit()
else:
pass
if os.geteuid() == 0:
if self.isroot:
pass
if not self.isroot:
cur = self.conn.cursor()
cur.execute("UPDATE config SET rootuser = 1")
cur.close()
except Exception as e:
print e
def handle_args(self):
"""
Handle any passed arguments.
"""
if self.args.resource:
resourceFile = self.args.resource[0]
self.do_resource(resourceFile)
if self.args.listener or self.args.stager:
# if we're displaying listeners/stagers or generating a stager
if self.args.listener:
if self.args.listener == 'list':
messages.display_listeners(self.listeners.activeListeners)
messages.display_listeners(self.listeners.get_inactive_listeners(), "Inactive")
else:
activeListeners = self.listeners.activeListeners
targetListener = [l for l in activeListeners if self.args.listener in l[1]]
if targetListener:
targetListener = targetListener[0]
# messages.display_listener_database(targetListener)
# TODO: reimplement this logic
else:
print helpers.color("\n[!] No active listeners with name '%s'\n" % (self.args.listener))
else:
if self.args.stager == 'list':
print "\nStagers:\n"
print " Name Description"
print " ---- -----------"
for stagerName, stager in self.stagers.stagers.iteritems():
print " %s%s" % ('{0: <17}'.format(stagerName), stager.info['Description'])
print "\n"
else:
stagerName = self.args.stager
try:
targetStager = self.stagers.stagers[stagerName]
menu = StagerMenu(self, stagerName)
if self.args.stager_options:
for option in self.args.stager_options:
if '=' not in option:
print helpers.color("\n[!] Invalid option: '%s'" % (option))
print helpers.color("[!] Please use Option=Value format\n")
if self.conn:
self.conn.close()
sys.exit()
# split the passed stager options by = and set the appropriate option
optionName, optionValue = option.split('=')
menu.do_set("%s %s" % (optionName, optionValue))
# generate the stager
menu.do_generate('')
else:
messages.display_stager(targetStager)
except Exception as e:
print e
print helpers.color("\n[!] No current stager with name '%s'\n" % (stagerName))
# shutdown the database connection object
if self.conn:
self.conn.close()
sys.exit()
def shutdown(self):
"""
Perform any shutdown actions.
"""
print "\n" + helpers.color("[!] Shutting down...")
message = "[*] Empire shutting down..."
signal = json.dumps({
'print': True,
'message': message
})
dispatcher.send(signal, sender="empire")
# enumerate all active servers/listeners and shut them down
self.listeners.shutdown_listener('all')
# shutdown the database connection object
if self.conn:
self.conn.close()
def database_connect(self):
"""
Connect to the default database at ./data/empire.db.
"""
try:
# set the database connectiont to autocommit w/ isolation level
self.conn = sqlite3.connect('./data/empire.db', check_same_thread=False)
self.conn.text_factory = str
self.conn.isolation_level = None
return self.conn
except Exception:
print helpers.color("[!] Could not connect to database")
print helpers.color("[!] Please run database_setup.py")
sys.exit()
def cmdloop(self):
"""
The main cmdloop logic that handles navigation to other menus.
"""
while True:
try:
if self.menu_state == 'Agents':
self.do_agents('')
elif self.menu_state == 'Listeners':
self.do_listeners('')
else:
# display the main title
messages.title(VERSION)
# get active listeners, agents, and loaded modules
num_agents = self.agents.get_agents_db()
if num_agents:
num_agents = len(num_agents)
else:
num_agents = 0
num_modules = self.modules.modules
if num_modules:
num_modules = len(num_modules)
else:
num_modules = 0
num_listeners = self.listeners.activeListeners
if num_listeners:
num_listeners = len(num_listeners)
else:
num_listeners = 0
print " " + helpers.color(str(num_modules), "green") + " modules currently loaded\n"
print " " + helpers.color(str(num_listeners), "green") + " listeners currently active\n"
print " " + helpers.color(str(num_agents), "green") + " agents currently active\n\n"
if len(self.resourceQueue) > 0:
self.cmdqueue.append(self.resourceQueue.pop(0))
cmd.Cmd.cmdloop(self)
# handle those pesky ctrl+c's
except KeyboardInterrupt as e:
self.menu_state = "Main"
try:
choice = raw_input(helpers.color("\n[>] Exit? [y/N] ", "red"))
if choice.lower() != "" and choice.lower()[0] == "y":
self.shutdown()
return True
else:
continue
except KeyboardInterrupt as e:
continue
# exception used to signal jumping to "Main" menu
except NavMain as e:
self.menu_state = "Main"
# exception used to signal jumping to "Agents" menu
except NavAgents as e:
self.menu_state = "Agents"
# exception used to signal jumping to "Listeners" menu
except NavListeners as e:
self.menu_state = "Listeners"
except Exception as e:
print helpers.color("[!] Exception: %s" % (e))
time.sleep(5)
def print_topics(self, header, commands, cmdlen, maxcol):
"""
Print a nicely formatted help menu.
Adapted from recon-ng
"""
if commands:
self.stdout.write("%s\n" % str(header))
if self.ruler:
self.stdout.write("%s\n" % str(self.ruler * len(header)))
for command in commands:
self.stdout.write("%s %s\n" % (command.ljust(17), getattr(self, 'do_' + command).__doc__))
self.stdout.write("\n")
def emptyline(self):
"""
If any empty line is entered, do nothing.
"""
pass
###################################################
# CMD methods
###################################################
def do_plugins(self, args):
"List all available and active plugins."
pluginPath = os.path.abspath("plugins")
print(helpers.color("[*] Searching for plugins at {}".format(pluginPath)))
# From walk_packages: "Note that this function must import all packages
# (not all modules!) on the given path, in order to access the __path__
# attribute to find submodules."
pluginNames = [name for _, name, _ in pkgutil.walk_packages([pluginPath])]
numFound = len(pluginNames)
# say how many we found, handling the 1 case
if numFound == 1:
print(helpers.color("[*] {} plugin found".format(numFound)))
else:
print(helpers.color("[*] {} plugins found".format(numFound)))
# if we found any, list them
if numFound > 0:
print("\tName\tActive")
print("\t----\t------")
activePlugins = self.loadedPlugins.keys()
for name in pluginNames:
active = ""
if name in activePlugins:
active = "******"
print("\t" + name + "\t" + active)
print("")
print(helpers.color("[*] Use \"plugin <plugin name>\" to load a plugin."))
def do_plugin(self, pluginName):
"Load a plugin file to extend Empire."
pluginPath = os.path.abspath("plugins")
print(helpers.color("[*] Searching for plugins at {}".format(pluginPath)))
# From walk_packages: "Note that this function must import all packages
# (not all modules!) on the given path, in order to access the __path__
# attribute to find submodules."
pluginNames = [name for _, name, _ in pkgutil.walk_packages([pluginPath])]
if pluginName in pluginNames:
print(helpers.color("[*] Plugin {} found.".format(pluginName)))
message = "[*] Loading plugin {}".format(pluginName)
signal = json.dumps({
'print': True,
'message': message
})
dispatcher.send(signal, sender="empire")
# 'self' is the mainMenu object
plugins.load_plugin(self, pluginName)
else:
raise Exception("[!] Error: the plugin specified does not exist in {}.".format(pluginPath))
def postcmd(self, stop, line):
if len(self.resourceQueue) > 0:
nextcmd = self.resourceQueue.pop(0)
self.cmdqueue.append(nextcmd)
def default(self, line):
"Default handler."
pass
def do_resource(self, arg):
"Read and execute a list of Empire commands from a file."
self.resourceQueue.extend(self.buildQueue(arg))
def buildQueue(self, resourceFile, autoRun=False):
cmds = []
if os.path.isfile(resourceFile):
with open(resourceFile, 'r') as f:
lines = []
lines.extend(f.read().splitlines())
else:
raise Exception("[!] Error: The resource file specified \"%s\" does not exist" % resourceFile)
for lineFull in lines:
line = lineFull.strip()
#ignore lines that start with the comment symbol (#)
if line.startswith("#"):
continue
#read in another resource file
elif line.startswith("resource "):
rf = line.split(' ')[1]
cmds.extend(self.buildQueue(rf, autoRun))
#add noprompt option to execute without user confirmation
elif autoRun and line == "execute":
cmds.append(line + " noprompt")
else:
cmds.append(line)
return cmds
def do_exit(self, line):
"Exit Empire"
raise KeyboardInterrupt
def do_agents(self, line):
"Jump to the Agents menu."
try:
agents_menu = AgentsMenu(self)
agents_menu.cmdloop()
except Exception as e:
raise e
def do_listeners(self, line):
"Interact with active listeners."
try:
listener_menu = ListenersMenu(self)
listener_menu.cmdloop()
except Exception as e:
raise e
def do_usestager(self, line):
"Use an Empire stager."
try:
parts = line.split(' ')
if parts[0] not in self.stagers.stagers:
print helpers.color("[!] Error: invalid stager module")
elif len(parts) == 1:
stager_menu = StagerMenu(self, parts[0])
stager_menu.cmdloop()
elif len(parts) == 2:
listener = parts[1]
if not self.listeners.is_listener_valid(listener):
print helpers.color("[!] Please enter a valid listener name or ID")
else:
self.stagers.set_stager_option('Listener', listener)
stager_menu = StagerMenu(self, parts[0])
stager_menu.cmdloop()
else:
print helpers.color("[!] Error in MainMenu's do_userstager()")
except Exception as e:
raise e
def do_usemodule(self, line):
"Use an Empire module."
# Strip asterisks added by MainMenu.complete_usemodule()
line = line.rstrip("*")
if line not in self.modules.modules:
print helpers.color("[!] Error: invalid module")
else:
try:
module_menu = ModuleMenu(self, line)
module_menu.cmdloop()
except Exception as e:
raise e
def do_searchmodule(self, line):
"Search Empire module names/descriptions."
self.modules.search_modules(line.strip())
def do_creds(self, line):
"Add/display credentials to/from the database."
filterTerm = line.strip()
if filterTerm == "":
creds = self.credentials.get_credentials()
elif shlex.split(filterTerm)[0].lower() == "add":
# add format: "domain username password <notes> <credType> <sid>
args = shlex.split(filterTerm)[1:]
if len(args) == 3:
domain, username, password = args
if helpers.validate_ntlm(password):
# credtype, domain, username, password, host, sid="", notes=""):
self.credentials.add_credential("hash", domain, username, password, "")
else:
self.credentials.add_credential("plaintext", domain, username, password, "")
elif len(args) == 4:
domain, username, password, notes = args
if helpers.validate_ntlm(password):
self.credentials.add_credential("hash", domain, username, password, "", notes=notes)
else:
self.credentials.add_credential("plaintext", domain, username, password, "", notes=notes)
elif len(args) == 5:
domain, username, password, notes, credType = args
self.credentials.add_credential(credType, domain, username, password, "", notes=notes)
elif len(args) == 6:
domain, username, password, notes, credType, sid = args
self.credentials.add_credential(credType, domain, username, password, "", sid=sid, notes=notes)
else:
print helpers.color("[!] Format is 'add domain username password <notes> <credType> <sid>")
return
creds = self.credentials.get_credentials()
elif shlex.split(filterTerm)[0].lower() == "remove":
try:
args = shlex.split(filterTerm)[1:]
if len(args) != 1:
print helpers.color("[!] Format is 'remove <credID>/<credID-credID>/all'")
else:
if args[0].lower() == "all":
choice = raw_input(helpers.color("[>] Remove all credentials from the database? [y/N] ", "red"))
if choice.lower() != "" and choice.lower()[0] == "y":
self.credentials.remove_all_credentials()
else:
if "," in args[0]:
credIDs = args[0].split(",")
self.credentials.remove_credentials(credIDs)
elif "-" in args[0]:
parts = args[0].split("-")
credIDs = [x for x in xrange(int(parts[0]), int(parts[1]) + 1)]
self.credentials.remove_credentials(credIDs)
else:
self.credentials.remove_credentials(args)
except Exception:
print helpers.color("[!] Error in remove command parsing.")
print helpers.color("[!] Format is 'remove <credID>/<credID-credID>/all'")
return
elif shlex.split(filterTerm)[0].lower() == "export":
args = shlex.split(filterTerm)[1:]
if len(args) != 1:
print helpers.color("[!] Please supply an output filename/filepath.")
return
else:
self.credentials.export_credentials(args[0])
return
elif shlex.split(filterTerm)[0].lower() == "plaintext":
creds = self.credentials.get_credentials(credtype="plaintext")
elif shlex.split(filterTerm)[0].lower() == "hash":
creds = self.credentials.get_credentials(credtype="hash")
elif shlex.split(filterTerm)[0].lower() == "krbtgt":
creds = self.credentials.get_krbtgt()
else:
creds = self.credentials.get_credentials(filterTerm=filterTerm)
messages.display_credentials(creds)
def do_set(self, line):
"Set a global option (e.g. IP whitelists)."
parts = line.split(' ')
if len(parts) == 1:
print helpers.color("[!] Please enter 'IP,IP-IP,IP/CIDR' or a file path.")
else:
if parts[0].lower() == "ip_whitelist":
if parts[1] != "" and os.path.exists(parts[1]):
try:
open_file = open(parts[1], 'r')
ipData = open_file.read()
open_file.close()
self.agents.ipWhiteList = helpers.generate_ip_list(ipData)
except Exception:
print helpers.color("[!] Error opening ip file %s" % (parts[1]))
else:
self.agents.ipWhiteList = helpers.generate_ip_list(",".join(parts[1:]))
elif parts[0].lower() == "ip_blacklist":
if parts[1] != "" and os.path.exists(parts[1]):
try:
open_file = open(parts[1], 'r')
ipData = open_file.read()
open_file.close()
self.agents.ipBlackList = helpers.generate_ip_list(ipData)
except Exception:
print helpers.color("[!] Error opening ip file %s" % (parts[1]))
else:
self.agents.ipBlackList = helpers.generate_ip_list(",".join(parts[1:]))
elif parts[0].lower() == "obfuscate":
if parts[1].lower() == "true":
if not helpers.is_powershell_installed():
print helpers.color("[!] PowerShell is not installed and is required to use obfuscation, please install it first.")
else:
self.obfuscate = True
message = "[*] Obfuscating all future powershell commands run on all agents."
signal = json.dumps({
'print': True,
'message': message
})
dispatcher.send(signal, sender="empire")
elif parts[1].lower() == "false":
self.obfuscate = False
message = "[*] Future powershell commands run on all agents will not be obfuscated."
signal = json.dumps({
'print': True,
'message': message
})
dispatcher.send(signal, sender="empire")
else:
print helpers.color("[!] Valid options for obfuscate are 'true' or 'false'")
elif parts[0].lower() == "obfuscate_command":
self.obfuscateCommand = parts[1]
else:
print helpers.color("[!] Please choose 'ip_whitelist', 'ip_blacklist', 'obfuscate', or 'obfuscate_command'")
def do_reset(self, line):
"Reset a global option (e.g. IP whitelists)."
if line.strip().lower() == "ip_whitelist":
self.agents.ipWhiteList = None
if line.strip().lower() == "ip_blacklist":
self.agents.ipBlackList = None
def do_show(self, line):
"Show a global option (e.g. IP whitelists)."
if line.strip().lower() == "ip_whitelist":
print self.agents.ipWhiteList
if line.strip().lower() == "ip_blacklist":
print self.agents.ipBlackList
if line.strip().lower() == "obfuscate":
print self.obfuscate
if line.strip().lower() == "obfuscate_command":
print self.obfuscateCommand
def do_load(self, line):
"Loads Empire modules from a non-standard folder."
if line.strip() == '' or not os.path.isdir(line.strip()):
print helpers.color("[!] Please specify a valid folder to load modules from.")
else:
self.modules.load_modules(rootPath=line.strip())
def do_reload(self, line):
"Reload one (or all) Empire modules."
if line.strip().lower() == "all":
# reload all modules
print "\n" + helpers.color("[*] Reloading all modules.") + "\n"
self.modules.load_modules()
elif os.path.isdir(line.strip()):
# if we're loading an external directory
self.modules.load_modules(rootPath=line.strip())
else:
if line.strip() not in self.modules.modules:
print helpers.color("[!] Error: invalid module")
else:
print "\n" + helpers.color("[*] Reloading module: " + line) + "\n"
self.modules.reload_module(line)
def do_list(self, line):
"Lists active agents or listeners."
parts = line.split(' ')
if parts[0].lower() == 'agents':
line = ' '.join(parts[1:])
allAgents = self.agents.get_agents_db()
if line.strip().lower() == 'stale':
agentsToDisplay = []
for agent in allAgents:
# max check in -> delay + delay*jitter
intervalMax = (agent['delay'] + agent['delay'] * agent['jitter']) + 30
# get the agent last check in time
agentTime = time.mktime(time.strptime(agent['lastseen_time'], "%Y-%m-%d %H:%M:%S"))
if agentTime < time.mktime(time.localtime()) - intervalMax:
# if the last checkin time exceeds the limit, remove it
agentsToDisplay.append(agent)
messages.display_agents(agentsToDisplay)
elif line.strip() != '':
# if we're listing an agents active in the last X minutes
try:
minutes = int(line.strip())
# grab just the agents active within the specified window (in minutes)
agentsToDisplay = []
for agent in allAgents:
agentTime = time.mktime(time.strptime(agent['lastseen_time'], "%Y-%m-%d %H:%M:%S"))
if agentTime > time.mktime(time.localtime()) - (int(minutes) * 60):
agentsToDisplay.append(agent)
messages.display_agents(agentsToDisplay)
except Exception:
print helpers.color("[!] Please enter the minute window for agent checkin.")
else:
messages.display_agents(allAgents)
elif parts[0].lower() == 'listeners':
messages.display_listeners(self.listeners.activeListeners)
messages.display_listeners(self.listeners.get_inactive_listeners(), "Inactive")
def do_interact(self, line):
"Interact with a particular agent."
name = line.strip()
sessionID = self.agents.get_agent_id_db(name)
if sessionID and sessionID != '' and sessionID in self.agents.agents:
AgentMenu(self, sessionID)
else:
print helpers.color("[!] Please enter a valid agent name")
def do_preobfuscate(self, line):
"Preobfuscate PowerShell module_source files"
if not helpers.is_powershell_installed():
print helpers.color("[!] PowerShell is not installed and is required to use obfuscation, please install it first.")
return
module = line.strip()
obfuscate_all = False
obfuscate_confirmation = False
reobfuscate = False
# Preobfuscate ALL module_source files
if module == "" or module == "all":
choice = raw_input(helpers.color("[>] Preobfuscate all PowerShell module_source files using obfuscation command: \"" + self.obfuscateCommand + "\"?\nThis may take a substantial amount of time. [y/N] ", "red"))
if choice.lower() != "" and choice.lower()[0] == "y":
obfuscate_all = True
obfuscate_confirmation = True
choice = raw_input(helpers.color("[>] Force reobfuscation of previously obfuscated modules? [y/N] ", "red"))
if choice.lower() != "" and choice.lower()[0] == "y":
reobfuscate = True
# Preobfuscate a selected module_source file
else:
module_source_fullpath = self.installPath + 'data/module_source/' + module
if not os.path.isfile(module_source_fullpath):
print helpers.color("[!] The module_source file:" + module_source_fullpath + " does not exist.")
return
choice = raw_input(helpers.color("[>] Preobfuscate the module_source file: " + module + " using obfuscation command: \"" + self.obfuscateCommand + "\"? [y/N] ", "red"))
if choice.lower() != "" and choice.lower()[0] == "y":
obfuscate_confirmation = True
choice = raw_input(helpers.color("[>] Force reobfuscation of previously obfuscated modules? [y/N] ", "red"))
if choice.lower() != "" and choice.lower()[0] == "y":
reobfuscate = True
# Perform obfuscation
if obfuscate_confirmation:
if obfuscate_all:
files = [file for file in helpers.get_module_source_files()]
else:
files = ['data/module_source/' + module]
for file in files:
file = self.installPath + file
if reobfuscate or not helpers.is_obfuscated(file):
message = "[*] Obfuscating {}...".format(os.path.basename(file))
signal = json.dumps({
'print': True,
'message': message,
'obfuscated_file': os.path.basename(file)
})
dispatcher.send(signal, sender="empire")
else:
print helpers.color("[*] " + os.path.basename(file) + " was already obfuscated. Not reobfuscating.")
helpers.obfuscate_module(file, self.obfuscateCommand, reobfuscate)
def do_report(self, line):
"Produce report CSV and log files: sessions.csv, credentials.csv, master.log"
conn = self.get_db_connection()
try:
self.lock.acquire()
# Agents CSV
cur = conn.cursor()
cur.execute('select session_id, hostname, username, checkin_time from agents')
rows = cur.fetchall()
print helpers.color("[*] Writing data/sessions.csv")
f = open('data/sessions.csv','w')
f.write("SessionID, Hostname, User Name, First Check-in\n")
for row in rows:
f.write(row[0]+ ','+ row[1]+ ','+ row[2]+ ','+ row[3]+'\n')
f.close()
# Credentials CSV
cur.execute("""
SELECT
domain
,username
,host
,credtype
,password
FROM
credentials
ORDER BY
domain
,credtype
,host
""")
rows = cur.fetchall()
print helpers.color("[*] Writing data/credentials.csv")
f = open('data/credentials.csv','w')
f.write('Domain, Username, Host, Cred Type, Password\n')
for row in rows:
f.write(row[0]+ ','+ row[1]+ ','+ row[2]+ ','+ row[3]+ ','+ row[4]+'\n')
f.close()
# Empire Log
cur.execute("""
SELECT
reporting.time_stamp
,reporting.event_type
,reporting.name as "AGENT_ID"
,a.hostname
,reporting.taskID
,t.data AS "Task"
,r.data AS "Results"
FROM
reporting
JOIN agents a on reporting.name = a.session_id
LEFT OUTER JOIN taskings t on (reporting.taskID = t.id) AND (reporting.name = t.agent)
LEFT OUTER JOIN results r on (reporting.taskID = r.id) AND (reporting.name = r.agent)
WHERE
reporting.event_type == 'task' OR reporting.event_type == 'checkin'
""")
rows = cur.fetchall()
print helpers.color("[*] Writing data/master.log")
f = open('data/master.log', 'w')
f.write('Empire Master Taskings & Results Log by timestamp\n')
f.write('='*50 + '\n\n')
for row in rows:
f.write('\n' + row[0] + ' - ' + row[3] + ' (' + row[2] + ')> ' + unicode(row[5]) + '\n' + unicode(row[6]) + '\n')
f.close()
cur.close()
finally:
self.lock.release()
def complete_usemodule(self, text, line, begidx, endidx, language=None):
"Tab-complete an Empire module path."
module_names = self.modules.modules.keys()
# suffix each module requiring elevated context with '*'
for module_name in module_names:
try:
if self.modules.modules[module_name].info['NeedsAdmin']:
module_names[module_names.index(module_name)] = (module_name+"*")
# handle modules without a NeedAdmins info key
except KeyError:
pass
if language:
module_names = [ (module_name[len(language)+1:]) for module_name in module_names if module_name.startswith(language)]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)