├── requirements.txt ├── Dockerfile ├── setup.py ├── README.md ├── LICENSE └── enum4linux-ng.py /requirements.txt: -------------------------------------------------------------------------------- 1 | impacket>=0.9.21 2 | ldap3 3 | PyYAML>=5.1 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8-alpine 2 | 3 | RUN apk upgrade --no-cache 4 | RUN apk add --no-cache rust cargo openssl-dev libffi-dev py3-pip python3 samba-client samba-common-tools yaml-dev 5 | RUN apk add --no-cache --virtual build-dependencies build-base git \ 6 | && git clone --depth 1 https://github.com/cddmp/enum4linux-ng.git \ 7 | && pip install --no-cache-dir -r enum4linux-ng/requirements.txt \ 8 | && apk del build-dependencies 9 | WORKDIR enum4linux-ng 10 | ENTRYPOINT ["python", "enum4linux-ng.py"] 11 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | from setuptools import setup 3 | 4 | with open('README.md', 'r', encoding='utf-8') as f: 5 | long_description = f.read() 6 | 7 | with open('requirements.txt', 'r', encoding='utf-8') as f: 8 | content = f.readlines() 9 | requirements = [x.strip() for x in content] 10 | 11 | shutil.copyfile('enum4linux-ng.py', 'enum4linux-ng') 12 | 13 | setup( 14 | name='enum4linux-ng', 15 | version='1.3.7', 16 | author='mw', 17 | description='A next generation version of enum4linux', 18 | long_description=long_description, 19 | long_description_content_type='text/markdown', 20 | url='https://github.com/cddmp/enum4linux-ng', 21 | classifiers=[ 22 | 'Environment :: Console' 23 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 24 | 'Operating System :: POSIX :: Linux', 25 | 'Programming Language :: Python :: 3', 26 | 'Topic :: Security', 27 | ], 28 | python_requires='>=3.6', 29 | install_requires=requirements, 30 | scripts=['enum4linux-ng'] 31 | ) 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

enum4linux-ng

2 |

3 | A next generation version of enum4linux 4 |

5 |

6 | 7 | 8 |

