Showing preview only (227K chars total). Download the full file or copy to clipboard to get everything.
Repository: kpcyrd/authoscope
Branch: main
Commit: 1317aece6faa
Files: 65
Total size: 212.0 KB
Directory structure:
gitextract_ctmbbqt6/
├── .dockerignore
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── rust.yml
├── .gitignore
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
├── ci/
│ └── smtp/
│ ├── Dockerfile
│ └── smtpd.conf
├── docs/
│ ├── Makefile
│ ├── authoscope.1
│ ├── conf.py
│ ├── config.rst
│ ├── index.rst
│ ├── install.rst
│ ├── make.bat
│ ├── man.rst
│ ├── scripting.rst
│ ├── test.sh
│ └── usage.rst
├── examples/
│ ├── README.md
│ └── load-creds.rs
├── scripts/
│ ├── basic_auth.lua
│ ├── benchmark.lua
│ ├── binary.lua
│ ├── cookies.lua
│ ├── error.lua
│ ├── execve.lua
│ ├── false.lua
│ ├── http.lua
│ ├── json.lua
│ ├── ldap.lua
│ ├── ldap_search.lua
│ ├── mysql-connect.lua
│ ├── mysql-query.lua
│ ├── post.lua
│ ├── print.lua
│ ├── random-errors.lua
│ ├── random.lua
│ ├── sleep.lua
│ ├── smtp.lua
│ ├── str-find.lua
│ └── true.lua
└── src/
├── args.rs
├── bin/
│ └── badtouch.rs
├── config.rs
├── ctx.rs
├── db/
│ ├── mod.rs
│ └── mysql.rs
├── errors.rs
├── fsck.rs
├── html.rs
├── http.rs
├── json.rs
├── keyboard.rs
├── lib.rs
├── main.rs
├── pb.rs
├── runtime.rs
├── scheduler.rs
├── sockets.rs
├── structs.rs
├── ulimit.rs
└── utils.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
target
Dockerfile
.dockerignore
.git
.gitignore
*.sw[op]
================================================
FILE: .github/FUNDING.yml
================================================
github: [kpcyrd]
================================================
FILE: .github/workflows/rust.yml
================================================
name: Rust
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
steps:
- uses: actions/checkout@v2
- name: Build
run: cargo build --verbose --all-targets
- name: Run tests
run: cargo test --verbose
- name: Run integration test (smtp)
if: matrix.os == 'ubuntu-latest'
run: |
docker build -t authoscope-smtpd ci/smtp/
docker run --name authoscope-smtpd -d --rm -p 127.0.0.1:25:25 authoscope-smtpd
echo root@example.com:foo > /tmp/authoscope-smtp-input.txt
target/debug/authoscope -o authoscope-smtp-output.txt combo /tmp/authoscope-smtp-input.txt scripts/smtp.lua
docker stop authoscope-smtpd
- name: Verify integration test (smtp)
if: matrix.os == 'ubuntu-latest'
run: grep -q root@example.com authoscope-smtp-output.txt
================================================
FILE: .gitignore
================================================
/target/
**/*.rs.bk
*.txt
*.sw[op]
/docs/_build/
================================================
FILE: Cargo.toml
================================================
[package]
name = "authoscope"
version = "0.8.1"
description = "Scriptable network authentication cracker"
authors = ["kpcyrd <git@rxv.cc>"]
license = "GPL-3.0"
repository = "https://github.com/kpcyrd/authoscope"
categories = ["command-line-utilities"]
default-run = "authoscope"
readme = "README.md"
edition = "2018"
[dependencies]
#hlua = "0.4"
#hlua-badtouch = { path="../hlua/hlua" }
hlua-badtouch = "0.4.2"
log = "0.4"
env_logger = "0.9"
pbr = "1.0"
threadpool = "1.7"
colored = "2"
humantime = "2"
structopt = "0.3"
anyhow = "1"
time = "0.3"
atty = "0.2"
rand = "0.8"
getch = "0.3"
toml = "0.5"
nix = "0.23"
serde = { version="1.0", features=["derive"] }
serde_json = "1.0"
bufstream = "0.1.3"
regex = "1.0.1"
md-5 = "0.10"
sha-1 = "0.10"
sha2 = "0.10"
sha3 = "0.10"
digest = "0.10"
hmac = "0.12"
base64 = "0.13"
bcrypt = "0.12"
reqwest = { version="0.11", features=["blocking", "json"] }
mysql = "22"
ldap3 = "0.10"
kuchiki = "0.8"
dirs = "4"
num-format = "0.4.0"
[target."cfg(unix)".dependencies]
termios = "0.3"
[target.'cfg(target_os="linux")'.dependencies]
rlimit = "0.7"
================================================
FILE: Dockerfile
================================================
FROM rust:alpine3.15
ENV RUSTFLAGS="-C target-feature=-crt-static"
RUN apk add musl-dev openssl-dev
WORKDIR /app
COPY . .
RUN cargo build --release --locked --verbose
RUN strip target/release/authoscope
FROM alpine:3.15
RUN apk add --no-cache libgcc openssl
COPY --from=0 /app/target/release/authoscope /usr/local/bin/authoscope
ENTRYPOINT ["authoscope"]
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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 <http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# authoscope [![Crates.io][crates-img]][crates]
[crates-img]: https://img.shields.io/crates/v/authoscope.svg
[crates]: https://crates.io/crates/authoscope
authoscope is a scriptable network authentication cracker. While the space for
common service bruteforce is already [very][ncrack] [well][hydra]
[saturated][medusa], you may still end up writing your own python scripts when
testing credentials for web applications.
[ncrack]: https://nmap.org/ncrack/
[hydra]: https://github.com/vanhauser-thc/thc-hydra
[medusa]: https://github.com/jmk-foofus/medusa
The scope of authoscope is specifically cracking custom services. This is done
by writing scripts that are loaded into a lua runtime. Those scripts represent
a single service and provide a `verify(user, password)` function that returns
either true or false. Concurrency, progress indication and reporting is
magically provided by the authoscope runtime.
[](https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ)
## Installation
<a href="https://repology.org/project/authoscope/versions"><img align="right" src="https://repology.org/badge/vertical-allrepos/authoscope.svg" alt="Packaging status"></a>
If you are on an Arch Linux based system, use
pacman -S authoscope
If you are on Mac OSX, use
brew install authoscope
To build from source, make sure you have [rust](https://rustup.rs/) and `libssl-dev` installed and run
cargo install
Verify your setup is complete with
authoscope --help
### Debian
1. Install essential build tools
```
sudo apt-get update && sudo apt-get dist-upgrade
sudo apt-get install build-essential libssl-dev pkg-config
```
2. Install rust
```
curl -sf -L https://static.rust-lang.org/rustup.sh | sh
source $HOME/.cargo/env
```
3. Install authoscope
```
cd /path/to/authoscope
cargo install
```
## Scripting
A simple script could look like this:
```lua
descr = "example.com"
function verify(user, password)
session = http_mksession()
-- get csrf token
req = http_request(session, 'GET', 'https://example.com/login', {})
resp = http_send(req)
if last_err() then return end
-- parse token from html
html = resp['text']
csrf = html_select(html, 'input[name="csrf"]')
token = csrf["attrs"]["value"]
-- send login
req = http_request(session, 'POST', 'https://example.com/login', {
form={
user=user,
password=password,
csrf=token
}
})
resp = http_send(req)
if last_err() then return end
-- search response for successful login
html = resp['text']
return html:find('Login successful') != nil
end
```
Please see the reference and [examples](/scripts) for all available functions.
Keep in mind that you can use `print(x)` and `authoscope oneshot` to debug your
script.
## Reference
- [base64_decode](#base64_decode)
- [base64_encode](#base64_encode)
- [clear_err](#clear_err)
- [execve](#execve)
- [hex](#hex)
- [hmac_md5](#hmac_md5)
- [hmac_sha1](#hmac_sha1)
- [hmac_sha2_256](#hmac_sha2_256)
- [hmac_sha2_512](#hmac_sha2_512)
- [hmac_sha3_256](#hmac_sha3_256)
- [hmac_sha3_512](#hmac_sha3_512)
- [html_select](#html_select)
- [html_select_list](#html_select_list)
- [http_basic_auth](#http_basic_auth)
- [http_mksession](#http_mksession)
- [http_request](#http_request)
- [http_send](#http_send)
- [json_decode](#json_decode)
- [json_encode](#json_encode)
- [last_err](#last_err)
- [ldap_bind](#ldap_bind)
- [ldap_escape](#ldap_escape)
- [ldap_search_bind](#ldap_search_bind)
- [md5](#md5)
- [mysql_connect](#mysql_connect)
- [mysql_query](#mysql_query)
- [print](#print)
- [rand](#rand)
- [randombytes](#randombytes)
- [sha1](#sha1)
- [sha2_256](#sha2_256)
- [sha2_512](#sha2_512)
- [sha3_256](#sha3_256)
- [sha3_512](#sha3_512)
- [sleep](#sleep)
- [sock_connect](#sock_connect)
- [sock_send](#sock_send)
- [sock_recv](#sock_recv)
- [sock_sendline](#sock_sendline)
- [sock_recvline](#sock_recvline)
- [sock_recvall](#sock_recvall)
- [sock_recvline_contains](#sock_recvline_contains)
- [sock_recvline_regex](#sock_recvline_regex)
- [sock_recvn](#sock_recvn)
- [sock_recvuntil](#sock_recvuntil)
- [sock_sendafter](#sock_sendafter)
- [sock_newline](#sock_newline)
- [Examples](/scripts)
- [Configuration](#configuration)
- [Wrapping python scripts](#wrapping-python-scripts)
### base64_decode
Decode a base64 string.
```lua
base64_decode("ww==")
```
### base64_encode
Encode a binary array with base64.
```lua
base64_encode("\x00\xff")
```
### clear_err
Clear all recorded errors to prevent a requeue.
```lua
if last_err() then
clear_err()
return false
else
return true
end
```
### execve
Execute an external program. Returns the exit code.
```lua
execve("myprog", {"arg1", "arg2", "--arg", "3"})
```
### hex
Hex encode a list of bytes.
```lua
hex("\x6F\x68\x61\x69\x0A\x00")
```
### hmac_md5
Calculate an hmac with md5. Returns a binary array.
```lua
hmac_md5("secret", "my authenticated message")
```
### hmac_sha1
Calculate an hmac with sha1. Returns a binary array.
```lua
hmac_sha1("secret", "my authenticated message")
```
### hmac_sha2_256
Calculate an hmac with sha2_256. Returns a binary array.
```lua
hmac_sha2_256("secret", "my authenticated message")
```
### hmac_sha2_512
Calculate an hmac with sha2_512. Returns a binary array.
```lua
hmac_sha2_512("secret", "my authenticated message")
```
### hmac_sha3_256
Calculate an hmac with sha3_256. Returns a binary array.
```lua
hmac_sha3_256("secret", "my authenticated message")
```
### hmac_sha3_512
Calculate an hmac with sha3_512. Returns a binary array.
```lua
hmac_sha3_512("secret", "my authenticated message")
```
### html_select
Parses an html document and returns the first element that matches the css
selector. The return value is a table with `text` being the inner text and
`attrs` being a table of the elements attributes.
```lua
csrf = html_select(html, 'input[name="csrf"]')
token = csrf["attrs"]["value"]
```
### html_select_list
Same as [`html_select`](#html_select) but returns all matches instead of the
first one.
```lua
html_select_list(html, 'input[name="csrf"]')
```
### http_basic_auth
Sends a `GET` request with basic auth. Returns `true` if no `WWW-Authenticate`
header is set and the status code is not `401`.
```lua
http_basic_auth("https://httpbin.org/basic-auth/foo/buzz", user, password)
```
### http_mksession
Create a session object. This is similar to `requests.Session` in
python-requests and keeps track of cookies.
```lua
session = http_mksession()
```
### http_request
Prepares an http request. The first argument is the session reference and
cookies from that session are copied into the request. After the request has
been sent, the cookies from the response are copied back into the session.
The next arguments are the `method`, the `url` and additional options. Please
note that you still need to specify an empty table `{}` even if no options are
set. The following options are available:
- `query` - a map of query parameters that should be set on the url
- `headers` - a map of headers that should be set
- `basic_auth` - configure the basic auth header with `{"user, "password"}`
- `user_agent` - overwrite the default user agent with a string
- `json` - the request body that should be json encoded
- `form` - the request body that should be form encoded
- `body` - the raw request body as string
```lua
req = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end
```
### http_send
Send the request that has been built with [`http_request`](#http_request).
Returns a table with the following keys:
- `status` - the http status code
- `headers` - a table of headers
- `text` - the response body as string
```lua
req = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end
```
### json_decode
Decode a lua value from a json string.
```lua
json_decode("{\"data\":{\"password\":\"fizz\",\"user\":\"bar\"},\"list\":[1,3,3,7]}")
```
### json_encode
Encode a lua value to a json string. Note that empty tables are encoded to an
empty object `{}` instead of an empty list `[]`.
```lua
x = json_encode({
hello="world",
almost_one=0.9999,
list={1,3,3,7},
data={
user=user,
password=password,
empty=nil
}
})
```
### last_err
Returns `nil` if no error has been recorded, returns a string otherwise.
```lua
if last_err() then return end
```
### ldap_bind
Connect to an ldap server and try to authenticate with the given user.
```lua
ldap_bind("ldaps://ldap.example.com/",
"cn=\"" .. ldap_escape(user) .. "\",ou=users,dc=example,dc=com", password)
```
### ldap_escape
Escape an attribute value in a relative distinguished name.
```lua
ldap_escape(user)
```
### ldap_search_bind
Connect to an ldap server, log into a search user, search for the target user
and then try to authenticate with the first DN that was returned by the search.
```lua
ldap_search_bind("ldaps://ldap.example.com/",
-- the user we use to find the correct DN
"cn=search_user,ou=users,dc=example,dc=com", "searchpw",
-- base DN we search in
"dc=example,dc=com",
-- the user we test
user, password)
```
### md5
Hash a byte array with md5 and return the results as bytes.
```lua
hex(md5("\x00\xff"))
```
### mysql_connect
Connect to a mysql database and try to authenticate with the provided
credentials. Returns a mysql connection on success.
```lua
sock = mysql_connect("127.0.0.1", 3306, user, password)
```
### mysql_query
Run a query on a mysql connection. The 3rd parameter is for prepared
statements.
```lua
rows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {
foo='magic'
})
```
### print
Prints the value of a variable. Please note that this bypasses the regular
writer and may interfer with the progress bar. Only use this for debugging.
```lua
print({
data={
user=user,
password=password
}
})
```
### rand
Returns a random `u32` with a minimum and maximum constraint. The return value
can be greater or equal to the minimum boundary, and always lower than the
maximum boundary. This function has not been reviewed for cryptographic
security.
```lua
rand(0, 256)
```
### randombytes
Generate the specified number of random bytes.
```lua
randombytes(16)
```
### sha1
Hash a byte array with sha1 and return the results as bytes.
```lua
hex(sha1("\x00\xff"))
```
### sha2_256
Hash a byte array with sha2_256 and return the results as bytes.
```lua
hex(sha2_256("\x00\xff"))
```
### sha2_512
Hash a byte array with sha2_512 and return the results as bytes.
```lua
hex(sha2_512("\x00\xff"))
```
### sha3_256
Hash a byte array with sha3_256 and return the results as bytes.
```lua
hex(sha3_256("\x00\xff"))
```
### sha3_512
Hash a byte array with sha3_512 and return the results as bytes.
```lua
hex(sha3_512("\x00\xff"))
```
### sleep
Pauses the thread for the specified number of seconds. This is mostly used to
debug concurrency.
```lua
sleep(3)
```
### sock_connect
Create a tcp connection.
```lua
sock = sock_connect("127.0.0.1", 1337)
```
### sock_send
Send data to the socket.
```lua
sock_send(sock, "hello world")
```
### sock_recv
Receive up to 4096 bytes from the socket.
```lua
x = sock_recv(sock)
```
### sock_sendline
Send a string to the socket. A newline is automatically appended to the string.
```lua
sock_sendline(sock, line)
```
### sock_recvline
Receive a line from the socket. The line includes the newline.
```lua
x = sock_recvline(sock)
```
### sock_recvall
Receive all data from the socket until EOF.
```lua
x = sock_recvall(sock)
```
### sock_recvline_contains
Receive lines from the server until a line contains the needle, then return
this line.
```lua
x = sock_recvline_contains(sock, needle)
```
### sock_recvline_regex
Receive lines from the server until a line matches the regex, then return this
line.
```lua
x = sock_recvline_regex(sock, "^250 ")
```
### sock_recvn
Receive exactly n bytes from the socket.
```lua
x = sock_recvn(sock, 4)
```
### sock_recvuntil
Receive until the needle is found, then return all data including the needle.
```lua
x = sock_recvuntil(sock, needle)
```
### sock_sendafter
Receive until the needle is found, then write data to the socket.
```lua
sock_sendafter(sock, needle, data)
```
### sock_newline
Overwrite the default `\n` newline.
```lua
sock_newline(sock, "\r\n")
```
## Configuration
You can place a config file at `~/.config/authoscope.toml` to set some
defaults.
### Global user agent
```toml
[runtime]
user_agent = "w3m/0.5.3+git20180125"
```
### RLIMIT_NOFILE
```toml
[runtime]
# requires CAP_SYS_RESOURCE
# sudo setcap 'CAP_SYS_RESOURCE=+ep' /usr/bin/authoscope
rlimit_nofile = 64000
```
## Wrapping python scripts
The authoscope runtime is still very bare bones, so you might have to shell out
to your regular python script occasionally. Your wrapper may look like this:
```lua
descr = "example.com"
function verify(user, password)
ret = execve("./docs/test.py", {user, password})
if last_err() then return end
if ret == 2 then
return "script signaled an exception"
end
return ret == 0
end
```
Your python script may look like this:
```python
import sys
try:
if sys.argv[1] == "foo" and sys.argv[2] == "bar":
# correct credentials
sys.exit(0)
else:
# incorrect credentials
sys.exit(1)
except:
# signal an exception
# this requeues the attempt instead of discarding it
sys.exit(2)
```
# License
GPLv3+
================================================
FILE: ci/smtp/Dockerfile
================================================
FROM debian:stretch
RUN apt-get update -qq \
&& apt-get install -yq opensmtpd
RUN echo "foo" > /etc/mailname
ADD smtpd.conf /etc/smtpd.conf
EXPOSE 25
CMD ["/usr/sbin/smtpd", "-d"]
================================================
FILE: ci/smtp/smtpd.conf
================================================
# This is the smtpd server system-wide configuration file.
# See smtpd.conf(5) for more information.
# To accept external mail, replace with: listen on all
listen on 0.0.0.0
# If you edit the file, you have to run "smtpctl update table aliases"
table aliases file:/etc/aliases
# Uncomment the following to accept external mail for domain "example.org"
accept from any for domain "example.com" alias <aliases> deliver to mbox
#accept for local alias <aliases> deliver to mbox
accept for any relay
================================================
FILE: docs/Makefile
================================================
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ReadtheDocsTemplate.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ReadtheDocsTemplate.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/ReadtheDocsTemplate"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ReadtheDocsTemplate"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
================================================
FILE: docs/authoscope.1
================================================
.TH AUTHOSCOPE "1" "August 2018" "authoscope 0.6.1" "User Commands"
.SH NAME
authoscope \- scriptable network authentication cracker
.SH SYNOPSIS
.B authoscope
[\fB\-nVh\fR] command
.SH DESCRIPTION
authoscope is a scriptable network authentication cracker. While the space for
common service bruteforce is already very well saturated, you may still end up
writing your own python scripts when testing credentials for web applications.
The scope of authoscope is specifically cracking custom services. This is done
by writing scripts that are loaded into a lua runtime. Those scripts represent
a single service and provide a `verify(user, password)` function that returns
either true or false. Concurrency, progress indication and reporting is
magically provided by the authoscope runtime.
.SH OPTIONS
.TP
\fB\-n\fR, \fB\-\-workers\fR <workers>
The number of concurrent workers to run.
.TP
\fB\-o\fR, \fB\-\-output\fR <output>
Write results to this file.
.TP
\fB\-v\fR, \fB\-\-verbose\fR
Enable verbose output.
.TP
\fB\-h\fR, \fB\-\-help\fR
Prints help information.
.TP
\fB\-V\fR, \fB\-\-version\fR
Prints version information.
.SH SUBCOMMANDS
Pick one of the following subcommands.
.SS Dictionary attack
.LP
Try each password for each user with every script.
.RS
\fBauthoscope dict\fR
<\fBusers\fR>
<\fBpasswords\fR>
[\fBscripts\fR]...
.RE
.SS Credential confirmation
.LP
Load a list of credentials with the format \fBuser:password\fR and verify them
with every script.
.RS
\fBauthoscope creds\fR
<\fBcredentials\fR>
[\fBscripts\fR]...
.RE
.SS Username enumeration
.LP
Takes a list of username and verifies they exist on the system. This is still
executing the \fBverify\fR function with two arguments, but the password is set
to \fBnil\fR. You may write a script that can do both by checking the password
for nil to detect in which mode the script is executed.
.RS
\fBauthoscope enum\fR
<\fBusers\fR>
[\fBscripts\fR]...
.RE
.SS Oneshot
.LP
Test a single username-password combination using a specific script. This
command is also useful when developing a new script. If the password argument
is omitted, the script is executed in enumerate mode. If you want to use this
command in scripts, set \-x so the exitcode is set to 2 if the credentials are
invalid.
.RS
\fBauthoscope oneshot\fR
[\fB\-x\fR]
<\fBscript\fR>
<\fBuser\fR>
[\fBpassword\fR]
.SH RUNTIME REFERENCE
The authoscope runtime provides a number of functions that can be used to test
target systems.
.SS base64_decode
.LP
Decode a base64 string.
.RS
.nf
\fBbase64_decode("ww==")\fP
.fi
.RE
.SS base64_encode
.LP
Encode a binary array with base64.
.RS
.nf
\fBbase64_encode("\\x00\\xff")\fP
.fi
.RE
.SS clear_err
.LP
Clear all recorded errors to prevent a requeue.
.RS
.nf
\fBif last_err() then
clear_err()
return false
else
return true
end\fP
.fi
.RE
.SS execve
.LP
Execute an external program. Returns the exit code.
.RS
.nf
\fBexecve("myprog", {"arg1", "arg2", "--arg", "3"})\fP
.fi
.RE
.SS hex
.LP
Hex encode a list of bytes.
.RS
.nf
\fBhex({0x6F, 0x68, 0x61, 0x69, 0x0A, 0x00})\fR
.fi
.RE
.SS hmac_md5
.LP
Calculate an hmac with md5. Returns a binary array.
.RS
.nf
\fBhmac_md5("secret", "my authenticated message")\fR
.fi
.RE
.SS hmac_sha1
.LP
Calculate an hmac with sha1. Returns a binary array.
.RS
.nf
\fBhmac_sha1("secret", "my authenticated message")\fR
.fi
.RE
.SS hmac_sha2_256
.LP
Calculate an hmac with sha2_256. Returns a binary array.
.RS
.nf
\fBhmac_sha2_256("secret", "my authenticated message")\fR
.fi
.RE
.SS hmac_sha2_512
.LP
Calculate an hmac with sha2_512. Returns a binary array.
.RS
.nf
\fBhmac_sha2_512("secret", "my authenticated message")\fR
.fi
.RE
.SS hmac_sha3_256
.LP
Calculate an hmac with sha3_256. Returns a binary array.
.RS
.nf
\fBhmac_sha3_256("secret", "my authenticated message")\fR
.fi
.RE
.SS hmac_sha3_512
.LP
Calculate an hmac with sha3_512. Returns a binary array.
.RS
.nf
\fBhmac_sha3_512("secret", "my authenticated message")\fR
.fi
.RE
.SS html_select
.LP
Parses an html document and returns the first element that matches the css
selector. The return value is a table with \fBtext\fR being the inner text and
\fBattrs\fR being a table of the elements attributes.
.RS
.nf
\fBcsrf = html_select(html, 'input[name="csrf"]')
token = csrf["attrs"]["value"]\fP
.fi
.RE
.SS html_select_list
.LP
Same as \fBhtml_select\fP but returns all matches instead of the first one.
.RS
.nf
\fBhtml_select_list(html, 'input[name="csrf"]')\fP
.fi
.RE
.SS http_basic_auth
.LP
Sends a \fBGET\fR request with basic auth. Returns \fBtrue\fR if no
\fBWWW-Authenticate\fR header is set and the status code is not \fB401\fR.
.RS
.nf
\fBhttp_basic_auth("https://httpbin.org/basic-auth/foo/buzz", user, password)\fP
.fi
.RE
.SS http_mksession
.LP
Create a session object. This is similar to \fBrequests.Session\fR in
python-requests and keeps track of cookies.
.RS
.nf
\fBsession = http_mksession()\fP
.fi
.RE
.SS http_request
.LP
Prepares an http request. The first argument is the session reference and
cookies from that session are copied into the request. After the request has
been sent, the cookies from the response are copied back into the session.
The next arguments are the \fBmethod\fR, the \fBurl\fR and additional options. Please
note that you still need to specify an empty table \fB{}\fR even if no options are
set. The following options are available:
.nf
- \fBquery\fR - a map of query parameters that should be set on the url
- \fBheaders\fR - a map of headers that should be set
- \fBbasic_auth\fR - configure the basic auth header with \fB{"user, "password"}\fR
- \fBuser_agent\fR - overwrite the default user agent with a string
- \fBjson\fR - the request body that should be json encoded
- \fBform\fR - the request body that should be form encoded
- \fBbody\fR - the raw request body as string
.fi
.RS
.nf
\fBreq = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end\fP
.fi
.RE
.SS http_send
.LP
Send the request that has been built with \fBhttp_request\fR.
Returns a table with the following keys:
.nf
- \fBstatus\fR - the http status code
- \fBheaders\fR - a table of headers
- \fBtext\fR - the response body as string
.fi
.RS
.nf
\fBreq = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end\fP
.fi
.RE
.SS json_decode
.LP
Decode a lua value from a json string.
.RS
.nf
\fBjson_decode("{\\"data\\":{\\"password\\":\\"fizz\\",\\"user\\":\\"bar\\"},\\"list\\":[1,3,3,7]}")\fP
.fi
.RE
.SS json_encode
.LP
Encode a lua value to a json string. Note that empty tables are encoded to an
empty object \fB{}\fR instead of an empty list \fB[]\fR.
.RS
.nf
\fBx = json_encode({
hello="world",
almost_one=0.9999,
list={1,3,3,7},
data={
user=user,
password=password,
empty=nil
}
})\fP
.fi
.RE
.SS last_err
.LP
Returns \fBnil\fR if no error has been recorded, returns a string otherwise.
.RS
.nf
\fBif last_err() then return end\fP
.fi
.RE
.SS ldap_bind
.LP
Connect to an ldap server and try to authenticate with the given user
.RS
.nf
\fBldap_bind("ldaps://ldap.example.com/",
"cn=\\"" .. ldap_escape(user) .. "\\",ou=users,dc=example,dc=com", password)\fP
.fi
.RE
.SS ldap_escape
.LP
Escape an attribute value in a relative distinguished name.
.RS
.nf
\fBldap_escape(user)\fP
.fi
.RE
.SS ldap_search_bind
.LP
Connect to an ldap server, log into a search user, search for the target user
and then try to authenticate with the first DN that was returned by the search.
.RS
.nf
\fBldap_search_bind("ldaps://ldap.example.com/",
-- the user we use to find the correct DN
"cn=search_user,ou=users,dc=example,dc=com", "searchpw",
-- base DN we search in
"dc=example,dc=com",
-- the user we test
user, password)\fP
.fi
.RE
.SS md5
.LP
Hash a byte array with md5 and return the results as bytes.
.RS
.nf
\fBhex(md5("\\x00\\xff"))\fP
.fi
.RE
.SS mysql_connect
.LP
Connect to a mysql database and try to authenticate with the provided
credentials. Returns a mysql connection on success.
.RS
.nf
\fBsock = mysql_connect("127.0.0.1", 3306, user, password)\fP
.fi
.RE
.SS mysql_query
.LP
Run a query on a mysql connection. The 3rd parameter is for prepared
statements.
.RS
.nf
\fBrows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {
foo='magic'
})\fP
.fi
.RE
.SS print
.LP
Prints the value of a variable. Please note that this bypasses the regular
writer and may interfer with the progress bar. Only use this for debugging.
.RS
.nf
\fBprint({
data={
user=user,
password=password
}
})\fP
.fi
.RE
.SS rand
.LP
Returns a random \fBu32\fP with a minimum and maximum constraint. The return value
can be greater or equal to the minimum boundary, and always lower than the
maximum boundary. This function has not been reviewed for cryptographic
security.
.RS
.nf
\fBrand(0, 256)\fP
.fi
.RE
.SS randombytes
.LP
Generate the specified number of random bytes.
.RS
.nf
\fBrandombytes(16)\fP
.fi
.RE
.SS sha1
.LP
Hash a byte array with sha1 and return the results as bytes.
.RS
.nf
\fBhex(sha1("\\x00\\xff"))\fP
.fi
.RE
.SS sha2_256
.LP
Hash a byte array with sha2_256 and return the results as bytes.
.RS
.nf
\fBhex(sha2_256("\\x00\\xff"))\fP
.fi
.RE
.SS sha2_512
.LP
Hash a byte array with sha2_512 and return the results as bytes.
.RS
.nf
\fBhex(sha2_512("\\x00\\xff"))\fP
.fi
.RE
.SS sha3_256
.LP
Hash a byte array with sha3_256 and return the results as bytes.
.RS
.nf
\fBhex(sha3_256("\\x00\\xff"))\fP
.fi
.RE
.SS sha3_512
.LP
Hash a byte array with sha3_512 and return the results as bytes.
.RS
.nf
\fBhex(sha3_512("\\x00\\xff"))\fP
.fi
.RE
.SS sleep
.LP
Pauses the thread for the specified number of seconds. This is mostly used to
debug concurrency.
.RS
.nf
\fBsleep(3)\fP
.fi
.RE
.SS sock_connect
.LP
Create a tcp connection.
.RS
.nf
\fBsock = sock_connect("127.0.0.1", 1337)\fP
.fi
.RE
.SS sock_send
.LP
Send data to the socket.
.RS
.nf
\fBsock_send(sock, "hello world")\fP
.fi
.RE
.SS sock_recv
.LP
Receive up to 4096 bytes from the socket.
.RS
.nf
\fBx = sock_recv(sock)\fP
.fi
.RE
.SS sock_sendline
.LP
Send a string to the socket. A newline is automatically appended to the string.
.RS
.nf
\fBsock_sendline(sock, line)\fP
.fi
.RE
.SS sock_recvline
.LP
Receive a line from the socket. The line includes the newline.
.RS
.nf
\fBx = sock_recvline(sock)\fP
.fi
.RE
.SS sock_recvall
.LP
Receive all data from the socket until EOF.
.RS
.nf
\fBx = sock_recvall(sock)\fP
.fi
.RE
.SS sock_recvline_contains
.LP
Receive lines from the server until a line contains the needle, then return
this line.
.RS
.nf
\fBx = sock_recvline_contains(sock, needle)\fP
.fi
.RE
.SS sock_recvline_regex
.LP
Receive lines from the server until a line matches the regex, then return this
line.
.RS
.nf
\fBx = sock_recvline_regex(sock, "^250 ")\fP
.fi
.RE
.SS sock_recvn
.LP
Receive exactly n bytes from the socket.
.RS
.nf
\fBx = sock_recvn(sock, 4)\fP
.fi
.RE
.SS sock_recvuntil
.LP
Receive until the needle is found, then return all data including the needle.
.RS
.nf
\fBx = sock_recvuntil(sock, needle)\fP
.fi
.RE
.SS sock_sendafter
.LP
Receive until the needle is found, then write data to the socket.
.RS
.nf
\fBsock_sendafter(sock, needle, data)\fP
.fi
.RE
.SS sock_newline
.LP
Overwrite the default `\\n` newline.
.RS
.nf
\fBsock_newline(sock, "\\r\\n")\fP
.fi
.RE
.SH SECURITY
To report a security issue please contact kpcyrd on ircs://irc.hackint.org.
.SH "SEE ALSO"
The documentation at lua.org.
.SH AUTHORS
This program was originally written and is currently maintained by kpcyrd.
Bugs and patches are welcome on github:
.LP
.RS
.I https://github.com/kpcyrd/authoscope
.RE
================================================
FILE: docs/conf.py
================================================
# -*- coding: utf-8 -*-
#
# Read the Docs Template documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 26 14:19:49 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'authoscope'
copyright = u'2018, kpcyrd'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
#version = '1.0'
# The full version, including alpha/beta/rc tags.
#release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'ReadtheDocsTemplatedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'authoscope.tex', u'authoscope Documentation',
u'kpcyrd', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('man', 'authoscope', u'Scriptable network authentication cracker',
[u'kpcyrd'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation',
u'Read the Docs', 'ReadtheDocsTemplate', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
================================================
FILE: docs/config.rst
================================================
Configuration
=============
You can place a config file at ``~/.config/authoscope.toml`` to set some defaults.
Global user agent
-----------------
.. code-block:: toml
[runtime]
user_agent = "w3m/0.5.3+git20180125"
RLIMIT_NOFILE
-------------
.. code-block:: toml
[runtime]
# requires CAP_SYS_RESOURCE
# sudo setcap 'CAP_SYS_RESOURCE=+ep' /usr/bin/authoscope
rlimit_nofile = 64000
================================================
FILE: docs/index.rst
================================================
authoscope
==========
authoscope (formerly badtouch) is a scriptable network authentication cracker.
While the space for common service bruteforce is already very_ well_
saturated_, you may still end up writing your own python scripts when testing
credentials for web applications.
.. _very: https://nmap.org/ncrack/
.. _well: https://github.com/vanhauser-thc/thc-hydra
.. _saturated: https://github.com/jmk-foofus/medusa
The scope of authoscope is specifically cracking custom services. This is done
by writing scripts that are loaded into a lua runtime. Those scripts represent
a single service and provide a ``verify(user, password)`` function that returns
either true or false. Concurrency, progress indication and reporting is
magically provided by the authoscope runtime.
.. image:: https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ.png
:target: https://asciinema.org/a/Ke5rHVsz5sJePNUK1k0ASAvuZ
Getting Started
---------------
.. toctree::
:maxdepth: 3
:glob:
install
usage
scripting
config
================================================
FILE: docs/install.rst
================================================
Installation
============
If available, please prefer the package shipped by your linux distribution.
Archlinux
---------
.. code-block:: bash
$ pacman -S authoscope
Mac OSX
-------
.. code-block:: bash
$ brew install authoscope
Docker
------
.. code-block:: bash
$ docker run --rm kpcyrd/authoscope --help
Source
------
To build from source, make sure you have rust_ and ``libssl-dev`` installed.
.. _rust: https://rustup.rs/
.. code-block:: bash
$ git clone https://github.com/kpcyrd/authoscope
$ cd authoscope
$ cargo build
================================================
FILE: docs/make.bat
================================================
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end
================================================
FILE: docs/man.rst
================================================
authoscope
========
authoscope (formerly badtouch) is a scriptable network authentication cracker.
While the space for common service bruteforce is already very well saturated,
you may still end up writing your own python scripts when testing credentials
for web applications.
The scope of authoscope is specifically cracking custom services. This is done
by writing scripts that are loaded into a lua runtime. Those scripts represent
a single service and provide a ``verify(user, password)`` function that returns
either true or false. Concurrency, progress indication and reporting is
magically provided by the authoscope runtime.
.. toctree::
:maxdepth: 3
:glob:
usage
scripting
config
================================================
FILE: docs/scripting.rst
================================================
Scripting
=========
A simple script could look like this:
.. code-block:: lua
descr = "example.com"
function verify(user, password)
session = http_mksession()
-- get csrf token
req = http_request(session, 'GET', 'https://example.com/login', {})
resp = http_send(req)
if last_err() then return end
-- parse token from html
html = resp['text']
csrf = html_select(html, 'input[name="csrf"]')
token = csrf["attrs"]["value"]
-- send login
req = http_request(session, 'POST', 'https://example.com/login', {
form={
user=user,
password=password,
csrf=token
}
})
resp = http_send(req)
if last_err() then return end
-- search response for successful login
html = resp['text']
return html:find('Login successful') ~= nil
end
Please see the reference and [examples](/scripts) for all available functions.
Keep in mind that you can use `print(x)` and `authoscope oneshot` to debug your
script.
base64_decode
-------------
Decode a base64 string.
.. code-block:: lua
base64_decode("ww==")
base64_encode
-------------
Encode a binary array with base64.
.. code-block:: lua
base64_encode("\x00\xff")
clear_err
---------
Clear all recorded errors to prevent a requeue.
.. code-block:: lua
if last_err() then
clear_err()
return false
else
return true
end
execve
------
Execute an external program. Returns the exit code.
.. code-block:: lua
execve("myprog", {"arg1", "arg2", "--arg", "3"})
hex
---
Hex encode a list of bytes.
.. code-block:: lua
hex("\x6F\x68\x61\x69\x0A\x00")
hmac_md5
--------
Calculate an hmac with md5. Returns a binary array.
.. code-block:: lua
hmac_md5("secret", "my authenticated message")
hmac_sha1
---------
Calculate an hmac with sha1. Returns a binary array.
.. code-block:: lua
hmac_sha1("secret", "my authenticated message")
hmac_sha2_256
-------------
Calculate an hmac with sha2_256. Returns a binary array.
.. code-block:: lua
hmac_sha2_256("secret", "my authenticated message")
hmac_sha2_512
-------------
Calculate an hmac with sha2_512. Returns a binary array.
.. code-block:: lua
hmac_sha2_512("secret", "my authenticated message")
hmac_sha3_256
-------------
Calculate an hmac with sha3_256. Returns a binary array.
.. code-block:: lua
hmac_sha3_256("secret", "my authenticated message")
hmac_sha3_512
-------------
Calculate an hmac with sha3_512. Returns a binary array.
.. code-block:: lua
hmac_sha3_512("secret", "my authenticated message")
html_select
-----------
Parses an html document and returns the first element that matches the css
selector. The return value is a table with ``text`` being the inner text and
``attrs`` being a table of the elements attributes.
.. code-block:: lua
csrf = html_select(html, 'input[name="csrf"]')
token = csrf["attrs"]["value"]
html_select_list
----------------
Same as html_select_ but returns all matches instead of the
first one.
.. code-block:: lua
html_select_list(html, 'input[name="csrf"]')
http_basic_auth
---------------
Sends a ``GET`` request with basic auth. Returns ``true`` if no ``WWW-Authenticate``
header is set and the status code is not ``401``.
.. code-block:: lua
http_basic_auth("https://httpbin.org/basic-auth/foo/buzz", user, password)
http_mksession
--------------
Create a session object. This is similar to ``requests.Session`` in
python-requests and keeps track of cookies.
.. code-block:: lua
session = http_mksession()
http_request
------------
Prepares an http request. The first argument is the session reference and
cookies from that session are copied into the request. After the request has
been sent, the cookies from the response are copied back into the session.
The next arguments are the ``method``, the ``url`` and additional options. Please
note that you still need to specify an empty table ``{}`` even if no options are
set. The following options are available:
- ``query`` - a map of query parameters that should be set on the url
- ``headers`` - a map of headers that should be set
- ``basic_auth`` - configure the basic auth header with ``{"user, "password"}``
- ``user_agent`` - overwrite the default user agent with a string
- ``json`` - the request body that should be json encoded
- ``form`` - the request body that should be form encoded
- ``body`` - the raw request body as string
.. code-block:: lua
req = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end
http_send
---------
Send the request that has been built with http_request_. Returns a table with
the following keys:
- ``status`` - the http status code
- ``headers`` - a table of headers
- ``text`` - the response body as string
.. code-block:: lua
req = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end
json_decode
-----------
Decode a lua value from a json string.
.. code-block:: lua
json_decode("{\"data\":{\"password\":\"fizz\",\"user\":\"bar\"},\"list\":[1,3,3,7]}")
json_encode
-----------
Encode a lua value to a json string. Note that empty tables are encoded to an
empty object ``{}`` instead of an empty list ``[]``.
.. code-block:: lua
x = json_encode({
hello="world",
almost_one=0.9999,
list={1,3,3,7},
data={
user=user,
password=password,
empty=nil
}
})
last_err
--------
Returns ``nil`` if no error has been recorded, returns a string otherwise.
.. code-block:: lua
if last_err() then return end
ldap_bind
---------
Connect to an ldap server and try to authenticate with the given user.
.. code-block:: lua
ldap_bind("ldaps://ldap.example.com/",
"cn=\"" .. ldap_escape(user) .. "\",ou=users,dc=example,dc=com", password)
ldap_escape
-----------
Escape an attribute value in a relative distinguished name.
.. code-block:: lua
ldap_escape(user)
ldap_search_bind
----------------
Connect to an ldap server, log into a search user, search for the target user
and then try to authenticate with the first DN that was returned by the search.
.. code-block:: lua
ldap_search_bind("ldaps://ldap.example.com/",
-- the user we use to find the correct DN
"cn=search_user,ou=users,dc=example,dc=com", "searchpw",
-- base DN we search in
"dc=example,dc=com",
-- the user we test
user, password)
md5
---
Hash a byte array with md5 and return the results as bytes.
.. code-block:: lua
hex(md5("\x00\xff"))
mysql_connect
-------------
Connect to a mysql database and try to authenticate with the provided
credentials. Returns a mysql connection on success.
.. code-block:: lua
sock = mysql_connect("127.0.0.1", 3306, user, password)
mysql_query
-----------
Run a query on a mysql connection. The 3rd parameter is for prepared
statements.
.. code-block:: lua
rows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {
foo='magic'
})
print
-----
Prints the value of a variable. Please note that this bypasses the regular
writer and may interfer with the progress bar. Only use this for debugging.
.. code-block:: lua
print({
data={
user=user,
password=password
}
})
rand
----
Returns a random ``u32`` with a minimum and maximum constraint. The return
value can be greater or equal to the minimum boundary, and always lower than
the maximum boundary. This function has not been reviewed for cryptographic
security.
.. code-block:: lua
rand(0, 256)
randombytes
-----------
Generate the specified number of random bytes.
.. code-block:: lua
randombytes(16)
sha1
----
Hash a byte array with sha1 and return the results as bytes.
.. code-block:: lua
hex(sha1("\x00\xff"))
sha2_256
--------
Hash a byte array with sha2_256 and return the results as bytes.
.. code-block:: lua
hex(sha2_256("\x00\xff"))
sha2_512
--------
Hash a byte array with sha2_512 and return the results as bytes.
.. code-block:: lua
hex(sha2_512("\x00\xff"))
sha3_256
--------
Hash a byte array with sha3_256 and return the results as bytes.
.. code-block:: lua
hex(sha3_256("\x00\xff"))
sha3_512
--------
Hash a byte array with sha3_512 and return the results as bytes.
.. code-block:: lua
hex(sha3_512("\x00\xff"))
sleep
-----
Pauses the thread for the specified number of seconds. This is mostly used to
debug concurrency.
.. code-block:: lua
sleep(3)
sock_connect
------------
Create a tcp connection.
.. code-block:: lua
sock = sock_connect("127.0.0.1", 1337)
sock_send
---------
Send data to the socket.
.. code-block:: lua
sock_send(sock, "hello world")
sock_recv
---------
Receive up to 4096 bytes from the socket.
.. code-block:: lua
x = sock_recv(sock)
sock_sendline
-------------
Send a string to the socket. A newline is automatically appended to the string.
.. code-block:: lua
sock_sendline(sock, line)
sock_recvline
-------------
Receive a line from the socket. The line includes the newline.
.. code-block:: lua
x = sock_recvline(sock)
sock_recvall
------------
Receive all data from the socket until EOF.
.. code-block:: lua
x = sock_recvall(sock)
sock_recvline_contains
----------------------
Receive lines from the server until a line contains the needle, then return
this line.
.. code-block:: lua
x = sock_recvline_contains(sock, needle)
sock_recvline_regex
-------------------
Receive lines from the server until a line matches the regex, then return this
line.
.. code-block:: lua
x = sock_recvline_regex(sock, "^250 ")
sock_recvn
----------
Receive exactly n bytes from the socket.
.. code-block:: lua
x = sock_recvn(sock, 4)
sock_recvuntil
--------------
Receive until the needle is found, then return all data including the needle.
.. code-block:: lua
x = sock_recvuntil(sock, needle)
sock_sendafter
--------------
Receive until the needle is found, then write data to the socket.
.. code-block:: lua
sock_sendafter(sock, needle, data)
sock_newline
------------
Overwrite the default `\n` newline.
.. code-block:: lua
sock_newline(sock, "\r\n")
Wrapping python scripts
-----------------------
The authoscope runtime is still very bare bones, so you might have to shell
out to your regular python script occasionally. Your wrapper may look like this:
.. code-block:: lua
descr = "example.com"
function verify(user, password)
ret = execve("./docs/test.py", {user, password})
if last_err() then return end
if ret == 2 then
return "script signaled an exception"
end
return ret == 0
end
Your python script may look like this:
.. code-block:: python
import sys
try:
if sys.argv[1] == "foo" and sys.argv[2] == "bar":
# correct credentials
sys.exit(0)
else:
# incorrect credentials
sys.exit(1)
except:
# signal an exception
# this requeues the attempt instead of discarding it
sys.exit(2)
================================================
FILE: docs/test.sh
================================================
#!/bin/sh
echo $2 | grep -q "buzz"
================================================
FILE: docs/usage.rst
================================================
Usage
========
Options
-------
.. code-block:: text
-n, --workers <workers> The number of concurrent workers to run.
-o, --output <output> Write results to this file.
-v, --verbose Enable verbose output.
-h, --help Prints help information.
-V, --version Prints version information.
Dictionary attack
-----------------
Try each password for each user with every script.
.. code-block:: bash
authoscope dict <users> <passwords> [scripts]...
Credential confirmation
-----------------------
Load a list of credentials with the format ``user:password`` and verify them
with every script.
.. code-block:: bash
authoscope creds <credentials> [scripts]...
Username enumeration
--------------------
Takes a list of username and verifies they exist on the system. This is still
executing the ``verify`` function with two arguments, but the password is set
to ``nil``. You may write a script that can do both by checking the password
for nil to detect in which mode the script is executed.
.. code-block:: bash
authoscope enum <users> [scripts]...
Oneshot
-------
Test a single username-password combination using a specific script. This
command is also useful when developing a new script. If the password argument
is omitted, the script is executed in enumerate mode. If you want to use this
command in scripts, set ``-x`` so the exitcode is set to 2 if the credentials
are invalid.
.. code-block:: bash
authoscope oneshot [-x] <script> <user> [password]
================================================
FILE: examples/README.md
================================================
These are small programs to benchmark some individual components.
================================================
FILE: examples/load-creds.rs
================================================
use std::env;
use std::time::Instant;
use authoscope::errors::*;
fn main() -> Result<()> {
env_logger::init();
let path = env::args().nth(1)
.context("Missing argument")?;
let start = Instant::now();
let creds = authoscope::utils::load_combolist(&path)
.context("Failed to load creds")?;
let elapsed = start.elapsed();
let average = elapsed / creds.len() as u32;
println!("loaded {} records in {}, on average {}",
creds.len(),
humantime::format_duration(elapsed),
humantime::format_duration(average),
);
Ok(())
}
================================================
FILE: scripts/basic_auth.lua
================================================
descr = "basic auth httpbin.org"
function verify(user, password)
return http_basic_auth("https://httpbin.org/basic-auth/foo/buzz", user, password)
end
================================================
FILE: scripts/benchmark.lua
================================================
descr = "for benchmarking only"
function verify(user, password)
return false
end
================================================
FILE: scripts/binary.lua
================================================
descr = "binary"
function verify(user, password)
print("\x00\xff")
print(hex("\x00\xff"))
print(base64_encode(md5("\x00\xff")))
return true
end
================================================
FILE: scripts/cookies.lua
================================================
descr = "http cookies"
function verify(user, password)
session = http_mksession()
-- set cookies
req = http_request(session, 'GET', 'https://httpbin.org/cookies/set', {
query={
fizz='buzz',
foo='; as=df'
}
})
resp = http_send(req)
if last_err() then return end
-- print(resp)
-- print(resp["headers"]["set-cookie"])
-- check cookies have been setup
-- TODO: removing the {} causes a segfault
req = http_request(session, 'GET', 'https://httpbin.org/cookies', {})
resp = http_send(req)
if last_err() then return end
if resp['status'] ~= 200 then return 'invalid status code: ' .. resp['status'] end
json = json_decode(resp['text'])
if last_err() then return end
-- print(json)
if json['cookies']['foo'] ~= '; as=df' then
return 'Unexpected value for foo cookie'
end
if json['cookies']['fizz'] ~= 'buzz' then
return 'Unexpected value for fizz cookie'
end
return true
end
================================================
FILE: scripts/error.lua
================================================
descr = "always error"
function verify(user, password)
return "this is an error"
end
================================================
FILE: scripts/execve.lua
================================================
descr = "exec test.sh"
function verify(user, password)
return execve("./docs/test.sh", {user, password}) == 0
end
================================================
FILE: scripts/false.lua
================================================
descr = "always false"
function verify(user, password)
return false
end
================================================
FILE: scripts/http.lua
================================================
descr = "http"
function verify(user, password)
session = http_mksession()
-- set cookies
req = http_request(session, 'GET', 'https://httpbin.org/anything', {
basic_auth={"user", "password"},
user_agent="some-agent/0.1",
headers={
foo="bar"
}
})
resp = http_send(req)
if last_err() then return end
json = json_decode(resp['text'])
if last_err() then return end
print(json)
return false
end
================================================
FILE: scripts/json.lua
================================================
descr = "json"
function verify(user, password)
x = json_encode({
hello="world",
almost_one=0.9999,
list={1,3,3,7},
data={
user=user,
password=password,
empty=nil
}
})
print(x)
y = json_decode(x)
print(y)
print(y["data"]["user"])
return true
end
================================================
FILE: scripts/ldap.lua
================================================
descr = "ldap"
function verify(user, password)
return ldap_bind("ldaps://ldap.example.com/",
"cn=\"" .. ldap_escape(user) .. "\",ou=users,dc=example,dc=com", password)
end
================================================
FILE: scripts/ldap_search.lua
================================================
descr = "ldap w/ search"
function verify(user, password)
return ldap_search_bind("ldaps://ldap.example.com/",
-- the user we use to find the correct DN
"cn=search_user,ou=users,dc=example,dc=com", "searchpw",
-- base DN we search in
"dc=example,dc=com",
-- the user we test
user, password)
end
================================================
FILE: scripts/mysql-connect.lua
================================================
descr = "local mysql"
function verify(user, password)
mysql_connect("127.0.0.1", 3306, user, password)
if last_err() then
clear_err()
return false
else
return true
end
end
================================================
FILE: scripts/mysql-query.lua
================================================
descr = "local mysql query"
function verify(user, password)
sock = mysql_connect("127.0.0.1", 3306, "root", "my-secret-pw")
if last_err() then return end
rows = mysql_query(sock, 'SELECT VERSION(), :foo as foo', {
foo='magic'
})
if last_err() then return end
if rows[1] then
print(rows[1])
return true
else
return false
end
end
================================================
FILE: scripts/post.lua
================================================
descr = "http post"
function verify(user, password)
session = http_mksession()
-- send login
req = http_request(session, 'POST', 'https://httpbin.org/post', {
json={
user=user,
password=password,
}
})
resp = http_send(req)
if last_err() then return end
if resp["status"] ~= 200 then return "invalid status code" end
json = json_decode(resp['text'])
if last_err() then return end
print(json)
return true
end
================================================
FILE: scripts/print.lua
================================================
descr = "print"
function b64u(s)
s = s:gsub('%=', '')
s = s:gsub('%+', '-')
s = s:gsub('%/', '_')
return s
end
function verify(user, password)
print("user=".. user ..", password=" .. password)
-- this is buggy with hlua 0.4.1
print({user, password})
print(b64u('as=+/=+/=+/df'))
print({
data={
user=user,
password=password
}
})
return true
end
================================================
FILE: scripts/random-errors.lua
================================================
descr = "random errors"
function verify(user, password)
if rand(0, 100) < 1 then
return "random error"
end
return false
end
================================================
FILE: scripts/random.lua
================================================
descr = "random"
function verify(user, password)
x = rand(0, 10000)
return x >= 9999
end
================================================
FILE: scripts/sleep.lua
================================================
descr = "sleepy zZz"
function verify(user, password)
sleep(1)
return true
end
================================================
FILE: scripts/smtp.lua
================================================
descr = "smtp enum"
function verify(user, password)
-- enumeration only, password is ignored
sock = sock_connect("127.0.0.1", 25)
if last_err() then return end
sock_newline(sock, "\r\n")
-- get the banner
sock_recvline(sock)
if last_err() then return end
-- send ehlo
sock_sendline(sock, "ehlo localhost")
if last_err() then return end
-- read extensions
sock_recvline_regex(sock, "^250 ")
if last_err() then return end
-- start delivering an email
sock_sendline(sock, "MAIL FROM:<root>")
if last_err() then return end
-- read reply
sock_recvline(sock)
if last_err() then return end
-- TODO: verify starts with "250 "
-- probe for user
sock_sendline(sock, "RCPT TO:<" .. user .. ">")
if last_err() then return end
-- read reply
reply = sock_recvn(sock, 1)
if last_err() then return end
-- check it was successful
return reply == "2"
end
================================================
FILE: scripts/str-find.lua
================================================
descr = "str-find"
function verify(user, password)
text = "You are currently logged in as 'foo', want to log out?"
return text:find(user) ~= nil
end
================================================
FILE: scripts/true.lua
================================================
descr = "always true"
function verify(user, password)
return true
end
================================================
FILE: src/args.rs
================================================
use crate::errors::*;
use std::io::stdout;
use std::path::PathBuf;
use structopt::StructOpt;
use structopt::clap::{AppSettings, Shell};
#[derive(Debug, StructOpt)]
#[structopt(global_settings = &[AppSettings::ColoredHelp])]
pub struct Args {
/// Verbose output
#[structopt(short="v", long="verbose",
global=true, parse(from_occurrences))]
pub verbose: u8,
/// Concurrent workers
#[structopt(short = "n", long = "workers", default_value = "16")]
pub workers: usize,
/// Write results to file
#[structopt(short = "o", long = "output")]
pub output: Option<String>,
#[structopt(subcommand)]
pub subcommand: SubCommand,
}
#[derive(Debug, StructOpt)]
pub enum SubCommand {
/// For each user try every password from a dictionary/wordlist
Dict(Dict),
/// Run a credential stuffing attack with a combolist
Combo(Combo),
/// For each user enumerate if an account exists with that name/email
Enum(Enum),
/// Run a script with a single username and password
Run(Run),
/// Verify a given input file is properly encoded and all entries have valid formatting
Fsck(Fsck),
Completions(Completions),
}
#[derive(Debug, StructOpt)]
pub struct Dict {
/// Username list path
pub users_path: PathBuf,
/// Password list path
pub passwords_path: PathBuf,
/// Scripts to run
#[structopt(required=true)]
pub scripts: Vec<String>,
}
#[derive(Debug, StructOpt)]
pub struct Combo {
/// Path to combolist
pub path: PathBuf,
/// Scripts to run
#[structopt(required=true)]
pub scripts: Vec<String>,
}
#[derive(Debug, StructOpt)]
pub struct Enum {
/// Username list path
pub users: String,
/// Scripts to run
#[structopt(required=true)]
pub scripts: Vec<String>,
}
#[derive(Debug, StructOpt)]
pub struct Run {
/// Script to run
pub script: String,
/// Username to test
pub user: String,
/// Password to test
pub password: Option<String>,
/// Set the exitcode to 2 if the credentials are invalid
#[structopt(short = "x", long = "exitcode")]
pub exitcode: bool,
}
#[derive(Debug, StructOpt)]
pub struct Fsck {
/// Do not show invalid lines
#[structopt(short = "q", long = "quiet")]
pub quiet: bool,
/// Do not show valid lines
#[structopt(short = "s", long = "silent")]
pub silent: bool,
/// Require one colon per line
#[structopt(short = "c", long = "colon")]
pub require_colon: bool,
/// Files to read
pub paths: Vec<String>,
}
/// Generate shell completions
#[derive(Debug, StructOpt)]
pub struct Completions {
#[structopt(possible_values=&Shell::variants())]
pub shell: Shell,
}
impl Completions {
pub fn gen(&self) -> Result<()> {
Args::clap().gen_completions_to("authoscope", self.shell, &mut stdout());
Ok(())
}
}
================================================
FILE: src/bin/badtouch.rs
================================================
use authoscope::args;
use authoscope::config::Config;
use authoscope::ctx::Script;
use authoscope::errors::*;
use authoscope::fsck;
use authoscope::keyboard::{Keyboard, Key};
use authoscope::pb::ProgressBar;
use authoscope::scheduler::{self, Scheduler, Attempt, Msg};
use authoscope::utils;
use colored::*;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdout;
use std::sync::Arc;
use std::thread;
use std::time::Instant;
use structopt::StructOpt;
use structopt::clap::{AppSettings, Shell};
#[derive(Debug, StructOpt)]
#[structopt(global_settings = &[AppSettings::ColoredHelp])]
pub struct Args {
/// Verbose output
#[structopt(short="v", long="verbose",
global=true, parse(from_occurrences))]
pub verbose: u8,
/// Concurrent workers
#[structopt(short = "n", long = "workers", default_value = "16")]
pub workers: usize,
/// Write results to file
#[structopt(short = "o", long = "output")]
pub output: Option<String>,
#[structopt(subcommand)]
pub subcommand: SubCommand,
}
#[derive(Debug, StructOpt)]
pub enum SubCommand {
/// Dictionary attack
#[structopt(name="dict")]
Dict(Dict),
/// Credential confirmation attack
#[structopt(name="creds")]
Creds(Creds),
/// Enumerate users
#[structopt(name="enum")]
Enum(Enum),
/// Test a single username-password combination
#[structopt(name="oneshot")]
Oneshot(Oneshot),
/// Verify and fix encoding of a list
#[structopt(name="fsck")]
Fsck(Fsck),
Completions(Completions),
}
#[derive(Debug, StructOpt)]
pub struct Dict {
/// Username list path
pub users: String,
/// Password list path
pub passwords: String,
/// Scripts to run
#[structopt(required=true)]
pub scripts: Vec<String>,
}
#[derive(Debug, StructOpt)]
pub struct Creds {
/// Credential list path
pub creds: String,
/// Scripts to run
#[structopt(required=true)]
pub scripts: Vec<String>,
}
#[derive(Debug, StructOpt)]
pub struct Enum {
/// Username list path
pub users: String,
/// Scripts to run
#[structopt(required=true)]
pub scripts: Vec<String>,
}
#[derive(Debug, StructOpt)]
pub struct Oneshot {
/// Script to run
pub script: String,
/// Username to test
pub user: String,
/// Password to test
pub password: Option<String>,
/// Set the exitcode to 2 if the credentials are invalid
#[structopt(short = "x", long = "exitcode")]
pub exitcode: bool,
}
#[derive(Debug, StructOpt)]
pub struct Fsck {
/// Do not show invalid lines
#[structopt(short = "q", long = "quiet")]
pub quiet: bool,
/// Do not show valid lines
#[structopt(short = "s", long = "silent")]
pub silent: bool,
/// Require one colon per line
#[structopt(short = "c", long = "colon")]
pub require_colon: bool,
/// Files to read
pub paths: Vec<String>,
}
/// Generate shell completions
#[derive(Debug, StructOpt)]
pub struct Completions {
#[structopt(possible_values=&Shell::variants())]
pub shell: Shell,
}
impl Completions {
pub fn gen(&self) -> Result<()> {
Args::clap().gen_completions_to("authoscope", self.shell, &mut stdout());
Ok(())
}
}
enum Report {
Some(File),
None
}
impl Report {
pub fn open(path: Option<String>) -> Result<Report> {
match path {
Some(path) => Ok(Report::Some(File::create(path)?)),
None => Ok(Report::None),
}
}
pub fn write_creds(&mut self, user: &str, password: &str, script: &str) -> Result<()> {
if let Report::Some(ref mut f) = *self {
writeln!(f, "{}:{}:{}", script, user, password)?;
}
Ok(())
}
pub fn write_enum(&mut self, user: &str, script: &str) -> Result<()> {
if let Report::Some(ref mut f) = *self {
writeln!(f, "{}:{}", script, user)?;
}
Ok(())
}
}
macro_rules! tinfof {
($arg1:tt, $fmt:expr, $($arg:tt)*) => (
$arg1.bold().to_string() + " " + &(format!($fmt, $($arg)*).dimmed().to_string())
);
}
macro_rules! tinfo {
($arg1:tt, $fmt:expr, $($arg:tt)*) => (
println!("{}", tinfof!($arg1, $fmt, $($arg)*));
);
}
fn setup_dictionary_attack(pool: &mut Scheduler, args: Dict, config: &Arc<Config>) -> Result<usize> {
let users = utils::load_list(&args.users)
.context("Failed to load users")?;
tinfo!("[+]", "loaded {} users", users.len());
let passwords = utils::load_list(&args.passwords)
.context("Failed to load passwords")?;
tinfo!("[+]", "loaded {} passwords", passwords.len());
let scripts = utils::load_scripts(args.scripts, config)
.context("Failed to load scripts")?;
tinfo!("[+]", "loaded {} scripts", scripts.len());
let attempts = users.len() * passwords.len() * scripts.len();
tinfo!("[*]", "submitting {} jobs to threadpool with {} workers", attempts, pool.max_count());
for user in &users {
for password in &passwords {
for script in &scripts {
let attempt = Attempt::new(user, password, script);
pool.run(attempt);
}
}
}
Ok(attempts)
}
fn setup_credential_confirmation(pool: &mut Scheduler, args: Creds, config: &Arc<Config>) -> Result<usize> {
let creds = utils::load_combolist(&args.creds)?;
tinfo!("[+]", "loaded {} credentials", creds.len());
let scripts = utils::load_scripts(args.scripts, config)
.context("Failed to load scripts")?;
tinfo!("[+]", "loaded {} scripts", scripts.len());
let attempts = creds.len() * scripts.len();
tinfo!("[*]", "submitting {} jobs to threadpool with {} workers", attempts, pool.max_count());
for cred in creds {
// TODO: optimization if we only have once script
for script in &scripts {
let attempt = Attempt::bytes(&cred, script);
pool.run(attempt);
}
}
Ok(attempts)
}
fn setup_enum_attack(pool: &mut Scheduler, args: Enum, config: &Arc<Config>) -> Result<usize> {
let users = utils::load_list(&args.users)
.context("Failed to load users")?;
tinfo!("[+]", "loaded {} users", users.len());
let scripts = utils::load_scripts(args.scripts, config)
.context("Failed to load scripts")?;
tinfo!("[+]", "loaded {} scripts", scripts.len());
let attempts = users.len() * scripts.len();
tinfo!("[*]", "submitting {} jobs to threadpool with {} workers", attempts, pool.max_count());
for user in &users {
for script in &scripts {
let attempt = Attempt::enumerate(user, script);
pool.run(attempt);
}
}
Ok(attempts)
}
fn run_oneshot(oneshot: Oneshot, config: Arc<Config>) -> Result<()> {
let script = Script::load(&oneshot.script, config)?;
let user = oneshot.user;
let valid = match oneshot.password {
Some(ref password) => script.run_creds(&user, password)?,
None => script.run_enum(&user)?,
};
if valid {
match oneshot.password {
Some(ref password) => println!("{}", format_valid_creds(script.descr(), &user, password)),
None => println!("{}", format_valid_enum(script.descr(), &user)),
}
} else if oneshot.exitcode {
std::process::exit(2);
}
Ok(())
}
fn format_valid_creds(script: &str, user: &str, password: &str) -> String {
format!("{} {}({}) => {:?}:{:?}", "[+]".bold(), "valid".green(),
script.yellow(), user, password)
}
fn format_valid_enum(script: &str, user: &str) -> String {
format!("{} {}({}) => {:?}", "[+]".bold(), "valid".green(),
script.yellow(), user)
}
fn main() -> Result<()> {
let args = Args::from_args();
let env = env_logger::Env::default();
let env = match args.verbose {
0 => env.filter_or("RUST_LOG", "warn"),
1 => env.filter_or("RUST_LOG", "info"),
_ => env.filter_or("RUST_LOG", "debug"),
};
env_logger::init_from_env(env);
warn!("badtouch has been renamed to authoscope, please use the new binary name instead");
if atty::isnt(atty::Stream::Stdout) {
colored::control::SHOULD_COLORIZE.set_override(false);
}
let config = Arc::new(Config::load()?);
#[cfg(target_os="linux")]
authoscope::ulimit::set_nofile(&config)
.context("Failed to set RLIMIT_NOFILE")?;
let mut pool = Scheduler::new(args.workers);
let mut report = Report::open(args.output)?;
let attempts = match args.subcommand {
SubCommand::Dict(dict) => setup_dictionary_attack(&mut pool, dict, &config)?,
SubCommand::Creds(creds) => setup_credential_confirmation(&mut pool, creds, &config)?,
SubCommand::Enum(enumerate) => setup_enum_attack(&mut pool, enumerate, &config)?,
SubCommand::Oneshot(oneshot) => return run_oneshot(oneshot, config),
SubCommand::Fsck(fsck) => return fsck::run_fsck(&args::Fsck {
paths: fsck.paths,
quiet: fsck.quiet,
require_colon: fsck.require_colon,
silent: fsck.silent,
}),
SubCommand::Completions(completions) => return completions.gen(),
};
let tx = pool.tx();
thread::spawn(move || {
let kb = Keyboard::new();
loop {
let key = kb.get();
tx.send(Msg::Key(key)).expect("failed to send key");
}
});
let mut pb = ProgressBar::new(attempts as u64);
pb.print_help();
pb.tick();
pool.resume();
let start = Instant::now();
let mut valid = 0;
let mut retries = 0;
let mut expired = 0;
while pool.has_work() {
match pool.recv() {
Msg::Key(key) => {
match key {
Key::H => pb.print_help(),
Key::P => {
pb.writeln(format!("{} {}", "[*]".bold(), "pausing threads".dimmed()));
pool.pause();
},
Key::R => {
pb.writeln(format!("{} {}", "[*]".bold(), "resuming threads".dimmed()));
pool.resume();
},
Key::Plus => {
let num = pool.incr();
pb.writeln(format!("{} {}", "[*]".bold(), format!("increased to {} threads", num).dimmed()));
},
Key::Minus => {
let num = pool.decr();
pb.writeln(format!("{} {}", "[*]".bold(), format!("decreased to {} threads", num).dimmed()));
},
}
pb.tick();
},
Msg::Attempt(mut attempt, result) => {
match result {
Ok(is_valid) => {
if is_valid {
match attempt.creds {
scheduler::Creds::Enum(_) => {
let user = attempt.user();
let script = attempt.script.descr();
pb.writeln(format_valid_enum(script, user));
report.write_enum(user, script)?;
},
_ => {
let user = attempt.user();
let password = attempt.password();
let script = attempt.script.descr();
pb.writeln(format_valid_creds(script, user, password));
report.write_creds(user, password, script)?;
},
};
valid += 1;
}
pb.inc();
},
Err(err) => {
pb.writeln(format!("{} {}({}, {}): {:?}", "[!]".bold(), "error".red(), attempt.script.descr().yellow(), format!("{:?}:{:?}", attempt.user(), attempt.password()).dimmed(), err));
if attempt.ttl > 0 {
// we have retries left
retries += 1;
attempt.ttl -= 1;
pool.run(*attempt);
pb.tick();
} else {
// giving up
expired += 1;
pb.inc();
}
}
};
},
}
}
let elapsed = start.elapsed();
let average = elapsed / attempts as u32;
pb.finish_replace(tinfof!("[+]", "found {} valid credentials with {} attempts and {} retries after {} and on average {} per attempt. {} attempts expired.\n",
valid, attempts, retries,
humantime::format_duration(elapsed),
humantime::format_duration(average),
expired,
));
Keyboard::reset();
Ok(())
}
================================================
FILE: src/config.rs
================================================
use crate::errors::*;
use serde::{Serialize, Deserialize};
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Config {
#[serde(default)]
pub runtime: RuntimeConfig,
}
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RuntimeConfig {
#[serde(default)]
pub user_agent: Option<String>,
#[serde(default)]
pub rlimit_nofile: Option<u64>,
}
impl Config {
pub fn load() -> Result<Config> {
let home = dirs::home_dir()
.ok_or_else(|| format_err!("home folder not found"))?;
for name in &["authoscope", "badtouch"] {
let path = home.join(&format!(".config/{}.toml", name));
if path.exists() {
return Config::from_file(path);
}
}
Ok(Config::default())
}
#[inline]
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
let mut file = File::open(path)?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
Config::try_from_str(&buf)
}
#[inline]
pub fn try_from_str(buf: &str) -> Result<Config> {
let config = toml::from_str(buf)?;
Ok(config)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_empty() {
let config = Config::try_from_str("").unwrap();
assert_eq!(config, Config::default());
}
}
================================================
FILE: src/ctx.rs
================================================
use crate::hlua::{self, AnyLuaValue};
use crate::errors::*;
use crate::runtime;
use std::fs::File;
use std::sync::{Arc, Mutex};
use std::io::prelude::*;
use std::collections::HashMap;
use crate::http::{HttpSession,
HttpRequest,
RequestOptions};
use crate::config::Config;
use crate::sockets::Socket;
use crate::utils;
#[derive(Debug, Clone)]
pub struct State {
config: Arc<Config>,
error: Arc<Mutex<Option<Error>>>,
http_sessions: Arc<Mutex<HashMap<String, HttpSession>>>,
mysql_sessions: Arc<Mutex<HashMap<String, Arc<Mutex<mysql::Conn>>>>>,
socket_sessions: Arc<Mutex<HashMap<String, Arc<Mutex<Socket>>>>>,
}
impl State {
pub fn new(config: Arc<Config>) -> State {
State {
config,
error: Arc::new(Mutex::new(None)),
http_sessions: Arc::new(Mutex::new(HashMap::new())),
mysql_sessions: Arc::new(Mutex::new(HashMap::new())),
socket_sessions: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn last_error(&self) -> Option<String> {
let lock = self.error.lock().unwrap();
lock.as_ref().map(|err| err.to_string())
}
pub fn clear_error(&self) {
let mut lock = self.error.lock().unwrap();
*lock = None;
}
pub fn set_error<I: Into<Error>>(&self, err: I) -> Error {
let err = err.into();
let mut mtx = self.error.lock().unwrap();
let cp = err.to_string();
*mtx = Some(err);
format_err!("{}", cp) // TODO: refactor
}
#[inline]
fn random_id(&self) -> String {
utils::random_string(16)
}
pub fn register_in_jar(&self, session: &str, cookies: Vec<(String, String)>) {
let mut mtx = self.http_sessions.lock().unwrap();
if let Some(session) = mtx.get_mut(session) {
session.cookies.register_in_jar(cookies);
}
}
pub fn http_mksession(&self) -> String {
let mut mtx = self.http_sessions.lock().unwrap();
let (id, session) = HttpSession::new();
mtx.insert(id.clone(), session);
id
}
pub fn http_request(&self, session_id: &str, method: String, url: String, options: RequestOptions) -> HttpRequest {
let mtx = self.http_sessions.lock().unwrap();
let session = mtx.get(session_id).expect("invalid session reference"); // TODO
HttpRequest::new(&self.config, session, method, url, options)
}
pub fn mysql_register(&self, sock: mysql::Conn) -> String {
let mut mtx = self.mysql_sessions.lock().unwrap();
let id = self.random_id();
let sock = Arc::new(Mutex::new(sock));
mtx.insert(id.clone(), sock);
id
}
pub fn mysql_session(&self, id: &str) -> Arc<Mutex<mysql::Conn>> {
let mtx = self.mysql_sessions.lock().unwrap();
let sock = mtx.get(id).expect("invalid session reference"); // TODO
sock.clone()
}
pub fn sock_connect(&self, host: &str, port: u16) -> Result<String> {
let mut mtx = self.socket_sessions.lock().unwrap();
let id = self.random_id();
let sock = Socket::connect(host, port)?;
mtx.insert(id.clone(), Arc::new(Mutex::new(sock)));
Ok(id)
}
pub fn get_sock(&self, id: &str)-> Arc<Mutex<Socket>> {
let mtx = self.socket_sessions.lock().unwrap();
let sock = mtx.get(id).expect("invalid session reference"); // TODO
sock.clone()
}
}
#[derive(Debug, Clone)]
pub struct Script {
descr: String,
code: String,
config: Arc<Config>,
}
impl Script {
pub fn load(path: &str, config: Arc<Config>) -> Result<Script> {
let mut file = File::open(path)?;
Script::load_from(&mut file, config)
}
pub fn load_from<R: Read>(mut src: R, config: Arc<Config>) -> Result<Script> {
let mut code = String::new();
src.read_to_string(&mut code)?;
let (mut lua, _) = Script::ctx(&config);
lua.execute::<()>(&code)?;
let descr = {
let descr: Result<_> = lua.get("descr").ok_or_else(|| format_err!("descr undefined"));
let descr: hlua::StringInLua<_> = descr?;
(*descr).to_owned()
};
{
let verify: Result<_> = lua.get("verify").ok_or_else(|| format_err!("verify undefined"));
let _: hlua::LuaFunction<_> = verify?;
};
Ok(Script {
descr,
code,
config,
})
}
fn ctx<'a>(config: &Arc<Config>) -> (hlua::Lua<'a>, State) {
let mut lua = hlua::Lua::new();
lua.open_string();
let state = State::new(config.clone());
runtime::base64_decode(&mut lua, state.clone());
runtime::base64_encode(&mut lua, state.clone());
runtime::bcrypt(&mut lua, state.clone());
runtime::bcrypt_verify(&mut lua, state.clone());
runtime::clear_err(&mut lua, state.clone());
runtime::execve(&mut lua, state.clone());
runtime::hex(&mut lua, state.clone());
runtime::hmac_md5(&mut lua, state.clone());
runtime::hmac_sha1(&mut lua, state.clone());
runtime::hmac_sha2_256(&mut lua, state.clone());
runtime::hmac_sha2_512(&mut lua, state.clone());
runtime::hmac_sha3_256(&mut lua, state.clone());
runtime::hmac_sha3_512(&mut lua, state.clone());
runtime::html_select(&mut lua, state.clone());
runtime::html_select_list(&mut lua, state.clone());
runtime::http_basic_auth(&mut lua, state.clone()); // TODO: deprecate?
runtime::http_mksession(&mut lua, state.clone());
runtime::http_request(&mut lua, state.clone());
runtime::http_send(&mut lua, state.clone());
runtime::json_decode(&mut lua, state.clone());
runtime::json_encode(&mut lua, state.clone());
runtime::last_err(&mut lua, state.clone());
runtime::ldap_bind(&mut lua, state.clone());
runtime::ldap_escape(&mut lua, state.clone());
runtime::ldap_search_bind(&mut lua, state.clone());
runtime::md5(&mut lua, state.clone());
runtime::mysql_connect(&mut lua, state.clone());
runtime::mysql_query(&mut lua, state.clone());
runtime::print(&mut lua, state.clone());
runtime::rand(&mut lua, state.clone());
runtime::randombytes(&mut lua, state.clone());
runtime::sha1(&mut lua, state.clone());
runtime::sha2_256(&mut lua, state.clone());
runtime::sha2_512(&mut lua, state.clone());
runtime::sha3_256(&mut lua, state.clone());
runtime::sha3_512(&mut lua, state.clone());
runtime::sleep(&mut lua, state.clone());
runtime::sock_connect(&mut lua, state.clone());
runtime::sock_send(&mut lua, state.clone());
runtime::sock_recv(&mut lua, state.clone());
runtime::sock_sendline(&mut lua, state.clone());
runtime::sock_recvline(&mut lua, state.clone());
runtime::sock_recvall(&mut lua, state.clone());
runtime::sock_recvline_contains(&mut lua, state.clone());
runtime::sock_recvline_regex(&mut lua, state.clone());
runtime::sock_recvn(&mut lua, state.clone());
runtime::sock_recvuntil(&mut lua, state.clone());
runtime::sock_sendafter(&mut lua, state.clone());
runtime::sock_newline(&mut lua, state.clone());
(lua, state)
}
#[inline]
pub fn descr(&self) -> &str {
self.descr.as_str()
}
/*
#[inline]
pub fn code(&self) -> &str {
self.code.as_str()
}
*/
pub fn run_once(&self, user: AnyLuaValue, password: AnyLuaValue) -> Result<bool> {
debug!("executing {:?} with {:?}:{:?}", self.descr(), user, password);
let (mut lua, state) = Script::ctx(&self.config);
lua.execute::<()>(&self.code)?;
let verify: Result<_> = lua.get("verify").ok_or_else(|| format_err!("verify undefined"));
let mut verify: hlua::LuaFunction<_> = verify?;
let result: hlua::AnyLuaValue = match verify.call_with_args((user, password)) {
Ok(res) => res,
Err(err) => {
bail!("execution failed: {:?}", err);
},
};
if let Some(err) = state.error.lock().unwrap().take() {
return Err(err);
}
use crate::hlua::AnyLuaValue::*;
match result {
LuaBoolean(x) => Ok(x),
LuaString(x) => Err(format_err!("error: {:?}", x)),
x => Err(format_err!("lua returned wrong type: {:?}", x)),
}
}
#[inline]
pub fn run_creds(&self, user: &str, password: &str) -> Result<bool> {
let user = AnyLuaValue::LuaString(user.to_string());
let password = AnyLuaValue::LuaString(password.to_string());
self.run_once(user, password)
}
#[inline]
pub fn run_enum(&self, user: &str) -> Result<bool> {
let user = AnyLuaValue::LuaString(user.to_string());
let password = AnyLuaValue::LuaNil;
self.run_once(user, password)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn empty_config() -> Arc<Config> {
Arc::new(Config::default())
}
#[test]
fn verify_false() {
let script = Script::load_from(r#"
descr = "verify_false"
function verify(user, password)
return false
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("foo", "bar").expect("test script failed");
assert!(!result);
}
#[test]
fn verify_true() {
let script = Script::load_from(r#"
descr = "verify_false"
function verify(user, password)
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("foo", "bar").expect("test script failed");
assert!(result);
}
#[test]
fn verify_record_error() {
let script = Script::load_from(r#"
descr = "json"
function verify(user, password)
json_decode("{{{{{{{{{{{{{{{{{{")
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x");
assert!(result.is_err());
}
#[test]
fn verify_clear_recorded_error() {
let script = Script::load_from(r#"
descr = "json"
function verify(user, password)
json_decode("{{{{{{{{{{{{{{{{{{")
clear_err()
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_sleep() {
let script = Script::load_from(r#"
descr = "slow script"
function verify(user, password)
sleep(1)
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("foo", "bar").expect("test script failed");
assert!(result);
}
#[test]
fn verify_basic_auth_correct() {
let script = Script::load_from(r#"
descr = "basic auth httpbin.org"
function verify(user, password)
return http_basic_auth("https://httpbin.org/basic-auth/foo/buzz", user, password)
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("foo", "buzz").expect("test script failed");
assert!(result);
}
#[test]
fn verify_basic_auth_incorrect() {
let script = Script::load_from(r#"
descr = "basic auth httpbin.org"
function verify(user, password)
return http_basic_auth("https://httpbin.org/basic-auth/foo/buzz", user, password)
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("invalid", "wrong").expect("test script failed");
assert!(!result);
}
#[test]
fn verify_cookies() {
let script = Script::load_from(r#"
descr = "cookies httpbin.org"
function verify(user, password)
session = http_mksession()
req = http_request(session, 'GET', 'https://httpbin.org/cookies/set/foo/; as=df', {})
resp = http_send(req)
if last_err() then return end
req = http_request(session, 'GET', 'https://httpbin.org/cookies/set/fizz/buzz', {})
resp = http_send(req)
if last_err() then return end
req = http_request(session, 'GET', 'https://httpbin.org/cookies', {})
resp = http_send(req)
if last_err() then return end
o = json_decode(resp['text'])
if last_err() then return end
print(o)
if o['cookies']['foo'] ~= '; as=df' then
return 'Unexpected value for foo cookie'
end
if o['cookies']['fizz'] ~= 'buzz' then
return 'Unexpected value for fizz cookie'
end
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("invalid", "wrong").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hex() {
let script = Script::load_from(r#"
descr = "hex test"
function verify(user, password)
x = hex({0x6F, 0x68, 0x61, 0x69, 0x0A, 0x00})
return x == "6f6861690a00"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hex_empty() {
let script = Script::load_from(r#"
descr = "hex test"
function verify(user, password)
x = hex({})
return x == ""
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_json_encode() {
let script = Script::load_from(r#"
descr = "json"
function verify(user, password)
json_encode({
hello="world",
almost_one=0.9999,
list={1,3,3,7},
data={
user=user,
password=password,
empty=nil
}
})
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_json_encode_decode() {
let script = Script::load_from(r#"
descr = "json"
function verify(user, password)
x = json_encode({
hello="world",
almost_one=0.9999,
list={1,3,3,7},
data={
user=user,
password=password,
empty=nil
}
})
json_decode(x)
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_json_decode_valid() {
let script = Script::load_from(r#"
descr = "json"
function verify(user, password)
json_decode("{\"almost_one\":0.9999,\"data\":{\"password\":\"fizz\",\"user\":\"bar\"},\"hello\":\"world\",\"list\":[1,3,3,7]}")
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_json_decode_invalid() {
let script = Script::load_from(r#"
descr = "json"
function verify(user, password)
json_decode("{\"almost_one\":0.9999,\"data\":{\"password\":\"fizz\",\"user\":\"bar\"}}}}}}}}}")
return true
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x");
assert!(result.is_err());
}
#[test]
fn verify_hmac_md5() {
let script = Script::load_from(r#"
descr = "hmac_md5"
function verify(user, password)
x = hex(hmac_md5("foo", "bar"))
-- print('md5: ' .. x)
return x == "0c7a250281315ab863549f66cd8a3a53"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hmac_sha1() {
let script = Script::load_from(r#"
descr = "hmac_sha1"
function verify(user, password)
x = hex(hmac_sha1("foo", "bar"))
-- print('sha1: ' .. x)
return x == "46b4ec586117154dacd49d664e5d63fdc88efb51"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hmac_sha2_256() {
let script = Script::load_from(r#"
descr = "hmac_sha2_256"
function verify(user, password)
x = hex(hmac_sha2_256("foo", "bar"))
-- print('sha2_256: ' .. x)
return x == "f9320baf0249169e73850cd6156ded0106e2bb6ad8cab01b7bbbebe6d1065317"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hmac_sha2_512() {
let script = Script::load_from(r#"
descr = "hmac_sha2_512"
function verify(user, password)
x = hex(hmac_sha2_512("foo", "bar"))
-- print('sha2_512: ' .. x)
return x == "114682914c5d017dfe59fdc804118b56a3a652a0b8870759cf9e792ed7426b08197076bf7d01640b1b0684df79e4b67e37485669e8ce98dbab60445f0db94fce"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hmac_sha3_256() {
let script = Script::load_from(r#"
descr = "hmac_sha3_256"
function verify(user, password)
x = hex(hmac_sha3_256("foo", "bar"))
-- print('sha3_256: ' .. x)
return x == "a7dc3fbbd45078239f0cb321e6902375d22b505f2c48722eb7009e7da2574893"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_hmac_sha3_512() {
let script = Script::load_from(r#"
descr = "hmac_sha3_512"
function verify(user, password)
x = hex(hmac_sha3_512("foo", "bar"))
-- print('sha3_512: ' .. x)
return x == "2da91b8227d106199fd06c5d8a6752796cf3c84dde5a427bd2aca384f0cffc19997e2584ed15c55542c2cb8918b987e2bcd9e77a9f3fdbb4dbea8a3d0136da2f"
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "x").expect("test script failed");
assert!(result);
}
#[test]
fn verify_bcrypt_verify() {
let script = Script::load_from(r#"
descr = "bcrypt_verify"
function verify(user, password)
return bcrypt_verify(password, "$2a$12$ByUlHCHx3rxMsdQONpuFbulQqut6GQ/84I5EAUkCqTTI07JA7wUju")
end
"#.as_bytes(), empty_config()).unwrap();
let result = script.run_creds("x", "hunter2").expect("test script failed");
assert!(result);
}
}
================================================
FILE: src/db/mod.rs
================================================
pub mod mysql;
================================================
FILE: src/db/mysql.rs
================================================
use crate::hlua::{AnyHashableLuaValue, AnyLuaValue};
use std::collections::HashMap;
use crate::structs::LuaMap;
impl From<mysql::Params> for LuaMap {
fn from(params: mysql::Params) -> LuaMap {
match params {
mysql::Params::Empty => LuaMap::new(),
mysql::Params::Named(map) => {
map.into_iter()
.map(|(k, v)| (AnyHashableLuaValue::LuaString(k), mysql_value_to_lua(v)))
.collect::<HashMap<AnyHashableLuaValue, AnyLuaValue>>()
.into()
},
mysql::Params::Positional(_) => unimplemented!(),
}
}
}
impl From<LuaMap> for mysql::Params {
fn from(x: LuaMap) -> mysql::Params {
if x.is_empty() {
mysql::Params::Empty
} else {
let mut params = HashMap::default();
for (k, v) in x {
if let AnyHashableLuaValue::LuaString(k) = k {
params.insert(k, lua_to_mysql_value(v));
} else {
panic!("unsupported keys in map");
}
}
mysql::Params::Named(params)
}
}
}
fn lua_to_mysql_value(value: AnyLuaValue) -> mysql::Value {
match value {
AnyLuaValue::LuaString(x) => mysql::Value::Bytes(x.into_bytes()),
AnyLuaValue::LuaAnyString(x) => mysql::Value::Bytes(x.0),
AnyLuaValue::LuaNumber(v) => if v % 1f64 == 0f64 {
mysql::Value::Int(v as i64)
} else {
mysql::Value::Float(v as f32)
},
AnyLuaValue::LuaBoolean(x) => mysql::Value::Int(if x { 1 } else { 0 }),
AnyLuaValue::LuaArray(_x) => unimplemented!(),
AnyLuaValue::LuaNil => mysql::Value::NULL,
AnyLuaValue::LuaOther => unimplemented!(),
}
}
pub fn mysql_value_to_lua(value: mysql::Value) -> AnyLuaValue {
use mysql::Value::*;
match value {
NULL => AnyLuaValue::LuaNil,
Bytes(bytes) => AnyLuaValue::LuaString(String::from_utf8(bytes).unwrap()),
Int(i) => AnyLuaValue::LuaNumber(i as f64),
UInt(i) => AnyLuaValue::LuaNumber(i as f64),
Float(i) => AnyLuaValue::LuaNumber(i as f64),
Double(i) => AnyLuaValue::LuaNumber(i as f64),
Date(_, _, _, _, _, _, _) => unimplemented!(),
Time(_, _, _, _, _, _) => unimplemented!(),
}
}
================================================
FILE: src/errors.rs
================================================
pub use anyhow::{anyhow, bail, format_err, Context, Error, Result};
pub use log::{trace, debug, info, warn, error};
================================================
FILE: src/fsck.rs
================================================
use crate::errors::Result;
use crate::args::Fsck;
use std::fs::File;
use std::io;
use std::io::BufReader;
use std::io::BufWriter;
use std::io::prelude::*;
use std::str;
fn validate_file(path: &str, args: &Fsck) -> Result<()> {
let f = File::open(path)?;
let mut file = BufReader::new(&f);
let mut out = BufWriter::new(io::stdout());
let mut i = 0;
let mut buf = Vec::new();
const DELIM: u8 = b'\n';
while 0 < file.read_until(DELIM, &mut buf)? {
/*
not removing the \n so we don't have to append it later
if buf[buf.len() - 1] == DELIM {
buf.pop();
}
*/
// TODO: remove empty lines?
match str::from_utf8(&buf) {
Ok(line) => {
if !args.require_colon || buf.iter().any(|x| *x == b':') {
if !args.silent {
out.write_all(line.as_bytes())?;
}
} else if !args.quiet {
eprintln!("Invalid(line {}): {:?}",
i,
line);
}
},
Err(_) => {
if !args.quiet {
eprintln!("Invalid(line {}): {:?} {:?}",
i,
String::from_utf8_lossy(&buf),
buf);
}
},
};
buf.clear();
i += 1;
}
// Close the BufWriter to flush it
let _ = out.into_inner()?;
Ok(())
}
pub fn run_fsck(args: &Fsck) -> Result<()> {
for path in &args.paths {
validate_file(path, args)?;
}
Ok(())
}
================================================
FILE: src/html.rs
================================================
use crate::errors::*;
use kuchiki::traits::TendrilSink;
use std::collections::HashMap;
use crate::hlua::AnyLuaValue;
use crate::structs::LuaMap;
#[derive(Debug, PartialEq)]
pub struct Element {
attrs: HashMap<String, String>,
text: String,
}
impl From<Element> for AnyLuaValue {
fn from(x: Element) -> AnyLuaValue {
let mut map = LuaMap::new();
map.insert_str("text", x.text);
map.insert("attrs", LuaMap::from(x.attrs));
map.into()
}
}
fn transform_element(entry: &kuchiki::NodeDataRef<kuchiki::ElementData>) -> Element {
let text = entry.text_contents();
let as_node = entry.as_node();
let mut attrs: HashMap<String, String> = HashMap::new();
if let Some(element) = as_node.as_element() {
for (k, v) in &element.attributes.borrow().map {
attrs.insert(k.local.to_string(), v.value.clone());
}
}
Element {
attrs,
text,
}
}
pub fn html_select(html: &str, selector: &str) -> Result<Element> {
let doc = kuchiki::parse_html().one(html);
match doc.select_first(selector) {
Ok(x) => Ok(transform_element(&x)),
Err(_) => bail!("css selector failed"),
}
}
pub fn html_select_list(html: &str, selector: &str) -> Result<Vec<Element>> {
let doc = kuchiki::parse_html().one(html);
match doc.select(selector) {
Ok(x) => Ok(x.into_iter().map(|x| transform_element(&x)).collect()),
Err(_) => bail!("css selector failed"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_html_select() {
let elems = html_select(r#"<html><div id="yey">content</div></html>"#, "#yey").unwrap();
assert_eq!(elems,
Element {
attrs: vec![(String::from("id"), String::from("yey"))].into_iter().collect(),
text: "content".into(),
}
);
}
#[test]
fn test_html_select_list() {
let elems = html_select_list(r#"<html><div id="yey">content</div></html>"#, "#yey").unwrap();
assert_eq!(elems, vec![
Element {
attrs: vec![(String::from("id"), String::from("yey"))].into_iter().collect(),
text: "content".into(),
}
]);
}
}
================================================
FILE: src/http.rs
================================================
use crate::errors::*;
use crate::structs::LuaMap;
use reqwest::Method;
use reqwest::header::{HeaderName, HeaderValue, COOKIE, SET_COOKIE, USER_AGENT};
use reqwest::redirect;
use crate::hlua::AnyLuaValue;
use crate::json::LuaJsonValue;
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::Arc;
use crate::config::Config;
use crate::ctx::State;
use crate::utils;
#[derive(Debug)]
pub struct HttpSession {
id: String,
pub cookies: CookieJar,
}
impl HttpSession {
pub fn new() -> (String, HttpSession) {
let id = utils::random_string(16);
(id.clone(), HttpSession {
id,
cookies: CookieJar::default(),
})
}
}
#[derive(Debug, Default, Deserialize)]
pub struct RequestOptions {
query: Option<HashMap<String, String>>,
headers: Option<HashMap<String, String>>,
basic_auth: Option<(String, String)>,
user_agent: Option<String>,
json: Option<serde_json::Value>,
form: Option<serde_json::Value>,
body: Option<String>,
}
impl RequestOptions {
pub fn try_from(x: AnyLuaValue) -> Result<RequestOptions> {
let x = LuaJsonValue::from(x);
let x = serde_json::from_value(x.into())?;
Ok(x)
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct HttpRequest {
// reference to the HttpSession
session: String,
cookies: CookieJar,
method: String,
url: String,
query: Option<HashMap<String, String>>,
headers: Option<HashMap<String, String>>,
basic_auth: Option<(String, String)>,
user_agent: Option<String>,
body: Option<Body>,
}
impl HttpRequest {
pub fn new(config: &Arc<Config>, session: &HttpSession, method: String, url: String, options: RequestOptions) -> HttpRequest {
let cookies = session.cookies.clone();
let user_agent = options.user_agent.or_else(|| config.runtime.user_agent.clone());
let mut request = HttpRequest {
session: session.id.clone(),
cookies,
method,
url,
query: options.query,
headers: options.headers,
basic_auth: options.basic_auth,
user_agent,
body: None,
};
if let Some(json) = options.json {
request.body = Some(Body::Json(json));
}
if let Some(form) = options.form {
request.body = Some(Body::Form(form));
}
if let Some(text) = options.body {
request.body = Some(Body::Raw(text));
}
request
}
pub fn send(&self, state: &State) -> Result<LuaMap> {
debug!("http send: {:?}", self);
let client = reqwest::blocking::Client::builder()
.redirect(redirect::Policy::none()) // TODO: this should be configurable
.build().unwrap();
let method = self.method.parse::<Method>()
.context("Invalid http method")?;
let mut req = client.request(method, &self.url);
if let Some(cookies) = self.cookies.assemble_cookie_header() {
debug!("Adding cookies to request: {:?}", cookies);
req = req.header(COOKIE, HeaderValue::from_str(&cookies)?);
}
if let Some(ref agent) = self.user_agent {
req = req.header(USER_AGENT, agent.as_str());
}
if let Some(ref auth) = self.basic_auth {
let &(ref user, ref password) = auth;
req = req.basic_auth(user, Some(password));
}
if let Some(ref headers) = self.headers {
for (k, v) in headers {
let k = HeaderName::from_bytes(k.as_bytes())?;
req = req.header(k, HeaderValue::from_str(v)?);
}
}
if let Some(ref query) = self.query {
req = req.query(query);
}
req = match self.body {
Some(Body::Raw(ref x)) => { req.body(x.clone()) },
Some(Body::Form(ref x)) => { req.form(x) },
Some(Body::Json(ref x)) => { req.json(x) },
None => req,
};
info!("http req: {:?}", req);
let res = req.send()?;
info!("http res: {:?}", res);
let mut resp = LuaMap::new();
let status = res.status();
resp.insert_num("status", f64::from(status.as_u16()));
{
let cookies = res.headers().get_all(SET_COOKIE);
HttpRequest::register_cookies_on_state(&self.session, state, &cookies)
.context("Failed to process http response cookies")?;
}
let mut headers = LuaMap::new();
for (name, value) in res.headers().iter() {
headers.insert_str(name.as_str().to_lowercase(), value.to_str()?);
}
resp.insert("headers", headers);
if let Ok(text) = res.text() {
resp.insert_str("text", text);
}
Ok(resp)
}
fn register_cookies_on_state(session: &str, state: &State, cookies: &reqwest::header::GetAll<HeaderValue>) -> Result<()> {
let mut jar = Vec::new();
for cookie in cookies.iter() {
let cookie = cookie.to_str()?;
let mut key = String::new();
let mut value = String::new();
let mut in_key = true;
for c in cookie.chars() {
match c {
'=' if in_key => in_key = false,
';' => break,
c if in_key => key.push(c),
c => value.push(c),
}
}
jar.push((key, value));
}
state.register_in_jar(session, jar);
Ok(())
}
}
impl HttpRequest {
pub fn try_from(x: AnyLuaValue) -> Result<HttpRequest> {
let x = LuaJsonValue::from(x);
let x = serde_json::from_value(x.into())?;
Ok(x)
}
}
impl From<HttpRequest> for AnyLuaValue {
fn from(x: HttpRequest) -> AnyLuaValue {
let v = serde_json::to_value(&x).unwrap();
LuaJsonValue::from(v).into()
}
}
// see https://github.com/seanmonstar/reqwest/issues/14 for proper cookie jars
// maybe change this to reqwest::header::Cookie
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct CookieJar(HashMap<String, String>);
impl CookieJar {
pub fn register_in_jar(&mut self, cookies: Vec<(String, String)>) {
for (key, value) in cookies {
self.0.insert(key, value);
}
}
pub fn assemble_cookie_header(&self) -> Option<String> {
if self.is_empty() {
return None;
}
let mut cookies: Vec<String> = Vec::new();
for (key, value) in self.iter() {
let value = if value.contains(' ') || value.contains(';') {
self.escape_cookie_value(value)
} else {
value.to_owned()
};
let cookie = format!("{}={}", key, value);
debug!("Adding cookie: {:?}", cookie);
cookies.push(cookie);
}
Some(cookies.join("; "))
}
fn escape_cookie_value(&self, value: &str) -> String {
value.chars()
.fold(String::new(), |mut s, c| {
match c {
';' => s.push_str("\\073"),
c => s.push(c),
}
s
})
}
}
impl Deref for CookieJar {
type Target = HashMap<String, String>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Serialize, Deserialize)]
pub enum Body {
Raw(String), // TODO: maybe Vec<u8>
Form(serde_json::Value),
Json(serde_json::Value),
}
================================================
FILE: src/json.rs
================================================
use crate::errors::*;
use crate::hlua::AnyLuaValue;
use serde_json::{self, Value, Number};
use std::collections::HashMap;
pub fn decode(x: &str) -> Result<AnyLuaValue> {
let v: Value = serde_json::from_str(x)
.context("deserialize failed")?;
let v: LuaJsonValue = v.into();
Ok(v.into())
}
pub fn encode(v: AnyLuaValue) -> Result<String> {
let v: LuaJsonValue = v.into();
let v: Value = v.into();
let s = serde_json::to_string(&v)
.context("Serialize failed")?;
Ok(s)
}
pub fn lua_array_is_list(array: &[(AnyLuaValue, AnyLuaValue)]) -> bool {
if !array.is_empty() {
let first = &array[0];
matches!(first.0, AnyLuaValue::LuaNumber(_))
} else {
// true // TODO: this breaks unserialize
false
}
}
#[derive(Debug)]
pub enum LuaJsonValue {
Null,
Bool(bool),
Number(Number),
String(String),
Array(Vec<LuaJsonValue>),
Object(HashMap<String, LuaJsonValue>),
}
impl From<LuaJsonValue> for AnyLuaValue {
fn from(x: LuaJsonValue) -> AnyLuaValue {
match x {
LuaJsonValue::Null => AnyLuaValue::LuaNil,
LuaJsonValue::Bool(v) => AnyLuaValue::LuaBoolean(v),
// TODO: not sure if this might fail
LuaJsonValue::Number(v) => AnyLuaValue::LuaNumber(v.as_f64().unwrap()),
LuaJsonValue::String(v) => AnyLuaValue::LuaString(v),
LuaJsonValue::Array(v) => AnyLuaValue::LuaArray(v.into_iter().enumerate()
.map(|(i, x)| (AnyLuaValue::LuaNumber(i as f64), x.into()))
.collect()
),
LuaJsonValue::Object(v) => AnyLuaValue::LuaArray(v.into_iter()
.map(|(k, v)| (AnyLuaValue::LuaString(k), v.into()))
.collect()
),
}
}
}
impl From<AnyLuaValue> for LuaJsonValue {
fn from(x: AnyLuaValue) -> LuaJsonValue {
match x {
AnyLuaValue::LuaNil => LuaJsonValue::Null,
AnyLuaValue::LuaBoolean(v) => LuaJsonValue::Bool(v),
AnyLuaValue::LuaString(v) => LuaJsonValue::String(v),
AnyLuaValue::LuaAnyString(v) => LuaJsonValue::Array(v.0.into_iter()
.map(|x| LuaJsonValue::Number(x.into()))
.collect()
),
AnyLuaValue::LuaNumber(v) => {
// this is needed or every number is detected as float
LuaJsonValue::Number(if v % 1f64 == 0f64 {
(v as u64).into()
} else {
Number::from_f64(v).expect("invalid LuaJson::Number")
})
},
AnyLuaValue::LuaArray(v) => {
if lua_array_is_list(&v) {
LuaJsonValue::Array(v.into_iter()
.map(|(_, v)| v.into())
.collect()
)
} else {
LuaJsonValue::Object(v.into_iter()
.filter_map(|(k, v)| match k {
AnyLuaValue::LuaString(k) => Some((k, v.into())),
_ => None,
})
.collect()
)
}
},
AnyLuaValue::LuaOther => LuaJsonValue::Null,
}
}
}
impl From<LuaJsonValue> for Value {
fn from(x: LuaJsonValue) -> Value {
match x {
LuaJsonValue::Null => Value::Null,
LuaJsonValue::Bool(v) => Value::Bool(v),
LuaJsonValue::Number(v) => Value::Number(v),
LuaJsonValue::String(v) => Value::String(v),
LuaJsonValue::Array(v) => Value::Array(v.into_iter()
.map(|x| x.into())
.collect()
),
LuaJsonValue::Object(v) => Value::Object(v.into_iter()
.map(|(k, v)| (k, v.into()))
.collect()
),
}
}
}
impl From<Value> for LuaJsonValue {
fn from(x: Value) -> LuaJsonValue {
match x {
Value::Null => LuaJsonValue::Null,
Value::Bool(v) => LuaJsonValue::Bool(v),
Value::Number(v) => LuaJsonValue::Number(v),
Value::String(v) => LuaJsonValue::String(v),
Value::Array(v) => LuaJsonValue::Array(v.into_iter()
.map(|x| x.into())
.collect()
),
Value::Object(v) => LuaJsonValue::Object(v.into_iter()
.map(|(k, v)| (k, v.into()))
.collect()
),
}
}
}
================================================
FILE: src/keyboard.rs
================================================
// use getch;
use getch::Getch;
#[cfg(not(windows))]
use termios::{self, tcsetattr, ICANON, ECHO};
pub struct Keyboard {
getch: Getch,
}
impl Default for Keyboard {
#[inline]
fn default() -> Keyboard {
let getch = Getch::new();
Keyboard {
getch,
}
}
}
impl Keyboard {
#[inline]
pub fn new() -> Keyboard {
Keyboard::default()
}
pub fn get(&self) -> Key {
loop {
let key = self.getch.getch();
// println!("{:?}", key);
match key {
Ok(112) => return Key::P,
Ok(114) => return Key::R,
Ok(43) => return Key::Plus,
Ok(45) => return Key::Minus,
Ok(104) => return Key::H,
_ => (),
}
}
}
// since the getch thread is orphaned, we have to cleanup manually
pub fn reset() {
#[cfg(not(windows))]
{
if let Ok(mut termios) = termios::Termios::from_fd(0) {
termios.c_lflag |= ICANON|ECHO;
tcsetattr(0,termios::TCSADRAIN, &termios).unwrap_or(());
}
}
}
}
#[derive(Debug)]
pub enum Key {
H,
P,
R,
Plus,
Minus,
}
================================================
FILE: src/lib.rs
================================================
#![allow(clippy::mutex_atomic)]
use hlua_badtouch as hlua;
pub mod args;
pub mod config;
pub mod ctx;
pub mod db;
pub mod errors;
pub mod fsck;
pub mod html;
pub mod http;
pub mod json;
pub mod keyboard;
pub mod pb;
pub mod runtime;
pub mod scheduler;
pub mod sockets;
pub mod structs;
#[cfg(target_os="linux")]
pub mod ulimit;
pub mod utils;
================================================
FILE: src/main.rs
================================================
use authoscope::args::{self, Args, SubCommand};
use authoscope::ctx::Script;
use authoscope::errors::*;
use authoscope::fsck;
use authoscope::utils;
use authoscope::config::Config;
use authoscope::pb::ProgressBar;
use authoscope::scheduler::{Scheduler, Attempt, Creds, Msg};
use authoscope::keyboard::{Keyboard, Key};
use colored::*;
use env_logger::Env;
use num_format::{Locale, ToFormattedString};
use std::thread;
use std::fs::File;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::io::prelude::*;
use structopt::StructOpt;
enum Report {
Some(File),
None
}
impl Report {
pub fn open(path: Option<String>) -> Result<Report> {
match path {
Some(path) => Ok(Report::Some(File::create(path)?)),
None => Ok(Report::None),
}
}
pub fn write_creds(&mut self, user: &str, password: &str, script: &str) -> Result<()> {
if let Report::Some(ref mut f) = *self {
writeln!(f, "{}:{}:{}", script, user, password)?;
}
Ok(())
}
pub fn write_enum(&mut self, user: &str, script: &str) -> Result<()> {
if let Report::Some(ref mut f) = *self {
writeln!(f, "{}:{}", script, user)?;
}
Ok(())
}
}
macro_rules! tinfof {
($arg1:tt, $fmt:expr, $($arg:tt)*) => (
$arg1.bold().to_string() + " " + &(format!($fmt, $($arg)*).dimmed().to_string())
);
}
macro_rules! tinfo {
($arg1:tt, $fmt:expr, $($arg:tt)*) => (
println!("{}", tinfof!($arg1, $fmt, $($arg)*));
);
}
fn setup_dictionary_attack(pool: &mut Scheduler, args: args::Dict, config: &Arc<Config>) -> Result<usize> {
let users = utils::load_list(&args.users_path)
.context("Failed to load users")?;
tinfo!("[+]", "loaded {} users", users.len());
let passwords = utils::load_list(&args.passwords_path)
.context("Failed to load passwords")?;
tinfo!("[+]", "loaded {} passwords", passwords.len());
let scripts = utils::load_scripts(args.scripts, config)
.context("Failed to load scripts")?;
tinfo!("[+]", "loaded {} scripts", scripts.len());
let attempts = users.len() * passwords.len() * scripts.len();
tinfo!("[*]", "submitting {} jobs to threadpool with {} workers",
attempts.to_formatted_string(&Locale::en),
pool.max_count());
for user in &users {
for password in &passwords {
for script in &scripts {
let attempt = Attempt::new(user, password, script);
pool.run(attempt);
}
}
}
Ok(attempts)
}
fn setup_combolist_attack(pool: &mut Scheduler, args: args::Combo, config: &Arc<Config>) -> Result<usize> {
let creds = utils::load_combolist(&args.path)?;
tinfo!("[+]", "loaded {} credentials", creds.len());
let scripts = utils::load_scripts(args.scripts, config)
.context("Failed to load scripts")?;
tinfo!("[+]", "loaded {} scripts", scripts.len());
let attempts = creds.len() * scripts.len();
tinfo!("[*]", "submitting {} jobs to threadpool with {} workers", attempts, pool.max_count());
for cred in creds {
// TODO: optimization if we only have once script
for script in &scripts {
let attempt = Attempt::bytes(&cred, script);
pool.run(attempt);
}
}
Ok(attempts)
}
fn setup_enum_attack(pool: &mut Scheduler, args: args::Enum, config: &Arc<Config>) -> Result<usize> {
let users = utils::load_list(&args.users)
.context("Failed to load users")?;
tinfo!("[+]", "loaded {} users", users.len());
let scripts = utils::load_scripts(args.scripts, config)
.context("Failed to load scripts")?;
tinfo!("[+]", "loaded {} scripts", scripts.len());
let attempts = users.len() * scripts.len();
tinfo!("[*]", "submitting {} jobs to threadpool with {} workers", attempts, pool.max_count());
for user in &users {
for script in &scripts {
let attempt = Attempt::enumerate(user, script);
pool.run(attempt);
}
}
Ok(attempts)
}
fn run_oneshot(oneshot: args::Run, config: Arc<Config>) -> Result<()> {
let script = Script::load(&oneshot.script, config)?;
let user = oneshot.user;
let valid = match oneshot.password {
Some(ref password) => script.run_creds(&user, password)?,
None => script.run_enum(&user)?,
};
if valid {
match oneshot.password {
Some(ref password) => println!("{}", format_valid_creds(script.descr(), &user, password)),
None => println!("{}", format_valid_enum(script.descr(), &user)),
}
} else if oneshot.exitcode {
std::process::exit(2);
}
Ok(())
}
fn format_valid_creds(script: &str, user: &str, password: &str) -> String {
format!("{} {}({}) => {:?}:{:?}", "[+]".bold(), "valid".green(),
script.yellow(), user, password)
}
fn format_valid_enum(script: &str, user: &str) -> String {
format!("{} {}({}) => {:?}", "[+]".bold(), "valid".green(),
script.yellow(), user)
}
fn log_filter(args: &Args) -> &'static str {
match args.verbose {
0 => "warn",
1 => "info",
_ => "debug",
}
}
fn main() -> Result<()> {
let args = Args::from_args();
env_logger::init_from_env(Env::default()
.default_filter_or(log_filter(&args)));
if atty::isnt(atty::Stream::Stdout) {
colored::control::SHOULD_COLORIZE.set_override(false);
}
let config = Arc::new(Config::load()?);
#[cfg(target_os="linux")]
authoscope::ulimit::set_nofile(&config)
.context("Failed to set RLIMIT_NOFILE")?;
let mut pool = Scheduler::new(args.workers);
let mut report = Report::open(args.output)?;
let attempts = match args.subcommand {
SubCommand::Dict(dict) => setup_dictionary_attack(&mut pool, dict, &config)?,
SubCommand::Combo(creds) => setup_combolist_attack(&mut pool, creds, &config)?,
SubCommand::Enum(enumerate) => setup_enum_attack(&mut pool, enumerate, &config)?,
SubCommand::Run(oneshot) => return run_oneshot(oneshot, config),
SubCommand::Fsck(fsck) => return fsck::run_fsck(&fsck),
SubCommand::Completions(completions) => return completions.gen(),
};
let tx = pool.tx();
thread::spawn(move || {
let kb = Keyboard::new();
loop {
let key = kb.get();
tx.send(Msg::Key(key)).expect("failed to send key");
}
});
let mut pb = ProgressBar::new(attempts as u64);
pb.print_help();
pb.tick();
pool.resume();
let start = Instant::now();
let mut valid = 0;
let mut retries = 0;
let mut expired = 0;
while pool.has_work() {
match pool.recv() {
Msg::Key(key) => {
match key {
Key::H => pb.print_help(),
Key::P => {
pb.writeln(format!("{} {}", "[*]".bold(), "pausing threads".dimmed()));
pool.pause();
},
Key::R => {
pb.writeln(format!("{} {}", "[*]".bold(), "resuming threads".dimmed()));
pool.resume();
},
Key::Plus => {
let num = pool.incr();
pb.writeln(format!("{} {}", "[*]".bold(), format!("increased to {} threads", num).dimmed()));
},
Key::Minus => {
let num = pool.decr();
pb.writeln(format!("{} {}", "[*]".bold(), format!("decreased to {} threads", num).dimmed()));
},
}
pb.tick();
},
Msg::Attempt(mut attempt, result) => {
match result {
Ok(is_valid) => {
if is_valid {
match attempt.creds {
Creds::Enum(_) => {
let user = attempt.user();
let script = attempt.script.descr();
pb.writeln(format_valid_enum(script, user));
report.write_enum(user, script)?;
},
_ => {
let user = attempt.user();
let password = attempt.password();
let script = attempt.script.descr();
pb.writeln(format_valid_creds(script, user, password));
report.write_creds(user, password, script)?;
},
};
valid += 1;
}
pb.inc();
},
Err(err) => {
pb.writeln(format!("{} {}({}, {}): {:?}", "[!]".bold(), "error".red(), attempt.script.descr().yellow(), format!("{:?}:{:?}", attempt.user(), attempt.password()).dimmed(), err));
if attempt.ttl > 0 {
// we have retries left
retries += 1;
attempt.ttl -= 1;
pool.run(*attempt);
pb.tick();
} else {
// giving up
expired += 1;
pb.inc();
}
}
};
},
}
}
// truncate precision
let elapsed = Duration::from_millis(start.elapsed().as_millis() as u64);
let average = elapsed / attempts as u32;
pb.finish_replace(tinfof!("[+]", "found {} valid credentials with {} attempts and {} retries after {} and on average {} per attempt. {} attempts expired.\n",
valid.to_formatted_string(&Locale::en),
attempts.to_formatted_string(&Locale::en),
retries.to_formatted_string(&Locale::en),
humantime::format_duration(elapsed),
humantime::format_duration(average),
expired.to_formatted_string(&Locale::en),
));
Keyboard::reset();
Ok(())
}
================================================
FILE: src/pb.rs
================================================
// this file contains a wrapper around pbr to work around three things:
//
// - there is no function to write above the progress bar
// - .draw() isn't exposed so we can't bypass the ratelimit in tick.
// This means we can't reliably redraw the graph after we wrote above it.
// We have to implement rate limiting in our wrapper to ensure we are
// able to bypass it when needed.
// - using colored strings breaks pbr
//
// https://github.com/a8m/pb/pull/62
use colored::Colorize;
use std::fmt::Display;
use std::io::prelude::*;
use std::io::{self, Stdout};
use time::{self, Instant, Duration};
macro_rules! printfl {
($w:expr, $($tt:tt)*) => {{
$w.write_all(&format!($($tt)*).as_bytes()).ok().expect("write_all() fail");
$w.flush().ok().expect("flush() fail");
}}
}
pub struct ProgressBar {
pb: pbr::ProgressBar<Stdout>,
current: u64,
last_refresh_time: Instant,
max_refresh_rate: Option<time::Duration>,
atty: bool,
}
impl ProgressBar {
#[inline]
pub fn new(total: u64) -> ProgressBar {
let mut pb = pbr::ProgressBar::new(total);
pb.format("(=> )");
let now = Instant::now();
let refresh_rate = Duration::milliseconds(250);
let atty = atty::is(atty::Stream::Stdout);
ProgressBar {
pb,
current: 0,
last_refresh_time: now - refresh_rate,
max_refresh_rate: Some(refresh_rate),
atty,
}
}
#[inline]
pub fn draw(&mut self) {
if !self.atty {
return;
}
self.pb.tick()
}
#[inline]
pub fn print_help(&mut self) {
self.writeln(format!("{} {}", "[+]".bold(),
"[h] help, [p] pause, [r] resume, [+] increase threads, [-] decrease threads".dimmed()));
}
#[inline]
pub fn writeln<T: Display>(&mut self, s: T) {
printfl!(io::stderr(), "\r\x1B[2K{}\n", s);
self.draw()
}
#[inline]
pub fn tick(&mut self) {
let now = Instant::now();
if let Some(mrr) = self.max_refresh_rate {
if now - self.last_refresh_time < mrr {
return;
}
}
self.draw();
self.last_refresh_time = Instant::now();
}
#[inline]
pub fn inc(&mut self) {
if !self.atty {
return;
}
let now = Instant::now();
if let Some(mrr) = self.max_refresh_rate {
if now - self.last_refresh_time < mrr {
self.current += 1;
return;
}
}
self.pb.set(self.current);
self.last_refresh_time = Instant::now();
}
#[inline]
pub fn finish_replace<T: Display>(&self, s: T) {
if self.atty {
print!("\r\x1B[2K{}", s);
} else {
print!("{}", s);
}
}
}
================================================
FILE: src/runtime.rs
================================================
use crate::hlua;
use crate::hlua::{AnyLuaValue, AnyHashableLuaValue, AnyLuaString};
use crate::hlua::AnyLuaValue::LuaString;
use crate::structs::LuaMap;
use crate::errors::*;
use crate::json;
use crate::db;
use digest::{
Digest,
block_buffer::Eager,
core_api::{BlockSizeUser, BufferKindUser, CoreProxy, FixedOutputCore, UpdateCore},
typenum::{IsLess, Le, NonZero, U256},
HashMarker, Mac,
};
use hmac::Hmac;
use mysql::prelude::Queryable;
use reqwest::header::WWW_AUTHENTICATE;
use rand::RngCore;
use std::thread;
use std::time::Duration;
use std::process::Command;
use std::collections::HashMap;
use crate::ctx::State;
use crate::http::HttpRequest;
use crate::http::RequestOptions;
use crate::html;
fn byte_array(bytes: AnyLuaValue) -> Result<Vec<u8>> {
match bytes {
AnyLuaValue::LuaAnyString(bytes) => Ok(bytes.0),
AnyLuaValue::LuaString(bytes) => Ok(bytes.into_bytes()),
AnyLuaValue::LuaArray(bytes) => {
Ok(bytes.into_iter()
.map(|num| match num.1 {
AnyLuaValue::LuaNumber(num) if (0.0..=255.0).contains(&num) && (num % 1.0 == 0.0) =>
Ok(num as u8),
AnyLuaValue::LuaNumber(num) =>
Err(format_err!("number is out of range: {:?}", num)),
_ => Err(format_err!("unexpected type: {:?}", num)),
})
.collect::<Result<_>>()?)
},
_ => Err(format_err!("Invalid type: {:?}", bytes)),
}
}
fn lua_bytes(bytes: &[u8]) -> AnyLuaValue {
let bytes = AnyLuaString(bytes.to_vec());
AnyLuaValue::LuaAnyString(bytes)
}
pub fn base64_decode(lua: &mut hlua::Lua, state: State) {
lua.set("base64_decode", hlua::function1(move |bytes: String| -> Result<AnyLuaValue> {
base64::decode(&bytes)
.map_err(|err| state.set_error(err))
.map(|bytes| lua_bytes(&bytes))
}))
}
pub fn base64_encode(lua: &mut hlua::Lua, state: State) {
lua.set("base64_encode", hlua::function1(move |bytes: AnyLuaValue| -> Result<String> {
byte_array(bytes)
.map_err(|err| state.set_error(err))
.map(|bytes| base64::encode(&bytes))
}))
}
pub fn bcrypt(lua: &mut hlua::Lua, state: State) {
lua.set("bcrypt", hlua::function2(move |password: String, cost: u32| -> Result<String> {
bcrypt::hash(&password, cost)
.map_err(|err| state.set_error(err))
}))
}
pub fn bcrypt_verify(lua: &mut hlua::Lua, state: State) {
lua.set("bcrypt_verify", hlua::function2(move |password: String, hashed: String| -> Result<bool> {
bcrypt::verify(&password, &hashed)
.map_err(|err| state.set_error(err))
}))
}
pub fn clear_err(lua: &mut hlua::Lua, state: State) {
lua.set("clear_err", hlua::function0(move || {
state.clear_error()
}))
}
pub fn execve(lua: &mut hlua::Lua, state: State) {
lua.set("execve", hlua::function2(move |prog: String, args: Vec<AnyLuaValue>| -> Result<i32> {
let args: Vec<_> = args.into_iter()
.flat_map(|x| match x {
LuaString(x) => Some(x),
_ => None, // TODO: error
})
.collect();
let status = match Command::new(prog)
.args(&args)
.status()
.context("Failed to spawn program") {
Ok(status) => status,
Err(err) => return Err(state.set_error(err)),
};
let code = match status.code() {
Some(code) => code,
None => return Err(state.set_error(format_err!("Process didn't return exit code"))),
};
Ok(code)
}))
}
pub fn hex(lua: &mut hlua::Lua, state: State) {
lua.set("hex", hlua::function1(move |bytes: AnyLuaValue| -> Result<String> {
byte_array(bytes)
.map_err(|err| state.set_error(err))
.map(|bytes| {
let mut out = String::new();
for b in bytes {
out += &format!("{:02x}", b);
}
out
})
}))
}
fn hmac<D>(secret: AnyLuaValue, msg: AnyLuaValue) -> Result<AnyLuaValue>
where
D: CoreProxy,
D::Core: HashMarker
+ UpdateCore
+ FixedOutputCore
+ BufferKindUser<BufferKind = Eager>
+ Default
+ Clone,
<D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
{
let secret = byte_array(secret)?;
let msg = byte_array(msg)?;
let mut mac = match Hmac::<D>::new_from_slice(&secret) {
Ok(mac) => mac,
Err(_) => bail!("Invalid key length"),
};
mac.update(&msg);
let result = mac.finalize();
Ok(lua_bytes(&result.into_bytes()))
}
pub fn hmac_md5(lua: &mut hlua::Lua, state: State) {
lua.set("hmac_md5", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {
hmac::<md5::Md5>(secret, msg)
.map_err(|err| state.set_error(err))
}))
}
pub fn hmac_sha1(lua: &mut hlua::Lua, state: State) {
lua.set("hmac_sha1", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {
hmac::<sha1::Sha1>(secret, msg)
.map_err(|err| state.set_error(err))
}))
}
pub fn hmac_sha2_256(lua: &mut hlua::Lua, state: State) {
lua.set("hmac_sha2_256", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {
hmac::<sha2::Sha256>(secret, msg)
.map_err(|err| state.set_error(err))
}))
}
pub fn hmac_sha2_512(lua: &mut hlua::Lua, state: State) {
lua.set("hmac_sha2_512", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {
hmac::<sha2::Sha512>(secret, msg)
.map_err(|err| state.set_error(err))
}))
}
pub fn hmac_sha3_256(lua: &mut hlua::Lua, state: State) {
lua.set("hmac_sha3_256", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {
hmac::<sha3::Sha3_256>(secret, msg)
.map_err(|err| state.set_error(err))
}))
}
pub fn hmac_sha3_512(lua: &mut hlua::Lua, state: State) {
lua.set("hmac_sha3_512", hlua::function2(move |secret: AnyLuaValue, msg: AnyLuaValue| -> Result<AnyLuaValue> {
hmac::<sha3::Sha3_512>(secret, msg)
.map_err(|err| state.set_error(err))
}))
}
pub fn html_select(lua: &mut hlua::Lua, state: State) {
lua.set("html_select", hlua::function2(move |html: String, selector: String| -> Result<AnyLuaValue> {
html::html_select(&html, &selector)
.map_err(|err| state.set_error(err))
.map(|x| x.into())
}))
}
pub fn html_select_list(lua: &mut hlua::Lua, state: State) {
lua.set("html_select_list", hlua::function2(move |html: String, selector: String| -> Result<Vec<AnyLuaValue>> {
html::html_select_list(&html, &selector)
.map_err(|err| state.set_error(err))
.map(|x| x.into_iter().map(|x| x.into()).collect())
}))
}
pub fn http_basic_auth(lua: &mut hlua::Lua, state: State) {
lua.set("http_basic_auth", hlua::function3(move |url: String, user: String, password: String| -> Result<bool> {
let client = reqwest::blocking::Client::new();
client.get(&url)
.basic_auth(user, Some(password))
.send()
.context("http request failed")
.map_err(|err| state.set_error(err))
.map(|response| {
info!("http_basic_auth: {:?}", response);
response.headers().get(WWW_AUTHENTICATE).is_none() &&
response.status() != reqwest::StatusCode::UNAUTHORIZED
})
}))
}
pub fn http_mksession(lua: &mut hlua::Lua, state: State) {
lua.set("http_mksession", hlua::function0(move || -> String {
state.http_mksession()
}))
}
pub fn http_request(lua: &mut hlua::Lua, state: State) {
lua.set("http_request", hlua::function4(move |session: String, method: String, url: String, options: AnyLuaValue| -> Result<AnyLuaValue> {
RequestOptions::try_from(options)
.context("Invalid request options")
.map_err(|err| state.set_error(err))
.map(|options| {
state.http_request(&session, method, url, options).into()
})
}))
}
pub fn http_send(lua: &mut hlua::Lua, state: State) {
lua.set("http_send", hlua::function1(move |request: AnyLuaValue| -> Result<HashMap<AnyHashableLuaValue, AnyLuaValue>> {
let req = match HttpRequest::try_from(request)
.context("Invalid http request object") {
Ok(req) => req,
Err(err) => return Err(state.set_error(err)),
};
req.send(&state)
.map_err(|err| state.set_error(err))
.map(|resp| resp.into())
}))
}
pub fn json_decode(lua: &mut hlua::Lua, state: State) {
lua.set("json_decode", hlua::function1(move |x: String| -> Result<AnyLuaValue> {
json::decode(&x)
.map_err(|err| state.set_error(err))
}))
}
pub fn json_encode(lua: &mut hlua::Lua, state: State) {
lua.set("json_encode", hlua::function1(move |x: AnyLuaValue| -> Result<String> {
json::encode(x)
.map_err(|err| state.set_error(err))
}))
}
pub fn last_err(lua: &mut hlua::Lua, state: State) {
lua.set("last_err", hlua::function0(move || -> AnyLuaValue {
match state.last_error() {
Some(err) => AnyLuaValue::LuaString(err),
None => AnyLuaValue::LuaNil,
}
}))
}
pub fn ldap_bind(lua: &mut hlua::Lua, state: State) {
lua.set("ldap_bind", hlua::function3(move |url: String, dn: String, password: String| -> Result<bool> {
let mut sock = match ldap3::LdapConn::new(&url)
.context("ldap connection failed") {
Ok(sock) => sock,
Err(err) => return Err(state.set_error(err)),
};
sock.simple_bind(&dn, &password)
.context("Fatal error during simple_bind")
.map_err(|err| state.set_error(err))
.map(|result| {
debug!("ldap_bind: {:?}", result);
result.success().is_ok()
})
}))
}
pub fn ldap_escape(lua: &mut hlua::Lua, _: State) {
lua.set("ldap_escape", hlua::function1(move |s: String| -> String {
ldap3::dn_escape(s).to_string()
}))
}
pub fn ldap_search_bind(lua: &mut hlua::Lua, state: State) {
lua.set("ldap_search_bind", hlua::function6(move |url: String, search_user: String, search_pw: String, base_dn: String, user: String, password: String| -> Result<bool> {
let mut sock = ldap3::LdapConn::new(&url)
.context("ldap connection failed")
.map_err(|err| state.set_error(err))?;
let result = sock.simple_bind(&search_user, &search_pw)
.context("Fatal error during simple_bind with search user")
.map_err(|err| state.set_error(err))?;
if result.success().is_err() {
return Err(state.set_error(format_err!("Login with search user failed")));
}
let search = format!("uid={}", ldap3::dn_escape(user));
let result = sock.search(&base_dn, ldap3::Scope::Subtree, &search, vec!["*"])
.context("Fatal error during ldap search")
.map_err(|err| state.set_error(err))?;
let entries = result.success()
.context("ldap search failed")
.map(|result| result.0)
.map_err(|err| state.set_error(err))?;
// take the first result
if let Some(entry) = entries.into_iter().next() {
let entry = ldap3::SearchEntry::construct(entry);
// we got the DN, try to login
let result = sock.simple_bind(&entry.dn, &password)
.context("Fatal error during simple_bind")
.map_err(|err| state.set_error(err))?;
// println!("{:?}", result);
Ok(result.success().is_ok())
} else {
Ok(false)
}
}))
}
pub fn md5(lua: &mut hlua::Lua, state: State) {
lua.set("md5", hlua::function1(move |bytes: AnyLuaValue| -> Result<AnyLuaValue> {
byte_array(bytes)
.map_err(|err| state.set_error(err))
.map(|bytes| lua_bytes(&md5::Md5::digest(&bytes)))
}))
}
pub fn mysql_connect(lua: &mut hlua::Lua, state: State) {
lua.set("mysql_connect", hlua::function4(move |host: String, port: u16, user: String, password: String| -> Result<String> {
let builder = mysql::OptsBuilder::new()
.ip_or_hostname(Some(host))
.tcp_port(port)
.prefer_socket(false)
.user(Some(user))
.pass(Some(password));
mysql::Conn::new(builder)
.map_err(|err| state.set_error(err))
.map(|sock| state.mysql_register(sock))
}))
}
pub fn mysql_query(lua: &mut hlua::Lua, state: St
gitextract_ctmbbqt6/
├── .dockerignore
├── .github/
│ ├── FUNDING.yml
│ └── workflows/
│ └── rust.yml
├── .gitignore
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
├── ci/
│ └── smtp/
│ ├── Dockerfile
│ └── smtpd.conf
├── docs/
│ ├── Makefile
│ ├── authoscope.1
│ ├── conf.py
│ ├── config.rst
│ ├── index.rst
│ ├── install.rst
│ ├── make.bat
│ ├── man.rst
│ ├── scripting.rst
│ ├── test.sh
│ └── usage.rst
├── examples/
│ ├── README.md
│ └── load-creds.rs
├── scripts/
│ ├── basic_auth.lua
│ ├── benchmark.lua
│ ├── binary.lua
│ ├── cookies.lua
│ ├── error.lua
│ ├── execve.lua
│ ├── false.lua
│ ├── http.lua
│ ├── json.lua
│ ├── ldap.lua
│ ├── ldap_search.lua
│ ├── mysql-connect.lua
│ ├── mysql-query.lua
│ ├── post.lua
│ ├── print.lua
│ ├── random-errors.lua
│ ├── random.lua
│ ├── sleep.lua
│ ├── smtp.lua
│ ├── str-find.lua
│ └── true.lua
└── src/
├── args.rs
├── bin/
│ └── badtouch.rs
├── config.rs
├── ctx.rs
├── db/
│ ├── mod.rs
│ └── mysql.rs
├── errors.rs
├── fsck.rs
├── html.rs
├── http.rs
├── json.rs
├── keyboard.rs
├── lib.rs
├── main.rs
├── pb.rs
├── runtime.rs
├── scheduler.rs
├── sockets.rs
├── structs.rs
├── ulimit.rs
└── utils.rs
SYMBOL INDEX (250 symbols across 19 files)
FILE: examples/load-creds.rs
function main (line 5) | fn main() -> Result<()> {
FILE: src/args.rs
type Args (line 9) | pub struct Args {
type SubCommand (line 25) | pub enum SubCommand {
type Dict (line 40) | pub struct Dict {
type Combo (line 51) | pub struct Combo {
type Enum (line 60) | pub struct Enum {
type Run (line 69) | pub struct Run {
type Fsck (line 82) | pub struct Fsck {
type Completions (line 98) | pub struct Completions {
method gen (line 104) | pub fn gen(&self) -> Result<()> {
FILE: src/bin/badtouch.rs
type Args (line 22) | pub struct Args {
type SubCommand (line 38) | pub enum SubCommand {
type Dict (line 58) | pub struct Dict {
type Creds (line 69) | pub struct Creds {
type Enum (line 78) | pub struct Enum {
type Oneshot (line 87) | pub struct Oneshot {
type Fsck (line 100) | pub struct Fsck {
type Completions (line 116) | pub struct Completions {
method gen (line 122) | pub fn gen(&self) -> Result<()> {
type Report (line 127) | enum Report {
method open (line 133) | pub fn open(path: Option<String>) -> Result<Report> {
method write_creds (line 140) | pub fn write_creds(&mut self, user: &str, password: &str, script: &str...
method write_enum (line 147) | pub fn write_enum(&mut self, user: &str, script: &str) -> Result<()> {
function setup_dictionary_attack (line 167) | fn setup_dictionary_attack(pool: &mut Scheduler, args: Dict, config: &Ar...
function setup_credential_confirmation (line 193) | fn setup_credential_confirmation(pool: &mut Scheduler, args: Creds, conf...
function setup_enum_attack (line 214) | fn setup_enum_attack(pool: &mut Scheduler, args: Enum, config: &Arc<Conf...
function run_oneshot (line 235) | fn run_oneshot(oneshot: Oneshot, config: Arc<Config>) -> Result<()> {
function format_valid_creds (line 256) | fn format_valid_creds(script: &str, user: &str, password: &str) -> String {
function format_valid_enum (line 261) | fn format_valid_enum(script: &str, user: &str) -> String {
function main (line 266) | fn main() -> Result<()> {
FILE: src/config.rs
type Config (line 8) | pub struct Config {
method load (line 22) | pub fn load() -> Result<Config> {
method from_file (line 37) | pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Config> {
method try_from_str (line 47) | pub fn try_from_str(buf: &str) -> Result<Config> {
type RuntimeConfig (line 14) | pub struct RuntimeConfig {
function verify_empty (line 58) | fn verify_empty() {
FILE: src/ctx.rs
type State (line 17) | pub struct State {
method new (line 26) | pub fn new(config: Arc<Config>) -> State {
method last_error (line 36) | pub fn last_error(&self) -> Option<String> {
method clear_error (line 41) | pub fn clear_error(&self) {
method set_error (line 46) | pub fn set_error<I: Into<Error>>(&self, err: I) -> Error {
method random_id (line 55) | fn random_id(&self) -> String {
method register_in_jar (line 59) | pub fn register_in_jar(&self, session: &str, cookies: Vec<(String, Str...
method http_mksession (line 66) | pub fn http_mksession(&self) -> String {
method http_request (line 73) | pub fn http_request(&self, session_id: &str, method: String, url: Stri...
method mysql_register (line 80) | pub fn mysql_register(&self, sock: mysql::Conn) -> String {
method mysql_session (line 90) | pub fn mysql_session(&self, id: &str) -> Arc<Mutex<mysql::Conn>> {
method sock_connect (line 96) | pub fn sock_connect(&self, host: &str, port: u16) -> Result<String> {
method get_sock (line 106) | pub fn get_sock(&self, id: &str)-> Arc<Mutex<Socket>> {
type Script (line 115) | pub struct Script {
method load (line 122) | pub fn load(path: &str, config: Arc<Config>) -> Result<Script> {
method load_from (line 127) | pub fn load_from<R: Read>(mut src: R, config: Arc<Config>) -> Result<S...
method ctx (line 152) | fn ctx<'a>(config: &Arc<Config>) -> (hlua::Lua<'a>, State) {
method descr (line 211) | pub fn descr(&self) -> &str {
method run_once (line 222) | pub fn run_once(&self, user: AnyLuaValue, password: AnyLuaValue) -> Re...
method run_creds (line 251) | pub fn run_creds(&self, user: &str, password: &str) -> Result<bool> {
method run_enum (line 258) | pub fn run_enum(&self, user: &str) -> Result<bool> {
function empty_config (line 269) | fn empty_config() -> Arc<Config> {
function verify_false (line 274) | fn verify_false() {
function verify_true (line 288) | fn verify_true() {
function verify_record_error (line 302) | fn verify_record_error() {
function verify_clear_recorded_error (line 317) | fn verify_clear_recorded_error() {
function verify_sleep (line 333) | fn verify_sleep() {
function verify_basic_auth_correct (line 348) | fn verify_basic_auth_correct() {
function verify_basic_auth_incorrect (line 362) | fn verify_basic_auth_incorrect() {
function verify_cookies (line 376) | fn verify_cookies() {
function verify_hex (line 416) | fn verify_hex() {
function verify_hex_empty (line 431) | fn verify_hex_empty() {
function verify_json_encode (line 446) | fn verify_json_encode() {
function verify_json_encode_decode (line 470) | fn verify_json_encode_decode() {
function verify_json_decode_valid (line 496) | fn verify_json_decode_valid() {
function verify_json_decode_invalid (line 511) | fn verify_json_decode_invalid() {
function verify_hmac_md5 (line 526) | fn verify_hmac_md5() {
function verify_hmac_sha1 (line 542) | fn verify_hmac_sha1() {
function verify_hmac_sha2_256 (line 558) | fn verify_hmac_sha2_256() {
function verify_hmac_sha2_512 (line 574) | fn verify_hmac_sha2_512() {
function verify_hmac_sha3_256 (line 590) | fn verify_hmac_sha3_256() {
function verify_hmac_sha3_512 (line 606) | fn verify_hmac_sha3_512() {
function verify_bcrypt_verify (line 622) | fn verify_bcrypt_verify() {
FILE: src/db/mysql.rs
method from (line 8) | fn from(params: mysql::Params) -> LuaMap {
function from (line 23) | fn from(x: LuaMap) -> mysql::Params {
function lua_to_mysql_value (line 42) | fn lua_to_mysql_value(value: AnyLuaValue) -> mysql::Value {
function mysql_value_to_lua (line 58) | pub fn mysql_value_to_lua(value: mysql::Value) -> AnyLuaValue {
FILE: src/fsck.rs
function validate_file (line 12) | fn validate_file(path: &str, args: &Fsck) -> Result<()> {
function run_fsck (line 62) | pub fn run_fsck(args: &Fsck) -> Result<()> {
FILE: src/html.rs
type Element (line 10) | pub struct Element {
method from (line 16) | fn from(x: Element) -> AnyLuaValue {
function transform_element (line 26) | fn transform_element(entry: &kuchiki::NodeDataRef<kuchiki::ElementData>)...
function html_select (line 44) | pub fn html_select(html: &str, selector: &str) -> Result<Element> {
function html_select_list (line 52) | pub fn html_select_list(html: &str, selector: &str) -> Result<Vec<Elemen...
function test_html_select (line 67) | fn test_html_select() {
function test_html_select_list (line 78) | fn test_html_select_list() {
FILE: src/http.rs
type HttpSession (line 18) | pub struct HttpSession {
method new (line 24) | pub fn new() -> (String, HttpSession) {
type RequestOptions (line 34) | pub struct RequestOptions {
method try_from (line 45) | pub fn try_from(x: AnyLuaValue) -> Result<RequestOptions> {
type HttpRequest (line 53) | pub struct HttpRequest {
method new (line 67) | pub fn new(config: &Arc<Config>, session: &HttpSession, method: String...
method send (line 99) | pub fn send(&self, state: &State) -> Result<LuaMap> {
method register_cookies_on_state (line 168) | fn register_cookies_on_state(session: &str, state: &State, cookies: &r...
method try_from (line 197) | pub fn try_from(x: AnyLuaValue) -> Result<HttpRequest> {
method from (line 205) | fn from(x: HttpRequest) -> AnyLuaValue {
type CookieJar (line 214) | pub struct CookieJar(HashMap<String, String>);
method register_in_jar (line 217) | pub fn register_in_jar(&mut self, cookies: Vec<(String, String)>) {
method assemble_cookie_header (line 223) | pub fn assemble_cookie_header(&self) -> Option<String> {
method escape_cookie_value (line 244) | fn escape_cookie_value(&self, value: &str) -> String {
type Target (line 257) | type Target = HashMap<String, String>;
method deref (line 259) | fn deref(&self) -> &Self::Target {
type Body (line 265) | pub enum Body {
FILE: src/json.rs
function decode (line 6) | pub fn decode(x: &str) -> Result<AnyLuaValue> {
function encode (line 13) | pub fn encode(v: AnyLuaValue) -> Result<String> {
function lua_array_is_list (line 21) | pub fn lua_array_is_list(array: &[(AnyLuaValue, AnyLuaValue)]) -> bool {
type LuaJsonValue (line 32) | pub enum LuaJsonValue {
method from (line 62) | fn from(x: AnyLuaValue) -> LuaJsonValue {
method from (line 120) | fn from(x: Value) -> LuaJsonValue {
method from (line 42) | fn from(x: LuaJsonValue) -> AnyLuaValue {
method from (line 101) | fn from(x: LuaJsonValue) -> Value {
FILE: src/keyboard.rs
type Keyboard (line 7) | pub struct Keyboard {
method new (line 24) | pub fn new() -> Keyboard {
method get (line 28) | pub fn get(&self) -> Key {
method reset (line 44) | pub fn reset() {
method default (line 13) | fn default() -> Keyboard {
type Key (line 56) | pub enum Key {
FILE: src/main.rs
type Report (line 21) | enum Report {
method open (line 27) | pub fn open(path: Option<String>) -> Result<Report> {
method write_creds (line 34) | pub fn write_creds(&mut self, user: &str, password: &str, script: &str...
method write_enum (line 41) | pub fn write_enum(&mut self, user: &str, script: &str) -> Result<()> {
function setup_dictionary_attack (line 61) | fn setup_dictionary_attack(pool: &mut Scheduler, args: args::Dict, confi...
function setup_combolist_attack (line 89) | fn setup_combolist_attack(pool: &mut Scheduler, args: args::Combo, confi...
function setup_enum_attack (line 110) | fn setup_enum_attack(pool: &mut Scheduler, args: args::Enum, config: &Ar...
function run_oneshot (line 131) | fn run_oneshot(oneshot: args::Run, config: Arc<Config>) -> Result<()> {
function format_valid_creds (line 152) | fn format_valid_creds(script: &str, user: &str, password: &str) -> String {
function format_valid_enum (line 157) | fn format_valid_enum(script: &str, user: &str) -> String {
function log_filter (line 162) | fn log_filter(args: &Args) -> &'static str {
function main (line 170) | fn main() -> Result<()> {
FILE: src/pb.rs
type ProgressBar (line 26) | pub struct ProgressBar {
method new (line 36) | pub fn new(total: u64) -> ProgressBar {
method draw (line 54) | pub fn draw(&mut self) {
method print_help (line 63) | pub fn print_help(&mut self) {
method writeln (line 69) | pub fn writeln<T: Display>(&mut self, s: T) {
method tick (line 75) | pub fn tick(&mut self) {
method inc (line 89) | pub fn inc(&mut self) {
method finish_replace (line 108) | pub fn finish_replace<T: Display>(&self, s: T) {
FILE: src/runtime.rs
function byte_array (line 32) | fn byte_array(bytes: AnyLuaValue) -> Result<Vec<u8>> {
function lua_bytes (line 51) | fn lua_bytes(bytes: &[u8]) -> AnyLuaValue {
function base64_decode (line 56) | pub fn base64_decode(lua: &mut hlua::Lua, state: State) {
function base64_encode (line 64) | pub fn base64_encode(lua: &mut hlua::Lua, state: State) {
function bcrypt (line 72) | pub fn bcrypt(lua: &mut hlua::Lua, state: State) {
function bcrypt_verify (line 79) | pub fn bcrypt_verify(lua: &mut hlua::Lua, state: State) {
function clear_err (line 86) | pub fn clear_err(lua: &mut hlua::Lua, state: State) {
function execve (line 92) | pub fn execve(lua: &mut hlua::Lua, state: State) {
function hex (line 118) | pub fn hex(lua: &mut hlua::Lua, state: State) {
function hmac (line 134) | fn hmac<D>(secret: AnyLuaValue, msg: AnyLuaValue) -> Result<AnyLuaValue>
function hmac_md5 (line 158) | pub fn hmac_md5(lua: &mut hlua::Lua, state: State) {
function hmac_sha1 (line 165) | pub fn hmac_sha1(lua: &mut hlua::Lua, state: State) {
function hmac_sha2_256 (line 172) | pub fn hmac_sha2_256(lua: &mut hlua::Lua, state: State) {
function hmac_sha2_512 (line 179) | pub fn hmac_sha2_512(lua: &mut hlua::Lua, state: State) {
function hmac_sha3_256 (line 186) | pub fn hmac_sha3_256(lua: &mut hlua::Lua, state: State) {
function hmac_sha3_512 (line 193) | pub fn hmac_sha3_512(lua: &mut hlua::Lua, state: State) {
function html_select (line 200) | pub fn html_select(lua: &mut hlua::Lua, state: State) {
function html_select_list (line 208) | pub fn html_select_list(lua: &mut hlua::Lua, state: State) {
function http_basic_auth (line 216) | pub fn http_basic_auth(lua: &mut hlua::Lua, state: State) {
function http_mksession (line 233) | pub fn http_mksession(lua: &mut hlua::Lua, state: State) {
function http_request (line 239) | pub fn http_request(lua: &mut hlua::Lua, state: State) {
function http_send (line 250) | pub fn http_send(lua: &mut hlua::Lua, state: State) {
function json_decode (line 264) | pub fn json_decode(lua: &mut hlua::Lua, state: State) {
function json_encode (line 271) | pub fn json_encode(lua: &mut hlua::Lua, state: State) {
function last_err (line 278) | pub fn last_err(lua: &mut hlua::Lua, state: State) {
function ldap_bind (line 287) | pub fn ldap_bind(lua: &mut hlua::Lua, state: State) {
function ldap_escape (line 305) | pub fn ldap_escape(lua: &mut hlua::Lua, _: State) {
function ldap_search_bind (line 311) | pub fn ldap_search_bind(lua: &mut hlua::Lua, state: State) {
function md5 (line 354) | pub fn md5(lua: &mut hlua::Lua, state: State) {
function mysql_connect (line 362) | pub fn mysql_connect(lua: &mut hlua::Lua, state: State) {
function mysql_query (line 377) | pub fn mysql_query(lua: &mut hlua::Lua, state: State) {
function format_lua (line 410) | fn format_lua(out: &mut String, x: &AnyLuaValue) {
function print (line 442) | pub fn print(lua: &mut hlua::Lua, _: State) {
function rand (line 453) | pub fn rand(lua: &mut hlua::Lua, _: State) {
function randombytes (line 460) | pub fn randombytes(lua: &mut hlua::Lua, _: State) {
function sha1 (line 469) | pub fn sha1(lua: &mut hlua::Lua, state: State) {
function sha2_256 (line 477) | pub fn sha2_256(lua: &mut hlua::Lua, state: State) {
function sha2_512 (line 485) | pub fn sha2_512(lua: &mut hlua::Lua, state: State) {
function sha3_256 (line 493) | pub fn sha3_256(lua: &mut hlua::Lua, state: State) {
function sha3_512 (line 501) | pub fn sha3_512(lua: &mut hlua::Lua, state: State) {
function sleep (line 509) | pub fn sleep(lua: &mut hlua::Lua, _: State) {
function sock_connect (line 516) | pub fn sock_connect(lua: &mut hlua::Lua, state: State) {
function sock_send (line 523) | pub fn sock_send(lua: &mut hlua::Lua, state: State) {
function sock_recv (line 538) | pub fn sock_recv(lua: &mut hlua::Lua, state: State) {
function sock_sendline (line 550) | pub fn sock_sendline(lua: &mut hlua::Lua, state: State) {
function sock_recvline (line 562) | pub fn sock_recvline(lua: &mut hlua::Lua, state: State) {
function sock_recvall (line 574) | pub fn sock_recvall(lua: &mut hlua::Lua, state: State) {
function sock_recvline_contains (line 586) | pub fn sock_recvline_contains(lua: &mut hlua::Lua, state: State) {
function sock_recvline_regex (line 598) | pub fn sock_recvline_regex(lua: &mut hlua::Lua, state: State) {
function sock_recvn (line 610) | pub fn sock_recvn(lua: &mut hlua::Lua, state: State) {
function sock_recvuntil (line 622) | pub fn sock_recvuntil(lua: &mut hlua::Lua, state: State) {
function sock_sendafter (line 637) | pub fn sock_sendafter(lua: &mut hlua::Lua, state: State) {
function sock_newline (line 655) | pub fn sock_newline(lua: &mut hlua::Lua, state: State) {
FILE: src/scheduler.rs
type Creds (line 9) | pub enum Creds {
method user (line 19) | pub fn user(&self) -> &str {
method password (line 33) | pub fn password(&self) -> &str {
type Attempt (line 49) | pub struct Attempt {
method new (line 57) | pub fn new(user: &Arc<String>, password: &Arc<String>, script: &Arc<Sc...
method bytes (line 66) | pub fn bytes(bytes: &Arc<Vec<u8>>, script: &Arc<Script>) -> Attempt {
method enumerate (line 75) | pub fn enumerate(user: &Arc<String>, script: &Arc<Script>) -> Attempt {
method user (line 84) | pub fn user(&self) -> &str {
method password (line 89) | pub fn password(&self) -> &str {
method run (line 94) | pub fn run(self, tx: &mpsc::Sender<Msg>) {
type Msg (line 104) | pub enum Msg {
type Scheduler (line 109) | pub struct Scheduler {
method new (line 120) | pub fn new(workers: usize) -> Scheduler {
method pause (line 133) | pub fn pause(&mut self) {
method resume (line 140) | pub fn resume(&mut self) {
method incr (line 148) | pub fn incr(&mut self) -> usize {
method decr (line 155) | pub fn decr(&mut self) -> usize {
method tx (line 166) | pub fn tx(&self) -> mpsc::Sender<Msg> {
method max_count (line 171) | pub fn max_count(&self) -> usize {
method has_work (line 176) | pub fn has_work(&self) -> bool {
method run (line 181) | pub fn run(&mut self, attempt: Attempt) {
method recv (line 201) | pub fn recv(&mut self) -> Msg {
FILE: src/sockets.rs
type Socket (line 15) | pub struct Socket {
method connect (line 21) | pub fn connect(host: &str, port: u16) -> Result<Socket> {
method send (line 49) | pub fn send(&mut self, data: &[u8]) -> Result<()> {
method recv (line 59) | pub fn recv(&mut self) -> Result<Vec<u8>> {
method sendline (line 70) | pub fn sendline(&mut self, line: &str) -> Result<()> {
method recvline (line 75) | pub fn recvline(&mut self) -> Result<String> {
method recvall (line 83) | pub fn recvall(&mut self) -> Result<Vec<u8>> {
method recvline_contains (line 93) | pub fn recvline_contains(&mut self, needle: &str) -> Result<String> {
method recvline_regex (line 102) | pub fn recvline_regex(&mut self, regex: &str) -> Result<String> {
method recvn (line 112) | pub fn recvn(&mut self, n: u32) -> Result<Vec<u8>> {
method recvuntil (line 122) | pub fn recvuntil(&mut self, delim: &[u8]) -> Result<Vec<u8>> {
method sendafter (line 158) | pub fn sendafter(&mut self, delim: &[u8], data: &[u8]) -> Result<()> {
method newline (line 163) | pub fn newline<I: Into<String>>(&mut self, delim: I) {
FILE: src/structs.rs
type LuaMap (line 8) | pub struct LuaMap(HashMap<AnyHashableLuaValue, AnyLuaValue>);
method new (line 12) | pub fn new() -> LuaMap {
method is_empty (line 17) | pub fn is_empty(&self) -> bool {
method insert (line 22) | pub fn insert<K: Into<String>, V: Into<AnyLuaValue>>(&mut self, k: K, ...
method insert_str (line 27) | pub fn insert_str<K: Into<String>, V: Into<String>>(&mut self, k: K, v...
method insert_num (line 32) | pub fn insert_num<K: Into<String>>(&mut self, k: K, v: f64) {
method from (line 47) | fn from(x: HashMap<String, String>) -> LuaMap {
method from (line 57) | fn from(x: HashMap<AnyHashableLuaValue, AnyLuaValue>) -> LuaMap {
method from (line 63) | fn from(x: Vec<(AnyLuaValue, AnyLuaValue)>) -> LuaMap {
type Item (line 38) | type Item = (AnyHashableLuaValue, AnyLuaValue);
type IntoIter (line 39) | type IntoIter = collections::hash_map::IntoIter<AnyHashableLuaValue, Any...
method into_iter (line 41) | fn into_iter(self) -> Self::IntoIter {
function from (line 78) | fn from(x: LuaMap) -> HashMap<AnyHashableLuaValue, AnyLuaValue> {
method from (line 84) | fn from(x: LuaMap) -> AnyLuaValue {
FILE: src/ulimit.rs
function set_nofile (line 6) | pub fn set_nofile(config: &Config) -> Result<()> {
FILE: src/utils.rs
function random_string (line 14) | pub fn random_string(len: usize) -> String {
function load_list (line 23) | pub fn load_list<P: AsRef<Path>>(path: P) -> Result<Vec<Arc<String>>> {
function load_combolist (line 32) | pub fn load_combolist<P: AsRef<Path>>(path: P) -> Result<Vec<Arc<Vec<u8>...
function load_scripts (line 62) | pub fn load_scripts(paths: Vec<String>, config: &Arc<Config>) -> Result<...
Condensed preview — 65 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (230K chars).
[
{
"path": ".dockerignore",
"chars": 57,
"preview": "target\nDockerfile\n.dockerignore\n.git\n.gitignore\n*.sw[op]\n"
},
{
"path": ".github/FUNDING.yml",
"chars": 17,
"preview": "github: [kpcyrd]\n"
},
{
"path": ".github/workflows/rust.yml",
"chars": 1032,
"preview": "name: Rust\n\non:\n push:\n branches: [ main ]\n pull_request:\n branches: [ main ]\n\nenv:\n CARGO_TERM_COLOR: always\n\n"
},
{
"path": ".gitignore",
"chars": 50,
"preview": "\n/target/\n**/*.rs.bk\n*.txt\n*.sw[op]\n/docs/_build/\n"
},
{
"path": "Cargo.toml",
"chars": 1087,
"preview": "[package]\nname = \"authoscope\"\nversion = \"0.8.1\"\ndescription = \"Scriptable network authentication cracker\"\nauthors = [\"kp"
},
{
"path": "Dockerfile",
"chars": 356,
"preview": "FROM rust:alpine3.15\nENV RUSTFLAGS=\"-C target-feature=-crt-static\"\nRUN apk add musl-dev openssl-dev\nWORKDIR /app\nCOPY . "
},
{
"path": "LICENSE",
"chars": 35142,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 13890,
"preview": "# authoscope [![Crates.io][crates-img]][crates]\n\n[crates-img]: https://img.shields.io/crates/v/authoscope.svg\n[crates]"
},
{
"path": "ci/smtp/Dockerfile",
"chars": 184,
"preview": "FROM debian:stretch\nRUN apt-get update -qq \\\n && apt-get install -yq opensmtpd\nRUN echo \"foo\" > /etc/mailname\nADD smt"
},
{
"path": "ci/smtp/smtpd.conf",
"chars": 500,
"preview": "# This is the smtpd server system-wide configuration file.\n# See smtpd.conf(5) for more information.\n\n# To accept extern"
},
{
"path": "docs/Makefile",
"chars": 6814,
"preview": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS =\nSPHINXBUILD "
},
{
"path": "docs/authoscope.1",
"chars": 11996,
"preview": ".TH AUTHOSCOPE \"1\" \"August 2018\" \"authoscope 0.6.1\" \"User Commands\"\n.SH NAME\nauthoscope \\- scriptable network authentica"
},
{
"path": "docs/conf.py",
"chars": 8221,
"preview": "# -*- coding: utf-8 -*-\n#\n# Read the Docs Template documentation build configuration file, created by\n# sphinx-quickstar"
},
{
"path": "docs/config.rst",
"chars": 412,
"preview": "Configuration\n=============\n\nYou can place a config file at ``~/.config/authoscope.toml`` to set some defaults.\n\nGlobal "
},
{
"path": "docs/index.rst",
"chars": 1026,
"preview": "authoscope\n==========\n\nauthoscope (formerly badtouch) is a scriptable network authentication cracker.\nWhile the space fo"
},
{
"path": "docs/install.rst",
"chars": 566,
"preview": "Installation\n============\n\nIf available, please prefer the package shipped by your linux distribution.\n\nArchlinux\n------"
},
{
"path": "docs/make.bat",
"chars": 6709,
"preview": "@ECHO OFF\r\n\r\nREM Command file for Sphinx documentation\r\n\r\nif \"%SPHINXBUILD%\" == \"\" (\r\n\tset SPHINXBUILD=sphinx-build\r\n)\r\n"
},
{
"path": "docs/man.rst",
"chars": 708,
"preview": "authoscope\n========\n\nauthoscope (formerly badtouch) is a scriptable network authentication cracker.\nWhile the space for "
},
{
"path": "docs/scripting.rst",
"chars": 11703,
"preview": "Scripting\n=========\n\nA simple script could look like this:\n\n.. code-block:: lua\n\n descr = \"example.com\"\n\n function"
},
{
"path": "docs/test.sh",
"chars": 35,
"preview": "#!/bin/sh\necho $2 | grep -q \"buzz\"\n"
},
{
"path": "docs/usage.rst",
"chars": 1556,
"preview": "Usage\n========\n\nOptions\n-------\n\n.. code-block:: text\n\n -n, --workers <workers> The number of concurrent workers "
},
{
"path": "examples/README.md",
"chars": 66,
"preview": "These are small programs to benchmark some individual components.\n"
},
{
"path": "examples/load-creds.rs",
"chars": 607,
"preview": "use std::env;\nuse std::time::Instant;\nuse authoscope::errors::*;\n\nfn main() -> Result<()> {\n env_logger::init();\n\n "
},
{
"path": "scripts/basic_auth.lua",
"chars": 156,
"preview": "descr = \"basic auth httpbin.org\"\n\nfunction verify(user, password)\n return http_basic_auth(\"https://httpbin.org/basic-"
},
{
"path": "scripts/benchmark.lua",
"chars": 86,
"preview": "descr = \"for benchmarking only\"\n\nfunction verify(user, password)\n return false\nend\n"
},
{
"path": "scripts/binary.lua",
"chars": 162,
"preview": "descr = \"binary\"\n\nfunction verify(user, password)\n print(\"\\x00\\xff\")\n print(hex(\"\\x00\\xff\"))\n print(base64_enco"
},
{
"path": "scripts/cookies.lua",
"chars": 1020,
"preview": "descr = \"http cookies\"\n\nfunction verify(user, password)\n session = http_mksession()\n\n -- set cookies\n req = htt"
},
{
"path": "scripts/error.lua",
"chars": 90,
"preview": "descr = \"always error\"\n\nfunction verify(user, password)\n return \"this is an error\"\nend\n"
},
{
"path": "scripts/execve.lua",
"chars": 119,
"preview": "descr = \"exec test.sh\"\n\nfunction verify(user, password)\n return execve(\"./docs/test.sh\", {user, password}) == 0\nend\n"
},
{
"path": "scripts/false.lua",
"chars": 77,
"preview": "descr = \"always false\"\n\nfunction verify(user, password)\n return false\nend\n"
},
{
"path": "scripts/http.lua",
"chars": 477,
"preview": "descr = \"http\"\n\nfunction verify(user, password)\n session = http_mksession()\n\n -- set cookies\n req = http_reques"
},
{
"path": "scripts/json.lua",
"chars": 353,
"preview": "descr = \"json\"\n\nfunction verify(user, password)\n x = json_encode({\n hello=\"world\",\n almost_one=0.9999,\n"
},
{
"path": "scripts/ldap.lua",
"chars": 185,
"preview": "descr = \"ldap\"\n\nfunction verify(user, password)\n return ldap_bind(\"ldaps://ldap.example.com/\",\n \"cn=\\\"\" .. lda"
},
{
"path": "scripts/ldap_search.lua",
"chars": 347,
"preview": "descr = \"ldap w/ search\"\n\nfunction verify(user, password)\n return ldap_search_bind(\"ldaps://ldap.example.com/\",\n "
},
{
"path": "scripts/mysql-connect.lua",
"chars": 214,
"preview": "descr = \"local mysql\"\n\nfunction verify(user, password)\n mysql_connect(\"127.0.0.1\", 3306, user, password)\n\n if last"
},
{
"path": "scripts/mysql-query.lua",
"chars": 395,
"preview": "descr = \"local mysql query\"\n\nfunction verify(user, password)\n sock = mysql_connect(\"127.0.0.1\", 3306, \"root\", \"my-sec"
},
{
"path": "scripts/post.lua",
"chars": 495,
"preview": "descr = \"http post\"\n\nfunction verify(user, password)\n session = http_mksession()\n\n -- send login\n req = http_re"
},
{
"path": "scripts/print.lua",
"chars": 430,
"preview": "descr = \"print\"\n\nfunction b64u(s)\n s = s:gsub('%=', '')\n s = s:gsub('%+', '-')\n s = s:gsub('%/', '_')\n retur"
},
{
"path": "scripts/random-errors.lua",
"chars": 146,
"preview": "descr = \"random errors\"\n\nfunction verify(user, password)\n if rand(0, 100) < 1 then\n return \"random error\"\n "
},
{
"path": "scripts/random.lua",
"chars": 98,
"preview": "descr = \"random\"\n\nfunction verify(user, password)\n x = rand(0, 10000)\n return x >= 9999\nend\n"
},
{
"path": "scripts/sleep.lua",
"chars": 87,
"preview": "descr = \"sleepy zZz\"\n\nfunction verify(user, password)\n sleep(1)\n return true\nend\n"
},
{
"path": "scripts/smtp.lua",
"chars": 958,
"preview": "descr = \"smtp enum\"\n\nfunction verify(user, password)\n -- enumeration only, password is ignored\n sock = sock_connec"
},
{
"path": "scripts/str-find.lua",
"chars": 158,
"preview": "descr = \"str-find\"\n\nfunction verify(user, password)\n text = \"You are currently logged in as 'foo', want to log out?\"\n"
},
{
"path": "scripts/true.lua",
"chars": 75,
"preview": "descr = \"always true\"\n\nfunction verify(user, password)\n return true\nend\n"
},
{
"path": "src/args.rs",
"chars": 2878,
"preview": "use crate::errors::*;\nuse std::io::stdout;\nuse std::path::PathBuf;\nuse structopt::StructOpt;\nuse structopt::clap::{AppSe"
},
{
"path": "src/bin/badtouch.rs",
"chars": 13081,
"preview": "use authoscope::args;\nuse authoscope::config::Config;\nuse authoscope::ctx::Script;\nuse authoscope::errors::*;\nuse authos"
},
{
"path": "src/config.rs",
"chars": 1460,
"preview": "use crate::errors::*;\nuse serde::{Serialize, Deserialize};\nuse std::fs::File;\nuse std::path::Path;\nuse std::io::prelude:"
},
{
"path": "src/ctx.rs",
"chars": 19782,
"preview": "use crate::hlua::{self, AnyLuaValue};\nuse crate::errors::*;\nuse crate::runtime;\n\nuse std::fs::File;\nuse std::sync::{Arc,"
},
{
"path": "src/db/mod.rs",
"chars": 15,
"preview": "pub mod mysql;\n"
},
{
"path": "src/db/mysql.rs",
"chars": 2365,
"preview": "use crate::hlua::{AnyHashableLuaValue, AnyLuaValue};\n\nuse std::collections::HashMap;\nuse crate::structs::LuaMap;\n\n\nimpl "
},
{
"path": "src/errors.rs",
"chars": 116,
"preview": "pub use anyhow::{anyhow, bail, format_err, Context, Error, Result};\npub use log::{trace, debug, info, warn, error};\n"
},
{
"path": "src/fsck.rs",
"chars": 1652,
"preview": "use crate::errors::Result;\nuse crate::args::Fsck;\n\nuse std::fs::File;\nuse std::io;\nuse std::io::BufReader;\nuse std::io::"
},
{
"path": "src/html.rs",
"chars": 2266,
"preview": "use crate::errors::*;\n\nuse kuchiki::traits::TendrilSink;\nuse std::collections::HashMap;\nuse crate::hlua::AnyLuaValue;\nus"
},
{
"path": "src/http.rs",
"chars": 7659,
"preview": "use crate::errors::*;\nuse crate::structs::LuaMap;\n\nuse reqwest::Method;\nuse reqwest::header::{HeaderName, HeaderValue, C"
},
{
"path": "src/json.rs",
"chars": 4551,
"preview": "use crate::errors::*;\nuse crate::hlua::AnyLuaValue;\nuse serde_json::{self, Value, Number};\nuse std::collections::HashMap"
},
{
"path": "src/keyboard.rs",
"chars": 1257,
"preview": "// use getch;\nuse getch::Getch;\n\n#[cfg(not(windows))]\nuse termios::{self, tcsetattr, ICANON, ECHO};\n\npub struct Keyboard"
},
{
"path": "src/lib.rs",
"chars": 345,
"preview": "#![allow(clippy::mutex_atomic)]\n\nuse hlua_badtouch as hlua;\n\npub mod args;\npub mod config;\npub mod ctx;\npub mod db;\npub "
},
{
"path": "src/main.rs",
"chars": 10381,
"preview": "use authoscope::args::{self, Args, SubCommand};\nuse authoscope::ctx::Script;\nuse authoscope::errors::*;\nuse authoscope::"
},
{
"path": "src/pb.rs",
"chars": 2861,
"preview": "// this file contains a wrapper around pbr to work around three things:\n//\n// - there is no function to write above the "
},
{
"path": "src/runtime.rs",
"chars": 22342,
"preview": "use crate::hlua;\nuse crate::hlua::{AnyLuaValue, AnyHashableLuaValue, AnyLuaString};\nuse crate::hlua::AnyLuaValue::LuaStr"
},
{
"path": "src/scheduler.rs",
"chars": 5100,
"preview": "use std::str;\nuse crate::ctx::Script;\nuse threadpool::ThreadPool;\nuse crate::keyboard;\nuse crate::errors::Result;\nuse st"
},
{
"path": "src/sockets.rs",
"chars": 4809,
"preview": "use crate::errors::*;\n\nuse bufstream::BufStream;\nuse regex::Regex;\n\nuse std::str;\nuse std::io;\nuse std::io::prelude::*;\n"
},
{
"path": "src/structs.rs",
"chars": 2542,
"preview": "use crate::hlua::{AnyHashableLuaValue, AnyLuaValue};\n\nuse std::collections;\nuse std::collections::HashMap;\n\n\n#[derive(De"
},
{
"path": "src/ulimit.rs",
"chars": 640,
"preview": "use rlimit::Resource;\nuse crate::errors::*;\nuse crate::config::Config;\n\n\npub fn set_nofile(config: &Config) -> Result<()"
},
{
"path": "src/utils.rs",
"chars": 2134,
"preview": "use crate::config::Config;\nuse crate::ctx;\nuse crate::errors::*;\nuse std::str;\nuse std::fs::{self, File};\nuse std::sync:"
}
]
About this extraction
This page contains the full source code of the kpcyrd/authoscope GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 65 files (212.0 KB), approximately 56.6k tokens, and a symbol index with 250 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.