-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathEnum4LinuxPy.py
More file actions
1142 lines (908 loc) · 51.8 KB
/
Enum4LinuxPy.py
File metadata and controls
1142 lines (908 loc) · 51.8 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
import argparse
import subprocess
import datetime
import terminaltables
import re
import sys
import time
import random
import getpass
from termcolor import cprint
# Global Vars
dependent_programs = ["nmblookup", "net", "rpcclient", "smbclient"]
optional_dependent_programs = ["polenum", "ldapsearch"]
user_list = []
full_sid = None
###############################################################################
# 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-1999
#
# 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
# TUPLE BASED DICTIONARY
nbt_info = {
("..__MSBROWSE__.", "01"): "Master Browser",
("INet~Services", "1c"): "IIS",
("IS~", "00"): "IIS",
("", "00"): "Workstation Service",
("", "01"): "Messenger Service",
("", "03"): "Messenger Service",
("", "06"): "RAS Server Service",
("", "1f"): "NetDDE Service",
("", "20"): "File Server Service",
("", "21"): "RAS Client Service",
("", "22"): "Microsoft Exchange Interchange(MSMail Connector)",
("", "23"): "Microsoft Exchange Store",
("", "24"): "Microsoft Exchange Directory",
("", "30"): "Modem Sharing Server Service",
("", "31"): "Modem Sharing Client Service",
("", "43"): "SMS Clients Remote Control",
("", "44"): "SMS Administrators Remote Control Tool",
("", "45"): "SMS Clients Remote Chat",
("", "46"): "SMS Clients Remote Transfer",
("", "4C"): "DEC Pathworks TCPIP service on Windows NT",
("", "52"): "DEC Pathworks TCPIP service on Windows NT",
("", "87"): "Microsoft Exchange MTA",
("", "6A"): "Microsoft Exchange IMC",
("", "Be"): "Network Monitor Agent",
("", "Bf"): "Network Monitor Application",
("", "03"): "Messenger Service",
("", "02"): "Domain/Workgroup Name",
# nbt stat code is really 00, but is 02 to prevent duplication difference between this and workstation is that Domain/Workgroup Name will have <GROUP> on the same line, workstation will not
("", "1b"): "Domain Master Browser",
("", "1c"): "Domain Controllers",
("", "1d"): "Master Browser",
("", "1e"): "Browser Service Elections",
("", "2b"): "Lotus Notes Server Service",
("IRISMULTICAST", "2f"): "Lotus Notes",
("IRISNAMESERVER", "33"): "Lotus Notes",
('Forte_$ND800ZA', "20"): "DCA IrmaLan Gateway Server Service"
}
####################### end of nbtscan-derrived code ############################
def setArgs(uargs):
# check main arguments
if uargs.a:
uargs.U = True
uargs.S = True
uargs.G = True
uargs.r = True
uargs.P = True
uargs.o = True
uargs.n = True
uargs.i = True
elif not uargs.U and not uargs.S and not uargs.G and not uargs.r and not uargs.p and not uargs.P and not uargs.o and not uargs.n and not uargs.i and not uargs.e:
uargs.a = True
elif uargs.spray and uargs.brute:
cprint("[E]: You may only choose to brute force or spray passwords in a single instance", "red",
attrs=["bold"])
exit(1)
elif uargs.spray:
uargs.U = True
else:
uargs.a = False
# check if lookupsids is true
if uargs.lookupsids:
uargs.r = True
# check if junk creds wanted
if uargs.j:
uargs.u = "Enum4Linux"
uargs.p = "Py"
# check if null password is wanted
if uargs.p == None or uargs.p == "":
uargs.p = getpass.getpass("Password:")
return uargs
def checkDependentProgs(proglist, verbose):
if sys.platform.lower() == "windows":
cprint(
"[E] Enum4LinuxPy is meant to be ran in an *unix type of environment. The reason for this is due to the fact that Enum4LinuxPy utilizes tools like smbclient and rpcclient, which are usually only found in *unix type environments.",
"red", attrs=["bold"])
exit(1)
for prog in proglist:
response = subprocess.run(["which", "{}".format(prog)], stdout=subprocess.PIPE, shell=False)
if response.returncode == 0 and verbose:
cprint("[V]: {} is present on this machine.".format(prog), "green", attrs=["bold"])
elif response.returncode != 0:
cprint("ERROR: {} is not in your path.".format(prog), "red", attrs=["bold"])
exit(1)
def checkOptProgs(proglist, verbose):
for prog in proglist:
response = subprocess.run(["which", "{}".format(prog)], stdout=subprocess.PIPE, shell=False)
if response.returncode == 0 and verbose:
cprint("[V]: {} is present on this machine.".format(prog), "green", attrs=["bold"])
elif response.returncode != 0:
cprint("WARNING: {} is not in your path.".format(prog), "yellow", attrs=["bold"])
def getArgs():
parser = argparse.ArgumentParser(description="""
Simple wrapper around the tools in the samba package to provide similar
functionality to enum.exe (formerly from www.bindview.com). Some additional
features such as RID cycling have also been added for convenience.
""",
usage="""python Enum4LinuxPy.py -t <target> <options>
E.g:
python Enum4LinuxPy.py -t 10.10.x.x -a
python Enum4LinuxPy.py -t 10.20.x.x -l
python Enum4LinuxPy.py -t 192.168.x.x -R 1000-2000 500-600 -k administrator wsusadmin exchadmin root guest admin
NOTE that -R or -k take a list as arguments and only require a space separation delimitation)""",
prog="Enum4LinuxPy https://github.com/0v3rride (Ryan Gore)",
epilog="""
RID cycling should extract a list of users from Windows (or Samba) hosts
which have RestrictAnonymous set to 1 (Windows NT and 2000), or "Network
access: Allow anonymous SID/Name translation" enabled (XP, 2003).
NB: Samba servers often seem to have RIDs in the range 3000-3050.
Dependancy info: You will need to have the samba package installed as this
script is basically just a wrapper around rpcclient, net, nmblookup and
smbclient. Polenum from http://labs.portcullis.co.uk/application/polenum/
is required to get Password Policy info.
""")
std = parser.add_argument_group("Options similar to Enum4Linux.pl")
std.add_argument("-t", required=True, type=str, default=None, help="specifiy the remote host")
std.add_argument("-u", required=False, type=str, default="", help="specifiy username to use (default '')")
std.add_argument("-p", required=False, type=str, default="", help="specifiy password to use (default '')")
std.add_argument("-d", required=False, action="store_true", default=False,
help="be detailed, applies to -U and -S")
std.add_argument("-G", required=False, action="store_true", default=False, help="get group and member list")
std.add_argument("-P", required=False, action="store_true", default=False, help="get password policy information")
std.add_argument("-S", required=False, action="store_true", default=False, help="get sharelist")
std.add_argument("-U", required=False, action="store_true", default=False, help="get userlist")
std.add_argument("-j", required=False, action="store_true", default=False,
help="junk creds (sometimes null session enumeration will not work with null creds)")
# Crap that wasn't implemented according to comments in enum4linux.pl (will work on this later)
# std.add_argument("-L", required=False, action="store_true", default=False, help="enum lsa policy)
# std.add_argument("-N", required=False, action="store_true", default=False, help="enum names)
# std.add_argument("-M", required=False, action="store_true", default=False, help="get machine list")
# std.add_argument("-F", required=False, action="store_true", default=False, help=")
# std.add_argument("-D", required=False, action="store_true", default=False, help=")
addops = parser.add_argument_group("Additional options")
addops.add_argument("-i", required=False, action="store_true", default=False, help="Get printer information")
addops.add_argument("-o", required=False, action="store_true", default=False, help="Get OS information")
addops.add_argument("-n", required=False, action="store_true", default=False,
help="Do an nmblookup (similar to nbtstat)")
addops.add_argument("-l", required=False, action="store_true", default=False,
help="Get some (limited) info via LDAP 389/TCP (for DCs only)")
addops.add_argument("-v", required=False, action="store_true", default=False,
help="Verbose. Shows full commands being run (net, rpcclient, etc.)")
addops.add_argument("-e", required=False, action="store_true", default=False, help="enumerate privileges")
addops.add_argument("-y", required=False, action="store_true", default=False,
help="attempt to enumerate Domain Controller names")
addops.add_argument("-z", required=False, action="store_true", default=False,
help="enumerate running services on remote host using supplied credentials (most likely will need privileged credentials)")
addops.add_argument("-q", required=False, action="store_true", default=False,
help="attempt to enumerate domain information")
addops.add_argument("--nomemberlist", required=False, action="store_true", default=False,
help="Do not list out the group memberships when enumerating groups and member lists")
addops.add_argument("-a", required=False, action="store_true", default=False, help="""
Do all simple enumeration (-U -S -G -P -r -o -n -i).
This option is enabled if you don't provide any other options.""")
addops.add_argument("-w", required=False, type=str, default=None,
help="Specify workgroup manually (usually found automatically)")
addops.add_argument("-s", required=False, type=str, default=None,
help="path to list for brute force guessing share names")
ridsnsids = parser.add_argument_group("Options for RID and SID enumeration")
ridsnsids.add_argument("-r", required=False, action="store_true", default=False,
help="enumerate users via RID cycling")
ridsnsids.add_argument("-R", required=False, type=str, nargs='+', default=["500-550", "1000-1050"],
help="RID ranges to enumerate, use with --lookupsids (default: rid_range, implies -r) Use spaces to try several rid ranges: -R 0-100 1000-2500 500-600)")
ridsnsids.add_argument("--basesid", required=False, type=str, default="S-1-5-21", help="The base SID to use when preforming SID bruteforcing (-lookupsids) (default S-1-5-21-)")
ridsnsids.add_argument("--lookupsids", required=False, action="store_true", default=False, help="Perform RID bruteforce (SID -> Object) via the lookupsids command in rpcclient. Similar to impacket's lookupsids.py script")
ridsnsids.add_argument("-k", required=False, type=str, nargs='+',
default=["administrator", "guest", "krbtgt", "domain admins", "root", "bin", "none"], help="""
User(s) that exists on remote system (default: ["administrator", "guest", "krbtgt", "domain admins", "root", "bin", "none"].
SID lookup via "lookupsid known_username" Use spaces to try several users: -k admin user1 user2)""")
ridsnsids.add_argument("-K", required=False, type=int, default=10, help="""
Keep searching RIDs until n number of consecutive RIDs don't correspond to a username.
Implies RID range ends at highest_rid. Useful against DCs (default 10).""")
passops = parser.add_argument_group("Password spraying and brute forcing options")
passops.add_argument("--brute", required=False, type=str, default=None,
help="Perform brute forcing using rpcclient (value should be username)")
passops.add_argument("--wordlist", required=False, type=str, default=None,
help="Wordlist to use when brute forcing (value should be absolute path to wordlist)")
passops.add_argument("--spray", required=False, type=str, default=None,
help="Perform password spray using rpcclient (value should be password to spray, a user list is built when enumerating them if possible)")
passops.add_argument("--timeout", required=False, type=int, default=None,
help="The timeout period in between each credential check (timeout is in seconds) (default: None)")
passops.add_argument("--randtimeout", required=False, type=int, default=None,
help="The celling value for random timeout period in between each credential check (timeout is in seconds starting at 0 to <value given> (default: None))")
return parser.parse_args()
def get_workgroup(args):
try:
if args.v:
cprint("[V] Attempting to get domain name", "yellow", attrs=["bold"])
output = str(subprocess.check_output(["nmblookup", "-A", str(args.t)], shell=False).decode("UTF-8"))
for line in output.splitlines():
if " <00> - <GROUP>" in line:
args.w = line.strip().split(' ')[0]
print("[+]: Obtained domain/workgroup name: {}\n".format(args.w))
except subprocess.CalledProcessError as cpe:
cprint("[E] Can't find workgroup/domain\n", "red", attrs=["bold"])
args.w = ""
def get_domain_info(args):
try:
if args.v:
cprint("[V] Attempting to get domain information with querydominfo\n", "yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c", "querydominfo"], shell=False).decode(
"UTF-8")
if output is not None:
print(output)
except subprocess.CalledProcessError as cpe:
cprint("[E] Unable to get domain information\n", "red", attrs=["bold"])
def get_dc_names(args):
try:
if args.v:
cprint("[V] Attempting to get domain controller information with dsr_getdcname\n", "yellow",
attrs=["bold"])
output = subprocess.check_output(["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c",
"dsr_getdcname {}".format(args.w)], shell=False).decode("UTF-8")
if output is not None:
print(output)
except subprocess.CalledProcessError as cpe:
cprint("[E] Unable to get DC name and information\n", "red", attrs=["bold"])
try:
if args.v:
cprint("[V] Attempting to get a domain controller name with getdcname\n", "yellow", attrs=["bold"])
output = subprocess.check_output(["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c",
"getdcname {}".format(str(args.w).split('.')[0])], shell=False).decode("UTF-8")
if output is not None:
cprint("[+] UNC Path Found: {}\n".format(output), "green", attrs=["bold"])
listout = subprocess.Popen(
["smbclient", "-L", r"{}".format((str(output).strip("\n\r\t\0"))), "-W", args.w, "-U",
"{}%{}".format(args.u, args.p)], stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if listout is not None:
cprint(listout, "green", attrs=["bold"])
except subprocess.CalledProcessError as cpe:
if str(cpe.output.decode("UTF-8")).find("WERR_NOT_SUPPORTED") > -1:
cprint("[E] The rpcclient command 'getdcname' only works against Domain Controllers\n", "red",
attrs=["bold"])
else:
cprint("[E] Unable to get DC name and information\n", "red", attrs=["bold"])
def get_nbtstat(target):
try:
output = subprocess.check_output(["nmblookup", "-A", target], shell=False).decode("UTF-8")
mac = output.splitlines()[len(output.splitlines()) - 2]
print("{}\n{}\n\n{}\n".format(output.splitlines()[0], nbt_to_human(output), mac))
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def nbt_to_human(output):
stringbuilder = []
servicedata = re.findall("(\t[\w\-\.]+|<\w{1,2}>)", output, re.I)
servicedata.remove("\tMAC")
counter = 0
for line in output.splitlines():
if counter < len(servicedata):
servicename = servicedata[counter].strip("\t")
if re.search("(..__MSBROWSE__.|INet~Services|IS~|IRISMULTICAST|IRISNAMESERVER|Forte_\$ND800ZA)",
servicename, re.I):
stringbuilder.append(
"{}\t{}".format(line, nbt_info[servicename, servicedata[counter + 1].strip("<>")]))
counter = (counter + 2)
elif re.search("<GROUP>", line, re.I) and re.search("<00>", line, re.I):
stringbuilder.append("{}\t{}".format(line, nbt_info["", "02"]))
counter = (counter + 2)
elif not re.search("(..__MSBROWSE__.|INet~Services|IS~|IRISMULTICAST|IRISNAMESERVER|Forte_\$ND800ZA)",
servicename, re.I) and re.search(servicedata[counter + 1], line, re.I):
stringbuilder.append("{}\t{}".format(line, nbt_info["", servicedata[counter + 1].strip("<>")]))
counter = (counter + 2)
return "\n".join(stringbuilder)
def make_session(args):
try:
if args.v:
cprint("[V] Attempting to make null session", "yellow", attrs=["bold"])
output = subprocess.check_output(
["smbclient", "-W", args.w, r"//{}/ipc$".format(args.t), "-U", "{}%{}".format(args.u, args.p), "-c",
"help"], shell=False).decode("UTF-8")
if output.find("session setup failed") > -1:
cprint(
"[E] Server doesn't allow session using username '{}', password '{}'. Aborting remainder of tests.\n".format(
args.u, args.p), "red", attrs=["bold"])
exit(1)
else:
cprint("[+] Server {} allows sessions using username '{}', password '{}'\n".format(args.t, args.u, args.p),
"green", attrs=["bold"])
except subprocess.CalledProcessError as cpe:
cprint(
"[E] Server doesn't allow session using username '{}', password '{}'. Aborting remainder of tests.\n".format(
args.u, args.p), "red", attrs=["bold"])
exit(1)
def get_ldapinfo(args):
try:
if args.v:
cprint("[V] Attempting to get long domain name", "yellow", attrs=["bold"])
output = subprocess.check_output(
["ldapsearch", "-x", "-h", args.t, "-p", "389", "-s", "base", "namingContexts"], shell=False).decode("UTF-8")
if output.find("ldap_sasl_bind") > -1:
cprint("[E] Connection error\n", "red", attrs=["bold"])
else:
print(output)
# PARSE LDAP STRING
except subprocess.CalledProcessError as cpe:
cprint(
"[E] Dependent program ldapsearch not present. Skipping this check. Install ldapsearch to fix this issue\n".format(
args.u, args.p), "red", attrs=["bold"])
def get_domain_sid(args):
try:
if args.v:
cprint("[V] Attempting to get domain SID", "yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c", "'lsaquery'"], shell=False).decode(
"UTF-8")
if (output.find("Domain Sid: S-0-0") > -1 or output.find("Domain Sid: (NULL SID)") > -1):
print("[+] Host is part of a workgroup (not a domain)\n")
elif (re.search("Domain Sid: S-\d+-\d+-\d+-\d+-\d+-\d+", output, re.I)):
print("[+] Host is part of a domain (not a workgroup)\n")
print("[+] {}".format(output))
if (args.w == None or args.w == "" or args.w == " "):
for line in output.splitlines():
if line.find("Domain Name:") > -1:
args.w = line.split(": ")[1]
cprint("[+] Found Domain/Workgroup Name: {}\n".format(args.w), "green", attrs=["bold"])
else:
cprint("[+] Can't determine if host is part of domain or part of a workgroup\n", "yellow", attrs=["bold"])
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def get_os_info(args):
try:
# smbclient
if args.v:
cprint(
"[V] Attempting to get OS info with command: smbclient -W {} //{}/ipc\$ -U {}%{} -c 'q'".format(args.w,
args.t,
args.u,
args.p),
"yellow", attrs=["bold"])
output = subprocess.check_output(
["smbclient", "-W", args.w, r"//{}/ipc$".format(args.t), "-U", "{}%{}".format(args.u, args.p), "-c",
"q"], shell=False).decode("UTF-8")
if re.search("(Domain=[^\n]+)", output, re.I):
print("[+] OS info for {} from smbclient: {}\n".format(args.t, output))
except subprocess.CalledProcessError as cpe:
cprint("SMBCLIENT Error: {}".format(cpe.output.decode("UTF-8")), "red", attrs=["bold"])
try:
# rpcclient
if args.v:
cprint("[V] Attempting to get OS info with command: rpcclient -W {} -U {}%{} -c srvinfo {}".format(args.w,
args.u,
args.p,
args.t),
"yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", r"{}%{}".format(args.u, args.p), "-c", "srvinfo", args.t], shell=False).decode(
"UTF-8")
if (output.find("error: NT_STATUS_ACCESS_DENIED") > -1):
cprint("[E] Can't get OS info with srvinfo: NT_STATUS_ACCESS_DENIED\n", "red", attrs=["bold"])
else:
print("[+] Got OS info for {} from srvinfo: {}\n".format(args.t, output))
except subprocess.CalledProcessError as cpe:
cprint("RPCCLIENT Error: {}".format(cpe.output.decode("UTF-8")), "red", attrs=["bold"])
def enum_groups(args):
try:
groups = ("builtin", "domain")
for group in groups:
# GET LIST OF GROUPS
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", r"{}%{}".format(args.u, args.p), args.t, "-c",
"enumalsgroups {}".format(group)], shell=False).decode("UTF-8")
if (group == "domain"):
if args.v:
cprint("[V] Getting local groups with enumalsgroups\n", "yellow", attrs=["bold"])
print("[+] Getting local groups:\n")
else:
if args.v:
cprint("[V] Getting {} groups with enumalsgroups\n".format(group), "yellow", attrs=["bold"])
print("[+] Getting {} groups\n".format(group))
if (output.find("error: NT_STATUS_ACCESS_DENIED") > -1):
if (group == "domain"):
cprint("[E] Can't get local groups: NT_STATUS_ACCESS_DENIED\n", "red", attrs=["bold"])
else:
cprint("[E] Can't get {} groups: NT_STATUS_ACCESS_DENIED\n".format(group), "red", attrs=["bold"])
else:
if (re.search("group:", output, re.I)):
print(output)
# GET GROUP NAME, MEMBERS & RID
if not args.nomemberlist:
groupdata = re.findall(r"(\[[\w\s\-\_\{\}\.\$\#]+\])", output, re.I)
for data in range(0, len(groupdata), 2):
print("[+] Information for group '{}' (RID {}):".format(groupdata[data].strip("[]"),
int(groupdata[(data + 1)].strip("[]"),
16)))
doutput = subprocess.Popen(
["net", "rpc", "group", "members", groupdata[data].strip("[]"), "-W", args.w, "-I", args.t,
"-U", "{}%{}".format(args.u, args.p)], stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if doutput:
print("Member List:\n{}".format(doutput))
else:
cprint("\tIt appears that this group has no members\n", "yellow", attrs=["bold"])
if args.d:
get_group_details_from_rid(int(groupdata[(data + 1)].strip("[]"), 16), args)
print("\n")
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def get_group_details_from_rid(rid, args):
try:
if args.v:
cprint("[V] Attempting to get detailed group info", "yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), "-c", "querygroup {}".format(str(rid)),
args.t], shell=False).decode("UTF-8")
if output:
print("{}\n".format(output))
else:
cprint("[E] No info found\n", "red", attrs=["bold"])
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def enum_password_policy(args):
try:
output = subprocess.check_output(["polenum", "{}:{}@{}".format(args.u, args.p, args.t)], shell=False).decode("UTF-8")
if args.v:
cprint("[V] Attempting to get Password Policy info", "yellow", attrs=["bold"])
if (output):
if (output.find("Account Lockout Threshold") > -1):
print(output)
elif (output.find("Error Getting Password Policy: Connect error") > -1):
cprint("[E] Can't connect to host with supplied credentials.\n", "red", attrs=["bold"])
else:
cprint("[E] Unexpected error from polenum.py:\n", "red", attrs=["bold"])
print(output)
else:
print("[E] polenum.py gave no output.\n")
except subprocess.CalledProcessError as cpe:
print(cpe.output.decode("UTF-8"))
return 0
def enum_users(args):
try:
if args.v:
cprint("[V] Attempting to get userlist with querydispinfo", "yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-c querydispinfo", "-U", "{}%{}".format(args.u, args.p), args.t], shell=False).decode(
"UTF-8")
print(output)
print("\n")
# GET USER RIDS
userenumdata = subprocess.check_output(
["rpcclient", "-W", args.w, "-c enumdomusers", "-U", "{}%{}".format(args.u, args.p), args.t], shell=False).decode(
"UTF-8")
userdata = re.findall(r"(\[[\w\s\-\_\{\}\.\$]+\])", userenumdata, re.I)
if args.v:
cprint("[V] Attempting to get userlist with enumdomusers", "yellow", attrs=["bold"])
if userenumdata.find("NT_STATUS_ACCESS_DENIED") > -1:
cprint("[E] Couldn't find users using querydispinfo: NT_STATUS_ACCESS_DENIED\n", "red", attrs=["bold"])
elif userenumdata.find("NT_STATUS_INVALID_PARAMETER") > -1:
cprint("[E] Couldn't find users using querydispinfo: NT_STATUS_INVALID_PARAMETER\n", "red", attrs=["bold"])
else:
for data in range(0, len(userdata), 2):
user_list.append(userdata[data].strip("[]"))
print("User: {}\{} ----- RID: {}".format(args.w, userdata[data].strip("[]"),
int(userdata[(data + 1)].strip("[]"), 16)))
print("")
except subprocess.CalledProcessError as cpe:
if cpe.output.decode("UTF").find("NT_STATUS_ACCESS_DENIED") > -1:
cprint("[E] Couldn't find users using querydispinfo: NT_STATUS_ACCESS_DENIED\n", "red", attrs=["bold"])
elif cpe.output.decode("UTF").find("NT_STATUS_INVALID_PARAMETER") > -1:
cprint("[E] Couldn't find users using querydispinfo: NT_STATUS_INVALID_PARAMETER\n", "red", attrs=["bold"])
def enum_shares(args):
output = None
try:
if args.v:
cprint("[V] Attempting to get share list using authentication", "yellow", attrs=["bold"])
# my $shares = `net rpc share -W '$global_workgroup' -I '$global_target' -U'$global_username'\%'$global_password' 2>&1` #perl example with net rpc command
output = subprocess.check_output(
["smbclient", "-W", args.w, "-L", r"//{}".format(args.t), "-U", "{}%{}".format(args.u, args.p)], shell=False).decode(
"UTF-8")
if output.find("NT_STATUS_ACCESS_DENIED") > -1:
cprint("[E] Can't list shares: NT_STATUS_ACCESS_DENIED\n", "red", attrs=["bold"])
else:
print(output)
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
try:
print("\n[+] Attempting to map shares on {}\n".format(args.t))
# Filter down the share list returned from the smbclient list command above
shares = re.findall("\t([\S]+?)\s+(?:Disk|IPC|Printer|-{4,})", output, re.I)
# Remove any line from the list shares that contains 4 or more -'s in it with a comprehension list (not pretty but it works for now, the number may need to be changed depending on the environment, sharename, etc.)
sharelist = [s for s in shares if not re.search("-{4,}", s, re.I)]
for share in sharelist:
if args.v:
cprint("[V] Attempting map to share //{}/{} with smbclient\n".format(args.t, share), "yellow",
attrs=["bold"])
map_response = subprocess.Popen(
["smbclient", "-W", args.w, r"//{}/{}".format(args.t, share), "-U", "{}%{}".format(args.u, args.p),
"-c dir"], stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if map_response.find("NT_STATUS_ACCESS_DENIED listing") > -1:
cprint("""\t[-] Share: {0:<15} \tMapping: OK Listing: DENIED """.format(share), "red", attrs=["bold"])
elif map_response.find("tree connect failed: NT_STATUS_ACCESS_DENIED") > -1:
cprint("""\t[-] Share: {0:<15} \tMapping: DENIED Listing: N/A """.format(share), "red", attrs=["bold"])
elif re.search("\n\s+\.\.\s+D.*\d{4}\n", map_response, re.I) or re.search("blocks of size|blocks available", map_response, re.I):
cprint("""\t[+] Share: {0:<15} \tMapping: OK Listing: OK """.format(share), "green", attrs=["bold"])
else:
cprint("\t[E] Can't understand response for {}: {}".format(share, map_response.rstrip("\n\r")), "red", attrs=["bold"])
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def enum_users_rids(args):
try:
# Get SID with known usernames
for known_username in args.k:
output = subprocess.Popen(["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t,
"-c lookupnames '{}'".format(known_username)],
stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if args.v:
cprint("[V] Attempting to get SID with lookupnames\n", "yellow", attrs=["bold"])
cprint("[V] Assuming that user {} exists\n".format(known_username), "yellow", attrs=["bold"])
logon = "username {}, password {}".format(args.u, args.p)
if output.find("NT_STATUS_ACCESS_DENIED") > -1:
cprint("[E] Couldn't get SID: NT_STATUS_ACCESS_DENIED. RID cycling not possible.\n", "red",
attrs=["bold"])
break
elif output.find("NT_STATUS_NONE_MAPPED") > -1:
if args.v:
cprint("[V] User {} doesn't exist. User enumeration should be possible, but SID needed...\n".format(
known_username), "yellow", attrs=["bold"])
continue
# TODO: redo regex to be S-[\d-]+ or S-1-5-21-[\d-]+
elif re.search("(S-1-5-[\d]+-[\d-]+)", output, re.I):
cprint("[+] Found new SID: {}".format(output).strip("\n\r\t\0"), "green", attrs=["bold"])
continue
elif re.search("(S-1-5-21-[\d]+-[\d-]+)", output, re.I):
cprint("[+] Found new SID: {}".format(output).strip("\n\r\t\0"), "green", attrs=["bold"])
continue
elif re.search("(S-1-5-22-[\d]+-[\d-]+)", output, re.I):
cprint("[+] Found new SID: {}".format(output).strip("\n\r\t\0"), "green", attrs=["bold"])
continue
else:
continue
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
# Get some more SIDs
try:
if args.v:
cprint("[V] Attempting to get SIDs from {} with lsaenumsid\n\r\t\0".format(args.t), "yellow", attrs=["bold"])
output = subprocess.Popen(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c lsaenumsid"],
stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
for sid in output.splitlines():
if args.v:
cprint("[V] Processing SID {}\n".format(sid), "yellow", attrs=["bold"])
if sid.find("NT_STATUS_ACCESS_DENIED") > -1:
cprint("[E] Couldn't get SID: NT_STATUS_ACCESS_DENIED. RID cycling not possible.\n", "red",
attrs=["bold"])
continue
# TODO: redo regex to be S-[\d-]+ or S-1-5-21-[\d-]+
elif re.search("(S-1-5-[\d]+-[\d-]+)", sid, re.I):
cprint("[+] Found new SID: {}".format(sid), "green", attrs=["bold"])
continue
elif re.search("(S-1-5-21-[\d]+-[\d-]+)", sid, re.I):
cprint("[I] Found new SID: {}".format(sid), "green", attrs=["bold"])
continue
elif re.search("(S-1-5-22-[\d]+-[\d-]+)", sid, re.I):
cprint("[I] Found new SID: {}".format(sid), "green", attrs=["bold"])
continue
print("")
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def enum_users_rids_lookupsids(args):
try:
output = subprocess.Popen(
["net", "rpc", "getsid", "-W", args.w, "-I", args.t, "-U", "{}%{}".format(args.u, args.p)], stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if not output or output == "":
cprint("[E] Could not find any matches with the base sid provided\n", "red", attrs=["bold"])
else:
full_sid = re.findall("({}-[\d]+-[\d-]+)".format(args.basesid), output, re.I)[0]
full_sid = "{}-".format(full_sid)
dlcid = subprocess.Popen(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c lookupsids '{}'".format(full_sid[:-1])],
stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
cprint("[+] Domain SID/Local SID: {} --> {}\n".format(full_sid[:-1], dlcid.split(" ")[1]))
for ridrange in args.R:
minrid = int(str(ridrange).split('-')[0])
maxrid = int(str(ridrange).split('-')[1])
for rid in range(minrid, maxrid):
output = subprocess.Popen(["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), args.t, "-c lookupsids {}{}".format(full_sid, rid)], stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
#if output.find("unknown") <= 0 or output.find("result was NT_STATUS_INVALID_SID") <= 0:
if r"*unknown*\*unknown*" not in output and "result was NT_STATUS_INVALID_SID" not in output:
cprint("[+]: {}: {}".format(rid, output.split(" ")[1]).strip("\n\r\t\0"), "green", attrs=["bold"])
print("")
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
except IndexError as ie:
cprint("[E] Could not find any matches with the base sid provided\n", "red", attrs=["bold"])
def enum_shares_unauth(args):
try:
with open(args.s, "r") as file:
shares = file.read().splitlines()
for share in shares:
output = subprocess.Popen(["smbclient", "-W", args.w, r"//{}/{}".format(args.t, share), "-U", "{}%{}".format(args.u, args.p), "-c", "dirq"], stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if re.search("blocks of size|blocks available", output, re.I):
cprint("[+] {} EXISTS, allows access using username: {}, password: {}\n".format(share, args.u, args.p), "green", attrs=["bold"])
elif re.search("NT_STATUS_ACCESS_DENIED", output, re.I):
cprint("[+] {} EXISTS, but credentials aren't valid\n".format(share), "yellow", attrs=["bold"])
elif re.search("NT_STATUS_BAD_NETWORK_NAME", output, re.I):
cprint("[-] {} doesn't exist\n".format(share), "red", attrs=["bold"])
else:
cprint("Cannot understand response: {}".format(output), "red", attrs=["bold"])
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
except FileNotFoundError as fnfe:
cprint("Path to file containing a list of share names is not valid", "red", attrs=["bold"])
def enum_privs(args):
try:
if args.v:
cprint("[V] Attempting to get privilege info with enumprivs\n", "yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), "-c enumprivs", args.t], shell=False).decode("UTF-8")
print("{}\n".format(output))
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def get_printer_info(args):
try:
if args.v:
cprint("[V] Attempting to get printer info with enumprinters\n", "yellow", attrs=["bold"])
output = subprocess.check_output(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.u, args.p), "-c enumprinters", args.t], shell=False).decode(
"UTF-8")
print("{}\n\n".format(output))
except subprocess.CalledProcessError as cpe:
cprint("[E] {}".format(cpe.output.decode("UTF-8"), "red", attrs=["bold"]))
def enum_services(args):
try:
if args.v:
cprint("[V] Attempting to get a list of services with net service list\n", "yellow", attrs=["bold"])
output = subprocess.check_output(
["net", "rpc", "service", "list", "-I", args.t, "-U", "{}\\{}%{}".format(args.w, args.u, args.p)], shell=False).decode(
"UTF-8")
print(output)
except subprocess.CalledProcessError as cpe:
if str(cpe.output.decode("UTF-8")).find("NT_STATUS_LOGON_FAILURE"):
cprint("[E] Could not get a list of services, because of invalid credentials\n", "red", attrs=["bold"])
else:
cprint("[E] Could not get a list of services\n", "red", attrs=["bold"])
def pass_spray(args):
try:
if args.v:
cprint("[V] Attempting to obtain valid credentials via password spray (timeout set to {} seconds)".format(
args.timeout), "red", attrs=["bold"])
count = 0
for user in user_list:
count = count + 1
output = subprocess.Popen(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(user, args.spray), "-c getusernamequit", args.t],
stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if output.find("Cannot connect to server") > -1 or output.find("Error was NT_STATUS_LOGON_FAILURE") > -1:
cprint("[{}] Username: '{}'\tPassword: '{}'\tResult: invalid".format(count, user, args.spray), "red",
attrs=["bold"])
elif output.find("Account Name") > -1 or output.find("Authority Name") > -1:
cprint("[{}] Username: '{}'\tPassword: '{}'\tResult: !*****VALID*****!".format(count, user, args.spray),
"green", attrs=["bold"])
else:
print(output)
if args.timeout and args.randtimeout is None:
if args.v:
cprint("[V] Timeout for {} seconds".format(str(args.timeout)), "yellow", attrs=["bold"])
time.sleep(float(args.timeout))
elif args.timeout is None and args.randtimeout:
tout = random.randint(0, args.randtimeout)
if args.v:
cprint("[V] Timeout for {} seconds".format(str(tout)), "yellow", attrs=["bold"])
time.sleep(float(tout))
print("")
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
def brute_pass(args):
try:
words = open(args.wordlist, "r").read().splitlines()
count = 0
for word in words:
count = count + 1
output = subprocess.Popen(
["rpcclient", "-W", args.w, "-U", "{}%{}".format(args.brute, word), args.t, "-c getusernamequit"],
stdout=subprocess.PIPE, shell=False).stdout.read().decode("UTF-8")
if output.find("Cannot connect to server") > -1 or output.find("Error was NT_STATUS_LOGON_FAILURE") > -1:
cprint("[{}] Username: '{}'\tPassword: '{}'\tResult: invalid".format(count, args.brute, word), "red",
attrs=["bold"])
elif output.find("Account Name") > -1 or output.find("Authority Name") > -1:
cprint("[{}] Username: '{}'\tPassword: '{}'\tResult: !*****VALID*****!".format(count, args.brute, word),
"green", attrs=["bold"])
else:
print(output)
if args.timeout and args.randtimeout is None:
if args.v:
cprint("[V] Timeout for {} seconds".format(str(args.timeout)), "yellow", attrs=["bold"])
time.sleep(float(args.timeout))
elif args.timeout is None and args.randtimeout:
tout = random.randint(0, args.randtimeout)
if args.v:
cprint("[V] Timeout for {} seconds".format(str(tout)), "yellow", attrs=["bold"])
time.sleep(float(tout))
print("")
except subprocess.CalledProcessError as cpe:
cprint(cpe.output.decode("UTF-8"), "red", attrs=["bold"])
except FileNotFoundError as fnfe:
cprint("[E] File path specified is not valid", "red", attrs=["bold"])
def main():
timestart = datetime.datetime.now()
carglist = setArgs(getArgs())
checkDependentProgs(dependent_programs, carglist.v)
checkOptProgs(optional_dependent_programs, carglist.v)
if carglist.v:
print("""
_____ ___ _ _ ______
| ___| / || | (_) | ___ \
| |__ _ __ _ _ _ __ ___ / /| || | _ _ __ _ ___ _| |_/ / _
| __| '_ \| | | | '_ ` _ \/ /_| || | | | '_ \| | | \ \/ / __/ | | |
| |__| | | | |_| | | | | | \___ || |___| | | | | |_| |> <| | | |_| |
\____/_| |_|\__,_|_| |_| |_| |_/\_____/_|_| |_|\__,_/_/\_\_| \__, |
__/ |
|___/
""")
print("""
[*] https://github.com/0v3rride
[*] Script has started...
[*] Use CTRL+C to cancel the script at anytime.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
CREDIT FOR THE ORIGINAL PERL VERSION OF ENUM4LINUX GOES
TO MARK LOWE, PORTCULLIS LABS & CONTRIBUTORS TO THE
ENUM4LINUX PROJECT
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+------------------------------+
| TARGETING INFORMATION |
+------------------------------+
Starting Enum4LinuxPy at {}
Target --------------------> {}
RID Ranges ----------------> {}
Username ------------------> {}
Password ------------------> {}
Known Usernames -----------> {}
Base SID ------------------> {}
""".format(timestart.strftime("%b %d %Y %H:%M:%S"), carglist.t, carglist.R, carglist.u, carglist.p, carglist.k, carglist.basesid))
# Basic Enumeration & Check Session----------------------------------------------------------------------------
# WORKGOUP/DOMAIN NAME INFORMATION
title = [["Enumerating Workgroup/Domain on {}".format(carglist.t).title()]]
header = terminaltables.AsciiTable(title)
print(header.table)
if not carglist.w:
get_workgroup(carglist)
else:
cprint("[+]: Domain/workgroup name specified: {}\n".format(carglist.w), "green", attrs=["bold"])
# NMBLOOKUP/NBTSCAN
if (carglist.n):
title = [["NBTStat Information for {}".format(carglist.t).title()]]
header = terminaltables.AsciiTable(title)
print(header.table)
get_nbtstat(carglist.t)
# NULL SESSION CHECK
title = [["Session Check on {}".format(carglist.t).title()]]
header = terminaltables.AsciiTable(title)
print(header.table)
make_session(carglist)
# GET LDAP INFO
if (carglist.l):
title = [["Getting information via LDAP for {}".format(carglist.t).title()]]
header = terminaltables.AsciiTable(title)
print(header.table)
get_ldapinfo(carglist)
# GET DOMAIN SID
title = [["Getting domain SID for {}".format(carglist.t).title()]]
header = terminaltables.AsciiTable(title)
print(header.table)