9 | 10 | enum4linux-ng.py 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, aimed for security professionals and CTF players. The tool is mainly a wrapper around the Samba tools `nmblookup`, `net`, `rpcclient` and `smbclient`. 11 | 12 | I made it for educational purposes for myself and to overcome issues with enum4linux.pl. It has the same functionality as the original tool (though it does some things [differently](#Differences)). Other than the original tool it parses all output of the Samba tools and allows to export all findings as YAML or JSON file. The idea behind this is to allow other tools to import the findings and further process them. It is planned to add new features in the future. 13 | 14 | ## Features 15 | - support for YAML and JSON export 16 | - colored console output (can be disabled via [NO_COLOR](https://no-color.org/)) 17 | - ldapsearch and polenum are natively implemented 18 | - support for multiple authentication methods 19 | - support for legacy SMBv1 connections 20 | - auto detection of IPC signing support 21 | - 'smart' enumeration will automatically disable tests which would otherwise fail 22 | - timeout support 23 | - SMB dialect checks 24 | - IPv6 support (experimental) 25 | 26 | ## Differences 27 | Some things are implemented differently compared to the original enum4linux. These are the important differences: 28 | - group members are not enumerated by default, this can be enabled with ````-Gm```` 29 | - RID cycling is not part of the default enumeration (```-A```) but can be enabled with ```-R``` 30 | - RID cycling can be achieved faster, by grouping multiple SID lookups in the same rpcclient call 31 | - parameter naming is slightly different (e.g. ```-A``` instead of ```-a```) 32 | 33 | ## Credits 34 | I'd like to thank and give credit to the people at former Portcullis Labs (now Cisco CX Security Labs), namely: 35 | - Mark Lowe for creating the original 'enum4linux.pl' (https://github.com/CiscoCXSecurity/enum4linux) 36 | - Richard 'deanx' Dean for creating the original 'polenum' (https://labs.portcullis.co.uk/tools/polenum/) 37 | 38 | In addition, I'd like to thank and give credit to: 39 | - Craig 'Wh1t3Fox' West for his fork of 'polenum' (https://github.com/Wh1t3Fox/polenum) 40 | 41 | It was lots of fun reading your code! :) 42 | 43 | Last but not least, I’d like to thank the various people who contributed code, reported issues, and provided helpful suggestions on how to improve the tool. 44 | 45 | ## Legal note 46 | If you use the tool: Don't use it for illegal purposes. 47 | 48 | ## Run 49 | An example run could look like that: 50 | ```console 51 | enum4linux-ng.py -As -oY out 52 | ``` 53 | 54 | ### Demo 55 | #### Windows Server 2012 R2 56 | This demonstrates a run against Windows Server 2012 R2 standard installation. The following command is being used: 57 | 58 | ```console 59 | enum4linux-ng.py 192.168.125.131 -u Tester -p 'Start123!' -oY out 60 | ``` 61 | 62 | A user 'Tester' with password 'Start123!' was created. Firewall access was allowed. Once the enumeration is finished, I scroll up so that the results become more clear. Since no other enumeration option is specified, the tool will assume ```-A``` which behaves similar to enum4linux ```-a``` option. User and password are passed in. The ```-oY``` option will export all enumerated data as YAML file for further processing in ```out.yaml```. The tool automatically detects at the beginning that LDAP is not running on the remote host. It will therefore skip any further LDAP checks which would normally be part of the default enumeration. 63 | 64 | ![Demo](https://github.com/cddmp/misc/blob/master/screencasts/enum4linux-ng/demo1.gif) 65 | 66 | #### Metasploitable 2 67 | The second demo shows a run against Metasploitable 2. The following command is being used: 68 | 69 | ```console 70 | enum4linux-ng.py 192.168.125.145 -A -C 71 | ``` 72 | 73 | This time the ```-A``` and ```-C``` option are used. While the first one behaves similar to enum4linux ```-a``` option, the second one will enable enumeration of services. This time no credentials were provided. The tool automatically detects that it needs to use SMBv1. No YAML or JSON file is being written. Again I scroll up so that the results become more clear. 74 | 75 | ![Demo](https://github.com/cddmp/misc/blob/master/screencasts/enum4linux-ng/demo2.gif) 76 | 77 | ### Usage 78 | ```console 79 | usage: enum4linux-ng.py [-h] [-A] [-As] [-U] [-G] [-Gm] [-S] [-C] [-P] [-O] [-L] [-I] [-R [BULK_SIZE]] [-N] [-w DOMAIN] [-u USER] 80 | [-p PW | -K TICKET_FILE | -H NTHASH] [--local-auth] [-d] [-k USERS] [-r RANGES] [-s SHARES_FILE] [-t TIMEOUT] [-v] [--keep] 81 | [-oJ OUT_JSON_FILE | -oY OUT_YAML_FILE | -oA OUT_FILE] 82 | host 83 | 84 | This tool is a rewrite of Mark Lowe's enum4linux.pl, a tool for enumerating information from Windows and Samba systems. It is mainly a wrapper around the Samba 85 | tools nmblookup, net, rpcclient and smbclient. Other than the original tool it allows to export enumeration results as YAML or JSON file, so that it can be 86 | further processed with other tools. The tool tries to do a 'smart' enumeration. It first checks whether SMB or LDAP is accessible on the target. Depending on the 87 | result of this check, it will dynamically skip checks (e.g. LDAP checks if LDAP is not running). If SMB is accessible, it will always check whether a session can 88 | be set up or not. If no session can be set up, the tool will stop enumeration. The enumeration process can be interupted with CTRL+C. If the options -oJ or -oY 89 | are provided, the tool will write out the current enumeration state to the JSON or YAML file, once it receives SIGINT triggered by CTRL+C. The tool was made for 90 | security professionals and CTF players. Illegal use is prohibited. 91 | 92 | positional arguments: 93 | host 94 | 95 | options: 96 | -h, --help show this help message and exit 97 | -A Do all simple enumeration including nmblookup (-U -G -S -P -O -N -I -L). This option is enabled if you don't provide any other option. 98 | -As Do all simple short enumeration without NetBIOS names lookup (-U -G -S -P -O -I -L) 99 | -U Get users via RPC 100 | -G Get groups via RPC 101 | -Gm Get groups with group members via RPC 102 | -S Get shares via RPC 103 | -C Get services via RPC 104 | -P Get password policy information via RPC 105 | -O Get OS information via RPC 106 | -L Get additional domain info via LDAP/LDAPS (for DCs only) 107 | -I Get printer information via RPC 108 | -R [BULK_SIZE] Enumerate users via RID cycling. Optionally, specifies lookup request size. 109 | -N Do an NetBIOS names lookup (similar to nbtstat) and try to retrieve workgroup from output 110 | -w DOMAIN Specify workgroup/domain manually (usually found automatically) 111 | -u USER Specify username to use (default "") 112 | -p PW Specify password to use (default "") 113 | -K TICKET_FILE Try to authenticate with Kerberos, only useful in Active Directory environment (Note: DNS must be setup correctly for this option to work) 114 | -H NTHASH Try to authenticate with hash 115 | --local-auth Authenticate locally to target 116 | -d Get detailed information for users and groups, applies to -U, -G and -R 117 | -k USERS User(s) that exists on remote system (default: administrator,guest,krbtgt,domain admins,root,bin,none). Used to get sid with "lookupsids" 118 | -r RANGES RID ranges to enumerate (default: 500-550,1000-1050) 119 | -s SHARES_FILE Brute force guessing for shares 120 | -t TIMEOUT Sets connection timeout in seconds (default: 5s) 121 | -v Verbose, show full samba tools commands being run (net, rpcclient, etc.) 122 | --keep Don't delete the Samba configuration file created during tool run after enumeration (useful with -v) 123 | -oJ OUT_JSON_FILE Writes output to JSON file (extension is added automatically) 124 | -oY OUT_YAML_FILE Writes output to YAML file (extension is added automatically) 125 | -oA OUT_FILE Writes output to YAML and JSON file (extensions are added automatically) 126 | ``` 127 | 128 | ## Installation 129 | There are multiple ways to install the tool. Either the tool comes as a package with your Linux distribution or you need to do a manual install. 130 | 131 | ### Kali Linux 132 | ```console 133 | apt install enum4linux-ng 134 | ``` 135 | 136 | ### Archstrike 137 | ```console 138 | pacman -S enum4linux-ng 139 | ``` 140 | 141 | ### NixOS 142 | (tested on NixOS 20.9) 143 | ```console 144 | nix-env -iA nixos.enum4linux-ng 145 | ``` 146 | 147 | ## Manual Installation 148 | If your Linux distribution does not offer a package, the following manual installation methods can be used instead. 149 | 150 | ### Dependencies 151 | The tool uses the samba clients tools, namely: 152 | - nmblookup 153 | - net 154 | - rpcclient 155 | - smbclient 156 | 157 | These should be available for all Linux distributions. The package is typically called `smbclient`, `samba-client` or something similar. 158 | 159 | In addition, you will need the following Python packages: 160 | - ldap3 161 | - PyYaml 162 | - impacket 163 | 164 | For a faster processing of YAML (optional!) also install (should come as a dependency for PyYaml for most Linux distributions): 165 | - LibYAML 166 | 167 | Some examples for specific Linux distributions installations are listed below. Alternatively, distribution-agnostic ways (python pip, python virtual env and Docker) are possible. 168 | 169 | ### Linux distribution specific 170 | For all distribution examples below, LibYAML is already a dependency of the corresponding PyYaml package and will be therefore installed automatically. 171 | #### ArchLinux 172 | 173 | ```console 174 | pacman -S smbclient python-ldap3 python-yaml impacket 175 | ``` 176 | #### Fedora/CentOS/RHEL 177 | (tested on Fedora Workstation 31) 178 | 179 | ```console 180 | dnf install samba-common-tools samba-client python3-ldap3 python3-pyyaml python3-impacket 181 | ``` 182 | 183 | #### Debian/Ubuntu/Linux Mint 184 | (For Ubuntu 18.04 or below use the Docker or Python virtual environment variant) 185 | 186 | ```console 187 | apt install smbclient python3-ldap3 python3-yaml python3-impacket 188 | ``` 189 | 190 | ### Linux distribution-agnostic 191 | #### Python pip 192 | Depending on the Linux distribution either `pip3` or `pip` is needed: 193 | 194 | ```console 195 | pip install pyyaml ldap3 impacket 196 | ``` 197 | 198 | Alternative: 199 | 200 | ```console 201 | pip install -r requirements.txt 202 | ``` 203 | 204 | Remember you need to still install the samba tools as mentioned above. 205 | 206 | #### Python virtual environment 207 | ```console 208 | git clone https://github.com/cddmp/enum4linux-ng 209 | cd enum4linux-ng 210 | python3 -m venv venv 211 | source venv/bin/activate 212 | pip install wheel 213 | pip install -r requirements.txt 214 | ``` 215 | Then run via: 216 | 217 | ```console 218 | python3 enum4linux-ng.py -As 219 | ``` 220 | 221 | Remember you need to still install the samba tools as mentioned above. In addition, make sure you run ```source venv/bin/activate``` everytime you spawn a new shell. Otherwise the wrong Python interpreter with the wrong libraries will be used (your system one rather than the virtual environment one). 222 | 223 | #### Docker 224 | ```console 225 | git clone https://github.com/cddmp/enum4linux-ng 226 | cd enum4linux-ng 227 | docker build . --tag enum4linux-ng 228 | ``` 229 | Once finished an example run could look like this: 230 | ```console 231 | docker run -t enum4linux-ng -As 232 | ``` 233 | ## Contribution and Support 234 | Occassionally, the tool will spit out error messages like this: 235 | 236 | ```Could not , please open a GitHub issue``` 237 | 238 | In that case, please rerun the tool with the ```-v``` and ```--keep``` option. This will allow you to see the exact command which caused the error message. Copy that command, run it in your terminal and redirect the output to a file. Then open a GitHub issue here, pasting the command and attaching the error output file. That helps to debug the issue. Of course, you can debug it yourself and make a pull request. 239 | 240 | If the tool is helpful for you, I'm happy if you leave a star! 241 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /enum4linux-ng.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # pylint: disable=C0301, E1101 4 | 5 | ### ENUM4LINUX-NG 6 | # This tool is a rewrite of Mark Lowe's (former Portcullis Labs, now Cisco CX Security Labs ) enum4linux.pl, 7 | # a tool for enumerating information from Windows and Samba systems. 8 | # As the original enum4linux.pl, this tool is mainly a wrapper around the Samba tools 'nmblookup', 'net', 9 | # 'rpcclient' and 'smbclient'. Other than the original enum4linux.pl, enum4linux-ng parses all output of 10 | # the previously mentioned commands and (if the user requests so), fills the data in JSON/YAML output. 11 | # The original enum4linux.pl had the additional dependencies 'ldapsearch' and 'polenum.py'. These are 12 | # natively implemented in enum4linux-ng. Console output is colored (can be deactivated by setting the 13 | # environment variable NO_COLOR to an arbitrary value). 14 | # 15 | ### CREDITS 16 | # I'd like to thank and give credit to the people at former Portcullis Labs (now Cisco CX Security Labs), namely: 17 | # 18 | # - Mark Lowe for creating the original 'enum4linux.pl' 19 | # https://github.com/CiscoCXSecurity/enum4linux 20 | # 21 | # - Richard "deanx" Dean for creating the original 'polenum' 22 | # https://labs.portcullis.co.uk/tools/polenum/ 23 | # 24 | # In addition, I'd like to thank and give credit to: 25 | # - Craig "Wh1t3Fox" West for his fork of 'polenum' 26 | # https://github.com/Wh1t3Fox/polenum 27 | # 28 | # 29 | ### DESIGN 30 | # 31 | # Error handling 32 | # ============== 33 | # 34 | # * Functions: 35 | # * return value is None 36 | # => an error happened, error messages will be printed out and will end up in the JSON/YAML with value 37 | # null (see also YAML/JSON below) 38 | # 39 | # * return value is an empty [],{},"" 40 | # => no error, nothing was returned (e.g. a group has no members) 41 | # 42 | # * return value is False for... 43 | # - sessions: 44 | # => it was not possible to set up the particular session with the target 45 | # - services: 46 | # => error, it was not possible to setup a service connection 47 | # - all other booleans: 48 | # => no errors 49 | # 50 | # * YAML/JSON: 51 | # * null 52 | # => an error happened (i.e. a function returned None which translates to null in JSON/YAML), in 53 | # this case an error message was generated and can be found under: 54 | # - 'errors', for which the error happened (e.g. os_info), where the error occured 55 | # (e.g. module_srvinfo) 56 | # 57 | # * missing key 58 | # => either it was not part of the enumeration because the user did not request it (aka did not provide 59 | # the right parameter when running enum4linux-ng) 60 | # => or it was part of the enumeration but no session could be set up (see above), in this case 61 | # - 'sessions', 'sessions_possible' should be 'False' 62 | # 63 | # Authentication 64 | # ============== 65 | # * Kerberos: 66 | # * While testing Kerberos authentication with the Samba client tools and the impacket library, it turned 67 | # out that they behave quite differently. While the impacket library will honor the username and the domain 68 | # given, it seems that the Samba client ignores them (-U and -W parameter) and uses the ones from the ticket 69 | # itself. 70 | # 71 | ### LICENSE 72 | # This tool may be used for legal purposes only. Users take full responsibility 73 | # for any actions performed using this tool. The author accepts no liability 74 | # for damage caused by this tool. If these terms are not acceptable to you, then 75 | # you are not permitted to use this tool. 76 | # 77 | # In all other respects the GPL version 3 applies. 78 | # 79 | # The original enum4linux.pl was released under GPL version 2 or later. 80 | # The original polenum.py was released under GPL version 3. 81 | 82 | from argparse import ArgumentParser 83 | from collections import OrderedDict 84 | from datetime import datetime, timezone 85 | import json 86 | import os 87 | import random 88 | import re 89 | import shutil 90 | import shlex 91 | import socket 92 | from subprocess import check_output, STDOUT, TimeoutExpired 93 | import sys 94 | import tempfile 95 | from impacket import nmb, smb, smbconnection, smb3 96 | from impacket.smbconnection import SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_311 97 | from impacket.dcerpc.v5.rpcrt import DCERPC_v5 98 | from impacket.dcerpc.v5 import transport, samr 99 | from ldap3 import Server, Connection, DSA 100 | import yaml 101 | from enum import Enum 102 | 103 | try: 104 | from yaml import CDumper as Dumper 105 | except ImportError: 106 | from yaml import Dumper 107 | 108 | ############################################################################### 109 | # The following mappings for nmblookup (nbtstat) status codes to human readable 110 | # format is taken from nbtscan 1.5.1 "statusq.c". This file in turn 111 | # was derived from the Samba package which contains the following 112 | # license: 113 | # Unix SMB/Netbios implementation 114 | # Version 1.9 115 | # Main SMB server routine 116 | # Copyright (C) Andrew Tridgell 1992-199 117 | # 118 | # This program is free software; you can redistribute it and/or modif 119 | # it under the terms of the GNU General Public License as published b 120 | # the Free Software Foundation; either version 2 of the License, o 121 | # (at your option) any later version 122 | # 123 | # This program is distributed in the hope that it will be useful 124 | # but WITHOUT ANY WARRANTY; without even the implied warranty o 125 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See th 126 | # GNU General Public License for more details 127 | # 128 | # You should have received a copy of the GNU General Public Licens 129 | # along with this program; if not, write to the Free Softwar 130 | # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA 131 | NBT_INFO = [ 132 | ["__MSBROWSE__", "01", False, "Master Browser"], 133 | ["INet~Services", "1C", False, "IIS"], 134 | ["IS~", "00", True, "IIS"], 135 | ["", "00", True, "Workstation Service"], 136 | ["", "01", True, "Messenger Service"], 137 | ["", "03", True, "Messenger Service"], 138 | ["", "06", True, "RAS Server Service"], 139 | ["", "1F", True, "NetDDE Service"], 140 | ["", "20", True, "File Server Service"], 141 | ["", "21", True, "RAS Client Service"], 142 | ["", "22", True, "Microsoft Exchange Interchange(MSMail Connector)"], 143 | ["", "23", True, "Microsoft Exchange Store"], 144 | ["", "24", True, "Microsoft Exchange Directory"], 145 | ["", "30", True, "Modem Sharing Server Service"], 146 | ["", "31", True, "Modem Sharing Client Service"], 147 | ["", "43", True, "SMS Clients Remote Control"], 148 | ["", "44", True, "SMS Administrators Remote Control Tool"], 149 | ["", "45", True, "SMS Clients Remote Chat"], 150 | ["", "46", True, "SMS Clients Remote Transfer"], 151 | ["", "4C", True, "DEC Pathworks TCPIP service on Windows NT"], 152 | ["", "52", True, "DEC Pathworks TCPIP service on Windows NT"], 153 | ["", "87", True, "Microsoft Exchange MTA"], 154 | ["", "6A", True, "Microsoft Exchange IMC"], 155 | ["", "BE", True, "Network Monitor Agent"], 156 | ["", "BF", True, "Network Monitor Application"], 157 | ["", "03", True, "Messenger Service"], 158 | ["", "00", False, "Domain/Workgroup Name"], 159 | ["", "1B", True, "Domain Master Browser"], 160 | ["", "1C", False, "Domain Controllers"], 161 | ["", "1D", True, "Master Browser"], 162 | ["", "1E", False, "Browser Service Elections"], 163 | ["", "2B", True, "Lotus Notes Server Service"], 164 | ["IRISMULTICAST", "2F", False, "Lotus Notes"], 165 | ["IRISNAMESERVER", "33", False, "Lotus Notes"], 166 | ['Forte_$ND800ZA', "20", True, "DCA IrmaLan Gateway Server Service"] 167 | ] 168 | 169 | # ACB (Account Control Block) contains flags an SAM account 170 | ACB_DICT = { 171 | 0x00000001: "Account Disabled", 172 | 0x00000200: "Password not expired", 173 | 0x00000400: "Account locked out", 174 | 0x00020000: "Password expired", 175 | 0x00000040: "Interdomain trust account", 176 | 0x00000080: "Workstation trust account", 177 | 0x00000100: "Server trust account", 178 | 0x00002000: "Trusted for delegation" 179 | } 180 | 181 | # Source: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/d275ab19-10b0-40e0-94bb-45b7fc130025 182 | DOMAIN_FIELDS = { 183 | 0x00000001: "DOMAIN_PASSWORD_COMPLEX", 184 | 0x00000002: "DOMAIN_PASSWORD_NO_ANON_CHANGE", 185 | 0x00000004: "DOMAIN_PASSWORD_NO_CLEAR_CHANGE", 186 | 0x00000008: "DOMAIN_PASSWORD_LOCKOUT_ADMINS", 187 | 0x00000010: "DOMAIN_PASSWORD_PASSWORD_STORE_CLEARTEXT", 188 | 0x00000020: "DOMAIN_PASSWORD_REFUSE_PASSWORD_CHANGE" 189 | } 190 | 191 | # Source: https://docs.microsoft.com/en-us/windows/win32/sysinfo/operating-system-version 192 | OS_VERSIONS = { 193 | "10.0": "Windows 10, Windows Server 2019, Windows Server 2016", 194 | "6.3": "Windows 8.1, Windows Server 2012 R2", 195 | "6.2": "Windows 8, Windows Server 2012", 196 | "6.1": "Windows 7, Windows Server 2008 R2", 197 | "6.0": "Windows Vista, Windows Server 2008", 198 | "5.2": "Windows XP 64-Bit Edition, Windows Server 2003, Windows Server 2003 R2", 199 | "5.1": "Windows XP", 200 | "5.0": "Windows 2000", 201 | } 202 | 203 | # Source: https://docs.microsoft.com/de-de/windows/release-health/release-information 204 | OS_RELEASE = { 205 | "19045": "22H2", 206 | "19044": "21H2", 207 | "19043": "21H1", 208 | "19042": "20H2", 209 | "19041": "2004", 210 | "18363": "1909", 211 | "18362": "1903", 212 | "17763": "1809", 213 | "17134": "1803", 214 | "16299": "1709", 215 | "15063": "1703", 216 | "14393": "1607", 217 | "10586": "1511", 218 | "10240": "1507" 219 | } 220 | 221 | # Filter for various samba client setup related error messages including bug 222 | # https://bugzilla.samba.org/show_bug.cgi?id=13925 223 | SAMBA_CLIENT_ERRORS = [ 224 | "Unable to initialize messaging context", 225 | "WARNING: no network interfaces found", 226 | "Can't load /etc/samba/smb.conf - run testparm to debug it" 227 | ] 228 | 229 | # Translates various SMB dialect values to human readable strings 230 | SMB_DIALECTS = { 231 | SMB_DIALECT: "SMB 1.0", 232 | SMB2_DIALECT_002: "SMB 2.0.2", 233 | SMB2_DIALECT_21: "SMB 2.1", 234 | SMB2_DIALECT_30: "SMB 3.0", 235 | SMB2_DIALECT_311: "SMB 3.1.1" 236 | } 237 | 238 | # This list will be used by the function nt_status_error_filter() which is typically 239 | # called after running a Samba client command (see run()). The idea is to filter out 240 | # common errors. For very specific status errors, please don't handle them here but 241 | # in the corresponding enumeration class/function. 242 | # In the current implementation this list is case insensitive. Also the order of errors 243 | # is important. Errors on top will be processed first. The access denied errors should 244 | # be kept on top since they occur typically first (see also comment on 245 | # STATUS_CONNECTION_DISCONNECTED). 246 | NT_STATUS_COMMON_ERRORS = [ 247 | "RPC_S_ACCESS_DENIED", 248 | "DCERPC_FAULT_ACCESS_DENIED", 249 | "WERR_ACCESS_DENIED", 250 | "STATUS_ACCESS_DENIED", 251 | "STATUS_ACCOUNT_LOCKED_OUT", 252 | "STATUS_NO_LOGON_SERVERS", 253 | "STATUS_LOGON_FAILURE", 254 | "STATUS_IO_TIMEOUT", 255 | "STATUS_NETWORK_UNREACHABLE", 256 | "STATUS_INVALID_PARAMETER", 257 | "STATUS_NOT_SUPPORTED", 258 | "STATUS_NO_SUCH_FILE", 259 | "STATUS_PASSWORD_EXPIRED", 260 | # This error code is from the depths of CIFS/SMBv1 261 | # https://tools.ietf.org/id/draft-leach-cifs-v1-spec-01.txt 262 | "ERRSRV:ERRaccess", 263 | # This error is misleading. It can occur when the an SMB client cannot negotiate 264 | # a connection with the SMB server e.g., because of both not supporting each others 265 | # SMB dialect. But this error can also occur if during an RPC call access was denied 266 | # to a specific ressource/function call. In this case the oppositve site often disconnects 267 | # and the Samba client tools will show this error. 268 | "STATUS_CONNECTION_DISCONNECTED" 269 | ] 270 | 271 | # Supported authentication methods/protocols 272 | AUTH_PASSWORD = "password" 273 | AUTH_NTLM = "NTLM" 274 | AUTH_KERBEROS = "Kerberos" 275 | AUTH_NULL = "null" 276 | AUTH_GUEST = "guest" 277 | 278 | # Mapping from errno to string for socket errors we often come across 279 | SOCKET_ERRORS = { 280 | 11: "timed out", 281 | 110: "timed out", 282 | 111: "connection refused", 283 | 113: "no route to host" 284 | } 285 | 286 | # This is needed for the ListenersScan class 287 | SERVICE_LDAP = "LDAP" 288 | SERVICE_LDAPS = "LDAPS" 289 | SERVICE_SMB = "SMB" 290 | SERVICE_SMB_NETBIOS = "SMB over NetBIOS" 291 | SERVICES = { 292 | SERVICE_LDAP: 389, 293 | SERVICE_LDAPS: 636, 294 | SERVICE_SMB: 445, 295 | SERVICE_SMB_NETBIOS: 139 296 | } 297 | 298 | # The current list of module names 299 | ENUM_LDAP_DOMAIN_INFO = "enum_ldap_domain_info" 300 | ENUM_NETBIOS = "enum_netbios" 301 | ENUM_SMB = "enum_smb" 302 | ENUM_SESSIONS = "enum_sessions" 303 | ENUM_SMB_DOMAIN_INFO = "enum_smb_domain_info" 304 | ENUM_LSAQUERY_DOMAIN_INFO = "enum_lsaquery_domain_info" 305 | ENUM_USERS_RPC = "enum_users_rpc" 306 | ENUM_GROUPS_RPC = "enum_groups_rpc" 307 | ENUM_SHARES = "enum_shares" 308 | ENUM_SERVICES = "enum_services" 309 | ENUM_LISTENERS = "enum_listeners" 310 | ENUM_POLICY = "enum_policy" 311 | ENUM_PRINTERS = "enum_printers" 312 | ENUM_OS_INFO = "enum_os_info" 313 | RID_CYCLING = "rid_cycling" 314 | BRUTE_FORCE_SHARES = "brute_force_shares" 315 | 316 | DEPS = ["nmblookup", "net", "rpcclient", "smbclient"] 317 | RID_RANGES = "500-550,1000-1050" 318 | KNOWN_USERNAMES = "administrator,guest,krbtgt,domain admins,root,bin,none" 319 | TIMEOUT = 10 320 | 321 | GLOBAL_VERSION = '1.3.7' 322 | GLOBAL_VERBOSE = False 323 | GLOBAL_COLORS = True 324 | GLOBAL_SAMBA_LEGACY = False 325 | 326 | class Colors(Enum): 327 | red = '\033[91m' 328 | green = '\033[92m' 329 | yellow = '\033[93m' 330 | blue = '\033[94m' 331 | 332 | def __call__(self, message): 333 | if GLOBAL_COLORS: 334 | return f"{self.value}{message}\033[0m" 335 | return message 336 | 337 | class Result: 338 | ''' 339 | The idea of the Result class is, that functions can easily return a return value 340 | as well as a return message. The return message can be further processed or printed 341 | out by the calling function, while the return value is supposed to be added to the 342 | output dictionary (contained in class Output), which will be later converted to JSON/YAML. 343 | ''' 344 | def __init__(self, retval, retmsg): 345 | self.retval = retval 346 | self.retmsg = retmsg 347 | 348 | class Target: 349 | ''' 350 | Target encapsulates various target information. The class should only be instantiated once and 351 | passed during the enumeration to the various modules. This allows to modify/update target information 352 | during enumeration. 353 | ''' 354 | def __init__(self, host, credentials, port=None, tls=None, timeout=None, samba_config=None): 355 | self.host = host 356 | self.creds = credentials 357 | self.port = port 358 | self.timeout = timeout 359 | self.tls = tls 360 | self.samba_config = samba_config 361 | 362 | self.ip_version = None 363 | self.smb_ports = [] 364 | self.ldap_ports = [] 365 | self.listeners = [] 366 | self.smb_preferred_dialect = None 367 | self.smb1_supported = False 368 | self.smb1_only = False 369 | 370 | self.sessions = {"sessions_possible":False, 371 | AUTH_NULL:False, 372 | AUTH_PASSWORD:False, 373 | AUTH_KERBEROS:False, 374 | AUTH_NTLM:False, 375 | AUTH_GUEST:False, 376 | } 377 | 378 | result = self.valid_host(host) 379 | if not result.retval: 380 | raise Exception(result.retmsg) 381 | 382 | def valid_host(self, host): 383 | try: 384 | result = socket.getaddrinfo(host, None) 385 | 386 | # Check IP version, alternatively we could save the socket type here 387 | ip_version = result[0][0] 388 | if ip_version == socket.AF_INET6: 389 | self.ip_version = 6 390 | elif ip_version == socket.AF_INET: 391 | self.ip_version = 4 392 | 393 | # Kerberos requires resolvable hostnames rather than IP adresses 394 | ip = result[0][4][0] 395 | if ip == host and self.creds.auth_method == AUTH_KERBEROS: 396 | return Result(False, f'Kerberos authentication requires a hostname, but an IPv{self.ip_version} address was given') 397 | 398 | return Result(True,'') 399 | except Exception as e: 400 | if isinstance(e, OSError) and e.errno == -2: 401 | return Result(False, f'Could not resolve host {host}') 402 | return Result(False, 'No valid host given') 403 | 404 | def as_dict(self): 405 | return {'target':{'host':self.host}} 406 | 407 | class Credentials: 408 | ''' 409 | Stores usernames and password. 410 | ''' 411 | def __init__(self, user='', pw='', domain='', ticket_file='', nthash='', local_auth=False): 412 | # Create an alternative user with pseudo-random username 413 | self.random_user = ''.join(random.choice("abcdefghijklmnopqrstuvwxyz") for i in range(8)) 414 | self.user = user 415 | self.pw = pw 416 | self.ticket_file = ticket_file 417 | self.nthash = nthash 418 | self.local_auth = local_auth 419 | 420 | # Only set the domain here, if it is not empty 421 | self.domain = '' 422 | if domain: 423 | self.set_domain(domain) 424 | 425 | if ticket_file: 426 | result = self.valid_ticket(ticket_file) 427 | if not result.retval: 428 | raise Exception(result.retmsg) 429 | self.auth_method = AUTH_KERBEROS 430 | elif nthash: 431 | result = self.valid_nthash(nthash) 432 | if not result.retval: 433 | raise Exception(result.retmsg) 434 | if nthash and not user: 435 | raise Exception("NT hash given (-H) without any user, please provide a username (-u)") 436 | self.auth_method = AUTH_NTLM 437 | elif not user and not pw: 438 | self.auth_method = AUTH_NULL 439 | else: 440 | if pw and not user: 441 | raise Exception("Password given (-p) without any user, please provide a username (-u)") 442 | self.auth_method = AUTH_PASSWORD 443 | 444 | def valid_nthash(self, nthash): 445 | hash_len = len(nthash) 446 | if hash_len != 32: 447 | return Result(False, f'The given hash has {hash_len} characters instead of 32 characters') 448 | if not re.match(r"^[a-fA-F0-9]{32}$", nthash): 449 | return Result(False, f'The given hash contains invalid characters') 450 | return Result(True, '') 451 | 452 | def valid_ticket(self, ticket_file): 453 | return valid_file(ticket_file, mode='600') 454 | 455 | # Allows various modules to set the domain during enumeration. The domain can only be set once. 456 | # Currently, we rely on the information gained via unauth smb session to guess the domain. 457 | # At a later call of lsaquery it might turn out that the domain is different. In this case the 458 | # user will be informed via print_hint() 459 | def set_domain(self, domain): 460 | if self.domain and self.domain.lower() == domain.lower(): 461 | return True 462 | if not self.domain: 463 | self.domain = domain 464 | return True 465 | return False 466 | 467 | def as_dict(self): 468 | 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})} 469 | 470 | class SmbConnection(): 471 | def __init__(self, target, creds=Credentials(), dialect=None): 472 | self.target = target 473 | self.creds = creds 474 | self.dialect = dialect 475 | self._conn = None 476 | 477 | self.connect() 478 | 479 | def connect(self): 480 | self._conn = smbconnection.SMBConnection(self.target.host, self.target.host, sess_port=self.target.port, timeout=self.target.timeout, preferredDialect=self.dialect) 481 | 482 | def login(self): 483 | creds = self.creds 484 | 485 | # Take a backup of the environment, in case we modify it for Kerberos 486 | env = os.environ.copy() 487 | try: 488 | if creds.ticket_file: 489 | # Currently we let impacket extract user and domain from the ticket 490 | os.environ['KRB5CCNAME'] = creds.ticket_file 491 | self._conn.kerberosLogin('', creds.pw, domain='', useCache=True) 492 | elif creds.nthash: 493 | self._conn.login(creds.user, creds.pw, domain=creds.domain, nthash=creds.nthash) 494 | else: 495 | self._conn.login(creds.user, creds.pw, creds.domain) 496 | except Exception as e: 497 | #FIXME: Might need adjustment 498 | return Result((None, None), process_impacket_smb_exception(e, self.target)) 499 | finally: 500 | # Restore environment in any case 501 | os.environ.clear() 502 | os.environ.update(env) 503 | 504 | def close(self): 505 | self._conn.close() 506 | 507 | def get_dialect(self): 508 | return self._conn.getDialect() 509 | 510 | def is_signing_required(self): 511 | return self._conn.isSigningRequired() 512 | 513 | def get_raw(self): 514 | return self._conn 515 | 516 | def get_server_lanman(self): 517 | return self._conn.getSMBServer().get_server_lanman() 518 | 519 | def get_server_os(self): 520 | return self._conn.getSMBServer().get_server_os() 521 | 522 | def get_server_os_major(self): 523 | return self._conn.getServerOSMajor() 524 | 525 | def get_server_os_minor(self): 526 | return self._conn.getServerOSMinor() 527 | 528 | def get_server_os_build(self): 529 | return self._conn.getServerOSBuild() 530 | 531 | def get_server_domain(self): 532 | return self._conn.getServerDomain() 533 | 534 | def get_server_name(self): 535 | return self._conn.getServerName() 536 | 537 | def get_server_dns_hostname(self): 538 | return self._conn.getServerDNSHostName() 539 | 540 | def get_server_dns_domainname(self): 541 | return self._conn.getServerDNSDomainName() 542 | 543 | class DceRpc(): 544 | def __init__(self, smb_conn): 545 | self._smb_conn = smb_conn 546 | self.dce = None 547 | self.filename = None 548 | self.msrpc_uuid = None 549 | 550 | if isinstance(self, SAMR): 551 | self.filename = r'\samr' 552 | self.msrpc_uuid = samr.MSRPC_UUID_SAMR 553 | 554 | self._connect() 555 | 556 | def _connect(self): 557 | rpctransport = transport.SMBTransport(smb_connection=self._smb_conn.get_raw(), filename=self.filename, remoteName=self._smb_conn.target.host) 558 | self.dce = DCERPC_v5(rpctransport) 559 | self.dce.connect() 560 | self.dce.bind(self.msrpc_uuid) 561 | 562 | class SAMR(DceRpc): 563 | def __init__(self, smb_conn=None): 564 | super().__init__(smb_conn) 565 | 566 | self._server_handle = self._get_server_handle() 567 | 568 | def _get_server_handle(self): 569 | # TODO: Investigate on the various hSamrConnect{_,2,3,4,5}() functions - hSamrConnect() results in STATUS_ACCESS_DENIED on old machines 570 | resp = samr.hSamrConnect2(self.dce) 571 | return resp['ServerHandle'] 572 | 573 | def get_domains(self): 574 | resp = samr.hSamrEnumerateDomainsInSamServer(self.dce, self._server_handle) 575 | domains = resp['Buffer']['Buffer'] 576 | domain_names = [] 577 | for domain in domains: 578 | domain_names.append(domain['Name']) 579 | return domain_names 580 | 581 | def get_domain_handle(self, domain_name): 582 | resp = samr.hSamrLookupDomainInSamServer(self.dce, self._server_handle, domain_name) 583 | resp = samr.hSamrOpenDomain(self.dce, serverHandle = self._server_handle, domainId = resp['DomainId']) 584 | return resp['DomainHandle'] 585 | 586 | def get_domain_password_information(self, domain_handle): 587 | resp = samr.hSamrQueryInformationDomain2(self.dce, domainHandle=domain_handle, domainInformationClass=samr.DOMAIN_INFORMATION_CLASS.DomainPasswordInformation) 588 | return resp['Buffer']['Password'] 589 | 590 | def get_domain_lockout_information(self, domain_handle): 591 | resp = samr.hSamrQueryInformationDomain2(self.dce, domainHandle=domain_handle, domainInformationClass=samr.DOMAIN_INFORMATION_CLASS.DomainLockoutInformation) 592 | return resp['Buffer']['Lockout'] 593 | 594 | def get_domain_logoff_information(self, domain_handle): 595 | resp = samr.hSamrQueryInformationDomain2(self.dce, domainHandle=domain_handle, domainInformationClass=samr.DOMAIN_INFORMATION_CLASS.DomainLogoffInformation) 596 | return resp['Buffer']['Logoff'] 597 | 598 | def query_display_information(self, domain_handle): 599 | resp = samr.hSamrQueryDisplayInformation(self.dce, domainHandle=domain_handle) 600 | return resp['Buffer']['UserInformation']['Buffer'] 601 | 602 | class SambaTool(): 603 | ''' 604 | Encapsulates various Samba Tools. 605 | ''' 606 | 607 | def __init__(self, command, target, creds): 608 | self.target = target 609 | self.creds = creds 610 | self.env = None 611 | 612 | # This list stores the various parts of the command which will be later executed by run(). 613 | self.exec = [] 614 | 615 | # Set authentication method 616 | if self.creds: 617 | if creds.ticket_file: 618 | # Set KRB5CCNAME as environment variable and let it point to the ticket. 619 | # The environment will be later passed to check_output() (see run() below). 620 | self.env = os.environ.copy() 621 | self.env['KRB5CCNAME'] = self.creds.ticket_file 622 | # User and domain are taken from the ticket 623 | # Kerberos options differ between samba versions - TODO: Can be removed in the future 624 | if GLOBAL_SAMBA_LEGACY: 625 | self.exec += ['-k'] 626 | else: 627 | self.exec += ['--use-krb5-ccache', self.creds.ticket_file] 628 | elif creds.nthash: 629 | self.exec += ['-W', f'{self.creds.domain}'] 630 | self.exec += ['-U', f'{self.creds.user}%{self.creds.nthash}', '--pw-nt-hash'] 631 | else: 632 | self.exec += ['-W', f'{self.creds.domain}'] 633 | self.exec += ['-U', f'{self.creds.user}%{self.creds.pw}'] 634 | 635 | # If the target has a custom Samba configuration attached, we will add it to the 636 | # command. This allows to modify the behaviour of the samba client commands during 637 | # run (e.g. enforce legacy SMBv1). 638 | if target.samba_config: 639 | self.exec += ['-s', f'{target.samba_config.get_path()}'] 640 | 641 | # This enables debugging output (level 1) for the Samba client tools. The problem is that the 642 | # tools often throw misleading error codes like NT_STATUS_CONNECTION_DISCONNECTED. Often this 643 | # error is associated with SMB dialect incompatibilities between client and server. But this 644 | # error also occurs on other occasions. In order to find out the real reason we need to fetch 645 | # earlier errors which this debugging level will provide. 646 | #self.exec += ['-d1'] 647 | 648 | def run(self, log, error_filter=True): 649 | ''' 650 | Runs a samba client command (net, nmblookup, smbclient or rpcclient) and does some basic output filtering. 651 | ''' 652 | 653 | if GLOBAL_VERBOSE and log: 654 | print_verbose(f"{log}, running command: {' '.join(shlex.quote(x) for x in self.exec)}") 655 | 656 | try: 657 | output = check_output(self.exec, env=self.env, shell=False, stderr=STDOUT, timeout=self.target.timeout) 658 | retval = 0 659 | except TimeoutExpired: 660 | return Result(False, "timed out") 661 | except Exception as e: 662 | output = e.output 663 | retval = 1 664 | 665 | output = output.decode() 666 | for line in output.splitlines(True): 667 | if any(entry in line for entry in SAMBA_CLIENT_ERRORS): 668 | output = output.replace(line, "") 669 | output = output.rstrip('\n') 670 | 671 | if "Cannot find KDC for realm" in output: 672 | return Result(False, "Cannot find KDC for realm, check DNS settings or setup /etc/krb5.conf") 673 | 674 | if retval == 1 and not output: 675 | return Result(False, "empty response") 676 | 677 | if error_filter: 678 | nt_status_error = nt_status_error_filter(output) 679 | if nt_status_error: 680 | return Result(False, nt_status_error) 681 | 682 | return Result(True, output) 683 | 684 | class SambaSmbclient(SambaTool): 685 | ''' 686 | Encapsulates a subset of the functionality of the Samba smbclient command. 687 | ''' 688 | def __init__(self, command, target, creds): 689 | super().__init__(command, target, creds) 690 | 691 | # Set timeout 692 | self.exec += ['-t', f'{target.timeout}'] 693 | 694 | # Build command 695 | if command[0] == 'list': 696 | self.exec += ['-L', f'//{target.host}', '-g'] 697 | elif command[0] == 'help': 698 | self.exec += ['-c','help', f'//{target.host}/ipc$'] 699 | elif command[0] == 'dir' and command[1]: 700 | self.exec += ['-c','dir', f'//{target.host}/{command[1]}'] 701 | 702 | self.exec = ['smbclient'] + self.exec 703 | 704 | class SambaRpcclient(SambaTool): 705 | ''' 706 | Encapsulates a subset of the functionality of the Samba rpcclient command. 707 | ''' 708 | def __init__(self, command, target, creds): 709 | super().__init__(command, target, creds) 710 | 711 | # Build command 712 | if command[0] == 'queryuser': 713 | rid = command[1] 714 | self.exec += ['-c', f'{command[0]} {rid}'] 715 | elif command[0] == 'querygroup': 716 | rid = command[1] 717 | self.exec += ['-c', f'{command[0]} {rid}'] 718 | elif command[0] == 'enumalsgroups': 719 | group_type = command[1] 720 | self.exec += ['-c', f'{command[0]} {group_type}'] 721 | elif command[0] == 'lookupnames': 722 | username = command[1] 723 | self.exec += ['-c', f'{command[0]} {username}'] 724 | elif command[0] == 'lookupsids': 725 | sid = command[1] 726 | self.exec += ['-c', f'{command[0]} {sid}'] 727 | # Currently, here the following commands should be handled: 728 | # enumprinters 729 | # enumdomusers, enumdomgroups 730 | # lsaenumsid, lsaquery 731 | # querydispinfo 732 | # srvinfo 733 | else: 734 | self.exec += ['-c', f'{command[0]}'] 735 | 736 | self.exec += [ target.host ] 737 | self.exec = ['rpcclient'] + self.exec 738 | 739 | class SambaNet(SambaTool): 740 | ''' 741 | Encapsulates a subset of the functionality of the Samba net command. 742 | ''' 743 | def __init__(self, command, target, creds): 744 | super().__init__(command, target, creds) 745 | 746 | # Set timeout 747 | self.exec += ['-t', f'{target.timeout}'] 748 | 749 | # Build command 750 | if command[0] == 'rpc': 751 | if command[1] == 'group': 752 | if command[2] == 'members': 753 | groupname = command[3] 754 | self.exec += [f'{command[0]}', f'{ command[1]}', f'{command[2]}', groupname] 755 | if command[1] == 'service': 756 | if command[2] == 'list': 757 | self.exec += [f'{command[0]}', f'{ command[1]}', f'{command[2]}'] 758 | 759 | self.exec += [ "-S", target.host ] 760 | self.exec = ['net'] + self.exec 761 | 762 | class SambaNmblookup(SambaTool): 763 | ''' 764 | Encapsulates the nmblookup command. Currently only the -A option is supported. 765 | ''' 766 | def __init__(self, target): 767 | super().__init__(None, target, creds=None) 768 | 769 | self.exec += [ "-A", target.host ] 770 | self.exec = ['nmblookup'] + self.exec 771 | 772 | class SambaConfig: 773 | ''' 774 | Allows to create custom Samba configurations which can be passed via path to the various Samba client tools. 775 | Currently such a configuration is always created on tool start. This allows to overcome issues with newer 776 | releases of the Samba client tools where certain features are disabled by default. 777 | ''' 778 | def __init__(self, entries): 779 | config = '\n'.join(['[global]']+entries) + '\n' 780 | with tempfile.NamedTemporaryFile(delete=False) as config_file: 781 | config_file.write(config.encode()) 782 | self.config_filename = config_file.name 783 | 784 | def get_path(self): 785 | return self.config_filename 786 | 787 | def add(self, entries): 788 | try: 789 | config = '\n'.join(entries) + '\n' 790 | with open(self.config_filename, 'a') as config_file: 791 | config_file.write(config) 792 | return True 793 | except: 794 | return False 795 | 796 | def delete(self): 797 | try: 798 | os.remove(self.config_filename) 799 | except OSError: 800 | return Result(False, f"Could not delete samba configuration file {self.config_filename}") 801 | return Result(True, "") 802 | 803 | class Output: 804 | ''' 805 | Output stores the output dictionary which will be filled out during the run of 806 | the tool. The update() function takes a dictionary, which will then be merged 807 | into the output dictionary (out_dict). In addition, the update() function is 808 | responsible for writing the JSON/YAML output. 809 | ''' 810 | def __init__(self, out_file=None, out_file_type=None): 811 | self.out_file = out_file 812 | self.out_file_type = out_file_type 813 | self.out_dict = OrderedDict({"errors":{}}) 814 | 815 | def update(self, content): 816 | # The following is needed, since python3 does not support nested merge of 817 | # dictionaries out of the box: 818 | 819 | # Temporarily save the current "errors" sub dict. Then update out_dict with the new 820 | # content. If "content" also had an "errors" dict (e.g. if the module run failed), 821 | # this would overwrite the "errors" dict from the previous run. Therefore, 822 | # we replace the old out_dict["errors"] with the saved one. A proper merge will 823 | # then be done further down. 824 | old_errors_dict = self.out_dict["errors"] 825 | self.out_dict.update(content) 826 | self.out_dict["errors"] = old_errors_dict 827 | 828 | # Merge dicts 829 | if "errors" in content: 830 | new_errors_dict = content["errors"] 831 | 832 | for key, value in new_errors_dict.items(): 833 | if key in old_errors_dict: 834 | self.out_dict["errors"][key] = {**old_errors_dict[key], **new_errors_dict[key]} 835 | else: 836 | self.out_dict["errors"][key] = value 837 | 838 | def flush(self): 839 | # Only for nice JSON/YAML output (errors at the end) 840 | self.out_dict.move_to_end("errors") 841 | 842 | # Write JSON/YAML 843 | if self.out_file is not None: 844 | if "json" in self.out_file_type and not self._write_json(): 845 | return Result(False, f"Could not write JSON output to {self.out_file}.json") 846 | if "yaml" in self.out_file_type and not self._write_yaml(): 847 | return Result(False, f"Could not write YAML output to {self.out_file}.yaml") 848 | return Result(True, "") 849 | 850 | def _write_json(self): 851 | try: 852 | with open(f"{self.out_file}.json", 'w') as f: 853 | f.write(json.dumps(self.out_dict, indent=4)) 854 | except OSError: 855 | return False 856 | return True 857 | 858 | def _write_yaml(self): 859 | try: 860 | with open(f"{self.out_file}.yaml", 'w') as f: 861 | f.write(yamlize(self.out_dict, rstrip=False)) 862 | except OSError: 863 | return False 864 | return True 865 | 866 | def as_dict(self): 867 | return self.out_dict 868 | 869 | ### Listeners Scans 870 | 871 | class ListenersScan(): 872 | def __init__(self, target, scan_list): 873 | self.target = target 874 | self.scan_list = scan_list 875 | self.listeners = OrderedDict({}) 876 | 877 | def run(self): 878 | module_name = ENUM_LISTENERS 879 | output = {} 880 | 881 | print_heading(f"Listener Scan on {self.target.host}") 882 | for listener, port in SERVICES.items(): 883 | if listener not in self.scan_list: 884 | continue 885 | 886 | print_info(f"Checking {listener}") 887 | result = self.check_accessible(listener, port) 888 | if result.retval: 889 | print_success(result.retmsg) 890 | else: 891 | output = process_error(result.retmsg, ["listeners"], module_name, output) 892 | 893 | self.listeners[listener] = {"port": port, "accessible": result.retval} 894 | 895 | output["listeners"] = self.listeners 896 | 897 | return output 898 | 899 | def check_accessible(self, listener, port): 900 | if self.target.ip_version == 6: 901 | address_family = socket.AF_INET6 902 | elif self.target.ip_version == 4: 903 | address_family = socket.AF_INET 904 | 905 | try: 906 | sock = socket.socket(address_family, socket.SOCK_STREAM) 907 | sock.settimeout(self.target.timeout) 908 | result = sock.connect_ex((self.target.host, port)) 909 | if result == 0: 910 | return Result(True, f"{listener} is accessible on {port}/tcp") 911 | return Result(False, f"Could not connect to {listener} on {port}/tcp: {SOCKET_ERRORS[result]}") 912 | except Exception: 913 | return Result(False, f"Could not connect to {listener} on {port}/tcp") 914 | 915 | def get_accessible_listeners(self): 916 | accessible = [] 917 | for listener, entry in self.listeners.items(): 918 | if entry["accessible"] is True: 919 | accessible.append(listener) 920 | return accessible 921 | 922 | def get_accessible_ports_by_pattern(self, pattern): 923 | accessible = [] 924 | for listener, entry in self.listeners.items(): 925 | if pattern in listener and entry["accessible"] is True: 926 | accessible.append(entry["port"]) 927 | return accessible 928 | 929 | ### NetBIOS Enumeration 930 | 931 | class EnumNetbios(): 932 | def __init__(self, target, creds): 933 | self.target = target 934 | self.creds = creds 935 | 936 | def run(self): 937 | ''' 938 | Run NetBIOS module which collects Netbios names and the workgroup/domain. 939 | ''' 940 | module_name = ENUM_NETBIOS 941 | print_heading(f"NetBIOS Names and Workgroup/Domain for {self.target.host}") 942 | output = {"domain":None, "nmblookup":None} 943 | 944 | nmblookup = self.nmblookup() 945 | if nmblookup.retval: 946 | result = self.get_domain(nmblookup.retval) 947 | if result.retval: 948 | print_success(result.retmsg) 949 | output["domain"] = result.retval 950 | else: 951 | output = process_error(result.retmsg, ["domain"], module_name, output) 952 | 953 | result = self.nmblookup_to_human(nmblookup.retval) 954 | print_success(result.retmsg) 955 | output["nmblookup"] = result.retval 956 | else: 957 | output = process_error(nmblookup.retmsg, ["nmblookup", "domain"], module_name, output) 958 | 959 | return output 960 | 961 | def nmblookup(self): 962 | ''' 963 | Runs nmblookup (a NetBIOS over TCP/IP Client) in order to lookup NetBIOS names information. 964 | ''' 965 | 966 | result = SambaNmblookup(self.target).run(log='Trying to get NetBIOS names information') 967 | 968 | if not result.retval: 969 | return Result(None, f"Could not get NetBIOS names information via 'nmblookup': {result.retmsg}") 970 | 971 | if "No reply from" in result.retmsg: 972 | return Result(None, "Could not get NetBIOS names information via 'nmblookup': host does not reply") 973 | 974 | return Result(result.retmsg, "") 975 | 976 | def get_domain(self, nmblookup_result): 977 | ''' 978 | Extract domain from given nmblookoup result. 979 | ''' 980 | match = re.search(r"^\s+(\S+)\s+<00>\s+-\s+\s+", nmblookup_result, re.MULTILINE) 981 | if match: 982 | if valid_domain(match.group(1)): 983 | domain = match.group(1) 984 | else: 985 | return Result(None, f"Workgroup {domain} contains some illegal characters") 986 | else: 987 | return Result(None, "Could not find domain/domain") 988 | 989 | if not self.creds.local_auth: 990 | self.creds.set_domain(domain) 991 | return Result(domain, f"Got domain/workgroup name: {domain}") 992 | 993 | def nmblookup_to_human(self, nmblookup_result): 994 | ''' 995 | Map nmblookup output to human readable strings. 996 | ''' 997 | output = [] 998 | nmblookup_result = nmblookup_result.splitlines() 999 | for line in nmblookup_result: 1000 | if "Looking up status of" in line or line == "": 1001 | continue 1002 | 1003 | line = line.replace("\t", "") 1004 | match = re.match(r"^(\S+)\s+<(..)>\s+-\s+?()?\s+?[A-Z]", line) 1005 | if match: 1006 | line_val = match.group(1) 1007 | line_code = match.group(2).upper() 1008 | line_group = not match.group(3) 1009 | for entry in NBT_INFO: 1010 | pattern, code, group, desc = entry 1011 | if pattern: 1012 | if pattern in line_val and line_code == code and line_group == group: 1013 | output.append(line + " " + desc) 1014 | break 1015 | else: 1016 | if line_code == code and line_group == group: 1017 | output.append(line + " " + desc) 1018 | break 1019 | else: 1020 | output.append(line) 1021 | return Result(output, f"Full NetBIOS names information:\n{yamlize(output)}") 1022 | 1023 | ### SMB checks 1024 | 1025 | class EnumSmb(): 1026 | def __init__(self, target, detailed): 1027 | self.target = target 1028 | self.detailed = detailed 1029 | 1030 | def run(self): 1031 | ''' 1032 | Run SMB module which checks for the supported SMB dialects. 1033 | ''' 1034 | module_name = ENUM_SMB 1035 | print_heading(f"SMB Dialect Check on {self.target.host}") 1036 | output = {} 1037 | 1038 | for port in self.target.smb_ports: 1039 | print_info(f"Trying on {port}/tcp") 1040 | self.target.port = port 1041 | result = self.check_smb_dialects() 1042 | if result.retval is None: 1043 | output = process_error(result.retmsg, ["smb1_only"], module_name, output) 1044 | else: 1045 | output["smb_dialects"] = result.retval 1046 | print_success(result.retmsg) 1047 | break 1048 | 1049 | # Does the target only support SMBv1? Then enforce it! 1050 | if result.retval and result.retval["SMB1 only"]: 1051 | print_info("Enforcing legacy SMBv1 for further enumeration") 1052 | result = self.enforce_smb1() 1053 | if not result.retval: 1054 | output = process_error(result.retmsg, ["smb_dialects"], module_name, output) 1055 | 1056 | output["smb_dialects"] = result.retval 1057 | return output 1058 | 1059 | def enforce_smb1(self): 1060 | try: 1061 | if self.target.samba_config.add(['client min protocol = NT1']): 1062 | return Result(True, "") 1063 | except: 1064 | pass 1065 | return Result(False, "Could not enforce SMBv1") 1066 | 1067 | def check_smb_dialects(self): 1068 | ''' 1069 | Current implementations of the samba client tools will enforce at least SMBv2 by default. This will give false 1070 | negatives during session checks, if the target only supports SMBv1. Therefore, we try to find out here whether 1071 | the target system only speaks SMBv1. 1072 | ''' 1073 | supported = { 1074 | SMB_DIALECTS[SMB_DIALECT]: False, 1075 | SMB_DIALECTS[SMB2_DIALECT_002]: False, 1076 | SMB_DIALECTS[SMB2_DIALECT_21]:False, 1077 | SMB_DIALECTS[SMB2_DIALECT_30]:False, 1078 | SMB_DIALECTS[SMB2_DIALECT_311]:False, 1079 | } 1080 | 1081 | output = { 1082 | "Supported dialects": None, 1083 | "Preferred dialect": None, 1084 | "SMB1 only": False, 1085 | "SMB signing required": None 1086 | } 1087 | 1088 | # List dialects supported by impacket 1089 | smb_dialects = [SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_311] 1090 | 1091 | # Check all dialects 1092 | last_supported_dialect = None 1093 | for dialect in smb_dialects: 1094 | try: 1095 | smb_conn = SmbConnection(self.target, dialect=dialect) 1096 | smb_conn.close() 1097 | supported[SMB_DIALECTS[dialect]] = True 1098 | last_supported_dialect = dialect 1099 | except Exception: 1100 | pass 1101 | 1102 | # Set whether we suppot SMB1 or not for this class 1103 | self.target.smb1_supported = supported[SMB_DIALECTS[SMB_DIALECT]] 1104 | 1105 | # Does the target only support one dialect? Then this must be also the preferred dialect. 1106 | preferred_dialect = None 1107 | if sum(1 for value in supported.values() if value is True) == 1: 1108 | if last_supported_dialect == SMB_DIALECT: 1109 | output["SMB1 only"] = True 1110 | self.target.smb1_only = True 1111 | preferred_dialect = last_supported_dialect 1112 | 1113 | try: 1114 | smb_conn = SmbConnection(self.target, dialect=preferred_dialect) 1115 | preferred_dialect = smb_conn.get_dialect() 1116 | # Check whether SMB signing is required or optional - since this seems to be a global setting, we check it only for the preferred dialect 1117 | output["SMB signing required"] = smb_conn.is_signing_required() 1118 | smb_conn.close() 1119 | 1120 | output["Preferred dialect"] = SMB_DIALECTS[preferred_dialect] 1121 | self.target.smb_preferred_dialect = preferred_dialect 1122 | except Exception as exc: 1123 | # FIXME: This can propably go as impacket now supports SMB3 up to 3.11. 1124 | if isinstance(exc, (smb3.SessionError)): 1125 | if nt_status_error_filter(str(exc)) == "STATUS_NOT_SUPPORTED": 1126 | output["Preferred Dialect"] = "> SMB 3.0" 1127 | 1128 | output["Supported dialects"] = supported 1129 | 1130 | # When we end up here, a preferred dialect must have been set. If this is still set to None, 1131 | # we can conclude that the target does not support any dialect at all. 1132 | if not output["Preferred dialect"]: 1133 | return Result(None, f"No supported dialects found") 1134 | return Result(output, f"Supported dialects and settings:\n{yamlize(output)}") 1135 | 1136 | ### Session Checks 1137 | 1138 | class EnumSessions(): 1139 | SESSION_PASSWORD = "password" 1140 | SESSION_GUEST = "guest" 1141 | SESSION_NULL = "null" 1142 | SESSION_KERBEROS="Kerberos" 1143 | SESSION_NTLM="NTLM" 1144 | 1145 | def __init__(self, target, creds): 1146 | 1147 | self.target = target 1148 | self.creds = creds 1149 | 1150 | def run(self): 1151 | ''' 1152 | Run session check module which tests for user and null sessions. 1153 | ''' 1154 | module_name = ENUM_SESSIONS 1155 | print_heading(f"RPC Session Check on {self.target.host}") 1156 | output = { "sessions":None } 1157 | sessions = {"sessions_possible":False, 1158 | AUTH_NULL:False, 1159 | AUTH_PASSWORD:False, 1160 | AUTH_KERBEROS:False, 1161 | AUTH_NTLM:False, 1162 | AUTH_GUEST:False, 1163 | } 1164 | 1165 | # Check null session 1166 | print_info("Check for anonymous access (null session)") 1167 | null_session = self.check_session(Credentials('', '', self.creds.domain), self.SESSION_NULL) 1168 | if null_session.retval: 1169 | sessions[AUTH_NULL] = True 1170 | print_success(null_session.retmsg) 1171 | else: 1172 | output = process_error(null_session.retmsg, ["sessions"], module_name, output) 1173 | 1174 | # Check Kerberos session 1175 | if self.creds.ticket_file: 1176 | print_info("Check for Kerberos authentication") 1177 | kerberos_session = self.check_session(self.creds, self.SESSION_KERBEROS) 1178 | if kerberos_session.retval: 1179 | sessions[AUTH_KERBEROS] = True 1180 | print_success(kerberos_session.retmsg) 1181 | else: 1182 | output = process_error(kerberos_session.retmsg, ["sessions"], module_name, output) 1183 | # Check for NTLM authentication with user-provided NT hash 1184 | elif self.creds.nthash: 1185 | print_info("Check for NTLM authentication") 1186 | ntlm_session = self.check_session(self.creds, self.SESSION_NTLM) 1187 | if ntlm_session.retval: 1188 | sessions[AUTH_NTLM] = True 1189 | print_success(ntlm_session.retmsg) 1190 | else: 1191 | output = process_error(ntlm_session.retmsg, ["sessions"], module_name, output) 1192 | # Check for password authentication 1193 | elif self.creds.user: 1194 | print_info("Check for password authentication") 1195 | user_session = self.check_session(self.creds, self.SESSION_PASSWORD) 1196 | if user_session.retval: 1197 | sessions[AUTH_PASSWORD] = True 1198 | print_success(user_session.retmsg) 1199 | else: 1200 | output = process_error(user_session.retmsg, ["sessions"], module_name, output) 1201 | 1202 | # Check for guest access via non-existing (i.e. random) user 1203 | # https://sensepost.com/blog/2024/guest-vs-null-session-on-windows/ 1204 | # https://www.samba.org/samba/docs/current/man-html/smb.conf.5.html#MAPTOGUEST 1205 | print_info("Check for guest access") 1206 | user_session = self.check_session(Credentials(self.creds.random_user, self.creds.pw, self.creds.domain), self.SESSION_GUEST) 1207 | if user_session.retval: 1208 | sessions[AUTH_GUEST] = True 1209 | print_success(user_session.retmsg) 1210 | print_hint(f"Rerunning enumeration with user '{self.creds.random_user}' might give more results") 1211 | else: 1212 | output = process_error(user_session.retmsg, ["sessions"], module_name, output) 1213 | 1214 | if sessions[AUTH_NULL] or \ 1215 | sessions[AUTH_PASSWORD] or \ 1216 | sessions[AUTH_KERBEROS] or \ 1217 | sessions[AUTH_NTLM] or \ 1218 | sessions[AUTH_GUEST]: 1219 | sessions["sessions_possible"] = True 1220 | else: 1221 | process_error("Sessions failed, neither null nor user sessions were possible", ["sessions"], module_name, output) 1222 | 1223 | output['sessions'] = sessions 1224 | return output 1225 | 1226 | def check_session(self, creds, session_type): 1227 | ''' 1228 | Tests access to the IPC$ share. 1229 | 1230 | General explanation: 1231 | The Common Internet File System(CIFS/Server Message Block (SMB) protocol specifies 1232 | mechanisms for interprocess communication over the network. This is called a named pipe. 1233 | In order to be able to "talk" to these named pipes, a special share named "IPC$" is provided. 1234 | SMB clients can access named pipes by using this share. Older Windows versions supported 1235 | anonymous access to this share (empty username and password), which is called a "null sessions". 1236 | This is a security vulnerability since it allows to gain valuable information about the host 1237 | system. 1238 | 1239 | How the test works: 1240 | In order to test for a null session, the smbclient command is used, by tring to connect to the 1241 | IPC$ share. If that works, smbclient's 'help' command will be run. If the login was successfull, 1242 | the help command will return a list of possible commands. One of these commands is called 1243 | 'case_senstive'. We search for this command as an indicator that the IPC session was setup correctly. 1244 | ''' 1245 | 1246 | result = SambaSmbclient(['help'], self.target, creds).run(log='Attempting to make session') 1247 | 1248 | if not result.retval: 1249 | return Result(False, f"Could not establish {session_type} session: {result.retmsg}") 1250 | 1251 | if "case_sensitive" in result.retmsg: 1252 | if session_type == self.SESSION_KERBEROS: 1253 | return Result(True, f"Server allows Kerberos authentication using ticket '{creds.ticket_file}'") 1254 | if session_type == self.SESSION_NTLM: 1255 | return Result(True, f"Server allows NTLM authentication using hash '{creds.nthash}'") 1256 | return Result(True, f"Server allows authentication via username '{creds.user}' and password '{creds.pw}'") 1257 | return Result(False, f"Could not establish session using '{creds.user}', password '{creds.pw}'") 1258 | 1259 | ### Domain Information Enumeration via LDAP 1260 | 1261 | class EnumLdapDomainInfo(): 1262 | def __init__(self, target): 1263 | self.target = target 1264 | 1265 | def run(self): 1266 | ''' 1267 | Run ldapsearch module which tries to find out whether host is a parent or 1268 | child DC. Also tries to fetch long domain name. The information are get from 1269 | the LDAP RootDSE. 1270 | ''' 1271 | module_name = ENUM_LDAP_DOMAIN_INFO 1272 | print_heading(f"Domain Information via LDAP for {self.target.host}") 1273 | output = {"is_parent_dc":None, 1274 | "is_child_dc":None, 1275 | "long_domain":None} 1276 | 1277 | for with_tls in [False, True]: 1278 | if with_tls: 1279 | if SERVICES[SERVICE_LDAPS] not in self.target.ldap_ports: 1280 | continue 1281 | print_info('Trying LDAPS') 1282 | else: 1283 | if SERVICES[SERVICE_LDAP] not in self.target.ldap_ports: 1284 | continue 1285 | print_info('Trying LDAP') 1286 | self.target.tls = with_tls 1287 | namingcontexts = self.get_namingcontexts() 1288 | if namingcontexts.retval is not None: 1289 | break 1290 | output = process_error(namingcontexts.retmsg, ["is_parent_dc", "is_child_dc", "long_domain"], module_name, output) 1291 | 1292 | if namingcontexts.retval: 1293 | # Parent/root or child DC? 1294 | result = self.check_parent_dc(namingcontexts.retval) 1295 | if result.retval: 1296 | output["is_parent_dc"] = True 1297 | output["is_child_dc"] = False 1298 | else: 1299 | output["is_parent_dc"] = True 1300 | output["is_child_dc"] = False 1301 | print_success(result.retmsg) 1302 | 1303 | # Try to get long domain from ldapsearch result 1304 | result = self.get_long_domain(namingcontexts.retval) 1305 | if result.retval: 1306 | print_success(result.retmsg) 1307 | output["long_domain"] = result.retval 1308 | else: 1309 | output = process_error(result.retmsg, ["long_domain"], module_name, output) 1310 | 1311 | return output 1312 | 1313 | def get_namingcontexts(self): 1314 | ''' 1315 | Tries to connect to LDAP/LDAPS. If successful, it tries to get the naming contexts from 1316 | the so called Root Directory Server Agent Service Entry (RootDSE). 1317 | ''' 1318 | try: 1319 | server = Server(self.target.host, use_ssl=self.target.tls, get_info=DSA, connect_timeout=self.target.timeout) 1320 | ldap_con = Connection(server, auto_bind=True) 1321 | ldap_con.unbind() 1322 | except Exception as e: 1323 | if len(e.args) == 1: 1324 | error = str(e.args[0]) 1325 | else: 1326 | error = str(e.args[1][0][0]) 1327 | if "]" in error: 1328 | error = error.split(']', 1)[1] 1329 | elif ":" in error: 1330 | error = error.split(':', 1)[1] 1331 | error = error.lstrip().rstrip() 1332 | if self.target.tls: 1333 | return Result(None, f"LDAPS connect error: {error}") 1334 | return Result(None, f"LDAP connect error: {error}") 1335 | 1336 | try: 1337 | if not server.info.naming_contexts: 1338 | return Result([], "NamingContexts are not readable") 1339 | except Exception: 1340 | return Result([], "NamingContexts are not readable") 1341 | 1342 | return Result(server.info.naming_contexts, "") 1343 | 1344 | def get_long_domain(self, namingcontexts_result): 1345 | ''' 1346 | Tries to extract the long domain from the naming contexts. 1347 | ''' 1348 | long_domain = "" 1349 | 1350 | for entry in namingcontexts_result: 1351 | match = re.search("(DC=[^,]+,DC=[^,]+)$", entry) 1352 | if match: 1353 | long_domain = match.group(1) 1354 | long_domain = long_domain.replace("DC=", "") 1355 | long_domain = long_domain.replace(",", ".") 1356 | break 1357 | if long_domain: 1358 | return Result(long_domain, f"Long domain name is: {long_domain}") 1359 | return Result(None, "Could not find long domain") 1360 | 1361 | def check_parent_dc(self, namingcontexts_result): 1362 | ''' 1363 | Checks whether the target is a parent or child domain controller. 1364 | This is done by searching for specific naming contexts. 1365 | ''' 1366 | parent = False 1367 | namingcontexts_result = '\n'.join(namingcontexts_result) 1368 | if "DC=DomainDnsZones" in namingcontexts_result or "ForestDnsZones" in namingcontexts_result: 1369 | parent = True 1370 | if parent: 1371 | return Result(True, "Appears to be root/parent DC") 1372 | return Result(False, "Appears to be child DC") 1373 | 1374 | ### Domain Information Enumeration via (unauthenticated) SMB 1375 | 1376 | class EnumSmbDomainInfo(): 1377 | def __init__(self, target, creds): 1378 | self.target = target 1379 | self.creds = creds 1380 | 1381 | def run(self): 1382 | ''' 1383 | Run module EnumSmbDomainInfo which extracts domain information from 1384 | Session Setup Request packets. 1385 | ''' 1386 | module_name = ENUM_SMB_DOMAIN_INFO 1387 | print_heading(f"Domain Information via SMB session for {self.target.host}") 1388 | output = {"smb_domain_info":None} 1389 | 1390 | for port in self.target.smb_ports: 1391 | self.target.port = port 1392 | print_info(f"Enumerating via unauthenticated SMB session on {port}/tcp") 1393 | result_smb = self.enum_from_smb() 1394 | if result_smb.retval: 1395 | print_success(result_smb.retmsg) 1396 | output["smb_domain_info"] = result_smb.retval 1397 | break 1398 | output = process_error(result_smb.retmsg, ["smb_domain_info"], module_name, output) 1399 | 1400 | return output 1401 | 1402 | def enum_from_smb(self): 1403 | ''' 1404 | Tries to set up an SMB null session. Even if the null session does not succeed, the SMB protocol will transfer 1405 | some information about the remote system in the SMB "Session Setup Response" or the SMB "Session Setup andX Response" 1406 | packet. These are the domain, DNS domain name as well as DNS host name. 1407 | ''' 1408 | smb_domain_info = {"NetBIOS computer name":None, "NetBIOS domain name":None, "DNS domain":None, "FQDN":None, "Derived membership":None, "Derived domain":None} 1409 | 1410 | smb_conn = None 1411 | try: 1412 | smb_conn = SmbConnection(self.target, Credentials(), dialect=self.target.smb_preferred_dialect) 1413 | smb_conn.login() 1414 | except Exception as e: 1415 | error_msg = process_impacket_smb_exception(e, self.target) 1416 | # STATUS_ACCESS_DENIED is the only error we can safely ignore. It basically tells us that a 1417 | # null session is not allowed, but that is not an issue for our enumeration. 1418 | if not "STATUS_ACCESS_DENIED" in error_msg: 1419 | return Result(None, error_msg) 1420 | 1421 | # For SMBv1 we can typically find Domain in the "Session Setup AndX Response" packet. 1422 | # For SMBv2 and later we find additional information like the DNS name and the DNS FQDN. 1423 | try: 1424 | smb_domain_info["NetBIOS domain name"] = smb_conn.get_server_domain() 1425 | smb_domain_info["NetBIOS computer name"] = smb_conn.get_server_name() 1426 | smb_domain_info["FQDN"] = smb_conn.get_server_dns_hostname().rstrip('\x00') 1427 | smb_domain_info["DNS domain"] = smb_conn.get_server_dns_domainname().rstrip('\x00') 1428 | except: 1429 | pass 1430 | 1431 | # This is based on testing various Windows and Samba setups and might not be 100% correct. 1432 | # The idea is that when we found a 'NetBIOS domain name' and the FQDN looks 'proper' we conclude 1433 | # that the machine is a member of a domain (not a workgroup). 1434 | # Very old Samba instances often only have the NetBIOS domain name set and nothing else. In this case, 1435 | # the machine is a member of a workgroup with that name. 1436 | # In all other cases, it can be concluded that the machine is a member of a workgroup. But that does not 1437 | # mean that the 'NetBIOS domain name' is the same as the machine's workgroup. Therefore, we set the domain 1438 | # to the 'NetBIOS computer name' which will enforce local authentication. 1439 | 1440 | if (smb_domain_info["NetBIOS computer name"] and 1441 | smb_domain_info["NetBIOS domain name"] and 1442 | smb_domain_info["DNS domain"] and 1443 | smb_domain_info["FQDN"] and 1444 | smb_domain_info["DNS domain"] in smb_domain_info["FQDN"] and 1445 | '.' in smb_domain_info["FQDN"]): 1446 | 1447 | smb_domain_info["Derived domain"] = smb_domain_info["NetBIOS domain name"] 1448 | smb_domain_info["Derived membership"] = "domain member" 1449 | 1450 | if not self.creds.local_auth: 1451 | self.creds.set_domain(smb_domain_info["NetBIOS domain name"]) 1452 | elif (smb_domain_info["NetBIOS domain name"] and 1453 | not smb_domain_info["NetBIOS computer name"] and 1454 | not smb_domain_info["FQDN"] and 1455 | not smb_domain_info["DNS domain"]): 1456 | 1457 | smb_domain_info["Derived domain"] = smb_domain_info["NetBIOS domain name"] 1458 | smb_domain_info["Derived membership"] = "workgroup member" 1459 | 1460 | if not self.creds.local_auth: 1461 | self.creds.set_domain(smb_domain_info["NetBIOS domain name"]) 1462 | elif smb_domain_info["NetBIOS computer name"]: 1463 | 1464 | smb_domain_info["Derived domain"] = "unknown" 1465 | smb_domain_info["Derived membership"] = "workgroup member" 1466 | 1467 | if self.creds.local_auth: 1468 | self.creds.set_domain(smb_domain_info["NetBIOS computer name"]) 1469 | 1470 | # Fallback to default workgroup 'WORKGROUP' if nothing else can be found 1471 | if not self.creds.domain: 1472 | self.creds.set_domain('WORKGROUP') 1473 | 1474 | if not any(smb_domain_info.values()): 1475 | return Result(None, "Could not enumerate domain information via unauthenticated SMB") 1476 | return Result(smb_domain_info, f"Found domain information via SMB\n{yamlize(smb_domain_info)}") 1477 | 1478 | ### Domain Information Enumeration via lsaquery 1479 | 1480 | class EnumLsaqueryDomainInfo(): 1481 | def __init__(self, target, creds): 1482 | self.target = target 1483 | self.creds = creds 1484 | 1485 | def run(self): 1486 | ''' 1487 | Run module lsaquery which tries to get domain information like 1488 | the domain/workgroup name, domain SID and the membership type. 1489 | ''' 1490 | module_name = ENUM_LSAQUERY_DOMAIN_INFO 1491 | print_heading(f"Domain Information via RPC for {self.target.host}") 1492 | output = {} 1493 | rpc_domain_info = {"Domain":None, 1494 | "Domain SID":None, 1495 | "Membership":None} 1496 | 1497 | lsaquery = self.lsaquery() 1498 | if lsaquery.retval is not None: 1499 | # Try to get domain/workgroup from lsaquery 1500 | result = self.get_domain(lsaquery.retval) 1501 | if result.retval: 1502 | print_success(result.retmsg) 1503 | rpc_domain_info["Domain"] = result.retval 1504 | 1505 | # In previous enumeration steps the domain was enumerated via unauthenticated 1506 | # SMB session. The domain found there might not be correct. Therefore, we only inform 1507 | # the user that we found a different domain via lsaquery. Jumping back to the session 1508 | # checks does not make sense. If the user was able to call lsaquery, he is already 1509 | # authenticated (likely via null session). 1510 | if not self.creds.local_auth and not self.creds.set_domain(result.retval): 1511 | print_hint(f"Found domain/workgroup '{result.retval}' which is different from the currently used one '{self.creds.domain}'.") 1512 | else: 1513 | output = process_error(result.retmsg, ["rpc_domain_info"], module_name, output) 1514 | 1515 | # Try to get domain SID 1516 | result = self.get_domain_sid(lsaquery.retval) 1517 | if result.retval: 1518 | print_success(result.retmsg) 1519 | rpc_domain_info["Domain SID"] = result.retval 1520 | else: 1521 | output = process_error(result.retmsg, ["rpc_domain_info"], module_name, output) 1522 | 1523 | # Is the host part of a domain or a workgroup? 1524 | result = self.check_is_part_of_workgroup_or_domain(lsaquery.retval) 1525 | if result.retval: 1526 | print_success(result.retmsg) 1527 | rpc_domain_info["Membership"] = result.retval 1528 | else: 1529 | output = process_error(result.retmsg, ["rpc_domain_info"], module_name, output) 1530 | else: 1531 | output = process_error(lsaquery.retmsg, ["rpc_domain_info"], module_name, output) 1532 | 1533 | output["rpc_domain_info"] = rpc_domain_info 1534 | return output 1535 | 1536 | def lsaquery(self): 1537 | ''' 1538 | Uses the rpcclient command to connect to the named pipe LSARPC (Local Security Authority Remote Procedure Call), 1539 | which allows to do remote management of domain security policies. In this specific case, we use rpcclient's lsaquery 1540 | command. This command will do an LSA_QueryInfoPolicy request to get the domain name and the domain service identifier 1541 | (SID). 1542 | ''' 1543 | 1544 | result = SambaRpcclient(['lsaquery'], self.target, self.creds).run(log='Attempting to get domain SID') 1545 | 1546 | if not result.retval: 1547 | return Result(None, f"Could not get domain information via 'lsaquery': {result.retmsg}") 1548 | 1549 | if result.retval: 1550 | return Result(result.retmsg, "") 1551 | return Result(None, "Could not get information via 'lsaquery'") 1552 | 1553 | def get_domain(self, lsaquery_result): 1554 | ''' 1555 | Takes the result of rpclient's lsaquery command and tries to extract the workgroup/domain. 1556 | ''' 1557 | domain = "" 1558 | if "Domain Name" in lsaquery_result: 1559 | match = re.search("Domain Name: (.*)", lsaquery_result) 1560 | if match: 1561 | domain = match.group(1) 1562 | 1563 | if domain: 1564 | return Result(domain, f"Domain: {domain}") 1565 | return Result(None, "Could not get workgroup/domain from lsaquery") 1566 | 1567 | def get_domain_sid(self, lsaquery_result): 1568 | ''' 1569 | Takes the result of rpclient's lsaquery command and tries to extract the domain SID. 1570 | ''' 1571 | domain_sid = None 1572 | if "Domain Sid: (NULL SID)" in lsaquery_result: 1573 | domain_sid = "NULL SID" 1574 | else: 1575 | match = re.search(r"Domain Sid: (S-\d+-\d+-\d+-\d+-\d+-\d+)", lsaquery_result) 1576 | if match: 1577 | domain_sid = match.group(1) 1578 | if domain_sid: 1579 | return Result(domain_sid, f"Domain SID: {domain_sid}") 1580 | return Result(None, "Could not get domain SID from lsaquery") 1581 | 1582 | def check_is_part_of_workgroup_or_domain(self, lsaquery_result): 1583 | ''' 1584 | Takes the result of rpclient's lsaquery command and tries to determine from the result whether the host 1585 | is part of a domain or workgroup. 1586 | ''' 1587 | if "Domain Sid: S-0-0" in lsaquery_result or "Domain Sid: (NULL SID)" in lsaquery_result: 1588 | return Result("workgroup member", "Membership: workgroup member") 1589 | if re.search(r"Domain Sid: S-\d+-\d+-\d+-\d+-\d+-\d+", lsaquery_result): 1590 | return Result("domain member", "Membership: domain member") 1591 | return Result(False, "Could not determine if host is part of domain or part of a workgroup") 1592 | 1593 | ### OS Information Enumeration 1594 | 1595 | class EnumOsInfo(): 1596 | def __init__(self, target, creds): 1597 | self.target = target 1598 | self.creds = creds 1599 | 1600 | def run(self): 1601 | ''' 1602 | Run module OS info which tries to collect OS information. The module supports both authenticated and unauthenticated 1603 | enumeration. This allows to get some target information without having a working session for many systems. 1604 | ''' 1605 | module_name = ENUM_OS_INFO 1606 | print_heading(f"OS Information via RPC for {self.target.host}") 1607 | output = {"os_info":None} 1608 | os_info = {"OS":None, "OS version":None, "OS release": None, "OS build": None, "Native OS":None, "Native LAN manager": None, "Platform id":None, "Server type":None, "Server type string":None} 1609 | 1610 | # Even an unauthenticated SMB session gives OS information about the target system, collect these first 1611 | for port in self.target.smb_ports: 1612 | self.target.port = port 1613 | print_info(f"Enumerating via unauthenticated SMB session on {port}/tcp") 1614 | result_smb = self.enum_from_smb() 1615 | if result_smb.retval: 1616 | print_success(result_smb.retmsg) 1617 | break 1618 | output = process_error(result_smb.retmsg, ["os_info"], module_name, output) 1619 | 1620 | if result_smb.retval: 1621 | os_info = {**os_info, **result_smb.retval} 1622 | 1623 | # If the earlier checks for RPC users sessions succeeded, we can continue by enumerating info via rpcclient's srvinfo 1624 | print_info("Enumerating via 'srvinfo'") 1625 | if self.target.sessions[self.creds.auth_method]: 1626 | result_srvinfo = self.enum_from_srvinfo() 1627 | if result_srvinfo.retval: 1628 | print_success(result_srvinfo.retmsg) 1629 | else: 1630 | output = process_error(result_srvinfo.retmsg, ["os_info"], module_name, output) 1631 | 1632 | if result_srvinfo.retval is not None: 1633 | os_info = {**os_info, **result_srvinfo.retval} 1634 | else: 1635 | output = process_error("Skipping 'srvinfo' run, not possible with provided credentials", ["os_info"], module_name, output) 1636 | 1637 | # Take all collected information and generate os_info entry 1638 | if result_smb.retval or (self.target.sessions[self.creds.auth_method] and result_srvinfo.retval): 1639 | os_info = self.os_info_to_human(os_info) 1640 | print_success(f"After merging OS information we have the following result:\n{yamlize(os_info)}") 1641 | output["os_info"] = os_info 1642 | 1643 | return output 1644 | 1645 | def srvinfo(self): 1646 | ''' 1647 | Uses rpcclient's srvinfo command to connect to the named pipe SRVSVC in order to call 1648 | NetSrvGetInfo() on the target. This will return OS information (OS version, platform id, 1649 | server type). 1650 | ''' 1651 | 1652 | result = SambaRpcclient(['srvinfo'], self.target, self.creds).run(log='Attempting to get OS info with command') 1653 | 1654 | if not result.retval: 1655 | return Result(None, f"Could not get OS info via 'srvinfo': {result.retmsg}") 1656 | 1657 | # FIXME: Came across this when trying to have multiple RPC sessions open, should this be moved to NT_STATUS_COMMON_ERRORS? 1658 | # This error is hard to reproduce. 1659 | if "NT_STATUS_REQUEST_NOT_ACCEPTED" in result.retmsg: 1660 | return Result(None, 'Could not get OS information via srvinfo: STATUS_REQUEST_NOT_ACCEPTED - too many RPC sessions open?') 1661 | 1662 | return Result(result.retmsg, "") 1663 | 1664 | def enum_from_srvinfo(self): 1665 | ''' 1666 | Parses the output of rpcclient's srvinfo command and extracts the various information. 1667 | ''' 1668 | result = self.srvinfo() 1669 | 1670 | if result.retval is None: 1671 | return result 1672 | 1673 | os_info = {"OS version":None, "Server type":None, "Server type string":None, "Platform id":None} 1674 | search_patterns = { 1675 | "platform_id":"Platform id", 1676 | "os version":"OS version", 1677 | "server type":"Server type" 1678 | } 1679 | first = True 1680 | for line in result.retval.splitlines(): 1681 | 1682 | if first: 1683 | match = re.search(r"\s+[^\s]+\s+(.*)", line) 1684 | if match: 1685 | os_info['Server type string'] = match.group(1).rstrip() 1686 | first = False 1687 | 1688 | for search_pattern in search_patterns.keys(): 1689 | match = re.search(fr"\s+{search_pattern}\s+:\s+(.*)", line) 1690 | if match: 1691 | os_info[search_patterns[search_pattern]] = match.group(1) 1692 | 1693 | if not os_info: 1694 | return Result(None, "Could not parse result of 'srvinfo' command, please open a GitHub issue") 1695 | return Result(os_info, "Found OS information via 'srvinfo'") 1696 | 1697 | def enum_from_smb(self): 1698 | ''' 1699 | Tries to set up an SMB null session. Even if the null session does not succeed, the SMB protocol will transfer 1700 | some information about the remote system in the SMB "Session Setup Response" or the SMB "Session Setup andX Response" 1701 | packet. This is the major and minor OS version as well as the build number. In SMBv1 also the "Native OS" as well as 1702 | the "Native LAN Manager" will be reported. 1703 | ''' 1704 | os_info = {"OS version":None, "OS release":None, "OS build":None, "Native LAN manager":None, "Native OS":None} 1705 | 1706 | os_major = None 1707 | os_minor = None 1708 | 1709 | # For SMBv1 we can typically find the "Native OS" (e.g. "Windows 5.1") and "Native LAN Manager" 1710 | # (e.g. "Windows 2000 LAN Manager") field in the "Session Setup AndX Response" packet. 1711 | # For SMBv2 and later we find the "OS Major" (e.g. 5), "OS Minor" (e.g. 1) as well as the 1712 | # "OS Build" fields in the "SMB2 Session Setup Response packet". 1713 | 1714 | if self.target.smb1_supported: 1715 | smb_conn = None 1716 | try: 1717 | smb_conn = SmbConnection(self.target, dialect=SMB_DIALECT) 1718 | smb_conn.login() 1719 | except Exception as e: 1720 | error_msg = process_impacket_smb_exception(e, self.target) 1721 | if not "STATUS_ACCESS_DENIED" in error_msg: 1722 | return Result(None, error_msg) 1723 | 1724 | if self.target.smb1_only: 1725 | os_info["OS build"] = "not supported" 1726 | os_info["OS release"] = "not supported" 1727 | 1728 | try: 1729 | native_lanman = smb_conn.get_server_lanman() 1730 | if native_lanman: 1731 | os_info["Native LAN manager"] = f"{native_lanman}" 1732 | 1733 | native_os = smb_conn.get_server_os() 1734 | if native_os: 1735 | os_info["Native OS"] = f"{native_os}" 1736 | match = re.search(r"Windows ([0-9])\.([0-9])", native_os) 1737 | if match: 1738 | os_major = match.group(1) 1739 | os_minor = match.group(2) 1740 | except AttributeError: 1741 | os_info["Native LAN manager"] = "not supported" 1742 | os_info["Native OS"] = "not supported" 1743 | except: 1744 | pass 1745 | 1746 | if not self.target.smb1_only: 1747 | smb_conn = None 1748 | try: 1749 | smb_conn = SmbConnection(self.target, dialect=self.target.smb_preferred_dialect) 1750 | smb_conn.login() 1751 | except Exception as e: 1752 | error_msg = process_impacket_smb_exception(e, self.target) 1753 | if not "STATUS_ACCESS_DENIED" in error_msg: 1754 | return Result(None, error_msg) 1755 | 1756 | if not self.target.smb1_supported: 1757 | os_info["Native LAN manager"] = "not supported" 1758 | os_info["Native OS"] = "not supported" 1759 | 1760 | try: 1761 | os_major = smb_conn.get_server_os_major() 1762 | os_minor = smb_conn.get_server_os_minor() 1763 | except: 1764 | pass 1765 | 1766 | try: 1767 | os_build = smb_conn.get_server_os_build() 1768 | if os_build is not None: 1769 | os_info["OS build"] = f"{os_build}" 1770 | if str(os_build) in OS_RELEASE: 1771 | os_info["OS release"] = OS_RELEASE[f"{os_build}"] 1772 | else: 1773 | os_info["OS release"] = "" 1774 | else: 1775 | os_info["OS build"] = "not supported" 1776 | os_info["OS release"] = "not supported" 1777 | except: 1778 | pass 1779 | 1780 | if os_major is not None and os_minor is not None: 1781 | os_info["OS version"] = f"{os_major}.{os_minor}" 1782 | else: 1783 | os_info["OS version"] = "not supported" 1784 | 1785 | if not any(os_info.values()): 1786 | return Result(None, "Could not enumerate information via unauthenticated SMB") 1787 | return Result(os_info, "Found OS information via SMB") 1788 | 1789 | def os_info_to_human(self, os_info): 1790 | native_lanman = os_info["Native LAN manager"] 1791 | native_os = os_info["Native OS"] 1792 | version = os_info["OS version"] 1793 | server_type_string = os_info["Server type string"] 1794 | os = "unknown" 1795 | 1796 | if native_lanman is not None and "Samba" in native_lanman: 1797 | os = f"Linux/Unix ({native_lanman})" 1798 | elif native_os is not None and "Windows" in native_os and not "Windows 5.0" in native_os: 1799 | os = native_os 1800 | elif server_type_string is not None and "Samba" in server_type_string: 1801 | # Examples: 1802 | # Wk Sv ... Samba 4.8.0-Debian 1803 | # Wk Sv ... (Samba 3.0.0) 1804 | match = re.search(r".*(Samba\s.*[^)])", server_type_string) 1805 | if match: 1806 | os = f"Linux/Unix ({match.group(1)})" 1807 | else: 1808 | os = "Linux/Unix" 1809 | elif version in OS_VERSIONS: 1810 | os = OS_VERSIONS[version] 1811 | 1812 | os_info["OS"] = os 1813 | 1814 | return os_info 1815 | 1816 | 1817 | ### Users Enumeration via RPC 1818 | 1819 | class EnumUsersRpc(): 1820 | def __init__(self, target, creds, detailed): 1821 | self.target = target 1822 | self.creds = creds 1823 | self.detailed = detailed 1824 | 1825 | def run(self): 1826 | ''' 1827 | Run module enum users. 1828 | ''' 1829 | module_name = ENUM_USERS_RPC 1830 | print_heading(f"Users via RPC on {self.target.host}") 1831 | output = {} 1832 | 1833 | # Get user via querydispinfo 1834 | print_info("Enumerating users via 'querydispinfo'") 1835 | users_qdi = self.enum_from_querydispinfo() 1836 | if users_qdi.retval is None: 1837 | output = process_error(users_qdi.retmsg, ["users"], module_name, output) 1838 | users_qdi_output = None 1839 | else: 1840 | print_success(users_qdi.retmsg) 1841 | users_qdi_output = users_qdi.retval 1842 | 1843 | # Get user via enumdomusers 1844 | print_info("Enumerating users via 'enumdomusers'") 1845 | users_edu = self.enum_from_enumdomusers() 1846 | if users_edu.retval is None: 1847 | output = process_error(users_edu.retmsg, ["users"], module_name, output) 1848 | users_edu_output = None 1849 | else: 1850 | print_success(users_edu.retmsg) 1851 | users_edu_output = users_edu.retval 1852 | 1853 | # Merge both users dicts 1854 | if users_qdi_output is not None and users_edu_output is not None: 1855 | users = {**users_edu_output, **users_qdi_output} 1856 | elif users_edu_output is None: 1857 | users = users_qdi_output 1858 | else: 1859 | users = users_edu_output 1860 | 1861 | if users: 1862 | if self.detailed: 1863 | print_info("Enumerating users details") 1864 | for rid in users.keys(): 1865 | name = users[rid]['username'] 1866 | user_details = self.get_details_from_rid(rid, name) 1867 | if user_details.retval: 1868 | print_success(user_details.retmsg) 1869 | users[rid]["details"] = user_details.retval 1870 | else: 1871 | output = process_error(user_details.retmsg, ["users"], module_name, output) 1872 | users[rid]["details"] = "" 1873 | 1874 | print_success(f"After merging user results we have {len(users.keys())} user(s) total:\n{yamlize(users, sort=True)}") 1875 | 1876 | output["users"] = users 1877 | return output 1878 | 1879 | def querydispinfo(self): 1880 | ''' 1881 | querydispinfo uses the Security Account Manager Remote Protocol (SAMR) named pipe to run the QueryDisplayInfo() request. 1882 | This request will return users with their corresponding Relative ID (RID) as well as multiple account information like a 1883 | description of the account. 1884 | ''' 1885 | 1886 | result = SambaRpcclient(['querydispinfo'], self.target, self.creds).run(log='Attempting to get userlist') 1887 | 1888 | if not result.retval: 1889 | return Result(None, f"Could not find users via 'querydispinfo': {result.retmsg}") 1890 | 1891 | return Result(result.retmsg, "") 1892 | 1893 | def enumdomusers(self): 1894 | ''' 1895 | enomdomusers command will again use the SAMR named pipe to run the EnumDomainUsers() request. This will again 1896 | return a list of users with their corresponding RID (see querydispinfo()). This is possible since by default 1897 | the registry key HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Lsa\\RestrictAnonymous = 0. If this is set to 1898 | 1 enumeration is no longer possible. 1899 | ''' 1900 | 1901 | result = SambaRpcclient(['enumdomusers'], self.target, self.creds).run(log='Attempting to get userlist') 1902 | 1903 | if not result.retval: 1904 | return Result(None, f"Could not find users via 'enumdomusers': {result.retmsg}") 1905 | 1906 | return Result(result.retmsg, "") 1907 | 1908 | def enum_from_querydispinfo(self): 1909 | ''' 1910 | Takes the result of rpclient's querydispinfo and tries to extract the users from it. 1911 | ''' 1912 | users = {} 1913 | querydispinfo = self.querydispinfo() 1914 | 1915 | if querydispinfo.retval is None: 1916 | return querydispinfo 1917 | 1918 | # Example output of rpcclient's querydispinfo: 1919 | # index: 0x2 RID: 0x3e9 acb: 0x00000010 Account: tester Name: Desc: 1920 | for line in filter(None, querydispinfo.retval.split('\n')): 1921 | match = re.search(r"index:\s+.*\s+RID:\s+(0x[A-F-a-f0-9]+)\s+acb:\s+(.*)\s+Account:\s+(.*)\s+Name:\s+(.*)\s+Desc:\s+(.*)", line) 1922 | if match: 1923 | rid = match.group(1) 1924 | rid = str(int(rid, 16)) 1925 | acb = match.group(2) 1926 | username = match.group(3) 1927 | name = match.group(4) 1928 | description = match.group(5) 1929 | users[rid] = OrderedDict({"username":username, "name":name, "acb":acb, "description":description}) 1930 | else: 1931 | return Result(None, "Could not extract users from querydispinfo output, please open a GitHub issue") 1932 | return Result(users, f"Found {len(users.keys())} user(s) via 'querydispinfo'") 1933 | 1934 | def enum_from_enumdomusers(self): 1935 | ''' 1936 | Takes the result of rpclient's enumdomusers and tries to extract the users from it. 1937 | ''' 1938 | users = {} 1939 | enumdomusers = self.enumdomusers() 1940 | 1941 | if enumdomusers.retval is None: 1942 | return enumdomusers 1943 | 1944 | # Example output of rpcclient's enumdomusers: 1945 | # user:[tester] rid:[0x3e9] 1946 | for line in enumdomusers.retval.splitlines(): 1947 | match = re.search(r"user:\[(.*)\]\srid:\[(0x[A-F-a-f0-9]+)\]", line) 1948 | if match: 1949 | username = match.group(1) 1950 | rid = match.group(2) 1951 | rid = str(int(rid, 16)) 1952 | users[rid] = {"username":username} 1953 | else: 1954 | return Result(None, "Could not extract users from eumdomusers output, please open a GitHub issue") 1955 | return Result(users, f"Found {len(users.keys())} user(s) via 'enumdomusers'") 1956 | 1957 | def get_details_from_rid(self, rid, name): 1958 | ''' 1959 | Takes an RID and makes use of the SAMR named pipe to call QueryUserInfo() on the given RID. 1960 | The output contains lots of information about the corresponding user account. 1961 | ''' 1962 | if not valid_rid(rid): 1963 | return Result(None, f"Invalid rid passed: {rid}") 1964 | 1965 | details = OrderedDict() 1966 | 1967 | result = SambaRpcclient(['queryuser', f'{rid}'], self.target, self.creds).run(log='Attempting to get detailed user info') 1968 | 1969 | if not result.retval: 1970 | return Result(None, f"Could not find details for user '{name}': {result.retmsg}") 1971 | 1972 | #FIXME: Examine - it is unclear why this is returned 1973 | if "NT_STATUS_NO_SUCH_USER" in result.retmsg: 1974 | return Result(None, f"Could not find details for user '{name}': STATUS_NO_SUCH_USER") 1975 | 1976 | match = re.search("([^\n]*User Name.*logon_hrs[^\n]*)", result.retmsg, re.DOTALL) 1977 | if match: 1978 | user_info = match.group(1) 1979 | 1980 | for line in filter(None, user_info.split('\n')): 1981 | if re.match(r'^\t[A-Za-z][A-Za-z\s_\.0-9]*(:|\[[0-9\.]+\]\.\.\.)(\t|\s)?', line): 1982 | if ":" in line: 1983 | key, value = line.split(":", 1) 1984 | if "..." in line: 1985 | key, value = line.split("...", 1) 1986 | 1987 | # Skip user and full name, we have this information already 1988 | if "User Name" in key or "Full Name" in key: 1989 | continue 1990 | 1991 | key = key.strip() 1992 | value = value.strip() 1993 | details[key] = value 1994 | else: 1995 | # If the regex above does not match, the output of the rpcclient queruser call must have 1996 | # changed. In this case, this would throw an exception since 'key' would be referenced before 1997 | # assignment. We catch that exception. 1998 | try: 1999 | if key not in details: 2000 | details[key] = line 2001 | else: 2002 | details[key] += "\n" + line 2003 | except: 2004 | return Result(None, f"Could not parse result of 'rpcclient' command, please open a GitHub issue") 2005 | 2006 | if "acb_info" in details and valid_hex(details["acb_info"]): 2007 | for key in ACB_DICT: 2008 | if int(details["acb_info"], 16) & key: 2009 | details[ACB_DICT[key]] = True 2010 | else: 2011 | details[ACB_DICT[key]] = False 2012 | 2013 | return Result(details, f"Found details for user '{name}' (RID {rid})") 2014 | return Result(None, f"Could not find details for user '{name}' (RID {rid})") 2015 | 2016 | ### Groups Enumeration via RPC 2017 | 2018 | class EnumGroupsRpc(): 2019 | def __init__(self, target, creds, with_members, detailed): 2020 | self.target = target 2021 | self.creds = creds 2022 | self.with_members = with_members 2023 | self.detailed = detailed 2024 | 2025 | def run(self): 2026 | ''' 2027 | Run module enum groups. 2028 | ''' 2029 | module_name = ENUM_GROUPS_RPC 2030 | print_heading(f"Groups via RPC on {self.target.host}") 2031 | output = {} 2032 | groups = None 2033 | 2034 | for grouptype in ["local", "builtin", "domain"]: 2035 | print_info(f"Enumerating {grouptype} groups") 2036 | enum = self.enum(grouptype) 2037 | if enum.retval is None: 2038 | output = process_error(enum.retmsg, ["groups"], module_name, output) 2039 | else: 2040 | if groups is None: 2041 | groups = {} 2042 | print_success(enum.retmsg) 2043 | groups.update(enum.retval) 2044 | 2045 | #FIXME: Adjust users enum stuff above so that it looks similar to this one? 2046 | if groups: 2047 | if self.with_members: 2048 | print_info("Enumerating group members") 2049 | for rid in groups.keys(): 2050 | # Get group members 2051 | groupname = groups[rid]['groupname'] 2052 | grouptype = groups[rid]['type'] 2053 | group_members = self.get_members_from_name(groupname, grouptype, rid) 2054 | if group_members.retval or group_members.retval == '': 2055 | print_success(group_members.retmsg) 2056 | else: 2057 | output = process_error(group_members.retmsg, ["groups"], module_name, output) 2058 | groups[rid]["members"] = group_members.retval 2059 | 2060 | if self.detailed: 2061 | print_info("Enumerating group details") 2062 | for rid in groups.keys(): 2063 | groupname = groups[rid]["groupname"] 2064 | grouptype = groups[rid]["type"] 2065 | details = self.get_details_from_rid(rid, groupname, grouptype) 2066 | 2067 | if details.retval: 2068 | print_success(details.retmsg) 2069 | else: 2070 | output = process_error(details.retmsg, ["groups"], module_name, output) 2071 | groups[rid]["details"] = details.retval 2072 | 2073 | print_success(f"After merging groups results we have {len(groups.keys())} group(s) total:\n{yamlize(groups, sort=True)}") 2074 | output["groups"] = groups 2075 | return output 2076 | 2077 | def enum(self, grouptype): 2078 | ''' 2079 | Tries to enumerate all groups by calling rpcclient's 'enumalsgroups builtin', 'enumalsgroups domain' as well 2080 | as 'enumdomgroups'. 2081 | ''' 2082 | grouptype_dict = { 2083 | "builtin":['enumalsgroups', 'builtin'], 2084 | "local":['enumalsgroups', 'domain'], 2085 | "domain":['enumdomgroups'] 2086 | } 2087 | 2088 | if grouptype not in ["builtin", "domain", "local"]: 2089 | return Result(None, f"Unsupported grouptype, supported types are: { ','.join(grouptype_dict.keys()) }") 2090 | 2091 | groups = {} 2092 | enum = self.enum_by_grouptype(grouptype) 2093 | 2094 | if enum.retval is None: 2095 | return enum 2096 | 2097 | if not enum.retval: 2098 | return Result({}, f"Found 0 group(s) via '{' '.join(grouptype_dict[grouptype])}'") 2099 | 2100 | match = re.search("(group:.*)", enum.retval, re.DOTALL) 2101 | if not match: 2102 | return Result(None, f"Could not parse result of '{' '.join(grouptype_dict[grouptype])}' command, please open a GitHub issue") 2103 | 2104 | # Example output of rpcclient's group commands: 2105 | # group:[RAS and IAS Servers] rid:[0x229] 2106 | for line in enum.retval.splitlines(): 2107 | match = re.search(r"group:\[(.*)\]\srid:\[(0x[A-F-a-f0-9]+)\]", line) 2108 | if match: 2109 | groupname = match.group(1) 2110 | rid = match.group(2) 2111 | rid = str(int(rid, 16)) 2112 | groups[rid] = OrderedDict({"groupname":groupname, "type":grouptype}) 2113 | else: 2114 | return Result(None, f"Could not extract groups from '{' '.join(grouptype_dict[grouptype])}' output, please open a GitHub issue") 2115 | return Result(groups, f"Found {len(groups.keys())} group(s) via '{' '.join(grouptype_dict[grouptype])}'") 2116 | 2117 | def enum_by_grouptype(self, grouptype): 2118 | ''' 2119 | Tries to fetch groups via rpcclient's enumalsgroups (so called alias groups) and enumdomgroups. 2120 | Grouptype "builtin", "local" and "domain" are supported. 2121 | ''' 2122 | grouptype_dict = { 2123 | "builtin":"enumalsgroups builtin", 2124 | "local":"enumalsgroups domain", 2125 | "domain": "enumdomgroups" 2126 | } 2127 | 2128 | if grouptype not in ["builtin", "domain", "local"]: 2129 | return Result(None, f"Unsupported grouptype, supported types are: { ','.join(grouptype_dict.keys()) }") 2130 | 2131 | result = SambaRpcclient([grouptype_dict[grouptype]], self.target, self.creds).run(log=f'Attempting to get {grouptype} groups') 2132 | 2133 | if not result.retval: 2134 | return Result(None, f"Could not get groups via '{grouptype_dict[grouptype]}': {result.retmsg}") 2135 | 2136 | return Result(result.retmsg, "") 2137 | 2138 | def get_members_from_name(self, groupname, grouptype, rid): 2139 | ''' 2140 | Takes a group name as first argument and tries to enumerate the group members. This is don by using 2141 | the 'net rpc group members' command. 2142 | ''' 2143 | 2144 | result = SambaNet(['rpc', 'group', 'members', groupname], self.target, self.creds).run(log=f"Attempting to get group memberships for {grouptype} group '{groupname}'") 2145 | 2146 | if not result.retval: 2147 | return Result(None, f"Could not lookup members for {grouptype} group '{groupname}' (RID {rid}): {result.retmsg}") 2148 | 2149 | members_string = result.retmsg 2150 | members = [] 2151 | for member in members_string.splitlines(): 2152 | if "Couldn't lookup SIDs" in member: 2153 | return Result(None, f"Could not lookup members for {grouptype} group '{groupname}' (RID {rid}): insufficient user permissions, try a different user") 2154 | if "Couldn't find group" in member: 2155 | return Result(None, f"Could not lookup members for {grouptype} group '{groupname}' (RID {rid}): group not found") 2156 | members.append(member) 2157 | 2158 | return Result(','.join(members), f"Found {len(members)} member(s) for {grouptype} group '{groupname}' (RID {rid})") 2159 | 2160 | def get_details_from_rid(self, rid, groupname, grouptype): 2161 | ''' 2162 | Takes an RID and makes use of the SAMR named pipe to open the group with OpenGroup() on the given RID. 2163 | ''' 2164 | if not valid_rid(rid): 2165 | return Result(None, f"Invalid rid passed: {rid}") 2166 | 2167 | details = OrderedDict() 2168 | 2169 | result = SambaRpcclient(['querygroup', f'{rid}'], self.target, self.creds).run(log='Attempting to get detailed group info') 2170 | 2171 | if not result.retval: 2172 | return Result(None, f"Could not find details for {grouptype} group '{groupname}': {result.retmsg}") 2173 | 2174 | #FIXME: Only works for domain groups, otherwise NT_STATUS_NO_SUCH_GROUP is returned 2175 | if "NT_STATUS_NO_SUCH_GROUP" in result.retmsg: 2176 | return Result(None, f"Could not get details for {grouptype} group '{groupname}' (RID {rid}): STATUS_NO_SUCH_GROUP") 2177 | 2178 | match = re.search("([^\n]*Group Name.*Num Members[^\n]*)", result.retmsg, re.DOTALL) 2179 | if match: 2180 | group_info = match.group(1) 2181 | group_info = group_info.replace("\t", "") 2182 | 2183 | for line in filter(None, group_info.split('\n')): 2184 | if ':' in line: 2185 | (key, value) = line.split(":", 1) 2186 | # Skip group name, we have this information already 2187 | if "Group Name" in key: 2188 | continue 2189 | details[key] = value 2190 | else: 2191 | details[line] = "" 2192 | 2193 | return Result(details, f"Found details for {grouptype} group '{groupname}' (RID {rid})") 2194 | return Result(None, f"Could not find details for {grouptype} group '{groupname}' (RID {rid})") 2195 | 2196 | ### RID Cycling 2197 | 2198 | class RidCycleParams: 2199 | ''' 2200 | Stores the various parameters needed for RID cycling. rid_ranges and known_usernames are mandatory. 2201 | enumerated_input is a dictionary which contains already enumerated input like "users, 2202 | "groups", "machines" and/or a domain sid. By default enumerated_input is an empty dict 2203 | and will be filled up during the tool run. 2204 | ''' 2205 | def __init__(self, rid_ranges, batch_size, known_usernames): 2206 | self.rid_ranges = rid_ranges 2207 | self.batch_size = batch_size 2208 | self.known_usernames = known_usernames 2209 | self.enumerated_input = {} 2210 | 2211 | def set_enumerated_input(self, enum_input): 2212 | for key in ["users", "groups", "machines"]: 2213 | if key in enum_input: 2214 | self.enumerated_input[key] = enum_input[key] 2215 | else: 2216 | self.enumerated_input[key] = None 2217 | 2218 | if "rpc_domain_info" in enum_input and enum_input["rpc_domain_info"]["Domain SID"] and "NULL SID" not in enum_input["rpc_domain_info"]["Domain SID"]: 2219 | self.enumerated_input["domain_sid"] = enum_input["rpc_domain_info"]["Domain SID"] 2220 | else: 2221 | self.enumerated_input["domain_sid"] = None 2222 | 2223 | class RidCycling(): 2224 | def __init__(self, cycle_params, target, creds, detailed): 2225 | self.cycle_params = cycle_params 2226 | self.target = target 2227 | self.creds = creds 2228 | self.detailed = detailed 2229 | 2230 | def run(self): 2231 | ''' 2232 | Run module RID cycling. 2233 | ''' 2234 | module_name = RID_CYCLING 2235 | print_heading(f"Users, Groups and Machines on {self.target.host} via RID Cycling") 2236 | output = self.cycle_params.enumerated_input 2237 | 2238 | # Try to enumerate SIDs first, if we don't have the domain SID already 2239 | if output["domain_sid"]: 2240 | sids_list = [output["domain_sid"]] 2241 | else: 2242 | print_info("Trying to enumerate SIDs") 2243 | sids = self.enum_sids(self.cycle_params.known_usernames) 2244 | if sids.retval is None: 2245 | output = process_error(sids.retmsg, ["users", "groups", "machines"], module_name, output) 2246 | return output 2247 | print_success(sids.retmsg) 2248 | sids_list = sids.retval 2249 | 2250 | # Keep track of what we found... 2251 | found_count = {"users": 0, "groups": 0, "machines": 0} 2252 | 2253 | # Run... 2254 | for sid in sids_list: 2255 | print_info(f"Trying SID {sid}") 2256 | rid_cycler = self.rid_cycle(sid) 2257 | for result in rid_cycler: 2258 | # We need the top level key to find out whether we got users, groups, machines or the domain_sid... 2259 | top_level_key = list(result.retval.keys())[0] 2260 | 2261 | # We found the domain_sid... 2262 | if top_level_key == 'domain_sid': 2263 | output['domain_sid'] = result.retval['domain_sid'] 2264 | continue 2265 | 2266 | # ...otherwise "users", "groups" or "machines". 2267 | # Get the RID of what we found (user, group or machine RID) as well as the corresponding entry (dict). 2268 | rid = list(result.retval[top_level_key])[0] 2269 | entry = result.retval[top_level_key][rid] 2270 | 2271 | # If we have the RID already, we continue... 2272 | if output[top_level_key] is not None and rid in output[top_level_key]: 2273 | continue 2274 | 2275 | print_success(result.retmsg) 2276 | found_count[top_level_key] += 1 2277 | 2278 | # ...else we add the result at the right position. 2279 | if output[top_level_key] is None: 2280 | output[top_level_key] = {} 2281 | output[top_level_key][rid] = entry 2282 | 2283 | if self.detailed and ("users" in top_level_key or "groups" in top_level_key): 2284 | if "users" in top_level_key: 2285 | rid, entry = list(result.retval["users"].items())[0] 2286 | name = entry["username"] 2287 | details = EnumUsersRpc(self.target, self.creds, False).get_details_from_rid(rid, name) 2288 | elif "groups" in top_level_key: 2289 | rid, entry = list(result.retval["groups"].items())[0] 2290 | groupname = entry["groupname"] 2291 | grouptype = entry["type"] 2292 | details = EnumGroupsRpc(self.target, self.creds, False, False).get_details_from_rid(rid, groupname, grouptype) 2293 | 2294 | if details.retval: 2295 | print_success(details.retmsg) 2296 | else: 2297 | output = process_error(details.retmsg, [top_level_key], module_name, output) 2298 | output[top_level_key][rid]["details"] = details.retval 2299 | 2300 | if found_count["users"] == 0 and found_count["groups"] == 0 and found_count["machines"] == 0: 2301 | output = process_error("Could not find any (new) users, (new) groups or (new) machines", ["users", "groups", "machines"], module_name, output) 2302 | else: 2303 | print_success(f"Found {found_count['users']} user(s), {found_count['groups']} group(s), {found_count['machines']} machine(s) in total") 2304 | 2305 | return output 2306 | 2307 | def enum_sids(self, users): 2308 | ''' 2309 | Tries to enumerate SIDs by looking up user names via rpcclient's lookupnames and by using rpcclient's lsaneumsid. 2310 | ''' 2311 | sids = [] 2312 | sid_patterns_list = [r"(S-1-5-21-[\d-]+)-\d+", r"(S-1-5-[\d-]+)-\d+", r"(S-1-22-[\d-]+)-\d+"] 2313 | 2314 | # Try to get a valid SID from well-known user names 2315 | for known_username in users.split(','): 2316 | result = SambaRpcclient(['lookupnames', f'{known_username}'], self.target, self.creds).run(log=f'Attempting to get SID for user {known_username}', error_filter=False) 2317 | sid_string = result.retmsg 2318 | 2319 | #FIXME: Should we use nt_status_error_filter here? (mind error_filter above) 2320 | if "NT_STATUS_ACCESS_DENIED" in sid_string or "NT_STATUS_NONE_MAPPED" in sid_string: 2321 | continue 2322 | 2323 | for pattern in sid_patterns_list: 2324 | match = re.search(pattern, sid_string) 2325 | if match: 2326 | result = match.group(1) 2327 | if result not in sids: 2328 | sids.append(result) 2329 | 2330 | # Try to get SID list via lsaenumsid 2331 | result = SambaRpcclient(['lsaenumsid'], self.target, self.creds).run(log="Attempting to get SIDs via 'lsaenumsid'", error_filter=False) 2332 | 2333 | #FIXME: Should we use nt_status_error_filter here? (mind error_filter above) 2334 | if "NT_STATUS_ACCESS_DENIED" not in result.retmsg: 2335 | for pattern in sid_patterns_list: 2336 | match_list = re.findall(pattern, result.retmsg) 2337 | for match in match_list: 2338 | if match not in sids: 2339 | sids.append(match) 2340 | 2341 | if sids: 2342 | return Result(sids, f"Found {len(sids)} SID(s)") 2343 | return Result(None, "Could not get any SIDs") 2344 | 2345 | def rid_cycle(self, sid): 2346 | ''' 2347 | Takes a SID as first parameter well as list of RID ranges (as tuples) as second parameter and does RID cycling. 2348 | ''' 2349 | for rid_range in self.cycle_params.rid_ranges: 2350 | (start_rid, end_rid) = rid_range 2351 | 2352 | for rid_base in range(start_rid, end_rid+1, self.cycle_params.batch_size): 2353 | target_sids = " ".join(list(map(lambda x: f'{sid}-{x}', range(rid_base, min(end_rid+1, rid_base+self.cycle_params.batch_size))))) 2354 | #FIXME: Could we get rid of error_filter=False? 2355 | result = SambaRpcclient(['lookupsids', target_sids], self.target, self.creds).run(log='RID Cycling', error_filter=False) 2356 | 2357 | for rid_offset, line in enumerate(result.retmsg.splitlines()): 2358 | # Example: S-1-5-80-3139157870-2983391045-3678747466-658725712-1004 *unknown*\*unknown* (8) 2359 | match = re.search(r"(S-\d+-\d+-\d+-[\d-]+\s+(.*)\s+[^\)]+\))", line) 2360 | if match: 2361 | sid_and_user = match.group(1) 2362 | entry = match.group(2) 2363 | rid = rid_base + rid_offset 2364 | 2365 | # Samba servers sometimes claim to have user accounts 2366 | # with the same name as the UID/RID. We don't report these. 2367 | if re.search(r"-(\d+) .*\\\1 \(", sid_and_user): 2368 | continue 2369 | 2370 | # "(1)" = User, "(2)" = Domain Group,"(3)" = Domain SID,"(4)" = Local Group 2371 | # "(5)" = Well-known group, "(6)" = Deleted account, "(7)" = Invalid account 2372 | # "(8)" = Unknown, "(9)" = Machine/Computer account 2373 | if "(1)" in sid_and_user: 2374 | yield Result({"users":{str(rid):{"username":entry}}}, f"Found user '{entry}' (RID {rid})") 2375 | elif "(2)" in sid_and_user: 2376 | yield Result({"groups":{str(rid):{"groupname":entry, "type":"domain"}}}, f"Found domain group '{entry}' (RID {rid})") 2377 | elif "(3)" in sid_and_user: 2378 | yield Result({"domain_sid":f"{sid}-{rid}"}, f"Found domain SID {sid}-{rid}") 2379 | elif "(4)" in sid_and_user: 2380 | yield Result({"groups":{str(rid):{"groupname":entry, "type":"builtin"}}}, f"Found builtin group '{entry}' (RID {rid})") 2381 | elif "(9)" in sid_and_user: 2382 | yield Result({"machines":{str(rid):{"machine":entry}}}, f"Found machine '{entry}' (RID {rid})") 2383 | 2384 | ### Shares Enumeration 2385 | 2386 | class EnumShares(): 2387 | def __init__(self, target, creds): 2388 | self.target = target 2389 | self.creds = creds 2390 | 2391 | def run(self): 2392 | ''' 2393 | Run module enum shares. 2394 | ''' 2395 | module_name = ENUM_SHARES 2396 | print_heading(f"Shares via RPC on {self.target.host}") 2397 | output = {} 2398 | shares = None 2399 | 2400 | enum = self.enum() 2401 | if enum.retval is None: 2402 | output = process_error(enum.retmsg, ["shares"], module_name, output) 2403 | else: 2404 | print_info("Enumerating shares") 2405 | # This will print success even if no shares were found (which is not an error.) 2406 | print_success(enum.retmsg) 2407 | shares = enum.retval 2408 | # Check access if there are any shares. 2409 | if enum.retmsg: 2410 | for share in sorted(shares): 2411 | print_info(f"Testing share {share}") 2412 | access = self.check_access(share) 2413 | if access.retval is None: 2414 | output = process_error(access.retmsg, ["shares"], module_name, output) 2415 | continue 2416 | print_success(access.retmsg) 2417 | shares[share]['access'] = access.retval 2418 | 2419 | output["shares"] = shares 2420 | return output 2421 | 2422 | def enum(self): 2423 | ''' 2424 | Tries to enumerate shares with the given username and password. It does this running the smbclient command. 2425 | smbclient will open a connection to the Server Service Remote Protocol named pipe (srvsvc). Once connected 2426 | it calls the NetShareEnumAll() to get a list of shares. 2427 | ''' 2428 | 2429 | result = SambaSmbclient(['list'], self.target, self.creds).run(log='Attempting to get share list using authentication') 2430 | 2431 | if not result.retval: 2432 | return Result(None, f"Could not list shares: {result.retmsg}") 2433 | 2434 | shares = {} 2435 | match_list = re.findall(r"^(Device|Disk|IPC|Printer)\|(.*)\|(.*)$", result.retmsg, re.MULTILINE|re.IGNORECASE) 2436 | if match_list: 2437 | for entry in match_list: 2438 | share_type = entry[0] 2439 | share_name = entry[1] 2440 | share_comment = entry[2].rstrip() 2441 | shares[share_name] = {'type':share_type, 'comment':share_comment} 2442 | 2443 | if shares: 2444 | return Result(shares, f"Found {len(shares.keys())} share(s):\n{yamlize(shares, sort=True)}") 2445 | return Result(shares, f"Found 0 share(s) for user '{self.creds.user}' with password '{self.creds.pw}', try a different user") 2446 | 2447 | def check_access(self, share): 2448 | ''' 2449 | Takes a share as first argument and checks whether the share is accessible. 2450 | The function returns a dictionary with the keys "mapping" and "listing". 2451 | "mapping" can be either OK or DENIED. OK means the share exists and is accessible. 2452 | "listing" can bei either OK, DENIED, N/A, NOT SUPPORTED or WRONG PASSWORD. 2453 | N/A means directory listing is not allowed, while NOT SUPPORTED means the share does 2454 | not support listing at all. This is the case for shares like IPC$ which is used for 2455 | remote procedure calls. 2456 | 2457 | In order to enumerate access permissions, smbclient is used with the "dir" command. 2458 | In the background this will send an SMB I/O Control (IOCTL) request in order to list the contents of the share. 2459 | ''' 2460 | 2461 | result = SambaSmbclient(['dir', f'{share}'], self.target, self.creds).run(log=f'Attempting to map share //{self.target.host}/{share}', error_filter=False) 2462 | 2463 | if not result.retval: 2464 | return Result(None, f"Could not check share: {result.retmsg}") 2465 | 2466 | if "NT_STATUS_BAD_NETWORK_NAME" in result.retmsg: 2467 | return Result(None, "Share doesn't exist") 2468 | 2469 | if "NT_STATUS_ACCESS_DENIED listing" in result.retmsg: 2470 | return Result({"mapping":"ok", "listing":"denied"}, "Mapping: OK, Listing: DENIED") 2471 | 2472 | if "NT_STATUS_WRONG_PASSWORD" in result.retmsg: 2473 | return Result({"mapping":"ok", "listing":"wrong password"}, "Mapping: OK, Listing: WRONG PASSWORD") 2474 | 2475 | if "tree connect failed: NT_STATUS_ACCESS_DENIED" in result.retmsg: 2476 | return Result({"mapping":"denied", "listing":"n/a"}, "Mapping: DENIED, Listing: N/A") 2477 | 2478 | if "NT_STATUS_INVALID_INFO_CLASS" in result.retmsg\ 2479 | or "NT_STATUS_CONNECTION_REFUSED listing" in result.retmsg\ 2480 | or "NT_STATUS_NETWORK_ACCESS_DENIED" in result.retmsg\ 2481 | or "NT_STATUS_NOT_A_DIRECTORY" in result.retmsg\ 2482 | or "NT_STATUS_NO_SUCH_FILE" in result.retmsg: 2483 | return Result({"mapping":"ok", "listing":"not supported"}, "Mapping: OK, Listing: NOT SUPPORTED") 2484 | 2485 | if "NT_STATUS_OBJECT_NAME_NOT_FOUND" in result.retmsg: 2486 | return Result(None, "Could not check share: STATUS_OBJECT_NAME_NOT_FOUND") 2487 | 2488 | if "NT_STATUS_INVALID_PARAMETER" in result.retmsg: 2489 | return Result(None, "Could not check share: STATUS_INVALID_PARAMETER") 2490 | 2491 | if "NT_STATUS_IO_TIMEOUT" in result.retmsg: 2492 | return Result(None, "Could not check share: STATUS_IO_TIMEOUT") 2493 | 2494 | if re.search(r"\n\s+\.\.\s+D.*\d{4}\n", result.retmsg) or re.search(r".*blocks\sof\ssize.*blocks\savailable.*", result.retmsg): 2495 | return Result({"mapping":"ok", "listing":"ok"}, "Mapping: OK, Listing: OK") 2496 | 2497 | return Result(None, "Could not parse result of smbclient command, please open a GitHub issue") 2498 | 2499 | ### Share Brute-Force 2500 | 2501 | class ShareBruteParams: 2502 | ''' 2503 | Stores the various parameters needed for Share Bruteforcing. shares_file is mandatory. 2504 | enumerated_input is a dictionary which contains already enumerated shares. By default 2505 | enumerated_input is an empty dict and will be filled up during the tool run. 2506 | ''' 2507 | def __init__(self, shares_file): 2508 | self.shares_file = shares_file 2509 | self.enumerated_input = {} 2510 | 2511 | def set_enumerated_input(self, enum_input): 2512 | if "shares" in enum_input: 2513 | self.enumerated_input["shares"] = enum_input["shares"] 2514 | else: 2515 | self.enumerated_input["shares"] = None 2516 | 2517 | class BruteForceShares(): 2518 | def __init__(self, brute_params, target, creds): 2519 | self.brute_params = brute_params 2520 | self.target = target 2521 | self.creds = creds 2522 | 2523 | def run(self): 2524 | ''' 2525 | Run module bruteforce shares. 2526 | ''' 2527 | module_name = BRUTE_FORCE_SHARES 2528 | print_heading(f"Share Bruteforcing on {self.target.host}") 2529 | output = self.brute_params.enumerated_input 2530 | 2531 | found_count = 0 2532 | try: 2533 | with open(self.brute_params.shares_file) as f: 2534 | for share in f: 2535 | share = share.rstrip() 2536 | 2537 | # Skip all shares we might have found by the enum_shares module already 2538 | if output["shares"] is not None and share in output["shares"].keys(): 2539 | continue 2540 | 2541 | result = EnumShares(self.target, self.creds).check_access(share) 2542 | if result.retval: 2543 | if output["shares"] is None: 2544 | output["shares"] = {} 2545 | print_success(f"Found share: {share}") 2546 | print_success(result.retmsg) 2547 | output["shares"][share] = result.retval 2548 | found_count += 1 2549 | except: 2550 | output = process_error(f"Failed to open {self.brute_params.shares_file}", ["shares"], module_name, output) 2551 | 2552 | if found_count == 0: 2553 | output = process_error("Could not find any (new) shares", ["shares"], module_name, output) 2554 | else: 2555 | print_success(f"Found {found_count} (new) share(s) in total") 2556 | 2557 | return output 2558 | 2559 | ### Policy Enumeration 2560 | 2561 | class EnumPolicy(): 2562 | def __init__(self, target, creds): 2563 | self.target = target 2564 | self.creds = creds 2565 | 2566 | def run(self): 2567 | ''' 2568 | Run module enum policy. 2569 | ''' 2570 | module_name = ENUM_POLICY 2571 | print_heading(f"Policies via RPC for {self.target.host}") 2572 | output = {} 2573 | 2574 | for port in self.target.smb_ports: 2575 | print_info(f"Trying port {port}/tcp") 2576 | self.target.port = port 2577 | enum = self.enum() 2578 | if enum.retval is None: 2579 | output = process_error(enum.retmsg, ["policy"], module_name, output) 2580 | output["policy"] = None 2581 | else: 2582 | print_success(enum.retmsg) 2583 | output["policy"] = enum.retval 2584 | break 2585 | 2586 | return output 2587 | 2588 | # This function is heavily based on this polenum fork: https://github.com/Wh1t3Fox/polenum 2589 | # The original polenum was written by Richard "deanx" Dean: https://labs.portcullis.co.uk/tools/polenum/ 2590 | # All credits to Richard "deanx" Dean and Craig "Wh1t3Fox" West! 2591 | def enum(self): 2592 | ''' 2593 | Tries to enum password policy and domain lockout and logoff information by opening a connection to the SAMR 2594 | named pipe and calling SamQueryInformationDomain() as well as SamQueryInformationDomain2(). 2595 | ''' 2596 | policy = {} 2597 | 2598 | try: 2599 | smb_conn = SmbConnection(self.target, self.creds) 2600 | smb_conn.login() 2601 | samr_object = SAMR(smb_conn) 2602 | domains = samr_object.get_domains() 2603 | # FIXME: Gets policy for domain only, [1] stores the policy for BUILTIN 2604 | domain_handle = samr_object.get_domain_handle(domains[0]) 2605 | except Exception as e: 2606 | return Result(None, process_impacket_smb_exception(e, self.target)) 2607 | 2608 | try: 2609 | result = samr_object.get_domain_password_information(domain_handle) 2610 | 2611 | policy["Domain password information"] = {} 2612 | policy["Domain password information"]["Password history length"] = result['PasswordHistoryLength'] or "None" 2613 | policy["Domain password information"]["Minimum password length"] = result['MinPasswordLength'] or "None" 2614 | policy["Domain password information"]["Minimum password age"] = self.policy_to_human(int(result['MinPasswordAge']['LowPart']), int(result['MinPasswordAge']['HighPart'])) 2615 | policy["Domain password information"]["Maximum password age"] = self.policy_to_human(int(result['MaxPasswordAge']['LowPart']), int(result['MaxPasswordAge']['HighPart'])) 2616 | policy["Domain password information"]["Password properties"] = [] 2617 | pw_prop = result['PasswordProperties'] 2618 | for bitmask in DOMAIN_FIELDS: 2619 | if pw_prop & bitmask == bitmask: 2620 | policy["Domain password information"]["Password properties"].append({DOMAIN_FIELDS[bitmask]:True}) 2621 | else: 2622 | policy["Domain password information"]["Password properties"].append({DOMAIN_FIELDS[bitmask]:False}) 2623 | except Exception as e: 2624 | nt_status_error = nt_status_error_filter(str(e)) 2625 | if nt_status_error: 2626 | return Result(None, f"Could not get domain password policy: {nt_status_error}") 2627 | return Result(None, "Could not get domain password policy") 2628 | 2629 | # Domain lockout 2630 | try: 2631 | result = samr_object.get_domain_lockout_information(domain_handle) 2632 | 2633 | policy["Domain lockout information"] = {} 2634 | policy["Domain lockout information"]["Lockout observation window"] = self.policy_to_human(0, result['LockoutObservationWindow'], lockout=True) 2635 | policy["Domain lockout information"]["Lockout duration"] = self.policy_to_human(0, result['LockoutDuration'], lockout=True) 2636 | policy["Domain lockout information"]["Lockout threshold"] = result['LockoutThreshold'] or "None" 2637 | except Exception as e: 2638 | nt_status_error = nt_status_error_filter(str(e)) 2639 | if nt_status_error: 2640 | return Result(None, f"Could not get domain lockout policy: {nt_status_error}") 2641 | return Result(None, "Could not get domain lockout policy") 2642 | 2643 | # Domain logoff 2644 | try: 2645 | result = samr_object.get_domain_logoff_information(domain_handle) 2646 | 2647 | policy["Domain logoff information"] = {} 2648 | policy["Domain logoff information"]["Force logoff time"] = self.policy_to_human(result['ForceLogoff']['LowPart'], result['ForceLogoff']['HighPart']) 2649 | except Exception as e: 2650 | nt_status_error = nt_status_error_filter(str(e)) 2651 | if nt_status_error: 2652 | return Result(None, f"Could not get domain logoff policy: {nt_status_error}") 2653 | return Result(None, "Could not get domain logoff policy") 2654 | 2655 | return Result(policy, f"Found policy:\n{yamlize(policy)}") 2656 | 2657 | # This function is heavily based on this polenum fork: https://github.com/Wh1t3Fox/polenum 2658 | # The original polenum was written by Richard "deanx" Dean: https://labs.portcullis.co.uk/tools/polenum/ 2659 | # All credits to Richard "deanx" Dean and Craig "Wh1t3Fox" West! 2660 | def policy_to_human(self, low, high, lockout=False): 2661 | ''' 2662 | Converts various values retrieved via the SAMR named pipe into human readable strings. 2663 | ''' 2664 | time = "" 2665 | tmp = 0 2666 | 2667 | if low == 0 and hex(high) == "-0x80000000": 2668 | return "not set" 2669 | if low == 0 and high == 0: 2670 | return "none" 2671 | 2672 | if not lockout: 2673 | if low != 0: 2674 | high = abs(high+1) 2675 | else: 2676 | high = abs(high) 2677 | low = abs(low) 2678 | 2679 | tmp = low + (high)*16**8 # convert to 64bit int 2680 | tmp *= (1e-7) # convert to seconds 2681 | else: 2682 | tmp = abs(high) * (1e-7) 2683 | 2684 | try: 2685 | dt = datetime.fromtimestamp(tmp, tz=timezone.utc) 2686 | minutes = dt.minute 2687 | hours = dt.hour 2688 | time_diff = dt - datetime.fromtimestamp(0, tz=timezone.utc) 2689 | days = time_diff.days 2690 | years = dt.year - 1970 2691 | except: 2692 | return "invalid time" 2693 | 2694 | if days > 1: 2695 | time += f"{days} days " 2696 | elif days == 1: 2697 | time += f"{days} day " 2698 | if years == 1: 2699 | time += f"({years} year) " 2700 | elif years > 1: 2701 | time += f"({years} years) " 2702 | if hours > 1: 2703 | time += f"{hours} hours " 2704 | elif hours == 1: 2705 | time += f"{hours} hour " 2706 | if minutes > 1: 2707 | time += f"{minutes} minutes" 2708 | elif minutes == 1: 2709 | time += f"{minutes} minute" 2710 | return time.rstrip() 2711 | 2712 | ### Printer Enumeration 2713 | 2714 | class EnumPrinters(): 2715 | def __init__(self, target, creds): 2716 | self.target = target 2717 | self.creds = creds 2718 | 2719 | def run(self): 2720 | ''' 2721 | Run module enum printers. 2722 | ''' 2723 | module_name = ENUM_PRINTERS 2724 | print_heading(f"Printers via RPC for {self.target.host}") 2725 | output = {} 2726 | 2727 | enum = self.enum() 2728 | if enum.retval is None: 2729 | output = process_error(enum.retmsg, ["printers"], module_name, output) 2730 | output["printers"] = None 2731 | else: 2732 | print_success(enum.retmsg) 2733 | output["printers"] = enum.retval 2734 | return output 2735 | 2736 | def enum(self): 2737 | ''' 2738 | Tries to enum printer via rpcclient's enumprinters. 2739 | ''' 2740 | 2741 | result = SambaRpcclient(['enumprinters'], self.target, self.creds).run(log='Attempting to get printer info') 2742 | printers = {} 2743 | 2744 | if not result.retval: 2745 | return Result(None, f"Could not get printer info via 'enumprinters': {result.retmsg}") 2746 | 2747 | #FIXME: Not 100% about this one, is the spooler propably not running? 2748 | if "NT_STATUS_OBJECT_NAME_NOT_FOUND" in result.retmsg: 2749 | return Result("", "No printers available") 2750 | if "No printers returned." in result.retmsg: 2751 | return Result({}, "No printers returned (this is not an error)") 2752 | 2753 | nt_status_error = nt_status_error_filter(result.retmsg) 2754 | if nt_status_error: 2755 | return Result(None, f"Could not get printers via 'enumprinters': {nt_status_error}") 2756 | #FIXME: It seems as this error has disappered in newer versions? 2757 | if "WERR_INVALID_NAME" in result.retmsg: 2758 | return Result(None, "Could not get printers via 'enumprinters': WERR_INVALID_NAME") 2759 | 2760 | match_list = re.findall(r"\s*flags:\[([^\n]*)\]\n\s*name:\[([^\n]*)\]\n\s*description:\[([^\n]*)\]\n\s*comment:\[([^\n]*)\]", result.retmsg, re.MULTILINE) 2761 | if not match_list: 2762 | return Result(None, "Could not parse result of enumprinters command, please open a GitHub issue") 2763 | 2764 | for match in match_list: 2765 | flags = match[0] 2766 | name = match[1] 2767 | description = match[2] 2768 | comment = match[3] 2769 | printers[name] = OrderedDict({"description":description, "comment":comment, "flags":flags}) 2770 | 2771 | return Result(printers, f"Found {len(printers.keys())} printer(s):\n{yamlize(printers, sort=True)}") 2772 | 2773 | ### Services Enumeration 2774 | 2775 | class EnumServices(): 2776 | def __init__(self, target, creds): 2777 | self.target = target 2778 | self.creds = creds 2779 | 2780 | def run(self): 2781 | ''' 2782 | Run module enum services. 2783 | ''' 2784 | module_name = ENUM_SERVICES 2785 | print_heading(f"Services via RPC on {self.target.host}") 2786 | output = {'services':None} 2787 | 2788 | enum = self.enum() 2789 | if enum.retval is None: 2790 | output = process_error(enum.retmsg, ["services"], module_name, output) 2791 | else: 2792 | print_success(enum.retmsg) 2793 | output['services'] = enum.retval 2794 | 2795 | return output 2796 | 2797 | def enum(self): 2798 | ''' 2799 | Tries to enum RPC services via net rpc service list. 2800 | ''' 2801 | 2802 | result = SambaNet(['rpc', 'service', 'list'], self.target, self.creds).run(log='Attempting to get RPC services') 2803 | services = {} 2804 | 2805 | if not result.retval: 2806 | return Result(None, f"Could not get RPC services via 'net rpc service list': {result.retmsg}") 2807 | 2808 | match_list = re.findall(r"([^\s]*)\s*\"(.*)\"", result.retmsg, re.MULTILINE) 2809 | if not match_list: 2810 | return Result(None, "Could not parse result of 'net rpc service list' command, please open a GitHub issue") 2811 | 2812 | for match in match_list: 2813 | name = match[0] 2814 | description = match[1] 2815 | services[name] = OrderedDict({"description":description}) 2816 | 2817 | return Result(services, f"Found {len(services.keys())} service(s):\n{yamlize(services, True)}") 2818 | 2819 | ### Enumerator 2820 | 2821 | class Enumerator(): 2822 | def __init__(self, args): 2823 | 2824 | # Init output files 2825 | if args.out_json_file: 2826 | output = Output(args.out_json_file, "json") 2827 | elif args.out_yaml_file: 2828 | output = Output(args.out_yaml_file, "yaml") 2829 | elif args.out_file: 2830 | output = Output(args.out_file, "json_yaml") 2831 | else: 2832 | output = Output() 2833 | 2834 | # Init target and creds 2835 | try: 2836 | self.creds = Credentials(args.user, args.pw, args.domain, args.ticket_file, args.nthash, args.local_auth) 2837 | self.target = Target(args.host, self.creds, timeout=args.timeout) 2838 | except Exception as e: 2839 | raise RuntimeError(str(e)) 2840 | 2841 | # Init default SambaConfig, make sure 'client ipc signing' is not required 2842 | try: 2843 | samba_config = SambaConfig(['client ipc signing = auto']) 2844 | self.target.samba_config = samba_config 2845 | except: 2846 | raise RuntimeError("Could not create default samba configuration") 2847 | 2848 | # Add target host and creds to output, so that it will end up in the JSON/YAML 2849 | output.update(self.target.as_dict()) 2850 | output.update(self.creds.as_dict()) 2851 | 2852 | self.args = args 2853 | self.output = output 2854 | self.cycle_params = None 2855 | self.share_brute_params = None 2856 | 2857 | def run(self): 2858 | # RID Cycling - init parameters 2859 | if self.args.R: 2860 | rid_ranges = self.prepare_rid_ranges() 2861 | self.cycle_params = RidCycleParams(rid_ranges, self.args.R, self.args.users) 2862 | 2863 | # Shares Brute Force - init parameters 2864 | if self.args.shares_file: 2865 | self.share_brute_params = ShareBruteParams(self.args.shares_file) 2866 | 2867 | print_heading("Target Information", False) 2868 | print_info(f"Target ........... {self.target.host}") 2869 | print_info(f"Username ......... '{self.creds.user}'") 2870 | print_info(f"Random Username .. '{self.creds.random_user}'") 2871 | print_info(f"Password ......... '{self.creds.pw}'") 2872 | print_info(f"Timeout .......... {self.target.timeout} second(s)") 2873 | if self.args.R: 2874 | print_info(f"RID Range(s) ..... {self.args.ranges}") 2875 | print_info(f"RID Req Size ..... {self.args.R}") 2876 | print_info(f"Known Usernames .. '{self.args.users}'") 2877 | 2878 | # The enumeration starts with a service scan. Currently this scans for 2879 | # SMB and LDAP, simple TCP connect scan is used for that. From the result 2880 | # of the scan and the arguments passed in by the user, a list of modules 2881 | # is generated. These modules will then be run. 2882 | listeners = self.service_scan() 2883 | self.target.listeners = listeners 2884 | modules = self.get_modules(listeners) 2885 | self.run_modules(modules) 2886 | 2887 | def service_scan(self): 2888 | # By default we scan for 445/tcp and 139/tcp (SMB). 2889 | # LDAP will be added if the user requested any option which requires LDAP 2890 | # like -L or -A. 2891 | scan_list = [SERVICE_SMB, SERVICE_SMB_NETBIOS] 2892 | if self.args.L: 2893 | scan_list += [SERVICE_LDAP, SERVICE_LDAPS] 2894 | 2895 | scanner = ListenersScan(self.target, scan_list) 2896 | result = scanner.run() 2897 | self.output.update(result) 2898 | self.target.smb_ports = scanner.get_accessible_ports_by_pattern("SMB") 2899 | self.target.ldap_ports = scanner.get_accessible_ports_by_pattern("LDAP") 2900 | return scanner.get_accessible_listeners() 2901 | 2902 | def get_modules(self, listeners, session=True): 2903 | modules = [] 2904 | if self.args.N: 2905 | modules.append(ENUM_NETBIOS) 2906 | 2907 | if SERVICE_LDAP in listeners or SERVICE_LDAPS in listeners: 2908 | if self.args.L: 2909 | modules.append(ENUM_LDAP_DOMAIN_INFO) 2910 | 2911 | if SERVICE_SMB in listeners or SERVICE_SMB_NETBIOS in listeners: 2912 | modules.append(ENUM_SMB) 2913 | modules.append(ENUM_SMB_DOMAIN_INFO) 2914 | modules.append(ENUM_SESSIONS) 2915 | 2916 | # The OS info module supports both session-less (unauthenticated) and session-based (authenticated) 2917 | # enumeration. Therefore, we can run it even if no session was possible... 2918 | if self.args.O: 2919 | modules.append(ENUM_OS_INFO) 2920 | 2921 | # ...the remaining modules still need a working session. 2922 | if session: 2923 | modules.append(ENUM_LSAQUERY_DOMAIN_INFO) 2924 | if self.args.U: 2925 | modules.append(ENUM_USERS_RPC) 2926 | if self.args.G: 2927 | modules.append(ENUM_GROUPS_RPC) 2928 | if self.args.Gm: 2929 | modules.append(ENUM_GROUPS_RPC) 2930 | if self.args.R: 2931 | modules.append(RID_CYCLING) 2932 | if self.args.S: 2933 | modules.append(ENUM_SHARES) 2934 | if self.args.shares_file: 2935 | modules.append(BRUTE_FORCE_SHARES) 2936 | if self.args.P: 2937 | modules.append(ENUM_POLICY) 2938 | if self.args.I: 2939 | modules.append(ENUM_PRINTERS) 2940 | if self.args.C: 2941 | modules.append(ENUM_SERVICES) 2942 | 2943 | return modules 2944 | 2945 | def run_modules(self, modules): 2946 | # Checks if host is a parent/child domain controller, try to get long domain name 2947 | if ENUM_LDAP_DOMAIN_INFO in modules: 2948 | result = EnumLdapDomainInfo(self.target).run() 2949 | self.output.update(result) 2950 | 2951 | # Try to retrieve workstation/domain and nbtstat information 2952 | if ENUM_NETBIOS in modules: 2953 | result = EnumNetbios(self.target, self.creds).run() 2954 | self.output.update(result) 2955 | 2956 | # Enumerate supported SMB versions 2957 | if ENUM_SMB in modules: 2958 | result = EnumSmb(self.target, self.args.d).run() 2959 | self.output.update(result) 2960 | 2961 | # Try to get domain name and sid via lsaquery 2962 | if ENUM_SMB_DOMAIN_INFO in modules: 2963 | result = EnumSmbDomainInfo(self.target, self.creds).run() 2964 | self.output.update(result) 2965 | 2966 | # Check for various session types including null sessions 2967 | if ENUM_SESSIONS in modules: 2968 | result = EnumSessions(self.target, self.creds).run() 2969 | self.output.update(result) 2970 | # Overwrite sessions 2971 | self.target.sessions = self.output.as_dict()['sessions'] 2972 | 2973 | # If sessions are not possible, we regenerate the list of modules again. 2974 | # This will only leave those modules in, which don't require authentication. 2975 | if not self.target.sessions[self.creds.auth_method]: 2976 | modules = self.get_modules(self.target.listeners, session=False) 2977 | 2978 | # Try to get domain name and sid via lsaquery 2979 | if ENUM_LSAQUERY_DOMAIN_INFO in modules: 2980 | result = EnumLsaqueryDomainInfo(self.target, self.creds).run() 2981 | self.output.update(result) 2982 | 2983 | # Get OS information like os version, server type string... 2984 | if ENUM_OS_INFO in modules: 2985 | result = EnumOsInfo(self.target, self.creds).run() 2986 | self.output.update(result) 2987 | 2988 | # Enum users 2989 | if ENUM_USERS_RPC in modules: 2990 | result = EnumUsersRpc(self.target, self.creds, self.args.d).run() 2991 | self.output.update(result) 2992 | 2993 | # Enum groups 2994 | if ENUM_GROUPS_RPC in modules: 2995 | result = EnumGroupsRpc(self.target, self.creds, self.args.Gm, self.args.d).run() 2996 | self.output.update(result) 2997 | 2998 | # Enum RPC services 2999 | if ENUM_SERVICES in modules: 3000 | result = EnumServices(self.target, self.creds).run() 3001 | self.output.update(result) 3002 | 3003 | # Enum shares 3004 | if ENUM_SHARES in modules: 3005 | result = EnumShares(self.target, self.creds).run() 3006 | self.output.update(result) 3007 | 3008 | # Enum password policy 3009 | if ENUM_POLICY in modules: 3010 | result = EnumPolicy(self.target, self.creds).run() 3011 | self.output.update(result) 3012 | 3013 | # Enum printers 3014 | if ENUM_PRINTERS in modules: 3015 | result = EnumPrinters(self.target, self.creds).run() 3016 | self.output.update(result) 3017 | 3018 | # RID Cycling (= bruteforce users, groups and machines) 3019 | if RID_CYCLING in modules: 3020 | self.cycle_params.set_enumerated_input(self.output.as_dict()) 3021 | result = RidCycling(self.cycle_params, self.target, self.creds, self.args.d).run() 3022 | self.output.update(result) 3023 | 3024 | # Brute force shares 3025 | if BRUTE_FORCE_SHARES in modules: 3026 | self.share_brute_params.set_enumerated_input(self.output.as_dict()) 3027 | result = BruteForceShares(self.share_brute_params, self.target, self.creds).run() 3028 | self.output.update(result) 3029 | 3030 | if not self.target.listeners: 3031 | warn("Aborting remainder of tests since neither SMB nor LDAP are accessible") 3032 | elif self.target.sessions['sessions_possible'] and not self.target.sessions[self.creds.auth_method]: 3033 | warn("Aborting remainder of tests, sessions are possible, but not with the provided credentials (see session check results)") 3034 | elif not self.target.sessions['sessions_possible']: 3035 | if SERVICE_SMB not in self.target.listeners and SERVICE_SMB_NETBIOS not in self.target.listeners: 3036 | warn("Aborting remainder of tests since SMB is not accessible") 3037 | else: 3038 | warn("Aborting remainder of tests since sessions failed, rerun with valid credentials") 3039 | 3040 | def prepare_rid_ranges(self): 3041 | ''' 3042 | Takes a string containing muliple RID ranges and returns a list of ranges as tuples. 3043 | ''' 3044 | rid_ranges = self.args.ranges 3045 | rid_ranges_list = [] 3046 | 3047 | for rid_range in rid_ranges.split(','): 3048 | if rid_range.isdigit(): 3049 | start_rid = rid_range 3050 | end_rid = rid_range 3051 | else: 3052 | [start_rid, end_rid] = rid_range.split("-") 3053 | 3054 | start_rid = int(start_rid) 3055 | end_rid = int(end_rid) 3056 | 3057 | # Reverse if neccessary 3058 | if start_rid > end_rid: 3059 | start_rid, end_rid = end_rid, start_rid 3060 | 3061 | rid_ranges_list.append((start_rid, end_rid)) 3062 | 3063 | return rid_ranges_list 3064 | 3065 | def finish(self): 3066 | errors = [] 3067 | 3068 | # Delete temporary samba config 3069 | if hasattr(self, 'target'): 3070 | if self.target.samba_config is not None and not self.args.keep: 3071 | result = self.target.samba_config.delete() 3072 | if not result.retval: 3073 | errors.append(result.retmsg) 3074 | 3075 | # Write YAML/JSON output (if the user requested that) 3076 | if hasattr(self, 'output'): 3077 | result = self.output.flush() 3078 | if not result.retval: 3079 | errors.append(result.retmsg) 3080 | 3081 | if errors: 3082 | return Result(False, "\n".join(errors)) 3083 | return Result(True, "") 3084 | 3085 | ### Validation Functions 3086 | 3087 | def valid_value(value, bounds): 3088 | min_val, max_val = bounds 3089 | try: 3090 | value = int(value) 3091 | if min_val <= value <= max_val: 3092 | return True 3093 | except ValueError: 3094 | pass 3095 | return False 3096 | 3097 | def valid_rid_ranges(rid_ranges): 3098 | if not rid_ranges: 3099 | return False 3100 | 3101 | for rid_range in rid_ranges.split(','): 3102 | match = re.search(r"^(\d+)-(\d+)$", rid_range) 3103 | if match: 3104 | continue 3105 | if rid_range.isdigit(): 3106 | continue 3107 | return False 3108 | return True 3109 | 3110 | def valid_shares_file(shares_file): 3111 | fault_shares = [] 3112 | NL = '\n' 3113 | 3114 | result = valid_file(shares_file) 3115 | if not result.retval: 3116 | return result 3117 | 3118 | try: 3119 | with open(shares_file) as f: 3120 | line_num = 1 3121 | for share in f: 3122 | share = share.rstrip() 3123 | if not valid_share(share): 3124 | fault_shares.append(f"line {line_num}:{share}") 3125 | line_num += 1 3126 | except: 3127 | return Result(False, f"Could not open shares file {shares_file}") 3128 | if fault_shares: 3129 | return Result(False, f"Shares with illegal characters found in {shares_file}:\n{NL.join(fault_shares)}") 3130 | return Result(True, "") 3131 | 3132 | def valid_share(share): 3133 | if re.search(r"^[a-zA-Z0-9\._\$-]+$", share): 3134 | return True 3135 | return False 3136 | 3137 | def valid_hex(hexnumber): 3138 | if re.search("^0x[0-9a-f]+$", hexnumber.lower()): 3139 | return True 3140 | return False 3141 | 3142 | def valid_rid(rid): 3143 | if isinstance(rid, int) and rid > 0: 3144 | return True 3145 | if rid.isdigit(): 3146 | return True 3147 | return False 3148 | 3149 | def valid_domain(domain): 3150 | if re.match(r"^[A-Za-z0-9_\.-]+$", domain): 3151 | return True 3152 | return False 3153 | 3154 | def valid_file(file, mode=None): 3155 | if not os.path.exists(file): 3156 | return Result(False, f'File {file} does not exist') 3157 | 3158 | stat = os.stat(file) 3159 | if stat.st_size == 0: 3160 | return Result(False, f'File {file} is empty') 3161 | 3162 | cur_mode = oct(stat.st_mode)[-3:] 3163 | if mode and not cur_mode == mode: 3164 | return Result(False, f'File permissions for {file} are currently set to {cur_mode}, but Samba tools require {mode}') 3165 | 3166 | if not os.access(file, os.R_OK): 3167 | return Result(False, f'Cannot read file {file}') 3168 | 3169 | return Result(True, '') 3170 | 3171 | ### Print Functions and Error Processing 3172 | 3173 | def print_banner(): 3174 | print(Colors.green(f'ENUM4LINUX - next generation (v{GLOBAL_VERSION})'), end="\n\n") 3175 | 3176 | def print_heading(text, leading_newline=True): 3177 | output = f"| {text} |" 3178 | length = len(output) 3179 | 3180 | if leading_newline: 3181 | print() 3182 | print(" " + "="*(length-2)) 3183 | print(output) 3184 | print(" " + "="*(length-2)) 3185 | 3186 | def print_success(msg): 3187 | print(Colors.green(f"[+] {msg}")) 3188 | 3189 | def print_hint(msg): 3190 | print(Colors.green(f"[H] {msg}")) 3191 | 3192 | def print_error(msg): 3193 | print(Colors.red(f"[-] {msg}")) 3194 | 3195 | def print_info(msg): 3196 | print(Colors.blue(f"[*] {msg}")) 3197 | 3198 | def print_verbose(msg): 3199 | print(f"[V] {msg}") 3200 | 3201 | def process_error(msg, affected_entries, module_name, output_dict): 3202 | ''' 3203 | Helper function to print error and update output dictionary at the same time. 3204 | ''' 3205 | print_error(msg) 3206 | 3207 | if not "errors" in output_dict: 3208 | output_dict["errors"] = {} 3209 | 3210 | for entry in affected_entries: 3211 | if not entry in output_dict["errors"]: 3212 | output_dict["errors"].update({entry: {}}) 3213 | 3214 | if not module_name in output_dict["errors"][entry]: 3215 | output_dict["errors"][entry].update({module_name: []}) 3216 | 3217 | output_dict["errors"][entry][module_name].append(msg) 3218 | return output_dict 3219 | 3220 | def process_impacket_smb_exception(exception, target): 3221 | ''' 3222 | Function for handling exceptions during SMB session setup when using the impacket library. 3223 | ''' 3224 | if len(exception.args) == 2: 3225 | if isinstance(exception.args[1], ConnectionRefusedError): 3226 | return f"SMB connection error on port {target.port}/tcp: Connection refused" 3227 | if isinstance(exception.args[1], socket.timeout): 3228 | return f"SMB connection error on port {target.port}/tcp: timed out" 3229 | if isinstance(exception, nmb.NetBIOSError): 3230 | return f"SMB connection error on port {target.port}/tcp: session failed" 3231 | if isinstance(exception, (smb.SessionError, smb3.SessionError)): 3232 | nt_status_error = nt_status_error_filter(str(exception)) 3233 | if nt_status_error: 3234 | return f"SMB connection error on port {target.port}/tcp: {nt_status_error}" 3235 | return f"SMB connection error on port {target.port}/tcp: session failed" 3236 | if isinstance(exception, AttributeError): 3237 | return f"SMB connection error on port {target.port}/tcp: session failed" 3238 | nt_status_error = nt_status_error_filter(str(exception)) 3239 | if nt_status_error: 3240 | return f"SMB connection error on port {target.port}/tcp: {nt_status_error}" 3241 | return f"SMB connection error on port {target.port}/tcp: session failed" 3242 | 3243 | def nt_status_error_filter(msg): 3244 | for error in NT_STATUS_COMMON_ERRORS: 3245 | if error.lower() in msg.lower(): 3246 | return error 3247 | return "" 3248 | 3249 | def abort(msg): 3250 | ''' 3251 | This function is used to abort the tool run on error. 3252 | The given error message will be printed out and the tool will abort with exit code 1. 3253 | ''' 3254 | print(Colors.red(f"[!] {msg}")) 3255 | sys.exit(1) 3256 | 3257 | def warn(msg): 3258 | print("\n"+Colors.yellow(f"[!] {msg}")) 3259 | 3260 | def yamlize(msg, sort=False, rstrip=True): 3261 | try: 3262 | result = yaml.dump(msg, default_flow_style=False, sort_keys=sort, width=160, Dumper=Dumper) 3263 | except TypeError: 3264 | # Handle old versions of PyYAML which do not support the sort_keys parameter 3265 | result = yaml.dump(msg, default_flow_style=False, width=160, Dumper=Dumper) 3266 | 3267 | if rstrip: 3268 | return result.rstrip() 3269 | return result 3270 | 3271 | ### Argument Processing 3272 | 3273 | def check_arguments(): 3274 | ''' 3275 | Takes all arguments from argv and processes them via ArgumentParser. In addition, some basic 3276 | validation of arguments is done. 3277 | ''' 3278 | 3279 | global GLOBAL_VERBOSE 3280 | global GLOBAL_SAMBA_LEGACY 3281 | 3282 | parser = ArgumentParser(description="""This tool is a rewrite of Mark Lowe's enum4linux.pl, a tool for enumerating information from Windows and Samba systems. 3283 | It is mainly a wrapper around the Samba tools nmblookup, net, rpcclient and smbclient. Other than the original tool it allows to export enumeration results 3284 | as YAML or JSON file, so that it can be further processed with other tools. 3285 | 3286 | The tool tries to do a 'smart' enumeration. It first checks whether SMB or LDAP is accessible on the target. Depending on the result of this check, it will 3287 | dynamically skip checks (e.g. LDAP checks if LDAP is not running). If SMB is accessible, it will always check whether a session can be set up or not. If no 3288 | session can be set up, the tool will stop enumeration. 3289 | 3290 | The enumeration process can be interupted with CTRL+C. If the options -oJ or -oY are provided, the tool will write out the current enumeration state to the 3291 | JSON or YAML file, once it receives SIGINT triggered by CTRL+C. 3292 | 3293 | The tool was made for security professionals and CTF players. Illegal use is prohibited.""") 3294 | parser.add_argument("host") 3295 | parser.add_argument("-A", action="store_true", help="Do all simple enumeration including nmblookup (-U -G -S -P -O -N -I -L). This option is enabled if you don't provide any other option.") 3296 | parser.add_argument("-As", action="store_true", help="Do all simple short enumeration without NetBIOS names lookup (-U -G -S -P -O -I -L)") 3297 | parser.add_argument("-U", action="store_true", help="Get users via RPC") 3298 | parser.add_argument("-G", action="store_true", help="Get groups via RPC") 3299 | parser.add_argument("-Gm", action="store_true", help="Get groups with group members via RPC") 3300 | parser.add_argument("-S", action="store_true", help="Get shares via RPC") 3301 | parser.add_argument("-C", action="store_true", help="Get services via RPC") 3302 | parser.add_argument("-P", action="store_true", help="Get password policy information via RPC") 3303 | parser.add_argument("-O", action="store_true", help="Get OS information via RPC") 3304 | parser.add_argument("-L", action="store_true", help="Get additional domain info via LDAP/LDAPS (for DCs only)") 3305 | parser.add_argument("-I", action="store_true", help="Get printer information via RPC") 3306 | parser.add_argument("-R", default=0, const=1, nargs='?', metavar="BULK_SIZE", type=int, help="Enumerate users via RID cycling. Optionally, specifies lookup request size.") 3307 | parser.add_argument("-N", action="store_true", help="Do an NetBIOS names lookup (similar to nbtstat) and try to retrieve workgroup from output") 3308 | parser.add_argument("-w", dest="domain", default='', type=str, help="Specify workgroup/domain manually (usually found automatically)") 3309 | parser.add_argument("-u", dest="user", default='', type=str, help="Specify username to use (default \"\")") 3310 | auth_methods = parser.add_mutually_exclusive_group() 3311 | auth_methods.add_argument("-p", dest="pw", default='', type=str, help="Specify password to use (default \"\")") 3312 | auth_methods.add_argument("-K", dest="ticket_file", default='', type=str, help="Try to authenticate with Kerberos, only useful in Active Directory environment (Note: DNS must be setup correctly for this option to work") 3313 | auth_methods.add_argument("-H", dest="nthash", default='', type=str, help="Try to authenticate with hash") 3314 | parser.add_argument("--local-auth", action="store_true", default=False, help="Authenticate locally to target") 3315 | parser.add_argument("-d", action="store_true", help="Get detailed information for users and groups, applies to -U, -G and -R") 3316 | parser.add_argument("-k", dest="users", default=KNOWN_USERNAMES, type=str, help=f'User(s) that exists on remote system (default: {KNOWN_USERNAMES}).\nUsed to get sid with "lookupsids"') 3317 | parser.add_argument("-r", dest="ranges", default=RID_RANGES, type=str, help=f"RID ranges to enumerate (default: {RID_RANGES})") 3318 | parser.add_argument("-s", dest="shares_file", help="Brute force guessing for shares") 3319 | parser.add_argument("-t", dest="timeout", default=TIMEOUT, help=f"Sets connection timeout in seconds (default: {TIMEOUT}s)") 3320 | parser.add_argument("-v", dest="verbose", action="store_true", help="Verbose, show full samba tools commands being run (net, rpcclient, etc.)") 3321 | parser.add_argument("--keep", action="store_true", help="Don't delete the Samba configuration file created during tool run after enumeration (useful with -v)") 3322 | out_group = parser.add_mutually_exclusive_group() 3323 | out_group.add_argument("-oJ", dest="out_json_file", help="Writes output to JSON file (extension is added automatically)") 3324 | out_group.add_argument("-oY", dest="out_yaml_file", help="Writes output to YAML file (extension is added automatically)") 3325 | out_group.add_argument("-oA", dest="out_file", help="Writes output to YAML and JSON file (extensions are added automatically)") 3326 | args = parser.parse_args() 3327 | 3328 | if not (args.A or args.As or args.U or args.G or args.Gm or args.S or args.C or args.P or args.O or args.L or args.I or args.R or args.N or args.shares_file): 3329 | args.A = True 3330 | 3331 | if args.A or args.As: 3332 | args.G = True 3333 | args.I = True 3334 | args.L = True 3335 | args.O = True 3336 | args.P = True 3337 | args.S = True 3338 | args.U = True 3339 | 3340 | if args.A: 3341 | args.N = True 3342 | 3343 | # Only global variable which meant to be modified 3344 | GLOBAL_VERBOSE = args.verbose 3345 | 3346 | # Check Workgroup 3347 | # Do not set the domain/workgroup for local auth 3348 | if not args.local_auth and args.domain: 3349 | if not valid_domain(args.domain): 3350 | raise RuntimeError(f"Workgroup/domain '{args.domain}' contains illegal character") 3351 | 3352 | # Check for RID parameter 3353 | if args.R: 3354 | if not valid_value(args.R, (1,2000)): 3355 | raise RuntimeError("The given RID bulk size must be a valid integer in the range 1-2000") 3356 | if not valid_rid_ranges(args.ranges): 3357 | raise RuntimeError("The given RID ranges should be a range '10-20' or just a single RID like '1199'") 3358 | 3359 | # Check shares file 3360 | if args.shares_file: 3361 | result = valid_shares_file(args.shares_file) 3362 | if not result.retval: 3363 | raise RuntimeError(result.retmsg) 3364 | 3365 | # Add given users to list of RID cycle users automatically 3366 | if args.user and args.user not in args.users.split(","): 3367 | args.users += f",{args.user}" 3368 | 3369 | # Check timeout 3370 | if not valid_value(args.timeout, (1,600)): 3371 | raise RuntimeError("Timeout must be a valid integer in the range 1-600") 3372 | args.timeout = int(args.timeout) 3373 | 3374 | # Perform Samba version checks - TODO: Can be removed in the future 3375 | samba_version = re.match(r".*(\d+\.\d+\.\d+).*", check_output(["smbclient", "--version"]).decode()).group(1) 3376 | samba_version = tuple(int(x) for x in samba_version.split('.')) 3377 | if samba_version < (4, 15, 0): 3378 | GLOBAL_SAMBA_LEGACY = True 3379 | 3380 | # While smbclient and rpcclient support '--pw-nt-hash' the net command does not before Samba 4.15. 3381 | # In Samba 4.15 the commandline parser of the various tools were unified so that '--pw-nt-hash' works 3382 | # for this and later versions. An option would be to run the tool in a docker container like a recent 3383 | # Alpine Linux version. 3384 | if GLOBAL_SAMBA_LEGACY and args.nthash and (args.Gm or args.C): 3385 | raise RuntimeError("The -C and -Gm argument require Samba 4.15 or higher when used in combination with -H") 3386 | 3387 | return args 3388 | 3389 | ### Dependency Checks 3390 | 3391 | def check_dependencies(): 3392 | missing = [] 3393 | 3394 | for dep in DEPS: 3395 | if not shutil.which(dep): 3396 | missing.append(dep) 3397 | 3398 | if missing: 3399 | error_msg = (f"The following dependend tools are missing: {', '.join(missing)}\n" 3400 | " For Gentoo, you need to install the 'samba' package.\n" 3401 | " For Debian derivates (like Ubuntu) or ArchLinux, you need to install the 'smbclient' package.\n" 3402 | " For Fedora derivates (like RHEL, CentOS), you need to install the 'samba-common-tools' and 'samba-client' package.") 3403 | raise RuntimeError(error_msg) 3404 | 3405 | ### Run! 3406 | 3407 | def main(): 3408 | # The user can disable colored output via environment variable NO_COLOR (see https://no-color.org) 3409 | global GLOBAL_COLORS 3410 | if "NO_COLOR" in os.environ: 3411 | GLOBAL_COLORS = False 3412 | 3413 | print_banner() 3414 | 3415 | # Check dependencies and process arguments, make sure yaml can handle OrdereDicts 3416 | try: 3417 | Dumper.add_representer(OrderedDict, lambda dumper, data: dumper.represent_mapping('tag:yaml.org,2002:map', data.items())) 3418 | check_dependencies() 3419 | args = check_arguments() 3420 | except Exception as e: 3421 | abort(str(e)) 3422 | 3423 | # Run! 3424 | start_time = datetime.now() 3425 | try: 3426 | enum = Enumerator(args) 3427 | enum.run() 3428 | except RuntimeError as e: 3429 | abort(str(e)) 3430 | except KeyboardInterrupt: 3431 | warn("Received SIGINT, aborting enumeration") 3432 | finally: 3433 | if 'enum' in locals(): 3434 | result = enum.finish() 3435 | if not result.retval: 3436 | abort(result.retmsg) 3437 | elapsed_time = datetime.now() - start_time 3438 | 3439 | print(f"\nCompleted after {elapsed_time.total_seconds():.2f} seconds") 3440 | 3441 | if __name__ == "__main__": 3442 | main() 3443 | --------------------------------------------------------------------------------