-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathenum4linux-ng.py
executable file
·3330 lines (2817 loc) · 139 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 an empty [],{},""
# => no error, nothing was returned (e.g. a group has no members)
#
# * return value is False for...
# - sessions:
# => it was not possible to set up the particular session with the target
# - services:
# => error, it was not possible to setup a service connection
# - all other booleans:
# => no errors
#
# * YAML/JSON:
# * null
# => an error happened (i.e. 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
# - 'sessions', 'sessions_possible' should be 'False'
#
# Authentication
# ==============
# * Kerberos:
# * While testing Kerberos authentication with the Samba client tools and the impacket library, it turned
# out that they behave quite differently. While the impacket library will honor the username and the domain
# given, it seems that the Samba client ignores them (-U and -W parameter) and uses the ones from the ticket
# itself.
#
### 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
from impacket.smbconnection import SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_311
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",
}
# Source: https://docs.microsoft.com/de-de/windows/release-health/release-information
OS_RELEASE = {
"19042": "20H2",
"19041": "2004",
"18363": "1909",
"18362": "1903",
"17763": "1809",
"17134": "1803",
"16299": "1709",
"15063": "1703",
"14393": "1607",
"10586": "1511",
"10240": "1507"
}
# 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"
]
# Translates various SMB dialect values to human readable strings
SMB_DIALECTS = {
SMB_DIALECT: "SMB 1.0",
SMB2_DIALECT_002: "SMB 2.02",
SMB2_DIALECT_21: "SMB 2.1",
SMB2_DIALECT_30: "SMB 3.0",
SMB2_DIALECT_311: "SMB 3.1.1"
}
# 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.
# In the current implementation this list is case insensitive. Also the order of errors
# is important. Errors on top will be processed first. The access denied errors should
# be kept on top since they occur typically first (see also comment on
# STATUS_CONNECTION_DISCONNECTED).
NT_STATUS_COMMON_ERRORS = [
"RPC_S_ACCESS_DENIED",
"DCERPC_FAULT_ACCESS_DENIED",
"WERR_ACCESS_DENIED",
"STATUS_ACCESS_DENIED",
"STATUS_ACCOUNT_LOCKED_OUT",
"STATUS_NO_LOGON_SERVERS",
"STATUS_LOGON_FAILURE",
"STATUS_IO_TIMEOUT",
"STATUS_NETWORK_UNREACHABLE",
"STATUS_INVALID_PARAMETER",
"STATUS_NOT_SUPPORTED",
"STATUS_NO_SUCH_FILE",
"STATUS_PASSWORD_EXPIRED",
# This error code is from the depths of CIFS/SMBv1
# https://tools.ietf.org/id/draft-leach-cifs-v1-spec-01.txt
"ERRSRV:ERRaccess",
# This error is misleading. It can occur when the an SMB client cannot negotiate
# a connection with the SMB server e.g., because of both not supporting each others
# SMB dialect. But this error can also occur if during an RPC call access was denied
# to a specific ressource/function call. In this case the oppositve site often disconnects
# and the Samba client tools will show this error.
"STATUS_CONNECTION_DISCONNECTED"
]
# Supported authentication methods
AUTH_PASSWORD = "password"
AUTH_NTHASH = "nthash"
AUTH_KERBEROS = "kerberos"
AUTH_NULL = "null"
# 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_SMB_DOMAIN_INFO = "enum_smb_domain_info"
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, credentials, port=None, tls=None, timeout=None, samba_config=None, sessions={}):
self.host = host
self.creds = credentials
self.port = port
self.timeout = timeout
self.tls = tls
self.samba_config = samba_config
self.sessions = sessions
self.ip_version = None
self.smb_ports = []
self.ldap_ports = []
self.services = []
self.smb_preferred_dialect = None
self.smb1_supported = False
self.smb1_only = False
result = self.valid_host(host)
if not result.retval:
raise Exception(result.retmsg)
def valid_host(self, host):
try:
result = socket.getaddrinfo(host, None)
# Check IP version, alternatively we could save the socket type here
ip_version = result[0][0]
if ip_version == socket.AF_INET6:
self.ip_version = 6
elif ip_version == socket.AF_INET:
self.ip_version = 4
# Kerberos requires resolvable hostnames rather than IP adresses
ip = result[0][4][0]
if ip == host and self.creds.auth_method == AUTH_KERBEROS:
return Result(False, f'Kerberos authentication requires a hostname, but an IPv{self.ip_version} address was given')
return Result(True,'')
except Exception as e:
if isinstance(e, OSError) and e.errno == -2:
return Result(False, f'Could not resolve host {host}')
return Result(False, 'No valid host given')
def as_dict(self):
return {'target':{'host':self.host}}
class Credentials:
'''
Stores usernames and password.
'''
def __init__(self, user='', pw='', domain='', ticket_file='', nthash='', local_auth=False):
# 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
self.ticket_file = ticket_file
self.nthash = nthash
self.local_auth = local_auth
# Only set the domain here, if it is not empty
self.domain = ''
if domain:
self.set_domain(domain)
if ticket_file:
result = self.valid_ticket(ticket_file)
if not result.retval:
raise Exception(result.retmsg)
self.auth_method = AUTH_KERBEROS
elif nthash:
result = self.valid_nthash(nthash)
if not result.retval:
raise Exception(result.retmsg)
if nthash and not user:
raise Exception("NT hash given (-H) without any user, please provide a username (-u)")
self.auth_method = AUTH_NTHASH
elif not user and not pw:
self.auth_method = AUTH_NULL
else:
if pw and not user:
raise Exception("Password given (-p) without any user, please provide a username (-u)")
self.auth_method = AUTH_PASSWORD
def valid_nthash(self, nthash):
hash_len = len(nthash)
if hash_len != 32:
return Result(False, f'The given hash has {hash_len} characters instead of 32 characters')
if not re.match(r"^[a-fA-F0-9]{32}$", nthash):
return Result(False, f'The given hash contains invalid characters')
return Result(True, '')
def valid_ticket(self, ticket_file):
return valid_file(ticket_file)
# Allows various modules to set the domain during enumeration. The domain can only be set once.
# Currently, we rely on the information gained via unauth smb session to guess the domain.
# At a later call of lsaquery it might turn out that the domain is different. In this case the
# user will be informed via print_hint()
def set_domain(self, domain):
if self.domain and self.domain.lower() == domain.lower():
return True
if not self.domain:
self.domain = domain
return True
return False
def as_dict(self):
return {'credentials':OrderedDict({'auth_method':self.auth_method, 'user':self.user, 'password':self.pw, 'domain':self.domain, 'ticket_file':self.ticket_file, 'nthash':self.nthash, 'random_user':self.random_user})}
class SambaTool():
'''
Encapsulates various Samba Tools.
'''
def __init__(self, command, target, creds):
self.target = target
self.creds = creds
self.env = None
# This list stores the various parts of the command which will be later executed by run().
self.exec = []
# Set authentication method
if self.creds:
if creds.ticket_file:
# Set KRB5CCNAME as environment variable and let it point to the ticket.
# The environment will be later passed to check_output() (see run() below).
self.env = os.environ.copy()
self.env['KRB5CCNAME'] = self.creds.ticket_file
# User and domain are taken from the ticket
# Kerberos options differ between samba versions
samba_version = re.match(r".*(\d+\.\d+\.\d+).*", check_output(["smbclient", "--version"]).decode()).group(1)
samba_version = tuple(int(x) for x in samba_version.split('.'))
if samba_version < (4, 15, 0):
self.exec += ['-k']
else:
self.exec += ['--use-krb5-ccache', self.creds.ticket_file]
elif creds.nthash:
self.exec += ['-W', f'{self.creds.domain}']
self.exec += ['-U', f'{self.creds.user}%{self.creds.nthash}', '--pw-nt-hash']
else:
self.exec += ['-W', f'{self.creds.domain}']
self.exec += ['-U', f'{self.creds.user}%{self.creds.pw}']
# If the target has a custom Samba configuration attached, we will add it to the
# command. This allows to modify the behaviour of the samba client commands during
# run (e.g. enforce legacy SMBv1).
if target.samba_config:
self.exec += ['-s', f'{target.samba_config.get_path()}']
# This enables debugging output (level 1) for the Samba client tools. The problem is that the
# tools often throw misleading error codes like NT_STATUS_CONNECTION_DISCONNECTED. Often this
# error is associated with SMB dialect incompatibilities between client and server. But this
# error also occurs on other occasions. In order to find out the real reason we need to fetch
# earlier errors which this debugging level will provide.
#self.exec += ['-d1']
def run(self, log, error_filter=True):
'''
Runs a samba client command (net, nmblookup, smbclient or rpcclient) and does some basic output filtering.
'''
if GLOBAL_VERBOSE and log:
print_verbose(f"{log}, running command: {' '.join(shlex.quote(x) for x in self.exec)}")
try:
output = check_output(self.exec, env=self.env, shell=False, stderr=STDOUT, timeout=self.target.timeout)
retval = 0
except TimeoutExpired:
return Result(False, "timed out")
except Exception as e:
output = e.output
retval = 1
output = output.decode()
for line in output.splitlines(True):
if any(entry in line for entry in SAMBA_CLIENT_ERRORS):
output = output.replace(line, "")
output = output.rstrip('\n')
if "Cannot find KDC for realm" in output:
return Result(False, "Cannot find KDC for realm, check DNS settings or setup /etc/krb5.conf")
if retval == 1 and not output:
return Result(False, "empty response")
if error_filter:
nt_status_error = nt_status_error_filter(output)
if nt_status_error:
return Result(False, nt_status_error)
return Result(True, output)
class SambaSmbclient(SambaTool):
'''
Encapsulates a subset of the functionality of the Samba smbclient command.
'''
def __init__(self, command, target, creds):
super().__init__(command, target, creds)
# Set timeout
self.exec += ['-t', f'{target.timeout}']
# Build command
if command[0] == 'list':
self.exec += ['-L', f'//{target.host}', '-g']
elif command[0] == 'help':
self.exec += ['-c','help', f'//{target.host}/ipc$']
elif command[0] == 'dir' and command[1]:
self.exec += ['-c','dir', f'//{target.host}/{command[1]}']
self.exec = ['smbclient'] + self.exec
class SambaRpcclient(SambaTool):
'''
Encapsulates a subset of the functionality of the Samba rpcclient command.
'''
def __init__(self, command, target, creds):
super().__init__(command, target, creds)
# Build command
if command[0] == 'queryuser':
rid = command[1]
self.exec += ['-c', f'{command[0]} {rid}']
elif command[0] == 'querygroup':
rid = command[1]
self.exec += ['-c', f'{command[0]} {rid}']
elif command[0] == 'enumalsgroups':
group_type = command[1]
self.exec += ['-c', f'{command[0]} {group_type}']
elif command[0] == 'lookupnames':
username = command[1]
self.exec += ['-c', f'{command[0]} {username}']
elif command[0] == 'lookupsids':
sid = command[1]
self.exec += ['-c', f'{command[0]} {sid}']
# Currently, here the following commands should be handled:
# enumprinters
# enumdomusers, enumdomgroups
# lsaenumsid, lsaquery
# querydispinfo
# srvinfo
else:
self.exec += ['-c', f'{command[0]}']
self.exec += [ target.host ]
self.exec = ['rpcclient'] + self.exec
class SambaNet(SambaTool):
'''
Encapsulates a subset of the functionality of the Samba net command.
'''
def __init__(self, command, target, creds):
super().__init__(command, target, creds)
# Set timeout
self.exec += ['-t', f'{target.timeout}']
# Build command
if command[0] == 'rpc':
if command[1] == 'group':
if command[2] == 'members':
groupname = command[3]
self.exec += [f'{command[0]}', f'{ command[1]}', f'{command[2]}', groupname]
if command[1] == 'service':
if command[2] == 'list':
self.exec += [f'{command[0]}', f'{ command[1]}', f'{command[2]}']
self.exec += [ "-S", target.host ]
self.exec = ['net'] + self.exec
class SambaNmblookup(SambaTool):
'''
Encapsulates the nmblookup command. Currently only the -A option is supported.
'''
def __init__(self, target):
super().__init__(None, target, creds=None)
self.exec += [ "-A", target.host ]
self.exec = ['nmblookup'] + self.exec
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'
with tempfile.NamedTemporaryFile(delete=False) as config_file:
config_file.write(config.encode())
self.config_filename = config_file.name
def get_path(self):
return self.config_filename
def add(self, entries):
try:
config = '\n'.join(entries) + '\n'
with open(self.config_filename, 'a') as config_file:
config_file.write(config)
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:
with open(f"{self.out_file}.json", 'w') as f:
f.write(json.dumps(self.out_dict, indent=4))
except OSError:
return False
return True
def _write_yaml(self):
try:
with open(f"{self.out_file}.yaml", 'w') as f:
f.write(yamlize(self.out_dict, rstrip=False))
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(entry["port"])
return accessible
### NetBIOS Enumeration
class EnumNetbios():
def __init__(self, target, creds):
self.target = target
self.creds = creds
def run(self):
'''
Run NetBIOS module which collects Netbios names and the workgroup/domain.
'''
module_name = ENUM_NETBIOS
print_heading(f"NetBIOS Names and Workgroup/Domain for {self.target.host}")
output = {"domain":None, "nmblookup":None}
nmblookup = self.nmblookup()
if nmblookup.retval:
result = self.get_domain(nmblookup.retval)
if result.retval:
print_success(result.retmsg)
output["domain"] = result.retval
else:
output = process_error(result.retmsg, ["domain"], 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", "domain"], module_name, output)
return output
def nmblookup(self):
'''
Runs nmblookup (a NetBIOS over TCP/IP Client) in order to lookup NetBIOS names information.
'''
result = SambaNmblookup(self.target).run(log='Trying to get NetBIOS names information')
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_domain(self, nmblookup_result):
'''
Extract domain from given nmblookoup result.
'''
match = re.search(r"^\s+(\S+)\s+<00>\s+-\s+<GROUP>\s+", nmblookup_result, re.MULTILINE)
if match:
if valid_domain(match.group(1)):
domain = match.group(1)
else:
return Result(None, f"Workgroup {domain} contains some illegal characters")
else:
return Result(None, "Could not find domain/domain")
if not self.creds.local_auth:
self.creds.set_domain(domain)
return Result(domain, f"Got domain/workgroup name: {domain}")
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 for the supported SMB dialects.
'''
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"Trying on {port}/tcp")
self.target.port = port
result = self.check_smb_dialects()
if result.retval is None:
output = process_error(result.retmsg, ["smb1_only"], module_name, output)
else:
output["smb_dialects"] = result.retval
print_success(result.retmsg)
break
# Does the target only support SMBv1? Then enforce it!
if result.retval and result.retval["SMB1 only"]:
print_info("Enforcing legacy SMBv1 for further enumeration")
result = self.enforce_smb1()
if not result.retval:
output = process_error(result.retmsg, ["smb_dialects"], module_name, output)
output["smb_dialects"] = 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_smb_dialects(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.
'''
supported = {
SMB_DIALECTS[SMB_DIALECT]: False,
SMB_DIALECTS[SMB2_DIALECT_002]: False,
SMB_DIALECTS[SMB2_DIALECT_21]:False,
SMB_DIALECTS[SMB2_DIALECT_30]:False,
SMB_DIALECTS[SMB2_DIALECT_311]:False,
}
output = {
"Supported dialects": None,
"Preferred dialect": None,
"SMB1 only": False,
"SMB signing required": None
}
# List dialects supported by impacket
smb_dialects = [SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_311]
# Check all dialects
last_supported_dialect = None
for dialect in smb_dialects:
try:
smb_conn = smbconnection.SMBConnection(self.target.host, self.target.host, sess_port=self.target.port, timeout=self.target.timeout, preferredDialect=dialect)
smb_conn.close()
supported[SMB_DIALECTS[dialect]] = True
last_supported_dialect = dialect
except Exception:
pass
# Set whether we suppot SMB1 or not for this class
self.target.smb1_supported = supported[SMB_DIALECTS[SMB_DIALECT]]
# Does the target only support one dialect? Then this must be also the preferred dialect.
preferred_dialect = None
if sum(1 for value in supported.values() if value == True) == 1:
if last_supported_dialect == SMB_DIALECT:
output["SMB1 only"] = True
self.target.smb1_only = True
preferred_dialect = last_supported_dialect
try:
smb_conn = smbconnection.SMBConnection(self.target.host, self.target.host, sess_port=self.target.port, timeout=self.target.timeout, preferredDialect=preferred_dialect)
preferred_dialect = smb_conn.getDialect()
# Check whether SMB signing is required or optional - since this seems to be a global setting, we check it only for the preferred dialect
output["SMB signing required"] = smb_conn.isSigningRequired()
smb_conn.close()
output["Preferred dialect"] = SMB_DIALECTS[preferred_dialect]
self.target.smb_preferred_dialect = preferred_dialect
except Exception as exc:
# FIXME: This can propably go as impacket now supports SMB3 up to 3.11.