forked from cddmp/enum4linux-ng
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenum4linux-ng.py
More file actions
executable file
·1886 lines (1621 loc) · 77.3 KB
/
Copy pathenum4linux-ng.py
File metadata and controls
executable file
·1886 lines (1621 loc) · 77.3 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
#!/usr/bin/env python3
### ENUM4LINUX-NG
# This tool is a rewrite of Mark Lowe's (Portcullis Labs/Cisco) enum4linux.pl, a tool for
# enumerating information from Windows and Samba systems. As the original enum4linux.pl, this
# tool is mainly a wrapper around the Samba tools 'nmblookup', 'net', 'rpcclient' and 'smbclient'.
# Other than the original enum4linux.pl, enum4linux-ng parses all output of the previously mentioned
# commands and (if the user requests so), fills the data in JSON/YAML output.
# The original enum4linux.pl had the additional dependencies 'ldapsearch' and 'polenum.py'. These are
# natively implemented in enum4linux-ng. Console output is colored.
#
### CREDITS
# I'd like to thank and give credit to Mark Lowe for creating the original 'enum4linux.pl'.
# In addition, I'd like to thank and give credit to Wh1t3Fox for creating 'polenum'.
#
### DESIGN
# * Functions:
# * return value is None/False => error happened
# * return value is empty [],{},"" => no error, nothing was returned
# * YAML/JSON:
# * something is missing => was not part of the enumeration OR an error happened, check
# errors entry in JSON/YAML file
### PYLINT
# pylint: disable=C0301
#
### FIXME
# FIXME: Not sure if the run_something stuff is too crappy,
# FIXME: equal output for users, groups and rid_cycling
# FIXME: services via 'net rpc service list -W bla -U % -I ip'
# FIXME: Handle NT_STATUS... message in one function
#
### LICENSE
# This tool may be used for legal purposes only. Users take full responsibility
# for any actions performed using this tool. The author accepts no liability
# for damage caused by this tool. If these terms are not acceptable to you, then
# you are not permitted to use this tool.
#
# In all other respects the GPL version 3 applies.
#
# The original enum4linux.pl was released under GPL version 2 or later.
# The original polenum.py was released under GPL version 3.
import argparse
import json
import os
import random
import re
import shutil
import shlex
import subprocess
import sys
from collections import OrderedDict
from time import gmtime, strftime, time
from impacket.dcerpc.v5.rpcrt import DCERPC_v5
from impacket.dcerpc.v5 import transport, samr
from ldap3 import Server, Connection, DSA
import yaml
###############################################################################
# The following mappings for nmblookup (nbtstat) status codes to human readable
# format is taken from nbtscan 1.5.1 "statusq.c". This file in turn
# was derived from the Samba package which contains the following
# license:
# Unix SMB/Netbios implementation
# Version 1.9
# Main SMB server routine
# Copyright (C) Andrew Tridgell 1992-199
#
# This program is free software; you can redistribute it and/or modif
# it under the terms of the GNU General Public License as published b
# the Free Software Foundation; either version 2 of the License, o
# (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 o
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th
# GNU General Public License for more details
#
# You should have received a copy of the GNU General Public Licens
# along with this program; if not, write to the Free Softwar
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA
CONST_NBT_INFO = [
["__MSBROWSE__", "01", False, "Master Browser"],
["INet~Services", "1C", False, "IIS"],
["IS~", "00", True, "IIS"],
["", "00", True, "Workstation Service"],
["", "01", True, "Messenger Service"],
["", "03", True, "Messenger Service"],
["", "06", True, "RAS Server Service"],
["", "1F", True, "NetDDE Service"],
["", "20", True, "File Server Service"],
["", "21", True, "RAS Client Service"],
["", "22", True, "Microsoft Exchange Interchange(MSMail Connector)"],
["", "23", True, "Microsoft Exchange Store"],
["", "24", True, "Microsoft Exchange Directory"],
["", "30", True, "Modem Sharing Server Service"],
["", "31", True, "Modem Sharing Client Service"],
["", "43", True, "SMS Clients Remote Control"],
["", "44", True, "SMS Administrators Remote Control Tool"],
["", "45", True, "SMS Clients Remote Chat"],
["", "46", True, "SMS Clients Remote Transfer"],
["", "4C", True, "DEC Pathworks TCPIP service on Windows NT"],
["", "52", True, "DEC Pathworks TCPIP service on Windows NT"],
["", "87", True, "Microsoft Exchange MTA"],
["", "6A", True, "Microsoft Exchange IMC"],
["", "BE", True, "Network Monitor Agent"],
["", "BF", True, "Network Monitor Application"],
["", "03", True, "Messenger Service"],
["", "00", False, "Domain/Workgroup Name"],
["", "1B", True, "Domain Master Browser"],
["", "1C", False, "Domain Controllers"],
["", "1D", True, "Master Browser"],
["", "1E", False, "Browser Service Elections"],
["", "2B", True, "Lotus Notes Server Service"],
["IRISMULTICAST", "2F", False, "Lotus Notes"],
["IRISNAMESERVER", "33", False, "Lotus Notes"],
['Forte_$ND800ZA', "20", True, "DCA IrmaLan Gateway Server Service"]
]
# ACB (Account Control Block) contains flags an SAM account
CONST_ACB_DICT = {
0x00000001: "Account Disabled",
0x00000200: "Password not expired",
0x00000400: "Account locked out",
0x00020000: "Password expired",
0x00000040: "Interdomain trust account",
0x00000080: "Workstation trust account",
0x00000100: "Server trust account",
0x00002000: "Trusted for delegation"
}
# Source: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/d275ab19-10b0-40e0-94bb-45b7fc130025
CONST_DOMAIN_FIELDS = {
0x00000001: "DOMAIN_PASSWORD_COMPLEX",
0x00000002: "DOMAIN_PASSWORD_NO_ANON_CHANGE",
0x00000004: "DOMAIN_PASSWORD_NO_CLEAR_CHANGE",
0x00000008: "DOMAIN_PASSWORD_LOCKOUT_ADMINS",
0x00000010: "DOMAIN_PASSWORD_PASSWORD_STORE_CLEARTEXT",
0x00000020: "DOMAIN_PASSWORD_REFUSE_PASSWORD_CHANGE"
}
CONST_DEPS = ["nmblookup", "net", "rpcclient", "smbclient"]
CONST_RID_RANGES = "500-550,1000-1050"
CONST_KNOWN_USERNAMES = "administrator,guest,krbtgt,domain admins,root,bin,none"
CONST_TIMEOUT = 2
# global_verbose is the only global variable which should be written to
global_verbose = False
class Colors:
reset = '\033[0m'
red = '\033[91m'
green = '\033[92m'
blue = '\033[94m'
class Result:
'''
The idea of the Result class is, that functions can easily return a return value
as well as a return message. The return message can be further processed or printed
out by the calling function, while the return value is supposed to be added to the
output dictionary (contained in class Output), which will be later converted to JSON/YAML.
'''
def __init__(self, retval, retmsg):
self.retval = retval
self.retmsg = retmsg
class Target:
'''
Target encapsulated target information like host name or ip, workgroup name, port number
or whether Transport Layer Security (TLS) is used or not.
'''
def __init__(self, host, workgroup, port=None, timeout=None, tls=None):
self.host = host
self.port = port
self.workgroup = workgroup
self.timeout = timeout
self.tls = tls
class Credentials:
'''
Stores username and password.
'''
def __init__(self, user, pw):
# Create an alternative user with pseudo-random username
self.random_user = ''.join(random.choice("abcdefghijklmnopqrstuvwxyz") for i in range(8))
self.user = user
self.pw = pw
class Output:
'''
Output stores the output dictionary which will be filled out during the run of
the tool. The update() function takes a dictionary, which will then be merged
into the output dictionary (out_dict). In addition, the update() function is
responsible for writing the JSON/YAML output.
'''
def __init__(self, out_file=None, out_file_type=None):
self.out_file = out_file
self.out_file_type = out_file_type
self.out_dict = OrderedDict({"errors":{}})
def update(self, content):
# The following is needed, since python3 does not support nested merge of
# dictionaries out of the box:
# Temporarily save the "errors" sub dict. This will make sure we don't lose
# any errors from previous module runs.
errors_dict = self.out_dict["errors"]
# Overwrite all sub dicts in out_dict (e.g. "users" or "groups") with the
# updated ones. Here we would normally lose all errors, if "content" had
# an "errors" dict.
self.out_dict.update(content)
# Make sure "errors" is the last sub dict in out_dict. This is just needed
# for nice JSON/YAML output.
self.out_dict.move_to_end("errors")
# Finally check, did the last module run produce errors?
# If so, merge the error dicts and append the result to out_dict.
if "errors" in content:
errors = {**errors_dict, **content["errors"]}
self.out_dict["errors"] = errors
if self.out_file is not None:
try:
f = open(self.out_file, 'w')
if self.out_file_type == "json":
f.write(json.dumps(self.out_dict, indent=4))
elif self.out_file_type == "yaml":
f.write(yaml.dump(self.out_dict))
f.close()
except:
abort(1, "An error happened trying go write to {}. Exiting.".format(self.out_file))
def as_dict(self):
return self.out_dict
class RidCycleParams:
'''
Stores the various parameters needed for RID cycling. rid_ranges and known_usernames are mandatory.
enumerated_input is a dictionary which contains already enumerated input like "users,
"groups", "machines" and/or a domain sid. By default enumerated_input is an empty dict
and will be filled up during the tool run.
'''
def __init__(self, rid_ranges, known_usernames):
self.rid_ranges = rid_ranges
self.known_usernames = known_usernames
self.enumerated_input = {}
def set_enumerated_input(self, enum_input):
for key in ["users", "groups", "machines"]:
if key in enum_input:
self.enumerated_input[key] = enum_input[key]
else:
self.enumerated_input[key] = {}
if "domain_sid" in enum_input:
self.enumerated_input["domain_sid"] = enum_input["domain_sid"]
else:
self.enumerated_input["domain_sid"] = ""
class ShareBruteParams:
'''
Stores the various parameters needed for Share Bruteforcing. shares_file is mandatory.
enumerated_input is a dictionary which contains already enumerated shares. By default
enumerated_input is an empty dict and will be filled up during the tool run.
'''
def __init__(self, shares_file):
self.shares_file = shares_file
self.enumerated_input = {}
def set_enumerated_input(self, enum_input):
if "shares" in enum_input:
self.enumerated_input["shares"] = enum_input["shares"]
else:
self.enumerated_input["shares"] = {}
def print_heading(text):
output = "| {} |".format(text)
length = len(output)
print()
print(" " + "="*(length-2))
print(output)
print(" " + "="*(length-2))
def print_success(msg):
print("{}[+] {} {}".format(Colors.green, msg, Colors.reset))
def print_error(msg):
print("{}[-] {} {}".format(Colors.red, msg, Colors.reset))
def print_info(msg):
print("{}[*] {} {}".format(Colors.blue, msg, Colors.reset))
def print_verbose(msg):
print("[V] {}".format(msg))
def process_error(msg, module_name, output_dict):
'''
Helper function to print error and update output dictionary at the same time.
'''
print_error(msg)
if not "errors" in output_dict:
output_dict["errors"] = {}
if not module_name in output_dict["errors"]:
output_dict["errors"] = {module_name: []}
output_dict["errors"][module_name] += [msg]
return output_dict
def abort(code, msg):
'''
This function is used to abort() the tool run on error. It will take a status code
as well as an error message. The error message will be printed out, the status code will
be used as exit code.
'''
print_error(msg)
sys.exit(code)
def run_nmblookup(host):
'''
Runs nmblookup (a NetBIOS over TCP/IP Client) in order to lookup NetBIOS names information.
'''
command = ["nmblookup", "-A", host]
nmblookup_result = run(command, "Trying to get NetBIOS names information")
if "No reply from {}".format(host) in nmblookup_result:
return Result(None, "Could not get NetBIOS names information via nmblookup: host does not reply")
return Result(nmblookup_result, "")
def get_workgroup_from_nmblookup(nmblookup_result):
'''
Extract workgroup from given nmblookoup result.
'''
match = re.search(r"^\s+(\S+)\s+<00>\s+-\s+<GROUP>\s+", nmblookup_result, re.MULTILINE)
if match:
if valid_workgroup(match.group(1)):
workgroup = match.group(1)
else:
return Result(None, "Workgroup {} contains some illegal characters".format(workgroup))
else:
return Result(None, "Could not find workgroup/domain")
return Result(workgroup, "Got domain/workgroup name: {}".format(workgroup))
def nmblookup_to_human(nmblookup_result):
'''
Map nmblookup output to human readable strings.
'''
output = []
nmblookup_result = nmblookup_result.splitlines()
for line in nmblookup_result:
if "Looking up status of" in line or line == "":
continue
line = line.replace("\t", "")
match = re.match(r"^(\S+)\s+<(..)>\s+-\s+?(<GROUP>)?\s+?[A-Z]", line)
if match:
line_val = match.group(1)
line_code = match.group(2).upper()
line_group = False if match.group(3) else True
for entry in CONST_NBT_INFO:
pattern, code, group, desc = entry
if pattern:
if pattern in line_val and line_code == code and line_group == group:
output.append(line + " " + desc)
break
else:
if line_code == code and line_group == group:
output.append(line + " " + desc)
break
else:
output.append(line)
return Result(output, "Full NetBIOS names information:\n{}".format(yaml.dump(output).rstrip()))
def check_session(target, creds, random_user_session=False):
'''
Tests access to the IPC$ share.
General explanation:
The Common Internet File System(CIFS/Server Message Block (SMB) protocol specifies
mechanisms for interprocess communication over the network. This is called a named pipe.
In order to be able to "talk" to these named pipes, a special share named "IPC$" is provided.
SMB clients can access named pipes by using this share. Older Windows versions supported
anonymous access to this share (empty username and password), which is called a "null sessions".
This is a security vulnerability since it allows to gain valuable information about the host
system.
How the test works:
In order to test for a null session, the smbclient command is used, by tring to connect to the
IPC$ share. If that works, smbclient's 'help' command will be run. If the login was successfull,
the help command will return a list of possible commands. One of these commands is called
'case_senstive'. We search for this command as an indicator that the IPC session was setup correctly.
'''
if random_user_session:
user = creds.random_user
pw = ''
session_type = "random user"
elif not creds.user and not creds.pw:
user = ''
pw = ''
session_type = "null"
else:
user = creds.user
pw = creds.pw
session_type = "user"
command = ['smbclient', '-W', target.workgroup, '//{}/ipc$'.format(target.host), '-U', '{}%{}'.format(user, pw), '-c', 'help']
session_output = run(command, "Attempting to make session")
match = re.search(r"do_connect:.*failed\s\(Error\s([^)]+)\)", session_output)
if match:
error_code = match.group(1)
return Result(None, "Server connection failed for {} session: {}".format(session_type, error_code))
if "case_sensitive" in session_output:
return Result(True, "Server allows session using username '{}', password '{}'".format(user, pw))
return Result(False, "Server doesn't allow session using username '{}', password '{}'".format(user, pw))
#FIXME: The code snippet below is a 1:1 translation from the original perl code.
# I tested the code against various machines. The smbclient command output
# will never contain a "Domain=.*" string. I still left it in here, in case
# I have something overlooked.
#if not workgroup:
# match = re.search("Domain=\[([^]]*)\]",session_output)
# if match and valid_workgroup(match.group[1]):
# workgroup = match.group[1]
# print(f"[+] Got domain/workgroup name: {workgroup}")
def get_namingcontexts(target):
'''
Tries to connect to LDAP/LDAPS. If successful, it tries to get the naming contexts from
the so called Root Directory Server Agent Service Entry (RootDSE).
'''
try:
server = Server(target.host, use_ssl=target.tls, get_info=DSA, connect_timeout=target.timeout)
ldap_con = Connection(server, auto_bind=True)
ldap_con.unbind()
except Exception as e:
error = str(e.args[1][0][0])
if "]" in error:
error = error.split(']', 1)[1]
elif ":" in error:
error = error.split(':', 1)[1]
error = error.lstrip().rstrip()
if target.tls:
return Result(None, "LDAPS connect error: {}".format(error))
return Result(None, "LDAP connect error: {}".format(error))
try:
if not server.info.naming_contexts:
return Result([], "NamingContexts are not readable")
except Exception as e:
return Result([], "NamingContexts are not readable")
return Result(server.info.naming_contexts, "")
def check_parent_dc(namingcontexts_result):
'''
Checks whether the target is a parent or child domain controller.
This is done by searching for specific naming contexts.
'''
parent = False
if "DC=DomainDnsZones" or "ForestDnsZones" in namingcontexts_result:
parent = True
if parent:
return Result(True, "Appears to be root/parent DC")
return Result(False, "Appears to be child DC")
def get_long_domain(namingcontexts_result):
'''
Tries to extract the long domain from the naming contexts.
'''
long_domain = ""
for entry in namingcontexts_result:
match = re.search("(DC=[^,]+,DC=[^,]+)$", entry)
if match:
long_domain = match.group(1)
long_domain = long_domain.replace("DC=", "")
long_domain = long_domain.replace(",", ".")
break
if long_domain:
return Result(long_domain, "Long domain name is: {}".format(long_domain))
return Result(None, "Could not find long domain")
def run_lsaquery(target, creds):
'''
Uses the rpcclient command to connect to the named pipe LSARPC (Local Security Authority Remote Procedure Call),
which allows to do remote management of domain security policies. In this specific case, we use rpcclient's lsaquery
command. This command will do an LSA_QueryInfoPolicy request to get the domain name and the domain service identifier
(SID).
'''
command = ['rpcclient', '-W', target.workgroup, '-U', '{}%{}'.format(creds.user, creds.pw), target.host, '-c', 'lsaquery']
lsaquery_result = run(command, "Attempting to get domain SID")
if "NT_STATUS_LOGON_FAILURE" in lsaquery_result:
return Result(None, "Could not get domain information via lsaquery: NT_STATUS_LOGON_FAILURE")
if "NT_STATUS_ACCESS_DENIED" in lsaquery_result:
return Result(None, "Could not get domain information via lsaquery: NT_STATUS_ACCESS_DENIED")
if lsaquery_result:
return Result(lsaquery_result, "")
return Result(None, "Could not get information via lsaquery")
def check_is_part_of_workgroup_or_domain(lsaquery_result):
'''
Takes the result of rpclient's lsaquery command and tries to determine from the result whether the host
is part of a domain or workgroup.
'''
if "Domain Sid: S-0-0" in lsaquery_result:
return Result("workgroup", "[+] Host is part of a workgroup (not a domain)")
if re.search(r"Domain Sid: S-\d+-\d+-\d+-\d+-\d+-\d+", lsaquery_result):
return Result("domain", "Host is part of a domain (not a workgroup)")
return Result(False, "Could not determine if host is part of domain or part of a workgroup")
def get_workgroup_from_lsaquery(lsaquery_result):
'''
Takes the result of rpclient's lsaquery command and tries to extract the workgroup.
'''
workgroup = ""
if "Domain Name" in lsaquery_result:
match = re.search("Domain Name: (.*)", lsaquery_result)
if match:
#FIXME: Validate domain? --> See valid_workgroup()
workgroup = match.group(1)
if workgroup:
return Result(workgroup, "Domain: {}".format(workgroup))
return Result(None, "Could not get workgroup from lsaquery")
def get_domain_sid_from_lsaquery(lsaquery_result):
'''
Takes the result of rpclient's lsaquery command and tries to extract the domain SID.
'''
domain_sid = ""
match = re.search(r"Domain Sid: (S-\d+-\d+-\d+-\d+-\d+-\d+)", lsaquery_result)
if match:
domain_sid = match.group(1)
if domain_sid:
return Result(domain_sid, "SID: {}".format(domain_sid))
return Result(None, "Could not get domain SID from lsaquery")
def run_srvinfo(target, creds):
'''
Uses rpcclient's srvinfo command to connect to the named pipe SRVSVC in order to call
NetSrvGetInfo() on the target. This will return OS information (OS version, platform id,
server type).
'''
#FIXME: The code snippet below is a 1:1 translation from the original perl code.
# I tested the code against various machines. The smbclient command output
# will never contain a "Domain=.*" string. I still left it in here, in case
# I have something overlooked.
#command = ['smbclient', '-W', workgroup, f'//{host}/ipc$', '-U', f'{user}%{pw}', '-c', 'q']
#output = run(command,"Attempting to get OS information")
#match = re.search('(Domain=[^\n]+)',output)
#if match:
# print(f"[+] Got OS info for {host} from smbclient: {match.group(1)}")
command = ["rpcclient", "-W", target.workgroup, '-U', '{}%{}'.format(creds.user, creds.pw), '-c', 'srvinfo', target.host]
srvinfo_result = run(command, "Attempting to get OS info with command")
if "NT_STATUS_ACCESS_DENIED" in srvinfo_result:
return Result(None, "Could not get OS info with srvinfo: NT_STATUS_ACCESS_DENIED")
if "NT_STATUS_LOGON_FAILURE" in srvinfo_result:
return Result(None, "Could not get OS info with srvinfo: NT_STATUS_LOGON_FAILURE")
return Result(srvinfo_result, "")
# FIXME: Evaluate server_type_string
def get_os_info(srvinfo_result):
'''
Takes the result of rpcclient's srvinfo command and tries to extract information like
platform_id, os version and server type.
'''
search_pattern_list = ["platform_id", "os version", "server type"]
os_info = {}
first = True
for line in srvinfo_result.splitlines():
if first:
match = re.search(r"\s+[^\s]+\s+(.*)", line)
if match:
os_info['server_type_string'] = match.group(1)
first = False
for search_pattern in search_pattern_list:
match = re.search(r"\s+{}\s+:\s+(.*)".format(search_pattern), line)
if match:
# os version => os_version, server type => server_type
search_pattern = search_pattern.replace(" ", "_")
os_info[search_pattern] = match.group(1)
if not os_info:
return Result(None, "Could not get OS information")
retmsg = "The following OS information were found:\n"
for key, value in os_info.items():
retmsg += ("{0: <18} = {}\n".format(key, value))
retmsg = retmsg.rstrip()
return Result(os_info, retmsg)
def run_querydispinfo(target, creds):
'''
querydispinfo uses the Security Account Manager Remote Protocol (SAMR) named pipe to run the QueryDisplayInfo() request.
This request will return users with their corresponding Relative ID (RID) as well as multiple account information like a
description of the account.
'''
command = ['rpcclient', '-W', target.workgroup, '-c', 'querydispinfo', '-U', '{}%{}'.format(creds.user, creds.pw), target.host]
querydispinfo_result = run(command, "Attempting to get userlist")
if "NT_STATUS_ACCESS_DENIED" in querydispinfo_result:
return Result(None, "Could not find users using querydispinfo: NT_STATUS_ACCESS_DENIED")
if "NT_STATUS_INVALID_PARAMETER" in querydispinfo_result:
return Result(None, "Could not find users using querydispinfo: NT_STATUS_INVALID_PARAMETER")
if "NT_STATUS_LOGON_FAILURE" in querydispinfo_result:
return Result(None, "Could not find users using querydispinfo: NT_STATUS_LOGON_FAILURE")
return Result(querydispinfo_result, "")
def run_enumdomusers(target, creds):
'''
enomdomusers command will again use the SAMR named pipe to run the EnumDomainUsers() request. This will again
return a list of users with their corresponding RID (see run_querydispinfo()). This is possible since by default
the registry key HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Lsa\\RestrictAnonymous = 0. If this is set to
1 enumeration is no longer possible.
'''
command = ["rpcclient", "-W", target.workgroup, "-c", "enumdomusers", "-U", "{}%{}".format(creds.user, creds.pw), target.host]
enumdomusers_result = run(command, "Attempting to get userlist")
if "NT_STATUS_ACCESS_DENIED" in enumdomusers_result:
return Result(None, "Could not find users using enumdomusers: NT_STATUS_ACCESS_DENIED")
if "NT_STATUS_INVALID_PARAMETER" in enumdomusers_result:
return Result(None, "Could not find users using enumdomusers: NT_STATUS_INVALID_PARAMETER")
if "NT_STATUS_LOGON_FAILURE" in enumdomusers_result:
return Result(None, "Could not find users using enumdomusers: NT_STATUS_LOGON_FAILURE")
return Result(enumdomusers_result, "")
def enum_users_from_querydispinfo(target, creds):
'''
Takes the result of rpclient's querydispinfo and tries to extract the users from it.
'''
users = {}
querydispinfo = run_querydispinfo(target, creds)
if querydispinfo.retval is None:
return querydispinfo
# Example output of rpcclient's querydispinfo:
# index: 0x2 RID: 0x3e9 acb: 0x00000010 Account: tester Name: Desc:
for line in querydispinfo.retval.splitlines():
match = re.search(r"index:\s+.*\s+RID:\s+(0x[A-F-a-f0-9]+)\s+acb:\s+(.*)\s+Account:\s+(.*)\s+Name:\s+(.*)\s+Desc:\s+(.*)", line)
if match:
rid = match.group(1)
rid = str(int(rid, 16))
acb = match.group(2)
username = match.group(3)
name = match.group(4)
description = match.group(5)
users[rid] = OrderedDict({"username":username, "name":name, "acb":acb, "description":description})
else:
return Result(None, "Could not extract users from querydispinfo output")
if users:
return Result(users, "Found {} via 'querydispinfo'".format(len(users.keys())))
return Result(users, "Got an empty response, there are no user(s) (this is not an error, there seem to be really none)")
def enum_users_from_enumdomusers(target, creds):
'''
Takes the result of rpclient's enumdomusers and tries to extract the users from it.
'''
users = {}
enumdomusers = run_enumdomusers(target, creds)
if enumdomusers.retval is None:
return enumdomusers
# Example output of rpcclient's enumdomusers:
# user:[tester] rid:[0x3e9]
for line in enumdomusers.retval.splitlines():
match = re.search(r"user:\[(.*)\]\srid:\[(0x[A-F-a-f0-9]+)\]", line)
if match:
username = match.group(1)
rid = match.group(2)
rid = str(int(rid, 16))
users[rid] = {"username":username}
else:
return Result(None, "Could not extract users from eumdomusers output")
if users:
return Result(users, "Found {} via 'enumdomusers'".format(len(users.keys())))
return Result(users, "Got an empty response, there are no user(s) (this is not an error, there seem to be really none)")
def get_user_details_from_rid(rid, target, creds):
'''
Takes an RID and makes use of the SAMR named pipe to call QueryUserInfo() on the given RID.
The output contains lots of information about the corresponding user account.
'''
if not valid_rid(rid):
return Result(None, "Invalid rid passed: {}".format(rid))
details = OrderedDict()
command = ["rpcclient", "-W", target.workgroup, "-U", "{}%{}".format(creds.user, creds.pw), "-c", "queryuser {}".format(rid), target.host]
output = run(command, "Attempting to get detailed user info")
match = re.search("([^\n]*User Name.*logon_hrs[^\n]*)", output, re.DOTALL)
if match:
user_info = match.group(1)
user_info = user_info.replace("\t", "")
for line in user_info.splitlines():
if ':' in line:
(key, value) = line.split(":", 1)
key = key.rstrip()
# Skip user and full name, we have this information already
if "User Name" in key or "Full Name" in key:
continue
details[key] = value
else:
details[line] = ""
if "acb_info" in details and valid_hex(details["acb_info"]):
for key in CONST_ACB_DICT.keys():
if int(details["acb_info"], 16) & key:
details[CONST_ACB_DICT[key]] = True
else:
details[CONST_ACB_DICT[key]] = False
return Result(details, "Found user details for user with RID {}".format(rid))
return Result(details, "Could not find user details for user with RID {}".format(rid))
def run_enum_groups(grouptype, target, creds):
'''
Tries to fetch groups via rpcclient's enumalsgroups (so called alias groups) and enumdomgroups.
Grouptype "builtin", "local" and "domain" are supported.
'''
grouptype_dict = {
"builtin":"enumalsgroups builtin",
"local":"enumalsgroups domain",
"domain": "enumdomgroups"
}
if grouptype not in ["builtin", "domain", "local"]:
return Result(None, "Unsupported grouptype, supported types are: {}".format( ','.join(grouptype_dict.keys())))
command = ["rpcclient", "-W", target.workgroup, "-U", "{}%{}".format(creds.user, creds.pw), target.host, "-c", "{}".format(grouptype_dict[grouptype])]
groups_string = run(command, "Attempting to get {} groups".format(grouptype))
if "NT_STATUS_ACCESS_DENIED" in groups_string:
return Result(None, "Could not get groups via {}: NT_STATUS_ACCESS_DENIED".format(grouptype_dict[grouptype]))
if "NT_STATUS_LOGON_FAILURE" in groups_string:
return Result(None, "Could not get groups via {}: NT_STATUS_LOGON_FAILURE".format(grouptype_dict[grouptype]))
return Result(groups_string, "")
def enum_groups(grouptype, target, creds):
'''
Tries to enumerate all groups by calling rpcclient's 'enumalsgroups builtin', 'enumalsgroups domain' as well
as 'enumdomgroups'.
'''
grouptype_dict = {
"builtin":"enumalsgroups builtin",
"local":"enumalsgroups domain",
"domain": "enumdomgroups"
}
if grouptype not in ["builtin", "domain", "local"]:
return Result(None, "Unsupported grouptype, supported types are: {}".format( ','.join(grouptype_dict.keys())))
groups = {}
enum = run_enum_groups(grouptype, target, creds)
if enum.retval is None:
return enum
if not enum.retval:
return Result({}, "Got an empty response, there no group(s) found via {} command (this is not an error, there seem to be really none)".format(grouptype_dict[grouptype]))
match = re.search("(group:.*)", enum.retval, re.DOTALL)
if not match:
return Result(None, "Could not parse result of {} command".format(grouptype_dict[grouptype]))
# Example output of rpcclient's group commands:
# group:[RAS and IAS Servers] rid:[0x229]
for line in enum.retval.splitlines():
match = re.search(r"group:\[(.*)\]\srid:\[(0x[A-F-a-f0-9]+)\]", line)
if match:
groupname = match.group(1)
rid = match.group(2)
rid = str(int(rid, 16))
groups[rid] = OrderedDict({"groupname":groupname, "type":grouptype})
else:
return Result(None, "Could not extract groups from {} output".format(grouptype_dict[grouptype]))
if groups:
return Result(groups, "Found {} groups via '{}'".format(len(groups.keys()), grouptype_dict[grouptype]))
return Result(groups, "Got an empty response, there are no group(s) (this is not an error, there seem to be really none)")
def get_group_members_from_name(groupname, target, creds):
'''
Takes a group name as first argument and tries to enumerate the group members. This is don by using
the 'net rpc group members' command.
'''
command = ["net", "rpc", "group", "members", groupname, "-W", target.workgroup, "-I", target.host, "-U", "{}%{}".format(creds.user, creds.pw)]
members_string = run(command, "Attempting to get group memberships for group {}".format(groupname))
members = []
for member in members_string.splitlines():
if "Couldn't lookup SIDs" in member:
return Result(None, "Members lookup failed for group '{}' due to insufficient user permissions, try a different user".format(groupname))
members.append(member)
if members:
return Result(','.join(members), "Found {} member(s) for group '{}'".format(len(members), groupname))
return Result('', "Could not find members for group '{}'".format(groupname))
def get_group_details_from_rid(rid, target, creds):
'''
Takes an RID and makes use of the SAMR named pipe to open the group with OpenGroup() on the given RID.
'''
if not valid_rid(rid):
return Result(None, "Invalid rid passed: {}".format(rid))
details = OrderedDict()
command = ["rpcclient", "-W", target.workgroup, "-U", '{}%{}'.format(creds.user, creds.pw), "-c", "querygroup {}".format(rid), target.host]
output = run(command, "Attempting to get detailed group info")
#FIXME: Only works for domain groups, otherwise NT_STATUS_NO_SUCH_GROUP is returned
match = re.search("([^\n]*Group Name.*Num Members[^\n]*)", output, re.DOTALL)
if match:
group_info = match.group(1)
group_info = group_info.replace("\t", "")
for line in group_info.splitlines():
if ':' in line:
(key, value) = line.split(":", 1)
# Skip group name, we have this information already
if "Group Name" in key:
continue
details[key] = value
else:
details[line] = ""
return Result(details, "Found group details for group with RID {}".format(rid))
return Result(details, "Could not find group details for group with RID {}".format(rid))
def check_share_access(share, target, creds):
'''
Takes a share as first argument and checks whether the share is accessible.
The function returns a dictionary with the keys "mapping" and "listing".
"mapping" can be either OK or DENIED. OK means the share exists and is accessible.
"listing" can bei either OK, DENIED, N/A or NOT SUPPORTED. N/A means directory listing
is not allowed, while NOT SUPPORTED means the share does not support listing at all.
This is the case for shares like IPC$ which is used for remote procedure calls.
'''
command = ["smbclient", "-W", target.workgroup, "//{}/{}".format(target.host, share), "-U", "{}%{}".format(creds.user, creds.pw), "-c", "dir"]
output = run(command, "Attempting to map share //{}/{}".format(target.host, share))
if "NT_STATUS_BAD_NETWORK_NAME" in output:
return Result(None, "Share doesn't exist")
if "NT_STATUS_ACCESS_DENIED listing" in output:
return Result({"mapping":"ok", "listing":"denied"}, "Mapping: OK, Listing: DENIED")
if "tree connect failed: NT_STATUS_ACCESS_DENIED" in output:
return Result({"mapping":"denied", "listing":"n/a"}, "Mapping: DENIED, Listing: N/A")
if "NT_STATUS_INVALID_INFO_CLASS" in output:
return Result({"mapping":"ok", "listing":"not supported"}, "Mapping: OK, Listing: NOT SUPPORTED")
if re.search(r"\n\s+\.\.\s+D.*\d{4}\n", output):
return Result({"mapping":"ok", "listing":"ok"}, "Mapping: OK, Listing: OK")
if "NT_STATUS_OBJECT_NAME_NOT_FOUND" in output:
return Result(None, "Could not check share: NT_STATUS_OBJECT_NAME_NOT_FOUND")
if "NT_STATUS_INVALID_PARAMETER" in output:
return Result(None, "Could not check share: NT_STATUS_INVALID_PARAMETER")
return Result(None, "Could not understand smbclient response")
def enum_shares(target, creds):
'''
Tries to enumerate shares with the given username and password. It does this running the smbclient command.
smbclient will open a connection to the Server Service Remote Protocol named pipe (srvsvc). Once connected
it calls the NetShareEnumAll() to get a list of shares.
For the list of resulting shares, smbclient is used again with the "dir" command. In the background this will
send an SMB I/O Control (IOCTL) request in order to list the contents of the share.
'''
command = ["smbclient", "-W", target.workgroup, "-L", "//{target.host}".format(target.host), "-U", "{}%{}".format(creds.user, creds.pw)]
shares_result = run(command, "Attempting to get share list using authentication")
if "NT_STATUS_ACCESS_DENIED" in shares_result:
return Result(None, "Could not list shares: NT_STATUS_ACCESS_DENIED")
shares = {}
match_list = re.findall(r"\n\s*([ \S]+?)\s+(?:Disk|IPC|Printer)", shares_result, re.IGNORECASE)
if match_list:
for share in match_list:
shares[share] = {}
if shares:
return Result(shares, "Found {} share(s): {}".format(len(shares.keys()), ','.join(shares.keys())))
return Result(None, "No shares found for user '{}' with password '{}', try a different user".format(creds.user, creds.pw))
def enum_sids(users, target, creds):
'''
Tries to enumerate SIDs by looking up user names via rpcclient's lookupnames and by using rpcclient's lsaneumsid.
'''
sids = []
sid_patterns_list = [r"(S-1-5-21-[\d-]+)-\d+", r"(S-1-5-[\d-]+)-\d+", r"(S-1-22-[\d-]+)-\d+"]
# Try to get a valid SID from well-known user names
for known_username in users:
command = ["rpcclient", "-W", target.workgroup, "-U", "{}%{}".format(creds.user, creds.pw), target.host, "-c", "lookupnames {}".format(known_username)]
sid_string = run(command, "Attempting to get SID for user {}".format(known_username))
if "NT_STATUS_ACCESS_DENIED" or "NT_STATUS_NONE_MAPPED" in sid_string:
continue
for pattern in sid_patterns_list:
match = re.search(pattern, sid_string)
if match:
result = match.group(1)
if result not in sids:
sids.append(result)
# Try to get SID list via lsaenumsid
command = ["rpcclient", "-W", target.workgroup, "-U", "{}%{}".format(creds.user, creds.pw), "-c", "lsaenumsid", target.host]
sids_string = run(command, "Attempting to get SIDs via lsaenumsid")
if "NT_STATUS_ACCESS_DENIED" not in sids_string:
for pattern in sid_patterns_list:
match_list = re.findall(pattern, sids_string)
for result in match_list:
if result not in sids:
sids.append(result)
if sids:
return Result(sids, "Found {} SIDs".format(len(sids)))
return Result(None, "Could not get any SIDs")
def prepare_rid_ranges(rid_ranges):
'''
Takes a string containing muliple RID ranges and returns a list of ranges as tuples.
'''
rid_ranges_list = []
for rid_range in rid_ranges.split(','):
if rid_range.isdigit():
start_rid = rid_range
end_rid = rid_range
else:
[start_rid, end_rid] = rid_range.split("-")
start_rid = int(start_rid)
end_rid = int(end_rid)
# Reverse if neccessary
if start_rid > end_rid:
start_rid, end_rid = end_rid, start_rid
rid_ranges_list.append((start_rid, end_rid))
return rid_ranges_list
def rid_cycle(sid, rid_ranges, target, creds):
'''
Takes a SID as first parameter well as list of RID ranges (as tuples) as second parameter and does RID cycling.
'''
for rid_range in rid_ranges:
(start_rid, end_rid) = rid_range
for rid in range(start_rid, end_rid):
command = ["rpcclient", "-W", target.workgroup, "-U", "{}%{}".format(creds.user, creds.pw), target.host, "-c", "lookupsids {}-{}".format(sid, rid)]
output = run(command, "RID Cycling")
# Example: S-1-5-80-3139157870-2983391045-3678747466-658725712-1004 *unknown*\*unknown* (8)
match = re.search(r"(S-\d+-\d+-\d+-[\d-]+\s+(.*)\s+[^\)]+\))", output)
if match:
sid_and_user = match.group(1)
entry = match.group(2)
# Samba servers sometimes claim to have user accounts
# with the same name as the UID/RID. We don't report these.
if re.search(r"-(\d+) .*\\\1 \(", sid_and_user):
continue
# "(1)" = User, "(2)" = Domain Group,"(3)" = Domain SID,"(4)" = Local Group
# "(5)" = Well-known group, "(6)" = Deleted account, "(7)" = Invalid account
# "(8)" = Unknown, "(9)" = Machine/Computer account
if "(1)" in sid_and_user:
yield Result({"users":{str(rid):{"username":entry}}}, "Found user {}".format(entry))
elif "(2)" in sid_and_user:
yield Result({"groups":{str(rid):{"groupname":entry, "type":"domain"}}}, "Found domain group {}".format(entry))
elif "(3)" in sid_and_user:
yield Result({"domain_sid":"{}-{}".format(sid, rid)}, "Found domain SID {}-{}".format(sid, rid))
elif "(4)" in sid_and_user:
yield Result({"groups":{str(rid):{"groupname":entry, "type":"builtin"}}}, "Found builtin group {}".format(entry))
elif "(9)" in sid_and_user:
yield Result({"machines":{str(rid):{"machine":entry}}}, "Found machine {}".format(entry))
def enum_printers(target, creds):
'''
Tries to enum printer via rpcclient's enumprinters.
'''
command = ["rpcclient", "-W", target.workgroup, "-U", "{}%{}".format(creds.user, creds.pw), "-c", "enumprinters", target.host]
printer_info = run(command, "Attempting to get printer info")
printers = {}
if "NT_STATUS_OBJECT_NAME_NOT_FOUND" in printer_info:
return Result("", "No printer available")