├── .github
├── dependabot.yml
├── pull_request_template.md
└── workflows
│ └── python-app.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── conftest.py
├── dev.requirements.txt
├── pytest.ini
├── requirements.txt
├── src
├── arg_parser.py
├── local_logging.py
├── scan.py
├── scan_internals.py
├── setup.py
└── smbscan.py
├── tests
└── test_scan_internals.py
└── wordlists
├── patterns.md
└── patterns.txt
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "pip" # See documentation for possible values
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "weekly"
12 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 | ### Purpose
2 |
3 |
8 |
9 | ### Description
10 |
11 |
16 |
17 | ### Verification and Testing
18 |
19 |
27 |
28 | ### Release Notes
29 |
30 |
37 |
--------------------------------------------------------------------------------
/.github/workflows/python-app.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
3 |
4 | name: Python application
5 |
6 | on:
7 | push:
8 | branches: [ "main" ]
9 | pull_request:
10 | branches: [ "main" ]
11 |
12 | permissions:
13 | contents: read
14 |
15 | jobs:
16 | build:
17 |
18 | runs-on: ubuntu-latest
19 |
20 | steps:
21 | - uses: actions/checkout@v3
22 | - name: Set up Python 3.10
23 | uses: actions/setup-python@v3
24 | with:
25 | python-version: "3.10"
26 | - name: Install dependencies
27 | run: |
28 | python -m pip install --upgrade pip
29 | pip install flake8 pytest
30 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
31 | - name: Lint with flake8
32 | run: |
33 | # stop the build if there are Python syntax errors or undefined names
34 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
35 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
36 | flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
37 | - name: Test with pytest
38 | run: |
39 | pytest
40 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # smbscan specific
2 | logs/
3 | *.log
4 | *.csv
5 | *.state
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | pip-wheel-metadata/
30 | share/python-wheels/
31 | *.egg-info/
32 | .installed.cfg
33 | *.egg
34 | MANIFEST
35 |
36 | # PyInstaller
37 | # Usually these files are written by a python script from a template
38 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
39 | *.manifest
40 | *.spec
41 |
42 | # Installer logs
43 | pip-log.txt
44 | pip-delete-this-directory.txt
45 |
46 | # Unit test / coverage reports
47 | htmlcov/
48 | .tox/
49 | .nox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | *.py,cover
57 | .hypothesis/
58 | .pytest_cache/
59 |
60 | # Translations
61 | *.mo
62 | *.pot
63 |
64 | # Django stuff:
65 | *.log
66 | local_settings.py
67 | db.sqlite3
68 | db.sqlite3-journal
69 |
70 | # Flask stuff:
71 | instance/
72 | .webassets-cache
73 |
74 | # Scrapy stuff:
75 | .scrapy
76 |
77 | # Sphinx documentation
78 | docs/_build/
79 |
80 | # PyBuilder
81 | target/
82 |
83 | # Jupyter Notebook
84 | .ipynb_checkpoints
85 |
86 | # IPython
87 | profile_default/
88 | ipython_config.py
89 |
90 | # pyenv
91 | .python-version
92 |
93 | # vscode stuff
94 | .vscode/
95 |
96 | # pipenv
97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
100 | # install all needed dependencies.
101 | #Pipfile.lock
102 |
103 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
104 | __pypackages__/
105 |
106 | # Celery stuff
107 | celerybeat-schedule
108 | celerybeat.pid
109 |
110 | # SageMath parsed files
111 | *.sage.py
112 |
113 | # Environments
114 | .env
115 | .venv
116 | env/
117 | venv/
118 | ENV/
119 | env.bak/
120 | venv.bak/
121 |
122 | # Spyder project settings
123 | .spyderproject
124 | .spyproject
125 |
126 | # Rope project settings
127 | .ropeproject
128 |
129 | # mkdocs documentation
130 | /site
131 |
132 | # mypy
133 | .mypy_cache/
134 | .dmypy.json
135 | dmypy.json
136 |
137 | # Pyre type checker
138 | .pyre/
139 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 |
2 | # How to Contribute
3 |
4 | ## Table of Contents
5 | * [Reporting Bugs](#reporting-bugs)
6 | * [Suggesting Enhancements](#suggesting-enhancements)
7 | * [Submitting Changes](#submitting-changes)
8 | * [Styleguides](#styleguides)
9 | * [GIT Commit Messages](#git-commit-messages)
10 | * [Code Conventions](#code-conventions)
11 | * [Testing](#testing)
12 | * [Versioning](#versioning)
13 | * [Suggested Development Environment](#suggested-development-environment)
14 | * [Resources](#resources)
15 |
16 |
17 | ## Reporting Bugs
18 | * Bugs are tracked as [GitHub issues](https://github.com/jeffhacks/smbscan/issues)
19 | * Use the [Bug](https://github.com/jeffhacks/smbscan/issues?q=is%3Aissue+label%3Abug) label
20 | * Include as many details as possible
21 | * Include steps to recreate the bug
22 | * Include impacted version(s)
23 |
24 |
25 | ## Suggesting Enhancements
26 | * Enhancements are tracked as [GitHub issues](https://github.com/jeffhacks/smbscan/issues)
27 | * Use the [Enhancement](https://github.com/jeffhacks/smbscan/issues?q=is%3Aissue+label%3Aenhancement) label
28 | * Include as many details as possible
29 |
30 |
31 | ## Submitting Changes
32 | * Review the [styleguides](#styleguides) below before commencing
33 | * Create a branch for focused development of a specific [issue](https://github.com/jeffhacks/smbscan/issues)
34 | * Submit a pull request using the pull request template
35 |
36 |
37 | ## Styleguides
38 | ### GIT Commit Messages
39 | * Keep messages short and simple
40 | * Use the present tense ("Add feature" not "Added feature")
41 | * Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
42 | * Reference issues and pull requests
43 |
44 | ### Python Conventions
45 | * Please follow the [PEP 8 Style Guide for Python Code](https://peps.python.org/pep-0008/)
46 |
47 |
48 | ## Testing
49 | * TBC
50 |
51 |
52 | ## Versioning
53 | * TBC
54 |
55 |
56 | ## Suggested Development Environment
57 | * It's recommended to use a Virtual Environment, to prevent dependency issues.
58 | ### Using virtualenv
59 | Read more [here](https://github.com/pypa/virtualenv)
60 |
61 | #### Create
62 | ```python3
63 | python3 -m venv env
64 | source env/bin/activate
65 | ```
66 |
67 | #### Activate
68 | ```python3
69 | source env/bin/activate
70 | ```
71 |
72 | #### Deactivate
73 | ```python3
74 | deactivate
75 | ```
76 |
77 | ## Resources
78 | Useful documentation and examples
79 | - https://github.com/SecureAuthCorp/impacket/blob/master/impacket/smbconnection.py
80 | - https://github.com/SecureAuthCorp/impacket/blob/429f97a894d35473d478cbacff5919739ae409b4/impacket/smbconnection.py
81 | - https://docs.python.org/2/howto/argparse.html
82 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SMBScan
2 |
3 | ### Overview
4 | SMBScan is a tool developed to enumerate file shares on an internal network.
5 |
6 | It's primary objectives are:
7 |
8 | * Scan a single target or hundreds of targets
9 | * Enumerate all accessible shares and files
10 | * Identify files that potentially contain credentials or secrets
11 | * Try to avoid detection by blue teams
12 |
13 | ### Table of Contents
14 | 1. [Getting Started](#getting-started)
15 | 2. [Running Scans](#running-scans)
16 | 3. [Scan Output](#scan-output)
17 | 4. [Analysing Output](#analysing-output)
18 | 5. [Authors](#authors)
19 | 6. [Acknowledgements](#acknowledgments)
20 |
21 | ---
22 | ## Getting Started
23 | Clone or download from the git repo.
24 |
25 | ### Installation
26 | ```bash
27 | pip3 install -r requirements.txt
28 | ```
29 |
30 | ---
31 | ## Running scans
32 | Scan a single target as guest
33 | ```bash
34 | python3 src/smbscan.py 192.168.0.0/24
35 | ```
36 |
37 | ```log
38 | [2022-05-21 22:14:17 INFO] src/smbscan.py 192.168.0.26
39 | [2022-05-22 20:45:36 INFO] Scanning 192.168.0.26
40 | [2022-05-21 22:14:17 INFO] 192.168.0.26 (TESTSERVER) Connected as tester, Target OS: eWeblrdS
41 | [2022-05-21 22:14:17 INFO] 192.168.0.26 (TESTSERVER) Scanning \\TESTSERVER\TESTER
42 | [2022-05-21 22:14:17 CRITICAL] Suspicous file: \\TESTSERVER\TESTER\.ssh\id_rsa.pub (Sat May 21 21:12:21 2022, 563)
43 | [2022-05-21 22:14:17 CRITICAL] Suspicous file: \\TESTSERVER\TESTER\.ssh\id_rsa (Sat May 21 21:12:21 2022, 2590)
44 | [2022-05-21 22:14:18 CRITICAL] Suspicous file: \\TESTSERVER\TESTER\.aws\credentials (Sat May 21 21:12:23 2022, 119)
45 | [2022-05-21 22:14:26 INFO] Scan completed
46 | ```
47 |
48 | Scan a range of targets as a specific domain user with a random delay of 1-3 seconds between targets and operations on targets:
49 | ```bash
50 | python3 src/smbscan.py 192.168.0.0/24 -u tester -p Monkey123 ---download-files --max-depth 3 --exclude-hosts 192.168.0.18
51 | ```
52 |
53 | ```log
54 | [2022-05-21 22:14:17 INFO] src/smbscan.py 192.168.0.0/24 -u tester -p Monkey123 ---download-files --max-depth 3 --exclude-hosts 192.168.0.18
55 | [2022-05-21 22:14:17 INFO] Scanning 192.168.0.0/24
56 | [2022-05-21 22:14:17 WARNING] Skipping 192.168.0.18 (on exclusion list)
57 | [2022-05-21 22:14:17 INFO] 192.168.0.26 (TESTSERVER) Connected as tester, Target OS: eWeblrdS
58 | [2022-05-21 22:14:17 INFO] 192.168.0.26 (TESTSERVER) Scanning \\TESTSERVER\TESTER
59 | [2022-05-21 22:14:17 CRITICAL] Suspicous file: \\TESTSERVER\TESTER\.ssh\id_rsa.pub (Sat May 21 21:12:21 2022, 563)
60 | [2022-05-21 22:14:17 CRITICAL] Suspicous file: \\TESTSERVER\TESTER\.ssh\id_rsa (Sat May 21 21:12:21 2022, 2590)
61 | [2022-05-21 22:14:18 CRITICAL] Suspicous file: \\TESTSERVER\TESTER\.aws\credentials (Sat May 21 21:12:23 2022, 119)
62 | [2022-05-21 22:14:18 INFO] Scanning 192.168.0.35
63 | [2022-05-21 22:14:19 INFO] 192.168.0.35 (desktop-9kolkm4) Connected as tester, Target OS: Windows 10.0 Build 19041
64 | [2022-05-21 22:14:19 INFO] 192.168.0.35 (desktop-9kolkm4) Scanning \\desktop-9kolkm4\ADMIN$
65 | [2022-05-21 22:14:19 INFO] 192.168.0.35 (desktop-9kolkm4) Error accessing ADMIN$
66 | [2022-05-21 22:14:19 INFO] 192.168.0.35 (desktop-9kolkm4) Scanning \\desktop-9kolkm4\Backups
67 | [2022-05-21 22:14:19 INFO] 192.168.0.35 (desktop-9kolkm4) Scanning \\desktop-9kolkm4\C$
68 | [2022-05-21 22:14:19 INFO] 192.168.0.35 (desktop-9kolkm4) Error accessing C$
69 | [2022-05-21 22:14:20 INFO] 192.168.0.35 (desktop-9kolkm4) Scanning \\desktop-9kolkm4\E$
70 | [2022-05-21 22:14:20 INFO] 192.168.0.35 (desktop-9kolkm4) Error accessing E$
71 | [2022-05-21 22:14:20 INFO] 192.168.0.35 (desktop-9kolkm4) Scanning \\desktop-9kolkm4\inetpub
72 | [2022-05-21 22:14:24 CRITICAL] Suspicous file: \\desktop-9kolkm4\inetpub\wwwroot\web.config (Sat May 21 20:48:54 2022, 31506)
73 | [2022-05-21 22:14:24 INFO] 192.168.0.35 (desktop-9kolkm4) Scanning \\desktop-9kolkm4\Users
74 | [2022-05-21 22:14:26 CRITICAL] Suspicous file: \\desktop-9kolkm4\Users\tester\Documents\Passwords.kdbx (Fri May 20 21:57:30 2022, 1870)
75 | [2022-05-21 22:14:26 INFO] Scan completed
76 | ```
77 |
78 | ---
79 | ## Scan Output
80 | SMBScan produces a number of files.
81 |
82 | * Primary logfile
83 | * A primary logfile for each scan - records everything that's output to the terminal
84 | * CSV index files
85 | * A listing of all accessible shares and files. One CSV file per target
86 | * Downloaded files
87 | * A collection of downloaded suspicious files (if download is enabled). Structured by TARGET\SHARE\DIRECTORY\FILE
88 |
89 | ```
90 | logs
91 | │ smbscan-20220518-075257.log
92 | │ smbscan-desktop-9kolm4-20220518-075257.csv
93 | │ smbscan-testserver-20220518-075257.csv
94 | │
95 | └───
96 | │ └───
97 | │ └───
98 | │ │ suspicious-file
99 | |
100 | └───DESKTOP-9KOLKM4
101 | │ └───inetpub
102 | │ | └───wwwroot
103 | │ | │ web.config
104 | │ └───Users
105 | │ └───tester
106 | │ └───Documents
107 | │ │ Passwords.kdbx
108 | │
109 | └───TESTSERVER
110 | │ └───TESTER
111 | │ └───.aws
112 | │ | credentials
113 | │ └───.ssh
114 | │ | id_rsa.pub
115 | ```
116 |
117 | ---
118 | ## Analysing Output
119 |
120 | ### Search Downloaded Files
121 | Use grep, or speed up the process with graudit (https://github.com/wireghoul/graudit)
122 | ```bash
123 | graudit -d secrets -x *.csv logs/
124 | ```
125 |
126 | ### View CSV Files
127 | ```bash
128 | cat logs/smbscan-desktop-9kolm4-20220518-075257.csv | sed -e 's/,,/, ,/g' | column -s, -t | less -#5 -N -S
129 | ```
130 |
131 | ```
132 | 1 tester DESKTOP-9KOLKM4 desktop-9kolkm4 192.168.0.35 Backups \MSSQL
133 | 2 tester DESKTOP-9KOLKM4 desktop-9kolkm4 192.168.0.35 Backups \MSSQL\BookingSystem.bak
134 | 3 tester DESKTOP-9KOLKM4 desktop-9kolkm4 192.168.0.35 inetpub \wwwroot
135 | 4 tester DESKTOP-9KOLKM4 desktop-9kolkm4 192.168.0.35 inetpub \wwwroot\index.cs
136 | 5 tester DESKTOP-9KOLKM4 desktop-9kolkm4 192.168.0.35 inetpub \wwwroot\Robots.txt
137 | 6 tester DESKTOP-9KOLKM4 desktop-9kolkm4 192.168.0.35 inetpub \wwwroot\web.config
138 | ```
139 |
140 | ### Search CSV Files
141 | ```bash
142 | grep -i -e \.bak *.csv
143 |
144 | tester,DESKTOP-9KOLKM4,desktop-9kolkm4,192.168.0.35,Backups,\MSSQL\BookingSystem.bak.....
145 | ```
146 |
147 | ---
148 | ## Authors
149 | * Jeff Thomas - https://github.com/jeffhacks
150 | * Yianna Paris - https://github.com/nekosoft
151 |
152 | ---
153 | ## Acknowledgments
154 | * Wireghoul - https://github.com/wireghoul
155 | * Justin Steven - https://github.com/justinsteven
156 | * Impacket - https://github.com/SecureAuthCorp/impacket
157 |
--------------------------------------------------------------------------------
/conftest.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/dev.requirements.txt:
--------------------------------------------------------------------------------
1 | black==25.1.0
2 | pytest==8.3.5
3 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | pythonpath = . src
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | impacket==0.11.0
2 | python-slugify==8.0.4
3 |
--------------------------------------------------------------------------------
/src/arg_parser.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import logging
3 | import os
4 |
5 | import setup
6 |
7 |
8 | class Options:
9 | def __init__(
10 | self,
11 | hostname = "SMBScan",
12 | logDirectory = os.path.join(os.getcwd(), "logs"),
13 | kerberos = False,
14 | port = 139,
15 | timeout = 2,
16 | jitter = 3,
17 | jitterTarget = 3,
18 | jitterOperation = 3,
19 | threads = 1,
20 | aesKey = "",
21 | dc_ip = "",
22 | csvFile = [],
23 | stateFile = "",
24 | includePaths = [],
25 | excludePaths = [],
26 | includeShares = [],
27 | excludeShares = [],
28 | excludeHosts = [],
29 | maxDepth = 0,
30 | patternsFile = setup.OS_PATH_DEFAULT_PATTERN_PATH,
31 | downloadFiles = 0,
32 | logLevel = logging.INFO
33 | ):
34 | self.hostname = hostname
35 | self.logDirectory = logDirectory
36 | self.kerberos = kerberos
37 | self.port = port
38 | self.timeout = timeout
39 | self.threads = threads
40 | self.jitter = jitter
41 | self.jitterTarget = jitterTarget
42 | self.jitterOperation = jitterOperation
43 | self.aesKey = aesKey
44 | self.dc_ip = dc_ip
45 | self.csvFile = csvFile
46 | self.stateFile = stateFile
47 | self.includePaths = includePaths
48 | self.excludePaths = excludePaths
49 | self.includeShares = includeShares
50 | self.excludeShares = excludeShares
51 | self.excludeHosts = excludeHosts
52 | self.maxDepth = maxDepth,
53 | self.patternsFile = patternsFile
54 | self.patterns = []
55 | self.downloadFiles = downloadFiles
56 | self.logLevel = logLevel
57 |
58 | def setup_command_line_args(args = None) -> argparse.Namespace:
59 | parser = argparse.ArgumentParser()
60 | group = parser.add_mutually_exclusive_group(required=True)
61 | group.add_argument(
62 | "target",
63 | nargs="?",
64 | help="Target for scanning. e.g. 192.168.1.1 or 192.168.1.0/24",
65 | )
66 | group.add_argument(
67 | "-f",
68 | "--file",
69 | help="List of targets for scanning.",
70 | type=argparse.FileType("r"),
71 | )
72 | parser.add_argument("-u", "--user", help="User to connect as")
73 | parser.add_argument(
74 | "-p", "--password", help="Password for user (will prompt if missing and needed)"
75 | )
76 | parser.add_argument(
77 | "--no-pass", help="Don't use a password. (Useful for Kerberos)", action="store_true"
78 | )
79 | parser.add_argument(
80 | "-H", "--hash", help="NTLM Hash for user"
81 | )
82 | parser.add_argument("-d", "--domain", help="Domain for user")
83 | parser.add_argument("-k", "--kerberos", help="Enable kerberos", action="store_true")
84 | parser.add_argument(
85 | "--aesKey",
86 | help="",
87 | )
88 | parser.add_argument(
89 | "--dc-ip",
90 | help="",
91 | )
92 | parser.add_argument(
93 | "-j",
94 | "--jitter",
95 | help="Random delay between some requests. Default 3 seconds.",
96 | type=int,
97 | default=3,
98 | )
99 | parser.add_argument(
100 | "-jt",
101 | "--jitter-target",
102 | help="Random delay before moving to next target. Default 3 seconds.",
103 | type=int,
104 | )
105 | parser.add_argument(
106 | "-jo",
107 | "--jitter-operation",
108 | help="Random delay between some file operations on target. Default 3 seconds.",
109 | type=int,
110 | )
111 | parser.add_argument(
112 | "-t",
113 | "--timeout",
114 | help="Set timeout for connections. Default 2 seconds.",
115 | type=int,
116 | default=2,
117 | )
118 | parser.add_argument(
119 | "--threads",
120 | help="Set number of threads. Default 1 thread.",
121 | type=int,
122 | default=1,
123 | )
124 | parser.add_argument(
125 | "--shares-only",
126 | help="Display shares only. Do not crawl directories and files.",
127 | action="store_true"
128 | )
129 | parser.add_argument(
130 | "--log-directory",
131 | help="Override log file directory",
132 | default=os.path.join(os.getcwd(), "logs")
133 | )
134 | parser.add_argument(
135 | "--include-paths",
136 | help="List of comma separated paths to include in scan. All others will be excluded.",
137 | )
138 | parser.add_argument(
139 | "--exclude-paths",
140 | help="List of comma separated paths to exclude from scan. All others will be included.",
141 | )
142 | parser.add_argument(
143 | "--include-shares",
144 | help="List of comma separated shares to include in scan. All others will be excluded.",
145 | )
146 | parser.add_argument(
147 | "--exclude-shares",
148 | help="List of comma separated shares to exclude from scan. All others will be included.",
149 | )
150 | parser.add_argument(
151 | "--exclude-hosts",
152 | help="List of comma separated hosts to exclude from scan.",
153 | )
154 | parser.add_argument(
155 | "--max-depth",
156 | help="Maximum depth to crawl. 0 (default) = unlimited.",
157 | type=int,
158 | default=0,
159 | )
160 | parser.add_argument(
161 | "--patterns-file",
162 | help="Specify patterns file. Default if unspecified is patterns.txt",
163 | default=setup.OS_PATH_DEFAULT_PATTERN_PATH
164 | )
165 | parser.add_argument(
166 | "-df",
167 | "--download-files",
168 | help="Download suspicious files. 0 (default) = no.",
169 | action="store_true"
170 | )
171 | parser.add_argument(
172 | "--debug",
173 | help="Include debug messages in terminal output.",
174 | action="store_true"
175 | )
176 | parser.add_argument(
177 | "--state-file",
178 | help="State file for tracking complete targets and skipping these on subsequent scans.",
179 | )
180 |
181 | return parser.parse_args()
182 |
--------------------------------------------------------------------------------
/src/local_logging.py:
--------------------------------------------------------------------------------
1 | import csv
2 |
3 | def create_log_entry(options, username, servername, target, share, sharedFile, logFile):
4 | row = [
5 | username,
6 | servername,
7 | target.name,
8 | target.ip,
9 | share.shareName,
10 | sharedFile.fullPath,
11 | sharedFile.fileName,
12 | ("D" if sharedFile.isDirectory > 0 else ""),
13 | sharedFile.cTime,
14 | sharedFile.mTime,
15 | sharedFile.aTime,
16 | sharedFile.fileSize,
17 | ]
18 | writer = csv.writer(logFile)
19 | writer.writerow(row)
20 |
21 |
--------------------------------------------------------------------------------
/src/scan.py:
--------------------------------------------------------------------------------
1 | import csv
2 | import ipaddress
3 | import logging
4 | import socket
5 | import traceback
6 | import random
7 | import time
8 |
9 | from slugify import slugify
10 |
11 | import scan_internals
12 |
13 | logger = logging.getLogger('smbscan')
14 |
15 | class Target:
16 | def __init__(self, target):
17 | self.ip = None
18 | self.name = None
19 | self.alias = ""
20 | self.addressList = ""
21 | self.shares = []
22 |
23 | try:
24 | # Assume target is an IP
25 | self.ip = str(ipaddress.ip_address(target))
26 | hostname, self.alias, self.addressList = socket.gethostbyaddr(str(self.ip))
27 | if is_valid_hostname(hostname):
28 | self.name = hostname
29 | else:
30 | self.name = self.ip
31 | except socket.herror:
32 | # No DNS resolution
33 | self.name = self.ip
34 | except ValueError:
35 | # Target is not an IP
36 | try:
37 | self.ip = socket.gethostbyname(target)
38 | self.name = target
39 | except socket.gaierror as e:
40 | logger.error(f"Target failure ({target}): {str(e)}")
41 | except Exception as e:
42 | logger.error(f"Target failure ({target}): {str(e)}")
43 |
44 | class User:
45 | def __init__(self, username = "Guest", password = "", domain = "", lmhash = "", nthash = ""):
46 | self.username = username
47 | self.password = password
48 | self.domain = domain
49 | self.lmhash = lmhash
50 | self.nthash = nthash
51 | self.results = []
52 |
53 | def scan_single(targetHost, user, options):
54 | if str(targetHost) in options.excludeHosts:
55 | logger.warning(
56 | "Skipping %1s (on exclusion list)" % (targetHost)
57 | )
58 | if is_host_in_statefile(options.stateFile, str(targetHost)):
59 | logger.warning(
60 | "Skipping %1s (already scanned)" % (targetHost)
61 | )
62 | else:
63 | logger.info(f'Scanning {targetHost}')
64 | target = Target(str(targetHost))
65 | smbClient = None
66 | targetScanResult = ''
67 |
68 | if not target.ip:
69 | targetScanResult = 'Unable to resolve'
70 | else:
71 | smbClient = scan_internals.get_client(target, user, options, 445)
72 | # TODO This could potentially be noisier than needed. Consider only using port 445
73 | # if (smbClient is None):
74 | # smbClient = get_client(target, user, options, 139)
75 |
76 | if smbClient is None:
77 | targetScanResult = 'Unable to connect'
78 | else:
79 | fileTimeStamp = time.strftime("%Y%m%d-%H%M%S")
80 | logfileName = (
81 | options.logDirectory
82 | + "/smbscan-"
83 | + slugify(target.name)
84 | + "-"
85 | + fileTimeStamp
86 | + ".csv"
87 | )
88 | if scan_internals.is_safe_filepath(options.logDirectory, logfileName):
89 | try:
90 | logfile = open(logfileName, "a")
91 |
92 | logger.info(f"{target.ip} ({target.name}) Connected as {user.username}, Target OS: {smbClient.getServerOS()}")
93 |
94 | target.shares = scan_internals.get_shares(smbClient)
95 |
96 | if options.crawlShares:
97 | scan_internals.get_files(smbClient, target, options, logfile)
98 | user.results.append(target)
99 | except Exception as e:
100 | targetScanResult = 'Error'
101 | logger.exception(f'General failure ({targetHost}): {str(e)}')
102 | #print(traceback.format_exc())
103 | finally:
104 | targetScanResult = 'Scan completed'
105 | smbClient.close()
106 | logfile.close()
107 |
108 | add_target_to_statefile(options.stateFile, str(targetHost), targetScanResult)
109 |
110 | if options.jitterTarget > 0:
111 | time.sleep(random.randint(0, options.jitterTarget))
112 |
113 | def is_valid_hostname(hostname):
114 | """"Returns True if host name does not contain illegal characters, as described in Microsoft Docs."""
115 | # https://docs.microsoft.com/en-us/troubleshoot/windows-server/identity/naming-conventions-for-computer-domain-site-ou
116 | illegalCharacters = ['\\','/',':','*','?','"','<','>','|']
117 | if any(char in hostname for char in illegalCharacters):
118 | logger.warning(f'Invalid hostname: {hostname}, contains illegal characters')
119 | return False
120 | else:
121 | return True
122 |
123 | def add_target_to_statefile(statefileName, targetHost, targetScanResult):
124 | row = [
125 | targetHost,
126 | time.strftime("%Y%m%d %H%M%S"),
127 | targetScanResult
128 | ]
129 | with open(statefileName, 'a+', encoding='utf-8') as statefile:
130 | writer = csv.writer(statefile)
131 | writer.writerow(row)
132 |
133 | def is_host_in_statefile(statefileName, targetHost):
134 | found = False
135 | try:
136 | with open(statefileName, 'r', encoding='utf-8') as statefile:
137 | reader = csv.reader(statefile, delimiter=',')
138 | found = any(targetHost == row[0].strip() for row in reader)
139 |
140 | except Exception as e:
141 | pass
142 | finally:
143 | return found
--------------------------------------------------------------------------------
/src/scan_internals.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import ntpath
3 | import os
4 | import random
5 | import re
6 | import time
7 |
8 | from impacket.smbconnection import SMBConnection, SessionError
9 |
10 | from local_logging import create_log_entry
11 |
12 | logger = logging.getLogger('smbscan')
13 |
14 | class Share:
15 | def __init__(self, shareName):
16 | self.shareName = shareName
17 | self.sharedFiles = []
18 |
19 | class SharedFile:
20 | def __init__(self, fileName, fullPath, isDirectory, cTime, mTime, aTime, fileSize):
21 | self.fileName = fileName
22 | self.fullPath = fullPath
23 | self.isDirectory = isDirectory
24 | self.cTime = cTime
25 | self.mTime = mTime
26 | self.aTime = aTime
27 | self.fileSize = fileSize
28 |
29 | def get_shares(smbClient):
30 | """Get SMB share names from client and return a list."""
31 | shares = []
32 | resp = smbClient.listShares()
33 | for i in range(len(resp)):
34 | shareName = resp[i]["shi1_netname"][:-1]
35 | if is_valid_share_name(shareName) and shareName not in ["IPC$", "print$"]:
36 | shares.append(Share(shareName))
37 | return shares
38 |
39 | def get_client(target, user, options, port):
40 | try:
41 | smbClient = SMBConnection(
42 | target.name,
43 | target.ip,
44 | timeout=options.timeout,
45 | sess_port=int(port)
46 | )
47 | if options.kerberos is True:
48 | logger.debug('Kerberos mode')
49 | smbClient.kerberosLogin(
50 | user.username,
51 | user.password,
52 | user.domain,
53 | user.lmhash,
54 | user.nthash,
55 | options.aesKey,
56 | options.dc_ip,
57 | )
58 | else:
59 | # smbClient.login(user.username, user.password, user.domain, user.lmhash, user.nthash, ntlmFallback=False)
60 | # TODO I'm not sure of any downsides to allowing ntlmFallback here...
61 | smbClient.login(
62 | user.username,
63 | user.password,
64 | user.domain,
65 | user.lmhash,
66 | user.nthash,
67 | ntlmFallback=True,
68 | )
69 | # Host is live
70 | return smbClient
71 | except SessionError as e:
72 | logger.info(f"{target.ip} ({target.name}) Session failure: ({user.username}, {str(port)}) {str(e)}")
73 | # Host is live
74 | return None
75 | except Exception as e:
76 | if "timed out" in str(e):
77 | None
78 | # logger.info(f"Connection failure: {str(e)}")
79 | # Host is not live - do not log this
80 | elif "Connection refused" in str(e) or "Permission denied" in str(e):
81 | logger.debug(f"{target.ip} ({target.name}) Connection failure: {str(e)}")
82 | # Host is live
83 | else:
84 | logger.debug(f"{target.ip} ({target.name}) Connection failure: ({user.username}, {str(port)}) {str(e)}")
85 | # Host is live
86 | return None
87 |
88 | def list_files(target, smbClient, share, sharePath, options, logFile, currentDepth):
89 | try:
90 | if sharePath == '':
91 | # Always allow listing the root of each share
92 | logger.debug(f'Allowed [{sharePath}]')
93 | elif any(sharePath.lower().startswith(x) for x in options.excludePaths):
94 | # If there are any exclusions, make sure we skip these
95 | logger.info(f'Skipping [{sharePath}] (Path is in exclude list)')
96 | return
97 | elif any(sharePath.lower().startswith(x) for x in options.includePaths):
98 | # Always allow paths that are on the include list
99 | logger.debug(f'Allowed [{sharePath}] (Path is in include list)')
100 | elif len(options.includePaths) > 0:
101 | # If there is an include list, and we have not had a match yet, exclude all others
102 | logger.info(f'Skipping [{sharePath}] (Include list exists but does not contain this path)')
103 | return
104 | else:
105 | # Path is not on the exclusion list and there is no inclusion list
106 | logger.debug(f'Allowed [{sharePath}]')
107 |
108 | for f in smbClient.listPath(share.shareName, sharePath + "\\*"):
109 | if f.get_longname() == "." or f.get_longname() == "..":
110 | continue
111 |
112 | file = (sharePath + "\\" + f.get_longname()).strip()
113 | if not is_safe_remotepath(file):
114 | continue
115 |
116 | sharedFile = SharedFile(
117 | fileName = f.get_longname(),
118 | fullPath = file,
119 | isDirectory = f.is_directory(),
120 | cTime = time.ctime(float(f.get_ctime_epoch())),
121 | mTime = time.ctime(float(f.get_mtime_epoch())),
122 | aTime = time.ctime(float(f.get_atime_epoch())),
123 | fileSize = f.get_filesize(),
124 | )
125 | share.sharedFiles.append(sharedFile)
126 |
127 | if any(regex.match(sharedFile.fullPath) for regex in options.patterns):
128 | logger.critical(
129 | f"Suspicous file: \\\\{target.name}\\{share.shareName}{sharedFile.fullPath} ({time.ctime(float(f.get_atime_epoch()))}, {f.get_filesize()})"
130 | )
131 |
132 | # Download file
133 | if options.downloadFiles and not f.is_directory():
134 | filepath = sharePath.lstrip('\\').replace('\\', os.path.sep)
135 | downloadPath = os.path.join(options.logDirectory,
136 | target.name,
137 | share.shareName,
138 | filepath)
139 | downloadFile = os.path.join(downloadPath, f.get_longname())
140 |
141 | if is_safe_filepath(options.logDirectory, downloadPath) and is_safe_filepath(options.logDirectory, downloadFile):
142 | os.makedirs(downloadPath, exist_ok=True)
143 | logger.debug(f'Downloading {os.path.realpath(downloadFile)}')
144 | fh = open(downloadFile,'wb')
145 | smbClient.getFile(share.shareName, sharedFile.fullPath, fh.write)
146 | fh.close()
147 |
148 | create_log_entry(
149 | options,
150 | smbClient.getCredentials()[0],
151 | smbClient.getServerName(),
152 | target,
153 | share,
154 | sharedFile,
155 | logFile,
156 | )
157 |
158 | if f.is_directory() > 0 and (
159 | options.maxDepth == 0 or currentDepth < options.maxDepth
160 | ):
161 | list_files(
162 | target,
163 | smbClient,
164 | share,
165 | sharedFile.fullPath,
166 | options,
167 | logFile,
168 | currentDepth + 1,
169 | )
170 | except Exception as e:
171 | logger.info(f"{target.ip} ({target.name}) Error accessing {share.shareName}")
172 | logger.debug(f"{e}")
173 | return
174 | finally:
175 | if options.jitterOperation > 0:
176 | time.sleep(random.randint(0, options.jitterOperation))
177 |
178 | def get_files(smbClient, target, options, logFile):
179 | for share in target.shares:
180 | if share.shareName in options.excludeShares:
181 | logger.warning(
182 | "Skipping %1s (on exclusion list)" % (share.shareName)
183 | )
184 | elif len(options.includeShares) > 0:
185 | if share.shareName in options.includeShares:
186 | logger.info(
187 | "Scanning %1s (on inclusion list)" % (share.shareName)
188 | )
189 | list_files(target, smbClient, share, "", options, logFile, 1)
190 | else:
191 | logger.warning(
192 | "Skipping item %1s (not on inclusion list)" % (share.shareName)
193 | )
194 | else:
195 | logger.info(f"{target.ip} ({target.name}) Scanning \\\\{target.name}\\%1s" % (share.shareName))
196 | list_files(target, smbClient, share, "", options, logFile, 1)
197 |
198 | def is_valid_share_name(shareName):
199 | """"Returns True if share name does not contain illegal characters, as described in Microsoft Docs."""
200 | # Illegal share name characters: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/dc9978d7-6299-4c5a-a22d-a039cdc716ea
201 | illegalCharacters = ['"','\\','/','[',']',':','|','<','>','+','=',';',',','*','?']
202 | if any(char in shareName for char in illegalCharacters):
203 | logger.warning(f'Invalid share name: {shareName}, contains illegal characters')
204 | return False
205 | else:
206 | return True
207 |
208 | def is_safe_remotepath(path):
209 | """Returns true if remote path is in UNC naming convention."""
210 | normpath = ntpath.normpath(path) # Force UNC naming convention by using ntpath
211 | if ntpath.isabs(path) and path == normpath:
212 | return True
213 | else:
214 | logger.warning(f'Unsafe remotepath: {path}')
215 | return False
216 |
217 | def is_safe_filepath(logDir, path):
218 | """Returns true if file path is pointing to a subdirectory of log directory."""
219 | realpath = os.path.realpath(path)
220 | commonPath = os.path.commonpath((realpath, logDir))
221 | if commonPath == logDir:
222 | return True
223 | else:
224 | logger.warning(f'Unsafe filepath: {path}. Received {realpath}, which has no common path with {logDir}')
225 | return False
226 |
--------------------------------------------------------------------------------
/src/setup.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | OS_PATH_DEFAULT_PATTERN_PATH = os.path.join(os.path.dirname(__file__), "..", "wordlists", "patterns.txt")
4 |
--------------------------------------------------------------------------------
/src/smbscan.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | __author__ = "jeffhacks"
3 |
4 | import getpass
5 | import ipaddress
6 | import logging
7 | import os
8 | import re
9 | import sys
10 | import time
11 |
12 | from impacket.smb import SMB_DIALECT
13 | from slugify import slugify
14 | from logging import handlers #import logging.handlers as handlers
15 |
16 | from arg_parser import setup_command_line_args, Options
17 | from scan import scan_single, User
18 |
19 | from multiprocessing.pool import Pool
20 | from multiprocessing.pool import ThreadPool
21 | from multiprocessing import set_start_method
22 | from threading import Thread
23 |
24 | def valid_ip(addr):
25 | try:
26 | ipaddress.IPv4Network(str(addr))
27 | return True
28 | except ipaddress.AddressValueError:
29 | return False
30 |
31 | def main():
32 | args = setup_command_line_args()
33 |
34 | # Refactor Options - config file?
35 | options = Options()
36 | options.jitter = args.jitter
37 | options.jitterTarget = args.jitter if args.jitter_target is None else args.jitter_target
38 | options.jitterOperation = args.jitter if args.jitter_operation is None else args.jitter_operation
39 | options.timeout = args.timeout
40 | options.threads = args.threads
41 | options.logDirectory = os.path.abspath(args.log_directory)
42 | os.makedirs(args.log_directory, exist_ok=True)
43 | options.csvFile = os.path.join(
44 | options.logDirectory, "smbscan-" + time.strftime("%Y%m%d-%H%M%S") + ".log"
45 | )
46 | if args.state_file == None:
47 | options.stateFile = os.path.join(
48 | options.logDirectory, "smbscan-" + time.strftime("%Y%m%d-%H%M%S") + ".state"
49 | )
50 | else:
51 | state_filename = args.state_file
52 | filename, file_extension = os.path.splitext(state_filename)
53 | if not file_extension == '.state':
54 | state_filename = f'{state_filename}.state'
55 | options.stateFile = os.path.join(
56 | options.logDirectory, state_filename
57 | )
58 | options.crawlShares = not args.shares_only
59 | options.maxDepth = args.max_depth
60 | options.patternsFile = args.patterns_file
61 | options.downloadFiles = args.download_files
62 | options.logLevel = logging.DEBUG if args.debug else logging.INFO
63 |
64 | if str(args.include_paths) != "None":
65 | options.includePaths = str(args.include_paths).split(",")
66 | if str(args.exclude_paths) != "None":
67 | options.excludePaths = str(args.exclude_paths).split(",")
68 | if str(args.include_shares) != "None":
69 | options.includeShares = str(args.include_shares).split(",")
70 | if str(args.exclude_shares) != "None":
71 | options.excludeShares = str(args.exclude_shares).split(",")
72 | if str(args.exclude_hosts) != "None":
73 | options.excludeHosts = str(args.exclude_hosts).split(",")
74 |
75 | with open(options.patternsFile, "r") as k_file:
76 | for line in k_file:
77 | options.patterns.append(re.compile(line.strip(), re.IGNORECASE))
78 |
79 | user = User()
80 | if args.user:
81 | user.username = args.user
82 | ntlmHash = args.hash
83 | if ntlmHash:
84 | user.lmhash = ntlmHash.split(':')[0]
85 | user.nthash = ntlmHash.split(':')[1]
86 | elif args.no_pass:
87 | pass
88 | else:
89 | user.password = args.password if args.password else getpass.getpass()
90 | user.domain = args.domain if args.domain else ""
91 |
92 | options.kerberos = args.kerberos
93 | if args.kerberos:
94 | user.domain = args.domain if args.domain else ""
95 | options.dc_ip = args.dc_ip if args.dc_ip else ""
96 | options.aesKey = args.aesKey if args.aesKey else ""
97 |
98 | logger = logging.getLogger('smbscan')
99 | logger.setLevel(options.logLevel)
100 | formatter = logging.Formatter("[%(asctime)s %(threadName)s %(levelname)s] %(message)s",
101 | "%Y-%m-%d %H:%M:%S")
102 |
103 | logFileHandler = handlers.RotatingFileHandler(options.csvFile,
104 | maxBytes=1024 * 1024 * 5,
105 | backupCount=2)
106 | logFileHandler.setLevel(options.logLevel)
107 | logFileHandler.setFormatter(formatter)
108 | logger.addHandler(logFileHandler)
109 |
110 | stdoutHandler = logging.StreamHandler(sys.stdout)
111 | stdoutHandler.setLevel(options.logLevel)
112 | stdoutHandler.setFormatter(formatter)
113 | logger.addHandler(stdoutHandler)
114 |
115 | # Record arguments
116 | logger.info(' '.join(sys.argv[0:]))
117 |
118 | # Load targets into list
119 | target_list = []
120 | if args.target:
121 | logger.info(f"Scanning {args.target}")
122 | if valid_ip(args.target):
123 | for targetIP in ipaddress.IPv4Network(str(args.target)):
124 | target_list.append((targetIP, user, options))
125 | else:
126 | target_list.append((str(args.target), user, options))
127 | else:
128 | with args.file as file:
129 | target = file.readline().strip()
130 | while target:
131 | if len(target.split(',')) == 3:
132 | hash_target = target.split(',')[0]
133 | hash_username = target.split(',')[1]
134 | hash_hash = target.split(',')[2]
135 | logger.debug(f'Hash Target: {hash_target}, User: {hash_username}, Hash: {hash_hash}')
136 |
137 | hash_user = User()
138 | hash_user.username = hash_username
139 | ntlmHash = hash_hash
140 | if ntlmHash:
141 | hash_user.lmhash = ntlmHash.split(':')[0]
142 | hash_user.nthash = ntlmHash.split(':')[1]
143 |
144 | if valid_ip(hash_target):
145 | for targetIP in ipaddress.IPv4Network(str(hash_target)):
146 | target_list.append((targetIP, hash_user, options))
147 | else:
148 | target_list.append((str(hash_target), hash_user, options))
149 | else:
150 | logger.debug(f'Standard Target: {target}, User: {user.username}')
151 | if valid_ip(target):
152 | for targetIP in ipaddress.IPv4Network(str(target)):
153 | target_list.append((targetIP, user, options))
154 | else:
155 | target_list.append((str(target), user, options))
156 | target = file.readline().strip()
157 |
158 | logger.info(f'Scanning with {options.threads} threads')
159 | set_start_method("spawn")
160 | with ThreadPool(processes=options.threads) as pool:
161 | result = pool.starmap_async(scan_single, target_list, chunksize=1)
162 | result.wait()
163 |
164 | logger.info("Scan completed")
165 |
166 |
167 | if __name__ == "__main__":
168 | main()
169 |
--------------------------------------------------------------------------------
/tests/test_scan_internals.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from unittest.mock import patch
3 |
4 | import impacket
5 |
6 | import arg_parser
7 | import scan
8 | import scan_internals
9 |
10 | class TestIsValidPath:
11 | TEST_CWD = '/Users/path' # Test Current Working Directory for patch
12 |
13 | logDirectory = TEST_CWD + '/logs'
14 |
15 | @patch('os.getcwd', return_value=TEST_CWD)
16 | def assert_is_safe_filepath(self, path, expectedResult, mock_os_cwd):
17 | assert(scan_internals.is_safe_filepath(self.logDirectory, path) == expectedResult)
18 |
19 | def test_normal_path(self):
20 | path = self.logDirectory + '/normal'
21 | self.assert_is_safe_filepath(path, True)
22 |
23 | def test_bad_path(self):
24 | self.assert_is_safe_filepath('/bad', False)
25 |
26 | def test_traversal_path(self):
27 | self.assert_is_safe_filepath('..', False)
28 |
29 |
30 | class TestIsValidShareName:
31 | def assert_is_valid_share_name(self, share_name, expectedResult):
32 | assert(scan_internals.is_valid_share_name(share_name) == expectedResult)
33 |
34 | def test_normal_path(self):
35 | self.assert_is_valid_share_name('tmp', True)
36 |
37 | def test_bad_path(self):
38 | self.assert_is_valid_share_name('tmp\\..\\tmp', False)
39 |
40 |
41 | class TestIsSafeRemotePath:
42 | def assert_is_safe_remotepath(self, path, expectedResult):
43 | assert(scan_internals.is_safe_remotepath(path) == expectedResult)
44 |
45 | def test_normal_path(self):
46 | self.assert_is_safe_remotepath('\\tmp', True)
47 |
48 | def test_bad_paths(self):
49 | self.assert_is_safe_remotepath('\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\tmp', False)
50 | self.assert_is_safe_remotepath('..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\tmp', False)
51 |
52 |
53 | def test_get_shares(test_client):
54 | shares = scan_internals.get_shares(test_client)
55 |
56 | assert(len(shares) == 2)
57 | assert(shares[0].shareName == "Admin")
58 | assert(shares[1].shareName == "TestShare")
59 |
60 | def test_get_client(test_target, test_user, test_options):
61 | with patch.object(impacket.smbconnection.SMBConnection, '__init__', mock_connection_init):
62 | with patch.object(impacket.smbconnection.SMBConnection, 'login', mock_login):
63 | port = 445
64 | client = scan_internals.get_client(test_target, test_user, test_options, port)
65 |
66 | assert(client != None)
67 | assert(client._remoteHost == test_target.ip)
68 |
69 | def mock_connection_init(self, remoteName='', remoteHost='', myName=None, sess_port=impacket.nmb.SMB_SESSION_PORT,
70 | timeout=60, preferredDialect=None, existingConnection=None, manualNegotiate=False):
71 | """Mock SMBConnection constructor and return default values."""
72 | self._SMBConnection = 0
73 | self._dialect = ''
74 | self._nmbSession = 0
75 | self._sess_port = sess_port
76 | self._myName = myName
77 | self._remoteHost = remoteHost
78 | self._remoteName = remoteName
79 | self._timeout = timeout
80 | self._preferredDialect = preferredDialect
81 | self._existingConnection = existingConnection
82 | self._manualNegotiate = manualNegotiate
83 | self._doKerberos = False
84 | self._kdcHost = None
85 | self._useCache = True
86 | self._ntlmFallback = True
87 |
88 | def mock_login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True):
89 | """Mock SMBConnection login() and return None"""
90 | return None
91 |
92 | @pytest.fixture
93 | def test_target():
94 | ip = '127.0.0.1'
95 | return scan.Target(ip)
96 |
97 | @pytest.fixture
98 | def test_user():
99 | return scan.User()
100 |
101 | @pytest.fixture
102 | def test_options():
103 | return arg_parser.Options()
104 |
105 | @pytest.fixture
106 | def test_client():
107 | class TestClient:
108 | def listShares(self):
109 | return [
110 | {"shi1_netname": "IPC$\\"},
111 | {"shi1_netname": "Admin\\"},
112 | {"shi1_netname": "TestShare\\"}
113 | ]
114 | return TestClient()
115 |
--------------------------------------------------------------------------------
/wordlists/patterns.md:
--------------------------------------------------------------------------------
1 | # Patterns
2 |
3 | | Example Filename or Extension | Regular Expression | Description |
4 | | --- | --- | --- |
5 | | `My Passwords.txt` | `^.*(password\|credential\|logon).*\.(txt\|rtf\|doc\|xls).?$` | Text, RTF, and Office files containing `password`, `credential`, or `logon` in the filename |
6 | | `web.config`, `*.conf` | `^.*\.(cfg\|conf(ig)?)$` | Config files, e.g. `web.config` |
7 | | `wp-config.php`, `wp-config.bak` | `^.*wp-config.*$` | Wordpress config files e.g. `wp-config.php` and `wp-config.bak` |
8 | | `*.env` | `^.*\.env$` | Environment variables |
9 | | `*.bat` | `^.*\.bat$` | Batch files |
10 | | `*.vbs` | `^.*\.vbs$` | VBScripts |
11 | | `*.ps1` | `^.*\.ps1$` | PowerShell scripts |
12 | | `*.sh` | `^.*\.sh$` | Shell scripts |
13 | | `*.htpass` | `^.*\.htpass$` | Usernames and passwords |
14 | | `Freds Handover.pptx` | `^.*(handover).*\.(txt\|rtf\|pdf\|doc\|ppt\|xls).?$` | Text, RTF, PDF, and Office files containing `handover` in the filename |
15 | | `credentials` | `^credentials$` | AWS Credentials file, e.g. `~/.aws/credentials` |
16 | | `unattend.xml `| `^unattend\.xml$` | Windows setup file |
17 | | `unattended.xml` | `^unattended\.xml$` | Windows setup file |
18 | | `sysprep.inf` | `^sysprep\.inf$` | Windows setup file |
19 | | `sysprep.xml` | `^sysprep\.xml$` | Windows setup file |
20 | | `group.xml` | `^group\.xml$` | Group Policy Preferences (GPP) |
21 | | `groups.xml` | `^groups\.xml$` | Group Policy Preferences (GPP) |
22 | | `services.xml` | `^services\.xml$` | Group Policy Preferences (GPP) Create/Update Services |
23 | | `scheduledtasks.xml` | `^scheduledtasks\.xml$` | Group Policy Preferences (GPP) Scheduled Tasks |
24 | | `printers.xml` | `^printers\.xml$` | Group Policy Preferences (GPP) Printer configuration |
25 | | `drives.xml` | `^drives\.xml$` | Group Policy Preferences (GPP) Map drives |
26 | | `datasources.xml` | `^datasources\.xml$` | Group Policy Preferences (GPP) Data Sources |
27 | | `vnc.ini` | `^vnc\.ini$` | May contain encrypted password |
28 | | `WinSCP.ini` | `^WinSCP\.ini$` | May contain ssh credentials |
29 | | `ws_ftp.ini` | `^ws_ftp\.ini$` | May contain ftp credentials |
30 | | `*.kdb`, `*.kdbx` | `^.*\.kdb.?$` | Keepass containers |
31 | | `config.xml` | `^.*config\.xml$` | Config files in XML |
32 | | `id_rsa` | `^.*(id_dsa\|id_ecdsa\|id_ed25519\|id_rsa).*$` | Default private key filenames from `ssh_keygen` |
33 | | `*.pem`, `*.ppk` | `^.*\.(pem\|ppk)$` | Private keys |
--------------------------------------------------------------------------------
/wordlists/patterns.txt:
--------------------------------------------------------------------------------
1 | ^.*(password|credential|logon).*\.(txt|rtf|doc|xls|pdf).?$
2 | ^.*\.(cfg|cnf|conf(ig)?)$
3 | ^.*wp-config.*$
4 | ^.*\.env$
5 | ^.*\.bat$
6 | ^.*\.vbs$
7 | ^.*\.ps1$
8 | ^.*\.sh$
9 | ^.*\.htpass$
10 | ^.*(handover).*\.(txt|rtf|pdf|doc|ppt|xls).?$
11 | ^.*credentials$
12 | ^.*unattend\.xml$
13 | ^.*unattended\.xml$
14 | ^.*sysprep\.inf$
15 | ^.*sysprep\.xml$
16 | ^.*group\.xml$
17 | ^.*groups\.xml$
18 | ^.*services\.xml$
19 | ^.*scheduledtasks\.xml$
20 | ^.*printers\.xml$
21 | ^.*drives\.xml$
22 | ^.*datasources\.xml$
23 | ^.*vnc\.ini$
24 | ^.*WinSCP\.ini$
25 | ^.*ws_ftp\.ini$
26 | ^.*\.kdb.?$
27 | ^.*config\.xml$
28 | ^.*(id_dsa|id_ecdsa|id_ed25519|id_rsa).*$
29 | ^.*\.(pem|ppk)$
30 | ^.*(known_hosts).*$
31 | ^.*(\\.ssh\\).*$
32 | ^.*(\\.aws\\).*$
33 | ^.*ntds\.dit$
34 | ^.*compose\.yaml$
35 | ^.*application\.yaml$
36 | ^.*docker-compose\.yaml$
37 | ^.*dockerfile$
38 | ^.*secure-key$
39 | ^.*\.hive$
40 | ^.*\.cred$
41 | ^.*\.key$
42 | ^.*(\\Users|\\ProgramData).*(\.ini)$
43 | ^.*\.rdp$
44 | ^.*ntuser\.(dat|log1|log2)$
45 | ^.*\.vcrd$
46 | ^.*\.vpol$
47 | ^.*(\\Users).*(\\AppData\\Local\\Microsoft\\Vault\\).*$
48 | ^.*(\\Users).*(\\AppData\\Local\\Microsoft\\Credentials\\).*$
49 | ^.*(\\Users).*(\\AppData\\Roaming\\Microsoft\\Protect\\).*$
50 | ^.*(\\Windows\\System32\\config\\systemprofile\\AppData\\Local\\Microsoft\\Credentials).*$
51 | ^.*(\\Windows\\System32\\Microsoft\\Protect).*$
52 | ^.*sitemanager\.xml$
53 | ^.*Sessions\.xml$
54 | ^.*\.sdtid$
55 | ^.*confcons\.xml.*$
56 | ^.*\.git\\config$
57 | ^.*\.gitconfig$
58 | ^.*\.ovpn$
59 | ^.*(\\cmder\\config\\).*$
--------------------------------------------------------------------------------