This repository has been archived by the owner on Aug 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
parseltongue.py
1538 lines (1177 loc) · 65.3 KB
/
parseltongue.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2020 Dan Breakiron
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from argparse import ArgumentParser, ArgumentError
from datetime import datetime
from datetime import timedelta
import sys
import os
import re
import json
import hashlib, binascii
import csv
from xml.etree import ElementTree
from xml.etree.ElementTree import ParseError
#==============================================================================
#******** CONFIGURABLE CONSTANTS ********
#==============================================================================
DEFAULT_CONFIG_FILEPATH = "config.json"
# Default configuration; overridden at runtime by loaded config
CONFIG_DATA = {
'INPUT': {
# CHANGE THESE TO CONTROL WHICH ATTRIBUTES ARE PARSED
# IMPORTANT: The last element must be unique, otherwise objects won't be delimited properly
'DSQUERY_ATTRS': {
'COMPUTERS': ['dnshostname', 'operatingsystem', 'operatingsystemversion', 'operatingsystemservicepack', 'lastlogon', 'lastlogontimestamp', 'useraccountcontrol', 'description', 'memberof', 'primarygroupid', 'location', 'objectsid', 'adspath'],
'GPOS': ['displayname', 'name', 'adspath'],
'GROUPS': ['samaccountname', 'name', 'distinguishedname', 'objectsid', 'primarygroupid', 'description', 'member', 'adspath'],
'OUS': ['name', 'managedby', 'description', 'gplink', 'adspath'],
'USERS': ['samaccountname', 'name', 'distinguishedname', 'lastlogon', 'lastlogontimestamp', 'pwdlastset', 'useraccountcontrol', 'memberof', 'description', 'objectsid', 'primarygroupid', 'adspath']
},
'DATA': {
'FILENAME_DATE_FORMAT': '%Y-%m-%d',
'CS_EXPORT': {
'FOREIGN_DOMAIN': 'include', # Valid options: 'include', 'ignore'
'INVALID_REALM': 'prompt', # Valid options: 'replace', 'prompt', 'warn', 'ignore', 'warn_and_ignore'
'POPULATE_COMMENT': 'append' # Valid options: "append", "empty_only", "none"
}
},
'WORDLIST': 'wordlists\\wordlist.txt'
},
'OUTPUT': {
'DATA': {
'FILENAME_DATE_FORMAT': '%Y-%m-%d',
'DIR': 'output',
'MULTI_OBJECT_DELIMITER': '\n',
'SEPARATE_BY_DOMAIN': False
},
'WORDLIST': 'wordlists\\wordlist.txt'
},
'LOGGING': {
'OUTPUT_DIR': 'logs',
'VERBOSITY': 2,
'TIMEFORMAT_FILE': '%Y-%m-%d_%H%M%S',
'TIMEFORMAT_LOG': '%Y-%m-%d %H:%M:%S',
'WRITE_FILE': True
},
'DEBUG': True,
'VERBOSITY': 1
}
#==============================================================================
#******** CONSTANTS ********
#==============================================================================
KV_PATT = re.compile('^(?P<key>.*?): (?P<value>.*)$')
# Types of data supported by Parseltongue
# These strings must appear at the end of the filename in order to identify the data type
FILE_TYPE_MAP = {
'computers': CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['COMPUTERS'],
'credentials': ['username', 'plaintext', 'ntlm', 'aes128', 'aes256', 'comment'],
'dns': ['hostname', 'ip', 'fqdn', 'cname'],
'gpos': CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['GPOS'],
'groups': CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['GROUPS'],
'ous': CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['OUS'],
'users': CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['USERS']
}
# Subset of file types which should be merged into 'credentials' data
CREDENTIAL_TYPES = ['cs_export', 'dcsync', 'hashdump', 'logonpasswords', 'lsadump']
FILE_TYPES = sorted(list(FILE_TYPE_MAP.keys()) + CREDENTIAL_TYPES)
VERSION = '2.1.4'
BANNER_SM = """
=======================================================================
____ _ ____ ____ _____ _ _____ ___ _ _ ____ _ _ _____
| _ \ / \ | _ \/ ___|| ____| | |_ _/ _ \| \ | |/ ___| | | | ____|
| |_) / _ \ | |_) \___ \| _| | | | || | | | \| | | _| | | | _|
| __/ ___ \| _ < ___) | |___| |___| || |_| | |\ | |_| | |_| | |___
|_| /_/ \_\_| \_\____/|_____|_____|_| \___/|_| \_|\____|\___/|_____|
=======================================================================
"""
BANNER_LG = """
=========================================================================================================
_______ _______ _______ _______ _______ _ _________ _______ _ _______ _______
( ____ )( ___ )( ____ )( ____ \( ____ \( \ \__ __/( ___ )( ( /|( ____ \|\ /|( ____ \
| ( )|| ( ) || ( )|| ( \/| ( \/| ( ) ( | ( ) || \ ( || ( \/| ) ( || ( \/
| (____)|| (___) || (____)|| (_____ | (__ | | | | | | | || \ | || | | | | || (__
| _____)| ___ || __)(_____ )| __) | | | | | | | || (\ \) || | ____ | | | || __)
| ( | ( ) || (\ ( ) || ( | | | | | | | || | \ || | \_ )| | | || (
| ) | ) ( || ) \ \__/\____) || (____/\| (____/\| | | (___) || ) \ || (___) || (___) || (____/\
|/ |/ \||/ \__/\_______)(_______/(_______/)_( (_______)|/ )_)(_______)(_______)(_______/
=========================================================================================================
"""
USAGE_TEXT="""
Parseltongue auto-detects information from the name of the data file being processed.
Therefore, data files must be named according to the following format:
<NT domain>_<date>_<file_type>
The accepted datestamp format can be configured using the ['INPUT']['DATA']['FILENAME_DATE_FORMAT']
option in the config file. Dates are used to chronologically order data of the same file type
so that more recent data overwrites older data, if applicable.
Valid File Types:
- {0}
Parseltongue can handle both XML and text versions of exported Cobalt Strike credentials; however, XML is highly preferred. The regex for the text version will not properly handle plaintext password entries where the username contains a space; this is a limitation of the text export format, which is space-delimited, not a bug with parseltongue. Since Cobalt Strike credentials may contain data from multiple domains, configuration options are provided that allows users to specify how to handle various situations; see the README for more details.
""".format('\n - '.join(FILE_TYPES))
EXAMPLES = """
EXAMPLES:
{0} -s
- Displays dsquery commands to run to generate expected output
{0} -c custom_config.json -g
- Creates a custom_config.json with the default config settings, if the file does not exist. If the file does exist, the "-g" argument does nothing. If "-g" is omitted and the specified file does not exist, the user will be prompted whether or not to create the file. Either way, the current configuration is printed to the screen. This can be used to double check settings, especially useful when using command-line options to override config file settings.
{0} -c custom_config.json -d "|" -u SGC_2020-03-11_users.txt
- Loads a custom config file (custom_config.json)
- Uses "|" as a delimiter between multiple values of the same type (e.g., member attribute of a group)
- Updates custom_config.json to use "|" as the delimiter
{0} -o ../parseltongue_output -w wordlist.txt SGC_2020-03-11_hashdump.txt SGC_2020-03-11_users.txt
- Specifies a custom output directory; overrides output directory specified in config file for current execution
- Reads a list of plaintext passwords (one per line) from wordlist.txt; uses these to crack hashes specified in the hashdump
- Parses Active Directory user data and enriches each record with the NTLM hash of the user; if a matching plaintext password was found in wordlist.txt, this will also be included
{0} SGC_2020-03-11_users.txt SGC_2020-03-11_computers.txt SGC_2020-03-11_groups.txt
- Parses users, computers, and group data for the SGC domain
""".format(sys.argv[0])
#==============================================================================
#******** GLOBAL VARIABLES ********
#==============================================================================
# A dictionary containing parsed system information, grouped by NT domain and broken down by file type
# FORMAT:
# data_objects = {
# <nt_domain>: {
# 'computers': {},
# 'credentials': {},
# 'dns': {},
# 'gpos': {},
# 'groups': {},
# 'ous': {},
# 'users': {}
# },
# ...
# }
data_objects = {}
# A dictionary containing a mapping of hostnames to IPs, CNAMEs, and FQDNs
hostname_map = {}
# A dictionary mapping NTLM hashes to plaintext password; used for rudimentary password cracking
ntlm_plaintext_map = {}
#==============================================================================
#******** UTILITIES ********
#==============================================================================
def pformat(obj):
"""
Converts the given object into a pretty printed string
Args:
obj: The object to pretty print
"""
return json.dumps(obj, indent=4, sort_keys=True, default=str)
def get_dsquery_commands_str():
"""
Returns a string containing the dsquery commands from which Parseltongue expects to receive output
This is a separate function (as opposed to the hardcoded USAGE and EXAMPLES strings because the command
attributes can be set via the config file so this string must be dynamically generated
"""
computers = 'dsquery * -filter "(objectclass=computer)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['COMPUTERS'])
users = 'dsquery * -filter "(&(objectclass=user)(!(objectclass=computer)))" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['USERS'])
groups = 'dsquery * -filter "(objectclass=group)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['GROUPS'])
gpos = 'dsquery * -filter "(objectclass=grouppolicycontainer)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['GPOS'])
ous = 'dsquery * -filter "(objectclass=organizationalunit)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['OUS'])
return """
DSQUERY COMMANDS:
COMPUTERS:
{0}
USERS:
{1}
GROUPS:
{2}
OUs:
{3}
GPOs:
{4}
""".format(computers, users, groups, ous, gpos)
def print_usage(parser):
"""
Prints usage information, including examples and sample queries
Args:
parser: An ArgumentParser object, used to print default help
"""
parser.print_help()
# Print usage, examples, sample queries, and current config
# separated by a horizontal line delimiter
divider = '\n%s\n' % ('-' * 90)
log(divider.join([USAGE_TEXT, EXAMPLES]))
print_dsquery_commands()
print_config()
# IMPORTANT: This needs to be a separate function because the dsquery attributes are set
# in the config file so this string must be generated dynamically rather than once at start up
def print_dsquery_commands():
"""
Returns a string containing the dsquery commands from which Parseltongue expects to receive output
"""
computers = 'dsquery * -filter "(objectclass=computer)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['COMPUTERS'])
users = 'dsquery * -filter "(&(objectclass=user)(!(objectclass=computer)))" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['USERS'])
groups = 'dsquery * -filter "(objectclass=group)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['GROUPS'])
gpos = 'dsquery * -filter "(objectclass=grouppolicycontainer)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['GPOS'])
ous = 'dsquery * -filter "(objectclass=organizationalunit)" -attr %s -limit 0 -l' % ' '.join(CONFIG_DATA['INPUT']['DSQUERY_ATTRS']['OUS'])
template = """
DSQUERY COMMANDS:
COMPUTERS:
{0}
USERS:
{1}
GROUPS:
{2}
OUs:
{3}
GPOs:
{4}
"""
log('%s\n%s' % ('-' * 90, template.format(computers, users, groups, ous, gpos)))
def print_config():
"""
Prints a horizontal delimiter and the current config
"""
log('%s\n\nCURRENT CONFIG:\n\n%s' % ('-' * 90, pformat(CONFIG_DATA)))
def log(msg, level=1, suppress=False):
"""
Print the specified message to the screen (unless suppressed)
if the level is below the verbosity threshold.
Write the message to a log file in all cases if the WRITE_LOGFILE is set to True in the config
Args:
msg: A message to print and log
level: A number indicating whether at which verbosity threshold the message should be printed
suppress: A boolean indicating whether the message should be logged only and not printed to the console
"""
if level <= CONFIG_DATA['VERBOSITY'] and not suppress:
print(msg)
if CONFIG_DATA['LOGGING']['WRITE_FILE'] and level <= CONFIG_DATA['LOGGING']['VERBOSITY']:
log_filepath = os.path.join(CONFIG_DATA['LOGGING']['OUTPUT_DIR'], 'parseltongue_%s.log' % datetime.now().strftime(CONFIG_DATA['LOGGING']['TIMEFORMAT_FILE']))
# Ensure the output directory exists
output_dir = os.path.dirname(log_filepath)
os.makedirs(output_dir, exist_ok = True)
with open(log_filepath, 'a') as log_file:
msg = '\n' if msg == '' else '%s> %s\n' % (datetime.now().strftime(CONFIG_DATA['LOGGING']['TIMEFORMAT_LOG']), msg)
log_file.writelines(msg)
def debug(data, msg=None):
"""
Logs the optional message and value of data, if debugging is enabled
Args:
data: A string or object whose contents should be written to the log file for debugging
msg: An optional human-readable message to provide context to the printed data
"""
if CONFIG_DATA['DEBUG']:
if msg is not None:
log('[DEBUG] %s' % msg, 0, suppress=True)
# Convert data to a str, if necessary
if not isinstance(data, str):
data = pformat(data)
log('\n%s\n' % data, 0, suppress=True)
# Source: https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries
def merge_dict(a, b, path=[]):
"""
Merges the second dictionary into the first one
Args:
a: The first dictionary; values from dictionary 'b' will be merged into this one
b: The second dictionary; values from this object will be merged into dictionary 'a'
path: A list of keys indicating where the current object falls in the hierarchy of nested objects
Returns:
Dictionary 'a' with values from 'b' merged into it
"""
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dict(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
log(' [*] Overriding default config setting: %s' % '.'.join(path + [str(key)]), 2)
a[key] = b[key]
else:
log(' [-] WARNING: Unused setting %s. Setting may have a typo or be deprecated' % '.'.join(path + [str(key)]), 2)
a[key] = b[key]
return a
def group_input_filepaths(filepaths):
"""
Create a dictionary of all data files supplied as arguments, grouped by NT domain
and file type.
Args:
filepaths: The list of data files supplied as arguments
Returns:
A dictionary of data files grouped by NT domain and file type
"""
global data_objects
data_files = {}
# Read in all the arguments, group by NT domain, sort by date
for filepath in filepaths:
log(' [*] %s' % filepath, 2)
(name, ext) = os.path.splitext(os.path.basename(filepath.lower()))
for type in FILE_TYPES:
if name.endswith(type):
category = 'credentials' if type in CREDENTIAL_TYPES else type
# Strip type (and the preceeding '_') from the end of the filename; date should now be the last value
name = name.replace('_' + type, '')
date = name.split('_')[-1]
# Strip off the date and treat whatever remains as the NT domain
# Accounts for cases where the NT domain may include an '_'
nt_domain = name.replace('_' + date, '').upper()
if nt_domain not in data_files:
data_files[nt_domain] = {}
data_objects[nt_domain] = {}
if category not in data_files[nt_domain]:
data_files[nt_domain][category] = []
data_objects[nt_domain][category] = {}
# Save parsed data about the current file
# Save the actual type so the correct parsing function can be called later
data_files[nt_domain][category].append({
'date': datetime.strptime(date, CONFIG_DATA['INPUT']['DATA']['FILENAME_DATE_FORMAT']),
'path': filepath,
'type': type
})
# IMPORTANT: Required for the 'for/else' to work
break
else:
log(' [-] ERROR: Unable to determine file type for: %s' % filepath, 0)
return data_files
def generate_ntlm(plaintext):
"""
Creates an NTLM hash from the given plaintext password. Stores a mapping
in ntlm_plaintext_map
Args:
plaintext: A plaintext password
Returns:
An uppercase hexadecimal string representing an NTLM hash
"""
global ntlm_plaintext_map
hash = hashlib.new('md4', plaintext.encode('utf-16le')).digest()
ntlm = binascii.hexlify(hash).upper().decode('utf-8')
# Store NTLM / plaintext association in the global map
ntlm_plaintext_map[ntlm] = plaintext
return ntlm
def convert_uac(uac):
"""
Converts a numeric Active Directory userAccountControl value to a human-readable string
Args:
uac: A numeric Active Directory userAccountControl value
Returns:
A human-readable string representation of the given userAccountControl value
"""
if uac.strip() == '':
return ''
# Source: https://support.microsoft.com/en-us/help/305144/how-to-use-useraccountcontrol-to-manipulate-user-account-properties
UAC_FLAGS = {
'0x0001': "Script",
'0x0002': "Account Disabled",
'0x0008': "Homedir Required",
'0x0010': "Lockout",
'0x0020': "Password Not Required",
'0x0040': "Password Can't Change",
'0x0080': "Encrypted Text Password Allowed",
'0x0100': "Temp Duplicate Account",
'0x0200': "Normal Account",
'0x0800': "Interdomain Trust Account",
'0x1000': "Workstation Trust Account",
'0x2000': "Server Trust Account",
'0x10000': "Password Doesn't Expire",
'0x20000': "MNS Logon Account",
'0x40000': "Smartcard Required",
'0x80000': "Trusted For Delegation",
'0x100000': "Not Delegated",
'0x200000': "Use DES Key Only",
'0x400000': "Don't Require PreAuth",
'0x800000': "Password Expired",
'0x1000000': "Trusted to auth for delegation",
'0x04000000': "Partial Secrets Account"
}
flags = []
for flag in UAC_FLAGS:
# Perform a bitwise XOR to determine if the flag is part of the UAC value
if int(uac) & int(flag, 16) == int(flag, 16):
flags.append(UAC_FLAGS[flag])
return CONFIG_DATA['OUTPUT']['DATA']['MULTI_OBJECT_DELIMITER'].join(sorted(flags))
def convert_nt_time(nt_time):
"""
Converts Windows NT time value to a human-readable datetime value
Args:
nt_time: A Windows NT time value
Returns:
A human-readable datetime value
"""
if nt_time.strip() == '':
return ''
try:
nt_time = int(nt_time)
if nt_time == 0:
return None
epoch_start = datetime(year=1601, month=1, day=1)
seconds_since_epoch = nt_time / 10 ** 7
timestamp = epoch_start + timedelta(seconds=seconds_since_epoch)
except ValueError:
timestamp = datetime.strptime(nt_time.split(".")[0], "%Y%m%d%H%M%S")
return timestamp.strftime('%Y-%m-%d %H:%M:%S')
def enhance_object(obj):
"""
Performs various conversions and enhancements of AD object data
- Picks the more recent of lastLogon and lastLogonTimestamp, and converts it to a human-readable timestamp
- Converts pwdLastSet to a human-readable timestamp
- If DNS data was provided, adds IP entries to computer objects
Args:
obj: A dictionary containing attributes of an Active Directory object; must contain an 'nt_domain' attribute
Returns:
An enhanced Active Directory object (dictionary)
"""
nt_domain = obj['nt_domain']
creds = data_objects[nt_domain]['credentials'] if 'credentials' in data_objects[nt_domain] else None
gpo_data = data_objects[nt_domain]['gpos'] if 'gpos' in data_objects[nt_domain] else None
delimiter = CONFIG_DATA['OUTPUT']['DATA']['MULTI_OBJECT_DELIMITER']
GPO_NAME_PATT = re.compile('\{[0-9A-Fa-f\-]{36}\}')
# Attempt to derive name from various fields
name = ''
if 'samaccountname' in obj.keys():
name = obj['samaccountname']
if name == '' and 'name' in obj.keys():
name = obj['name']
if name == '' and 'dnshostname' in obj.keys():
name = obj['dnshostname'].split('.')[0]
if name == '':
log(' [-] WARNING: Object contains no name field', 2)
# Standardize capitalization to ensure a proper look-up in the creds object
name = name.lower()
obj['id'] = name
# Add credential fields
if creds is not None:
if name in creds:
# Create a copy of the credential so that username isn't deleted from the original dictionary
tmp_creds = creds[name].copy()
del tmp_creds['username']
obj.update(tmp_creds)
elif name + '$' in creds:
# Add credential fields for computer accounts
# Create a copy of the credential so that username isn't deleted from the original dictionary
tmp_creds = creds[name + '$'].copy()
del tmp_creds['username']
obj.update(tmp_creds)
# Figure out the most recent logon time (between lastlogon and lastlogontimestamp)
# Convert it to human-readable time
if 'lastlogon' in obj.keys() and 'lastlogontimestamp' in obj.keys():
obj['lastlogon'] = convert_nt_time(max(obj['lastlogon'], obj['lastlogontimestamp']))
del obj['lastlogontimestamp']
elif 'lastlogontimestamp' in obj.keys():
obj['lastlogon'] = convert_nt_time(obj['lastlogontimestamp'])
del obj['lastlogontimestamp']
elif 'lastlogon' in obj.keys():
obj['lastlogon'] = convert_nt_time(obj['lastlogon'])
if 'pwdlastset' in obj.keys():
obj['pwdlastset'] = convert_nt_time(obj['pwdlastset'])
if 'useraccountcontrol' in obj.keys():
obj['useraccountcontrol'] = convert_uac(obj['useraccountcontrol'])
# If DNS data was provided, add the computer's IP
hostname = name.upper()
if hostname in hostname_map and 'ip' in hostname_map[hostname]:
# Account for multiple IP addresses per host
obj['ip'] = delimiter.join(set(hostname_map[hostname]['ip']))
else:
# Set a default so CSV writer doesn't get angry if it's empty
obj['ip'] = ''
# Replace values in gplink with human-readable names
if gpo_data is not None and bool(gpo_data) and 'gplink' in obj.keys() and obj['gplink'] != '':
gpos = []
gpo_guids = GPO_NAME_PATT.findall(obj['gplink'].lower())
for guid in gpo_guids:
if guid in gpo_data and 'displayname' in gpo_data[guid]:
gpos.append(gpo_data[guid]['displayname'])
else:
# All GPOs should be found, but just in case, it's good to know if data is missing
gpos.append(guid)
obj['gpos'] = delimiter.join(gpos)
del obj['gplink']
return obj
def merge_creds(cred):
"""
Adds the specified credential data to the data_objects aggregator variable for the
current domain if the username has not existing data or updates their credentials
if they do
Args:
cred: A dictionary containing credentials
"""
global data_objects
debug(cred, 'Credential')
nt_domain = cred['nt_domain']
username = cred['username']
# Ensure the NT domain and credentials keys exist
if nt_domain not in data_objects:
data_objects[nt_domain] = {
'credentials': {}
}
if username in data_objects[nt_domain]['credentials']:
data_objects[nt_domain]['credentials'][username].update(cred)
else:
data_objects[nt_domain]['credentials'][username] = cred
# Update plaintext password to match NTLM (either an appropriate mapping from ntlm_plaintext_map or '')
ntlm = cred['ntlm']
plaintext = ntlm_plaintext_map[ntlm] if ntlm in ntlm_plaintext_map else ''
data_objects[nt_domain]['credentials'][username]['plaintext'] = plaintext
#==============================================================================
#******** DNS PARSER ********
#==============================================================================
def parse_dnscmd(filepath, nt_domain):
"""
Reads and parses output from "dnscmd /zoneprint" to create a dictionary of hostnames and their associated IPs, CNAMEs, and FQDNs
Args:
filepath: The path to a file containing output from a "dnscmd /zoneprint" command
nt_domain: NT domain
"""
global data_objects
global hostname_map
log(' [*] Parsing DNSCMD output from: %s' % filepath)
delimiter = CONFIG_DATA['OUTPUT']['DATA']['MULTI_OBJECT_DELIMITER']
# Regex for A records
A_REC_PATT = re.compile('^(?P<hostname>[a-zA-Z0-9\-]*?)\s.+?\s?\d*\sA\s(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$')
# Regex for CNAME records
CNAME_REC_PATT = re.compile('^(?P<alias>[a-zA-Z0-9\-]*?)\s[.+?\s]?\d*\sCNAME\s(?P<fqdn>[a-zA-Z0-9\-\.]*)$')
zone = ''
with open(filepath, 'r') as zone_file:
for line in zone_file.readlines():
line = line.strip()
if '; Zone:' in line:
zone = line.split(':')[1].strip().upper()
a_rec = A_REC_PATT.search(line)
if a_rec is not None:
a_rec = a_rec.groupdict()
hostname = a_rec['hostname'].upper()
ip = a_rec['ip']
# Skip FORESTDNSZONES and DOMAINDNSZONES (not sure what these are for)
if hostname.endswith('DNSZONES'):
continue
# Save the IP in a list to gracefully handle multiple IPs per hostname
if hostname in hostname_map:
hostname_map[hostname]['ip'].append(ip)
else:
hostname_map[hostname] = {
'ip': [ip],
'fqdn': ['%s.%s' % (hostname, zone)],
'cname': []
}
else:
cname = CNAME_REC_PATT.search(line)
if cname is not None:
cname = cname.groupdict()
fqdn = cname['fqdn'].strip('.').upper()
hostname = fqdn.split('.')[0]
alias = cname['alias'].upper()
# Save the CNAME and FQDN in lists to gracefully handle multiples
if hostname in hostname_map:
hostname_map[hostname]['fqdn'].append(fqdn)
hostname_map[hostname]['cname'].append(alias)
else:
#print('[-] ERROR: CNAME without A record...is this even possible?')
hostname_map[hostname] = {
'ip': [],
'fqdn': [fqdn],
'cname': [alias]
}
# TODO
# - Add other record types records (PTR, SRV, etc.)
# Populate objects in case no other options were specified
for name in hostname_map.keys():
obj = {
'nt_domain': nt_domain,
'hostname': name
}
# Add other fields (if applicable), use set() to ensure only unique values
if 'ip' in hostname_map[name]:
obj['ip'] = delimiter.join(set(hostname_map[name]['ip']))
if 'fqdn' in hostname_map[name]:
obj['fqdn'] = delimiter.join(set(hostname_map[name]['fqdn']))
if 'cname' in hostname_map[name]:
obj['cname'] = delimiter.join(set(hostname_map[name]['cname']))
# Storing the data in a dictionary using the hostname as the key ensures that entries from more recent files will overwrite the previous records
data_objects[nt_domain]['dns'][name] = obj
debug(hostname_map, 'Hostname to IP map')
#==============================================================================
#******** CREDENTIAL PARSERS ********
#==============================================================================
def parse_credentials(filepath):
"""
Parses Parseltongue credential output
Args:
filepath: The path to a file containing Parseltongue credential output
"""
with open(filepath, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
merge_creds(row)
def parse_hashdump(filepath, nt_domain):
"""
Parses output from a hashdump (in pwdump format) into a dictionary
Args:
filepath: The path to a file containing output from a pwdump hashdump
nt_domain: NT domain
"""
log(' [*] Parsing hashdump output from: %s' % filepath)
with open(filepath, 'r') as hashdump:
for line in hashdump.readlines():
if ':' in line:
(username, rid, lm_hash, nt_hash) = line.lower().split(':')[:4]
ntlm = nt_hash.upper()
merge_creds({'nt_domain': nt_domain, 'username': username, 'ntlm': ntlm, 'comment': 'hashdump'})
def parse_lsadump(filepath, nt_domain):
"""
Parses output from Mimikatz lsadump into a dictionary
Args:
filepath: The path to a file containing output from Mimikatz lsadump
nt_domain: NT domain
"""
log(' [*] Parsing lsadump output from: %s' % filepath)
username = ''
with open(filepath, 'r') as lsadump:
for line in lsadump.readlines():
if 'User : ' in line:
username = KV_PATT.search(line).groupdict()['value'].lower()
elif 'NTLM : ' in line:
ntlm = KV_PATT.search(line).groupdict()['value'].upper()
if ntlm != '':
merge_creds({'nt_domain': nt_domain, 'username': username, 'ntlm': ntlm, 'comment': 'lsadump'})
username = ''
def parse_cs_export(filepath, nt_domain):
"""
Parses exported Cobalt Strike credentials into a dictionary
Args:
filepath: The path to a Cobalt Strike credential export file
nt_domain: NT domain
"""
# '&' isn't a valid XML character but Cobalt Strike includes it in the XML export anyway...
# So when parsing, we replace '&' with '&', then remove it when retrieving
# the contents of each element
def get_text(entry, field):
text = entry.find(field).text
text = text.replace('&', '&') if text else ''
return text
log(' [*] Parsing Cobalt Strike credential export from: %s' % filepath)
with open(filepath, 'r') as in_file:
data = in_file.readlines()
if '<credentials>' in data[0]:
log(' [*] Auto-detected Cobalt Strike XML export', 2)
try:
# Replace invalid XML token '&' with the appropriate '&'
# This will be undone later by get_text()
credentials = ElementTree.fromstring(''.join(data).replace('&', '&'))
# Save the CS export options for convenient access
cs_export_settings = CONFIG_DATA['INPUT']['DATA']['CS_EXPORT']
NTLM_PATT = re.compile('^[A-Fa-f0-9]{32}$')
# Store user provided DNS to NT domain mapping for future use
dns_to_nt_map = {}
for entry in credentials.iter('entry'):
# Convert entry back to XML for debugging
debug(' ' + ElementTree.tostring(entry).decode('utf-8').replace('\t', ' ').strip(), 'XML entry')
realm = get_text(entry, 'realm').upper()
# Convert DNS domain to NT domain, if applicable and possible
if realm in dns_to_nt_map:
log(' [*] Replacing invalid realm %s with %s' % (realm, dns_to_nt_map[realm]), 2)
realm = dns_to_nt_map[realm]
cred = {
'nt_domain': realm,
'username': get_text(entry, 'user').lower(),
'comment': get_text(entry, 'note')
}
password = get_text(entry, 'password')
# Determine if the 'password' element is an NTLM hash or a plaintext password
if NTLM_PATT.match(password):
cred['ntlm'] = password.upper()
else:
# generate_ntlm() will store the plaintext in the ntlm_plaintext_map
# merge_creds() will add the plaintext, so no need to store it here
cred['ntlm'] = generate_ntlm(password)
# IMPORTANT: Domain manipulation takes place after the password manipulation to ensure that any plaintext
# passwords encountered still make it into the ntlm_plaintext_map for cracking and wordlist output
# Determine whether the realm is a DNS domain rather than an NT one
if '.' in cred['nt_domain']:
setting = cs_export_settings['INVALID_REALM']
if setting == 'replace':
log(' [*] Replacing invalid realm %s with %s' % (realm, nt_domain), 2)
cred['nt_domain'] = nt_domain
elif setting == 'prompt':
while '.' in cred['nt_domain']:
log(' [*] %s is not a valid NT domain' % cred['nt_domain'])
cred['nt_domain'] = input(' [?] Please enter the NT domain that matches %s: ' % realm).upper()
# Reset to the original value if user did not provide input
if cred['nt_domain'] == '':
cred['nt_domain'] = realm
log(' [*] Replacing invalid realm %s with %s' % (realm, cred['nt_domain']), 2)
# Add it to a map for future reference
dns_to_nt_map[realm] = cred['nt_domain']
elif 'warn' in setting:
log(' [-] WARNING: %s is not a valid NT domain' % cred['nt_domain'])
# If set to ignore, skip this entry and continue with the next
if 'ignore' in setting:
continue
# Skip foreign realms (i.e., ones that do not match the NT domain
# specified in the filename) if configured to do so
if cred['nt_domain'] != nt_domain and cs_export_settings['FOREIGN_DOMAIN'] == 'ignore':
continue
# Optionally save the source and host information in the comment
source = get_text(entry, 'source')
host = get_text(entry, 'host')
src_host_info = source if host is '' else '%s on %s' % (source, host)
if cred['comment'] == '' and cs_export_settings['POPULATE_COMMENT'] in ['append', 'empty_only']:
cred['comment'] = src_host_info
elif cred['comment'] != '' and cs_export_settings['POPULATE_COMMENT'] == 'append':
cred['comment'] += '; %s' % src_host_info
merge_creds(cred)
except ParseError as e:
log(' [-] ERROR: Failed to parse XML file; see error message below')
log(' %s' % e)
return
else:
log(' [*] Auto-detected Cobalt Strike text export', 2)
# IMPORTANT: This code will not reliably handle plaintext passwords if the username
# has a space because text export is space delimited
NTLM_PATT = re.compile('^(?P<realm>.*?)\\\\(?P<username>.*?):::(?P<ntlm>[a-fA-F0-9]{32}):::$')
PLAIN_PATT = re.compile('^(?P<realm>.*)\\\\(?P<username>.*?) (?P<plaintext>.*)$')
for line in data:
line = line.strip()
data = NTLM_PATT.search(line)
if data is not None:
data = data.groupdict()
realm = data['realm']
username = data['username'].lower()
ntlm = data['ntlm'].upper()
if realm == nt_domain:
merge_creds({'nt_domain': nt_domain, 'username': username, 'ntlm': ntlm, 'comment': 'cs_export'})
else:
data = PLAIN_PATT.search(line)
if data is not None:
data = data.groupdict()
realm = data['realm']
username = data['username'].lower()
plaintext = data['plaintext']
if realm == nt_domain:
merge_creds({'nt_domain': nt_domain, 'username': username, 'ntlm': generate_ntlm(plaintext), 'plaintext': plaintext, 'comment': 'cs_export'})
def parse_dcsync(filepath, nt_domain):
"""
Parses output from Mimikatz dcsync into a dictionary
Args:
filepath: The path to a file containing output from Mimikatz dcsync
nt_domain: NT domain
"""
log(' [*] Parsing dcsync output from: %s' % filepath)
cred = {'nt_domain': nt_domain}
with open(filepath, 'r') as lsadump: