[
  {
    "path": ".gitignore",
    "content": "PackNGo\ntest\ndist\n__*\ntags\nTODO.md\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM golang:alpine\n\nENV CGO_ENABLED=0\nENV GO111MODULE=off\n\nRUN apk add --update-cache upx git make binutils coreutils \\\n    && rm -rf /var/cache/apk/*\n\nRUN upx --version\n\nRUN go version\nRUN go get -d -v github.com/89luca89/pakkero\n\nWORKDIR $GOPATH/src/github.com/89luca89/pakkero\nRUN make\n\nRUN ./dist/pakkero -v\n\nENTRYPOINT [\"./dist/pakkero\"]"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": "all:\n\tgo build -i \\\n\t\t-gcflags=\"-N\" \\\n\t\t-gcflags=\"-nolocalimports\" \\\n\t\t-gcflags=\"-pack\" \\\n\t\t-gcflags=\"-trimpath=.\" \\\n\t\t-asmflags=\"-trimpath=.\" \\\n\t\t-gcflags=\"-trimpath=$$GOPATH/src/\" \\\n\t\t-asmflags=\"-trimpath=$$GOPATH/src/\" \\\n\t\t-ldflags=\"-X github.com/89luca89/pakkero/internal/pakkero.LauncherStub=$$(base64 -w0 data/launcher.go) -s\" \\\n\t\t-o dist/pakkero;\n\tstrip \\\n\t\t-sxX \\\n\t\t--remove-section=.bss \\\n\t\t--remove-section=.comment \\\n\t\t--remove-section=.eh_frame \\\n\t\t--remove-section=.eh_frame_hdr \\\n\t\t--remove-section=.fini \\\n\t\t--remove-section=.fini_array \\\n\t\t--remove-section=.gnu.build.attributes \\\n\t\t--remove-section=.gnu.hash \\\n\t\t--remove-section=.gnu.version \\\n\t\t--remove-section=.got \\\n\t\t--remove-section=.note.ABI-tag \\\n\t\t--remove-section=.note.gnu.build-id \\\n\t\t--remove-section=.shstrtab \\\n\t\t--remove-section=.typelink \\\n\t\tdist/pakkero;\nclean:\n\trm -rf dist/;\n\tgo build -i \\\n\t\t-gcflags=\"-N\" \\\n\t\t-gcflags=\"-nolocalimports\" \\\n\t\t-gcflags=\"-pack\" \\\n\t\t-gcflags=\"-trimpath=.\" \\\n\t\t-asmflags=\"-trimpath=.\" \\\n\t\t-gcflags=\"-trimpath=$$GOPATH/src/\" \\\n\t\t-asmflags=\"-trimpath=$$GOPATH/src/\" \\\n\t\t-ldflags=\"-X github.com/89luca89/pakkero/internal/pakkero.LauncherStub=$$(base64 -w0 data/launcher.go) -s\" \\\n\t\t-o dist/pakkero;\n\tstrip \\\n\t\t-sxXwSgd \\\n\t\t--remove-section=.bss \\\n\t\t--remove-section=.comment \\\n\t\t--remove-section=.eh_frame \\\n\t\t--remove-section=.eh_frame_hdr \\\n\t\t--remove-section=.fini \\\n\t\t--remove-section=.fini_array \\\n\t\t--remove-section=.gnu.build.attributes \\\n\t\t--remove-section=.gnu.hash \\\n\t\t--remove-section=.gnu.version \\\n\t\t--remove-section=.got \\\n\t\t--remove-section=.note.ABI-tag \\\n\t\t--remove-section=.note.gnu.build-id \\\n\t\t--remove-section=.shstrtab \\\n\t\t--remove-section=.typelink \\\n\t\tdist/pakkero\n\ntest: clean\n\tdist/pakkero \\\n\t\t-file /usr/bin/echo -c \\\n\t\t-o /tmp/test.enc \\\n\t\t-offset 2850000 \\\n\t\t-enable-stdout \\\n\t\t-register-dep /usr/bin/bash;\n\tsync;\n\tsh -c \"/tmp/test.enc test\"\n"
  },
  {
    "path": "README.md",
    "content": "# Pakkero\n\n<img src=\"pics/logo.jpg\" data-canonical-src=\"pics/logo.jpg\" width=\"250\" height=\"250\" />\n\nCredit: [alegrey91](https://github.com/alegrey91) for the logo! Thanks!\n\n[![Go Report Card](https://goreportcard.com/badge/github.com/89luca89/pakkero)](https://goreportcard.com/report/github.com/89luca89/pakkero)\n[![GPLv3 license](https://img.shields.io/badge/License-GPLv3-blue.svg)](http://perso.crans.org/besson/LICENSE.html)\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2F89luca89%2Fpakkero.svg?type=small)](https://app.fossa.com/projects/git%2Bgithub.com%2F89luca89%2Fpakkero?ref=badge_small)\n\n## Introduction\n\n**Pakkero** is a binary packer written in Go made for fun and educational purpose.\n\nIts main goal is to take in input a program file (elf binary, script, even appimage) and compress it, protect it from tampering and intrusion.\n\nIt is not recommended for very small files as the launcher itself can vary from ~700kb to ~1.7mb depending on compression. On files above 2.6mb there is gain, else the resulting binary is larger than the original:\n\n```\nbase-bin    1.2M    ->  1.6M\nsmaller-bin 2.4M    ->  2.3M\nsmall-bin   3.7M    ->  3.0M\nmedium-bin  25M     ->  16M\nbig-bin     148M    ->  88M\n```\n\nWith compression disabled, all resulting file size are ~1mb higher, making it suitable for 5+mb files.  \n\n#### How compares to UPX?\n\nTested with a 24mb binary file (I didn't have a big project handy so I just concatenated a bunch of programs from `/usr/bin/` to make one big elf) became:\n\n- 12mb using `upx -9`\n- 13mb using `pakkero -c`\n- 14mb using `pakkero` without compression\n\n## Install\n\nIf you have a [Go](https://golang.org/) environment ready to go, it's as easy as:\n\n```bash\ngo get github.com/89luca89/pakkero\n```\n\nOnce you retrieved you are ready to build:\n\n```bash\ncd $GOPATH/src/github.com/89luca89/pakkero; make\n```\n\nor to test\n\n```bash\ncd $GOPATH/src/github.com/89luca89/pakkero; make test\n```\n\nThe binary file will be in `$GOPATH/src/github.com/89luca89/pakkero/dist`\n\nThe following are hard dependencies:\n\n```\n - go -> to build the launcher\n - ls\n - sed\n - strip -> to strip the launcher\n```\n\nThe following are weak dependencies\n\n```\n - upx -> needed for launcher compression (optional)\n```\n\n**GO 1.13+ needed**\n\n**Dependencies are checked at runtime and an error message will specify what is missing**\n\n# Disclaimer\n\n**This is a for-fun and educational project**, complete protection for a binary is **impossible**, in a way or another there is always someone that will reverse it, even if only based on 0 an 1, so this is more about exploring some arguments that to create an anti-reverse launcher.\n\n---\n\nPakkero is divided in two main pieces, the packer part (Pakkero itself) and the\nlauncher part.\n\n## Part 1: the packer\n\nPakkero can be launched like:\n\n```bash\npakkero --file ./target-file -o ./output-file -register-dep dependency-file -c\n```\n\n![demo](pics/demo.png)\n\n### Usage\n\nTyping `pakker -h` the following output will be shown:\n\n```bash\nUsage: pakkero -file /path/to/file -offset OFFSET (-o /path/to/output) (-c) (-register-dep /path/to/file)\n  -file <file>          Target file to Pack\n  -o   <file>           place the output into <file> (default is <inputfile>.enc), optional\n  -c                    compress the output to occupy less space (uses UPX), optional\n  -offset               Offset where to start the payload (Number of Bytes)\n  -enable-stdout        Whether to wait and handle the process stdout/sterr or not (false by default, optional)\n  -register-dep         /path/to/dependency to analyze and use as fingerprint (absolutea, optional)\n  -v                    Check pakkero version\n```\n\nBelow there is a full explanation of provided arguments:\n\n* **file**: The file we want to pack\n* **o**: (optional) The file output that we will create\n* **c**: (optional) If specified, UPX will be used to further compress the Launcher\n* **offset**: (optional) The number of bytes from where to start the payload (increases if not using compression)\n* **enable-stdout** (optional) whether to enable or not the handling of the stdout/err of the payload <u>**disabled by default, less secure**</u>\n* **regiser-dep** (optional) Path to a file that can be used to register the fingerprint of a dependency to ensure that the Launcher runs only if a file with similar fingerprint is present\n* **v**: Print version\n\n### Packaging\n\n**The main intent is to not alter the payload in any way, this can be very important\nfor types of binary that rely on specific order of instructions or relatively fragile timings.**\n\nThe target of pakkero is not to touch the \"payload\".\nOther packers like UPX works by compressing the sections stored within the Section Table of the executable file, relocating the sections and renaming them. It then alters \nthe entry point where the binary will run. While this is really what defines storically a packer, this in some way or another \"touches\" the payload so can make it unusable (when it works on strict timing, precise elf sections tricks and so on)\n\n#### Building\n\nTo build the project, you can simply use the `Makefile`;\n\n- `make` will compile\n\n- `make test` will compile and run a run with a simple binary (echo)\n\n**Why not using simply go build?**\n\nGo build works fine, but will skip a fundamental step in the building process, **the injection of the launcher stub inside Pakkero source**\n\nThis way the Pakkero binary has inside the source of the Launcher to be used for each packaging.\n\n#### Building using Docker\n\nBuild Pakkero image:\n\n```sh\nsudo docker build . -t pakkero\n```\n\nRun containerized Pakkero:\n\n```sh\nsudo docker run -it -v <target_dir>:/ext pakkero --file /ext/<target_elf> -o /ext/<target_elf>.packed\n```\n\n#### Building using Podman\n\nBuild Pakkero image:\n\n```sh\nsudo podman build . -t pakkero\n```\n\nRun containerized Pakkero:\n\n```sh\nsudo podman run -it -v <target_dir>:/ext pakkero --file /ext/<target_elf> -o /ext/<target_elf>.packed\n```\n\n#### Payload\n\nFor this purpose the payload is simply compressed using zlib then encrypted using AES256-GCM\n\nDuring encryption, some basic operations are also performed on the payload:\n\n- putting garbage random values before and after the payload to mask it\n- reverse it and change each byte endianess\n\nEncryption password is the hash SHA512 of the compiled launcher itself together with the garbage values added to fill the file till the offset, thus providing\nsome integrity protection and anti-tampering.\n\n#### Offset\n\nThe offset will decide **where in the output file the payload starts**.\n\nPut simply, after the launcher is compiled (more on the launcher later), the payload is\nattached to it. The offset ensures that the payload can be put anywhere after it.\nAll the space after the launcher until the payload is filled with random garbage.\n\n![payload](./pics/decryption.png)\n\nBeing part of the password itself, greater offset will make stronger the encryption, but\nenlarge the final output file.\n\nOptimal value are **at least** 800000 when compression is enabled and **1900000** when disabled. *If not specified a random one will be chosen upon creation.\n\n### Obfuscation\n\nThe final thing the packer does is compiling the launcher. To protect some of the fundamental part of it (namely where the offset starts) the launcher is *obfuscated* and heavily stripped down.\n\nThe technique utilized for obfuscating the function and variables name is based on typo-squatting:\n\n![obfuscation](./pics/obfuscation.png)\n\nThis is done in a pretty naive way, simply put, in the launcher each function/variable which name has to be obfuscated, needs to start with the suffix **ob**, it will be then put into a secret map, and each occurrence will be replaced in the file with a random string of length 128, composed only of runes that have similar shape, namely:\n\n```go\n    mixedRunes := []rune(\"0OÓÕÔÒÖŌŎŐƠΘΟ\")\n```\n\nFor pure strings in the launcher, they are detected using regular expressions, finding\nall the words that are comprised between the three type of ticks supported in go\n\n```\n`\n'\n\"\n```\n\nAll of the strings found this way, are then replaced with a function that performs a simple operation of reconstruction of the original string:\n\n```go\nfunc ÓΘŌOÒŐÒŌÓÒOŎΘOΟ0ŐÒÖŎÕΟΘÕÓÕÓŎÓŌÕ0ŎŌΘÕŎÕ() string {\n    ŌÒ0ŎŎŐÓÖÖΘO0ŌŌŌÒŌŌÒƠÔÖΘŐÖΟŎƠƠ00Õ0ÖÕ0ÖŐŐÓΟŌΟ := []string{\"Ò0ƠŐÖŐŎΘÖƠÔÖÕÓΘÕÕŌŎŐƠÔΘΘƠ\", \"ÔÒÕΟƠŐÒŌOƠÖ\", \"ƠΘŐÒƠΘŌ00ΘΘΟÔŎŎΘŐƠŐΘŎΟÕÖÕÖΟÖΘÒÖ\"}\n    var ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ []byte\n    for _, ŌΘƠÔÕÔΘÔOÔOŐΟΘŌΘƠÔÕÔΘÔOÔOŐΟΘ := range ŌÒ0ŎŎŐÓÖÖΘO0ŌŌŌÒŌÕÒÔÕŌŎ00ÔÔÒOƠÓÕÔÒ0ΘƠΘŐ0OOŎÓÒŐ0Õ0ÓOÕÓŐƠŌŎÕÖ0ÕÖÔŌΟΟŌÒÖÒÖOΟOÒ0ÖŐŐÓΟŌΟ {\n        ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ = append(ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ, byte(len([]rune(ŌΘƠÔÕÔΘÔOÔOŐΟΘŌΘƠÔÕÔΘÔOÔOŐΟΘ))))\n    }\n    return string(ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ)\n}\n```\n\nA slice of string is generated, with each element has a lenght derived from the byte value of the original char of the original string.\nThis way each byte of the original string is computed and calculated as the lenght of the correspondent string, casted to rune slice.\n\nThe launcher is compiled then using:\n\n```go\n    flags = []string{\"build\", \"-a\",\n        \"-trimpath\",\n        \"-gcflags\",\n        \"-N -l -nolocalimports\",\n        \"-ldflags\",\n        \"-s -w -extldflags -static\",\n    }\n    exec.Command(\"go\", flags...)\n```\n\nFile is the **stripped**, using `strip` with the flags:\n\n```bash\n    -sxX\n    --remove-section=.bss\n    --remove-section=.comment\n    --remove-section=.eh_frame\n    --remove-section=.eh_frame_hdr\n    --remove-section=.fini\n    --remove-section=.fini_array\n    --remove-section=.gnu.build.attributes\n    --remove-section=.gnu.hash\n    --remove-section=.gnu.version\n    --remove-section=.gosymtab\n    --remove-section=.got\n    --remove-section=.note.ABI-tag\n    --remove-section=.note.gnu.build-id\n    --remove-section=.note.go.buildid\n    --remove-section=.shstrtab\n    --remove-section=.typelink\n```\n\nAdditionally, if using *UPX*, their headers are **removed and replaced with randomness**, to ensure simple things like `upx -d` will not work.\n\nAdditionally a series of extra words are removed from the binary and replaced with random bytes, to make it harder to do static analysis:\n\n```\n    .gopclntab\n    .go.buildinfo\n    .noptrdata\n    .noptrbss\n    .data\n    .rodata\n    .text\n    .itablink\n    .shstrtab\n    .data\n    .dynamic\n    .dynstr\n    .dynsym\n    .gnu.version_r\n    .gopclntab\n    .got.plt\n    .init_array\n    .interp\n    .itablink\n    .rela.dyn\n    .rela.plt\n    .tbss\n    .plt\n    .init\n    name runtime command cmd\n    ptr process unicode main\n    path get reflect context\n    debug fmt sync sort\n    size heap fatal call\n    fixed slice bit file\n    read write buffer encrypt\n    decrypt hash state\n    external internal float\n    env trace pid\n```\n\nOutput of readelf to see the effect:\n\n![readelf](./pics/readelf.png)\n\n#### File Entropy\n\nUsing binwalk to analyze the file entropy can give some hint on how the process works:\n\nThis is the entropy of the binary we want to package (for this example /usr/bin/bash):\n\n![original-entropy.png](./pics/original-entropy.png)\n\nThis is the entropy of a packaged binary **without compression**\n\n![uncompressed](./pics/uncompressed-entropy.png)\n\nThis is the entropy of a packaged binary **with compression**\n\n![compressed](./pics/compressed-entropy.png)\n\nIn both cases (but mainly the first) it is possible to see when the launcher stops and\nthe garbage before the payload starts. This is really not a problem, because the offset of garbage is both pre-poned **and** post-poned to the payload, and the \"secret number\" of when it starts is kept inside the launcher and computed at runtime.\n\nThis is obviously vulnerable, reversing the binary will reveal the secret, all the launcher part is dedicated to the implementation of a series of measures to **block dynamic analysis** and try to force static analysis.\n\n## Part 2: the launcher\n\nThe launcher is the second part of the project, it allows to decompress, decrypt and launch the payload without touching storage, but using a file descriptor in RAM.\n\nThis is a well known technique as it is possible to read:\n\n- [In-Memory-Only ELF Execution (Without tmpfs) Mrs Quis Will Think of a Better Title](https://magisterquis.github.io/2018/03/31/in-memory-only-elf-execution.html)\n\n- [ELF in-memory execution](https://blog.fbkcs.ru/en/elf-in-memory-execution/)\n\nand in many other places in C programming literature.\n\n```\nPut briefly, use syscall to create a memory file descriptor (syscall 319 for amd64),\nwrite the plaintext payload here, and execute. \nThe fd will be automatically removed after the execution without \nleaving trace on the storage.\n```\n\n### Possible weakpoints\n\nThis approach is vulnerable to \n\n1. \"memory dump attack\", for example pausing the VM during execution and manually search the ram for all file descriptors until you find the right one\n\n2. \"proc dump attack\", in linux all the file descriptors are in `/proc` so dumping to another disk the complete folder will in a way or another dump the decrypted payload (if done before the execution finishes), **this is even more accentuated if stdout management is enabled**\n\n3. dynamic analysis, during execution \"pausing\" the process and spot the right fd\n\n4. reversing the binary to find the \"secret\" (which in our case is the offset) and from there, reverse the encryption process and reconstruct the plaintext\n\nFor point 1, it is possible to insert hypervisor detection, sandbox detection etc... it is in my TODO list, but I would leave it optional, in case you genuinely want to run the binary in VMs or Dockers.\n\nPoint 3 (and by consequence point 4) can be made harder by blocking dynamic analysis detecting debuggers, tracers and so on... \n\nForcing static analysis of the decompiled code is already a big step forward in protecting the binary execution.\n\n### Anti-debug\n\nImplemented here are a series of anti-debug techniques that are quite common in C/C++, from the **double-ptrace method** to the **ppid analysis** and breakpoints interception.\n\nFirst line of protection is breakpoints interception, on linux, a breakpoints is equivalent to signal *SIGILL* and *SIGTRAP* so:\n\n```go\n/*\nBreakpoint on linux are 0xCC and will be interpreted as a\nSIGTRAP, we will intercept them.\n*/\nfunc obSigTrap(obInput chan obOS.Signal) {\n    obMySignal := <-obInput\n    switch obMySignal {\n    case obSyscall.SIGILL:\n        obExit()\n    case obSyscall.SIGTRAP:\n        obExit()\n    default:\n        return\n    }\n}\n```\n\nThis is pretty basic, so we go ahead and try to block **ptrace**:\n\n```go\n// attach to PTRACE, register if successful\n// attach A G A I N , register if unsuccessful\n// this protects against custom ptrace (always returning 0)\n// against NOP attacks and LD_PRELOAD attacks\nfunc obPtraceDetect() {\n\n\tvar obOffset = 0\n\n\tobProc, _ := obOS.FindProcess(obOS.Getppid())\n\n\tobErr := obSyscall.PtraceAttach(obProc.Pid)\n\tif obErr == nil {\n\t\tobOffset = 5\n\t}\n\n\tobErr = obSyscall.PtraceAttach(obProc.Pid)\n\tif obErr != nil {\n\t\tobOffset *= 3\n\t}\n\n\tif obOffset != (3 * 5) {\n\t\tobProc.Signal(obSyscall.SIGCONT)\n\t\tprintln(1)\n\n\t\treturn\n\t}\n\n\tobErr = obSyscall.PtraceDetach(obProc.Pid)\n\tif obErr != nil {\n\t\tobProc.Signal(obSyscall.SIGCONT)\n\t\tprintln(0)\n\n\t\treturn\n\t}\n\n\tobProc.Signal(obSyscall.SIGCONT)\n\tprintln(0)\n}\n```\n\n*Double ptraceme* ensures that tampering the ptrace loading with a fake ptrace lib that always returns 0, would result in a failure.\n\nCMD Line detection, would check for common processes for debugging, this is pretty naive check:\n\n```go\n/*\nCheck the process cmdline to spot if a debugger is inline\n*/\nfunc obParentCmdLineDetect() {\n    obPidParent := obOS.Getppid()\n\n    obNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n        \"/cmdline\"\n    obStatParent, _ := obUtilio.ReadFile(obNameFile)\n\n    if obStrings.Contains(string(obStatParent), \"gdb\") ||\n        obStrings.Contains(string(obStatParent), \"dlv\") ||\n        obStrings.Contains(string(obStatParent), \"edb\") ||\n        obStrings.Contains(string(obStatParent), \"frida\") ||\n        obStrings.Contains(string(obStatParent), \"ghidra\") ||\n        obStrings.Contains(string(obStatParent), \"godebug\") ||\n        obStrings.Contains(string(obStatParent), \"ida\") ||\n        obStrings.Contains(string(obStatParent), \"lldb\") ||\n        obStrings.Contains(string(obStatParent), \"ltrace\") ||\n        obStrings.Contains(string(obStatParent), \"strace\") ||\n        obStrings.Contains(string(obStatParent), \"valgrind\") {\n        obExit()\n    }\n}\n```\n\n```go\n/*\nCheck the process cmdline to spot if a debugger is the PPID of our process\n*/\nfunc obParentDetect() {\n    obPidParent := obOS.Getppid()\n\n    obNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n        \"/stat\"\n    obStatParent, _ := obUtilio.ReadFile(obNameFile)\n\n    if obStrings.Contains(string(obStatParent), \"gdb\") ||\n        obStrings.Contains(string(obStatParent), \"dlv\") ||\n        obStrings.Contains(string(obStatParent), \"edb\") ||\n        obStrings.Contains(string(obStatParent), \"frida\") ||\n        obStrings.Contains(string(obStatParent), \"ghidra\") ||\n        obStrings.Contains(string(obStatParent), \"godebug\") ||\n        obStrings.Contains(string(obStatParent), \"ida\") ||\n        obStrings.Contains(string(obStatParent), \"lldb\") ||\n        obStrings.Contains(string(obStatParent), \"ltrace\") ||\n        obStrings.Contains(string(obStatParent), \"strace\") ||\n        obStrings.Contains(string(obStatParent), \"valgrind\") {\n        obExit()\n    }\n}\n```\n\nthis goes in conjunction with the TracePid check to see if a parent is tracing us:\n\n```go\n/*\nCheck the process status to spot if a debugger is active using the TracePid key\n*/\nfunc obParentTracerDetect() {\n    obPidParent := obOS.Getppid()\n\n    obNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n        \"/status\"\n    obStatParent, _ := obUtilio.ReadFile(obNameFile)\n    obStatLines := obStrings.Split(string(obStatParent), \"\\n\")\n\n    for _, obValue := range obStatLines {\n        if obStrings.Contains(obValue, \"TracerPid\") {\n            obSplitArray := obStrings.Split(obValue, \":\")\n            obSplitValue := obStrings.Replace(obSplitArray[1], \"\\t\", \"\", -1)\n\n            if obSplitValue != \"0\" {\n                obExit()\n            }\n        }\n    }\n}\n```\n\nand verification that the process cmdline corresponds to \"argv[0]\" (for example, launching `strace mybin arg1` would result in a cmdline of `strace` and argv[0] of `mybin`\n\n```go\n/*\nCheck the process cmdline to spot if a debugger is launcher\n\"_\" and Args[0] should match otherwise\n*/\nfunc obEnvArgsDetect() {\n    obLines, _ := obOS.LookupEnv(\"_\")\n    if obLines != obOS.Args[0] {\n        obExit()\n    }\n}\n```\n\nand check if there is none of the known debuggers inline with the command\n\n```go\n/*\nCheck the process cmdline to spot if a debugger is inline\n\"_\" should not contain the name of any debugger\n*/\nfunc obEnvParentDetect() {\n    obLines, _ := obOS.LookupEnv(\"_\")\n    if obStrings.Contains(obLines, \"gdb\") ||\n        obStrings.Contains(obLines, \"dlv\") ||\n        obStrings.Contains(obLines, \"edb\") ||\n        obStrings.Contains(obLines, \"frida\") ||\n        obStrings.Contains(obLines, \"ghidra\") ||\n        obStrings.Contains(obLines, \"godebug\") ||\n        obStrings.Contains(obLines, \"ida\") ||\n        obStrings.Contains(obLines, \"lldb\") ||\n        obStrings.Contains(obLines, \"ltrace\") ||\n        obStrings.Contains(obLines, \"strace\") ||\n        obStrings.Contains(obLines, \"valgrind\") {\n        obExit()\n    }\n}\n```\n\nAlso a pretty common check to do if we are in a debugger is to see if ENV has the variables LINES and COLUMNS:\n\n```go\n/*\nCheck the process cmdline to spot if a debugger is active\nmost debuggers (like GDB) will set LINE,COLUMNS or LD_PRELOAD\nto function, we try to spot this\n*/\nfunc obEnvDetect() {\n    _, obLines := obOS.LookupEnv(\"LINES\")\n    _, obColumns := obOS.LookupEnv(\"COLUMNS\")\n    _, obLineLdPreload := obOS.LookupEnv(\"LD_PRELOAD\")\n\n    if obLines || obColumns || obLineLdPreload {\n        obExit()\n    }\n}\n```\n\nThis can give false positives (example the embedded terminal in VSCode or VIM), but worth checking for a normal environment.\n\nAlso banally checking for LD_PRELOAD env variable present:\n\n```go\n/*\nCheck the process is launcher with a LD_PRELOAD set.\nThis can be an injection attack (like on frida) to try and circumvent\nvarious restrictions (like ptrace checks)\n*/\nfunc obLdPreloadDetect() {\n    obKey := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)\n    obValue := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)\n\n    err := obOS.Setenv(obKey, obValue)\n    if err != nil {\n        obExit()\n    }\n\n    obLineLdPreload, _ := obOS.LookupEnv(obKey)\n    if obLineLdPreload == obValue {\n        err := obOS.Unsetenv(obKey)\n        if err != nil {\n            obExit()\n        }\n    } else {\n        obExit()\n    }\n}\n```\n\nto make it more resilient to \"false environment\" attacks, we also try and set a random key-value in the environment, and check if it works, to ensure we do not have a \"fake\" environment (always empty for example).\n\nThis type of checks are pretty basic and easy to port from C to Go. \n\nA couple of checks I would like to port are for example the heap relocation check, as explained in this repo: [debugmenot/test_nearheap.c at master · kirschju/debugmenot · GitHub](https://github.com/kirschju/debugmenot/blob/master/src/test_nearheap.c) \n\n>  GDB relocates the heap to the end of the bss section\n\nThis type of check is not easily done in Go because *go does not support pointer arithmetic*, CGO should be the way, but would make it dynamically linked for the C part (or twice the size if statically linked)\n\n### Making difficult to reverse\n\nTo add to this in many points of the source code it is possible to see that a comment is made:\n\n`//OB_CHECK`\n\nThis is because during the obfuscation phase, every time we encounter this string, we will inject a random permutation of ALL of the anti-debug tricks that will be executed in parallel using go routines.\n\n```go\n/*\nGenerateRandomAntiDebug will Insert random order of anti-debug check\ntogether with inline compilation to induce big number\nof instructions in random order\n*/\nfunc GenerateRandomAntiDebug(input string) string {\n    lines := strings.Split(input, \"\\n\")\n    randomChecks := []string{\n        `obDependencyCheck()`,\n        `obEnvArgsDetect()`,\n        `obParentTracerDetect()`,\n        `obParentCmdLineDetect()`,\n        `obEnvDetect()`,\n        `obEnvParentDetect() `,\n        `obLdPreloadDetect()`,\n        `obParentDetect()`,\n    }\n    // find OB_CHECK and put the checks there.\n    for i, v := range lines {\n        if strings.Contains(v, \"// OB_CHECK\") {\n            threadString := \"\"\n            checkString := \"\"\n            // randomize order of check to replace\n            for j, v := range ShuffleSlice(randomChecks) {\n                threadString = threadString + \"go \" + v + \";\"\n                checkString += v\n\n                if j != (len(randomChecks) - 1) {\n                    checkString += `||`\n                }\n            }\n            // add action in case of failed check\n            lines[i] = threadString\n        }\n    }\n    // back to single string\n    return strings.Join(lines, \"\\n\")\n}\n```\n\nThe generated source will be filled with this always-changing code, that will make difficult to use NOP attacks, manual jump using breakpoints and make confusion in the  graph view of disassemblers like Cutter, IDA Pro or Ghidra.\n\nSo the main, for example, becomes something like:\n\n```go\nfunc main() {\n    // Prepare to intercept SIGTRAP\n    ÖÖΘÓOŐƠOΟŌΟŐÔÒÕÓÒÒÒOŎŌO0ÔŌÓÖOŐŎΟŌŌŌÔ0OOŌŐΘŎΘÔOOOÓΘŐΘ00ƠŎÖÖ0ÔÕÕŎŎŎÒÖO00ŎÔΘÓOÖ0ΘÔOΟÒŐŐƠÒΘÒ0ŎŌŌÖΟÓ0ƠŎŌŌΟŎΘŐÖÒŐΘÔÕOŌÕŎÒŎÔŌÓƠÓŌŐΟΟÒÒƠ := make(chan ÒÕ0ΟÓŎ0ÖÒŌƠÒΘ0ÓΘΘƠΟÕƠΘÕO0OŐOŎOƠŎƠÖOOÒÖÒO0ÕÕÓÖΘΘÓÒÕŌŐΘŐƠÖOÕΘÔÕÖƠƠŌŐƠ0ÖÖƠŌΟ0ΘƠÕÒÔƠÒOÒΘÔΟÒ0OÕOŌÕΘÒÒŐÓΟÕÖÕŎΟƠŎOŌÔΟŎŐÒŎŎOƠOO0Ō0ŌŐÓÖŎÖ.Signal, 1)\n    ÔƠÕΟÒΘΘÖŎ0ÓŎÒŎOÕΟÒ0ŐΘƠÓOƠOÔÒÕŐ0OÔÒÓΟOÓŐŐŎΟÒŐÒ0ŌΟO0ΟOÔOΘOƠƠÒ0ŐÓΘÖΘΘÕÖΟÔÖÖΘÔŎÕ00ŐÖÔŎŎŌ0ŐƠOÖÖΟΘÕÓŌÖÔÖÕÒƠƠÓÓ0ÒÖƠŌÔÔŐƠŌOŐÔÒ0ŐÕÖOŐŌŎÔÔ.Notify(ÖÖΘÓOŐƠOΟŌΟŐÔÒÕÓÒÒÒOŎŌO0ÔŌÓÖOŐŎΟŌŌŌÔ0OOŌŐΘŎΘÔOOOÓΘŐΘ00ƠŎÖÖ0ÔÕÕŎŎŎÒÖO00ŎÔΘÓOÖ0ΘÔOΟÒŐŐƠÒΘÒ0ŎŌŌÖΟÓ0ƠŎŌŌΟŎΘŐÖÒŐΘÔÕOŌÕŎÒŎÔŌÓƠÓŌŐΟΟÒÒƠ, O0OÓΟ0ŎŐOƠOŎƠ0ÓƠΘÒƠÕƠÖÓÕŎƠŎOΟΘƠŌƠÖÔÓÔÕŐŎŌŐŐƠΘO0Ô0Ò0OÕƠ0ŐÓÖÔ0ŎΘÕÔÔŎƠÓÔOÕO0ÓΘÒOŎŎÔ0ÓƠ0ÖŎŎΘO0ƠŐÖŐŌOOOΟOÒΘΟΟƠΘΟ0ÖÔŎƠÓŌÕÕOΘÕŎŐŌΘOŐΘÕŌ.SIGTRAP, O0OÓΟ0ŎŐOƠOŎƠ0ÓƠΘÒƠÕƠÖÓÕŎƠŎOΟΘƠŌƠÖÔÓÔÕŐŎŌŐŐƠΘO0Ô0Ò0OÕƠ0ŐÓÖÔ0ŎΘÕÔÔŎƠÓÔOÕO0ÓΘÒOŎŎÔ0ÓƠ0ÖŎŎΘO0ƠŐÖŐŌOOOΟOÒΘΟΟƠΘΟ0ÖÔŎƠÓŌÕÕOΘÕŎŐŌΘOŐΘÕŌ.SIGILL)\n\n    go ÔΘƠƠƠŎÔŐŌÖOŐÒÓO0ÖΘΘ0ΘŐŎΘ0ÖŌOÒŐÕ0ÒŐ0ƠÖÕŐÓÕÕŌƠƠÖÒÔŎÔÔÖÕŐÖΟÒÖŐÓÕÔÓΘΟÕƠOŐ0ŌÓÖÔOƠÓ0ŎÓ0ŎOÒΟÓOΘÔΟÒÔƠΘŐÒΘΘÓƠΟƠÓÒÓƠ0Ŏ0ÓÒŌOŌÕÕΟŌOΘ0ŎƠŎ0ÕƠƠ(ÖÖΘÓOŐƠOΟŌΟŐÔÒÕÓÒÒÒOŎŌO0ÔŌÓÖOŐŎΟŌŌŌÔ0OOŌŐΘŎΘÔOOOÓΘŐΘ00ƠŎÖÖ0ÔÕÕŎŎŎÒÖO00ŎÔΘÓOÖ0ΘÔOΟÒŐŐƠÒΘÒ0ŎŌŌÖΟÓ0ƠŎŌŌΟŎΘŐÖÒŐΘÔÕOŌÕŎÒŎÔŌÓƠÓŌŐΟΟÒÒƠ)\n\n    // ÔOÒŎ00ƠÒŎΟOÓΟÖΟOÖΘÓƠƠƠŎÖŌŐŐÒÓÔOŎÒÔΘŌΟÓŐÒΟƠOÕÖÕƠƠÕŎÔÔÒΟOÖO0ŐÔÓÓƠÒ0ŎΘOÒŎOŐÔŌƠÓÒÕÕΟO0ÓƠÒŎŌÖOŌÖOÕÒƠŐÓΟŐÔÔŎŐÓÔÓOƠΘOOŎ0ƠΘÓΘÕÔÕƠÓΘÒÔŐΟÒ()\n    go ÔŐŌŌÒÓ0OΟO0ÖΟŌ0ƠÒ0ÒŌÔOΟΟÖŎÕ0ΘÓΘOOΟΟΘ0Ơ0ΘŐÕ0ΟÔŐ0ŐŌÕ00ŌOΟΟÒÕÒÖŌÓOOÒÔΘÒΘÒÔŌŎΟÒŐŌÕÒÕŎÖÒÖÕΘ00OÖÓŌÓÖÖÓÔƠΘŌ0ÓÕ0ŌÖΘOÖ0ÓŐƠ0ΟÖ00ŌŐŐΘΘÕÒƠÕΟ()\n    go ÖƠŎŎΘΟÓÓÒÖÒ0ÓΘŎÖΘŌ0ŎOÕÔÓƠÔÔΘŌÔΘ0OÕOΟOÕƠŌÒŎ0O0ŎΘΟÒÕΟΟÓ0ŎΟÒΘÕΟÖŎÕÔOÕOΘΘŐÖŌŐΟÔΟÖΟ0OÔÓ0ΟŐOŌÕŌOŌOÕÒÒΘΟŎƠΟÒŌ0ƠΟÔOÒÓÒΟŐÕÒŌƠÔÖ0ŐÖÖÖÓΟƠŌÕ()\n    go ƠΘÔŐŎŌÒŌÖŌΟŎOΟŐŎŎΘOƠÔ0ŐƠΘÒΟƠŐŌ0ŌΘΟΟÒŎÖÓ0ÒΟŐ0ƠΘŌÒÔÔŌƠŌÖOƠÓÔŌOÓ0OŐÕÒ0ŌÖÓŎÕŎÕÓÓ0ÒΘÖΟΘŎÕÓƠŐΟÕΟŌÔŎŌÓOÒÓ0Ŏ0ΟÕÔÒŌƠΘŌΟŎŐΘƠÔÓŐΘŎÔŌŌO0ƠÒÖÖ()\n    go ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()\n    go ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()\n    go ÔŌÕŌŐ0ŐÓÖΘŐÖΟŎΟƠŎOÖÖÕÒΘƠŐΟÓΟΘOÒƠΟ0ÒÒÖÖŌŎŌΘƠƠOΟÒƠΟΘOÓÕŌÕÒÕO0ŎOÔŐOÖŎÓÔOO0OÕŌOΘ0ÒƠƠÔŌÔÔÔŐΟ0ΘΘOŌOÒÕÒÕÕOÔÕŐŌΟÒŌÔ00ÖƠÔΟ0ΟÔŐΟƠÖÕΘ0ÖΟŌÖÖ()\n    go ÒŎÒ0ΘŐŐÔƠΘÒŐŎΘÓÕÕÔŎÖ0ŌÖÖΟÖÓÔÓÒÖÖŌŐΘŌ0ÕÖŎÓΟŌŌÒÖ0ΘÖOΘŎŎÖΘΟÓÒƠΟŐOƠOΘΘÓ0ÕΘŐƠÔÖΟΟ0OΘÖΘŎΟŐÕΘŐΟÓÓƠƠŐÒΟÖΘOŌƠΟΘŎ0ÒΟƠƠÔŎ00ŌÕÓÒ0ŌŎÒOƠŎÖŐÕÓƠ()\n    go ŎÓÕƠŌOŌΟÖÓ0ÒÓΘΟ0ƠŎÖΟŌŎÕÒÕÓŎÖÕƠÒŎŐƠÒƠ0ÒƠÖÕŎÒŐÓÔÓÒ0ΟÕŌÒŐOŐŌÖOÕƠƠÔŎÖ0ÒÓÒÕOÖÕƠÔÕOÔÖΟΘÕÔ0OÕƠÓOÓOÔÖÒ0ΟÖOÖÔΘŌOŌŎΘΘΘ0ŐŌOÔÒΟƠ0ŐÓÕŐÔŐΟÒŐÒΟ()\n    ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()\n    go ÔŐŌŌÒÓ0OΟO0ÖΟŌ0ƠÒ0ÒŌÔOΟΟÖŎÕ0ΘÓΘOOΟΟΘ0Ơ0ΘŐÕ0ΟÔŐ0ŐŌÕ00ŌOΟΟÒÕÒÖŌÓOOÒÔΘÒΘÒÔŌŎΟÒŐŌÕÒÕŎÖÒÖÕΘ00OÖÓŌÓÖÖÓÔƠΘŌ0ÓÕ0ŌÖΘOÖ0ÓŐƠ0ΟÖ00ŌŐŐΘΘÕÒƠÕΟ()\n    go ƠΘÔŐŎŌÒŌÖŌΟŎOΟŐŎŎΘOƠÔ0ŐƠΘÒΟƠŐŌ0ŌΘΟΟÒŎÖÓ0ÒΟŐ0ƠΘŌÒÔÔŌƠŌÖOƠÓÔŌOÓ0OŐÕÒ0ŌÖÓŎÕŎÕÓÓ0ÒΘÖΟΘŎÕÓƠŐΟÕΟŌÔŎŌÓOÒÓ0Ŏ0ΟÕÔÒŌƠΘŌΟŎŐΘƠÔÓŐΘŎÔŌŌO0ƠÒÖÖ()\n    go ÖƠŎŎΘΟÓÓÒÖÒ0ÓΘŎÖΘŌ0ŎOÕÔÓƠÔÔΘŌÔΘ0OÕOΟOÕƠŌÒŎ0O0ŎΘΟÒÕΟΟÓ0ŎΟÒΘÕΟÖŎÕÔOÕOΘΘŐÖŌŐΟÔΟÖΟ0OÔÓ0ΟŐOŌÕŌOŌOÕÒÒΘΟŎƠΟÒŌ0ƠΟÔOÒÓÒΟŐÕÒŌƠÔÖ0ŐÖÖÖÓΟƠŌÕ()\n    go ÒŎÒ0ΘŐŐÔƠΘÒŐŎΘÓÕÕÔŎÖ0ŌÖÖΟÖÓÔÓÒÖÖŌŐΘŌ0ÕÖŎÓΟŌŌÒÖ0ΘÖOΘŎŎÖΘΟÓÒƠΟŐOƠOΘΘÓ0ÕΘŐƠÔÖΟΟ0OΘÖΘŎΟŐÕΘŐΟÓÓƠƠŐÒΟÖΘOŌƠΟΘŎ0ÒΟƠƠÔŎ00ŌÕÓÒ0ŌŎÒOƠŎÖŐÕÓƠ()\n    go ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()\n    go ŎÓÕƠŌOŌΟÖÓ0ÒÓΘΟ0ƠŎÖΟŌŎÕÒÕÓŎÖÕƠÒŎŐƠÒƠ0ÒƠÖÕŎÒŐÓÔÓÒ0ΟÕŌÒŐOŐŌÖOÕƠƠÔŎÖ0ÒÓÒÕOÖÕƠÔÕOÔÖΟΘÕÔ0OÕƠÓOÓOÔÖÒ0ΟÖOÖÔΘŌOŌŎΘΘΘ0ŐŌOÔÒΟƠ0ŐÓÕŐÔŐΟÒŐÒΟ()\n    go ÔŌÕŌŐ0ŐÓÖΘŐÖΟŎΟƠŎOÖÖÕÒΘƠŐΟÓΟΘOÒƠΟ0ÒÒÖÖŌŎŌΘƠƠOΟÒƠΟΘOÓÕŌÕÒÕO0ŎOÔŐOÖŎÓÔOO0OÕŌOΘ0ÒƠƠÔŌÔÔÔŐΟ0ΘΘOŌOÒÕÒÕÕOÔÕŐŌΟÒŌÔ00ÖƠÔΟ0ΟÔŐΟƠÖÕΘ0ÖΟŌÖÖ()\n    go ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()\n    ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()\n    go ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()\n    go ÔŌÕŌŐ0ŐÓÖΘŐÖΟŎΟƠŎOÖÖÕÒΘƠŐΟÓΟΘOÒƠΟ0ÒÒÖÖŌŎŌΘƠƠOΟÒƠΟΘOÓÕŌÕÒÕO0ŎOÔŐOÖŎÓÔOO0OÕŌOΘ0ÒƠƠÔŌÔÔÔŐΟ0ΘΘOŌOÒÕÒÕÕOÔÕŐŌΟÒŌÔ00ÖƠÔΟ0ΟÔŐΟƠÖÕΘ0ÖΟŌÖÖ()\n    go ƠΘÔŐŎŌÒŌÖŌΟŎOΟŐŎŎΘOƠÔ0ŐƠΘÒΟƠŐŌ0ŌΘΟΟÒŎÖÓ0ÒΟŐ0ƠΘŌÒÔÔŌƠŌÖOƠÓÔŌOÓ0OŐÕÒ0ŌÖÓŎÕŎÕÓÓ0ÒΘÖΟΘŎÕÓƠŐΟÕΟŌÔŎŌÓOÒÓ0Ŏ0ΟÕÔÒŌƠΘŌΟŎŐΘƠÔÓŐΘŎÔŌŌO0ƠÒÖÖ()\n    go ÒŎÒ0ΘŐŐÔƠΘÒŐŎΘÓÕÕÔŎÖ0ŌÖÖΟÖÓÔÓÒÖÖŌŐΘŌ0ÕÖŎÓΟŌŌÒÖ0ΘÖOΘŎŎÖΘΟÓÒƠΟŐOƠOΘΘÓ0ÕΘŐƠÔÖΟΟ0OΘÖΘŎΟŐÕΘŐΟÓÓƠƠŐÒΟÖΘOŌƠΟΘŎ0ÒΟƠƠÔŎ00ŌÕÓÒ0ŌŎÒOƠŎÖŐÕÓƠ()\n    go ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()\n    go ÔŐŌŌÒÓ0OΟO0ÖΟŌ0ƠÒ0ÒŌÔOΟΟÖŎÕ0ΘÓΘOOΟΟΘ0Ơ0ΘŐÕ0ΟÔŐ0ŐŌÕ00ŌOΟΟÒÕÒÖŌÓOOÒÔΘÒΘÒÔŌŎΟÒŐŌÕÒÕŎÖÒÖÕΘ00OÖÓŌÓÖÖÓÔƠΘŌ0ÓÕ0ŌÖΘOÖ0ÓŐƠ0ΟÖ00ŌŐŐΘΘÕÒƠÕΟ()\n    go ŎÓÕƠŌOŌΟÖÓ0ÒÓΘΟ0ƠŎÖΟŌŎÕÒÕÓŎÖÕƠÒŎŐƠÒƠ0ÒƠÖÕŎÒŐÓÔÓÒ0ΟÕŌÒŐOŐŌÖOÕƠƠÔŎÖ0ÒÓÒÕOÖÕƠÔÕOÔÖΟΘÕÔ0OÕƠÓOÓOÔÖÒ0ΟÖOÖÔΘŌOŌŎΘΘΘ0ŐŌOÔÒΟƠ0ŐÓÕŐÔŐΟÒŐÒΟ()\n    go ÖƠŎŎΘΟÓÓÒÖÒ0ÓΘŎÖΘŌ0ŎOÕÔÓƠÔÔΘŌÔΘ0OÕOΟOÕƠŌÒŎ0O0ŎΘΟÒÕΟΟÓ0ŎΟÒΘÕΟÖŎÕÔOÕOΘΘŐÖŌŐΟÔΟÖΟ0OÔÓ0ΟŐOŌÕŌOŌOÕÒÒΘΟŎƠΟÒŌ0ƠΟÔOÒÓÒΟŐÕÒŌƠÔÖ0ŐÖÖÖÓΟƠŌÕ()\n\n\n.....\n```\n\n### \n\n### Dependency Registration\n\nAnother form of protection, is the *dependency registration*.\n\nThe idea behind it is to protect not only elf binaries, but also executable scripts, like python, bash, perl, php or anything with a shebang.\n\nA common attack that is possible is a \"man in the middle execution\", for example, let the payload be a bash script, in the moment of execution `/usr/bin/env bash` is called to execute the content of the script.\n\nIf in the environment (or really with a symlink on /usr/bin/bash) we put something like:\n\n```bash\n#!/bin/sh\n\ncp $0 /tmp/plaintext\n\n/usr/bin/real-bash $@\n```\n\nThis will result in a transparent execution but a dumped plaintext in /tmp\n\n(credits for the attack idea to [mrnfrancesco (Francesco Marano) · GitHub](https://github.com/mrnfrancesco) )\n\n### \n\nSo what can we do to ensure nothing like this happens?\n\nWe will *register a binary/dependency* that is necessary for the payload to run (for example /usr/bin/bash for a bash script, /usr/bin/python3 for a python script etc etc) and verify that the dependency in the target where we would execute the payload is valid or not.\n\nNow there is a problem, how do we verify that it's a valid binary? \n\nUsing an Hash is too strict , for  example /usr/bin/bash on fedora is different from the one on centos 8, but both are valid binaries.\n\nOnly the presence of it is not enough (like in the example attack before)\n\nSome basic checks are made:\n\n- the file exists\n\n- file size is +/- 15% of the registered one\n\nBut something more is needed.\n\n#### Byte Frequency Distribution Study\n\nTo address the problem it is possible to recycle a technique mostly used in the data-recovery territory: the <u>byte frequency distribution study</u>.\n\nReferences:\n\n- [byte frequency analysis descriptor with spatial information for file fragment classification| Semantic Scholar](https://www.semanticscholar.org/paper/BYTE-FREQUENCY-ANALYSIS-DESCRIPTOR-WITH-SPATIAL-FOR-Xie-Abdullah/c39872eae0c61ecf47603aab3f5c1545ee612ac9)\n\n- [A New Approach to Content-based File Type Detection](https://arxiv.org/pdf/1002.3174)\n\nThe idea is to register the BFD of our dependency, then calculate the correlation index of Bravais-Pearson to see if the two dataset are linearly correlated.\n\n> Ref: [Pearson correlation coefficient - Wikipedia](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient)\n\nPearson's correlation coefficient is the [covariance](https://en.wikipedia.org/wiki/Covariance \"Covariance\") of the two variables divided by the product of their [standard deviations](https://en.wikipedia.org/wiki/Standard_deviations \"Standard deviations\").\n\n![pearson](https://wikimedia.org/api/rest_v1/media/math/render/svg/f76ccfa7c2ed7f5b085115086107bbe25d329cec)\n\nIf the index indicates strong correlation, we know that the two file are of the same type (binary)\n\nA second step is to study the combined standard deviation of the two datasets (std deviation of the first and the second) and see if both values, the correlation and the combined std deviation are in certain ranges.\n\nThis ensures that the dependency we are finding is of *the same type* (a binary) using the Bravais-Pearson index and *similar distribution* from the combined std deviation.\n\nHere an example of a valid dependency: /usr/bin/bash on fedora30 vs centos7\n\n![bfd](./pics/bfd-std.png)\n\nBlue and green the two BFD of the binaries, in green the combined std deviation.\n\nThis method is able to distinguish (and stop) the use of different (but functionally equal) binaries like zsh, dash or busybox\n\n### Decryption\n\nThe last line of defense is also the encryption of the payload. \n\nThe decryption key of the payload is the sha512sum of the compiled launcher itself with the random garbage appended to it.\n\nFor example:\n\nWith offset 930000\n\n```\nCompiled launcher (800kb)\n\nOFFSET1 (130kb)\n\nPayload\n\nOFFSET2 ( different one, 130kb)\n```\n\nThe decryption key is \n\n`sha512sum(Launcher+OFFSET1)`\n\nThis protects from file-based NOP attacks to remove some instructions from the launcher, and acts also as binary validation.\n\n![payload](./pics/decryption.png)\n\nThe payload is structured as above, OFFSET1 **ends on the offset value**, OFFSET2 is calculated as the byte reverse of the offset value.\n\nThe procedure will:\n\n- calculate the offset\n\n- take the launcher+OFFSET1, sha512sum it\n\n- remove OFFSET2 random bytes at the end\n\n- decrypt payload using the calculated sha512sum\n\nSo **THE REAL DECRYPTION KEY IS BASED ON THE OFFSET ITSELF**, all the obfuscation/anti-debug is to protect this information that is stored in an obfuscated string (that is not saved but computed at runtime) of random name and content. \n\n### Execution\n\nAs explained above, we will use a memory file descriptor to execute the binary without passing for the storage.\n\nThe binary will be executed using the `Command` library of Go, that uses the syscall exec under the hood, so no new shells are instantiated.\n\n### **If stdout management is NOT enabled (default)**\n\nThe process is launched and disowned.\nUpon the termination of the launcher process, the `/proc/PID/fd/mem` of the process is deleted, so the only \"copy\" of the payload is in the process table of the detached process itself\n\n**This is the most secure approach** as it deletes all instances of the plaintext payload, leaving it only in a highly private part of the RAM of the process itself, even gaining immunity to /proc dump attacks\n\nThis way even a script launcher with this approach is not possible to be retrieved:\n\n![stdout](./pics/handle-stdout.png)\n\n### **If stdout management is enabled**\n\nTwo routines are used to pipe the payload stderr and stdout to the launcher process.\n\nAlso piping is supported.\n\nFor IO heavy processes it is possible to insert in the `Scan` of the outputs an `OB_CHECK` like this:\n\n```go\n    // OB_CHECK\n    // async fetch stdout\n    go func() {\n        defer obWaitGroup.Done()\n\n        for obStdoutScan.Scan() {\n            // OB_CHECK\n            println(obStdoutScan.Text())\n        }\n    }()\n    // OB_CHECK\n    // async fetch stderr\n    go func() {\n        defer obWaitGroup.Done()\n\n        for obStderrScan.Scan() {\n            // OB_CHECK\n            println(obStderrScan.Text())\n        }\n    }()\n```\n\nThis will make an impact on performance (all check are executed **for each IO on any standard output/error**)  but can give a layer of hardness to process hijacking or tracing\n\n<u>*<mark>**this is the least secure approach**</mark>*</u> as while the launcher is running the `/proc/PID/fd/mem` of the process is still accessible and thus containing the plaintext payload ready to be stealed\n\nThis is particularly discouraged for **srcipts payloads**, as they are even easier to spot as the path is directly in the process\n\n![handle](./pics/handle-stdout-2.png)\n\nWith binaries the approach is safer (only the binary name is in the process, thus making it hard to spot requiring a complete /proc dump)\n\n\n## License\n[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2F89luca89%2Fpakkero.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2F89luca89%2Fpakkero?ref=badge_large)\n"
  },
  {
    "path": "data/launcher.go",
    "content": "// Package main.\npackage main\n\nimport (\n\tobBufio \"bufio\"\n\tobBytes \"bytes\"\n\tobZlib \"compress/zlib\"\n\tobAES \"crypto/aes\"\n\tobCipher \"crypto/cipher\"\n\tobSHA \"crypto/sha512\"\n\tobBase64 \"encoding/base64\"\n\tobBinary \"encoding/binary\"\n\tobErrors \"errors\"\n\tobUtilio \"io/ioutil\"\n\tobMath \"math\"\n\tobOS \"os\"\n\tobExec \"os/exec\"\n\tobSignal \"os/signal\"\n\tobStrconv \"strconv\"\n\tobStrings \"strings\"\n\tobSync \"sync\"\n\tobSyscall \"syscall\"\n\tobTime \"time\"\n\tobUnsafe \"unsafe\"\n)\n\ntype obDependency struct {\n\tobDepSize string\n\tobDepName string\n\tobDepBFD  []float64\n}\n\n// Stdout variable will be overwritten during compilation.\nvar Stdout string = \"ENABLESTDOUT\"\n\nconst (\n\tobErr              = 1\n\tobCorrelationLevel = 0.4\n\tobStdLevel         = 1\n\tobFileSizeLevel    = 15\n)\n\nfunc obExit() {\n\tprintln(\"https://shorturl.at/crzEZ\")\n\tobOS.Exit(obErr)\n}\n\n// Breakpoint on linux are 0xCC and will be interpreted as a\n// SIGTRAP, we will intercept them.\nfunc obSigTrap(obInput chan obOS.Signal) {\n\tobMySignal := <-obInput\n\tswitch obMySignal {\n\tcase obSyscall.SIGILL:\n\t\tobExit()\n\tcase obSyscall.SIGTRAP:\n\t\tobExit()\n\tdefault:\n\t\treturn\n\t}\n}\n\n// attach to PTRACE, register if successful\n// attach A G A I N , register if unsuccessful\n// this protects against custom ptrace (always returning 0)\n// against NOP attacks and LD_PRELOAD attacks.\n//\n// keep attached to avoid late attaching.\nfunc obPtraceDetect(pid int, father bool) {\n\tobOffset := 0\n\n\tobProc, _ := obOS.FindProcess(pid)\n\n\tobErr := obSyscall.PtraceAttach(obProc.Pid)\n\tif obErr == nil {\n\t\tobOffset = 5\n\t}\n\n\t// continuously check for ptrace on passed pid\n\tfor {\n\t\tobErr = obSyscall.PtraceAttach(obProc.Pid)\n\t\tif obErr != nil {\n\t\t\tobOffset *= 3\n\t\t}\n\n\t\tobErr = obProc.Signal(obSyscall.SIGCONT)\n\t\tif obErr != nil {\n\t\t\t// we cannot send sigcont to out pid\n\t\t\t// we should exit.\n\t\t\tif father {\n\t\t\t\tobExit()\n\t\t\t} else {\n\t\t\t\tobErr = obProc.Signal(obSyscall.SIGTRAP)\n\t\t\t\tif obErr != nil {\n\t\t\t\t\tobExit()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif obOffset != (3 * 5) {\n\t\t\tif father {\n\t\t\t\tobExit()\n\t\t\t} else {\n\t\t\t\tobErr = obProc.Signal(obSyscall.SIGTRAP)\n\t\t\t\tif obErr != nil {\n\t\t\t\t\tobExit()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tobTime.Sleep(250 * obTime.Millisecond)\n\n\t\tobOffset /= 3\n\t}\n}\n\n// Check the process cmdline to spot if a debugger is inline.\nfunc obParentCmdLineDetect() {\n\tobPidParent := obOS.Getppid()\n\n\tobNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n\t\t\"/cmdline\"\n\tobStatParent, _ := obUtilio.ReadFile(obNameFile)\n\n\tif obStrings.Contains(string(obStatParent), \"gdb\") ||\n\t\tobStrings.Contains(string(obStatParent), \"dlv\") ||\n\t\tobStrings.Contains(string(obStatParent), \"edb\") ||\n\t\tobStrings.Contains(string(obStatParent), \"frida\") ||\n\t\tobStrings.Contains(string(obStatParent), \"ghidra\") ||\n\t\tobStrings.Contains(string(obStatParent), \"godebug\") ||\n\t\tobStrings.Contains(string(obStatParent), \"ida\") ||\n\t\tobStrings.Contains(string(obStatParent), \"lldb\") ||\n\t\tobStrings.Contains(string(obStatParent), \"ltrace\") ||\n\t\tobStrings.Contains(string(obStatParent), \"strace\") ||\n\t\tobStrings.Contains(string(obStatParent), \"valgrind\") {\n\t\tobExit()\n\t}\n}\n\n// Check the process status to spot if a debugger is active using the TracePid key.\nfunc obParentTracerDetect() {\n\tobPidParent := obOS.Getppid()\n\n\tobNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n\t\t\"/status\"\n\tobStatParent, _ := obUtilio.ReadFile(obNameFile)\n\tobStatLines := obStrings.Split(string(obStatParent), \"\\n\")\n\n\tfor _, obValue := range obStatLines {\n\t\tif obStrings.Contains(obValue, \"TracerPid\") {\n\t\t\tobSplitArray := obStrings.Split(obValue, \":\")\n\t\t\tobSplitValue := obStrings.Replace(obSplitArray[1], \"\\t\", \"\", -1)\n\n\t\t\tif obSplitValue != \"0\" {\n\t\t\t\tobExit()\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Check the process cmdline to spot if a debugger is the PPID of our process.\nfunc obParentDetect() {\n\tobPidParent := obOS.Getppid()\n\n\tobNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n\t\t\"/stat\"\n\tobStatParent, _ := obUtilio.ReadFile(obNameFile)\n\n\tif obStrings.Contains(string(obStatParent), \"gdb\") ||\n\t\tobStrings.Contains(string(obStatParent), \"dlv\") ||\n\t\tobStrings.Contains(string(obStatParent), \"edb\") ||\n\t\tobStrings.Contains(string(obStatParent), \"frida\") ||\n\t\tobStrings.Contains(string(obStatParent), \"ghidra\") ||\n\t\tobStrings.Contains(string(obStatParent), \"godebug\") ||\n\t\tobStrings.Contains(string(obStatParent), \"ida\") ||\n\t\tobStrings.Contains(string(obStatParent), \"lldb\") ||\n\t\tobStrings.Contains(string(obStatParent), \"ltrace\") ||\n\t\tobStrings.Contains(string(obStatParent), \"strace\") ||\n\t\tobStrings.Contains(string(obStatParent), \"valgrind\") {\n\t\tobExit()\n\t}\n}\n\n// Check the process cmdline to spot if a debugger is launcher\n// \"_\" and Args[0] should match otherwise.\nfunc obEnvArgsDetect() {\n\tobLines, _ := obOS.LookupEnv(\"_\")\n\tif obLines != obOS.Args[0] {\n\t\tobExit()\n\t}\n}\n\n// Check the process cmdline to spot if a debugger is inline\n// \"_\" should not contain the name of any debugger.\nfunc obEnvParentDetect() {\n\tobLines, _ := obOS.LookupEnv(\"_\")\n\tif obStrings.Contains(obLines, \"gdb\") ||\n\t\tobStrings.Contains(obLines, \"dlv\") ||\n\t\tobStrings.Contains(obLines, \"edb\") ||\n\t\tobStrings.Contains(obLines, \"frida\") ||\n\t\tobStrings.Contains(obLines, \"ghidra\") ||\n\t\tobStrings.Contains(obLines, \"godebug\") ||\n\t\tobStrings.Contains(obLines, \"ida\") ||\n\t\tobStrings.Contains(obLines, \"lldb\") ||\n\t\tobStrings.Contains(obLines, \"ltrace\") ||\n\t\tobStrings.Contains(obLines, \"strace\") ||\n\t\tobStrings.Contains(obLines, \"valgrind\") {\n\t\tobExit()\n\t}\n}\n\n// Check the process cmdline to spot if a debugger is active\n// most debuggers (like GDB) will set LINE,COLUMNS or LD_PRELOAD\n// to function, we try to spot this.\nfunc obEnvDetect() {\n\t_, obLines := obOS.LookupEnv(\"LINES\")\n\t_, obColumns := obOS.LookupEnv(\"COLUMNS\")\n\t_, obLineLdPreload := obOS.LookupEnv(\"LD_PRELOAD\")\n\n\tif obLines || obColumns || obLineLdPreload {\n\t\tobExit()\n\t}\n}\n\n// Check the process is launcher with a LD_PRELOAD set.\n// This can be an injection attack (like on frida) to try and circumvent\n// various restrictions (like ptrace checks).\nfunc obLdPreloadDetect() {\n\tobKey := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)\n\tobValue := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)\n\n\tobErr := obOS.Setenv(obKey, obValue)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\n\tobLineLdPreload, _ := obOS.LookupEnv(obKey)\n\tif obLineLdPreload == obValue {\n\t\tobErr := obOS.Unsetenv(obKey)\n\t\tif obErr != nil {\n\t\t\tobExit()\n\t\t}\n\t} else {\n\t\tobExit()\n\t}\n}\n\n// calculate BFD (byte frequency distribution) for the input dependency.\nfunc obUtilBFDCalc(obInput string) []float64 {\n\tobFile, _ := obUtilio.ReadFile(obInput)\n\n\tobBfd := make([]float64, 256)\n\tfor _, obValue := range obFile {\n\t\tobBfd[obValue]++\n\t}\n\n\treturn obBfd\n}\n\n// Abs returns the absolute value of obInput.\nfunc obUtilAbsCalc(obInput float64) float64 {\n\tif obInput < 0 {\n\t\treturn -obInput\n\t}\n\n\treturn obInput\n}\n\n// calculate the covariance of two input slices.\nfunc obUtilCovarianceCalc(obDepInput []float64, obTargetInput []float64) float64 {\n\tobMeanDepInput := 0.0\n\tobMeanTargetInput := 0.0\n\n\tfor obIndex := 0; obIndex < 256; obIndex++ {\n\t\tobMeanDepInput += obDepInput[obIndex]\n\t\tobMeanTargetInput += obTargetInput[obIndex]\n\t}\n\n\tobMeanDepInput /= 256\n\tobMeanTargetInput /= 256\n\n\tobCovariance := 0.0\n\tfor obIndex := 0; obIndex < 256; obIndex++ {\n\t\tobCovariance += (obDepInput[obIndex] - obMeanDepInput) * (obTargetInput[obIndex] - obMeanTargetInput)\n\t}\n\n\tobCovariance /= 255\n\n\treturn obCovariance\n}\n\n// calculate the standard deviation of the values in a slice.\nfunc obUtilStandardDeviationCalc(obInput []float64) float64 {\n\tobSums := 0.0\n\t// calculate the array of rations between the values\n\tfor obIndex := 0; obIndex < 256; obIndex++ {\n\t\t// increase obInstanceDep to calculate mean value of registered distribution\n\t\tobSums += obInput[obIndex]\n\t}\n\t// calculate the mean\n\tobMeanSums := obSums / float64(len(obInput))\n\tobStdDev := 0.0\n\t// calculate the standard deviation\n\tfor obIndex := 0; obIndex < 256; obIndex++ {\n\t\tobStdDev += obMath.Pow(obInput[obIndex]-obMeanSums, 2)\n\t}\n\n\tobStdDev = (obMath.Sqrt(obStdDev / float64(len(obInput))))\n\n\treturn obStdDev\n}\n\n// calculate the standard deviation of the values of reference over\n// retrieved values.\nfunc obUtilCombinedStandardDeviationCalc(obDepBFD []float64, obTargetBFD []float64) float64 {\n\tobDiffs := [256]float64{}\n\tobSums := 0.0\n\tobDepSums := 0.0\n\t// calculate the array of rations between the values\n\tfor obIndex := 0; obIndex < 256; obIndex++ {\n\t\t// add 1 to both to work aroung division by zero\n\t\tobDiffs[obIndex] = obUtilAbsCalc(obDepBFD[obIndex] - obTargetBFD[obIndex])\n\t\tobSums += obDiffs[obIndex]\n\t\t// increase obInstanceDep to calculate mean value of registered distribution\n\t\tobDepSums += obDepBFD[obIndex]\n\t}\n\t// calculate the mean\n\tobDepSums /= float64(len(obDepBFD))\n\t// calculate the mean\n\tobMeanSums := obSums / float64(len(obDepBFD))\n\n\tobStdDev := 0.0\n\t// calculate the standard deviation\n\tfor obIndex := 0; obIndex < 256; obIndex++ {\n\t\tobStdDev += obMath.Pow(obDiffs[obIndex]-obMeanSums, 2)\n\t}\n\n\tobStdDev = (obMath.Sqrt(obStdDev / float64(len(obDepBFD)))) / obDepSums\n\n\treturn obStdDev\n}\n\nfunc obDependencyCheck() {\n\tobStrControl1 := \"_DEP\"\n\tobStrControl2 := \"_NAME\"\n\tobStrControl3 := \"_SIZE\"\n\tobInstanceDep := obDependency{\n\t\tobDepName: \"DEPNAME1\",\n\t\tobDepSize: \"DEPSIZE2\",\n\t\tobDepBFD:  []float64{1, 2, 3, 4},\n\t}\n\t// control that we effectively want to control the dependencies\n\tif (obInstanceDep.obDepName != obStrControl1[1:]+obStrControl2[1:]+\"1\") &&\n\t\t(obInstanceDep.obDepSize != obStrControl1[1:]+obStrControl3[1:]+\"2\") {\n\t\t// check if the file is a symbolic link\n\t\tobLTargetStats, _ := obOS.Lstat(obInstanceDep.obDepName)\n\t\tif (obLTargetStats.Mode() & obOS.ModeSymlink) != 0 {\n\t\t\tobExit()\n\t\t}\n\t\t// open dependency in current environment and check it's size\n\t\tobFile, obErr := obOS.Open(obInstanceDep.obDepName)\n\t\tif obErr != nil {\n\t\t\tobExit()\n\t\t}\n\t\tdefer obFile.Close()\n\n\t\tobStatsFile, _ := obFile.Stat()\n\t\tobTargetDepSize, _ := obStrconv.ParseInt(obInstanceDep.obDepSize, 10, 64)\n\t\tobTargetTreshold := (obTargetDepSize / 100) * obFileSizeLevel\n\t\t// first check if file size is +/- 15% of registered size\n\t\tif (obStatsFile.Size()-obTargetDepSize) < (-1*(obTargetTreshold)) ||\n\t\t\t(obStatsFile.Size()-obTargetDepSize) > obTargetTreshold {\n\t\t\tobExit()\n\t\t}\n\n\t\t// Calculate BFD (byte frequency distribution) of target file\n\t\t// and calculate standard deviation from registered fingerprint.\n\t\tobTargetBFD := obUtilBFDCalc(obInstanceDep.obDepName)\n\n\t\t// Calculate covariance of the 2 dataset\n\t\tobCovariance := obUtilCovarianceCalc(obInstanceDep.obDepBFD, obTargetBFD)\n\t\t// calculate the correlation index of  Bravais-Pearson to see if the\n\t\t// two dataset are linearly correlated\n\t\tobDepStdDev := obUtilStandardDeviationCalc(obInstanceDep.obDepBFD)\n\t\tobTargetStdDev := obUtilStandardDeviationCalc(obTargetBFD)\n\t\tobCorrelation := obCovariance / (obDepStdDev * obTargetStdDev)\n\n\t\tif obCorrelation < obCorrelationLevel {\n\t\t\t// not correlated, different nature\n\t\t\tobExit()\n\t\t}\n\n\t\tobCombinedStdDev := obUtilCombinedStandardDeviationCalc(\n\t\t\tobInstanceDep.obDepBFD,\n\t\t\tobTargetBFD)\n\n\t\t// standard deviation should not be greater than 1\n\t\tif obCombinedStdDev > obStdLevel {\n\t\t\tobExit()\n\t\t}\n\t}\n}\n\n// Reverse a slice of bytes.\nfunc obReverseByteArray(obInput []byte) []byte {\n\tobResult := []byte{}\n\n\tfor i := range obInput {\n\t\tn := obInput[len(obInput)-1-i]\n\t\tobResult = append(obResult, n)\n\t}\n\n\treturn obResult\n}\n\n// Change byte endianess.\nfunc obByteReverse(obBar byte) byte {\n\tvar obFoo byte\n\n\tfor obStart := 0; obStart < 8; obStart++ {\n\t\tobFoo <<= 1\n\t\tobFoo |= obBar & 1\n\t\tobBar >>= 1\n\t}\n\n\treturn obFoo\n}\n\nconst (\n\tobCloexec uint = 1\n\t// allow seal operations to be performed.\n\tobAllowSealing uint = 2\n\t// memfd is now immutable.\n\tobSealAll = 0x0001 | 0x0002 | 0x0004 | 0x0008\n\t// amd64 specific.\n\tobSysFCNTL       = obSyscall.SYS_FCNTL\n\tobSysMEMFDCreate = 319\n)\n\nfunc obGetFDPath(obPid int, obFD int, obPayload []byte) string {\n\t// check if we are pakkering a script, if it's a script\n\t// use specific pid path.\n\tif string(obPayload[0:2]) == \"#!\" {\n\t\treturn \"/proc/\" +\n\t\t\tobStrconv.Itoa(obPid) +\n\t\t\t\"/fd/\" +\n\t\t\tobStrconv.Itoa(obFD)\n\t}\n\t// else use self for elf files\n\treturn \"/proc/self/fd/\" + obStrconv.Itoa(obFD)\n}\n\nfunc obLauncher() {\n\t// OB_CHECK\n\tobNameFile, _ := obOS.Executable()\n\n\tobFile, _ := obOS.Open(obNameFile)\n\tdefer obFile.Close()\n\n\t// OB_CHECK\n\tobOffset, _ := obStrconv.ParseInt(\"9999999\", 10, 64)\n\tobStatsFile, _ := obFile.Stat()\n\n\t// calculate final padding\n\tobArrayFinalPadding := make([]byte, obBinary.MaxVarintLen64)\n\tobByteFinalPadding := obArrayFinalPadding[:obBinary.PutVarint(obArrayFinalPadding, obOffset)]\n\n\tfor obIndex := range obByteFinalPadding {\n\t\tobByteFinalPadding[obIndex] = obByteReverse(obByteFinalPadding[obIndex])\n\t}\n\n\tobFinalPadding, _ := obBinary.Varint(obByteFinalPadding)\n\n\t// make it positive!\n\tif obFinalPadding < 0 {\n\t\tobFinalPadding *= -1\n\t}\n\t// read the complete executable\n\tobKey := make([]byte, obOffset)\n\n\t_, obErr := obFile.Read(obKey)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\n\t// OB_CHECK\n\tobSizeFile := obStatsFile.Size() - obOffset\n\n\t// OB_CHECK\n\t_, obErr = obFile.Seek(obOffset, 0)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\n\tobCiphertext := make([]byte, obSizeFile)\n\n\t// OB_CHECK\n\t_, obErr = obFile.Read(obCiphertext)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\n\tobCiphertext = obCiphertext[:int64(len(obCiphertext))-obFinalPadding]\n\t// OB_CHECK\n\t// the payload was reversed!\n\tobCiphertext = obReverseByteArray(obCiphertext)\n\n\t// OB_CHECK\n\t// restore endianess\n\tfor obIndex := range obCiphertext {\n\t\tobCiphertext[obIndex] = obByteReverse(obCiphertext[obIndex])\n\t}\n\n\t// OB_CHECK\n\n\t//\t\tthe aes-256 psk is the sha512_256 sum of the whole executable\n\t//\t\tthis is also useful to protect against NOP attacks to the anti-debug\n\t//\t\tfeatures in the binary.\n\t//\t\tThis doubles also as anti-tamper measure.\n\tobPassword := obSHA.Sum512_256(obKey)\n\t// OB_CHECK\n\tobCipherBlock, _ := obAES.NewCipher(obPassword[:])\n\n\t// OB_CHECK\n\tobGCM, _ := obCipher.NewGCM(obCipherBlock)\n\n\t// OB_CHECK\n\tobSizeNonce := obGCM.NonceSize()\n\n\t// OB_CHECK\n\t// decrypt!!!\n\tobNonce, obCiphertext := obCiphertext[:obSizeNonce], obCiphertext[obSizeNonce:]\n\tobCompressedPlaintext, _ := obGCM.Open(nil, obNonce, obCiphertext, nil)\n\n\t// OB_CHECK\n\t// the payload was compressed!\n\tobBufferPlaintext := obBytes.NewReader(obCompressedPlaintext)\n\t// OB_CHECK\n\tobZlibReader, obErr := obZlib.NewReader(obBufferPlaintext)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\t// OB_CHECK\n\tobPlaintext, _ := obUtilio.ReadAll(obZlibReader)\n\tobZlibReader.Close()\n\t// OB_CHECK\n\t// payload was in b64\n\tobPayload, _ := obBase64.StdEncoding.DecodeString(string(obPlaintext))\n\n\t// OB_CHECK\n\tobFDName := \"\"\n\tobFileDescriptor, _, _ := obSyscall.Syscall(obSysMEMFDCreate,\n\t\tuintptr(obUnsafe.Pointer(&obFDName)),\n\t\tuintptr(obCloexec|obAllowSealing), 0)\n\n\t// OB_CHECK\n\t// write payload to FD\n\t_, obErr = obSyscall.Write(int(obFileDescriptor), obPayload)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\n\t// OB_CHECK\n\t// make it immutable\n\t_, _, obErr = obSyscall.Syscall(obSysFCNTL,\n\t\tobFileDescriptor,\n\t\tuintptr(1024+9),\n\t\tuintptr(obSealAll))\n\tif !obErrors.Is(obErr, obSyscall.Errno(0)) {\n\t\tobExit()\n\t}\n\n\t// OB_CHECK\n\tobFDPath := obGetFDPath(obOS.Getpid(), int(obFileDescriptor), obPayload)\n\n\t// OB_CHECK\n\tobCommand := obExec.Command(obFDPath)\n\t// OB_CHECK\n\tobCommand.Args = obOS.Args\n\tobCommand.Stdin = obOS.Stdin\n\t// OB_CHECK\n\tobStdoutIn, _ := obCommand.StdoutPipe()\n\tdefer obStdoutIn.Close()\n\n\tobStderrIn, _ := obCommand.StderrPipe()\n\tdefer obStderrIn.Close()\n\n\tobStdout, obErr := obStrconv.ParseBool(Stdout)\n\tif obErr != nil {\n\t\tobExit()\n\t}\n\n\tif obStdout {\n\t\t// OB_CHECK\n\t\t// launch and remain attached\n\t\tobErr = obCommand.Start()\n\t\tif obErr != nil {\n\t\t\tobExit()\n\t\t}\n\n\t\tvar obWaitGroup obSync.WaitGroup\n\n\t\tobWaitGroup.Add(2)\n\n\t\tobStdoutScan := obBufio.NewScanner(obStdoutIn)\n\t\tobStderrScan := obBufio.NewScanner(obStderrIn)\n\t\t// OB_CHECK\n\t\t// async fetch stdout\n\t\tgo func() {\n\t\t\tdefer obWaitGroup.Done()\n\n\t\t\tfor obStdoutScan.Scan() {\n\t\t\t\tprintln(obStdoutScan.Text())\n\t\t\t}\n\t\t}()\n\t\t// OB_CHECK\n\t\t// async fetch stderr\n\t\tgo func() {\n\t\t\tdefer obWaitGroup.Done()\n\n\t\t\tfor obStderrScan.Scan() {\n\t\t\t\tprintln(obStderrScan.Text())\n\t\t\t}\n\t\t}()\n\n\t\t// OB_CHECK\n\t\tobWaitGroup.Wait()\n\t} else {\n\t\t// launch and forget\n\t\tobCommand.SysProcAttr = &obSyscall.SysProcAttr{Setpgid: true, Noctty: true}\n\t\t// OB_CHECK\n\t\tobErr = obCommand.Start()\n\t\tif obErr != nil {\n\t\t\tobExit()\n\t\t}\n\t\tobTime.Sleep(2 * obTime.Second)\n\t}\n}\n\n// obIsForked returns wether we are a forked process of ourself, or a new spawn.\nfunc obIsForked() bool {\n\tobPidParent := obOS.Getppid()\n\tobNameFile := \"/proc/\" + obStrconv.FormatInt(int64(obPidParent), 10) +\n\t\t\"/cmdline\"\n\tobStatParent, _ := obUtilio.ReadFile(obNameFile)\n\n\treturn obStrings.Contains(string(obStatParent), obOS.Args[0])\n}\n\nfunc main() {\n\t// Prepare to intercept SIGTRAP\n\tobChannel := make(chan obOS.Signal, 1)\n\tobSignal.Notify(obChannel, obSyscall.SIGTRAP, obSyscall.SIGILL)\n\n\tgo obSigTrap(obChannel)\n\n\t// OB_CHECK\n\tobDependencyCheck()\n\t// OB_CHECK\n\tobEnvArgsDetect()\n\t// OB_CHECK\n\tobParentTracerDetect()\n\t// OB_CHECK\n\tobParentCmdLineDetect()\n\t// OB_CHECK\n\tobEnvDetect()\n\t// OB_CHECK\n\tobEnvParentDetect()\n\t// OB_CHECK\n\tobLdPreloadDetect()\n\t// OB_CHECK\n\tobParentDetect()\n\t// check if we are a forked process, if not, fork\n\t// and ptrace ourself, else exit gracefully and continue\n\t// with normal execution.\n\t//\n\t// this workaround is because go does not support traditional fork()\n\t// and calling ptrace in the main thread of execution will neuter\n\t// any possibility of calling \"exec\" afterwards.\n\tif obIsForked() {\n\t\t// we are a child process, let's ptrace\n\t\tobPtraceDetect(obOS.Getppid(), false)\n\t} else {\n\t\t// simulate for self, launch ourself in another\n\t\t// process to ptrace ourself\n\t\tobCommand := obExec.Command(obOS.Args[0], obOS.Args[1:]...)\n\t\tobErr := obCommand.Start()\n\t\tif obErr != nil {\n\t\t\tprintln(obErr.Error())\n\t\t\tobExit()\n\t\t}\n\t\tgo obPtraceDetect(obCommand.Process.Pid, true)\n\t\t// Ok we are set to go! Let's execute the payload\n\t\t// OB_CHECK\n\t\tobLauncher()\n\t}\n}\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/89luca89/pakkero\n\ngo 1.16\n\nrequire github.com/alegrey91/go-upx v0.2.0 // indirect\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/alegrey91/go-upx v0.2.0 h1:EFhbmAbFET2mqHRLunHFOVo3+mxdnR2/EQMfv0OOR0k=\ngithub.com/alegrey91/go-upx v0.2.0/go.mod h1:qrYpv/uZT6Qs1mrNz3wxrL/u7kbbTWkbVJnHyzsiJmU=\n"
  },
  {
    "path": "internal/pakkero/encryption.go",
    "content": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\nEncryption library\n*/\npackage pakkero\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"crypto/sha512\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n)\n\n/*\nEncryptAESReversed Wrapper around AESGCM encryption\n\nthis will not only encrypt the payload but:\n- generate a password using the randomized UPX Binary's sha512_256 sum\n- cipher the payload with AESGCM using the generated password\n- swap endianess on all the encrypted bytes\n- reverse the complete payload.\n*/\nfunc EncryptAESReversed(plaintext []byte, outfile string) (string, error) {\n\t// generate a password using the randomized UPX Binary's sha512_256 sum\n\t/*\n\t\t\t    the aes-256 psk is the sha512_256 sum of the whole executable\n\t\t        this is also useful to protect against NOP attacks to the anti-debug\n\t\t        features in the binary.\n\t\t        This doubles also as anti-tamper measure.\n\t*/\n\tb, err := ioutil.ReadFile(outfile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to read input file: %w\", err)\n\t}\n\n\t// use SHA512 (32byte) of the passphrase as key\n\tkey := sha512.Sum512_256(b)\n\n\t//\tgenerate new cipher\n\tc, err := aes.NewCipher(key[:])\n\tif err != nil {\n\t\tprintln(err)\n\t}\n\n\tgcm, err := cipher.NewGCM(c)\n\tif err != nil {\n\t\tprintln(err)\n\t}\n\n\tnonce := make([]byte, gcm.NonceSize())\n\tif _, err = io.ReadFull(rand.Reader, nonce); err != nil {\n\t\tprintln(err)\n\t}\n\n\t// cipher the payload with AESGCM using the generated password\n\tbCiphertext := gcm.Seal(nonce, nonce, plaintext, nil)\n\n\t// swap endianess on all the encrypted bytes\n\tfor i := range bCiphertext {\n\t\tbCiphertext[i] = ReverseByte(bCiphertext[i])\n\t}\n\n\tciphertext := string(bCiphertext)\n\n\t// reverse the complete payload\n\tciphertext = string(ReverseByteArray([]byte(ciphertext)))\n\n\treturn ciphertext, nil\n}\n"
  },
  {
    "path": "internal/pakkero/obfuscation.go",
    "content": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\nObfuscation library\n*/\npackage pakkero\n\nimport (\n\t\"crypto/rand\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n// Secrets are the group of strings that we want to obfuscate.\nvar Secrets = map[string][]string{}\n\n// LauncherStub Stub of the Launcher.go, put here during compilation time.\nvar LauncherStub = \"unset\"\n\nvar extras = []string{\n\t// ELF Headers\n\t\".gopclntab\",\n\t\".go.buildinfo\",\n\t\".noptrdata\",\n\t\".noptrbss\",\n\t\".data\",\n\t\".rodata\",\n\t\".text\",\n\t\".itablink\",\n\t\".shstrtab\",\n\t\".data\",\n\t\".dynamic\",\n\t\".dynstr\",\n\t\".dynsym\",\n\t\".gnu.version_r\",\n\t\".gopclntab\",\n\t\".got.plt\",\n\t\".init_array\",\n\t\".interp\",\n\t\".itablink\",\n\t\".rela.dyn\",\n\t\".rela.plt\",\n\t\".tbss\",\n\t\".plt\",\n\t\".init\",\n\t// internal golang\n\t\"name\", \"runtime\", \"command\", \"cmd\",\n\t\"ptr\", \"process\", \"unicode\", \"main\",\n\t\"path\", \"get\", \"reflect\", \"context\",\n\t\"debug\", \"fmt\", \"sync\", \"sort\",\n\t\"size\", \"heap\", \"fatal\", \"call\",\n\t\"fixed\", \"slice\", \"bit\", \"file\",\n\t\"read\", \"write\", \"buffer\", \"encrypt\",\n\t\"decrypt\", \"hash\", \"state\",\n\t\"external\", \"internal\", \"float\",\n\t// anti debug traces\n\t\"env\", \"trace\", \"pid\",\n}\n\n/*\nStripUPXHeaders will ensure no trace of UPX headers are left\nso that reversing will be more challenging and break\nsimple attempts like \"upx -d\" in case of compression.\n*/\nfunc StripUPXHeaders(infile string) bool {\n\t// Bit sequence of UPX copyright and header infos\n\theader := []string{\n\t\t`\\x49\\x6e\\x66\\x6f\\x3a\\x20\\x54\\x68\\x69\\x73`,\n\t\t`\\x20\\x66\\x69\\x6c\\x65\\x20\\x69\\x73\\x20\\x70`,\n\t\t`\\x61\\x63\\x6b\\x65\\x64\\x20\\x77\\x69\\x74\\x68`,\n\t\t`\\x20\\x74\\x68\\x65\\x20\\x55\\x50\\x58\\x20\\x65`,\n\t\t`\\x78\\x65\\x63\\x75\\x74\\x61\\x62\\x6c\\x65\\x20`,\n\t\t`\\x70\\x61\\x63\\x6b\\x65\\x72\\x20\\x68\\x74\\x74`,\n\t\t`\\x70\\x3a\\x2f\\x2f\\x75\\x70\\x78\\x2e\\x73\\x66`,\n\t\t`\\x2e\\x6e\\x65\\x74\\x20\\x24\\x0a\\x00\\x24\\x49`,\n\t\t`\\x64\\x3a\\x20\\x55\\x50\\x58\\x20\\x33\\x2e\\x39`,\n\t\t`\\x36\\x20\\x43\\x6f\\x70\\x79\\x72\\x69\\x67\\x68`,\n\t\t`\\x74\\x20\\x28\\x43\\x29\\x20\\x31\\x39\\x39\\x36`,\n\t\t`\\x2d\\x32\\x30\\x32\\x30\\x20\\x74\\x68\\x65\\x20`,\n\t\t`\\x55\\x50\\x58\\x20\\x54\\x65\\x61\\x6d\\x2e\\x20`,\n\t\t`\\x41\\x6c\\x6c\\x20\\x52\\x69\\x67\\x68\\x74\\x73`,\n\t\t`\\x20\\x52\\x65\\x73\\x65\\x72\\x76\\x65\\x64\\x2e`,\n\t\t`\\x55\\x50\\x58\\x21`,\n\t}\n\tresult := true\n\n\tfor _, v := range header {\n\t\tsedString := \"\"\n\t\t// generate random byte sequence\n\t\treplace := make([]byte, 1)\n\n\t\tfor len(sedString) < len(v) {\n\t\t\t_, err := rand.Read(replace)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tsedString += `\\x` + hex.EncodeToString(replace)\n\t\t}\n\t\t// replace UPX sequence with random garbage\n\t\tresult = ExecCommand(\"sed\", []string{\"-i\", `s/` + v + `/` + sedString + `/g`, infile})\n\t\tif !result {\n\t\t\treturn result\n\t\t}\n\t}\n\n\treturn result\n}\n\n/*\nStripFile will strip out all unneeded headers from and ELF\nfile in input.\n*/\nfunc StripFile(infile string, launcherFile string) bool {\n\t// strip symbols and headers\n\tif !ExecCommand(\"strip\",\n\t\t[]string{\n\t\t\t\"-sxX\",\n\t\t\t\"--remove-section=.bss\",\n\t\t\t\"--remove-section=.comment\",\n\t\t\t\"--remove-section=.eh_frame\",\n\t\t\t\"--remove-section=.eh_frame_hdr\",\n\t\t\t\"--remove-section=.fini\",\n\t\t\t\"--remove-section=.fini_array\",\n\t\t\t\"--remove-section=.gnu.build.attributes\",\n\t\t\t\"--remove-section=.gnu.hash\",\n\t\t\t\"--remove-section=.gnu.version\",\n\t\t\t\"--remove-section=.gosymtab\",\n\t\t\t\"--remove-section=.got\",\n\t\t\t\"--remove-section=.note.ABI-tag\",\n\t\t\t\"--remove-section=.note.gnu.build-id\",\n\t\t\t\"--remove-section=.shstrtab\",\n\t\t\t\"--remove-section=.typelink\",\n\t\t\tinfile,\n\t\t}) {\n\t\treturn false\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// proceede with manual\n\t// stripping of golang builtins and keyWords strings\n\tremoveStrings := []string{}\n\tremoveStrings = append(removeStrings, extras...)\n\t// anonymize the launcherFile string to hide the original launcher file name\n\tremoveStrings = append(removeStrings, launcherFile)\n\n\t// deduplicate\n\tremoveStrings = Unique(removeStrings)\n\n\t// read file to string\n\tbyteContent, err := ioutil.ReadFile(infile)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tinput := string(byteContent)\n\n\tfor _, remove := range removeStrings {\n\t\t// generate new random string to place instead\n\t\tnewName := GenerateNullString(len(remove))\n\t\tinput = strings.ReplaceAll(input, remove, newName)\n\t\tinput = strings.ReplaceAll(input, strings.Title(remove), newName)\n\t}\n\t// save.\n\terr = ioutil.WriteFile(infile, []byte(input), 0600)\n\t// ------------------------------------------------------------------------\n\n\treturn err == nil\n}\n\n/*\nGenerateTyposquatName is a typosquat name generator\nbased on a length (128 default) this will create a random\nuniqe string composed only of letters and zeroes that are lookalike.\n*/\nfunc GenerateTyposquatName(length int) string {\n\t// We divide between an alphabet with number\n\t// and one without, because function/variable names\n\t// must not start with a number.\n\tletterRunes := []rune(\"OÓÕÔÒÖŌŎŐƠΘΟ\")\n\tmixedRunes := []rune(\"0OÓÕÔÒÖŌŎŐƠΘΟ\")\n\tb := make([]rune, length)\n\t// ensure we do not start with a number or we will break code.\n\tb[0] = letterRunes[Random(0, int64(len(mixedRunes)-1))]\n\tfor i := range b {\n\t\tif i != 0 {\n\t\t\tb[i] = mixedRunes[Random(0, int64(len(mixedRunes)-1))]\n\t\t}\n\t}\n\n\treturn string(b)\n}\n\n/*\nObfuscateFuncVars will:\n  - extract all obfuscation-enabled func and var names:\n  - those start with \"ob*\" and will be listed\n  - for each matching string generate a typosquatted random string and\n    replace all string with that\n*/\nfunc ObfuscateFuncVars(input string) string {\n\t// obfuscate functions and variables names\n\tregex := regexp.MustCompile(`\\bob[a-zA-Z0-9_]+`)\n\twords := regex.FindAllString(input, -1)\n\twords = ReverseStringArray(words)\n\twords = Unique(words)\n\n\tfor _, w := range words {\n\t\t// generate random name for each matching string\n\t\tinput = strings.ReplaceAll(input, w, GenerateTyposquatName(128))\n\t}\n\n\treturn input\n}\n\n/*\nGenerateStringFunc will hide a string creating a function that returns\nthat value as a string encoded with a series of length calculation of randomic\nstring arrays generated.\n*/\nfunc GenerateStringFunc(txt string, function string) string {\n\tresString := \"{\"\n\tfor _, b := range []byte(txt) {\n\t\tresString += \"\\\"\" + GenerateTyposquatName(int(b)) + \"\\\"\" + \",\"\n\t}\n\t// remove last comma\n\tresString = strings.TrimSuffix(resString, \",\")\n\t// close array\n\tresString += \"}\"\n\tresult := fmt.Sprintf(\"func \" +\n\t\tfunction +\n\t\t\"() string {\\nobRegistered := []string\" + resString +\n\t\t\"\\nvar obResult []byte\\nfor _,obValue := range obRegistered \" +\n\t\t\"{\\nobResult = append(obResult, byte(len([]rune(obValue))))\\n}\\nreturn string(obResult)\\n}\")\n\n\treturn result\n}\n\n/*\nObfuscateStrings will extract all plaintext strings denotet with\nbackticks and obfuscate them using byteshift wise operations.\n*/\nfunc ObfuscateStrings(input string) string {\n\t// parse the launcher file to create the list of imports in it\n\timports := strings.Index(input, \"import (\")\n\tendimports := strings.Index(input[imports:], \")\")\n\n\t// import section\n\timportSection := input[:imports+endimports+1]\n\n\t// the rest of the program\n\tbody := input[imports+endimports+1:]\n\n\t// various types of string delimiter\n\ttickTypes := []string{\"`\", `'`, `\"`}\n\n\t// for each ticktype, try to get all the strings and\n\t// obfuscate them using functions\n\tfor _, v := range tickTypes {\n\t\tregex := regexp.MustCompile(v + \".*?\" + v)\n\t\twords := regex.FindAllString(body, -1)\n\t\twords = Unique(words)\n\n\t\tfor _, w := range words {\n\t\t\t// string not void, accounting for quotes\n\t\t\tif len(w) > 2 && !strings.Contains(w, `\\`) {\n\t\t\t\t// add string to the secrets! if not present\n\t\t\t\t_, present := Secrets[w]\n\t\t\t\tif !present {\n\t\t\t\t\tsecret := w[1 : len(w)-1]\n\t\t\t\t\tSecrets[w] = []string{secret, GenerateTyposquatName(128)}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// create function call\n\tfuncString := \"\"\n\t// replace all secrects with the respective obfuscated string\n\tfor k, w := range Secrets {\n\t\t// in case we manually added some secrets that we want to leave\n\t\tif !strings.Contains(w[1], \"leave\") {\n\t\t\tfuncString = funcString + GenerateStringFunc(w[0], w[1]) + \"\\n\"\n\t\t\tbody = strings.ReplaceAll(body, k, w[1]+\"()\")\n\t\t} else {\n\t\t\tbody = strings.ReplaceAll(body, k, w[0])\n\t\t}\n\t}\n\n\t// reconstruct the program correctly and\n\t// insert all the functions before the main\n\tbody = body + \"\\n\" + funcString\n\n\t// join back with the import section\n\treturn importSection + body\n}\n\n/*\nGenerateRandomAntiDebug will Insert random order of anti-debug check\ntogether with inline compilation to induce big number\nof instructions in random order.\n*/\nfunc GenerateRandomAntiDebug(input string) string {\n\tlines := strings.Split(input, \"\\n\")\n\trandomChecks := []string{\n\t\t`obDependencyCheck()`,\n\t\t`obEnvArgsDetect()`,\n\t\t`obParentTracerDetect()`,\n\t\t`obParentCmdLineDetect()`,\n\t\t`obEnvDetect()`,\n\t\t`obEnvParentDetect() `,\n\t\t`obLdPreloadDetect()`,\n\t\t`obParentDetect()`,\n\t}\n\tvar obfile []string\n\t// find OB_CHECK and put the checks there.\n\tfor _, v := range lines {\n\t\tif strings.Contains(v, \"//\") {\n\t\t\tif strings.Contains(v, \"// OB_CHECK\") {\n\t\t\t\tthreadString := \"\"\n\t\t\t\tcheckString := \"\"\n\t\t\t\t// randomize order of check to replace\n\t\t\t\tfor j, v := range ShuffleSlice(randomChecks) {\n\t\t\t\t\tthreadString = threadString + \"go \" + v + \";\"\n\t\t\t\t\tcheckString += v\n\n\t\t\t\t\tif j != (len(randomChecks) - 1) {\n\t\t\t\t\t\tcheckString += `||`\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// add action in case of failed check\n\t\t\t\tobfile = append(obfile, threadString)\n\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t// remove comment, this is more to scramble the line numbers\n\t\t\t\t// and make error reporting less accurate\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tobfile = append(obfile, v)\n\t}\n\t// back to single string\n\treturn strings.Join(obfile, \"\\n\")\n}\n\n/*\nObfuscateLauncher the go code of the runner before compiling it.\n\nBasic techniques are applied:\n- GenerateRandomAntiDebug\n- ObfuscateStrings\n- ObfuscateFuncVars.\n*/\nfunc ObfuscateLauncher(infile string) error {\n\tbyteContent, err := ioutil.ReadFile(infile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read input file: %w\", err)\n\t}\n\n\tcontent := string(byteContent)\n\n\t// ------------------------------------------------------------------------\n\t//\t--- Start anti-debug checks\n\tcontent = GenerateRandomAntiDebug(content)\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t//\t--- Start string obfuscation\n\tcontent = ObfuscateStrings(content)\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t//\t--- Start function name obfuscation\n\tcontent = ObfuscateFuncVars(content)\n\t// ------------------------------------------------------------------------\n\n\t// save.\n\terr = ioutil.WriteFile(infile, []byte(content), 0600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to save output file: %w\", err)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "internal/pakkero/pakkero.go",
    "content": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\n*/\npackage pakkero\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"os\"\n\t\"os/signal\"\n\t\"strconv\"\n\t\"syscall\"\n\n\t\"github.com/alegrey91/go-upx\"\n)\n\nconst (\n\toffsetPlaceholder        = `\"9999999\"`\n\tstdoutEnabledPlaceholder = `\"ENABLESTDOUT\"`\n\tdepNamePlaceholder       = `\"DEPNAME1\"`\n\tdepSizePlaceholder       = `\"DEPSIZE2\"`\n\tdepBFDPlaceholder        = \"[]float64{1, 2, 3, 4}\"\n)\n\nvar launcherFile = os.TempDir() + \"/launcher.go\"\n\nfunc cleanup() {\n\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\tfmt.Print(\" → Cleaning up...\")\n\n\t// remove unused file\n\tExecCommand(\"rm\", []string{\"-f\", launcherFile})\n\tfmt.Printf(SuccessColor, \"\\t\\t\\t[ OK ]\\n\")\n}\n\nfunc trap() {\n\t// Prepare to intercept SIGTERM\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\n\tgo func() {\n\t\t<-c\n\t\tcleanup()\n\t\tos.Exit(ERR)\n\t}()\n}\n\n// Pakkero will Encrypt and pack the payload for a secure execution.\nfunc Pakkero(infile string, offset int64, outfile string, dependency string, compress bool, stdout bool) {\n\ttrap()\n\n\tfmt.Print(\" → Randomizing offset...\")\n\n\t// declare outfile as original filename + .enc\n\tif len(outfile) == 0 {\n\t\toutfile = infile + \".enc\"\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// offset Hysteresis, this will prevent easy key retrieving\n\toffset += Random(128, 4094)\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Register Dependency to try and bypass any tampering on dependent\n\t// packages\n\tfmt.Print(\" → Registering Dependencies...\")\n\n\tSecrets[stdoutEnabledPlaceholder] = []string{\"\\\"unset\\\"\", \"leaveunset\"}\n\t// ------------------------------------------------------------------------\n\t// Register eventual dependency passed by cli\n\t// If a dependency check is present, register it.\n\tif dependency != \"\" {\n\t\tRegisterDependency(dependency)\n\t} else {\n\t\t// in case of missing dependency add an empty variable for BFD\n\t\tSecrets[depBFDPlaceholder] = []string{\"[]float64{}\", \"leaveBFD\"}\n\t}\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Create the launcher program starting from our stub\n\tfmt.Print(\" → Creating Launcher Stub...\")\n\n\t// add offset to the secrets!\n\tSecrets[offsetPlaceholder] = []string{\n\t\tfmt.Sprintf(\"%d\", offset),\n\t\tGenerateTyposquatName(128),\n\t}\n\n\t// copy the stub from where to start.\n\tlauncherStub, _ := base64.StdEncoding.DecodeString(LauncherStub)\n\n\terr := ioutil.WriteFile(launcherFile, launcherStub, 0600)\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed writing to file: %s\", err))\n\t\tcleanup()\n\t\tos.Exit(ERR)\n\t}\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Obfuscate the launcher\n\tfmt.Print(\" → Obfuscating Launcher Stub...\")\n\n\terr = ObfuscateLauncher(launcherFile)\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed obfuscating file file: %s\", err))\n\t\tcleanup()\n\t\tos.Exit(ERR)\n\t}\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// compile the launcher binary\n\tfmt.Print(\" → Compiling Launcher...\")\n\n\tvar flags []string\n\n\tos.Setenv(\"CGO_ENABLED\", \"0\")\n\n\tflags = []string{\n\t\t\"build\", \"-a\",\n\t\t\"-trimpath\",\n\t\t\"-gcflags\",\n\t\t\"-N -l -nolocalimports\",\n\t\t\"-ldflags=\" +\n\t\t\t\"-X main.Stdout=\" + strconv.FormatBool(stdout) +\n\t\t\t\" -s -w -extldflags -static\\\"\",\n\t}\n\tflags = append(flags, \"-o\")\n\tflags = append(flags, outfile)\n\tflags = append(flags, launcherFile)\n\n\tif ExecCommand(\"go\", flags) {\n\t\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t} else {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tExecCommand(\"rm\", []string{\"-f\", outfile})\n\t\tcleanup()\n\t\tos.Exit(ERR)\n\t}\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Strip File of excess headers\n\tfmt.Print(\" → Stripping Launcher...\")\n\n\tif StripFile(outfile, launcherFile) {\n\t\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t} else {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tExecCommand(\"rm\", []string{\"-f\", outfile})\n\t\tcleanup()\n\t\tos.Exit(ERR)\n\t}\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Compress File of occupy less space\n\t// Then remove UPX headers from file.\n\tfmt.Print(\" → Compressing Launcher...\")\n\n\tif compress {\n\t\toptions := goupx.Options{\n\t\t\tOutput:               \"\",\n\t\t\tForce:                false,\n\t\t\tVerbose:              false,\n\t\t}\n\t\tupx := goupx.NewUPX()\n\t\tcompression, err := upx.Compress(outfile, 8, options)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\tif compression &&\n\t\t\tStripUPXHeaders(outfile) {\n\t\t\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t\t} else {\n\t\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\t\tExecCommand(\"rm\", []string{\"-f\", outfile})\n\t\t\tcleanup()\n\t\t\tos.Exit(ERR)\n\t\t}\n\t} else {\n\t\tfmt.Printf(WarningColor, \"\\t\\t[ SKIPPING ]\\n\")\n\t}\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Remove unused file\n\tfmt.Print(\" → Cleaning up...\")\n\n\tif ExecCommand(\"rm\", []string{\"-f\", launcherFile}) {\n\t\tfmt.Printf(SuccessColor, \"\\t\\t\\t[ OK ]\\n\")\n\t} else {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t\\t[ ERR ]\\n\")\n\t\tExecCommand(\"rm\", []string{\"-f\", outfile})\n\t\tos.Exit(ERR)\n\t}\n\t// ------------------------------------------------------------------------\n\n\t// read compiled file\n\tencFile, err := os.OpenFile(outfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed writing to file: %s\", err))\n\t\tos.Exit(ERR)\n\t}\n\tdefer encFile.Close()\n\tencFileStat, _ := encFile.Stat()\n\tencFileSize := encFileStat.Size()\n\n\t// ------------------------------------------------------------------------\n\t// Input validation\n\tfmt.Print(\" → Verifying input offset...\")\n\n\t// Ensure input offset is valid comared to compiled file size!\n\tif offset <= encFileSize {\n\t\tExecCommand(\"rm\", []string{\"-f\", outfile})\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(\"ERROR! Calculated offset is lower than launcher size: \" +\n\t\t\tfmt.Sprintf(\"offset=%d, filesize=%d\", offset, encFileSize))\n\t\tos.Exit(ERR)\n\t}\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Pre-Payload Garbage\n\t// calculate where to put garbage and where to put the payload\n\tfmt.Print(\" → Adding garbage...\")\n\n\tblockCount := offset - encFileSize\n\t// append randomness to the runner itself\n\t_, err = encFile.WriteString(GenerateRandomGarbage(blockCount))\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed writing to file: %s\", err))\n\t\tos.Exit(ERR)\n\t}\n\n\tfmt.Printf(SuccessColor, \"\\t\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Encryption and compression of the payload\n\t// get file to encrypt argument\n\tfmt.Print(\" → Reading payload...\")\n\n\tbyteContent, err := ioutil.ReadFile(infile) // just pass the file name\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed reading file: %s\", err))\n\t\tos.Exit(ERR)\n\t}\n\n\tcontent := string(byteContent)\n\n\t// plaintext content\n\tplaintext := []byte(base64.StdEncoding.EncodeToString([]byte(content)))\n\n\tfmt.Printf(SuccessColor, \"\\t\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\tfmt.Print(\" → Compressing payload...\")\n\n\t// GZIP before encrypt\n\tplaintext = GzipContent(plaintext)\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\tfmt.Print(\" → Encrypting payload...\")\n\n\t// encrypt aes256-gcm\n\tciphertext, err := EncryptAESReversed(plaintext, outfile)\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed encrypting file: %s\", err))\n\t\tos.Exit(ERR)\n\t}\n\n\t// append payload to the runner itself\n\t_, err = encFile.WriteString(ciphertext)\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed writing to file: %s\", err))\n\t\tos.Exit(ERR)\n\t}\n\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n\t// ------------------------------------------------------------------------\n\n\t// ------------------------------------------------------------------------\n\t// Post-Payload Garbage\n\t// calculate final padding\n\tfmt.Print(\" → Adding garbage to payload...\")\n\n\tfinalPaddingArray := make([]byte, binary.MaxVarintLen64)\n\tn := binary.PutVarint(finalPaddingArray, offset)\n\tfinalPaddingB := finalPaddingArray[:n]\n\t// change endianess to every byte composing\n\t// the offset\n\tfor i := range finalPaddingB {\n\t\tfinalPaddingB[i] = ReverseByte(finalPaddingB[i])\n\t}\n\n\tfinalPadding, _ := binary.Varint(finalPaddingB)\n\t// and ensure it is positive!\n\tif finalPadding < 0 {\n\t\tfinalPadding *= -1\n\t}\n\n\t// append random garbage equal to bit-reverse of the offset\n\t// at the end of the payload\n\t_, err = encFile.WriteString(GenerateRandomGarbage(finalPadding))\n\tif err != nil {\n\t\tfmt.Printf(ErrorColor, \"\\t\\t[ ERR ]\\n\")\n\t\tprintln(fmt.Sprintf(\"failed writing to file: %s\", err))\n\t\tos.Exit(ERR)\n\t}\n\n\t// ------------------------------------------------------------------------\n\tfmt.Printf(SuccessColor, \"\\t\\t[ OK ]\\n\")\n}\n"
  },
  {
    "path": "internal/pakkero/utilities.go",
    "content": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\nUtilities library\n*/\npackage pakkero\n\nimport (\n\t\"bytes\"\n\t\"compress/zlib\"\n\t\"crypto/rand\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"math/big\"\n\t\"os\"\n\t\"os/exec\"\n)\n\n// Colors for strings.\nconst (\n\tSuccessColor = \"\\033[1;32m%s\\033[0m\"\n\tWarningColor = \"\\033[1;33m%s\\033[0m\"\n\tErrorColor   = \"\\033[1;31m%s\\033[0m\"\n)\n\n// ERR Is the exit Code 1.\nconst ERR = 1\n\n// OK Is the exit Code 0.\nconst OK = 0\n\n/*\nRandomInt64 will return a random number in a range.\n*/\nfunc RandomInt64(max int64) int64 {\n\tbg := big.NewInt(max)\n\n\tn, err := rand.Int(rand.Reader, bg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn n.Int64()\n}\n\n/*\nRandom will return a random number in a range.\n*/\nfunc Random(min, max int64) int64 {\n\tbg := big.NewInt(max - min)\n\n\tn, err := rand.Int(rand.Reader, bg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t// add n to min to support the passed in range\n\treturn n.Int64() + min\n}\n\n/*\nUnique will deduplicate a given slice.\n*/\nfunc Unique(slice []string) []string {\n\tkeys := make(map[string]bool)\n\tlist := []string{}\n\n\tfor _, entry := range slice {\n\t\tif _, value := keys[entry]; !value {\n\t\t\tkeys[entry] = true\n\n\t\t\tlist = append(list, entry)\n\t\t}\n\t}\n\n\treturn list\n}\n\n/*\nReverseByteArray will reverse a slice of bytes.\n*/\nfunc ReverseByteArray(input []byte) []byte {\n\treversed := []byte{}\n\n\tfor i := range input {\n\t\tn := input[len(input)-1-i]\n\n\t\treversed = append(reversed, n)\n\t}\n\n\treturn reversed\n}\n\n/*\nReverseByte will change a byte endianess.\n*/\nfunc ReverseByte(b byte) byte {\n\tvar d byte\n\n\tfor i := 0; i < 8; i++ {\n\t\td <<= 1\n\t\td |= b & 1\n\t\tb >>= 1\n\t}\n\n\treturn d\n}\n\n/*\nReverseStringArray reverse a slice of strings.\n*/\nfunc ReverseStringArray(ss []string) []string {\n\tlast := len(ss) - 1\n\n\tfor i := 0; i < len(ss)/2; i++ {\n\t\tss[i], ss[last-i] = ss[last-i], ss[i]\n\t}\n\n\treturn ss\n}\n\n/*\nReverseString reverse a string.\n*/\nfunc ReverseString(input string) string {\n\tvar result string\n\n\tfor _, value := range input {\n\t\tresult = string(value) + result\n\t}\n\n\treturn result\n}\n\n/*\nShuffleSlice will shuffle a slice.\n*/\nfunc ShuffleSlice(in []string) []string {\n\tfor i := len(in) - 1; i > 0; i-- {\n\t\tj := RandomInt64(int64(i) + 1)\n\t\tin[i], in[j] = in[j], in[i]\n\t}\n\n\treturn in\n}\n\n/*\nExecCommand is a wrapper arount exec.Command to execute a command\nand ensure it's result is not err.\n*/\nfunc ExecCommand(name string, args []string) bool {\n\tcmd := exec.Command(name, args...)\n\n\terrString, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tprintln(fmt.Sprintf(\"failed to execute command %s: %s\", cmd, err))\n\t\tprintln(string(errString))\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n/*\nGenerateRandomGarbage creates random garbage to rise entropy.\n*/\nfunc GenerateRandomGarbage(size int64) string {\n\trandomGarbage := make([]byte, size)\n\n\t_, err := rand.Read(randomGarbage)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(randomGarbage)\n}\n\n/*\nGzipContent an input byte slice and return it compressed.\n*/\nfunc GzipContent(input []byte) []byte {\n\t// GZIP before encrypt\n\tvar zlibPlaintext bytes.Buffer\n\tzlibWriter := zlib.NewWriter(&zlibPlaintext)\n\n\t_, err := zlibWriter.Write(input)\n\tzlibWriter.Close()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn zlibPlaintext.Bytes()\n}\n\n/*\nGenerateNullString will return a string with only void chars.\n*/\nfunc GenerateNullString(n int) string {\n\tresult := \"\"\n\n\tfor len(result) < n {\n\t\tresult += string(0)\n\t}\n\n\treturn result\n}\n\n/*\nRegisterDependency will take a file in input and register the\nByte Frequency Distribution (BFD) and some other data to let the launcher\ndo statystical analysis of the found files.\n*/\nfunc RegisterDependency(dependency string) {\n\tdependencyFile, _ := os.Open(dependency)\n\tdefer dependencyFile.Close()\n\tdependencyStats, _ := dependencyFile.Stat()\n\tdepenencyLinkStats, _ := os.Lstat(dependency)\n\n\tif (depenencyLinkStats.Mode() & os.ModeSymlink) != 0 {\n\t\tcleanup()\n\t\tfmt.Printf(\"Invalid path: %s is a symlink, use absolute paths.\\n\", dependency)\n\t\tos.Exit(1)\n\t}\n\t// calculate BFD (byte frequency distribution) for the input dependency\n\tbytes, _ := ioutil.ReadFile(dependency)\n\n\tbfd := make([]float64, 256)\n\n\tfor _, b := range bytes {\n\t\tbfd[b]++\n\t}\n\t// make a string out of it\n\tbfdString := \"[]float64{\"\n\tfor _, v := range bfd {\n\t\tbfdString += fmt.Sprintf(\"%f\", v) + \",\"\n\t}\n\n\tbfdString += \"}\"\n\n\t// add Dependency data to the secrets\n\t// register BFD\n\tSecrets[depBFDPlaceholder] = []string{bfdString, \"leaveBFD\"}\n\t// register name\n\tSecrets[depNamePlaceholder] = []string{dependency, GenerateTyposquatName(128)}\n\t// register size\n\tSecrets[depSizePlaceholder] = []string{\n\t\tfmt.Sprintf(\"%d\", dependencyStats.Size()), GenerateTyposquatName(128),\n\t}\n}\n"
  },
  {
    "path": "main.go",
    "content": "/*\nPackage main, calls all the libraries needed and handles cli flags.\n*/\npackage main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\t\"github.com/89luca89/pakkero/internal/pakkero\"\n)\n\nconst (\n\tprogramName = \"pakkero\"\n\tversion     = \"0.7.0\"\n\tminArgsLen  = 2\n)\n\nconst (\n\tminOffsetCompressed = 750000\n\tmaxOffsetCompressed = 800000\n\tminOffset           = 1910000\n\tmaxOffset           = 2100000\n)\n\nvar (\n\tdependencies         = []string{\"ls\", \"sed\", \"go\", \"strip\"}\n\tdependenciesComplete = []string{\"upx\", \"ls\", \"sed\", \"go\", \"strip\"}\n)\n\n/*\nTestDependencies if all dependencies are present\nin the system.\n*/\nfunc testDependencies(deps []string) {\n\tfor _, v := range deps {\n\t\tif !pakkero.ExecCommand(\"which\", []string{v}) {\n\t\t\tprintln(\"Missing Dependency: \" + v)\n\t\t\tos.Exit(pakkero.ERR)\n\t\t}\n\t}\n}\n\n/*\nPrint version.\n*/\nfunc printVersion() {\n\tprintln(programName + \" v\" + version)\n\tos.Exit(pakkero.OK)\n}\n\n/*\nPrint Help.\n*/\nfunc help() {\n\tprintln(\"Usage: \" +\n\t\tprogramName +\n\t\t\" -file /path/to/file -offset OFFSET (-o /path/to/output) (-c) (-register-dep /path/to/file)\")\n\tprintln(\"  -file <file>\t\t\t\tTarget file to Pack\")\n\tprintln(\"  -o    <file>\t\t\t\tplace the output into <file> (default is <inputfile>.enc, optional)\")\n\tprintln(\"  -offset <offset>\t\t\tOffset where to start the payload (Number of Bytes, optional)\")\n\tprintln(\"  -register-dep <file-dependency>\tTarget file to analyze and use as fingerprint (absolute path, optional)\")\n\tprintln(\"  -c\t\t\t\t\tcompress the output to occupy less space (uses UPX, optional)\")\n\tprintln(\"  -enable-stdout\t\t\tWhether to wait and handle the process stdout/sterr or not (false by default, optional)\")\n\tprintln(\"  -v\t\t\t\t\tCheck \" + programName + \" version\")\n}\n\nfunc main() {\n\tif len(os.Args) < minArgsLen {\n\t\thelp()\n\t\tos.Exit(pakkero.ERR)\n\t}\n\n\tflag.Usage = func() {\n\t\thelp()\n\t}\n\tfile := flag.String(\"file\", \"\", \"\")\n\tdependency := flag.String(\"register-dep\", \"\", \"\")\n\toutput := flag.String(\"o\", \"\", \"\")\n\toffset := flag.Int64(\"offset\", 0, \"\")\n\tcompress := flag.Bool(\"c\", false, \"\")\n\tstdout := flag.Bool(\"enable-stdout\", false, \"\")\n\tflag.Bool(\"v\", false, \"\")\n\tflag.Parse()\n\n\tswitch os.Args[1] {\n\tcase \"-v\":\n\t\tprintVersion()\n\tdefault:\n\t\t// fist test if all dependencies are present\n\t\tif *compress {\n\t\t\t// compression needs additional upx dependency\n\t\t\ttestDependencies(dependenciesComplete)\n\t\t} else {\n\t\t\ttestDependencies(dependencies)\n\t\t}\n\n\t\t// set a default offset if not specified\n\t\tif *offset == 0 {\n\t\t\tif *compress {\n\t\t\t\t*offset = pakkero.Random(minOffsetCompressed, maxOffsetCompressed)\n\t\t\t} else {\n\t\t\t\t*offset = pakkero.Random(minOffset, maxOffset)\n\t\t\t}\n\t\t}\n\n\t\tif *file != \"\" {\n\t\t\tpakkero.Pakkero(*file, *offset, *output, *dependency, *compress, *stdout)\n\t\t} else {\n\t\t\tprintln(\"Missing arguments or invalid arguments!\")\n\t\t\thelp()\n\t\t\tos.Exit(pakkero.ERR)\n\t\t}\n\t}\n}\n"
  }
]