/
enum4linux-ng.py
executable file
·2704 lines (2294 loc) · 112 KB
/
enum4linux-ng.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
#!/usr/bin/env python3
# pylint: disable=C0301, E1101
### ENUM4LINUX-NG
# This tool is a rewrite of Mark Lowe's (former Portcullis Labs, now Cisco CX Security Labs ) 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 (can be deactivated by setting the
# environment variable NO_COLOR to an arbitrary value).
#
### CREDITS
# I'd like to thank and give credit to the people at former Portcullis Labs (now Cisco CX Security Labs), namely:
#
# - Mark Lowe for creating the original 'enum4linux.pl'
# https://github.com/CiscoCXSecurity/enum4linux
#
# - Richard "deanx" Dean for creating the original 'polenum'
# https://labs.portcullis.co.uk/tools/polenum/
#
# In addition, I'd like to thank and give credit to:
# - Craig "Wh1t3Fox" West for his fork of 'polenum'
# https://github.com/Wh1t3Fox/polenum
#
#
### DESIGN
#
# Error handling
# ==============
#
# * Functions:
# * return value is None
# => an error happened, error messages will be printed out and will end up in the JSON/YAML with value
# null (see also YAML/JSON below)
#
# * return value is False for...
# ...'session_possible'
# => error, it was not possible to setup a session with the target, therefore any subsequent module runs were
# omitted
# * ...'services'-->'accessible'
# => error, it was not possible to setup a service connection
# => all other booleans are not errors
#
# * return value is empty [],{},""
# => no error, nothing was returned (e.g. a group has no members)
#
# * YAML/JSON:
# * null
# => an error happened (see above, a function returned None which translates to null in JSON/YAML) - in
# this case an error message was generated and can be found under:
# 'errors' -> key for which the error happened (e.g. os_info) -> module name where the error occured
# (e.g. module_srvinfo)
#
# * missing key
# => either it was not part of the enumeration because the user did not request it (aka did not provide
# the right parameter when running enum4linux-ng)
# => or it was part of the enumeration but no session could be set up (see above), in this case the
# 'session_possible' should be 'False'
#
### 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.
from argparse import ArgumentParser
from collections import OrderedDict
from datetime import datetime
import json
import os
import random
import re
import shutil
import shlex
import socket
from subprocess import check_output, STDOUT, TimeoutExpired
import sys
import tempfile
from impacket import nmb, smb, smbconnection, smb3, nt_errors
from impacket.smbconnection import SMB_DIALECT
from impacket.dcerpc.v5.rpcrt import DCERPC_v5
from impacket.dcerpc.v5 import transport, samr
from ldap3 import Server, Connection, DSA
import yaml
try:
from yaml import CDumper as Dumper
except ImportError:
from yaml import Dumper
###############################################################################
# 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
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
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
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"
}
# Source: https://docs.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version
OS_VERSIONS = {
"10.0": "Windows 10, Windows Server 2019, Windows Server 2016",
"6.3": "Windows 8.1, Windows Server 2012 R2",
"6.2": "Windows 8, Windows Server 2012",
"6.1": "Windows 7, Windows Server 2008 R2",
"6.0": "Windows Vista, Windows Server 2008",
"5.2": "Windows XP 64-Bit Edition, Windows Server 2003, Windows Server 2003 R2",
"5.1": "Windows XP",
"5.0": "Windows 2000",
}
# Filter for various samba client setup related error messages including bug
# https://bugzilla.samba.org/show_bug.cgi?id=13925
SAMBA_CLIENT_ERRORS = [
"Unable to initialize messaging context",
"WARNING: no network interfaces found",
"Can't load /etc/samba/smb.conf - run testparm to debug it"
]
# This list will be used by the function nt_status_error_filter() which is typically
# called after running a Samba client command (see run()). The idea is to filter out
# common errors. For very specific status errors, please don't handle them here but
# in the corresponding enumeration class/function.
NT_STATUS_COMMON_ERRORS = [
"STATUS_ACCESS_DENIED",
"STATUS_LOGON_FAILURE",
"STATUS_IO_TIMEOUT",
"STATUS_NETWORK_UNREACHABLE",
"STATUS_INVALID_PARAMETER",
"STATUS_NOT_SUPPORTED",
# This is a rather strange status which needs more examination and might be
# removed from here in the future.
"STATUS_CONNECTION_DISCONNECTED",
"WERR_ACCESS_DENIED"
]
# Mapping from errno to string for socket errors we often come across
SOCKET_ERRORS = {
11: "timed out",
110: "timed out",
111: "connection refused",
113: "no route to host"
}
# This is needed for the ServiceScan class
SERVICE_LDAP = "LDAP"
SERVICE_LDAPS = "LDAPS"
SERVICE_SMB = "SMB"
SERVICE_SMB_NETBIOS = "SMB over NetBIOS"
SERVICES = {
SERVICE_LDAP: 389,
SERVICE_LDAPS: 636,
SERVICE_SMB: 445,
SERVICE_SMB_NETBIOS: 139
}
# The current list of module names
ENUM_LDAP_DOMAIN_INFO = "enum_ldap_domain_info"
ENUM_NETBIOS = "enum_netbios"
ENUM_SMB = "enum_smb"
ENUM_SESSIONS = "enum_sessions"
ENUM_LSAQUERY_DOMAIN_INFO = "enum_lsaquery_domain_info"
ENUM_USERS_RPC = "enum_users_rpc"
ENUM_GROUPS_RPC = "enum_groups_rpc"
ENUM_SERVICES = "services_check"
ENUM_SHARES = "enum_shares"
ENUM_SERVICES = "enum_services"
ENUM_POLICY = "enum_policy"
ENUM_PRINTERS = "enum_printers"
ENUM_OS_INFO = "enum_os_info"
RID_CYCLING = "rid_cycling"
BRUTE_FORCE_SHARES = "brute_force_shares"
DEPS = ["nmblookup", "net", "rpcclient", "smbclient"]
RID_RANGES = "500-550,1000-1050"
KNOWN_USERNAMES = "administrator,guest,krbtgt,domain admins,root,bin,none"
TIMEOUT = 5
# global_verbose and global_colors should be the only variables which should be written to
global_verbose = False
global_colors = True
class Colors:
ansi_reset = '\033[0m'
ansi_red = '\033[91m'
ansi_green = '\033[92m'
ansi_yellow = '\033[93m'
ansi_blue = '\033[94m'
@classmethod
def red(cls, msg):
if global_colors:
return f"{cls.ansi_red}{msg}{cls.ansi_reset}"
return msg
@classmethod
def green(cls, msg):
if global_colors:
return f"{cls.ansi_green}{msg}{cls.ansi_reset}"
return msg
@classmethod
def yellow(cls, msg):
if global_colors:
return f"{cls.ansi_yellow}{msg}{cls.ansi_reset}"
return msg
@classmethod
def blue(cls, msg):
if global_colors:
return f"{cls.ansi_blue}{msg}{cls.ansi_reset}"
return msg
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 encapsulates various target information. The class should only be instantiated once and
passed during the enumeration to the various modules. This allows to modify/update target information
during enumeration.
'''
def __init__(self, host, workgroup, port=None, timeout=None, tls=None, samba_config=None, sessions=False):
self.host = host
self.port = port
self.workgroup = workgroup
self.timeout = timeout
self.tls = tls
self.samba_config = samba_config
self.sessions = sessions
self.workgroup_from_long_domain = False
self.ip_version = None
self.smb_ports = []
self.ldap_ports = []
self.services = []
if not self.valid_host(host):
raise Exception()
def update_workgroup(self, workgroup, long_domain=False):
# Occassionally lsaquery would return a slightly different domain name than LDAP, e.g.
# MYDOMAIN vs. MY-DOMAIN. It is unclear what the impact of using one or the other is for
# subsequent enumeration steps.
# For now we prefer the domain name from LDAP ("long domain") over the domain/workgroup
# discovered by lsaquery or others.
if self.workgroup_from_long_domain:
return
if long_domain:
self.workgroup = workgroup.split('.')[0]
self.workgroup_from_long_domain = True
else:
self.workgroup = workgroup
def valid_host(self, host):
try:
result = socket.getaddrinfo(host, None)
if result[0][0] == socket.AF_INET6:
self.ip_version = 6
return True
if result[0][0] == socket.AF_INET:
self.ip_version = 4
return True
except:
pass
return False
def as_dict(self):
return {'target':{'host':self.host, 'workgroup':self.workgroup}}
class Credentials:
'''
Stores usernames 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
def as_dict(self):
return {'credentials':OrderedDict({'user':self.user, 'password':self.pw, 'random_user':self.random_user})}
class SambaConfig:
'''
Allows to create custom Samba configurations which can be passed via path to the various Samba client tools.
Currently such a configuration is always created on tool start. This allows to overcome issues with newer
releases of the Samba client tools where certain features are disabled by default.
'''
def __init__(self, entries):
config = '\n'.join(['[global]']+entries) + '\n'
config_file = tempfile.NamedTemporaryFile(delete=False)
config_file.write(config.encode())
self.config_filename = config_file.name
config_file.close()
def get_path(self):
return self.config_filename
def add(self, entries):
try:
config = '\n'.join(entries) + '\n'
config_file = open(self.config_filename, 'a')
config_file.write(config)
config_file.close()
return True
except:
return False
def delete(self):
try:
os.remove(self.config_filename)
except OSError:
return Result(False, f"Could not delete samba configuration file {self.config_filename}")
return Result(True, "")
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 current "errors" sub dict. Then update out_dict with the new
# content. If "content" also had an "errors" dict (e.g. if the module run failed),
# this would overwrite the "errors" dict from the previous run. Therefore,
# we replace the old out_dict["errors"] with the saved one. A proper merge will
# then be done further down.
old_errors_dict = self.out_dict["errors"]
self.out_dict.update(content)
self.out_dict["errors"] = old_errors_dict
# Merge dicts
if "errors" in content:
new_errors_dict = content["errors"]
for key, value in new_errors_dict.items():
if key in old_errors_dict:
self.out_dict["errors"][key] = {**old_errors_dict[key], **new_errors_dict[key]}
else:
self.out_dict["errors"][key] = value
def flush(self):
# Only for nice JSON/YAML output (errors at the end)
self.out_dict.move_to_end("errors")
# Write JSON/YAML
if self.out_file is not None:
if "json" in self.out_file_type and not self._write_json():
return Result(False, f"Could not write JSON output to {self.out_file}.json")
if "yaml" in self.out_file_type and not self._write_yaml():
return Result(False, f"Could not write YAML output to {self.out_file}.yaml")
return Result(True, "")
def _write_json(self):
try:
f = open(f"{self.out_file}.json", 'w')
f.write(json.dumps(self.out_dict, indent=4))
f.close()
except OSError:
return False
return True
def _write_yaml(self):
try:
f = open(f"{self.out_file}.yaml", 'w')
f.write(yamlize(self.out_dict, rstrip=False))
f.close()
except OSError:
return False
return True
def as_dict(self):
return self.out_dict
### Service Scans
class ServiceScan():
def __init__(self, target, scan_list):
self.target = target
self.scan_list = scan_list
self.services = OrderedDict({})
def run(self):
module_name = ENUM_SERVICES
output = {}
print_heading(f"Service Scan on {self.target.host}")
for service, port in SERVICES.items():
if service not in self.scan_list:
continue
print_info(f"Checking {service}")
result = self.check_accessible(service, port)
if result.retval:
print_success(result.retmsg)
else:
output = process_error(result.retmsg, ["services"], module_name, output)
self.services[service] = {"port": port, "accessible": result.retval}
output["services"] = self.services
return output
def check_accessible(self, service, port):
if self.target.ip_version == 6:
address_family = socket.AF_INET6
elif self.target.ip_version == 4:
address_family = socket.AF_INET
try:
sock = socket.socket(address_family, socket.SOCK_STREAM)
sock.settimeout(self.target.timeout)
result = sock.connect_ex((self.target.host, port))
if result == 0:
return Result(True, f"{service} is accessible on {port}/tcp")
return Result(False, f"Could not connect to {service} on {port}/tcp: {SOCKET_ERRORS[result]}")
except Exception:
return Result(False, f"Could not connect to {service} on {port}/tcp")
def get_accessible_services(self):
accessible = []
for service, entry in self.services.items():
if entry["accessible"] is True:
accessible.append(service)
return accessible
def get_accessible_ports_by_pattern(self, pattern):
accessible = []
for service, entry in self.services.items():
if pattern in service and entry["accessible"] is True:
accessible.append(self.services[service]["port"])
return accessible
### NetBIOS Enumeration
class EnumNetbios():
def __init__(self, target):
self.target = target
def run(self):
'''
Run NetBIOS module which collects Netbios names and the workgroup.
'''
module_name = ENUM_NETBIOS
print_heading(f"NetBIOS Names and Workgroup for {self.target.host}")
output = {"workgroup":None, "nmblookup":None}
nmblookup = self.nmblookup()
if nmblookup.retval:
result = self.get_workgroup(nmblookup.retval)
if result.retval:
print_success(result.retmsg)
output["workgroup"] = result.retval
else:
output = process_error(result.retmsg, ["workgroup"], module_name, output)
result = self.nmblookup_to_human(nmblookup.retval)
print_success(result.retmsg)
output["nmblookup"] = result.retval
else:
output = process_error(nmblookup.retmsg, ["nmblookup"], module_name, output)
return output
def nmblookup(self):
'''
Runs nmblookup (a NetBIOS over TCP/IP Client) in order to lookup NetBIOS names information.
'''
command = ["nmblookup", "-A", self.target.host]
result = run(command, "Trying to get NetBIOS names information", timeout=self.target.timeout)
if not result.retval:
return Result(None, f"Could not get NetBIOS names information via 'nmblookup': {result.retmsg}")
if "No reply from" in result.retmsg:
return Result(None, "Could not get NetBIOS names information via 'nmblookup': host does not reply")
return Result(result.retmsg, "")
def get_workgroup(self, 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, f"Workgroup {workgroup} contains some illegal characters")
else:
return Result(None, "Could not find workgroup/domain")
return Result(workgroup, f"Got domain/workgroup name: {workgroup}")
def nmblookup_to_human(self, 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 = not match.group(3)
for entry in 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, f"Full NetBIOS names information:\n{yamlize(output)}")
### SMB checks
class EnumSmb():
def __init__(self, target, detailed):
self.target = target
self.detailed = detailed
def run(self):
'''
Run SMB module which checks whether only SMBv1 is supported.
'''
module_name = ENUM_SMB
print_heading(f"SMB Dialect Check on {self.target.host}")
output = {}
for port in self.target.smb_ports:
print_info(f"Check for legacy SMBv1 on {port}/tcp")
self.target.port = port
result = self.check_smb1()
if result.retval is None:
output = process_error(result.retmsg, ["smb1_only"], module_name, output)
else:
output["smb1_only"] = result.retval
print_success(result.retmsg)
break
# Does the target only support SMBv1? Then enforce it!
if result.retval:
print_info("Enforcing legacy SMBv1 for further enumeration")
result = self.enforce_smb1()
if not result.retval:
output = process_error(result.retmsg, ["smb1_only"], module_name, output)
output["smb1_only"] = result.retval
return output
def enforce_smb1(self):
try:
if self.target.samba_config.add(['client min protocol = NT1']):
return Result(True, "")
except:
pass
return Result(False, "Could not enforce SMBv1")
def check_smb1(self):
'''
Current implementations of the samba client tools will enforce at least SMBv2 by default. This will give false
negatives during session checks, if the target only supports SMBv1. Therefore, we try to find out here whether
the target system only speaks SMBv1.
'''
try:
smb_conn = smbconnection.SMBConnection(self.target.host, self.target.host, sess_port=self.target.port, timeout=self.target.timeout)
dialect = smb_conn.getDialect()
smb_conn.close()
if dialect == SMB_DIALECT:
return Result(True, "Server supports only SMBv1")
return Result(False, "Server supports dialects higher SMBv1")
except Exception as e:
if len(e.args) == 2:
if isinstance(e.args[1], ConnectionRefusedError):
return Result(None, f"SMB connection error on port {self.target.port}/tcp: Connection refused")
if isinstance(e.args[1], socket.timeout):
return Result(None, f"SMB connection error on port {self.target.port}/tcp: timed out")
if isinstance(e, nmb.NetBIOSError):
return Result(None, f"SMB connection error on port {self.target.port}/tcp: session failed")
if isinstance(e, (smb.SessionError, smb3.SessionError)):
if e.get_error_code() == nt_errors.STATUS_NOT_SUPPORTED:
return Result(False, "Server supports dialects higher SMBv1")
return Result(None, "SMB connection error: session failed")
return Result(None, f"SMB connection error on port {self.target.port}/tcp")
### Session Checks
class EnumSessions():
def __init__(self, target, creds):
self.target = target
self.creds = creds
def run(self):
'''
Run session check module which tests for user and null sessions.
'''
module_name = ENUM_SESSIONS
print_heading(f"RPC Session Check on {self.target.host}")
output = {"sessions_possible":False,
"null_session_possible":False,
"user_session_possible":False,
"random_user_session_possible":False}
# Check null session
print_info("Check for null session")
null_session = self.check_user_session(Credentials('', ''))
if null_session.retval:
output["null_session_possible"] = True
print_success(null_session.retmsg)
else:
output = process_error(null_session.retmsg, ["null_session_possible"], module_name, output)
# Check user session
if self.creds.user:
print_info("Check for user session")
user_session = self.check_user_session(self.creds)
if user_session.retval:
output["user_session_possible"] = True
print_success(user_session.retmsg)
else:
output = process_error(user_session.retmsg, ["user_session_possible"], module_name, output)
# Check random user session
print_info("Check for random user session")
user_session = self.check_user_session(self.creds, random_user_session=True)
if user_session.retval:
output["random_user_session_possible"] = True
print_success(user_session.retmsg)
print_hint(f"Rerunning enumeration with user '{self.creds.random_user}' might give more results")
else:
output = process_error(user_session.retmsg, ["random_user_session_possible"], module_name, output)
if output["null_session_possible"] or output["user_session_possible"] or output["random_user_session_possible"]:
output["sessions_possible"] = True
else:
process_error("Sessions failed, neither null nor user sessions were possible", ["sessions_possible", "null_session_possible", "user_session_possible", "random_user_session_possible"], module_name, output)
return output
def check_user_session(self, 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', '-t', f"{self.target.timeout}", '-W', self.target.workgroup, f'//{self.target.host}/ipc$', '-U', f'{user}%{pw}', '-c', 'help']
result = run(command, "Attempting to make session", self.target.samba_config)
if not result.retval:
return Result(False, f"Could not establish {session_type} session: {result.retmsg}")
if "case_sensitive" in result.retmsg:
return Result(True, f"Server allows session using username '{user}', password '{pw}'")
return Result(False, f"Could not establish session using '{user}', password '{pw}'")
### Domain Information Enumeration via LDAP
class EnumLdapDomainInfo():
def __init__(self, target):
self.target = target
def run(self):
'''
Run ldapsearch module which tries to find out whether host is a parent or
child DC. Also tries to fetch long domain name. The information are get from
the LDAP RootDSE.
'''
module_name = ENUM_LDAP_DOMAIN_INFO
print_heading(f"Domain Information via LDAP for {self.target.host}")
output = {"is_parent_dc":None,
"is_child_dc":None,
"long_domain":None}
for with_tls in [False, True]:
if with_tls:
if SERVICES[SERVICE_LDAPS] not in self.target.ldap_ports:
continue
print_info(f'Trying LDAPS')
else:
if SERVICES[SERVICE_LDAP] not in self.target.ldap_ports:
continue
print_info(f'Trying LDAP')
self.target.tls = with_tls
namingcontexts = self.get_namingcontexts()
if namingcontexts.retval is not None:
break
output = process_error(namingcontexts.retmsg, ["is_parent_dc", "is_child_dc", "long_domain"], module_name, output)
if namingcontexts.retval:
# Parent/root or child DC?
result = self.check_parent_dc(namingcontexts.retval)
if result.retval:
output["is_parent_dc"] = True
output["is_child_dc"] = False
else:
output["is_parent_dc"] = True
output["is_child_dc"] = False
print_success(result.retmsg)
# Try to get long domain from ldapsearch result
result = self.get_long_domain(namingcontexts.retval)
if result.retval:
print_success(result.retmsg)
output["long_domain"] = result.retval
else:
output = process_error(result.retmsg, ["long_domain"], module_name, output)
return output
def get_namingcontexts(self):
'''
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(self.target.host, use_ssl=self.target.tls, get_info=DSA, connect_timeout=self.target.timeout)
ldap_con = Connection(server, auto_bind=True)
ldap_con.unbind()
except Exception as e:
if len(e.args) == 1:
error = str(e.args[0])
else:
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 self.target.tls:
return Result(None, f"LDAPS connect error: {error}")
return Result(None, f"LDAP connect error: {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 get_long_domain(self, 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, f"Long domain name is: {long_domain}")
return Result(None, "Could not find long domain")
def check_parent_dc(self, namingcontexts_result):
'''
Checks whether the target is a parent or child domain controller.
This is done by searching for specific naming contexts.
'''
parent = False
namingcontexts_result = '\n'.join(namingcontexts_result)
if "DC=DomainDnsZones" in namingcontexts_result 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")
### Domain Information Enumeration via lsaquery
class EnumLsaqueryDomainInfo():
def __init__(self, target, creds):
self.target = target
self.creds = creds
def run(self):
'''
Run module lsaquery which tries to get domain information like
the domain/workgroup name, domain SID and the membership type.
'''
module_name = ENUM_LSAQUERY_DOMAIN_INFO
print_heading(f"Domain Information via RPC for {self.target.host}")
output = {"workgroup":None,
"domain_sid":None,
"member_of":None}
lsaquery = self.lsaquery()
if lsaquery.retval is not None:
# Try to get domain/workgroup from lsaquery
result = self.get_workgroup(lsaquery.retval)
if result.retval:
print_success(result.retmsg)
output["workgroup"] = result.retval
else:
output = process_error(result.retmsg, ["workgroup"], module_name, output)
# Try to get domain SID
result = self.get_domain_sid(lsaquery.retval)
if result.retval:
print_success(result.retmsg)
output["domain_sid"] = result.retval
else:
output = process_error(result.retmsg, ["domain_sid"], module_name, output)
# Is the host part of a domain or a workgroup?
result = self.check_is_part_of_workgroup_or_domain(lsaquery.retval)
if result.retval:
print_success(result.retmsg)
output["member_of"] = result.retval
else:
output = process_error(result.retmsg, ["member_of"], module_name, output)
else:
output = process_error(lsaquery.retmsg, ["workgroup", "domain_sid", "member_of"], module_name, output)
return output
def lsaquery(self):
'''
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', self.target.workgroup, '-U', f'{self.creds.user}%{self.creds.pw}', self.target.host, '-c', 'lsaquery']
result = run(command, "Attempting to get domain SID", self.target.samba_config, timeout=self.target.timeout)
if not result.retval:
return Result(None, f"Could not get domain information via 'lsaquery': {result.retmsg}")
if result.retval:
return Result(result.retmsg, "")
return Result(None, "Could not get information via 'lsaquery'")
def get_workgroup(self, 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, f"Domain: {workgroup}")
return Result(None, "Could not get workgroup from lsaquery")
def get_domain_sid(self, lsaquery_result):
'''
Takes the result of rpclient's lsaquery command and tries to extract the domain SID.
'''
domain_sid = ""
if "Domain Sid: (NULL SID)" in lsaquery_result:
domain_sid = "NULL SID"
else:
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, f"SID: {domain_sid}")
return Result(None, "Could not get domain SID from lsaquery")