pax_global_header 0000666 0000000 0000000 00000000064 14111332555 0014512 g ustar 00root root 0000000 0000000 52 comment=9e907dfe09fce2997f0301d746796408e01a60b7
recon-ng-5.1.2/ 0000775 0000000 0000000 00000000000 14111332555 0013227 5 ustar 00root root 0000000 0000000 recon-ng-5.1.2/.gitignore 0000664 0000000 0000000 00000000045 14111332555 0015216 0 ustar 00root root 0000000 0000000 *.pyc
*.rdb
*sublime*
venv/
scripts/
recon-ng-5.1.2/Dockerfile 0000664 0000000 0000000 00000000463 14111332555 0015224 0 ustar 00root root 0000000 0000000 FROM python:3.7-alpine AS recon-ng
RUN mkdir -p /recon-ng
WORKDIR /recon-ng
COPY ./REQUIREMENTS /recon-ng/REQUIREMENTS
RUN apk add --no-cache --virtual .build-deps gcc libc-dev libxslt-dev &&\
apk add --no-cache libxslt &&\
pip install --no-cache-dir -r REQUIREMENTS &&\
apk del .build-deps
recon-ng-5.1.2/LICENSE 0000664 0000000 0000000 00000104505 14111332555 0014241 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
.
recon-ng-5.1.2/README.md 0000664 0000000 0000000 00000003472 14111332555 0014514 0 ustar 00root root 0000000 0000000 # The Recon-ng Framework
[Recon-ng content now available on Pluralsight!](https://app.pluralsight.com/library/courses/technical-information-gathering-recon-ng)
Recon-ng is a full-featured reconnaissance framework designed with the goal of providing a powerful environment to conduct open source web-based reconnaissance quickly and thoroughly.
Recon-ng has a look and feel similar to the Metasploit Framework, reducing the learning curve for leveraging the framework. However, it is quite different. Recon-ng is not intended to compete with existing frameworks, as it is designed exclusively for web-based open source reconnaissance. If you want to exploit, use the Metasploit Framework. If you want to social engineer, use the Social-Engineer Toolkit. If you want to conduct reconnaissance, use Recon-ng! See the [Wiki](https://github.com/lanmaster53/recon-ng/wiki) to get started.
Recon-ng is a completely modular framework and makes it easy for even the newest of Python developers to contribute. See the [Development Guide](https://github.com/lanmaster53/recon-ng/wiki/Development-Guide) for more information on building and maintaining modules.
## Sponsors
[](http://www.blackhillsinfosec.com)
[](http://www.practisec.com)
## Donations
Recon-ng is free software. However, large amounts of time and effort go into its continued development. If you are interested in financially supporting the project, you can view and assist in marketing the [Pluralsight content](https://app.pluralsight.com/library/courses/technical-information-gathering-recon-ng), or send a donation to tjt1980[at]gmail.com via PayPal. Thank you.
recon-ng-5.1.2/REQUIREMENTS 0000664 0000000 0000000 00000000173 14111332555 0015076 0 ustar 00root root 0000000 0000000 # framework
pyyaml
dnspython
lxml
mechanize
requests
# web
flask
flask-restful
flasgger
dicttoxml
XlsxWriter
unicodecsv
rq
recon-ng-5.1.2/VERSION 0000664 0000000 0000000 00000000453 14111332555 0014301 0 ustar 00root root 0000000 0000000 __version__ = '5.1.2'
# ex. x.y.z
# x - Incremented for changes requiring migration. (major revision)
# y - Incremented for the addition of new features. (minor revision)
# z - Incremented for minor code changes and bug fixes. (hotfix)
# Subordinate items reset to 0 when superior items increment.
recon-ng-5.1.2/docker-compose.yml 0000664 0000000 0000000 00000001330 14111332555 0016661 0 ustar 00root root 0000000 0000000 version: '3.7'
services:
web:
build: .
image: recon-ng
container_name: recon-ng
ports:
- '5000:5000'
command: ./recon-web --host 0.0.0.0
volumes:
- .:/recon-ng
- ~/.recon-ng:/root/.recon-ng
environment:
- REDIS_URL=redis://redis:6379/0
depends_on:
- redis
worker:
image: recon-ng
command: rq worker -u redis://redis:6379/0 recon-tasks
volumes:
- .:/recon-ng
- ~/.recon-ng:/root/.recon-ng
environment:
- REDIS_URL=redis://redis:6379/0
depends_on:
- redis
- web
redis:
image: redis
recon-ng-5.1.2/recon-cli 0000775 0000000 0000000 00000010032 14111332555 0015024 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import argparse
import sys
# prevent creation of compiled bytecode files
sys.dont_write_bytecode = True
from recon.core import base
from recon.core.framework import Colors
def output(string):
print(f"{Colors.B}[*]{Colors.N} {string}")
def recon_cli(args):
# process toggle flag arguments
flags = {
'check': args.check if not args.stealth else False,
'analytics': args.analytics if not args.stealth else False,
'marketplace': args.marketplace if not args.stealth else False,
}
# instantiate framework
x = base.Recon(**flags)
options = [base.Mode.CLI]
if args.workspace:
options.append(args.workspace)
x.start(*options)
# set given workspace
if args.workspace:
x._init_workspace(args.workspace)
print(f"WORKSPACE => {args.workspace}")
# run given global commands
for command in args.global_commands:
print(f"GLOBAL COMMAND => {command}")
x.onecmd(command)
# set given global options
for option in args.goptions:
param = ' '.join(option.split('='))
x._do_options_set(param)
# if requested, show global options and exit
if args.gshow:
x._do_options_list('')
return
# if requested, show modules and exit
if args.show_modules:
x._do_modules_search('')
return
# exit if module not specified
if not args.module:
output('No module provided.')
return
# load the module
y = x._do_modules_load(args.module)
# exit if module not successfully loaded
if not y: return
print(f"MODULE => {args.module}")
# run given module commands
for command in args.module_commands:
print(f"MODULE COMMAND => {command}")
y.onecmd(command)
# set given module options
for option in args.options:
param = ' '.join(option.split('='))
y._do_options_set(param)
# if requested, show module options and exit
if args.show:
y._do_options_list('')
return
if args.run:
# run the module
y.do_run(None)
description = f"%(prog)s - {base.__author__}"
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-w', help='load/create a workspace', metavar='workspace', dest='workspace', action='store')
parser.add_argument('-C', help='runs a command at the global context', metavar='command', dest='global_commands' ,default=[], action='append')
parser.add_argument('-c', help='runs a command at the module context (pre-run)', metavar='command', dest='module_commands' ,default=[], action='append')
parser.add_argument('-G', help='show available global options', dest='gshow', default=False, action='store_true')
parser.add_argument('-g', help='set a global option (can be used more than once)', metavar='name=value', dest='goptions', default=[], action='append')
parser.add_argument('-M', help='show modules', dest='show_modules', default=False, action='store_true')
parser.add_argument('-m', help='specify the module', metavar='module', dest='module', action='store')
parser.add_argument('-O', help='show available module options', dest='show', default=False, action='store_true')
parser.add_argument('-o', help='set a module option (can be used more than once)', metavar='name=value', dest='options', default=[], action='append')
parser.add_argument('-x', help='run the module', dest='run', default=False, action='store_true')
parser.add_argument('--no-version', help='disable version check', dest='check', default=True, action='store_false')
parser.add_argument('--no-analytics', help='disable analytics reporting', dest='analytics', default=True, action='store_false')
parser.add_argument('--no-marketplace', help='disable remote module management', dest='marketplace', default=True, action='store_false')
parser.add_argument('--stealth', help='disable all passive requests (--no-*)', dest='stealth', default=False, action='store_true')
parser.add_argument('--version', help='displays the current version', action='version', version=base.__version__)
args = parser.parse_args()
recon_cli(args)
recon-ng-5.1.2/recon-ng 0000775 0000000 0000000 00000005162 14111332555 0014671 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import argparse
import re
import sys
# prevent creation of compiled bytecode files
sys.dont_write_bytecode = True
from recon.core import base
from recon.core.framework import Colors
def recon_ui(args):
# set up command completion
try:
import readline
except ImportError:
print(f"{Colors.R}[!] Module 'readline' not available. Tab complete disabled.{Colors.N}")
else:
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
readline.set_completer_delims(re.sub('[/-]', '', readline.get_completer_delims()))
# for possible future use to format command completion output
#readline.set_completion_display_matches_hook(display_hook)
# process toggle flag arguments
flags = {
'check': args.check if not args.stealth else False,
'analytics': args.analytics if not args.stealth else False,
'marketplace': args.marketplace if not args.stealth else False,
'accessible' : args.accessible
}
# instantiate framework
x = base.Recon(**flags)
# check for and run script session
if args.script_file:
x._do_script_execute(args.script_file)
# launch the interactive session
options = [base.Mode.CONSOLE]
if args.workspace:
options.append(args.workspace)
try:
x.start(*options)
except KeyboardInterrupt:
print('')
description = f"%(prog)s - {base.__author__}"
parser = argparse.ArgumentParser(description=description)
parser.add_argument('-w', help='load/create a workspace', metavar='workspace', dest='workspace', action='store')
parser.add_argument('-r', help='load commands from a resource file', metavar='filename', dest='script_file', action='store')
parser.add_argument('--no-version', help='disable version check', dest='check', default=True, action='store_false')
parser.add_argument('--no-analytics', help='disable analytics reporting', dest='analytics', default=True, action='store_false')
parser.add_argument('--no-marketplace', help='disable remote module management', dest='marketplace', default=True, action='store_false')
parser.add_argument('--stealth', help='disable all passive requests (--no-*)', dest='stealth', default=False, action='store_true')
parser.add_argument('--accessible', help='Use accessible outputs when available', dest='accessible', default=False, action='store_true')
parser.add_argument('--version', help='displays the current version', action='version', version=base.__version__)
args = parser.parse_args()
recon_ui(args)
recon-ng-5.1.2/recon-web 0000775 0000000 0000000 00000000617 14111332555 0015042 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
from recon.core.web import create_app
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='127.0.0.1', help="IP address to listen on")
parser.add_argument('--port', default=5000, help="port to bind the web server to")
args = parser.parse_args()
app = create_app()
if __name__ == '__main__':
app.run(host=args.host, port=args.port)
recon-ng-5.1.2/recon/ 0000775 0000000 0000000 00000000000 14111332555 0014335 5 ustar 00root root 0000000 0000000 recon-ng-5.1.2/recon/__init__.py 0000664 0000000 0000000 00000000000 14111332555 0016434 0 ustar 00root root 0000000 0000000 recon-ng-5.1.2/recon/core/ 0000775 0000000 0000000 00000000000 14111332555 0015265 5 ustar 00root root 0000000 0000000 recon-ng-5.1.2/recon/core/__init__.py 0000664 0000000 0000000 00000000000 14111332555 0017364 0 ustar 00root root 0000000 0000000 recon-ng-5.1.2/recon/core/base.py 0000664 0000000 0000000 00000120374 14111332555 0016560 0 ustar 00root root 0000000 0000000 __author__ = 'Tim Tomes (@lanmaster53)'
from datetime import datetime
from pathlib import Path
from urllib.parse import urljoin
import errno
import imp
import json
import os
import random
import re
import shutil
import sys
import yaml
import builtins
# import framework libs
from recon.core import framework
from recon.core.constants import BANNER, BANNER_SMALL
# set the __version__ variable based on the VERSION file
exec(open(os.path.join(Path(os.path.abspath(__file__)).parents[2], 'VERSION')).read())
# using stdout to spool causes tab complete issues
# therefore, override print function
# use a lock for thread safe console and spool output
from threading import Lock
_print_lock = Lock()
# spooling system
def spool_print(*args, **kwargs):
with _print_lock:
if framework.Framework._spool:
framework.Framework._spool.write(f"{args[0]}{os.linesep}")
framework.Framework._spool.flush()
# disable terminal output for server jobs
if framework.Framework._mode == Mode.JOB:
return
# new print function must still use the old print function via the backup
builtins._print(*args, **kwargs)
# make a builtin backup of the original print function
builtins._print = print
# override the builtin print function with the new print function
builtins.print = spool_print
#=================================================
# BASE CLASS
#=================================================
class Recon(framework.Framework):
repo_url = 'https://raw.githubusercontent.com/lanmaster53/recon-ng-modules/master/'
def __init__(self, check=True, analytics=True, marketplace=True, accessible=False):
framework.Framework.__init__(self, 'base')
self._name = 'recon-ng'
self._prompt_template = '{}[{}] > '
self._base_prompt = self._prompt_template.format('', self._name)
# set toggle flags
self._check = check
self._analytics = analytics
self._marketplace = marketplace
self._accessible = accessible
# set path variables
self.app_path = framework.Framework.app_path = sys.path[0]
self.core_path = framework.Framework.core_path = os.path.join(self.app_path, 'core')
self.home_path = framework.Framework.home_path = os.path.join(os.path.expanduser('~'), '.recon-ng')
self.mod_path = framework.Framework.mod_path = os.path.join(self.home_path, 'modules')
self.data_path = framework.Framework.data_path = os.path.join(self.home_path, 'data')
self.spaces_path = framework.Framework.spaces_path = os.path.join(self.home_path, 'workspaces')
def start(self, mode, workspace='default'):
# initialize framework components
self._mode = framework.Framework._mode = mode
self._init_global_options()
self._init_home()
self._init_workspace(workspace)
self._check_version()
if self._mode == Mode.CONSOLE:
self._print_banner()
self.cmdloop()
#==================================================
# SUPPORT METHODS
#==================================================
def _init_global_options(self):
self.options = self._global_options
self.register_option('nameserver', '8.8.8.8', True, 'default nameserver for the resolver mixin')
self.register_option('proxy', None, False, 'proxy server (address:port)')
self.register_option('threads', 10, True, 'number of threads (where applicable)')
self.register_option('timeout', 10, True, 'socket timeout (seconds)')
self.register_option('user-agent', f"Recon-ng/v{__version__.split('.')[0]}", True, 'user-agent string')
self.register_option('verbosity', 1, True, 'verbosity level (0 = minimal, 1 = verbose, 2 = debug)')
def _init_home(self):
# initialize home folder
if not os.path.exists(self.home_path):
os.makedirs(self.home_path)
# initialize keys database
self._query_keys('CREATE TABLE IF NOT EXISTS keys (name TEXT PRIMARY KEY, value TEXT)')
# initialize module index
self._fetch_module_index()
def _check_version(self):
if self._check:
pattern = r"'(\d+\.\d+\.\d+[^']*)'"
remote = 0
local = 0
try:
remote = re.search(pattern, self.request('GET', 'https://raw.githubusercontent.com/lanmaster53/recon-ng/master/VERSION').text).group(1)
local = re.search(pattern, open('VERSION').read()).group(1)
except Exception as e:
self.error(f"Version check failed ({type(e).__name__}).")
#self.print_exception()
if remote != local:
self.alert('Your version of Recon-ng does not match the latest release.')
self.alert('Please consider updating before further use.')
self.output(f"Remote version: {remote}")
self.output(f"Local version: {local}")
else:
self.alert('Version check disabled.')
def _print_banner(self):
banner = BANNER
banner_len = len(max(banner.split(os.linesep), key=len))
author = '{0:^{1}}'.format(f"{framework.Colors.O}[{self._name} v{__version__}, {__author__}]{framework.Colors.N}", banner_len + 8)
if self._accessible:
banner = BANNER_SMALL
author = f"{framework.Colors.O}{self._name}, version {__version__}, by {__author__}{framework.Colors.N}"
print(banner)
print(author)
print('')
counts = [(len(self._loaded_category[x]), x) for x in self._loaded_category]
if counts:
count_len = len(max([self.to_unicode_str(x[0]) for x in counts], key=len))
for count in sorted(counts, reverse=True):
cnt = f"[{count[0]}]"
print(f"{framework.Colors.B}{cnt.ljust(count_len+2)} {count[1].title()} modules{framework.Colors.N}")
# create dynamic easter egg command based on counts
setattr(self, f"do_{count[0]}", self._menu_egg)
else:
self.alert('No modules enabled/installed.')
print('')
def _send_analytics(self, cd):
if self._analytics:
try:
cid_path = os.path.join(self.home_path, '.cid')
if not os.path.exists(cid_path):
# create the cid and file
import uuid
with open(cid_path, 'w') as fp:
fp.write(self.to_unicode_str(uuid.uuid4()))
with open(cid_path) as fp:
cid = fp.read().strip()
params = {
'v': 1,
'tid': 'UA-52269615-2',
'cid': cid,
't': 'screenview',
'an': 'Recon-ng',
'av': __version__,
'cd': cd
}
self.request('GET', 'https://www.google-analytics.com/collect', params=params)
except Exception as e:
self.debug(f"Analytics failed ({type(e).__name__}).")
#self.print_exception()
return
else:
self.debug('Analytics disabled.')
def _menu_egg(self, params):
eggs = [
'Really? A menu option? Try again.',
'You clearly need \'help\'.',
'That makes no sense to me.',
'*grunt* *grunt* Nope. I got nothin\'.',
'Wait for it...',
'This is not the Social Engineering Toolkit.',
'Don\'t you think if that worked the numbers would at least be in order?',
'Reserving that option for the next-NEXT generation of the framework.',
'You\'ve clearly got the wrong framework. Attempting to start SET...',
'1980 called. They want there menu driven UI back.',
]
print(random.choice(eggs))
return
#==================================================
# WORKSPACE METHODS
#==================================================
def _init_workspace(self, workspace):
if not workspace:
return
path = os.path.join(self.spaces_path, workspace)
self.workspace = framework.Framework.workspace = path
if not os.path.exists(path):
os.makedirs(path)
self._create_db()
else:
self._migrate_db()
# set workspace prompt
self.prompt = self._prompt_template.format(self._base_prompt[:-3], self.workspace.split('/')[-1])
# load workspace configuration
self._load_config()
# reload modules after config to populate options
self._load_modules()
return True
def remove_workspace(self, workspace):
path = os.path.join(self.spaces_path, workspace)
try:
shutil.rmtree(path)
except OSError:
return False
if workspace == self.workspace.split('/')[-1]:
self._init_workspace('default')
return True
def _get_workspaces(self):
workspaces = []
path = self.spaces_path
for name in os.listdir(path):
if os.path.isdir(os.path.join(path, name)):
workspaces.append(name)
return workspaces
def _get_snapshots(self):
snapshots = []
for f in os.listdir(self.workspace):
if re.search(r'^snapshot_\d{14}.db$', f):
snapshots.append(f)
return snapshots
def _create_db(self):
self.query('CREATE TABLE IF NOT EXISTS domains (domain TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS companies (company TEXT, description TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS netblocks (netblock TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS locations (latitude TEXT, longitude TEXT, street_address TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS vulnerabilities (host TEXT, reference TEXT, example TEXT, publish_date TEXT, category TEXT, status TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS ports (ip_address TEXT, host TEXT, port TEXT, protocol TEXT, banner TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS hosts (host TEXT, ip_address TEXT, region TEXT, country TEXT, latitude TEXT, longitude TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS contacts (first_name TEXT, middle_name TEXT, last_name TEXT, email TEXT, title TEXT, region TEXT, country TEXT, phone TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS credentials (username TEXT, password TEXT, hash TEXT, type TEXT, leak TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS leaks (leak_id TEXT, description TEXT, source_refs TEXT, leak_type TEXT, title TEXT, import_date TEXT, leak_date TEXT, attackers TEXT, num_entries TEXT, score TEXT, num_domains_affected TEXT, attack_method TEXT, target_industries TEXT, password_hash TEXT, password_type TEXT, targets TEXT, media_refs TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS pushpins (source TEXT, screen_name TEXT, profile_name TEXT, profile_url TEXT, media_url TEXT, thumb_url TEXT, message TEXT, latitude TEXT, longitude TEXT, time TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS profiles (username TEXT, resource TEXT, url TEXT, category TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS repositories (name TEXT, owner TEXT, description TEXT, resource TEXT, category TEXT, url TEXT, notes TEXT, module TEXT)')
self.query('CREATE TABLE IF NOT EXISTS dashboard (module TEXT PRIMARY KEY, runs INT)')
self.query('PRAGMA user_version = 10')
def _migrate_db(self):
db_version = lambda self: self.query('PRAGMA user_version')[0][0]
db_orig = db_version(self)
if db_version(self) == 0:
# add mname column to contacts table
tmp = self.get_random_str(20)
self.query(f"ALTER TABLE contacts RENAME TO {tmp}")
self.query('CREATE TABLE contacts (fname TEXT, mname TEXT, lname TEXT, email TEXT, title TEXT, region TEXT, country TEXT)')
self.query(f"INSERT INTO contacts (fname, lname, email, title, region, country) SELECT fname, lname, email, title, region, country FROM {tmp}")
self.query(f"DROP TABLE {tmp}")
self.query('PRAGMA user_version = 1')
if db_version(self) == 1:
# rename name columns
tmp = self.get_random_str(20)
self.query(f"ALTER TABLE contacts RENAME TO {tmp}")
self.query('CREATE TABLE contacts (first_name TEXT, middle_name TEXT, last_name TEXT, email TEXT, title TEXT, region TEXT, country TEXT)')
self.query(f"INSERT INTO contacts (first_name, middle_name, last_name, email, title, region, country) SELECT fname, mname, lname, email, title, region, country FROM {tmp}")
self.query(f"DROP TABLE {tmp}")
# rename pushpin table
self.query('ALTER TABLE pushpin RENAME TO pushpins')
# add new tables
self.query('CREATE TABLE IF NOT EXISTS domains (domain TEXT)')
self.query('CREATE TABLE IF NOT EXISTS companies (company TEXT, description TEXT)')
self.query('CREATE TABLE IF NOT EXISTS netblocks (netblock TEXT)')
self.query('CREATE TABLE IF NOT EXISTS locations (latitude TEXT, longitude TEXT)')
self.query('CREATE TABLE IF NOT EXISTS vulnerabilities (host TEXT, reference TEXT, example TEXT, publish_date TEXT, category TEXT)')
self.query('CREATE TABLE IF NOT EXISTS ports (ip_address TEXT, host TEXT, port TEXT, protocol TEXT)')
self.query('CREATE TABLE IF NOT EXISTS leaks (leak_id TEXT, description TEXT, source_refs TEXT, leak_type TEXT, title TEXT, import_date TEXT, leak_date TEXT, attackers TEXT, num_entries TEXT, score TEXT, num_domains_affected TEXT, attack_method TEXT, target_industries TEXT, password_hash TEXT, targets TEXT, media_refs TEXT)')
self.query('PRAGMA user_version = 2')
if db_version(self) == 2:
# add street_address column to locations table
self.query('ALTER TABLE locations ADD COLUMN street_address TEXT')
self.query('PRAGMA user_version = 3')
if db_version(self) == 3:
# account for db_version bug
if 'creds' in self.get_tables():
# rename creds table
self.query('ALTER TABLE creds RENAME TO credentials')
self.query('PRAGMA user_version = 4')
if db_version(self) == 4:
# add status column to vulnerabilities table
if 'status' not in [x[0] for x in self.get_columns('vulnerabilities')]:
self.query('ALTER TABLE vulnerabilities ADD COLUMN status TEXT')
# add module column to all tables
for table in ['domains', 'companies', 'netblocks', 'locations', 'vulnerabilities', 'ports', 'hosts', 'contacts', 'credentials', 'leaks', 'pushpins']:
if 'module' not in [x[0] for x in self.get_columns(table)]:
self.query(f"ALTER TABLE {table} ADD COLUMN module TEXT")
self.query('PRAGMA user_version = 5')
if db_version(self) == 5:
# add profile table
self.query('CREATE TABLE IF NOT EXISTS profiles (username TEXT, resource TEXT, url TEXT, category TEXT, notes TEXT, module TEXT)')
self.query('PRAGMA user_version = 6')
if db_version(self) == 6:
# add repositories table
self.query('CREATE TABLE IF NOT EXISTS repositories (name TEXT, owner TEXT, description TEXT, resource TEXT, category TEXT, url TEXT, module TEXT)')
self.query('PRAGMA user_version = 7')
if db_version(self) == 7:
# add password_type column to leaks table
self.query('ALTER TABLE leaks ADD COLUMN password_type TEXT')
self.query('UPDATE leaks SET password_type=\'unknown\'')
self.query('PRAGMA user_version = 8')
if db_version(self) == 8:
# add banner column to ports table
self.query('ALTER TABLE ports ADD COLUMN banner TEXT')
# add notes column to all tables
for table in ['domains', 'companies', 'netblocks', 'locations', 'vulnerabilities', 'ports', 'hosts', 'contacts', 'credentials', 'leaks', 'pushpins', 'profiles', 'repositories']:
if 'notes' not in [x[0] for x in self.get_columns(table)]:
self.query(f"ALTER TABLE {table} ADD COLUMN notes TEXT")
self.query('PRAGMA user_version = 9')
if db_version(self) == 9:
# add phone column to contacts table
self.query('ALTER TABLE contacts ADD COLUMN phone TEXT')
self.query('PRAGMA user_version = 10')
if db_orig != db_version(self):
self.alert(f"Database upgraded to version {db_version(self)}.")
#==================================================
# MODULE METHODS
#==================================================
def _request_file_from_repo(self, path):
resp = self.request('GET', urljoin(self.repo_url, path))
if resp.status_code != 200:
raise framework.FrameworkException(f"Invalid response from module repository ({resp.status_code}).")
return resp
def _write_local_file(self, path, content):
dirpath = os.path.sep.join(path.split(os.path.sep)[:-1])
if not os.path.exists(dirpath):
os.makedirs(dirpath)
with open(path, 'w') as outfile:
outfile.write(content)
def _remove_empty_dirs(self, base_path):
for root, dirs, files in os.walk(base_path, topdown=False):
for rel_path in dirs:
abs_path = os.path.join(root, rel_path)
if os.path.exists(abs_path):
if not os.listdir(abs_path):
os.removedirs(abs_path)
def _fetch_module_index(self):
if self._marketplace:
content = '[]'
self.debug('Fetching index file...')
try:
resp = self._request_file_from_repo('modules.yml')
except Exception as e:
self.error(f"Unable to synchronize module index. ({type(e).__name__})")
#self.print_exception()
return
content = resp.text
path = os.path.join(self.home_path, 'modules.yml')
self._write_local_file(path, content)
else:
self.alert('Marketplace disabled.')
def _update_module_index(self):
self.debug('Updating index file...')
# initialize module index
self._module_index = []
# load module index from local copy
path = os.path.join(self.home_path, 'modules.yml')
if os.path.exists(path):
with open(path, 'r') as infile:
self._module_index = yaml.safe_load(infile)
# add status to index for each module
for module in self._module_index:
status = 'not installed'
if module['path'] in self._loaded_category.get('disabled', []):
status = 'disabled'
elif module['path'] in self._loaded_modules.keys():
status = 'installed'
loaded = self._loaded_modules[module['path']]
if loaded.meta['version'] != module['version']:
status = 'outdated'
module['status'] = status
def _search_module_index(self, s):
keys = ('path', 'name', 'description', 'status')
modules = []
for module in self._module_index:
for key in keys:
if re.search(s, module[key]):
modules.append(module)
break
return modules
def _get_module_from_index(self, path):
for module in self._module_index:
if module['path'] == path:
return module
return None
def _install_module(self, path):
# download supporting data files
downloads = {}
files = self._get_module_from_index(path).get('files', [])
for filename in files:
try:
resp = self._request_file_from_repo('/'.join(['data', filename]))
except:
self.error(f"Supporting file download for {path} failed: ({filename})")
self.error('Module installation aborted.')
raise
abs_path = os.path.join(self.data_path, filename)
downloads[abs_path] = resp.text
# download the module
rel_path = '.'.join([path, 'py'])
try:
resp = self._request_file_from_repo('/'.join(['modules', rel_path]))
except:
self.error(f"Module installation failed: {path}")
raise
abs_path = os.path.join(self.mod_path, rel_path)
downloads[abs_path] = resp.text
# install the module
for abs_path, content in downloads.items():
self._write_local_file(abs_path, content)
self.output(f"Module installed: {path}")
def _remove_module(self, path):
# remove the module
rel_path = '.'.join([path, 'py'])
abs_path = os.path.join(self.mod_path, rel_path)
os.remove(abs_path)
# remove supporting data files
files = self._get_module_from_index(path).get('files', [])
for filename in files:
abs_path = os.path.join(self.data_path, filename)
if os.path.exists(abs_path):
os.remove(abs_path)
self.output(f"Module removed: {path}")
def _load_modules(self):
self._loaded_category = {}
self._loaded_modules = framework.Framework._loaded_modules = {}
# crawl the module directory and build the module tree
for dirpath, dirnames, filenames in os.walk(self.mod_path, followlinks=True):
# remove hidden files and directories
filenames = [f for f in filenames if not f[0] == '.']
dirnames[:] = [d for d in dirnames if not d[0] == '.']
if len(filenames) > 0:
for filename in [f for f in filenames if f.endswith('.py')]:
self._load_module(dirpath, filename)
# cleanup module directory
self._remove_empty_dirs(self.mod_path)
# update module index
self._update_module_index()
def _load_module(self, dirpath, filename):
mod_name = filename.split('.')[0]
mod_category = re.search('/modules/([^/]*)', dirpath).group(1)
mod_dispname = '/'.join(re.split('/modules/', dirpath)[-1].split('/') + [mod_name])
mod_loadname = mod_dispname.replace('/', '_')
mod_loadpath = os.path.join(dirpath, filename)
mod_file = open(mod_loadpath)
try:
# import the module into memory
mod = imp.load_source(mod_loadname, mod_loadpath, mod_file)
__import__(mod_loadname)
# add the module to the framework's loaded modules
self._loaded_modules[mod_dispname] = sys.modules[mod_loadname].Module(mod_dispname)
self._categorize_module(mod_category, mod_dispname)
# return indication of success to support module reload
return True
except ImportError as e:
# notify the user of missing dependencies
self.error(f"Module '{mod_dispname}' disabled. Dependency required: '{self.to_unicode_str(e)[16:]}'")
except:
# notify the user of errors
self.print_exception()
self.error(f"Module '{mod_dispname}' disabled.")
# remove the module from the framework's loaded modules
self._loaded_modules.pop(mod_dispname, None)
self._categorize_module('disabled', mod_dispname)
def _categorize_module(self, category, module):
if not category in self._loaded_category:
self._loaded_category[category] = []
self._loaded_category[category].append(module)
#==================================================
# COMMAND METHODS
#==================================================
def do_index(self, params):
'''Creates a module index (dev only)'''
mod_path, file_name = self._parse_params(params)
if not mod_path:
self.help_index()
return
self.output('Building index markup...')
yaml_objs = []
modules = [m for m in self._loaded_modules.items() if mod_path in m[0] or mod_path == 'all']
for path, module in sorted(modules, key=lambda k: k[0]):
yaml_obj = {}
# not in meta
yaml_obj['path'] = path
yaml_obj['last_updated'] = datetime.strftime(datetime.now(), '%Y-%m-%d')
# meta required
yaml_obj['author'] = module.meta.get('author')
yaml_obj['name'] = module.meta.get('name')
yaml_obj['description'] = module.meta.get('description')
yaml_obj['version'] = module.meta.get('version', '1.0')
# meta optional
#yaml_obj['comments'] = module.meta.get('comments', [])
yaml_obj['dependencies'] = module.meta.get('dependencies', [])
yaml_obj['files'] = module.meta.get('files', [])
#yaml_obj['options'] = module.meta.get('options', [])
#yaml_obj['query'] = module.meta.get('query', '')
yaml_obj['required_keys'] = module.meta.get('required_keys', [])
yaml_objs.append(yaml_obj)
if yaml_objs:
markup = yaml.safe_dump(yaml_objs)
print(markup)
# write to file if index name provided
if file_name:
with open(file_name, 'w') as outfile:
outfile.write(markup)
self.output('Module index created.')
else:
self.output('No modules found.')
def do_marketplace(self, params):
'''Interfaces with the module marketplace'''
if not self._marketplace:
self.alert('Marketplace disabled.')
return
if not params:
self.help_marketplace()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('marketplace'):
return getattr(self, '_do_marketplace_'+arg)(params)
else:
self.help_marketplace()
def _do_marketplace_refresh(self, params):
'''Refreshes the marketplace index'''
self._fetch_module_index()
self._update_module_index()
self.output('Marketplace index refreshed.')
def _do_marketplace_search(self, params):
'''Searches marketplace modules'''
modules = [m for m in self._module_index]
if params:
self.output(f"Searching module index for '{params}'...")
modules = self._search_module_index(params)
if modules:
rows = []
for module in sorted(modules, key=lambda m: m['path']):
row = []
for key in ('path', 'version', 'status', 'last_updated'):
row.append(module[key])
row.append('*' if module['dependencies'] else '')
row.append('*' if module['required_keys'] else '')
rows.append(row)
header = ('Path', 'Version', 'Status', 'Updated', 'D', 'K')
self.table(rows, header=header)
print(f"{self.spacer}D = Has dependencies. See info for details.")
print(f"{self.spacer}K = Requires keys. See info for details.{os.linesep}")
else:
self.error('No modules found.')
self._help_marketplace_search()
def _do_marketplace_info(self, params):
'''Shows detailed information about available modules'''
if not params:
self._help_marketplace_info()
return
modules = [m for m in self._module_index if params in m['path'] or params == 'all']
if modules:
for module in modules:
rows = []
for key in ('path', 'name', 'author', 'version', 'last_updated', 'description', 'required_keys', 'dependencies', 'files', 'status'):
row = (key, module[key])
rows.append(row)
self.table(rows)
else:
self.error('Invalid module path.')
def _do_marketplace_install(self, params):
'''Installs modules from the marketplace'''
if not params:
self._help_marketplace_install()
return
modules = [m for m in self._module_index if params in m['path'] or params == 'all']
if modules:
for module in modules:
self._install_module(module['path'])
self._do_modules_reload('')
else:
self.error('Invalid module path.')
def _do_marketplace_remove(self, params):
'''Removes marketplace modules from the framework'''
if not params:
self._help_marketplace_remove()
return
modules = [m for m in self._module_index if m['status'] in ('installed', 'disabled') and (params in m['path'] or params == 'all')]
if modules:
for module in modules:
self._remove_module(module['path'])
self._do_modules_reload('')
else:
self.error('Invalid module path.')
def do_workspaces(self, params):
'''Manages workspaces'''
if not params:
self.help_workspaces()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('workspaces'):
return getattr(self, '_do_workspaces_'+arg)(params)
else:
self.help_workspaces()
def _do_workspaces_list(self, params):
'''Lists existing workspaces'''
rows = []
for workspace in self._get_workspaces():
db_path = os.path.join(self.spaces_path, workspace, 'data.db')
modified = datetime.fromtimestamp(os.path.getmtime(db_path)).strftime('%Y-%m-%d %H:%M:%S')
rows.append((workspace, modified))
rows.sort(key=lambda x: x[0])
self.table(rows, header=['Workspaces', 'Modified'])
def _do_workspaces_create(self, params):
'''Creates a new workspace'''
if not params:
self._help_workspaces_create()
return
if not self._init_workspace(params):
self.output(f"Unable to create '{params}' workspace.")
def _do_workspaces_load(self, params):
'''Loads an existing workspace'''
if not params:
self._help_workspaces_load()
return
if params in self._get_workspaces():
if not self._init_workspace(params):
self.output(f"Unable to initialize '{params}' workspace.")
else:
self.output('Invalid workspace name.')
def _do_workspaces_remove(self, params):
'''Removes an existing workspace'''
if not params:
self._help_workspaces_remove()
return
if not self.remove_workspace(params):
self.output(f"Unable to remove '{params}' workspace.")
def do_snapshots(self, params):
'''Manages workspace snapshots'''
if not params:
self.help_snapshots()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('snapshots'):
return getattr(self, '_do_snapshots_'+arg)(params)
else:
self.help_snapshots()
def _do_snapshots_list(self, params):
'''Lists existing database snapshots'''
snapshots = self._get_snapshots()
if snapshots:
self.table([[x] for x in snapshots], header=['Snapshots'])
else:
self.output('This workspace has no snapshots.')
def _do_snapshots_take(self, params):
'''Takes a snapshot of the current database'''
ts = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
snapshot = f"snapshot_{ts}.db"
src = os.path.join(self.workspace, 'data.db')
dst = os.path.join(self.workspace, snapshot)
shutil.copyfile(src, dst)
self.output(f"Snapshot created: {snapshot}")
def _do_snapshots_load(self, params):
'''Loads an existing database snapshot'''
if not params:
self._help_snapshots_load()
return
if params in self._get_snapshots():
src = os.path.join(self.workspace, params)
dst = os.path.join(self.workspace, 'data.db')
shutil.copyfile(src, dst)
self.output(f"Snapshot loaded: {params}")
else:
self.error(f"No snapshot named '{params}'.")
def _do_snapshots_remove(self, params):
'''Removes an existing snapshot'''
if not params:
self._help_snapshots_remove()
return
if params in self._get_snapshots():
os.remove(os.path.join(self.workspace, params))
self.output(f"Snapshot removed: {params}")
else:
self.error(f"No snapshot named '{params}'.")
def _do_modules_load(self, params):
'''Loads a module'''
# validate global options before loading the module
try:
self._validate_options()
except framework.FrameworkException as e:
self.error(e)
return
if not params:
self._help_modules_load()
return
# finds any modules that contain params
modules = self._match_modules(params)
# notify the user if none or multiple modules are found
if len(modules) != 1:
if not modules:
self.error('Invalid module name.')
else:
self.output(f"Multiple modules match '{params}'.")
self._list_modules(modules)
return
# load the module
mod_dispname = modules[0]
# loop to support reload logic
while True:
y = self._loaded_modules[mod_dispname]
# send analytics information
mod_loadpath = os.path.abspath(sys.modules[y.__module__].__file__)
self._send_analytics(mod_dispname)
# return the loaded module if not in console mode
if self._mode != Mode.CONSOLE:
return y
# begin a command loop
y.prompt = self._prompt_template.format(self.prompt[:-3], mod_dispname.split('/')[-1])
try:
y.cmdloop()
except KeyboardInterrupt:
print('')
if y._exit == 1:
return True
if y._reload == 1:
self.output('Reloading module...')
# reload the module in memory
is_loaded = self._load_module(os.path.dirname(mod_loadpath), os.path.basename(mod_loadpath))
if is_loaded:
# reload the module in the framework
continue
# shuffle category counts?
break
def _do_modules_reload(self, params):
'''Reloads installed modules'''
self.output('Reloading modules...')
self._load_modules()
#==================================================
# HELP METHODS
#==================================================
def help_index(self):
print(getattr(self, 'do_index').__doc__)
print(f"{os.linesep}Usage: index {os.linesep}")
def help_marketplace(self):
print(getattr(self, 'do_marketplace').__doc__)
print(f"{os.linesep}Usage: marketplace <{'|'.join(self._parse_subcommands('marketplace'))}> [...]{os.linesep}")
def _help_marketplace_search(self):
print(getattr(self, '_do_marketplace_search').__doc__)
print(f"{os.linesep}Usage: marketplace search []{os.linesep}")
def _help_marketplace_info(self):
print(getattr(self, '_do_marketplace_info').__doc__)
print(f"{os.linesep}Usage: marketplace info <||all>{os.linesep}")
def _help_marketplace_install(self):
print(getattr(self, '_do_marketplace_install').__doc__)
print(f"{os.linesep}Usage: marketplace install <||all>{os.linesep}")
def _help_marketplace_remove(self):
print(getattr(self, '_do_marketplace_remove').__doc__)
print(f"{os.linesep}Usage: marketplace remove <||all>{os.linesep}")
def help_workspaces(self):
print(getattr(self, 'do_workspaces').__doc__)
print(f"{os.linesep}Usage: workspaces <{'|'.join(self._parse_subcommands('workspaces'))}> [...]{os.linesep}")
def _help_workspaces_create(self):
print(getattr(self, '_do_workspaces_create').__doc__)
print(f"{os.linesep}Usage: workspace create {os.linesep}")
def _help_workspaces_load(self):
print(getattr(self, '_do_workspaces_load').__doc__)
print(f"{os.linesep}Usage: workspace load {os.linesep}")
def _help_workspaces_remove(self):
print(getattr(self, '_do_workspaces_remove').__doc__)
print(f"{os.linesep}Usage: workspace remove {os.linesep}")
def help_snapshots(self):
print(getattr(self, 'do_snapshots').__doc__)
print(f"{os.linesep}Usage: snapshots <{'|'.join(self._parse_subcommands('snapshots'))}> [...]{os.linesep}")
def _help_snapshots_load(self):
print(getattr(self, '_do_snapshots_load').__doc__)
print(f"{os.linesep}Usage: snapshots load {os.linesep}")
def _help_snapshots_remove(self):
print(getattr(self, '_do_snapshots_remove').__doc__)
print(f"{os.linesep}Usage: snapshots remove {os.linesep}")
#==================================================
# COMPLETE METHODS
#==================================================
def complete_index(self, text, line, *ignored):
if len(line.split(' ')) == 2:
return [x for x in self._loaded_modules if x.startswith(text)]
return []
def complete_marketplace(self, text, line, *ignored):
arg, params = self._parse_params(line.split(' ', 1)[1])
subs = self._parse_subcommands('marketplace')
if arg in subs:
return getattr(self, '_complete_marketplace_'+arg)(text, params)
return [sub for sub in subs if sub.startswith(text)]
def _complete_marketplace_refresh(self, text, *ignored):
return []
_complete_marketplace_search = _complete_marketplace_refresh
def _complete_marketplace_info(self, text, *ignored):
return [x['path'] for x in self._module_index if x['path'].startswith(text)]
_complete_marketplace_install = _complete_marketplace_info
def _complete_marketplace_remove(self, text, *ignored):
return [x['path'] for x in self._module_index if x['status'] == 'installed' and x['path'].startswith(text)]
def complete_workspaces(self, text, line, *ignored):
arg, params = self._parse_params(line.split(' ', 1)[1])
subs = self._parse_subcommands('workspaces')
if arg in subs:
return getattr(self, '_complete_workspaces_'+arg)(text, params)
return [sub for sub in subs if sub.startswith(text)]
def _complete_workspaces_list(self, text, *ignored):
return []
_complete_workspaces_create = _complete_workspaces_list
def _complete_workspaces_load(self, text, *ignored):
return [x for x in self._get_workspaces() if x.startswith(text)]
_complete_workspaces_remove = _complete_workspaces_load
def complete_snapshots(self, text, line, *ignored):
arg, params = self._parse_params(line.split(' ', 1)[1])
subs = self._parse_subcommands('snapshots')
if arg in subs:
return getattr(self, '_complete_snapshots_'+arg)(text, params)
return [sub for sub in subs if sub.startswith(text)]
def _complete_snapshots_list(self, text, *ignored):
return []
_complete_snapshots_take = _complete_snapshots_list
def _complete_snapshots_load(self, text, *ignored):
return [x for x in self._get_snapshots() if x.startswith(text)]
_complete_snapshots_remove = _complete_snapshots_load
def _complete_modules_reload(self, text, *ignored):
return []
#=================================================
# SUPPORT CLASSES
#=================================================
class Mode(object):
'''Contains constants that represent the state of the interpreter.'''
CONSOLE = 0
CLI = 1
WEB = 2
JOB = 3
def __init__(self):
raise NotImplementedError('This class should never be instantiated.')
recon-ng-5.1.2/recon/core/constants.py 0000664 0000000 0000000 00000003100 14111332555 0017645 0 ustar 00root root 0000000 0000000 BANNER = r'''
_/_/_/ _/_/_/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ _/_/_/
_/ _/ _/ _/ _/ _/ _/_/ _/ _/_/ _/ _/
_/_/_/ _/_/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/_/_/
_/ _/ _/ _/ _/ _/ _/ _/_/ _/ _/_/ _/ _/
_/ _/ _/_/_/_/ _/_/_/ _/_/_/ _/ _/ _/ _/ _/_/_/
/\
/ \\ /\
Sponsored by... /\ /\/ \\V \/\
/ \\/ // \\\\\ \\ \/\
// // BLACK HILLS \/ \\
www.blackhillsinfosec.com
____ ____ ____ ____ _____ _ ____ ____ ____
|____] | ___/ |____| | | | |____ |____ |
| | \_ | | |____ | | ____| |____ |____
www.practisec.com
'''
BANNER_SMALL = r'''
RECON-NG
Sponsored by...
- BLACK HILLS INFORMATION SECURITY at www.blackhillsinfosec.com
- PRACTISEC at www.practisec.com
'''
BANNER_WEB = '''\
*************************************************************************
* Welcome to Recon-web, the analytics and reporting engine for Recon-ng!
* This is a web-based user interface. Open the URL below in your browser to begin.
* Recon-web includes the Recon-API, which can be accessed via the `/api/` URL.
*************************************************************************\
'''
recon-ng-5.1.2/recon/core/framework.py 0000664 0000000 0000000 00000160014 14111332555 0017636 0 ustar 00root root 0000000 0000000 from contextlib import closing
import cmd
import codecs
import inspect
import json
import os
import random
import re
import requests
import socket
import sqlite3
import string
import subprocess
import sys
import traceback
#=================================================
# SUPPORT CLASSES
#=================================================
class FrameworkException(Exception):
def __init__(self, message):
Exception.__init__(self, message)
class Colors(object):
N = '\033[m' # native
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
class Options(dict):
def __init__(self, *args, **kwargs):
self.required = {}
self.description = {}
super(Options, self).__init__(*args, **kwargs)
def __getitem__(self, name):
name = self.__keytransform__(name)
return super(Options, self).__getitem__(name)
def __setitem__(self, name, value):
name = self.__keytransform__(name)
value = self._autoconvert(value)
super(Options, self).__setitem__(name, value)
def __delitem__(self, name):
name = self.__keytransform__(name)
super(Options, self).__delitem__(name)
if name in self.required:
del self.required[name]
if name in self.description:
del self.description[name]
def __keytransform__(self, key):
return key.upper()
def _boolify(self, value):
# designed to throw an exception if value is not a string representation of a boolean
return {'true':True, 'false':False}[value.lower()]
def _autoconvert(self, value):
if value in (None, True, False):
return value
elif (isinstance(value, str)) and value.lower() in ('none', "''", '""'):
return None
orig = value
for fn in (self._boolify, int, float):
try:
value = fn(value)
break
except ValueError: pass
except KeyError: pass
except AttributeError: pass
if type(value) is int and '.' in str(orig):
return float(orig)
return value
def init_option(self, name, value=None, required=False, description=''):
name = self.__keytransform__(name)
self[name] = value
self.required[name] = required
self.description[name] = description
def serialize(self):
options = []
for key in self:
option = {}
option['name'] = key
option['value'] = self[key]
option['required'] = self.required[key]
option['description'] = self.description[key]
options.append(option)
return options
#=================================================
# FRAMEWORK CLASS
#=================================================
class Framework(cmd.Cmd):
prompt = '>>>'
# mode flags
_script = 0
_load = 0
_mode = 0
# framework variables
_global_options = Options()
_loaded_modules = {}
app_path = ''
data_path = ''
core_path = ''
home_path = ''
mod_path = ''
spaces_path = ''
workspace = ''
_record = None
_spool = None
_summary_counts = {}
def __init__(self, params):
cmd.Cmd.__init__(self)
self._modulename = params
self.ruler = '-'
self.spacer = ' '
self.time_format = '%Y-%m-%d %H:%M:%S'
self.nohelp = f"{Colors.R}[!] No help on %s{Colors.N}"
self.do_help.__func__.__doc__ = '''Displays this menu'''
self.doc_header = 'Commands (type [help|?] ):'
self._exit = 0
#==================================================
# CMD OVERRIDE METHODS
#==================================================
def default(self, line):
self.error(f"Invalid command: {line}")
def emptyline(self):
# disables running of last command when no command is given
# return flag to tell interpreter to continue
return 0
def precmd(self, line):
if Framework._load:
print('\r', end='')
if Framework._script:
print(f"{line}")
if Framework._record:
recorder = codecs.open(Framework._record, 'ab', encoding='utf-8')
recorder.write(f"{line}{os.linesep}")
recorder.flush()
recorder.close()
if Framework._spool:
Framework._spool.write(f"{self.prompt}{line}{os.linesep}")
Framework._spool.flush()
return line
def onecmd(self, line):
cmd, arg, line = self.parseline(line)
if not line:
return self.emptyline()
if line == 'EOF':
# reset stdin for raw_input
sys.stdin = sys.__stdin__
Framework._script = 0
Framework._load = 0
return
if cmd is None:
return self.default(line)
self.lastcmd = line
if cmd == '':
return self.default(line)
else:
try:
func = getattr(self, 'do_' + cmd)
except AttributeError:
return self.default(line)
try:
return func(arg)
except Exception:
self.print_exception()
# make help menu more attractive
def print_topics(self, header, cmds, cmdlen, maxcol):
if cmds:
self.stdout.write(f"{header}{os.linesep}")
if self.ruler:
self.stdout.write(f"{self.ruler * len(header)}{os.linesep}")
for cmd in cmds:
self.stdout.write(f"{cmd.ljust(15)} {getattr(self, 'do_' + cmd).__doc__}{os.linesep}")
self.stdout.write(os.linesep)
#==================================================
# SUPPORT METHODS
#==================================================
def to_unicode_str(self, obj, encoding='utf-8'):
# converts non-stringish types to unicode
if type(obj) not in (str, bytes):
obj = str(obj)
obj = self.to_unicode(obj, encoding)
return obj
def to_unicode(self, obj, encoding='utf-8'):
# converts bytes to unicode
if isinstance(obj, bytes):
obj = obj.decode(encoding)
return obj
def is_hash(self, hashstr):
hashdict = [
{'pattern': r'^[a-fA-F0-9]{32}$', 'type': 'MD5'},
{'pattern': r'^[a-fA-F0-9]{16}$', 'type': 'MySQL'},
{'pattern': r'^\*[a-fA-F0-9]{40}$', 'type': 'MySQL5'},
{'pattern': r'^[a-fA-F0-9]{40}$', 'type': 'SHA1'},
{'pattern': r'^[a-fA-F0-9]{56}$', 'type': 'SHA224'},
{'pattern': r'^[a-fA-F0-9]{64}$', 'type': 'SHA256'},
{'pattern': r'^[a-fA-F0-9]{96}$', 'type': 'SHA384'},
{'pattern': r'^[a-fA-F0-9]{128}$', 'type': 'SHA512'},
{'pattern': r'^\$[PH]{1}\$.{31}$', 'type': 'phpass'},
{'pattern': r'^\$2[ya]?\$.{56}$', 'type': 'bcrypt'},
]
for hashitem in hashdict:
if re.match(hashitem['pattern'], hashstr):
return hashitem['type']
return False
def get_random_str(self, length):
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))
def _is_writeable(self, filename):
try:
fp = open(filename, 'a')
fp.close()
return True
except IOError:
return False
def _parse_rowids(self, rowids):
xploded = []
rowids = [x.strip() for x in rowids.split(',')]
for rowid in rowids:
try:
if '-' in rowid:
start = int(rowid.split('-')[0].strip())
end = int(rowid.split('-')[-1].strip())
xploded += range(start, end+1)
else:
xploded.append(int(rowid))
except ValueError:
continue
return sorted(list(set(xploded)))
#==================================================
# OUTPUT METHODS
#==================================================
def print_exception(self, line=''):
stack_list = [x.strip() for x in traceback.format_exc().strip().splitlines()]
exctype = stack_list[-1].split(':', 1)[0].strip()
message = stack_list[-1].split(':', 1)[-1].strip()
if self._global_options['verbosity'] == 0:
return
elif self._global_options['verbosity'] == 1:
line = ' '.join([x for x in [message, line] if x])
self.error(line)
elif self._global_options['verbosity'] == 2:
print(f"{Colors.R}{'-'*60}")
traceback.print_exc()
print(f"{'-'*60}{Colors.N}")
def error(self, line):
'''Formats and presents errors.'''
if not re.search('[.,;!?]$', line):
line += '.'
line = line[:1].upper() + line[1:]
print(f"{Colors.R}[!] {line}{Colors.N}")
def output(self, line):
'''Formats and presents normal output.'''
print(f"{Colors.B}[*]{Colors.N} {line}")
def alert(self, line):
'''Formats and presents important output.'''
print(f"{Colors.G}[*]{Colors.N} {line}")
def verbose(self, line):
'''Formats and presents output if in verbose mode.'''
if self._global_options['verbosity'] >= 1:
self.output(line)
def debug(self, line):
'''Formats and presents output if in debug mode (very verbose).'''
if self._global_options['verbosity'] >= 2:
self.output(line)
def heading(self, line, level=1):
'''Formats and presents styled header text'''
line = line
print('')
if level == 0:
print(self.ruler*len(line))
print(line.upper())
print(self.ruler*len(line))
if level == 1:
print(f"{self.spacer}{line.title()}")
print(f"{self.spacer}{self.ruler*len(line)}")
def table(self, data, header=[], title=''):
'''Accepts a list of rows and outputs a table.'''
tdata = list(data)
if header:
tdata.insert(0, header)
if len(set([len(x) for x in tdata])) > 1:
raise FrameworkException('Row lengths not consistent.')
lens = []
cols = len(tdata[0])
# create a list of max widths for each column
for i in range(0,cols):
lens.append(len(max([self.to_unicode_str(x[i]) if x[i] != None else '' for x in tdata], key=len)))
# calculate dynamic widths based on the title
title_len = len(title)
tdata_len = sum(lens) + (3*(cols-1))
diff = title_len - tdata_len
if diff > 0:
diff_per = diff / cols
lens = [x+diff_per for x in lens]
diff_mod = diff % cols
for x in range(0, diff_mod):
lens[x] += 1
# build ascii table
if len(tdata) > 0:
separator_str = f"{self.spacer}+-{'%s---'*(cols-1)}%s-+"
separator_sub = tuple(['-'*x for x in lens])
separator = separator_str % separator_sub
data_str = f"{self.spacer}| {'%s | '*(cols-1)}%s |"
# top of ascii table
print('')
print(separator)
# ascii table data
if title:
print(f"{self.spacer}| {title.center(tdata_len)} |")
print(separator)
if header:
rdata = tdata.pop(0)
data_sub = tuple([rdata[i].center(lens[i]) for i in range(0,cols)])
print(data_str % data_sub)
print(separator)
for rdata in tdata:
data_sub = tuple([self.to_unicode_str(rdata[i]).ljust(lens[i]) if rdata[i] != None else ''.ljust(lens[i]) for i in range(0,cols)])
print(data_str % data_sub)
# bottom of ascii table
print(separator)
print('')
#==================================================
# DATABASE METHODS
#==================================================
def query(self, *args, **kwargs):
path = os.path.join(self.workspace, 'data.db')
return self._query(path, *args, **kwargs)
def _query(self, path, query, values=(), include_header=False):
'''Queries the database and returns the results as a list.'''
self.debug(f"DATABASE => {path}")
self.debug(f"QUERY => {query}")
with sqlite3.connect(path) as conn:
with closing(conn.cursor()) as cur:
if values:
self.debug(f"VALUES => {repr(values)}")
cur.execute(query, values)
else:
cur.execute(query)
# a rowcount of -1 typically refers to a select statement
if cur.rowcount == -1:
rows = []
if include_header:
rows.append(tuple([x[0] for x in cur.description]))
rows.extend(cur.fetchall())
results = rows
# a rowcount of 1 == success and 0 == failure
else:
conn.commit()
results = cur.rowcount
return results
def get_columns(self, table):
return [(x[1], x[2]) for x in self.query(f"PRAGMA table_info('{table}')")]
def get_tables(self):
return [x[0] for x in self.query('SELECT name FROM sqlite_master WHERE type=\'table\'') if x[0] not in ['dashboard']]
#==================================================
# INSERT METHODS
#==================================================
def _display(self, data, rowcount):
display = self.alert if rowcount else self.verbose
for key in sorted(data.keys()):
display(f"{key.title()}: {data[key]}")
display(self.ruler*50)
def insert_domains(self, domain=None, notes=None, mute=False):
'''Adds a domain to the database and returns the affected row count.'''
data = dict(
domain = domain,
notes = notes
)
rowcount = self.insert('domains', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_companies(self, company=None, description=None, notes=None, mute=False):
'''Adds a company to the database and returns the affected row count.'''
data = dict(
company = company,
description = description,
notes = notes
)
rowcount = self.insert('companies', data.copy(), ('company',))
if not mute: self._display(data, rowcount)
return rowcount
def insert_netblocks(self, netblock=None, notes=None, mute=False):
'''Adds a netblock to the database and returns the affected row count.'''
data = dict(
netblock = netblock,
notes = notes
)
rowcount = self.insert('netblocks', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_locations(self, latitude=None, longitude=None, street_address=None, notes=None, mute=False):
'''Adds a location to the database and returns the affected row count.'''
data = dict(
latitude = latitude,
longitude = longitude,
street_address = street_address,
notes = notes
)
rowcount = self.insert('locations', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_vulnerabilities(self, host=None, reference=None, example=None, publish_date=None, category=None, status=None, notes=None, mute=False):
'''Adds a vulnerability to the database and returns the affected row count.'''
data = dict(
host = host,
reference = reference,
example = example,
publish_date = publish_date.strftime(self.time_format) if publish_date else None,
category = category,
status = status,
notes = notes
)
rowcount = self.insert('vulnerabilities', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_ports(self, ip_address=None, host=None, port=None, protocol=None, banner=None, notes=None, mute=False):
'''Adds a port to the database and returns the affected row count.'''
data = dict(
ip_address = ip_address,
port = port,
host = host,
protocol = protocol,
banner = banner,
notes = notes
)
rowcount = self.insert('ports', data.copy(), ('ip_address', 'port', 'host'))
if not mute: self._display(data, rowcount)
return rowcount
def insert_hosts(self, host=None, ip_address=None, region=None, country=None, latitude=None, longitude=None, notes=None, mute=False):
'''Adds a host to the database and returns the affected row count.'''
data = dict(
host = host,
ip_address = ip_address,
region = region,
country = country,
latitude = latitude,
longitude = longitude,
notes = notes
)
rowcount = self.insert('hosts', data.copy(), ('host', 'ip_address'))
if not mute: self._display(data, rowcount)
return rowcount
def insert_contacts(self, first_name=None, middle_name=None, last_name=None, email=None, title=None, region=None, country=None, phone=None, notes=None, mute=False):
'''Adds a contact to the database and returns the affected row count.'''
data = dict(
first_name = first_name,
middle_name = middle_name,
last_name = last_name,
title = title,
email = email,
region = region,
country = country,
phone = phone,
notes = notes
)
rowcount = self.insert('contacts', data.copy(), ('first_name', 'middle_name', 'last_name', 'title', 'email', 'phone'))
if not mute: self._display(data, rowcount)
return rowcount
def insert_credentials(self, username=None, password=None, _hash=None, _type=None, leak=None, notes=None, mute=False):
'''Adds a credential to the database and returns the affected row count.'''
# account for hashes provided in the password field
if password and not _hash:
_type = self.is_hash(password)
if _type:
_hash = password
password = None
# handle hashes provided without a type
if _hash and not _type:
_type = self.is_hash(_hash)
# add email usernames to contacts
if username is not None and '@' in username:
self.insert_contacts(first_name=None, last_name=None, title=None, email=username)
data = dict (
username = username,
password = password,
hash = _hash,
type = _type,
leak = leak,
notes = notes
)
rowcount = self.insert('credentials', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_leaks(self, leak_id=None, description=None, source_refs=None, leak_type=None, title=None, import_date=None, leak_date=None, attackers=None, num_entries=None, score=None, num_domains_affected=None, attack_method=None, target_industries=None, password_hash=None, password_type=None, targets=None, media_refs=None, notes=None, mute=False):
'''Adds a leak to the database and returns the affected row count.'''
data = dict(
leak_id = leak_id,
description = description,
source_refs = source_refs,
leak_type = leak_type,
title = title,
import_date = import_date,
leak_date = leak_date,
attackers = attackers,
num_entries = num_entries,
score = score,
num_domains_affected = num_domains_affected,
attack_method = attack_method,
target_industries = target_industries,
password_hash = password_hash,
password_type = password_type,
targets = targets,
media_refs = media_refs,
notes = notes
)
rowcount = self.insert('leaks', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_pushpins(self, source=None, screen_name=None, profile_name=None, profile_url=None, media_url=None, thumb_url=None, message=None, latitude=None, longitude=None, time=None, notes=None, mute=False):
'''Adds a pushpin to the database and returns the affected row count.'''
data = dict(
source = source,
screen_name = screen_name,
profile_name = profile_name,
profile_url = profile_url,
media_url = media_url,
thumb_url = thumb_url,
message = message,
latitude = latitude,
longitude = longitude,
time = time.strftime(self.time_format),
notes = notes
)
rowcount = self.insert('pushpins', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert_profiles(self, username=None, resource=None, url=None, category=None, notes=None, mute=False):
'''Adds a profile to the database and returns the affected row count.'''
data = dict(
username = username,
resource = resource,
url = url,
category = category,
notes = notes
)
rowcount = self.insert('profiles', data.copy(), ('username', 'url'))
if not mute: self._display(data, rowcount)
return rowcount
def insert_repositories(self, name=None, owner=None, description=None, resource=None, category=None, url=None, notes=None, mute=False):
'''Adds a repository to the database and returns the affected row count.'''
data = dict(
name = name,
owner = owner,
description = description,
resource = resource,
category = category,
url = url,
notes = notes
)
rowcount = self.insert('repositories', data.copy(), data.keys())
if not mute: self._display(data, rowcount)
return rowcount
def insert(self, table, data, unique_columns=[]):
'''Inserts items into database and returns the affected row count.
table - the table to insert the data into
data - the information to insert into the database table in the form of a dictionary
where the keys are the column names and the values are the column values
unique_columns - a list of column names that should be used to determine if the
information being inserted is unique'''
# set module to the calling module unless the do_add command was used
data['module'] = 'user_defined' if '_do_db_insert' in [x[3] for x in inspect.stack()] else self._modulename.split('/')[-1]
# sanitize the inputs to remove NoneTypes, blank strings, and zeros
columns = [x for x in data.keys() if data[x]]
# make sure that module is not seen as a unique column
unique_columns = [x for x in unique_columns if x in columns and x != 'module']
# exit if there is nothing left to insert
if not columns:
return 0
# convert any type to unicode (str) for external processing
for column in columns:
data[column] = self.to_unicode_str(data[column])
# build the insert query
columns_str = '`, `'.join(columns)
placeholder_str = ', '.join('?'*len(columns))
unique_columns_str = ' and '.join([f"`{column}`=?" for column in unique_columns])
if not unique_columns:
query = f"INSERT INTO `{table}` (`{columns_str}`) VALUES ({placeholder_str})"
else:
query = f"INSERT INTO `{table}` (`{columns_str}`) SELECT {placeholder_str} WHERE NOT EXISTS(SELECT * FROM `{table}` WHERE {unique_columns_str})"
values = tuple([data[column] for column in columns] + [data[column] for column in unique_columns])
# query the database
rowcount = self.query(query, values)
# increment summary tracker
if table not in self._summary_counts:
self._summary_counts[table] = {'count': 0, 'new': 0}
self._summary_counts[table]['new'] += rowcount
self._summary_counts[table]['count'] += 1
return rowcount
#==================================================
# OPTIONS METHODS
#==================================================
def register_option(self, name, value, required, description):
self.options.init_option(name=name, value=value, required=required, description=description)
# needs to be optimized rather than ran on every register
self._load_config()
def _validate_options(self):
for option in self.options:
# if value type is bool or int, then we know the options is set
if not type(self.options[option]) in [bool, int]:
if self.options.required[option] is True and not self.options[option]:
raise FrameworkException(f"Value required for the '{option}' option.")
return
def _list_options(self, options=None):
'''Lists options'''
if options is None:
options = self.options
if options:
pattern = f"{self.spacer}%s %s %s %s"
key_len = len(max(options, key=len))
if key_len < 4: key_len = 4
val_len = len(max([self.to_unicode_str(options[x]) for x in options], key=len))
if val_len < 13: val_len = 13
print('')
print(pattern % ('Name'.ljust(key_len), 'Current Value'.ljust(val_len), 'Required', 'Description'))
print(pattern % (self.ruler*key_len, (self.ruler*13).ljust(val_len), self.ruler*8, self.ruler*11))
for key in sorted(options):
value = options[key] if options[key] != None else ''
reqd = 'no' if options.required[key] is False else 'yes'
desc = options.description[key]
print(pattern % (key.ljust(key_len), self.to_unicode_str(value).ljust(val_len), self.to_unicode_str(reqd).ljust(8), desc))
print('')
else:
print('')
print(f"{self.spacer}No options available for this module.")
print('')
def _load_config(self):
config_path = os.path.join(self.workspace, 'config.dat')
# don't bother loading if a config file doesn't exist
if os.path.exists(config_path):
# retrieve saved config data
with open(config_path) as config_file:
try:
config_data = json.loads(config_file.read())
except ValueError:
# file is corrupt, nothing to load, exit gracefully
pass
else:
# set option values
for key in self.options:
try:
self.options[key] = config_data[self._modulename][key]
except KeyError:
# invalid key, contnue to load valid keys
continue
def _save_config(self, name, module=None, options=None):
config_path = os.path.join(self.workspace, 'config.dat')
# create a config file if one doesn't exist
open(config_path, 'a').close()
# retrieve saved config data
with open(config_path) as config_file:
try:
config_data = json.loads(config_file.read())
except ValueError:
# file is empty or corrupt, nothing to load
config_data = {}
# override implicit defaults if specified
module = module or self._modulename
options = options or self.options
# create a container for the current module
if module not in config_data:
config_data[module] = {}
# set the new option value in the config
config_data[module][name] = options[name]
# remove the option if it has been unset
if config_data[module][name] is None:
del config_data[module][name]
# remove the module container if it is empty
if not config_data[module]:
del config_data[module]
# write the new config data to the config file
with open(config_path, 'w') as config_file:
json.dump(config_data, config_file, indent=4)
#==================================================
# API KEY METHODS
#==================================================
def get_key(self, name):
rows = self._query_keys('SELECT value FROM keys WHERE name=? AND value NOT NULL', (name,))
if not rows:
return None
return rows[0][0]
def add_key(self, name, value):
result = self._query_keys('UPDATE keys SET value=? WHERE name=?', (value, name))
if not result:
return self._query_keys('INSERT INTO keys VALUES (?, ?)', (name, value))
return result
def remove_key(self, name):
#return self._query_keys('UPDATE keys SET value=NULL WHERE name=?', (name,))
return self._query_keys('DELETE FROM keys WHERE name=?', (name,))
def _query_keys(self, query, values=()):
path = os.path.join(self.home_path, 'keys.db')
result = self._query(path, query, values)
# filter out tokens when not called from the get_key method
if type(result) is list and 'get_key' not in [x[3] for x in inspect.stack()]:
result = [x for x in result if not x[0].endswith('_token')]
return result
def _list_keys(self):
keys = self._query_keys('SELECT * FROM keys')
tdata = []
for key in sorted(keys):
tdata.append(key)
if tdata:
self.table(tdata, header=['Name', 'Value'])
def _get_key_names(self):
return [x[0] for x in self._query_keys('SELECT name FROM keys')]
#==================================================
# REQUEST METHODS
#==================================================
def _print_prepared_request(self, prepared):
self.debug(f"{'='*25} REQUEST {'='*25}")
print(f"url: {prepared.url}")
print(f"method: {prepared.method} {prepared.path_url}")
for k, v in prepared.headers.items():
print(f"header: {k}: {v}")
if prepared.body:
print(f"body: {prepared.body}")
def _print_response(self, resp):
self.debug(f"{'='*25} RESPONSE {'='*25}")
print(f"status: {resp.status_code} {resp.reason}")
for k, v in resp.headers.items():
print(f"header: {k}: {v}")
if resp.content:
print(f"body: {resp.content}")
def request(self, method, url, **kwargs):
# process socket timeout
kwargs['timeout'] = kwargs.get('timeout') or self._global_options['timeout']
# process headers
headers = kwargs.get('headers') or {}
# set the User-Agent header
if 'user-agent' not in [h.lower() for h in headers]:
headers['user-agent'] = self._global_options['user-agent']
# normalize capitalization of the User-Agent header
headers = {k.title(): v for k, v in headers.items()}
kwargs['headers'] = headers
# process proxy
proxy = self._global_options['proxy']
if proxy:
proxies = {
'http': f"http://{proxy}",
'https': f"http://{proxy}",
}
kwargs['proxies'] = proxies
# disable TLS validation and warning
kwargs['verify'] = False
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
# send the request
resp = getattr(requests, method.lower())(url, **kwargs)
if self._global_options['verbosity'] < 2:
return resp
# display request data
self._print_prepared_request(resp.request)
# display response data
self._print_response(resp)
return resp
#==================================================
# MODULES METHODS
#==================================================
def _match_modules(self, params):
# return an exact match
if params in Framework._loaded_modules:
return [params]
# use the provided name as a keyword search and return the results
return [x for x in Framework._loaded_modules if params in x]
def _list_modules(self, modules):
if modules:
key_len = len(max(modules, key=len)) + len(self.spacer)
last_category = ''
for module in sorted(modules):
category = module.split('/')[0]
if category != last_category:
# print header
last_category = category
self.heading(last_category)
# print module
print(f"{self.spacer*2}{module}")
else:
print('')
self.alert('No modules enabled/installed.')
print('')
#==================================================
# SHOW METHODS
#==================================================
def _get_show_names(self):
# Any method beginning with "show_" will be parsed
# and added as a subcommand for the show command.
prefix = 'show_'
return [x[len(prefix):] for x in self.get_names() if x.startswith(prefix)]
#==================================================
# COMMAND METHODS
#==================================================
def _parse_subcommands(self, command):
subcommands = []
for method in dir(self):
if f"_do_{command}_" in method:
subcommands.append(method.split('_')[-1])
return subcommands
def _parse_params(self, params):
params = params.split()
arg = ''
if params:
arg = params.pop(0)
params = ' '.join(params)
return arg, params
def do_exit(self, params):
'''Exits the framework'''
self._exit = 1
return True
def do_back(self, params):
'''Exits the current context'''
return True
def do_options(self, params):
'''Manages the current context options'''
if not params:
self.help_options()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('options'):
return getattr(self, '_do_options_'+arg)(params)
else:
self.help_options()
def _do_options_list(self, params):
'''Shows the current context options'''
self._list_options()
def _do_options_set(self, params):
'''Sets a current context option'''
option, value = self._parse_params(params)
if not (option and value):
self._help_options_set()
return
name = option.upper()
if name in self.options:
self.options[name] = value
print(f"{name} => {value}")
self._save_config(name)
else:
self.error('Invalid option name.')
def _do_options_unset(self, params):
'''Unsets a current context option'''
option, value = self._parse_params(params)
if not option:
self._help_options_unset()
return
name = option.upper()
if name in self.options:
self._do_options_set(' '.join([name, 'None']))
else:
self.error('Invalid option name.')
def do_keys(self, params):
'''Manages third party resource credentials'''
if not params:
self.help_keys()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('keys'):
return getattr(self, '_do_keys_'+arg)(params)
else:
self.help_keys()
def _do_keys_list(self, params):
'''Lists third party resource credentials'''
self._list_keys()
def _do_keys_add(self, params):
'''Adds/Updates a third party resource credential'''
key, value = self._parse_params(params)
if not (key and value):
self._help_keys_add()
return
if self.add_key(key, value):
self.output(f"Key '{key}' added.")
def _do_keys_remove(self, params):
'''Removes a third party resource credential'''
key, value = self._parse_params(params)
if not key:
self._help_keys_remove()
return
if self.get_key(key):
if self.remove_key(key):
self.output(f"Key '{key}' removed.")
else:
self.error('Invalid key name.')
def do_modules(self, params):
'''Interfaces with installed modules'''
if not params:
self.help_modules()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('modules'):
return getattr(self, '_do_modules_'+arg)(params)
else:
self.help_modules()
def _do_modules_search(self, params):
'''Searches installed modules'''
modules = [x for x in Framework._loaded_modules]
if params:
self.output(f"Searching installed modules for '{params}'...")
modules = [x for x in Framework._loaded_modules if re.search(params, x)]
if modules:
self._list_modules(modules)
else:
self.error('No modules found.')
self._help_modules_search()
def _do_modules_load(self, params):
'''Searches installed modules'''
raise NotImplementedError
def do_show(self, params):
'''Shows various framework items'''
if not params:
self.help_show()
return
arg, params = self._parse_params(params)
if arg in self._get_show_names():
getattr(self, 'show_' + arg)()
elif arg in self.get_tables():
self.do_db(f"query SELECT ROWID, * FROM `{arg}`")
else:
self.help_show()
def do_db(self, params):
'''Interfaces with the workspace's database'''
if not params:
self.help_db()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('db'):
return getattr(self, '_do_db_'+arg)(params)
else:
self.help_db()
def _do_db_notes(self, params):
'''Adds notes to rows in the database'''
table, params = self._parse_params(params)
if not table:
self._help_db_notes()
return
if table in self.get_tables():
# get rowid and note from parameters
if params:
arg, note = self._parse_params(params)
rowids = self._parse_rowids(arg)
# get rowid and note from interactive input
else:
try:
# prompt user for data
params = input('rowid(s) (INT): ')
rowids = self._parse_rowids(params)
note = input('note (TXT): ')
except KeyboardInterrupt:
print('')
return
finally:
# ensure proper output for resource scripts
if Framework._script:
print(f"{params}")
# delete record(s) from the database
count = 0
for rowid in rowids:
count += self.query(f"UPDATE `{table}` SET notes=? WHERE ROWID IS ?", (note, rowid))
self.output(f"{count} rows affected.")
else:
self.output('Invalid table name.')
def _do_db_insert(self, params):
'''Inserts a row into the database'''
table, params = self._parse_params(params)
if not table:
self._help_db_insert()
return
if table in self.get_tables():
# validate insert_* method for table
if not hasattr(self, 'insert_' + table):
self.error('Cannot add records to dynamically created tables.')
return
columns = [x for x in self.get_columns(table) if x[0] != 'module']
# sanitize column names to avoid conflicts with builtins in insert_* method
sanitize_column = lambda x: '_'+x if x in ['hash', 'type'] else x
record = {}
# build record from parameters
if params:
# parse params into values by delim
values = params.split('~')
# validate parsed value input
if len(columns) == len(values):
# assign each value to a column
for i in range(0,len(columns)):
record[sanitize_column(columns[i][0])] = values[i]
else:
self.error('Columns and values length mismatch.')
return
# build record from interactive input
else:
for column in columns:
try:
# prompt user for data
value = input(f"{column[0]} ({column[1]}): ")
record[sanitize_column(column[0])] = value
except KeyboardInterrupt:
print('')
return
finally:
# ensure proper output for resource scripts
if Framework._script:
print(f"{value}")
# add record to the database
func = getattr(self, 'insert_' + table)
count = func(mute=True, **record)
self.output(f"{count} rows affected.")
else:
self.output('Invalid table name.')
def _do_db_delete(self, params):
'''Deletes a row from the database'''
table, params = self._parse_params(params)
if not table:
self._help_db_delete()
return
if table in self.get_tables():
# get rowid from parameters
if params:
rowids = self._parse_rowids(params)
# get rowid from interactive input
else:
try:
# prompt user for data
params = input('rowid(s) (INT): ')
rowids = self._parse_rowids(params)
except KeyboardInterrupt:
print('')
return
finally:
# ensure proper output for resource scripts
if Framework._script:
print(f"{params}")
# delete record(s) from the database
count = 0
for rowid in rowids:
count += self.query(f"DELETE FROM `{table}` WHERE ROWID IS ?", (rowid,))
self.output(f"{count} rows affected.")
else:
self.output('Invalid table name.')
def _do_db_query(self, params):
'''Queries the database with custom SQL'''
if not params:
self._help_db_query()
return
try:
results = self.query(params, include_header=True)
except sqlite3.OperationalError as e:
self.error(f"Invalid query. {type(e).__name__} {e}")
return
if type(results) == list:
header = results.pop(0)
if not results:
self.output('No data returned.')
else:
self.table(results, header=header)
self.output(f"{len(results)} rows returned")
else:
self.output(f"{results} rows affected.")
def _do_db_schema(self, params):
'''Displays the database schema'''
tables = self.get_tables()
for table in tables:
columns = self.get_columns(table)
self.table(columns, title=table)
def do_script(self, params):
'''Records and executes command scripts'''
if not params:
self.help_script()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('script'):
return getattr(self, '_do_script_'+arg)(params)
else:
self.help_script()
def _do_script_record(self, params):
'''Records commands in a script file'''
if not Framework._record:
filename, params = self._parse_params(params)
if not filename:
self._help_script_record()
return
if not self._is_writeable(filename):
self.output(f"Cannot record commands to '{filename}'.")
else:
Framework._record = filename
self.output(f"Recording commands to '{Framework._record}'.")
else:
self.output('Recording is already started.')
def _do_script_stop(self, params):
'''Stops command recording'''
if Framework._record:
self.output(f"Recording stopped. Commands saved to '{Framework._record}'.")
Framework._record = None
else:
self.output('Recording is already stopped.')
def _do_script_status(self, params):
'''Provides the status of command recording'''
status = 'started' if Framework._record else 'stopped'
self.output(f"Command recording is {status}.")
def _do_script_execute(self, params):
'''Executes commands from a script file'''
if not params:
self._help_script_execute()
return
if os.path.exists(params):
# works even when called before Recon.start due
# to stdin waiting for the iteractive prompt
sys.stdin = open(params)
Framework._script = 1
else:
self.error(f"Script file '{params}' not found.")
def do_spool(self, params):
'''Spools output to a file'''
if not params:
self.help_spool()
return
arg, params = self._parse_params(params)
if arg in self._parse_subcommands('spool'):
return getattr(self, '_do_spool_'+arg)(params)
else:
self.help_spool()
def _do_spool_start(self, params):
'''Starts output spooling'''
if not Framework._spool:
filename, params = self._parse_params(params)
if not filename:
self._help_spool_start()
return
if not self._is_writeable(filename):
self.output(f"Cannot spool output to '{filename}'.")
else:
Framework._spool = codecs.open(filename, 'ab', encoding='utf-8')
self.output(f"Spooling output to '{Framework._spool.name}'.")
else:
self.output('Spooling is already started.')
def _do_spool_stop(self, params):
'''Stops output spooling'''
if Framework._spool:
self.output(f"Spooling stopped. Output saved to '{Framework._spool.name}'.")
Framework._spool = None
else:
self.output('Spooling is already stopped.')
def _do_spool_status(self, params):
'''Provides the status of output spooling'''
status = 'started' if Framework._spool else 'stopped'
self.output(f"Output spooling is {status}.")
def do_shell(self, params):
'''Executes shell commands'''
if not params:
self.help_shell()
return
proc = subprocess.Popen(params, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
self.output(f"Command: {params}")
stdout = proc.stdout.read()
stderr = proc.stderr.read()
if stdout:print(f"{Colors.O}{self.to_unicode(stdout)}{Colors.N}", end='')
if stderr:print(f"{Colors.R}{self.to_unicode(stderr)}{Colors.N}", end='')
def do_dashboard(self, params):
'''Displays a summary of activity'''
rows = self.query('SELECT * FROM dashboard ORDER BY 1')
if rows:
# display activity table
tdata = []
for row in rows:
tdata.append(row)
self.table(tdata, header=['Module', 'Runs'], title='Activity Summary')
# display summary results table
tables = self.get_tables()
tdata = []
for table in tables:
count = self.query(f"SELECT COUNT(*) FROM `{table}`")[0][0]
tdata.append([table.title(), count])
self.table(tdata, header=['Category', 'Quantity'], title='Results Summary')
else:
self.output('This workspace has no record of activity.')
def do_pdb(self, params):
'''Starts a Python Debugger session (dev only)'''
import pdb
pdb.set_trace()
#==================================================
# HELP METHODS
#==================================================
def help_options(self):
print(getattr(self, 'do_options').__doc__)
print(f"{os.linesep}Usage: options <{'|'.join(self._parse_subcommands('options'))}> [...]{os.linesep}")
def _help_options_set(self):
print(getattr(self, '_do_options_set').__doc__)
print(f"{os.linesep}Usage: options set