Repository: 89luca89/pakkero
Branch: master
Commit: 86322011b06e
Files: 13
Total size: 118.1 KB
Directory structure:
gitextract_h2o9k04m/
├── .gitignore
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── data/
│ └── launcher.go
├── go.mod
├── go.sum
├── internal/
│ └── pakkero/
│ ├── encryption.go
│ ├── obfuscation.go
│ ├── pakkero.go
│ └── utilities.go
└── main.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
PackNGo
test
dist
__*
tags
TODO.md
================================================
FILE: Dockerfile
================================================
FROM golang:alpine
ENV CGO_ENABLED=0
ENV GO111MODULE=off
RUN apk add --update-cache upx git make binutils coreutils \
&& rm -rf /var/cache/apk/*
RUN upx --version
RUN go version
RUN go get -d -v github.com/89luca89/pakkero
WORKDIR $GOPATH/src/github.com/89luca89/pakkero
RUN make
RUN ./dist/pakkero -v
ENTRYPOINT ["./dist/pakkero"]
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: Makefile
================================================
all:
go build -i \
-gcflags="-N" \
-gcflags="-nolocalimports" \
-gcflags="-pack" \
-gcflags="-trimpath=." \
-asmflags="-trimpath=." \
-gcflags="-trimpath=$$GOPATH/src/" \
-asmflags="-trimpath=$$GOPATH/src/" \
-ldflags="-X github.com/89luca89/pakkero/internal/pakkero.LauncherStub=$$(base64 -w0 data/launcher.go) -s" \
-o dist/pakkero;
strip \
-sxX \
--remove-section=.bss \
--remove-section=.comment \
--remove-section=.eh_frame \
--remove-section=.eh_frame_hdr \
--remove-section=.fini \
--remove-section=.fini_array \
--remove-section=.gnu.build.attributes \
--remove-section=.gnu.hash \
--remove-section=.gnu.version \
--remove-section=.got \
--remove-section=.note.ABI-tag \
--remove-section=.note.gnu.build-id \
--remove-section=.shstrtab \
--remove-section=.typelink \
dist/pakkero;
clean:
rm -rf dist/;
go build -i \
-gcflags="-N" \
-gcflags="-nolocalimports" \
-gcflags="-pack" \
-gcflags="-trimpath=." \
-asmflags="-trimpath=." \
-gcflags="-trimpath=$$GOPATH/src/" \
-asmflags="-trimpath=$$GOPATH/src/" \
-ldflags="-X github.com/89luca89/pakkero/internal/pakkero.LauncherStub=$$(base64 -w0 data/launcher.go) -s" \
-o dist/pakkero;
strip \
-sxXwSgd \
--remove-section=.bss \
--remove-section=.comment \
--remove-section=.eh_frame \
--remove-section=.eh_frame_hdr \
--remove-section=.fini \
--remove-section=.fini_array \
--remove-section=.gnu.build.attributes \
--remove-section=.gnu.hash \
--remove-section=.gnu.version \
--remove-section=.got \
--remove-section=.note.ABI-tag \
--remove-section=.note.gnu.build-id \
--remove-section=.shstrtab \
--remove-section=.typelink \
dist/pakkero
test: clean
dist/pakkero \
-file /usr/bin/echo -c \
-o /tmp/test.enc \
-offset 2850000 \
-enable-stdout \
-register-dep /usr/bin/bash;
sync;
sh -c "/tmp/test.enc test"
================================================
FILE: README.md
================================================
# Pakkero
<img src="pics/logo.jpg" data-canonical-src="pics/logo.jpg" width="250" height="250" />
Credit: [alegrey91](https://github.com/alegrey91) for the logo! Thanks!
[](https://goreportcard.com/report/github.com/89luca89/pakkero)
[](http://perso.crans.org/besson/LICENSE.html)
[](https://app.fossa.com/projects/git%2Bgithub.com%2F89luca89%2Fpakkero?ref=badge_small)
## Introduction
**Pakkero** is a binary packer written in Go made for fun and educational purpose.
Its main goal is to take in input a program file (elf binary, script, even appimage) and compress it, protect it from tampering and intrusion.
It 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:
```
base-bin 1.2M -> 1.6M
smaller-bin 2.4M -> 2.3M
small-bin 3.7M -> 3.0M
medium-bin 25M -> 16M
big-bin 148M -> 88M
```
With compression disabled, all resulting file size are ~1mb higher, making it suitable for 5+mb files.
#### How compares to UPX?
Tested 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:
- 12mb using `upx -9`
- 13mb using `pakkero -c`
- 14mb using `pakkero` without compression
## Install
If you have a [Go](https://golang.org/) environment ready to go, it's as easy as:
```bash
go get github.com/89luca89/pakkero
```
Once you retrieved you are ready to build:
```bash
cd $GOPATH/src/github.com/89luca89/pakkero; make
```
or to test
```bash
cd $GOPATH/src/github.com/89luca89/pakkero; make test
```
The binary file will be in `$GOPATH/src/github.com/89luca89/pakkero/dist`
The following are hard dependencies:
```
- go -> to build the launcher
- ls
- sed
- strip -> to strip the launcher
```
The following are weak dependencies
```
- upx -> needed for launcher compression (optional)
```
**GO 1.13+ needed**
**Dependencies are checked at runtime and an error message will specify what is missing**
# Disclaimer
**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.
---
Pakkero is divided in two main pieces, the packer part (Pakkero itself) and the
launcher part.
## Part 1: the packer
Pakkero can be launched like:
```bash
pakkero --file ./target-file -o ./output-file -register-dep dependency-file -c
```

### Usage
Typing `pakker -h` the following output will be shown:
```bash
Usage: pakkero -file /path/to/file -offset OFFSET (-o /path/to/output) (-c) (-register-dep /path/to/file)
-file <file> Target file to Pack
-o <file> place the output into <file> (default is <inputfile>.enc), optional
-c compress the output to occupy less space (uses UPX), optional
-offset Offset where to start the payload (Number of Bytes)
-enable-stdout Whether to wait and handle the process stdout/sterr or not (false by default, optional)
-register-dep /path/to/dependency to analyze and use as fingerprint (absolutea, optional)
-v Check pakkero version
```
Below there is a full explanation of provided arguments:
* **file**: The file we want to pack
* **o**: (optional) The file output that we will create
* **c**: (optional) If specified, UPX will be used to further compress the Launcher
* **offset**: (optional) The number of bytes from where to start the payload (increases if not using compression)
* **enable-stdout** (optional) whether to enable or not the handling of the stdout/err of the payload <u>**disabled by default, less secure**</u>
* **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
* **v**: Print version
### Packaging
**The main intent is to not alter the payload in any way, this can be very important
for types of binary that rely on specific order of instructions or relatively fragile timings.**
The target of pakkero is not to touch the "payload".
Other 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
the 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)
#### Building
To build the project, you can simply use the `Makefile`;
- `make` will compile
- `make test` will compile and run a run with a simple binary (echo)
**Why not using simply go build?**
Go build works fine, but will skip a fundamental step in the building process, **the injection of the launcher stub inside Pakkero source**
This way the Pakkero binary has inside the source of the Launcher to be used for each packaging.
#### Building using Docker
Build Pakkero image:
```sh
sudo docker build . -t pakkero
```
Run containerized Pakkero:
```sh
sudo docker run -it -v <target_dir>:/ext pakkero --file /ext/<target_elf> -o /ext/<target_elf>.packed
```
#### Building using Podman
Build Pakkero image:
```sh
sudo podman build . -t pakkero
```
Run containerized Pakkero:
```sh
sudo podman run -it -v <target_dir>:/ext pakkero --file /ext/<target_elf> -o /ext/<target_elf>.packed
```
#### Payload
For this purpose the payload is simply compressed using zlib then encrypted using AES256-GCM
During encryption, some basic operations are also performed on the payload:
- putting garbage random values before and after the payload to mask it
- reverse it and change each byte endianess
Encryption 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
some integrity protection and anti-tampering.
#### Offset
The offset will decide **where in the output file the payload starts**.
Put simply, after the launcher is compiled (more on the launcher later), the payload is
attached to it. The offset ensures that the payload can be put anywhere after it.
All the space after the launcher until the payload is filled with random garbage.

Being part of the password itself, greater offset will make stronger the encryption, but
enlarge the final output file.
Optimal value are **at least** 800000 when compression is enabled and **1900000** when disabled. *If not specified a random one will be chosen upon creation.
### Obfuscation
The 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.
The technique utilized for obfuscating the function and variables name is based on typo-squatting:

This 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:
```go
mixedRunes := []rune("0OÓÕÔÒÖŌŎŐƠΘΟ")
```
For pure strings in the launcher, they are detected using regular expressions, finding
all the words that are comprised between the three type of ticks supported in go
```
`
'
"
```
All of the strings found this way, are then replaced with a function that performs a simple operation of reconstruction of the original string:
```go
func ÓΘŌOÒŐÒŌÓÒOŎΘOΟ0ŐÒÖŎÕΟΘÕÓÕÓŎÓŌÕ0ŎŌΘÕŎÕ() string {
ŌÒ0ŎŎŐÓÖÖΘO0ŌŌŌÒŌŌÒƠÔÖΘŐÖΟŎƠƠ00Õ0ÖÕ0ÖŐŐÓΟŌΟ := []string{"Ò0ƠŐÖŐŎΘÖƠÔÖÕÓΘÕÕŌŎŐƠÔΘΘƠ", "ÔÒÕΟƠŐÒŌOƠÖ", "ƠΘŐÒƠΘŌ00ΘΘΟÔŎŎΘŐƠŐΘŎΟÕÖÕÖΟÖΘÒÖ"}
var ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ []byte
for _, ŌΘƠÔÕÔΘÔOÔOŐΟΘŌΘƠÔÕÔΘÔOÔOŐΟΘ := range ŌÒ0ŎŎŐÓÖÖΘO0ŌŌŌÒŌÕÒÔÕŌŎ00ÔÔÒOƠÓÕÔÒ0ΘƠΘŐ0OOŎÓÒŐ0Õ0ÓOÕÓŐƠŌŎÕÖ0ÕÖÔŌΟΟŌÒÖÒÖOΟOÒ0ÖŐŐÓΟŌΟ {
ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ = append(ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ, byte(len([]rune(ŌΘƠÔÕÔΘÔOÔOŐΟΘŌΘƠÔÕÔΘÔOÔOŐΟΘ))))
}
return string(ΟŐÔÒÖÔΘÕÔŎÒÓÖÖÒΘ0ÖÔΟÖŎ0ÔOÓÖƠŌÔÓŌŌ)
}
```
A slice of string is generated, with each element has a lenght derived from the byte value of the original char of the original string.
This way each byte of the original string is computed and calculated as the lenght of the correspondent string, casted to rune slice.
The launcher is compiled then using:
```go
flags = []string{"build", "-a",
"-trimpath",
"-gcflags",
"-N -l -nolocalimports",
"-ldflags",
"-s -w -extldflags -static",
}
exec.Command("go", flags...)
```
File is the **stripped**, using `strip` with the flags:
```bash
-sxX
--remove-section=.bss
--remove-section=.comment
--remove-section=.eh_frame
--remove-section=.eh_frame_hdr
--remove-section=.fini
--remove-section=.fini_array
--remove-section=.gnu.build.attributes
--remove-section=.gnu.hash
--remove-section=.gnu.version
--remove-section=.gosymtab
--remove-section=.got
--remove-section=.note.ABI-tag
--remove-section=.note.gnu.build-id
--remove-section=.note.go.buildid
--remove-section=.shstrtab
--remove-section=.typelink
```
Additionally, if using *UPX*, their headers are **removed and replaced with randomness**, to ensure simple things like `upx -d` will not work.
Additionally a series of extra words are removed from the binary and replaced with random bytes, to make it harder to do static analysis:
```
.gopclntab
.go.buildinfo
.noptrdata
.noptrbss
.data
.rodata
.text
.itablink
.shstrtab
.data
.dynamic
.dynstr
.dynsym
.gnu.version_r
.gopclntab
.got.plt
.init_array
.interp
.itablink
.rela.dyn
.rela.plt
.tbss
.plt
.init
name runtime command cmd
ptr process unicode main
path get reflect context
debug fmt sync sort
size heap fatal call
fixed slice bit file
read write buffer encrypt
decrypt hash state
external internal float
env trace pid
```
Output of readelf to see the effect:

#### File Entropy
Using binwalk to analyze the file entropy can give some hint on how the process works:
This is the entropy of the binary we want to package (for this example /usr/bin/bash):

This is the entropy of a packaged binary **without compression**

This is the entropy of a packaged binary **with compression**

In both cases (but mainly the first) it is possible to see when the launcher stops and
the 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.
This 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.
## Part 2: the launcher
The 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.
This is a well known technique as it is possible to read:
- [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)
- [ELF in-memory execution](https://blog.fbkcs.ru/en/elf-in-memory-execution/)
and in many other places in C programming literature.
```
Put briefly, use syscall to create a memory file descriptor (syscall 319 for amd64),
write the plaintext payload here, and execute.
The fd will be automatically removed after the execution without
leaving trace on the storage.
```
### Possible weakpoints
This approach is vulnerable to
1. "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
2. "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**
3. dynamic analysis, during execution "pausing" the process and spot the right fd
4. 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
For 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.
Point 3 (and by consequence point 4) can be made harder by blocking dynamic analysis detecting debuggers, tracers and so on...
Forcing static analysis of the decompiled code is already a big step forward in protecting the binary execution.
### Anti-debug
Implemented 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.
First line of protection is breakpoints interception, on linux, a breakpoints is equivalent to signal *SIGILL* and *SIGTRAP* so:
```go
/*
Breakpoint on linux are 0xCC and will be interpreted as a
SIGTRAP, we will intercept them.
*/
func obSigTrap(obInput chan obOS.Signal) {
obMySignal := <-obInput
switch obMySignal {
case obSyscall.SIGILL:
obExit()
case obSyscall.SIGTRAP:
obExit()
default:
return
}
}
```
This is pretty basic, so we go ahead and try to block **ptrace**:
```go
// attach to PTRACE, register if successful
// attach A G A I N , register if unsuccessful
// this protects against custom ptrace (always returning 0)
// against NOP attacks and LD_PRELOAD attacks
func obPtraceDetect() {
var obOffset = 0
obProc, _ := obOS.FindProcess(obOS.Getppid())
obErr := obSyscall.PtraceAttach(obProc.Pid)
if obErr == nil {
obOffset = 5
}
obErr = obSyscall.PtraceAttach(obProc.Pid)
if obErr != nil {
obOffset *= 3
}
if obOffset != (3 * 5) {
obProc.Signal(obSyscall.SIGCONT)
println(1)
return
}
obErr = obSyscall.PtraceDetach(obProc.Pid)
if obErr != nil {
obProc.Signal(obSyscall.SIGCONT)
println(0)
return
}
obProc.Signal(obSyscall.SIGCONT)
println(0)
}
```
*Double ptraceme* ensures that tampering the ptrace loading with a fake ptrace lib that always returns 0, would result in a failure.
CMD Line detection, would check for common processes for debugging, this is pretty naive check:
```go
/*
Check the process cmdline to spot if a debugger is inline
*/
func obParentCmdLineDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/cmdline"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
if obStrings.Contains(string(obStatParent), "gdb") ||
obStrings.Contains(string(obStatParent), "dlv") ||
obStrings.Contains(string(obStatParent), "edb") ||
obStrings.Contains(string(obStatParent), "frida") ||
obStrings.Contains(string(obStatParent), "ghidra") ||
obStrings.Contains(string(obStatParent), "godebug") ||
obStrings.Contains(string(obStatParent), "ida") ||
obStrings.Contains(string(obStatParent), "lldb") ||
obStrings.Contains(string(obStatParent), "ltrace") ||
obStrings.Contains(string(obStatParent), "strace") ||
obStrings.Contains(string(obStatParent), "valgrind") {
obExit()
}
}
```
```go
/*
Check the process cmdline to spot if a debugger is the PPID of our process
*/
func obParentDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/stat"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
if obStrings.Contains(string(obStatParent), "gdb") ||
obStrings.Contains(string(obStatParent), "dlv") ||
obStrings.Contains(string(obStatParent), "edb") ||
obStrings.Contains(string(obStatParent), "frida") ||
obStrings.Contains(string(obStatParent), "ghidra") ||
obStrings.Contains(string(obStatParent), "godebug") ||
obStrings.Contains(string(obStatParent), "ida") ||
obStrings.Contains(string(obStatParent), "lldb") ||
obStrings.Contains(string(obStatParent), "ltrace") ||
obStrings.Contains(string(obStatParent), "strace") ||
obStrings.Contains(string(obStatParent), "valgrind") {
obExit()
}
}
```
this goes in conjunction with the TracePid check to see if a parent is tracing us:
```go
/*
Check the process status to spot if a debugger is active using the TracePid key
*/
func obParentTracerDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/status"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
obStatLines := obStrings.Split(string(obStatParent), "\n")
for _, obValue := range obStatLines {
if obStrings.Contains(obValue, "TracerPid") {
obSplitArray := obStrings.Split(obValue, ":")
obSplitValue := obStrings.Replace(obSplitArray[1], "\t", "", -1)
if obSplitValue != "0" {
obExit()
}
}
}
}
```
and 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`
```go
/*
Check the process cmdline to spot if a debugger is launcher
"_" and Args[0] should match otherwise
*/
func obEnvArgsDetect() {
obLines, _ := obOS.LookupEnv("_")
if obLines != obOS.Args[0] {
obExit()
}
}
```
and check if there is none of the known debuggers inline with the command
```go
/*
Check the process cmdline to spot if a debugger is inline
"_" should not contain the name of any debugger
*/
func obEnvParentDetect() {
obLines, _ := obOS.LookupEnv("_")
if obStrings.Contains(obLines, "gdb") ||
obStrings.Contains(obLines, "dlv") ||
obStrings.Contains(obLines, "edb") ||
obStrings.Contains(obLines, "frida") ||
obStrings.Contains(obLines, "ghidra") ||
obStrings.Contains(obLines, "godebug") ||
obStrings.Contains(obLines, "ida") ||
obStrings.Contains(obLines, "lldb") ||
obStrings.Contains(obLines, "ltrace") ||
obStrings.Contains(obLines, "strace") ||
obStrings.Contains(obLines, "valgrind") {
obExit()
}
}
```
Also a pretty common check to do if we are in a debugger is to see if ENV has the variables LINES and COLUMNS:
```go
/*
Check the process cmdline to spot if a debugger is active
most debuggers (like GDB) will set LINE,COLUMNS or LD_PRELOAD
to function, we try to spot this
*/
func obEnvDetect() {
_, obLines := obOS.LookupEnv("LINES")
_, obColumns := obOS.LookupEnv("COLUMNS")
_, obLineLdPreload := obOS.LookupEnv("LD_PRELOAD")
if obLines || obColumns || obLineLdPreload {
obExit()
}
}
```
This can give false positives (example the embedded terminal in VSCode or VIM), but worth checking for a normal environment.
Also banally checking for LD_PRELOAD env variable present:
```go
/*
Check the process is launcher with a LD_PRELOAD set.
This can be an injection attack (like on frida) to try and circumvent
various restrictions (like ptrace checks)
*/
func obLdPreloadDetect() {
obKey := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)
obValue := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)
err := obOS.Setenv(obKey, obValue)
if err != nil {
obExit()
}
obLineLdPreload, _ := obOS.LookupEnv(obKey)
if obLineLdPreload == obValue {
err := obOS.Unsetenv(obKey)
if err != nil {
obExit()
}
} else {
obExit()
}
}
```
to 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).
This type of checks are pretty basic and easy to port from C to Go.
A 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)
> GDB relocates the heap to the end of the bss section
This 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)
### Making difficult to reverse
To add to this in many points of the source code it is possible to see that a comment is made:
`//OB_CHECK`
This 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.
```go
/*
GenerateRandomAntiDebug will Insert random order of anti-debug check
together with inline compilation to induce big number
of instructions in random order
*/
func GenerateRandomAntiDebug(input string) string {
lines := strings.Split(input, "\n")
randomChecks := []string{
`obDependencyCheck()`,
`obEnvArgsDetect()`,
`obParentTracerDetect()`,
`obParentCmdLineDetect()`,
`obEnvDetect()`,
`obEnvParentDetect() `,
`obLdPreloadDetect()`,
`obParentDetect()`,
}
// find OB_CHECK and put the checks there.
for i, v := range lines {
if strings.Contains(v, "// OB_CHECK") {
threadString := ""
checkString := ""
// randomize order of check to replace
for j, v := range ShuffleSlice(randomChecks) {
threadString = threadString + "go " + v + ";"
checkString += v
if j != (len(randomChecks) - 1) {
checkString += `||`
}
}
// add action in case of failed check
lines[i] = threadString
}
}
// back to single string
return strings.Join(lines, "\n")
}
```
The 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.
So the main, for example, becomes something like:
```go
func main() {
// Prepare to intercept SIGTRAP
ÖÖΘÓ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)
ÔƠÕΟÒΘΘÖŎ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)
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ŌÕŎÒŎÔŌÓƠÓŌŐΟΟÒÒƠ)
// ÔOÒŎ00ƠÒŎΟOÓΟÖΟOÖΘÓƠƠƠŎÖŌŐŐÒÓÔOŎÒÔΘŌΟÓŐÒΟƠOÕÖÕƠƠÕŎÔÔÒΟOÖO0ŐÔÓÓƠÒ0ŎΘOÒŎOŐÔŌƠÓÒÕÕΟO0ÓƠÒŎŌÖOŌÖOÕÒƠŐÓΟŐÔÔŎŐÓÔÓOƠΘOOŎ0ƠΘÓΘÕÔÕƠÓΘÒÔŐΟÒ()
go ÔŐŌŌÒÓ0OΟO0ÖΟŌ0ƠÒ0ÒŌÔOΟΟÖŎÕ0ΘÓΘOOΟΟΘ0Ơ0ΘŐÕ0ΟÔŐ0ŐŌÕ00ŌOΟΟÒÕÒÖŌÓOOÒÔΘÒΘÒÔŌŎΟÒŐŌÕÒÕŎÖÒÖÕΘ00OÖÓŌÓÖÖÓÔƠΘŌ0ÓÕ0ŌÖΘOÖ0ÓŐƠ0ΟÖ00ŌŐŐΘΘÕÒƠÕΟ()
go ÖƠŎŎΘΟÓÓÒÖÒ0ÓΘŎÖΘŌ0ŎOÕÔÓƠÔÔΘŌÔΘ0OÕOΟOÕƠŌÒŎ0O0ŎΘΟÒÕΟΟÓ0ŎΟÒΘÕΟÖŎÕÔOÕOΘΘŐÖŌŐΟÔΟÖΟ0OÔÓ0ΟŐOŌÕŌOŌOÕÒÒΘΟŎƠΟÒŌ0ƠΟÔOÒÓÒΟŐÕÒŌƠÔÖ0ŐÖÖÖÓΟƠŌÕ()
go ƠΘÔŐŎŌÒŌÖŌΟŎOΟŐŎŎΘOƠÔ0ŐƠΘÒΟƠŐŌ0ŌΘΟΟÒŎÖÓ0ÒΟŐ0ƠΘŌÒÔÔŌƠŌÖOƠÓÔŌOÓ0OŐÕÒ0ŌÖÓŎÕŎÕÓÓ0ÒΘÖΟΘŎÕÓƠŐΟÕΟŌÔŎŌÓOÒÓ0Ŏ0ΟÕÔÒŌƠΘŌΟŎŐΘƠÔÓŐΘŎÔŌŌO0ƠÒÖÖ()
go ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()
go ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()
go ÔŌÕŌŐ0ŐÓÖΘŐÖΟŎΟƠŎOÖÖÕÒΘƠŐΟÓΟΘOÒƠΟ0ÒÒÖÖŌŎŌΘƠƠOΟÒƠΟΘOÓÕŌÕÒÕO0ŎOÔŐOÖŎÓÔOO0OÕŌOΘ0ÒƠƠÔŌÔÔÔŐΟ0ΘΘOŌOÒÕÒÕÕOÔÕŐŌΟÒŌÔ00ÖƠÔΟ0ΟÔŐΟƠÖÕΘ0ÖΟŌÖÖ()
go ÒŎÒ0ΘŐŐÔƠΘÒŐŎΘÓÕÕÔŎÖ0ŌÖÖΟÖÓÔÓÒÖÖŌŐΘŌ0ÕÖŎÓΟŌŌÒÖ0ΘÖOΘŎŎÖΘΟÓÒƠΟŐOƠOΘΘÓ0ÕΘŐƠÔÖΟΟ0OΘÖΘŎΟŐÕΘŐΟÓÓƠƠŐÒΟÖΘOŌƠΟΘŎ0ÒΟƠƠÔŎ00ŌÕÓÒ0ŌŎÒOƠŎÖŐÕÓƠ()
go ŎÓÕƠŌOŌΟÖÓ0ÒÓΘΟ0ƠŎÖΟŌŎÕÒÕÓŎÖÕƠÒŎŐƠÒƠ0ÒƠÖÕŎÒŐÓÔÓÒ0ΟÕŌÒŐOŐŌÖOÕƠƠÔŎÖ0ÒÓÒÕOÖÕƠÔÕOÔÖΟΘÕÔ0OÕƠÓOÓOÔÖÒ0ΟÖOÖÔΘŌOŌŎΘΘΘ0ŐŌOÔÒΟƠ0ŐÓÕŐÔŐΟÒŐÒΟ()
ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()
go ÔŐŌŌÒÓ0OΟO0ÖΟŌ0ƠÒ0ÒŌÔOΟΟÖŎÕ0ΘÓΘOOΟΟΘ0Ơ0ΘŐÕ0ΟÔŐ0ŐŌÕ00ŌOΟΟÒÕÒÖŌÓOOÒÔΘÒΘÒÔŌŎΟÒŐŌÕÒÕŎÖÒÖÕΘ00OÖÓŌÓÖÖÓÔƠΘŌ0ÓÕ0ŌÖΘOÖ0ÓŐƠ0ΟÖ00ŌŐŐΘΘÕÒƠÕΟ()
go ƠΘÔŐŎŌÒŌÖŌΟŎOΟŐŎŎΘOƠÔ0ŐƠΘÒΟƠŐŌ0ŌΘΟΟÒŎÖÓ0ÒΟŐ0ƠΘŌÒÔÔŌƠŌÖOƠÓÔŌOÓ0OŐÕÒ0ŌÖÓŎÕŎÕÓÓ0ÒΘÖΟΘŎÕÓƠŐΟÕΟŌÔŎŌÓOÒÓ0Ŏ0ΟÕÔÒŌƠΘŌΟŎŐΘƠÔÓŐΘŎÔŌŌO0ƠÒÖÖ()
go ÖƠŎŎΘΟÓÓÒÖÒ0ÓΘŎÖΘŌ0ŎOÕÔÓƠÔÔΘŌÔΘ0OÕOΟOÕƠŌÒŎ0O0ŎΘΟÒÕΟΟÓ0ŎΟÒΘÕΟÖŎÕÔOÕOΘΘŐÖŌŐΟÔΟÖΟ0OÔÓ0ΟŐOŌÕŌOŌOÕÒÒΘΟŎƠΟÒŌ0ƠΟÔOÒÓÒΟŐÕÒŌƠÔÖ0ŐÖÖÖÓΟƠŌÕ()
go ÒŎÒ0ΘŐŐÔƠΘÒŐŎΘÓÕÕÔŎÖ0ŌÖÖΟÖÓÔÓÒÖÖŌŐΘŌ0ÕÖŎÓΟŌŌÒÖ0ΘÖOΘŎŎÖΘΟÓÒƠΟŐOƠOΘΘÓ0ÕΘŐƠÔÖΟΟ0OΘÖΘŎΟŐÕΘŐΟÓÓƠƠŐÒΟÖΘOŌƠΟΘŎ0ÒΟƠƠÔŎ00ŌÕÓÒ0ŌŎÒOƠŎÖŐÕÓƠ()
go ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()
go ŎÓÕƠŌOŌΟÖÓ0ÒÓΘΟ0ƠŎÖΟŌŎÕÒÕÓŎÖÕƠÒŎŐƠÒƠ0ÒƠÖÕŎÒŐÓÔÓÒ0ΟÕŌÒŐOŐŌÖOÕƠƠÔŎÖ0ÒÓÒÕOÖÕƠÔÕOÔÖΟΘÕÔ0OÕƠÓOÓOÔÖÒ0ΟÖOÖÔΘŌOŌŎΘΘΘ0ŐŌOÔÒΟƠ0ŐÓÕŐÔŐΟÒŐÒΟ()
go ÔŌÕŌŐ0ŐÓÖΘŐÖΟŎΟƠŎOÖÖÕÒΘƠŐΟÓΟΘOÒƠΟ0ÒÒÖÖŌŎŌΘƠƠOΟÒƠΟΘOÓÕŌÕÒÕO0ŎOÔŐOÖŎÓÔOO0OÕŌOΘ0ÒƠƠÔŌÔÔÔŐΟ0ΘΘOŌOÒÕÒÕÕOÔÕŐŌΟÒŌÔ00ÖƠÔΟ0ΟÔŐΟƠÖÕΘ0ÖΟŌÖÖ()
go ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()
ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()
go ÒŎ0ÖƠÔŌÔÖΟΘƠΟÒƠƠÖ0ŐÓÓΟOÓŎÖΟÔŌOOΟÔÒÓƠÓΟŎŎ0ÕƠŌÕÒÒÖ0OŌÕŐ0ƠÖΟƠÕÔÒÖŎÖÔÕÔŐOƠŌƠÒΘŌŎÖOŎΘÓÔÔΟŐŌΟŐƠÕΟÖŐ0ÔΘƠŌƠƠÒOOŎÔ0ŐΟÕÕŌÕÔÕÒŐÔŐÔÖÓƠÖΟOŌŎƠ()
go ÔŌÕŌŐ0ŐÓÖΘŐÖΟŎΟƠŎOÖÖÕÒΘƠŐΟÓΟΘOÒƠΟ0ÒÒÖÖŌŎŌΘƠƠOΟÒƠΟΘOÓÕŌÕÒÕO0ŎOÔŐOÖŎÓÔOO0OÕŌOΘ0ÒƠƠÔŌÔÔÔŐΟ0ΘΘOŌOÒÕÒÕÕOÔÕŐŌΟÒŌÔ00ÖƠÔΟ0ΟÔŐΟƠÖÕΘ0ÖΟŌÖÖ()
go ƠΘÔŐŎŌÒŌÖŌΟŎOΟŐŎŎΘOƠÔ0ŐƠΘÒΟƠŐŌ0ŌΘΟΟÒŎÖÓ0ÒΟŐ0ƠΘŌÒÔÔŌƠŌÖOƠÓÔŌOÓ0OŐÕÒ0ŌÖÓŎÕŎÕÓÓ0ÒΘÖΟΘŎÕÓƠŐΟÕΟŌÔŎŌÓOÒÓ0Ŏ0ΟÕÔÒŌƠΘŌΟŎŐΘƠÔÓŐΘŎÔŌŌO0ƠÒÖÖ()
go ÒŎÒ0ΘŐŐÔƠΘÒŐŎΘÓÕÕÔŎÖ0ŌÖÖΟÖÓÔÓÒÖÖŌŐΘŌ0ÕÖŎÓΟŌŌÒÖ0ΘÖOΘŎŎÖΘΟÓÒƠΟŐOƠOΘΘÓ0ÕΘŐƠÔÖΟΟ0OΘÖΘŎΟŐÕΘŐΟÓÓƠƠŐÒΟÖΘOŌƠΟΘŎ0ÒΟƠƠÔŎ00ŌÕÓÒ0ŌŎÒOƠŎÖŐÕÓƠ()
go ΟƠŐΟÔOƠÔΟΟÓΘÖOŐΟÕƠ0ΘŐÓÖÔŎÒ0OÔŐÓΟƠΘΘΘÔOÖŌÕŎÒŎΟÔÕÒŎÓ0OÖƠ0ÖÓOÒŐÓŐÔΘÓŌƠÕŎÕÒΟÖŌÒŎΟ0ÒÔÔÕ0ÕÓÒÓÒÔ0ŎO0Θ0ΘŐÖΟŎÖŌOΘÒΘ0ÕŐÖÓΟOÖÒÒÔÕOƠÒŎΘO0ÔÓÔ()
go ÔŐŌŌÒÓ0OΟO0ÖΟŌ0ƠÒ0ÒŌÔOΟΟÖŎÕ0ΘÓΘOOΟΟΘ0Ơ0ΘŐÕ0ΟÔŐ0ŐŌÕ00ŌOΟΟÒÕÒÖŌÓOOÒÔΘÒΘÒÔŌŎΟÒŐŌÕÒÕŎÖÒÖÕΘ00OÖÓŌÓÖÖÓÔƠΘŌ0ÓÕ0ŌÖΘOÖ0ÓŐƠ0ΟÖ00ŌŐŐΘΘÕÒƠÕΟ()
go ŎÓÕƠŌOŌΟÖÓ0ÒÓΘΟ0ƠŎÖΟŌŎÕÒÕÓŎÖÕƠÒŎŐƠÒƠ0ÒƠÖÕŎÒŐÓÔÓÒ0ΟÕŌÒŐOŐŌÖOÕƠƠÔŎÖ0ÒÓÒÕOÖÕƠÔÕOÔÖΟΘÕÔ0OÕƠÓOÓOÔÖÒ0ΟÖOÖÔΘŌOŌŎΘΘΘ0ŐŌOÔÒΟƠ0ŐÓÕŐÔŐΟÒŐÒΟ()
go ÖƠŎŎΘΟÓÓÒÖÒ0ÓΘŎÖΘŌ0ŎOÕÔÓƠÔÔΘŌÔΘ0OÕOΟOÕƠŌÒŎ0O0ŎΘΟÒÕΟΟÓ0ŎΟÒΘÕΟÖŎÕÔOÕOΘΘŐÖŌŐΟÔΟÖΟ0OÔÓ0ΟŐOŌÕŌOŌOÕÒÒΘΟŎƠΟÒŌ0ƠΟÔOÒÓÒΟŐÕÒŌƠÔÖ0ŐÖÖÖÓΟƠŌÕ()
.....
```
###
### Dependency Registration
Another form of protection, is the *dependency registration*.
The idea behind it is to protect not only elf binaries, but also executable scripts, like python, bash, perl, php or anything with a shebang.
A 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.
If in the environment (or really with a symlink on /usr/bin/bash) we put something like:
```bash
#!/bin/sh
cp $0 /tmp/plaintext
/usr/bin/real-bash $@
```
This will result in a transparent execution but a dumped plaintext in /tmp
(credits for the attack idea to [mrnfrancesco (Francesco Marano) · GitHub](https://github.com/mrnfrancesco) )
###
So what can we do to ensure nothing like this happens?
We 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.
Now there is a problem, how do we verify that it's a valid binary?
Using 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.
Only the presence of it is not enough (like in the example attack before)
Some basic checks are made:
- the file exists
- file size is +/- 15% of the registered one
But something more is needed.
#### Byte Frequency Distribution Study
To address the problem it is possible to recycle a technique mostly used in the data-recovery territory: the <u>byte frequency distribution study</u>.
References:
- [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)
- [A New Approach to Content-based File Type Detection](https://arxiv.org/pdf/1002.3174)
The 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.
> Ref: [Pearson correlation coefficient - Wikipedia](https://en.wikipedia.org/wiki/Pearson_correlation_coefficient)
Pearson'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").

If the index indicates strong correlation, we know that the two file are of the same type (binary)
A 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.
This 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.
Here an example of a valid dependency: /usr/bin/bash on fedora30 vs centos7

Blue and green the two BFD of the binaries, in green the combined std deviation.
This method is able to distinguish (and stop) the use of different (but functionally equal) binaries like zsh, dash or busybox
### Decryption
The last line of defense is also the encryption of the payload.
The decryption key of the payload is the sha512sum of the compiled launcher itself with the random garbage appended to it.
For example:
With offset 930000
```
Compiled launcher (800kb)
OFFSET1 (130kb)
Payload
OFFSET2 ( different one, 130kb)
```
The decryption key is
`sha512sum(Launcher+OFFSET1)`
This protects from file-based NOP attacks to remove some instructions from the launcher, and acts also as binary validation.

The payload is structured as above, OFFSET1 **ends on the offset value**, OFFSET2 is calculated as the byte reverse of the offset value.
The procedure will:
- calculate the offset
- take the launcher+OFFSET1, sha512sum it
- remove OFFSET2 random bytes at the end
- decrypt payload using the calculated sha512sum
So **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.
### Execution
As explained above, we will use a memory file descriptor to execute the binary without passing for the storage.
The binary will be executed using the `Command` library of Go, that uses the syscall exec under the hood, so no new shells are instantiated.
### **If stdout management is NOT enabled (default)**
The process is launched and disowned.
Upon 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
**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
This way even a script launcher with this approach is not possible to be retrieved:

### **If stdout management is enabled**
Two routines are used to pipe the payload stderr and stdout to the launcher process.
Also piping is supported.
For IO heavy processes it is possible to insert in the `Scan` of the outputs an `OB_CHECK` like this:
```go
// OB_CHECK
// async fetch stdout
go func() {
defer obWaitGroup.Done()
for obStdoutScan.Scan() {
// OB_CHECK
println(obStdoutScan.Text())
}
}()
// OB_CHECK
// async fetch stderr
go func() {
defer obWaitGroup.Done()
for obStderrScan.Scan() {
// OB_CHECK
println(obStderrScan.Text())
}
}()
```
This 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
<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
This is particularly discouraged for **srcipts payloads**, as they are even easier to spot as the path is directly in the process

With binaries the approach is safer (only the binary name is in the process, thus making it hard to spot requiring a complete /proc dump)
## License
[](https://app.fossa.com/projects/git%2Bgithub.com%2F89luca89%2Fpakkero?ref=badge_large)
================================================
FILE: data/launcher.go
================================================
// Package main.
package main
import (
obBufio "bufio"
obBytes "bytes"
obZlib "compress/zlib"
obAES "crypto/aes"
obCipher "crypto/cipher"
obSHA "crypto/sha512"
obBase64 "encoding/base64"
obBinary "encoding/binary"
obErrors "errors"
obUtilio "io/ioutil"
obMath "math"
obOS "os"
obExec "os/exec"
obSignal "os/signal"
obStrconv "strconv"
obStrings "strings"
obSync "sync"
obSyscall "syscall"
obTime "time"
obUnsafe "unsafe"
)
type obDependency struct {
obDepSize string
obDepName string
obDepBFD []float64
}
// Stdout variable will be overwritten during compilation.
var Stdout string = "ENABLESTDOUT"
const (
obErr = 1
obCorrelationLevel = 0.4
obStdLevel = 1
obFileSizeLevel = 15
)
func obExit() {
println("https://shorturl.at/crzEZ")
obOS.Exit(obErr)
}
// Breakpoint on linux are 0xCC and will be interpreted as a
// SIGTRAP, we will intercept them.
func obSigTrap(obInput chan obOS.Signal) {
obMySignal := <-obInput
switch obMySignal {
case obSyscall.SIGILL:
obExit()
case obSyscall.SIGTRAP:
obExit()
default:
return
}
}
// attach to PTRACE, register if successful
// attach A G A I N , register if unsuccessful
// this protects against custom ptrace (always returning 0)
// against NOP attacks and LD_PRELOAD attacks.
//
// keep attached to avoid late attaching.
func obPtraceDetect(pid int, father bool) {
obOffset := 0
obProc, _ := obOS.FindProcess(pid)
obErr := obSyscall.PtraceAttach(obProc.Pid)
if obErr == nil {
obOffset = 5
}
// continuously check for ptrace on passed pid
for {
obErr = obSyscall.PtraceAttach(obProc.Pid)
if obErr != nil {
obOffset *= 3
}
obErr = obProc.Signal(obSyscall.SIGCONT)
if obErr != nil {
// we cannot send sigcont to out pid
// we should exit.
if father {
obExit()
} else {
obErr = obProc.Signal(obSyscall.SIGTRAP)
if obErr != nil {
obExit()
}
}
}
if obOffset != (3 * 5) {
if father {
obExit()
} else {
obErr = obProc.Signal(obSyscall.SIGTRAP)
if obErr != nil {
obExit()
}
}
}
obTime.Sleep(250 * obTime.Millisecond)
obOffset /= 3
}
}
// Check the process cmdline to spot if a debugger is inline.
func obParentCmdLineDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/cmdline"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
if obStrings.Contains(string(obStatParent), "gdb") ||
obStrings.Contains(string(obStatParent), "dlv") ||
obStrings.Contains(string(obStatParent), "edb") ||
obStrings.Contains(string(obStatParent), "frida") ||
obStrings.Contains(string(obStatParent), "ghidra") ||
obStrings.Contains(string(obStatParent), "godebug") ||
obStrings.Contains(string(obStatParent), "ida") ||
obStrings.Contains(string(obStatParent), "lldb") ||
obStrings.Contains(string(obStatParent), "ltrace") ||
obStrings.Contains(string(obStatParent), "strace") ||
obStrings.Contains(string(obStatParent), "valgrind") {
obExit()
}
}
// Check the process status to spot if a debugger is active using the TracePid key.
func obParentTracerDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/status"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
obStatLines := obStrings.Split(string(obStatParent), "\n")
for _, obValue := range obStatLines {
if obStrings.Contains(obValue, "TracerPid") {
obSplitArray := obStrings.Split(obValue, ":")
obSplitValue := obStrings.Replace(obSplitArray[1], "\t", "", -1)
if obSplitValue != "0" {
obExit()
}
}
}
}
// Check the process cmdline to spot if a debugger is the PPID of our process.
func obParentDetect() {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/stat"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
if obStrings.Contains(string(obStatParent), "gdb") ||
obStrings.Contains(string(obStatParent), "dlv") ||
obStrings.Contains(string(obStatParent), "edb") ||
obStrings.Contains(string(obStatParent), "frida") ||
obStrings.Contains(string(obStatParent), "ghidra") ||
obStrings.Contains(string(obStatParent), "godebug") ||
obStrings.Contains(string(obStatParent), "ida") ||
obStrings.Contains(string(obStatParent), "lldb") ||
obStrings.Contains(string(obStatParent), "ltrace") ||
obStrings.Contains(string(obStatParent), "strace") ||
obStrings.Contains(string(obStatParent), "valgrind") {
obExit()
}
}
// Check the process cmdline to spot if a debugger is launcher
// "_" and Args[0] should match otherwise.
func obEnvArgsDetect() {
obLines, _ := obOS.LookupEnv("_")
if obLines != obOS.Args[0] {
obExit()
}
}
// Check the process cmdline to spot if a debugger is inline
// "_" should not contain the name of any debugger.
func obEnvParentDetect() {
obLines, _ := obOS.LookupEnv("_")
if obStrings.Contains(obLines, "gdb") ||
obStrings.Contains(obLines, "dlv") ||
obStrings.Contains(obLines, "edb") ||
obStrings.Contains(obLines, "frida") ||
obStrings.Contains(obLines, "ghidra") ||
obStrings.Contains(obLines, "godebug") ||
obStrings.Contains(obLines, "ida") ||
obStrings.Contains(obLines, "lldb") ||
obStrings.Contains(obLines, "ltrace") ||
obStrings.Contains(obLines, "strace") ||
obStrings.Contains(obLines, "valgrind") {
obExit()
}
}
// Check the process cmdline to spot if a debugger is active
// most debuggers (like GDB) will set LINE,COLUMNS or LD_PRELOAD
// to function, we try to spot this.
func obEnvDetect() {
_, obLines := obOS.LookupEnv("LINES")
_, obColumns := obOS.LookupEnv("COLUMNS")
_, obLineLdPreload := obOS.LookupEnv("LD_PRELOAD")
if obLines || obColumns || obLineLdPreload {
obExit()
}
}
// Check the process is launcher with a LD_PRELOAD set.
// This can be an injection attack (like on frida) to try and circumvent
// various restrictions (like ptrace checks).
func obLdPreloadDetect() {
obKey := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)
obValue := obStrconv.FormatInt(obTime.Now().UnixNano(), 10)
obErr := obOS.Setenv(obKey, obValue)
if obErr != nil {
obExit()
}
obLineLdPreload, _ := obOS.LookupEnv(obKey)
if obLineLdPreload == obValue {
obErr := obOS.Unsetenv(obKey)
if obErr != nil {
obExit()
}
} else {
obExit()
}
}
// calculate BFD (byte frequency distribution) for the input dependency.
func obUtilBFDCalc(obInput string) []float64 {
obFile, _ := obUtilio.ReadFile(obInput)
obBfd := make([]float64, 256)
for _, obValue := range obFile {
obBfd[obValue]++
}
return obBfd
}
// Abs returns the absolute value of obInput.
func obUtilAbsCalc(obInput float64) float64 {
if obInput < 0 {
return -obInput
}
return obInput
}
// calculate the covariance of two input slices.
func obUtilCovarianceCalc(obDepInput []float64, obTargetInput []float64) float64 {
obMeanDepInput := 0.0
obMeanTargetInput := 0.0
for obIndex := 0; obIndex < 256; obIndex++ {
obMeanDepInput += obDepInput[obIndex]
obMeanTargetInput += obTargetInput[obIndex]
}
obMeanDepInput /= 256
obMeanTargetInput /= 256
obCovariance := 0.0
for obIndex := 0; obIndex < 256; obIndex++ {
obCovariance += (obDepInput[obIndex] - obMeanDepInput) * (obTargetInput[obIndex] - obMeanTargetInput)
}
obCovariance /= 255
return obCovariance
}
// calculate the standard deviation of the values in a slice.
func obUtilStandardDeviationCalc(obInput []float64) float64 {
obSums := 0.0
// calculate the array of rations between the values
for obIndex := 0; obIndex < 256; obIndex++ {
// increase obInstanceDep to calculate mean value of registered distribution
obSums += obInput[obIndex]
}
// calculate the mean
obMeanSums := obSums / float64(len(obInput))
obStdDev := 0.0
// calculate the standard deviation
for obIndex := 0; obIndex < 256; obIndex++ {
obStdDev += obMath.Pow(obInput[obIndex]-obMeanSums, 2)
}
obStdDev = (obMath.Sqrt(obStdDev / float64(len(obInput))))
return obStdDev
}
// calculate the standard deviation of the values of reference over
// retrieved values.
func obUtilCombinedStandardDeviationCalc(obDepBFD []float64, obTargetBFD []float64) float64 {
obDiffs := [256]float64{}
obSums := 0.0
obDepSums := 0.0
// calculate the array of rations between the values
for obIndex := 0; obIndex < 256; obIndex++ {
// add 1 to both to work aroung division by zero
obDiffs[obIndex] = obUtilAbsCalc(obDepBFD[obIndex] - obTargetBFD[obIndex])
obSums += obDiffs[obIndex]
// increase obInstanceDep to calculate mean value of registered distribution
obDepSums += obDepBFD[obIndex]
}
// calculate the mean
obDepSums /= float64(len(obDepBFD))
// calculate the mean
obMeanSums := obSums / float64(len(obDepBFD))
obStdDev := 0.0
// calculate the standard deviation
for obIndex := 0; obIndex < 256; obIndex++ {
obStdDev += obMath.Pow(obDiffs[obIndex]-obMeanSums, 2)
}
obStdDev = (obMath.Sqrt(obStdDev / float64(len(obDepBFD)))) / obDepSums
return obStdDev
}
func obDependencyCheck() {
obStrControl1 := "_DEP"
obStrControl2 := "_NAME"
obStrControl3 := "_SIZE"
obInstanceDep := obDependency{
obDepName: "DEPNAME1",
obDepSize: "DEPSIZE2",
obDepBFD: []float64{1, 2, 3, 4},
}
// control that we effectively want to control the dependencies
if (obInstanceDep.obDepName != obStrControl1[1:]+obStrControl2[1:]+"1") &&
(obInstanceDep.obDepSize != obStrControl1[1:]+obStrControl3[1:]+"2") {
// check if the file is a symbolic link
obLTargetStats, _ := obOS.Lstat(obInstanceDep.obDepName)
if (obLTargetStats.Mode() & obOS.ModeSymlink) != 0 {
obExit()
}
// open dependency in current environment and check it's size
obFile, obErr := obOS.Open(obInstanceDep.obDepName)
if obErr != nil {
obExit()
}
defer obFile.Close()
obStatsFile, _ := obFile.Stat()
obTargetDepSize, _ := obStrconv.ParseInt(obInstanceDep.obDepSize, 10, 64)
obTargetTreshold := (obTargetDepSize / 100) * obFileSizeLevel
// first check if file size is +/- 15% of registered size
if (obStatsFile.Size()-obTargetDepSize) < (-1*(obTargetTreshold)) ||
(obStatsFile.Size()-obTargetDepSize) > obTargetTreshold {
obExit()
}
// Calculate BFD (byte frequency distribution) of target file
// and calculate standard deviation from registered fingerprint.
obTargetBFD := obUtilBFDCalc(obInstanceDep.obDepName)
// Calculate covariance of the 2 dataset
obCovariance := obUtilCovarianceCalc(obInstanceDep.obDepBFD, obTargetBFD)
// calculate the correlation index of Bravais-Pearson to see if the
// two dataset are linearly correlated
obDepStdDev := obUtilStandardDeviationCalc(obInstanceDep.obDepBFD)
obTargetStdDev := obUtilStandardDeviationCalc(obTargetBFD)
obCorrelation := obCovariance / (obDepStdDev * obTargetStdDev)
if obCorrelation < obCorrelationLevel {
// not correlated, different nature
obExit()
}
obCombinedStdDev := obUtilCombinedStandardDeviationCalc(
obInstanceDep.obDepBFD,
obTargetBFD)
// standard deviation should not be greater than 1
if obCombinedStdDev > obStdLevel {
obExit()
}
}
}
// Reverse a slice of bytes.
func obReverseByteArray(obInput []byte) []byte {
obResult := []byte{}
for i := range obInput {
n := obInput[len(obInput)-1-i]
obResult = append(obResult, n)
}
return obResult
}
// Change byte endianess.
func obByteReverse(obBar byte) byte {
var obFoo byte
for obStart := 0; obStart < 8; obStart++ {
obFoo <<= 1
obFoo |= obBar & 1
obBar >>= 1
}
return obFoo
}
const (
obCloexec uint = 1
// allow seal operations to be performed.
obAllowSealing uint = 2
// memfd is now immutable.
obSealAll = 0x0001 | 0x0002 | 0x0004 | 0x0008
// amd64 specific.
obSysFCNTL = obSyscall.SYS_FCNTL
obSysMEMFDCreate = 319
)
func obGetFDPath(obPid int, obFD int, obPayload []byte) string {
// check if we are pakkering a script, if it's a script
// use specific pid path.
if string(obPayload[0:2]) == "#!" {
return "/proc/" +
obStrconv.Itoa(obPid) +
"/fd/" +
obStrconv.Itoa(obFD)
}
// else use self for elf files
return "/proc/self/fd/" + obStrconv.Itoa(obFD)
}
func obLauncher() {
// OB_CHECK
obNameFile, _ := obOS.Executable()
obFile, _ := obOS.Open(obNameFile)
defer obFile.Close()
// OB_CHECK
obOffset, _ := obStrconv.ParseInt("9999999", 10, 64)
obStatsFile, _ := obFile.Stat()
// calculate final padding
obArrayFinalPadding := make([]byte, obBinary.MaxVarintLen64)
obByteFinalPadding := obArrayFinalPadding[:obBinary.PutVarint(obArrayFinalPadding, obOffset)]
for obIndex := range obByteFinalPadding {
obByteFinalPadding[obIndex] = obByteReverse(obByteFinalPadding[obIndex])
}
obFinalPadding, _ := obBinary.Varint(obByteFinalPadding)
// make it positive!
if obFinalPadding < 0 {
obFinalPadding *= -1
}
// read the complete executable
obKey := make([]byte, obOffset)
_, obErr := obFile.Read(obKey)
if obErr != nil {
obExit()
}
// OB_CHECK
obSizeFile := obStatsFile.Size() - obOffset
// OB_CHECK
_, obErr = obFile.Seek(obOffset, 0)
if obErr != nil {
obExit()
}
obCiphertext := make([]byte, obSizeFile)
// OB_CHECK
_, obErr = obFile.Read(obCiphertext)
if obErr != nil {
obExit()
}
obCiphertext = obCiphertext[:int64(len(obCiphertext))-obFinalPadding]
// OB_CHECK
// the payload was reversed!
obCiphertext = obReverseByteArray(obCiphertext)
// OB_CHECK
// restore endianess
for obIndex := range obCiphertext {
obCiphertext[obIndex] = obByteReverse(obCiphertext[obIndex])
}
// OB_CHECK
// the aes-256 psk is the sha512_256 sum of the whole executable
// this is also useful to protect against NOP attacks to the anti-debug
// features in the binary.
// This doubles also as anti-tamper measure.
obPassword := obSHA.Sum512_256(obKey)
// OB_CHECK
obCipherBlock, _ := obAES.NewCipher(obPassword[:])
// OB_CHECK
obGCM, _ := obCipher.NewGCM(obCipherBlock)
// OB_CHECK
obSizeNonce := obGCM.NonceSize()
// OB_CHECK
// decrypt!!!
obNonce, obCiphertext := obCiphertext[:obSizeNonce], obCiphertext[obSizeNonce:]
obCompressedPlaintext, _ := obGCM.Open(nil, obNonce, obCiphertext, nil)
// OB_CHECK
// the payload was compressed!
obBufferPlaintext := obBytes.NewReader(obCompressedPlaintext)
// OB_CHECK
obZlibReader, obErr := obZlib.NewReader(obBufferPlaintext)
if obErr != nil {
obExit()
}
// OB_CHECK
obPlaintext, _ := obUtilio.ReadAll(obZlibReader)
obZlibReader.Close()
// OB_CHECK
// payload was in b64
obPayload, _ := obBase64.StdEncoding.DecodeString(string(obPlaintext))
// OB_CHECK
obFDName := ""
obFileDescriptor, _, _ := obSyscall.Syscall(obSysMEMFDCreate,
uintptr(obUnsafe.Pointer(&obFDName)),
uintptr(obCloexec|obAllowSealing), 0)
// OB_CHECK
// write payload to FD
_, obErr = obSyscall.Write(int(obFileDescriptor), obPayload)
if obErr != nil {
obExit()
}
// OB_CHECK
// make it immutable
_, _, obErr = obSyscall.Syscall(obSysFCNTL,
obFileDescriptor,
uintptr(1024+9),
uintptr(obSealAll))
if !obErrors.Is(obErr, obSyscall.Errno(0)) {
obExit()
}
// OB_CHECK
obFDPath := obGetFDPath(obOS.Getpid(), int(obFileDescriptor), obPayload)
// OB_CHECK
obCommand := obExec.Command(obFDPath)
// OB_CHECK
obCommand.Args = obOS.Args
obCommand.Stdin = obOS.Stdin
// OB_CHECK
obStdoutIn, _ := obCommand.StdoutPipe()
defer obStdoutIn.Close()
obStderrIn, _ := obCommand.StderrPipe()
defer obStderrIn.Close()
obStdout, obErr := obStrconv.ParseBool(Stdout)
if obErr != nil {
obExit()
}
if obStdout {
// OB_CHECK
// launch and remain attached
obErr = obCommand.Start()
if obErr != nil {
obExit()
}
var obWaitGroup obSync.WaitGroup
obWaitGroup.Add(2)
obStdoutScan := obBufio.NewScanner(obStdoutIn)
obStderrScan := obBufio.NewScanner(obStderrIn)
// OB_CHECK
// async fetch stdout
go func() {
defer obWaitGroup.Done()
for obStdoutScan.Scan() {
println(obStdoutScan.Text())
}
}()
// OB_CHECK
// async fetch stderr
go func() {
defer obWaitGroup.Done()
for obStderrScan.Scan() {
println(obStderrScan.Text())
}
}()
// OB_CHECK
obWaitGroup.Wait()
} else {
// launch and forget
obCommand.SysProcAttr = &obSyscall.SysProcAttr{Setpgid: true, Noctty: true}
// OB_CHECK
obErr = obCommand.Start()
if obErr != nil {
obExit()
}
obTime.Sleep(2 * obTime.Second)
}
}
// obIsForked returns wether we are a forked process of ourself, or a new spawn.
func obIsForked() bool {
obPidParent := obOS.Getppid()
obNameFile := "/proc/" + obStrconv.FormatInt(int64(obPidParent), 10) +
"/cmdline"
obStatParent, _ := obUtilio.ReadFile(obNameFile)
return obStrings.Contains(string(obStatParent), obOS.Args[0])
}
func main() {
// Prepare to intercept SIGTRAP
obChannel := make(chan obOS.Signal, 1)
obSignal.Notify(obChannel, obSyscall.SIGTRAP, obSyscall.SIGILL)
go obSigTrap(obChannel)
// OB_CHECK
obDependencyCheck()
// OB_CHECK
obEnvArgsDetect()
// OB_CHECK
obParentTracerDetect()
// OB_CHECK
obParentCmdLineDetect()
// OB_CHECK
obEnvDetect()
// OB_CHECK
obEnvParentDetect()
// OB_CHECK
obLdPreloadDetect()
// OB_CHECK
obParentDetect()
// check if we are a forked process, if not, fork
// and ptrace ourself, else exit gracefully and continue
// with normal execution.
//
// this workaround is because go does not support traditional fork()
// and calling ptrace in the main thread of execution will neuter
// any possibility of calling "exec" afterwards.
if obIsForked() {
// we are a child process, let's ptrace
obPtraceDetect(obOS.Getppid(), false)
} else {
// simulate for self, launch ourself in another
// process to ptrace ourself
obCommand := obExec.Command(obOS.Args[0], obOS.Args[1:]...)
obErr := obCommand.Start()
if obErr != nil {
println(obErr.Error())
obExit()
}
go obPtraceDetect(obCommand.Process.Pid, true)
// Ok we are set to go! Let's execute the payload
// OB_CHECK
obLauncher()
}
}
================================================
FILE: go.mod
================================================
module github.com/89luca89/pakkero
go 1.16
require github.com/alegrey91/go-upx v0.2.0 // indirect
================================================
FILE: go.sum
================================================
github.com/alegrey91/go-upx v0.2.0 h1:EFhbmAbFET2mqHRLunHFOVo3+mxdnR2/EQMfv0OOR0k=
github.com/alegrey91/go-upx v0.2.0/go.mod h1:qrYpv/uZT6Qs1mrNz3wxrL/u7kbbTWkbVJnHyzsiJmU=
================================================
FILE: internal/pakkero/encryption.go
================================================
/*
Package pakkero will pack, compress and encrypt any type of executable.
Encryption library
*/
package pakkero
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha512"
"fmt"
"io"
"io/ioutil"
)
/*
EncryptAESReversed Wrapper around AESGCM encryption
this will not only encrypt the payload but:
- generate a password using the randomized UPX Binary's sha512_256 sum
- cipher the payload with AESGCM using the generated password
- swap endianess on all the encrypted bytes
- reverse the complete payload.
*/
func EncryptAESReversed(plaintext []byte, outfile string) (string, error) {
// generate a password using the randomized UPX Binary's sha512_256 sum
/*
the aes-256 psk is the sha512_256 sum of the whole executable
this is also useful to protect against NOP attacks to the anti-debug
features in the binary.
This doubles also as anti-tamper measure.
*/
b, err := ioutil.ReadFile(outfile)
if err != nil {
return "", fmt.Errorf("failed to read input file: %w", err)
}
// use SHA512 (32byte) of the passphrase as key
key := sha512.Sum512_256(b)
// generate new cipher
c, err := aes.NewCipher(key[:])
if err != nil {
println(err)
}
gcm, err := cipher.NewGCM(c)
if err != nil {
println(err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
println(err)
}
// cipher the payload with AESGCM using the generated password
bCiphertext := gcm.Seal(nonce, nonce, plaintext, nil)
// swap endianess on all the encrypted bytes
for i := range bCiphertext {
bCiphertext[i] = ReverseByte(bCiphertext[i])
}
ciphertext := string(bCiphertext)
// reverse the complete payload
ciphertext = string(ReverseByteArray([]byte(ciphertext)))
return ciphertext, nil
}
================================================
FILE: internal/pakkero/obfuscation.go
================================================
/*
Package pakkero will pack, compress and encrypt any type of executable.
Obfuscation library
*/
package pakkero
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io/ioutil"
"regexp"
"strings"
)
// Secrets are the group of strings that we want to obfuscate.
var Secrets = map[string][]string{}
// LauncherStub Stub of the Launcher.go, put here during compilation time.
var LauncherStub = "unset"
var extras = []string{
// ELF Headers
".gopclntab",
".go.buildinfo",
".noptrdata",
".noptrbss",
".data",
".rodata",
".text",
".itablink",
".shstrtab",
".data",
".dynamic",
".dynstr",
".dynsym",
".gnu.version_r",
".gopclntab",
".got.plt",
".init_array",
".interp",
".itablink",
".rela.dyn",
".rela.plt",
".tbss",
".plt",
".init",
// internal golang
"name", "runtime", "command", "cmd",
"ptr", "process", "unicode", "main",
"path", "get", "reflect", "context",
"debug", "fmt", "sync", "sort",
"size", "heap", "fatal", "call",
"fixed", "slice", "bit", "file",
"read", "write", "buffer", "encrypt",
"decrypt", "hash", "state",
"external", "internal", "float",
// anti debug traces
"env", "trace", "pid",
}
/*
StripUPXHeaders will ensure no trace of UPX headers are left
so that reversing will be more challenging and break
simple attempts like "upx -d" in case of compression.
*/
func StripUPXHeaders(infile string) bool {
// Bit sequence of UPX copyright and header infos
header := []string{
`\x49\x6e\x66\x6f\x3a\x20\x54\x68\x69\x73`,
`\x20\x66\x69\x6c\x65\x20\x69\x73\x20\x70`,
`\x61\x63\x6b\x65\x64\x20\x77\x69\x74\x68`,
`\x20\x74\x68\x65\x20\x55\x50\x58\x20\x65`,
`\x78\x65\x63\x75\x74\x61\x62\x6c\x65\x20`,
`\x70\x61\x63\x6b\x65\x72\x20\x68\x74\x74`,
`\x70\x3a\x2f\x2f\x75\x70\x78\x2e\x73\x66`,
`\x2e\x6e\x65\x74\x20\x24\x0a\x00\x24\x49`,
`\x64\x3a\x20\x55\x50\x58\x20\x33\x2e\x39`,
`\x36\x20\x43\x6f\x70\x79\x72\x69\x67\x68`,
`\x74\x20\x28\x43\x29\x20\x31\x39\x39\x36`,
`\x2d\x32\x30\x32\x30\x20\x74\x68\x65\x20`,
`\x55\x50\x58\x20\x54\x65\x61\x6d\x2e\x20`,
`\x41\x6c\x6c\x20\x52\x69\x67\x68\x74\x73`,
`\x20\x52\x65\x73\x65\x72\x76\x65\x64\x2e`,
`\x55\x50\x58\x21`,
}
result := true
for _, v := range header {
sedString := ""
// generate random byte sequence
replace := make([]byte, 1)
for len(sedString) < len(v) {
_, err := rand.Read(replace)
if err != nil {
return false
}
sedString += `\x` + hex.EncodeToString(replace)
}
// replace UPX sequence with random garbage
result = ExecCommand("sed", []string{"-i", `s/` + v + `/` + sedString + `/g`, infile})
if !result {
return result
}
}
return result
}
/*
StripFile will strip out all unneeded headers from and ELF
file in input.
*/
func StripFile(infile string, launcherFile string) bool {
// strip symbols and headers
if !ExecCommand("strip",
[]string{
"-sxX",
"--remove-section=.bss",
"--remove-section=.comment",
"--remove-section=.eh_frame",
"--remove-section=.eh_frame_hdr",
"--remove-section=.fini",
"--remove-section=.fini_array",
"--remove-section=.gnu.build.attributes",
"--remove-section=.gnu.hash",
"--remove-section=.gnu.version",
"--remove-section=.gosymtab",
"--remove-section=.got",
"--remove-section=.note.ABI-tag",
"--remove-section=.note.gnu.build-id",
"--remove-section=.shstrtab",
"--remove-section=.typelink",
infile,
}) {
return false
}
// ------------------------------------------------------------------------
// proceede with manual
// stripping of golang builtins and keyWords strings
removeStrings := []string{}
removeStrings = append(removeStrings, extras...)
// anonymize the launcherFile string to hide the original launcher file name
removeStrings = append(removeStrings, launcherFile)
// deduplicate
removeStrings = Unique(removeStrings)
// read file to string
byteContent, err := ioutil.ReadFile(infile)
if err != nil {
return false
}
input := string(byteContent)
for _, remove := range removeStrings {
// generate new random string to place instead
newName := GenerateNullString(len(remove))
input = strings.ReplaceAll(input, remove, newName)
input = strings.ReplaceAll(input, strings.Title(remove), newName)
}
// save.
err = ioutil.WriteFile(infile, []byte(input), 0600)
// ------------------------------------------------------------------------
return err == nil
}
/*
GenerateTyposquatName is a typosquat name generator
based on a length (128 default) this will create a random
uniqe string composed only of letters and zeroes that are lookalike.
*/
func GenerateTyposquatName(length int) string {
// We divide between an alphabet with number
// and one without, because function/variable names
// must not start with a number.
letterRunes := []rune("OÓÕÔÒÖŌŎŐƠΘΟ")
mixedRunes := []rune("0OÓÕÔÒÖŌŎŐƠΘΟ")
b := make([]rune, length)
// ensure we do not start with a number or we will break code.
b[0] = letterRunes[Random(0, int64(len(mixedRunes)-1))]
for i := range b {
if i != 0 {
b[i] = mixedRunes[Random(0, int64(len(mixedRunes)-1))]
}
}
return string(b)
}
/*
ObfuscateFuncVars will:
- extract all obfuscation-enabled func and var names:
- those start with "ob*" and will be listed
- for each matching string generate a typosquatted random string and
replace all string with that
*/
func ObfuscateFuncVars(input string) string {
// obfuscate functions and variables names
regex := regexp.MustCompile(`\bob[a-zA-Z0-9_]+`)
words := regex.FindAllString(input, -1)
words = ReverseStringArray(words)
words = Unique(words)
for _, w := range words {
// generate random name for each matching string
input = strings.ReplaceAll(input, w, GenerateTyposquatName(128))
}
return input
}
/*
GenerateStringFunc will hide a string creating a function that returns
that value as a string encoded with a series of length calculation of randomic
string arrays generated.
*/
func GenerateStringFunc(txt string, function string) string {
resString := "{"
for _, b := range []byte(txt) {
resString += "\"" + GenerateTyposquatName(int(b)) + "\"" + ","
}
// remove last comma
resString = strings.TrimSuffix(resString, ",")
// close array
resString += "}"
result := fmt.Sprintf("func " +
function +
"() string {\nobRegistered := []string" + resString +
"\nvar obResult []byte\nfor _,obValue := range obRegistered " +
"{\nobResult = append(obResult, byte(len([]rune(obValue))))\n}\nreturn string(obResult)\n}")
return result
}
/*
ObfuscateStrings will extract all plaintext strings denotet with
backticks and obfuscate them using byteshift wise operations.
*/
func ObfuscateStrings(input string) string {
// parse the launcher file to create the list of imports in it
imports := strings.Index(input, "import (")
endimports := strings.Index(input[imports:], ")")
// import section
importSection := input[:imports+endimports+1]
// the rest of the program
body := input[imports+endimports+1:]
// various types of string delimiter
tickTypes := []string{"`", `'`, `"`}
// for each ticktype, try to get all the strings and
// obfuscate them using functions
for _, v := range tickTypes {
regex := regexp.MustCompile(v + ".*?" + v)
words := regex.FindAllString(body, -1)
words = Unique(words)
for _, w := range words {
// string not void, accounting for quotes
if len(w) > 2 && !strings.Contains(w, `\`) {
// add string to the secrets! if not present
_, present := Secrets[w]
if !present {
secret := w[1 : len(w)-1]
Secrets[w] = []string{secret, GenerateTyposquatName(128)}
}
}
}
}
// create function call
funcString := ""
// replace all secrects with the respective obfuscated string
for k, w := range Secrets {
// in case we manually added some secrets that we want to leave
if !strings.Contains(w[1], "leave") {
funcString = funcString + GenerateStringFunc(w[0], w[1]) + "\n"
body = strings.ReplaceAll(body, k, w[1]+"()")
} else {
body = strings.ReplaceAll(body, k, w[0])
}
}
// reconstruct the program correctly and
// insert all the functions before the main
body = body + "\n" + funcString
// join back with the import section
return importSection + body
}
/*
GenerateRandomAntiDebug will Insert random order of anti-debug check
together with inline compilation to induce big number
of instructions in random order.
*/
func GenerateRandomAntiDebug(input string) string {
lines := strings.Split(input, "\n")
randomChecks := []string{
`obDependencyCheck()`,
`obEnvArgsDetect()`,
`obParentTracerDetect()`,
`obParentCmdLineDetect()`,
`obEnvDetect()`,
`obEnvParentDetect() `,
`obLdPreloadDetect()`,
`obParentDetect()`,
}
var obfile []string
// find OB_CHECK and put the checks there.
for _, v := range lines {
if strings.Contains(v, "//") {
if strings.Contains(v, "// OB_CHECK") {
threadString := ""
checkString := ""
// randomize order of check to replace
for j, v := range ShuffleSlice(randomChecks) {
threadString = threadString + "go " + v + ";"
checkString += v
if j != (len(randomChecks) - 1) {
checkString += `||`
}
}
// add action in case of failed check
obfile = append(obfile, threadString)
continue
} else {
// remove comment, this is more to scramble the line numbers
// and make error reporting less accurate
continue
}
}
obfile = append(obfile, v)
}
// back to single string
return strings.Join(obfile, "\n")
}
/*
ObfuscateLauncher the go code of the runner before compiling it.
Basic techniques are applied:
- GenerateRandomAntiDebug
- ObfuscateStrings
- ObfuscateFuncVars.
*/
func ObfuscateLauncher(infile string) error {
byteContent, err := ioutil.ReadFile(infile)
if err != nil {
return fmt.Errorf("failed to read input file: %w", err)
}
content := string(byteContent)
// ------------------------------------------------------------------------
// --- Start anti-debug checks
content = GenerateRandomAntiDebug(content)
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// --- Start string obfuscation
content = ObfuscateStrings(content)
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// --- Start function name obfuscation
content = ObfuscateFuncVars(content)
// ------------------------------------------------------------------------
// save.
err = ioutil.WriteFile(infile, []byte(content), 0600)
if err != nil {
return fmt.Errorf("failed to save output file: %w", err)
}
return nil
}
================================================
FILE: internal/pakkero/pakkero.go
================================================
/*
Package pakkero will pack, compress and encrypt any type of executable.
*/
package pakkero
import (
"encoding/base64"
"encoding/binary"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strconv"
"syscall"
"github.com/alegrey91/go-upx"
)
const (
offsetPlaceholder = `"9999999"`
stdoutEnabledPlaceholder = `"ENABLESTDOUT"`
depNamePlaceholder = `"DEPNAME1"`
depSizePlaceholder = `"DEPSIZE2"`
depBFDPlaceholder = "[]float64{1, 2, 3, 4}"
)
var launcherFile = os.TempDir() + "/launcher.go"
func cleanup() {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
fmt.Print(" → Cleaning up...")
// remove unused file
ExecCommand("rm", []string{"-f", launcherFile})
fmt.Printf(SuccessColor, "\t\t\t[ OK ]\n")
}
func trap() {
// Prepare to intercept SIGTERM
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
cleanup()
os.Exit(ERR)
}()
}
// Pakkero will Encrypt and pack the payload for a secure execution.
func Pakkero(infile string, offset int64, outfile string, dependency string, compress bool, stdout bool) {
trap()
fmt.Print(" → Randomizing offset...")
// declare outfile as original filename + .enc
if len(outfile) == 0 {
outfile = infile + ".enc"
}
// ------------------------------------------------------------------------
// offset Hysteresis, this will prevent easy key retrieving
offset += Random(128, 4094)
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Register Dependency to try and bypass any tampering on dependent
// packages
fmt.Print(" → Registering Dependencies...")
Secrets[stdoutEnabledPlaceholder] = []string{"\"unset\"", "leaveunset"}
// ------------------------------------------------------------------------
// Register eventual dependency passed by cli
// If a dependency check is present, register it.
if dependency != "" {
RegisterDependency(dependency)
} else {
// in case of missing dependency add an empty variable for BFD
Secrets[depBFDPlaceholder] = []string{"[]float64{}", "leaveBFD"}
}
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Create the launcher program starting from our stub
fmt.Print(" → Creating Launcher Stub...")
// add offset to the secrets!
Secrets[offsetPlaceholder] = []string{
fmt.Sprintf("%d", offset),
GenerateTyposquatName(128),
}
// copy the stub from where to start.
launcherStub, _ := base64.StdEncoding.DecodeString(LauncherStub)
err := ioutil.WriteFile(launcherFile, launcherStub, 0600)
if err != nil {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println(fmt.Sprintf("failed writing to file: %s", err))
cleanup()
os.Exit(ERR)
}
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Obfuscate the launcher
fmt.Print(" → Obfuscating Launcher Stub...")
err = ObfuscateLauncher(launcherFile)
if err != nil {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println(fmt.Sprintf("failed obfuscating file file: %s", err))
cleanup()
os.Exit(ERR)
}
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// compile the launcher binary
fmt.Print(" → Compiling Launcher...")
var flags []string
os.Setenv("CGO_ENABLED", "0")
flags = []string{
"build", "-a",
"-trimpath",
"-gcflags",
"-N -l -nolocalimports",
"-ldflags=" +
"-X main.Stdout=" + strconv.FormatBool(stdout) +
" -s -w -extldflags -static\"",
}
flags = append(flags, "-o")
flags = append(flags, outfile)
flags = append(flags, launcherFile)
if ExecCommand("go", flags) {
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
} else {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
ExecCommand("rm", []string{"-f", outfile})
cleanup()
os.Exit(ERR)
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Strip File of excess headers
fmt.Print(" → Stripping Launcher...")
if StripFile(outfile, launcherFile) {
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
} else {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
ExecCommand("rm", []string{"-f", outfile})
cleanup()
os.Exit(ERR)
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Compress File of occupy less space
// Then remove UPX headers from file.
fmt.Print(" → Compressing Launcher...")
if compress {
options := goupx.Options{
Output: "",
Force: false,
Verbose: false,
}
upx := goupx.NewUPX()
compression, err := upx.Compress(outfile, 8, options)
if err != nil {
fmt.Println(err)
}
if compression &&
StripUPXHeaders(outfile) {
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
} else {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
ExecCommand("rm", []string{"-f", outfile})
cleanup()
os.Exit(ERR)
}
} else {
fmt.Printf(WarningColor, "\t\t[ SKIPPING ]\n")
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Remove unused file
fmt.Print(" → Cleaning up...")
if ExecCommand("rm", []string{"-f", launcherFile}) {
fmt.Printf(SuccessColor, "\t\t\t[ OK ]\n")
} else {
fmt.Printf(ErrorColor, "\t\t\t[ ERR ]\n")
ExecCommand("rm", []string{"-f", outfile})
os.Exit(ERR)
}
// ------------------------------------------------------------------------
// read compiled file
encFile, err := os.OpenFile(outfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println(fmt.Sprintf("failed writing to file: %s", err))
os.Exit(ERR)
}
defer encFile.Close()
encFileStat, _ := encFile.Stat()
encFileSize := encFileStat.Size()
// ------------------------------------------------------------------------
// Input validation
fmt.Print(" → Verifying input offset...")
// Ensure input offset is valid comared to compiled file size!
if offset <= encFileSize {
ExecCommand("rm", []string{"-f", outfile})
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println("ERROR! Calculated offset is lower than launcher size: " +
fmt.Sprintf("offset=%d, filesize=%d", offset, encFileSize))
os.Exit(ERR)
}
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Pre-Payload Garbage
// calculate where to put garbage and where to put the payload
fmt.Print(" → Adding garbage...")
blockCount := offset - encFileSize
// append randomness to the runner itself
_, err = encFile.WriteString(GenerateRandomGarbage(blockCount))
if err != nil {
fmt.Printf(ErrorColor, "\t\t\t[ ERR ]\n")
println(fmt.Sprintf("failed writing to file: %s", err))
os.Exit(ERR)
}
fmt.Printf(SuccessColor, "\t\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Encryption and compression of the payload
// get file to encrypt argument
fmt.Print(" → Reading payload...")
byteContent, err := ioutil.ReadFile(infile) // just pass the file name
if err != nil {
fmt.Printf(ErrorColor, "\t\t\t[ ERR ]\n")
println(fmt.Sprintf("failed reading file: %s", err))
os.Exit(ERR)
}
content := string(byteContent)
// plaintext content
plaintext := []byte(base64.StdEncoding.EncodeToString([]byte(content)))
fmt.Printf(SuccessColor, "\t\t\t[ OK ]\n")
// ------------------------------------------------------------------------
fmt.Print(" → Compressing payload...")
// GZIP before encrypt
plaintext = GzipContent(plaintext)
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
fmt.Print(" → Encrypting payload...")
// encrypt aes256-gcm
ciphertext, err := EncryptAESReversed(plaintext, outfile)
if err != nil {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println(fmt.Sprintf("failed encrypting file: %s", err))
os.Exit(ERR)
}
// append payload to the runner itself
_, err = encFile.WriteString(ciphertext)
if err != nil {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println(fmt.Sprintf("failed writing to file: %s", err))
os.Exit(ERR)
}
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Post-Payload Garbage
// calculate final padding
fmt.Print(" → Adding garbage to payload...")
finalPaddingArray := make([]byte, binary.MaxVarintLen64)
n := binary.PutVarint(finalPaddingArray, offset)
finalPaddingB := finalPaddingArray[:n]
// change endianess to every byte composing
// the offset
for i := range finalPaddingB {
finalPaddingB[i] = ReverseByte(finalPaddingB[i])
}
finalPadding, _ := binary.Varint(finalPaddingB)
// and ensure it is positive!
if finalPadding < 0 {
finalPadding *= -1
}
// append random garbage equal to bit-reverse of the offset
// at the end of the payload
_, err = encFile.WriteString(GenerateRandomGarbage(finalPadding))
if err != nil {
fmt.Printf(ErrorColor, "\t\t[ ERR ]\n")
println(fmt.Sprintf("failed writing to file: %s", err))
os.Exit(ERR)
}
// ------------------------------------------------------------------------
fmt.Printf(SuccessColor, "\t\t[ OK ]\n")
}
================================================
FILE: internal/pakkero/utilities.go
================================================
/*
Package pakkero will pack, compress and encrypt any type of executable.
Utilities library
*/
package pakkero
import (
"bytes"
"compress/zlib"
"crypto/rand"
"fmt"
"io/ioutil"
"math/big"
"os"
"os/exec"
)
// Colors for strings.
const (
SuccessColor = "\033[1;32m%s\033[0m"
WarningColor = "\033[1;33m%s\033[0m"
ErrorColor = "\033[1;31m%s\033[0m"
)
// ERR Is the exit Code 1.
const ERR = 1
// OK Is the exit Code 0.
const OK = 0
/*
RandomInt64 will return a random number in a range.
*/
func RandomInt64(max int64) int64 {
bg := big.NewInt(max)
n, err := rand.Int(rand.Reader, bg)
if err != nil {
panic(err)
}
return n.Int64()
}
/*
Random will return a random number in a range.
*/
func Random(min, max int64) int64 {
bg := big.NewInt(max - min)
n, err := rand.Int(rand.Reader, bg)
if err != nil {
panic(err)
}
// add n to min to support the passed in range
return n.Int64() + min
}
/*
Unique will deduplicate a given slice.
*/
func Unique(slice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range slice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
/*
ReverseByteArray will reverse a slice of bytes.
*/
func ReverseByteArray(input []byte) []byte {
reversed := []byte{}
for i := range input {
n := input[len(input)-1-i]
reversed = append(reversed, n)
}
return reversed
}
/*
ReverseByte will change a byte endianess.
*/
func ReverseByte(b byte) byte {
var d byte
for i := 0; i < 8; i++ {
d <<= 1
d |= b & 1
b >>= 1
}
return d
}
/*
ReverseStringArray reverse a slice of strings.
*/
func ReverseStringArray(ss []string) []string {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
return ss
}
/*
ReverseString reverse a string.
*/
func ReverseString(input string) string {
var result string
for _, value := range input {
result = string(value) + result
}
return result
}
/*
ShuffleSlice will shuffle a slice.
*/
func ShuffleSlice(in []string) []string {
for i := len(in) - 1; i > 0; i-- {
j := RandomInt64(int64(i) + 1)
in[i], in[j] = in[j], in[i]
}
return in
}
/*
ExecCommand is a wrapper arount exec.Command to execute a command
and ensure it's result is not err.
*/
func ExecCommand(name string, args []string) bool {
cmd := exec.Command(name, args...)
errString, err := cmd.CombinedOutput()
if err != nil {
println(fmt.Sprintf("failed to execute command %s: %s", cmd, err))
println(string(errString))
return false
}
return true
}
/*
GenerateRandomGarbage creates random garbage to rise entropy.
*/
func GenerateRandomGarbage(size int64) string {
randomGarbage := make([]byte, size)
_, err := rand.Read(randomGarbage)
if err != nil {
panic(err)
}
return string(randomGarbage)
}
/*
GzipContent an input byte slice and return it compressed.
*/
func GzipContent(input []byte) []byte {
// GZIP before encrypt
var zlibPlaintext bytes.Buffer
zlibWriter := zlib.NewWriter(&zlibPlaintext)
_, err := zlibWriter.Write(input)
zlibWriter.Close()
if err != nil {
panic(err)
}
return zlibPlaintext.Bytes()
}
/*
GenerateNullString will return a string with only void chars.
*/
func GenerateNullString(n int) string {
result := ""
for len(result) < n {
result += string(0)
}
return result
}
/*
RegisterDependency will take a file in input and register the
Byte Frequency Distribution (BFD) and some other data to let the launcher
do statystical analysis of the found files.
*/
func RegisterDependency(dependency string) {
dependencyFile, _ := os.Open(dependency)
defer dependencyFile.Close()
dependencyStats, _ := dependencyFile.Stat()
depenencyLinkStats, _ := os.Lstat(dependency)
if (depenencyLinkStats.Mode() & os.ModeSymlink) != 0 {
cleanup()
fmt.Printf("Invalid path: %s is a symlink, use absolute paths.\n", dependency)
os.Exit(1)
}
// calculate BFD (byte frequency distribution) for the input dependency
bytes, _ := ioutil.ReadFile(dependency)
bfd := make([]float64, 256)
for _, b := range bytes {
bfd[b]++
}
// make a string out of it
bfdString := "[]float64{"
for _, v := range bfd {
bfdString += fmt.Sprintf("%f", v) + ","
}
bfdString += "}"
// add Dependency data to the secrets
// register BFD
Secrets[depBFDPlaceholder] = []string{bfdString, "leaveBFD"}
// register name
Secrets[depNamePlaceholder] = []string{dependency, GenerateTyposquatName(128)}
// register size
Secrets[depSizePlaceholder] = []string{
fmt.Sprintf("%d", dependencyStats.Size()), GenerateTyposquatName(128),
}
}
================================================
FILE: main.go
================================================
/*
Package main, calls all the libraries needed and handles cli flags.
*/
package main
import (
"flag"
"os"
"github.com/89luca89/pakkero/internal/pakkero"
)
const (
programName = "pakkero"
version = "0.7.0"
minArgsLen = 2
)
const (
minOffsetCompressed = 750000
maxOffsetCompressed = 800000
minOffset = 1910000
maxOffset = 2100000
)
var (
dependencies = []string{"ls", "sed", "go", "strip"}
dependenciesComplete = []string{"upx", "ls", "sed", "go", "strip"}
)
/*
TestDependencies if all dependencies are present
in the system.
*/
func testDependencies(deps []string) {
for _, v := range deps {
if !pakkero.ExecCommand("which", []string{v}) {
println("Missing Dependency: " + v)
os.Exit(pakkero.ERR)
}
}
}
/*
Print version.
*/
func printVersion() {
println(programName + " v" + version)
os.Exit(pakkero.OK)
}
/*
Print Help.
*/
func help() {
println("Usage: " +
programName +
" -file /path/to/file -offset OFFSET (-o /path/to/output) (-c) (-register-dep /path/to/file)")
println(" -file <file> Target file to Pack")
println(" -o <file> place the output into <file> (default is <inputfile>.enc, optional)")
println(" -offset <offset> Offset where to start the payload (Number of Bytes, optional)")
println(" -register-dep <file-dependency> Target file to analyze and use as fingerprint (absolute path, optional)")
println(" -c compress the output to occupy less space (uses UPX, optional)")
println(" -enable-stdout Whether to wait and handle the process stdout/sterr or not (false by default, optional)")
println(" -v Check " + programName + " version")
}
func main() {
if len(os.Args) < minArgsLen {
help()
os.Exit(pakkero.ERR)
}
flag.Usage = func() {
help()
}
file := flag.String("file", "", "")
dependency := flag.String("register-dep", "", "")
output := flag.String("o", "", "")
offset := flag.Int64("offset", 0, "")
compress := flag.Bool("c", false, "")
stdout := flag.Bool("enable-stdout", false, "")
flag.Bool("v", false, "")
flag.Parse()
switch os.Args[1] {
case "-v":
printVersion()
default:
// fist test if all dependencies are present
if *compress {
// compression needs additional upx dependency
testDependencies(dependenciesComplete)
} else {
testDependencies(dependencies)
}
// set a default offset if not specified
if *offset == 0 {
if *compress {
*offset = pakkero.Random(minOffsetCompressed, maxOffsetCompressed)
} else {
*offset = pakkero.Random(minOffset, maxOffset)
}
}
if *file != "" {
pakkero.Pakkero(*file, *offset, *output, *dependency, *compress, *stdout)
} else {
println("Missing arguments or invalid arguments!")
help()
os.Exit(pakkero.ERR)
}
}
}
gitextract_h2o9k04m/ ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── data/ │ └── launcher.go ├── go.mod ├── go.sum ├── internal/ │ └── pakkero/ │ ├── encryption.go │ ├── obfuscation.go │ ├── pakkero.go │ └── utilities.go └── main.go
SYMBOL INDEX (78 symbols across 6 files)
FILE: data/launcher.go
type obDependency (line 27) | type obDependency struct
constant obErr (line 37) | obErr = 1
constant obCorrelationLevel (line 38) | obCorrelationLevel = 0.4
constant obStdLevel (line 39) | obStdLevel = 1
constant obFileSizeLevel (line 40) | obFileSizeLevel = 15
function obExit (line 43) | func obExit() {
function obSigTrap (line 50) | func obSigTrap(obInput chan obOS.Signal) {
function obPtraceDetect (line 68) | func obPtraceDetect(pid int, father bool) {
function obParentCmdLineDetect (line 117) | func obParentCmdLineDetect() {
function obParentTracerDetect (line 140) | func obParentTracerDetect() {
function obParentDetect (line 161) | func obParentDetect() {
function obEnvArgsDetect (line 185) | func obEnvArgsDetect() {
function obEnvParentDetect (line 194) | func obEnvParentDetect() {
function obEnvDetect (line 214) | func obEnvDetect() {
function obLdPreloadDetect (line 227) | func obLdPreloadDetect() {
function obUtilBFDCalc (line 248) | func obUtilBFDCalc(obInput string) []float64 {
function obUtilAbsCalc (line 260) | func obUtilAbsCalc(obInput float64) float64 {
function obUtilCovarianceCalc (line 269) | func obUtilCovarianceCalc(obDepInput []float64, obTargetInput []float64)...
function obUtilStandardDeviationCalc (line 292) | func obUtilStandardDeviationCalc(obInput []float64) float64 {
function obUtilCombinedStandardDeviationCalc (line 314) | func obUtilCombinedStandardDeviationCalc(obDepBFD []float64, obTargetBFD...
function obDependencyCheck (line 342) | func obDependencyCheck() {
function obReverseByteArray (line 404) | func obReverseByteArray(obInput []byte) []byte {
function obByteReverse (line 416) | func obByteReverse(obBar byte) byte {
constant obCloexec (line 429) | obCloexec uint = 1
constant obAllowSealing (line 431) | obAllowSealing uint = 2
constant obSealAll (line 433) | obSealAll = 0x0001 | 0x0002 | 0x0004 | 0x0008
constant obSysFCNTL (line 435) | obSysFCNTL = obSyscall.SYS_FCNTL
constant obSysMEMFDCreate (line 436) | obSysMEMFDCreate = 319
function obGetFDPath (line 439) | func obGetFDPath(obPid int, obFD int, obPayload []byte) string {
function obLauncher (line 452) | func obLauncher() {
function obIsForked (line 640) | func obIsForked() bool {
function main (line 649) | func main() {
FILE: internal/pakkero/encryption.go
function EncryptAESReversed (line 26) | func EncryptAESReversed(plaintext []byte, outfile string) (string, error) {
FILE: internal/pakkero/obfuscation.go
function StripUPXHeaders (line 67) | func StripUPXHeaders(infile string) bool {
function StripFile (line 116) | func StripFile(infile string, launcherFile string) bool {
function GenerateTyposquatName (line 178) | func GenerateTyposquatName(length int) string {
function ObfuscateFuncVars (line 203) | func ObfuscateFuncVars(input string) string {
function GenerateStringFunc (line 223) | func GenerateStringFunc(txt string, function string) string {
function ObfuscateStrings (line 245) | func ObfuscateStrings(input string) string {
function GenerateRandomAntiDebug (line 304) | func GenerateRandomAntiDebug(input string) string {
function ObfuscateLauncher (line 358) | func ObfuscateLauncher(infile string) error {
FILE: internal/pakkero/pakkero.go
constant offsetPlaceholder (line 20) | offsetPlaceholder = `"9999999"`
constant stdoutEnabledPlaceholder (line 21) | stdoutEnabledPlaceholder = `"ENABLESTDOUT"`
constant depNamePlaceholder (line 22) | depNamePlaceholder = `"DEPNAME1"`
constant depSizePlaceholder (line 23) | depSizePlaceholder = `"DEPSIZE2"`
constant depBFDPlaceholder (line 24) | depBFDPlaceholder = "[]float64{1, 2, 3, 4}"
function cleanup (line 29) | func cleanup() {
function trap (line 38) | func trap() {
function Pakkero (line 51) | func Pakkero(infile string, offset int64, outfile string, dependency str...
FILE: internal/pakkero/utilities.go
constant SuccessColor (line 20) | SuccessColor = "\033[1;32m%s\033[0m"
constant WarningColor (line 21) | WarningColor = "\033[1;33m%s\033[0m"
constant ErrorColor (line 22) | ErrorColor = "\033[1;31m%s\033[0m"
constant ERR (line 26) | ERR = 1
constant OK (line 29) | OK = 0
function RandomInt64 (line 34) | func RandomInt64(max int64) int64 {
function Random (line 48) | func Random(min, max int64) int64 {
function Unique (line 62) | func Unique(slice []string) []string {
function ReverseByteArray (line 80) | func ReverseByteArray(input []byte) []byte {
function ReverseByte (line 95) | func ReverseByte(b byte) byte {
function ReverseStringArray (line 110) | func ReverseStringArray(ss []string) []string {
function ReverseString (line 123) | func ReverseString(input string) string {
function ShuffleSlice (line 136) | func ShuffleSlice(in []string) []string {
function ExecCommand (line 149) | func ExecCommand(name string, args []string) bool {
function GenerateRandomGarbage (line 166) | func GenerateRandomGarbage(size int64) string {
function GzipContent (line 180) | func GzipContent(input []byte) []byte {
function GenerateNullString (line 198) | func GenerateNullString(n int) string {
function RegisterDependency (line 213) | func RegisterDependency(dependency string) {
FILE: main.go
constant programName (line 14) | programName = "pakkero"
constant version (line 15) | version = "0.7.0"
constant minArgsLen (line 16) | minArgsLen = 2
constant minOffsetCompressed (line 20) | minOffsetCompressed = 750000
constant maxOffsetCompressed (line 21) | maxOffsetCompressed = 800000
constant minOffset (line 22) | minOffset = 1910000
constant maxOffset (line 23) | maxOffset = 2100000
function testDependencies (line 35) | func testDependencies(deps []string) {
function printVersion (line 47) | func printVersion() {
function help (line 55) | func help() {
function main (line 68) | func main() {
Condensed preview — 13 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (133K chars).
[
{
"path": ".gitignore",
"chars": 35,
"preview": "PackNGo\ntest\ndist\n__*\ntags\nTODO.md\n"
},
{
"path": "Dockerfile",
"chars": 342,
"preview": "FROM golang:alpine\n\nENV CGO_ENABLED=0\nENV GO111MODULE=off\n\nRUN apk add --update-cache upx git make binutils coreutils \\\n"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "Makefile",
"chars": 1884,
"preview": "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-"
},
{
"path": "README.md",
"chars": 35495,
"preview": "# Pakkero\n\n<img src=\"pics/logo.jpg\" data-canonical-src=\"pics/logo.jpg\" width=\"250\" height=\"250\" />\n\nCredit: [alegrey91]("
},
{
"path": "data/launcher.go",
"chars": 17943,
"preview": "// Package main.\npackage main\n\nimport (\n\tobBufio \"bufio\"\n\tobBytes \"bytes\"\n\tobZlib \"compress/zlib\"\n\tobAES \"crypto/aes\"\n\to"
},
{
"path": "go.mod",
"chars": 100,
"preview": "module github.com/89luca89/pakkero\n\ngo 1.16\n\nrequire github.com/alegrey91/go-upx v0.2.0 // indirect\n"
},
{
"path": "go.sum",
"chars": 173,
"preview": "github.com/alegrey91/go-upx v0.2.0 h1:EFhbmAbFET2mqHRLunHFOVo3+mxdnR2/EQMfv0OOR0k=\ngithub.com/alegrey91/go-upx v0.2.0/go"
},
{
"path": "internal/pakkero/encryption.go",
"chars": 1795,
"preview": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\nEncryption library\n*/\npackage pakkero\n\nimport"
},
{
"path": "internal/pakkero/obfuscation.go",
"chars": 10697,
"preview": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\nObfuscation library\n*/\npackage pakkero\n\nimpor"
},
{
"path": "internal/pakkero/pakkero.go",
"chars": 9986,
"preview": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\n*/\npackage pakkero\n\nimport (\n\t\"encoding/base6"
},
{
"path": "internal/pakkero/utilities.go",
"chars": 4615,
"preview": "/*\nPackage pakkero will pack, compress and encrypt any type of executable.\nUtilities library\n*/\npackage pakkero\n\nimport "
},
{
"path": "main.go",
"chars": 2766,
"preview": "/*\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"
}
]
About this extraction
This page contains the full source code of the 89luca89/pakkero GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 13 files (118.1 KB), approximately 35.1k tokens, and a symbol index with 78 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.