Compare commits

..

No commits in common. "main" and "0.0.1" have entirely different histories.
main ... 0.0.1

48 changed files with 580 additions and 114220 deletions

View File

@ -1,89 +0,0 @@
kind: pipeline
name: default
workspace:
base: /go
path: src/deadbeef.codes/steven/hyp
steps:
- name: create build environment
image: plugins/docker
settings:
repo: registry.deadbeef.codes/hyp-build
when:
target:
include:
- environment
- name: build hyp (client) linux-amd64
image: registry.deadbeef.codes/hyp-build:latest
pull: always
volumes:
- name: publicrelease
path: /dist
environment:
GOOS: linux
GOARCH: amd64
CGO_ENABLED: 0
commands:
- . /root/.profile
- cd hyp
- go build -o /dist/hyp-linux-amd64 .
- name: build hypd (server) linux-amd64
image: registry.deadbeef.codes/hyp-build:latest
pull: always
volumes:
- name: publicrelease
path: /dist
environment:
GOOS: linux
GOARCH: amd64
CGO_ENABLED: 0
commands:
- . /root/.profile
- cd hypd/server
- go generate
- cd ..
- go build -o /dist/hypd-linux-amd64 .
- name: build hyp (client) windows-amd64
image: registry.deadbeef.codes/hyp-build:latest
pull: always
volumes:
- name: publicrelease
path: /dist
environment:
GOOS: windows
GOARCH: amd64
CGO_ENABLED: 0
commands:
- . /root/.profile
- cd hyp
- go build -o /dist/hyp-windows-amd64.exe .
- name: release
image: plugins/gitea-release
pull: always
volumes:
- name: publicrelease
path: /dist
settings:
api_key:
from_secret: drone_token
base_url: https://deadbeef.codes
files: /dist/*
when:
event:
- tag
volumes:
- name: publicrelease
host:
path: /data/public/build/hyp

8
.gitignore vendored
View File

@ -1,8 +1,4 @@
hyp.secret hyp.secret
*.exe *.exe
hypd/hypd hypd
hyp/hyp hyp
hypd/hypdconfig.json
hypd/secrets/
hypd/server/*.o
env.sh

View File

@ -1,20 +0,0 @@
# Build environment container
# THIS CONTAINER IS NOT FOR RUNNING HYP, IT IS FOR BUILDING IT FROM SOURCE
FROM debian:stable
LABEL maintainer="himself@stevenpolley.net"
# Install build
RUN apt update -y && \
apt upgrade -y && \
apt install -y wget git clang linux-headers-amd64 libbpf-dev
# Create a few symlinks
RUN ln -s /usr/bin/llvm-strip-14 /usr/bin/llvm-strip && \
ln -s /usr/include/x86_64-linux-gnu/asm /usr/include/asm
# Install golang - Latest at: https://go.dev/dl/
RUN wget https://go.dev/dl/go1.22.2.linux-amd64.tar.gz && \
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.22.2.linux-amd64.tar.gz && \
rm -rf *.tar.gz && \
echo "export PATH=$PATH:/usr/local/go/bin" >> /root/.profile && . /root/.profile

253
LICENSE
View File

@ -1,29 +1,232 @@
Copyright (c) 2024 Steven Polley GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
All rights reserved. Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Redistribution and use in source and binary forms, with or without Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright Preamble
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Steven Polley, hyp, nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS The GNU General Public License is a free, copyleft license for software and other kinds of works.
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 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.
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 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.
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 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.
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 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.
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 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.
hyp
Copyright (C) 2024 steven
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:
hyp Copyright (C) 2024 steven
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/philosophy/why-not-lgpl.html>.

View File

@ -1,51 +1,36 @@
# hyp | Hide Your Ports # hyp | Hide Your Ports
[![Build Status](https://drone.stevenpolley.net/api/badges/steven/hyp/status.svg)](https://drone.deadbeef.codes/steven/hyp) hyp is a [port knocking](https://www.youtube.com/watch?v=a7VJZEJVhD0) implementation written in Go, using spread-spectrum UDP as an authentication mechanism. It enables trusted devices to access services over the internet, wherever they are, and without the service being publicly accessible. The benefit is that the ports are not open publicly on the internet, they won't show in a port scan and are therefore less likely to be attacked by a threat actor.
hyp is a [port knocking](https://www.youtube.com/watch?v=a7VJZEJVhD0) implementation written in Go and C. hyp uses spread-spectrum UDP as an authentication mechanism and enables trusted agents to access services over the internet, wherever they are, and without the service being accessible by others. Your TCP and UDP ports are closed. They will not show in a port scan. Nobody else can connect to them. This is particularly useful as [there](https://nvd.nist.gov/vuln/detail/CVE-2024-21888) [have](https://nvd.nist.gov/vuln/detail/CVE-2023-20269) [been](https://nvd.nist.gov/vuln/detail/CVE-2021-26109) [a](https://nvd.nist.gov/vuln/detail/CVE-2024-22394) [few](https://nvd.nist.gov/vuln/detail/CVE-2024-21894) [VPN](https://nvd.nist.gov/vuln/detail/CVE-2024-3400) [gateway](https://nvd.nist.gov/vuln/detail/CVE-2023-27997) [vulnerabilities](https://nvd.nist.gov/vuln/detail/CVE-2024-21762) [over](https://nvd.nist.gov/vuln/detail/CVE-2022-3236) [the](https://nvd.nist.gov/vuln/detail/CVE-2024-21893) [years](https://nvd.nist.gov/vuln/detail/CVE-2022-42475). I often wonder what's out there and hasn't been discovered. Why take the chance of leaving your VPN open to the whole internet? With hyp, you don't have to. hyp provides security through obscurity. Security through obscurity tends to have a negative connotation, at least in the IT world. I don't agree with this, but it's prescribed as being bad. My belief is security through obscurity is a "further step" one can take to eliminate a certain class of threats. It by no means should be the only mechanism of protection, but instead should be incorporated only as part of a layered defense.
Compared to most port knocking daemons, hyp is extremely fast, lightweight and has no dependency on libpcap. Instead of libpcap, hyp uses eBPF technology which runs in the kernel and only sends data to userspace that's absolutely required. hyp also provides additional protection against replay and sweep attacks. Each authentic knock sequence is a one time use, and new knock sequences are generated every 30 seconds. hyp makes use of pre-shared keys and time to calculate an authentic knock sequence on both the client and server. The following process describes how hyp works: ### Physical World Analogy
1. The pre-shared key is generated and distributed between both the hyp client and the hyp server. *Scenario:* You drive to the grocery store and you happen to have your laptop computer with you in the car. You're worried someone may break into your car and steal your laptop, but luckily you have some options to consider before you leave the car to go into the store:
2. The pre-shared key is run through a sha1-hmac algorithm along with the current system time, this produces the same 160 bits of output on both sides.
3. The 160 bits is reduced down to 64 bits. This helps protect the key by not revealing the entire output of the hmac... we assume you are transmitting over an untrusted network.
4. The 64 bits are divided into four 16-bit structures which are typecast to 16-bit unsigned integers. A 16-bit integer can have a value from 0-65535, the same as UDP port numbers. We have four of them now.
5. Transmit one empty datagram to the knock daemon at a time, one after another using the four integers from the previous calculation as the destination port numbers.
6. The knock daemon on the firewall verifies the sequence and performs the action of opening the firewall port configured for the client to let them in while remaining closed to everyone else.
7. The client connects to their application which has its own authentication, authorization, and auditing.
![Authentic Knock Sequence](https://code.stevenpolley.net/steven/hyp/raw/branch/main/docs/authentic-knock-sequence-calculation.png) 1. You could leave your laptop sitting where it is, on the passenger seat
2. You could conceal the laptop from outside view
### Runtime Requirements Option 1 is the default option and is analogous to having your services internet-accessible. Option 2 is similar to what port knocking is trying to achieve. In either case, there still exists some risk that your laptop will be stolen in a random bip, which is why port knocking should not be your sole focus when it comes to your security strategy and should instead be something you can use to reduce the risk of drive-by attacks.
Port knocking clients have minimal requirements and can run on x86, ARM, MIPS, PowerPC, IBM390, or RISC-V. Currently only supported OS's are Linux and Windows, with support for Android planned to be added in the future. ### Brute Force Simple Overview
The port knocking daemon has more strict requirements and is only available for Linux. It requires the kernel be built with CONFIG_DEBUG_INFO_BTF, which most major distributions have out of the box. Additionally, hypd has some network requirements. hypd is only expected to work on ethernet networks with IPv4. To put it in simple terms, hyp requires an adversary to guess a number between 1 and 18,446,744,073,709,551,615 within 90 seconds. Each guess attempt requires four ordered UDP datagrams to be transmitted. The requirement for correct order on arrival, multiple network paths, and network latency means the datagrams have to be spaced out and transmitted one at a time with time spent waiting before the next datagram is sent. An odd but perhaps useful implication of this is that the further away you are (higher latency), the less reliable guess attempts you can make before the number changes. With 20ms of latency, you can perform a maximum of 4,500 reliable guesses. With 100ms of latency, you can only perform a maximum of 900 reliable guesses.
Once you get the runtime requirements sorted, be sure to check out the hyp and hypd directories of the repository for README information for how to use hyp. ### Protection Against Replay Attacks
### Build Requirements Most port-knocking implementations are susceptible to replay attacks, a network operator could intercept your authentic knock sequence and then replay the sequence. hyp works around this by using 64-bit time-based one-time tokens. The 64 bits of the token are then divided into 4x16-bit unsigned integers representing a port number.
Pre-built binaries for configurations I've tested are available on the [releases page](https://deadbeef.codes/steven/hyp/releases). This will likely run in many CPU architectures I haven't tested yet though. hyp supports a clock skew of up to 30 seconds between client and server.
To build this yourself, you will need Linux with packages for: git, clang, linux-headers-<architecture> libbpf-dev and golang. Check out the [Dockerfile](https://deadbeef.codes/steven/hyp/src/branch/main/Dockerfile) as a reference for how the build environment for official releases is configured. Once the environment is ready, you can clone the repo and build. ### TBD: Protection Against Sweeping Attacks
```sh ~~hyp protects against sweeping attacks where an adversary modulates over the entire port range multiple times by ensuring the authentic knock sequence is strict and ordered correctly. If the first port is guessed, but the next pack arrives and is the incorrect second port in the sequence, the progress gets reset.~~
# Clone repository
git clone https://deadbeef.codes/steven/hyp.git
# Build eBPF program ### Known Weaknesses
cd hyp/hypd/server
go generate
# Build knock daemon * Lossy networks can result in the knock sequence failing
cd .. * Networks with latency > 500ms can result in the knock sequence failing if packets arrive out of order
go build -o hypd .
chmod +x hypd
# Run knock daemon and show help
./hypd -h
```
### References ### References

9
client/README.md Normal file
View File

@ -0,0 +1,9 @@
# hyp-client
The client expects there to be a file named hyp.secret in the same directory. This file is generated by the hypd server using ./hypd generatesecret.
```bash
# Example Usage
# ./hyp-client <server>
./hyp-client 192.168.50.5
```

5
client/go.mod Normal file
View File

@ -0,0 +1,5 @@
module deadbeef.codes/steven/hyp-client
go 1.22.0
require deadbeef.codes/steven/hyp/otphyp v0.0.0-20240407035202-7ccdf4d89fee

2
client/go.sum Normal file
View File

@ -0,0 +1,2 @@
deadbeef.codes/steven/hyp/otphyp v0.0.0-20240407035202-7ccdf4d89fee h1:r9xdoIGPhc/tXzyOj+lCDb+ReYa/zkysqK3ZRCqpyIU=
deadbeef.codes/steven/hyp/otphyp v0.0.0-20240407035202-7ccdf4d89fee/go.mod h1:NANpGD/K+nDkW+bkomchwaXMrsXWza58+8AR7Sau3fs=

51
client/main.go Normal file
View File

@ -0,0 +1,51 @@
package main
import (
"fmt"
"log"
"net"
"os"
"time"
"deadbeef.codes/steven/hyp/otphyp"
)
// MaxNetworkLatency specifies the number of milliseconds
// A packet-switched network... more like "race condition factory"
const MaxNetworkLatency = 500
func main() {
// validate number of input arguments
if len(os.Args) < 2 {
usage()
os.Exit(1)
}
// load secret and generate ports using secret and current time
secretBytes, err := os.ReadFile("hyp.secret")
if err != nil {
log.Fatalf("failed to read file 'hyp.secret': %v", err)
}
sharedSecret := string(secretBytes)
ports, err := otphyp.GeneratePorts(sharedSecret, time.Now())
if err != nil {
log.Fatalf("failed to generate ports from shared secret: %v", err)
}
// Transmit
fmt.Println("Transmitting knock sequence:", ports)
for _, port := range ports {
conn, _ := net.Dial("udp", fmt.Sprintf("%s:%d", os.Args[1], port))
conn.Write([]byte{0})
conn.Close()
time.Sleep(time.Millisecond * MaxNetworkLatency)
}
}
func usage() {
fmt.Println(os.Args[0], "usage")
fmt.Println("Supply an ordered list of ports to knock")
fmt.Println(os.Args[0], "server")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 196 KiB

15
go.mod
View File

@ -1,15 +0,0 @@
module deadbeef.codes/steven/hyp
go 1.22.0
require (
github.com/cilium/ebpf v0.14.0
github.com/spf13/cobra v1.8.0
)
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f // indirect
golang.org/x/sys v0.19.0 // indirect
)

26
go.sum
View File

@ -1,26 +0,0 @@
github.com/cilium/ebpf v0.14.0 h1:0PsxAjO6EjI1rcT+rkp6WcCnE0ZvfkXBYiMedJtrSUs=
github.com/cilium/ebpf v0.14.0/go.mod h1:DHp1WyrLeiBh19Cf/tfiSMhqheEiK8fXFZ4No0P1Hso=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

7
go.work Normal file
View File

@ -0,0 +1,7 @@
go 1.22.0
use (
./client
./otphyp
./server
)

View File

@ -1,34 +0,0 @@
# hyp | Hide Your Ports Client
The hyp client is used on machines to perform an authentic knock sequence.
### Usage
You can use -h to get help for hyp and all its commands. When figuring out how to do something, -h is your friend.
```bash
# Get general hyp help
./hyp -h
# Get help specific to the hyp knock command
./hyp knock -h
```
In order to use the hyp client, it must have the secret. Secrets are generated by hypd, the knock daemon. See the hypd README.md file for more information about generating secrets.
Once you have the secret, you can then perform an authentic knock sequence to a server.
```bash
# Assumes secret is in file named my-first-secret in same directory
./hyp knock 8.69.4.20 --secret my-first-secret
# If you omit --secret, hyp will look for a file named hyp.secret
./hyp knock 8.69.4.20
```
This will perform a single one-shot knock sequence and then hyp will exit. You can also run hyp in a persistent mode where it will perform an authentic knock sequence at a specified interval.
```bash
# Performs an authentic knock sequence every 45 minutes
./hyp knock 8.69.4.20 --refreshtime=45
```

View File

@ -1,98 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"encoding/base32"
"fmt"
"log"
"net"
"os"
"time"
"deadbeef.codes/steven/hyp/otphyp"
"github.com/spf13/cobra"
)
// knockCmd represents the knock command
var knockCmd = &cobra.Command{
Use: "knock <hypServer>",
Short: "Sends an authenticated knock sequence to the server specified",
Long: `Runs the hyp client and performs an authentic knock sequence
against the server provided.
Example usage:
hyp knock <hypServer>
hyp knock hyp.deadbeef.codes
hyp knock 10.69.4.20
`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// load secret and generate ports using secret and current time
secretFilePath, err := cmd.Flags().GetString("secret")
if err != nil {
panic(fmt.Errorf("failed to parse command flag 'secret': %w", err))
}
maxJitter, err := cmd.Flags().GetInt("maxjitter")
if err != nil {
panic(fmt.Errorf("failed to parse command flag 'maxjitter': %w", err))
}
if maxJitter < 1 || maxJitter > 1500 {
panic(fmt.Errorf("maxjitter must be value between 1 and 1500"))
}
refreshTime, err := cmd.Flags().GetInt("refreshtime")
if err != nil {
panic(fmt.Errorf("failed to parse command flag 'refreshtime': %w", err))
}
secretBytes, err := os.ReadFile(secretFilePath)
if err != nil {
log.Fatalf("failed to read file 'hyp.secret': %v", err)
}
decodedSecret, err := base32.StdEncoding.DecodeString(string(secretBytes))
if err != nil {
log.Fatalf("failed to base32 decode secret '%s': %v", secretFilePath, err)
}
for {
ports, err := otphyp.GeneratePorts(decodedSecret, time.Now())
if err != nil {
log.Fatalf("failed to generate ports from shared secret: %v", err)
}
// Transmit
for _, port := range ports {
fmt.Printf("knock | %s:%d\n", args[0], port)
conn, _ := net.Dial("udp", fmt.Sprintf("%s:%d", args[0], port))
conn.Write([]byte{0})
conn.Close()
time.Sleep(time.Millisecond * time.Duration(maxJitter)) // TBD: Make this configurable with flag (maxJitter)
}
if refreshTime < 1 {
break
}
sleepDuration := time.Minute * time.Duration(refreshTime)
fmt.Printf("waiting until: %s...\n", time.Now().Add(sleepDuration).Format("15:04:05"))
time.Sleep(sleepDuration)
}
},
}
func init() {
rootCmd.AddCommand(knockCmd)
knockCmd.PersistentFlags().String("secret", "hyp.secret", "Path to the file containing the hyp secret")
knockCmd.PersistentFlags().Int("maxjitter", 200, "Specifies the time in milliseconds between transmissions while performing the knock sequence")
knockCmd.PersistentFlags().Int("refreshtime", 0, "If specified, the hyp client will run persistently and send a full knock sequence at this interval in minutes")
}

View File

@ -1,33 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"os"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "hyp",
Short: "Hide Your Ports Client",
Long: `Hide Your Ports (hyp) is a combination of Port Knocking and One Time Passwords:
hyp uses a pre-shared key distributed between the server and client, as well as the time
to calculate a unique authentic knock sequence which is only valid for 90 seconds.`,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
}

View File

@ -1,10 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package main
import "deadbeef.codes/steven/hyp/hyp/cmd"
func main() {
cmd.Execute()
}

View File

@ -1,47 +0,0 @@
# hypd | Hide Your Ports Daemon
hypd is the pork knocking daemon which listens for incoming authentic knock sequences. When it sees an authentic knock sequence, it then performs an action.
### Usage
You can use -h to get help for hypd and all its commands. When figuring out how to do something, -h is your friend.
```bash
# Get general hypd help
./hypd -h
# Get help specific to the hypd generate command
./hypd generate -h
```
Running hypd requires generating secrets which are then shared with hyp clients. hypd is used to generate these secrets, and it's recommended you create a directory just for hyp secrets.
```bash
# Example: create a directory named secrets
mkdir -p secrets
# Then generate a secret file in this directory
./hypd generate secret > secrets/my-first-secret
```
It's recommended you generate a secret for each trusted agent so you can granularly control revocation just by removing a secret file from the secrets directory.
Running hypd requires specifying a configuration file. It's recommended you generate the default configuration file and then edit it afterwards.
```bash
# Create a default configuration file
./hypd generate defaultconfig > hypd.conf
```
Make sure you take the time to review the hypd.conf file and edit it to your liking, this is the most important step. Make sure the network interface is correct, hypd will make an educated guess based on the interfaces your system has.
If you have complex requirements, you can make the successAction/timeoutAction an external shell script. If you want to disable the timeoutAction, you can set timeoutSeconds to 0.
Once you have set your config file, you can finally run hypd.
```bash
# As root or sudo, specify the configuration file
sudo ./hypd server hypd.conf
```
If you encounter any errors while trying to run, address those. If not, then you're now listening for incoming authentic knock sequences. Make sure you distribute the secret to the client.

View File

@ -1,34 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"encoding/json"
"fmt"
"deadbeef.codes/steven/hyp/hypd/configuration"
"github.com/spf13/cobra"
)
// defaultconfigCmd represents the defaultconfig command
var defaultconfigCmd = &cobra.Command{
Use: "defaultconfig",
Short: "Prints the default configuration to stdout",
Long: `The default configuration is used if one is not set. The default configuration
can be used as a reference to build your own.
hypd generate defaultconfig | tee hypdconfig.json`,
Run: func(cmd *cobra.Command, args []string) {
config := configuration.DefaultConfig()
b, err := json.MarshalIndent(config, "", " ")
if err != nil {
panic(fmt.Errorf("failed to marshal default configuration to json (this should never happen): %v", err))
}
fmt.Println(string(b))
},
}
func init() {
generateCmd.AddCommand(defaultconfigCmd)
}

View File

@ -1,18 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"github.com/spf13/cobra"
)
// generateCmd represents the generate command
var generateCmd = &cobra.Command{
Use: "generate",
Short: "Generates configuration for Hide Your Ports",
}
func init() {
rootCmd.AddCommand(generateCmd)
}

View File

@ -1,33 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"os"
"github.com/spf13/cobra"
)
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "hypd",
Short: "Hide Your Ports Daemon",
Long: `Hide Your Ports (hyp) is a combination of Port Knocking and One Time Passwords:
hyp uses a pre-shared key distributed between the server and client, as well as the time
to calculate a unique authentic knock sequence which is only valid for 90 seconds.`,
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}
func init() {
}

View File

@ -1,34 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"fmt"
"deadbeef.codes/steven/hyp/otphyp"
"github.com/spf13/cobra"
)
// secretCmd represents the secret command
var secretCmd = &cobra.Command{
Use: "secret",
Short: "Generates a secret key for hyp",
Long: `Generates a secret for hyp which should be distributed to both the
server and to clients.
Example:
hypd generate secret > hyp.secret`,
Run: func(cmd *cobra.Command, args []string) {
sharedSecret, err := otphyp.GenerateSecret()
if err != nil {
panic(fmt.Errorf("failed to generate shared secret: %w", err))
}
fmt.Println(sharedSecret)
},
}
func init() {
generateCmd.AddCommand(secretCmd)
}

View File

@ -1,67 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package cmd
import (
"fmt"
"os/user"
"deadbeef.codes/steven/hyp/hypd/configuration"
"deadbeef.codes/steven/hyp/hypd/server"
"github.com/spf13/cobra"
)
// serverCmd represents the server command
var serverCmd = &cobra.Command{
Use: "server <configFilePath>",
Args: cobra.ExactArgs(1),
Short: "Runs hyp in server mode",
Long: `Runs the hyp server and begins watching for authentic knock sequences.
Before running this command, you must first have a configuration file. You can
generate a configuration file with: hypd generate defaultconfig > hypdconfig.json
You should then edit the config file to meet your needs.
In addition to a config file you will need to generate pre-shared keys:
mkdir -p ./secrets
hypd generate secret > secrets/mykey.secret
Example Usage:
# Use config file in local directory
hypd server hypdconfig.json
# Use config file in /etc/hyp/
hypd server /etc/hyp/hypdconfig.json
`,
Run: func(cmd *cobra.Command, args []string) {
currentUser, err := user.Current()
if err != nil {
panic(fmt.Errorf("could not determine current user: %w", err))
}
if currentUser.Username != "root" {
fmt.Println("WARNING: It's recommended you run this as root, but will proceed anyways...")
}
hypdConfiguration, err := configuration.LoadConfiguration(args[0])
if err != nil {
panic(fmt.Errorf("failed to load configuration file '%s': %w", args[0], err))
}
secrets, err := configuration.LoadSecrets(hypdConfiguration.PreSharedKeyDirectory)
if err != nil {
panic(fmt.Errorf("failed to load secrets from directory '%s': %w", hypdConfiguration.PreSharedKeyDirectory, err))
}
err = server.PacketServer(hypdConfiguration, secrets)
if err != nil {
panic(fmt.Errorf("failed to start packet server: %w", err))
}
},
}
func init() {
rootCmd.AddCommand(serverCmd)
}

View File

@ -1,75 +0,0 @@
package configuration
import (
"encoding/json"
"fmt"
"os"
)
type HypdConfiguration struct {
NetworkInterface string `json:"networkInterface"` // The network interface that the eBPF program attaches to
PreSharedKeyDirectory string `json:"preSharedKeyDirectory"` // hypd will load all *.secret files from this directory
SuccessAction string `json:"successAction"` // The action to take for a successful knock, each argument is a separate string
TimeoutSeconds int `json:"timeoutSeconds"` // If > 0, once a knock sequence has been successful this value will count down and when it reaches 0, it will perform the TimeoutAction on the client
TimeoutAction string `json:"timeoutAction"` // The action to take after TimeoutSeconds has elapsed. only applicable if TimeoutSeconds is > 0, each argument is a separate string
}
// LoadConfiguration opens and parses the configuration file into a HypdConfiguration struct
// If a configFilePath is not specified, it will search in common locations
func LoadConfiguration(configFilePath string) (*HypdConfiguration, error) {
if configFilePath == "" {
commonLocations := []string{"hypdconfig.json",
"~/.hypdconfig.json",
"~/.config/hyp/hypdConfig.json",
"/etc/hyp/hypdConfig.json",
"/usr/local/etc/hyp/hypdConfig.json",
}
for _, loc := range commonLocations {
if _, err := os.Stat(loc); err == nil {
configFilePath = loc
break
}
}
}
// if it's still not found after checking common locations, load default config
if configFilePath == "" {
fmt.Println("no configuration file found. You can generate one with ./hypd generate defaultconfig | tee hypdconfig.json")
return DefaultConfig(), nil
}
// Otherwise if a config is specified, try to load it and error if it fails.
// I think it's better to error here if a config was intended and failed
// rather than failing back to default
b, err := os.ReadFile(configFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read config file '%s': %w", configFilePath, err)
}
hypdConfiguration := &HypdConfiguration{}
err = json.Unmarshal(b, hypdConfiguration)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal config file json to HypdConfiguration (is the config file malformed?): %w", err)
}
return hypdConfiguration, nil
}
func DefaultConfig() *HypdConfiguration {
var ifaceString string
iface, err := getDefaultNIC()
if err == nil {
ifaceString = iface.Name
} else {
ifaceString = "enp0s3" // fallback to fixed value
}
return &HypdConfiguration{
NetworkInterface: ifaceString,
PreSharedKeyDirectory: "./secrets/",
SuccessAction: "iptables -A INPUT -p tcp -s %s --dport 22 -j ACCEPT",
TimeoutSeconds: 1440,
TimeoutAction: "iptables -D INPUT -p tcp -s %s --dport 22 -j ACCEPT",
}
}

View File

@ -1,81 +0,0 @@
package configuration
import (
"fmt"
"net"
)
// QoL feature to try and detect the best NIC for hyp
func getDefaultNIC() (*net.Interface, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("failed to get network interfaces on this system: %v", err)
}
if len(ifaces) < 1 {
return nil, fmt.Errorf("this system has no network interfaces: %v", err)
}
// Just pick one to start
selectedIface := ifaces[0]
filteredIfaces := make([]net.Interface, 0)
// Check for ethernet addresses
for _, iface := range ifaces {
if len(iface.HardwareAddr) == 6 {
selectedIface = iface
filteredIfaces = append(filteredIfaces, iface)
}
}
ifaces = filteredIfaces
filteredIfaces = make([]net.Interface, 0)
// Check for interfaces that are up and not loopbacks
for _, iface := range ifaces {
if iface.Flags&net.FlagUp != 0 && iface.Flags&net.FlagRunning != 0 && iface.Flags&net.FlagLoopback == 0 {
selectedIface = iface
filteredIfaces = append(filteredIfaces, iface)
}
}
ifaces = filteredIfaces
filteredIfaces = make([]net.Interface, 0)
// Check for interfaces that have IPv4 addresses assigned
for _, iface := range ifaces {
addresses, err := iface.Addrs()
if err != nil {
continue
}
for _, address := range addresses {
ip, _, err := net.ParseCIDR(address.String())
if err != nil {
continue
}
if ip.To4() != nil {
selectedIface = iface
filteredIfaces = append(filteredIfaces, iface)
}
}
}
ifaces = filteredIfaces
filteredIfaces = nil
// Check for interfaces that have non RFC1918 addresses assigned
for _, iface := range ifaces {
addresses, err := iface.Addrs()
if err != nil {
continue
}
for _, address := range addresses {
ip, _, err := net.ParseCIDR(address.String())
if err != nil {
continue
}
if !ip.IsPrivate() {
selectedIface = iface
}
}
}
return &selectedIface, nil // TBD
}

View File

@ -1,49 +0,0 @@
package configuration
import (
"encoding/base32"
"fmt"
"io/fs"
"os"
"path/filepath"
)
var secrets [][]byte
// LoadSecrets processes all files within the specified directory and attempts to
// convert the file contents to secrets to by used by hypd
func LoadSecrets(preSharedKeyDirectory string) ([][]byte, error) {
secrets = make([][]byte, 0)
err := filepath.Walk(preSharedKeyDirectory, processSecretFile)
if err != nil {
return nil, fmt.Errorf("failed to walk directory '%s': %w", preSharedKeyDirectory, err)
}
return secrets, nil
}
// processSecretFile is called against each file in the preSharedKeyDirectory
// It reads each file and attemts to base32 decode their contents
func processSecretFile(path string, info fs.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to process file '%s': %w", path, err)
}
if info.IsDir() {
return nil
}
secretBytes, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("failed to read file '%s': %w", path, err)
}
decodedSecret, err := base32.StdEncoding.DecodeString(string(secretBytes))
if err != nil {
return fmt.Errorf("failed to base32 decode secret '%s': %w", path, err)
}
secrets = append(secrets, decodedSecret)
return nil
}

View File

@ -1,7 +0,0 @@
{
"networkInterface": "enp0s3",
"preSharedKeyDirectory": "./secrets/",
"successAction": "./examples/fortigate/openfortigate.sh %s",
"timeoutSeconds": 0,
"timeoutAction": ""
}

View File

@ -1,33 +0,0 @@
#!/bin/bash
# Make sure you have environment variables set for FORTIGATE_MGMT_URL, FORTIGATE_API_TOKEN and FORTIGATE_ADDRESS_OBJECT_GROUP
# Examples:
export FORTIGATE_MGMT_URL="https://69.4.20.10:8443"
export FORTIGATE_API_KEY="5fkwkkzgQ4s31bdH60qsxxfN093zgt"
export FORTIGATE_ADDRESS_OBJECT_GROUP="hyp-allowed-clients"
if [ $# -lt 1 ]; then
echo "Usage: $0 <srcip>"
exit 1
fi
echo $FORTIGATE_MGMT_URL
echo $1
# Create the address object
curl "$FORTIGATE_MGMT_URL/api/v2/cmdb/firewall/address?datasource=1" \
-X "POST" \
-H "Authorization: Bearer $FORTIGATE_API_KEY" \
-H "Content-Type: application/json" \
--data-raw "{\"name\":\"hyp_$1\",\"subnet\":\"$1/32\",\"color\":\"0\"}" \
--insecure # LOL - remove this if you want, but I want this to be easy for noobs
# Add to address object group
curl "$FORTIGATE_MGMT_URL/api/v2/cmdb/firewall/addrgrp/$FORTIGATE_ADDRESS_OBJECT_GROUP/member" \
-X "POST" \
-H "Authorization: Bearer $FORTIGATE_API_KEY" \
-H "Content-Type: application/json" \
--data-raw "{\"name\":\"hyp_$1\"}" \
--insecure # And here too

View File

@ -1,12 +0,0 @@
# Using hyp with OpenWrt Wireguard
This example case is to deploy hypd on OpenWrt to open up access to the WireGuard VPN service.
hyp utilizes eBPF technology to ensure runtime overhead is extremely small (in a way, but in a way not). Most Linux distributions have support for this out of the box, however OpenWrt does not. OpenWrt has a very stripped down, purpose-configured kernel and does not have the requirements built in to run hyp.
The good news is, you can build OpenWrt yourself and configure it with the requirements. Follow the directions at this page: https://openwrt.org/docs/guide-developer/toolchain/use-buildsystem
When you run *make menuconfig*, make sure you check off *Enable additional BTF type information* which is also known as CONFIG_KERNEL_DEBUG_INFO_BTF. This is required to support eBPF CO:RE.
![Kernel Config](https://deadbeef.codes/steven/hyp/raw/branch/main/hypd/examples/openwrt-wireguard/kernel_config.png)

View File

@ -1,14 +0,0 @@
#!/bin/sh
if [ $# -lt 1 ]; then
echo "Usage: $0 <srcip>"
exit 1
fi
# Can't use dots in rule name, so swap for underscores
rulename="hypd_${1//./_}_wireguard"
# Configure the rule in OpenWRT's uci interface
uci delete firewall.$rulename
uci commit firewall
service firewall restart

View File

@ -1,7 +0,0 @@
{
"networkInterface": "enp0s3",
"preSharedKeyDirectory": "./secrets/",
"successAction": "./examples/openwrt-wireguard/openwireguard.sh %s",
"timeoutSeconds": 1440,
"timeoutAction": "./examples/openwrt-wireguard/closewireguard.sh %s"
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

View File

@ -1,24 +0,0 @@
#!/bin/sh
if [ $# -lt 1 ]; then
echo "Usage: $0 <srcip>"
exit 1
fi
# Can't use dots in rule name, so swap for underscores
# example: 10.69.69.100 changes to hypd_10_69_69_100_wireguard
rulename="hypd_${1//./_}_wireguard"
# Configure the rule in OpenWRT's uci interface
uci set firewall.$rulename=redirect
uci set firewall.$rulename.dest=lan
uci set firewall.$rulename.target=DNAT
uci set firewall.$rulename.name=$rulename
uci set firewall.$rulename.src=wan
uci set firewall.$rulename.src_dport=51820
uci set firewall.$rulename.dest_ip=10.0.100.1
uci set firewall.$rulename.dest_port=51820
uci set firewall.$rulename.src_ip=$1
uci add_list firewall.$rulename.proto=udp
uci commit firewall
service firewall restart

View File

@ -1,10 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package main
import "deadbeef.codes/steven/hyp/hypd/cmd"
func main() {
cmd.Execute()
}

View File

@ -1,30 +0,0 @@
# hypd server
hypd is the port knocking daemon which runs on an edge device connecting to an untrusted network. Leveraging eBPF's XDP hook point, it extracts header information directly and sends to userspace the specific information required. This method is faster than alternative methods such as using libpcap.
### eBPF
The hyp_bpf.c program can be recompiled using go generate.
```bash
# Debian: sudo apt install git clang linux-headers-amd64 libbpf-dev
go generate .
```
### Generating vmlinux.h
vmlinux.h is included in hyp_bpf.c and can be regenerated with bpftool.
```bash
# Debian: sudo apt install bpftool
sudo bpftool btf dump file /sys/kernel/btf/vmlinux format c > ../headers/vmlinux.h
```
### Building hypd
hypd has no CGO dependencies and so can run on musl systems as well.
```bash
# To ensure it can run on systems don't use CGO
CGO_ENABLED=0 go build .
```

View File

@ -1,100 +0,0 @@
// Code lifted from the folks at Cilium from ebpf-go repo
#ifndef __BPF_ENDIAN__
#define __BPF_ENDIAN__
/*
* Isolate byte #n and put it into byte #m, for __u##b type.
* E.g., moving byte #6 (nnnnnnnn) into byte #1 (mmmmmmmm) for __u64:
* 1) xxxxxxxx nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx
* 2) nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx 00000000
* 3) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn
* 4) 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn 00000000
*/
#define ___bpf_mvb(x, b, n, m) ((__u##b)(x) << (b-(n+1)*8) >> (b-8) << (m*8))
#define ___bpf_swab16(x) ((__u16)( \
___bpf_mvb(x, 16, 0, 1) | \
___bpf_mvb(x, 16, 1, 0)))
#define ___bpf_swab32(x) ((__u32)( \
___bpf_mvb(x, 32, 0, 3) | \
___bpf_mvb(x, 32, 1, 2) | \
___bpf_mvb(x, 32, 2, 1) | \
___bpf_mvb(x, 32, 3, 0)))
#define ___bpf_swab64(x) ((__u64)( \
___bpf_mvb(x, 64, 0, 7) | \
___bpf_mvb(x, 64, 1, 6) | \
___bpf_mvb(x, 64, 2, 5) | \
___bpf_mvb(x, 64, 3, 4) | \
___bpf_mvb(x, 64, 4, 3) | \
___bpf_mvb(x, 64, 5, 2) | \
___bpf_mvb(x, 64, 6, 1) | \
___bpf_mvb(x, 64, 7, 0)))
/* LLVM's BPF target selects the endianness of the CPU
* it compiles on, or the user specifies (bpfel/bpfeb),
* respectively. The used __BYTE_ORDER__ is defined by
* the compiler, we cannot rely on __BYTE_ORDER from
* libc headers, since it doesn't reflect the actual
* requested byte order.
*
* Note, LLVM's BPF target has different __builtin_bswapX()
* semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
* in bpfel and bpfeb case, which means below, that we map
* to cpu_to_be16(). We could use it unconditionally in BPF
* case, but better not rely on it, so that this header here
* can be used from application and BPF program side, which
* use different targets.
*/
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define __bpf_ntohs(x) __builtin_bswap16(x)
# define __bpf_htons(x) __builtin_bswap16(x)
# define __bpf_constant_ntohs(x) ___bpf_swab16(x)
# define __bpf_constant_htons(x) ___bpf_swab16(x)
# define __bpf_ntohl(x) __builtin_bswap32(x)
# define __bpf_htonl(x) __builtin_bswap32(x)
# define __bpf_constant_ntohl(x) ___bpf_swab32(x)
# define __bpf_constant_htonl(x) ___bpf_swab32(x)
# define __bpf_be64_to_cpu(x) __builtin_bswap64(x)
# define __bpf_cpu_to_be64(x) __builtin_bswap64(x)
# define __bpf_constant_be64_to_cpu(x) ___bpf_swab64(x)
# define __bpf_constant_cpu_to_be64(x) ___bpf_swab64(x)
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
# define __bpf_ntohs(x) (x)
# define __bpf_htons(x) (x)
# define __bpf_constant_ntohs(x) (x)
# define __bpf_constant_htons(x) (x)
# define __bpf_ntohl(x) (x)
# define __bpf_htonl(x) (x)
# define __bpf_constant_ntohl(x) (x)
# define __bpf_constant_htonl(x) (x)
# define __bpf_be64_to_cpu(x) (x)
# define __bpf_cpu_to_be64(x) (x)
# define __bpf_constant_be64_to_cpu(x) (x)
# define __bpf_constant_cpu_to_be64(x) (x)
#else
# error "Fix your compiler's __BYTE_ORDER__?!"
#endif
#define bpf_htons(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_htons(x) : __bpf_htons(x))
#define bpf_ntohs(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_ntohs(x) : __bpf_ntohs(x))
#define bpf_htonl(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_htonl(x) : __bpf_htonl(x))
#define bpf_ntohl(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_ntohl(x) : __bpf_ntohl(x))
#define bpf_cpu_to_be64(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x))
#define bpf_be64_to_cpu(x) \
(__builtin_constant_p(x) ? \
__bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x))
#endif /* __BPF_ENDIAN__ */

View File

@ -1,74 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
//go:build ignore
#include "vmlinux.h"
#include "bpf_endian.h"
#include <bpf/bpf_helpers.h>
char __license[] SEC("license") = "BSD";
// representation of knock data that gets sent to userspace
struct knock_data {
__u32 srcip; // 4 bytes
__u16 dstport; // 2 bytes
__u16 pad; // required padding - struct must be multiple of 4 bytes
};
// ring buffer used to send data to userspace
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 24);
} rb SEC(".maps");
// force emitting struct event into the ELF
const struct knock_data *unused __attribute__((unused));
// hook into xpress data path attach point
SEC("xdp")
int xdp_prog_func(struct xdp_md *ctx) {
// xdp gives us the raw frame with no structures, it must be parsed
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
// A knock should not contain any data
if (data_end - data > 60) {
return XDP_PASS;
}
// parse ethernet header
struct ethhdr *eth = data;
if ((void *)eth + sizeof(*eth) > data_end) {
return XDP_PASS;
}
// parse IP header
struct iphdr *ip = data + sizeof(*eth);
if ((void *)ip + sizeof(*ip) > data_end) {
return XDP_PASS;
}
// Ensure IP header protocol field is UDP (protocol 17)
if (ip->protocol != IPPROTO_UDP) {
return XDP_PASS;
}
// parse UDP header
struct udphdr *udp = (void *)ip + sizeof(*ip);
if ((void *)udp + sizeof(*udp) > data_end) {
return XDP_PASS;
}
// pack into knock structure and send to userspace
struct knock_data knock = {
.srcip = bpf_ntohl(ip->saddr),
.dstport = bpf_htons(udp->dest),
.pad = 0
};
bpf_ringbuf_output(&rb, &knock, sizeof(knock), BPF_RB_FORCE_WAKEUP);
// We send everything to XDP_PASS
return XDP_PASS;
}

View File

@ -1,125 +0,0 @@
// Code generated by bpf2go; DO NOT EDIT.
//go:build mips || mips64 || ppc64 || s390x
package server
import (
"bytes"
_ "embed"
"fmt"
"io"
"github.com/cilium/ebpf"
)
type hyp_bpfKnockData struct {
Srcip uint32
Dstport uint16
Pad uint16
}
// loadHyp_bpf returns the embedded CollectionSpec for hyp_bpf.
func loadHyp_bpf() (*ebpf.CollectionSpec, error) {
reader := bytes.NewReader(_Hyp_bpfBytes)
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
if err != nil {
return nil, fmt.Errorf("can't load hyp_bpf: %w", err)
}
return spec, err
}
// loadHyp_bpfObjects loads hyp_bpf and converts it into a struct.
//
// The following types are suitable as obj argument:
//
// *hyp_bpfObjects
// *hyp_bpfPrograms
// *hyp_bpfMaps
//
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
func loadHyp_bpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
spec, err := loadHyp_bpf()
if err != nil {
return err
}
return spec.LoadAndAssign(obj, opts)
}
// hyp_bpfSpecs contains maps and programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type hyp_bpfSpecs struct {
hyp_bpfProgramSpecs
hyp_bpfMapSpecs
}
// hyp_bpfSpecs contains programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type hyp_bpfProgramSpecs struct {
XdpProgFunc *ebpf.ProgramSpec `ebpf:"xdp_prog_func"`
}
// hyp_bpfMapSpecs contains maps before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type hyp_bpfMapSpecs struct {
Rb *ebpf.MapSpec `ebpf:"rb"`
}
// hyp_bpfObjects contains all objects after they have been loaded into the kernel.
//
// It can be passed to loadHyp_bpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type hyp_bpfObjects struct {
hyp_bpfPrograms
hyp_bpfMaps
}
func (o *hyp_bpfObjects) Close() error {
return _Hyp_bpfClose(
&o.hyp_bpfPrograms,
&o.hyp_bpfMaps,
)
}
// hyp_bpfMaps contains all maps after they have been loaded into the kernel.
//
// It can be passed to loadHyp_bpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type hyp_bpfMaps struct {
Rb *ebpf.Map `ebpf:"rb"`
}
func (m *hyp_bpfMaps) Close() error {
return _Hyp_bpfClose(
m.Rb,
)
}
// hyp_bpfPrograms contains all programs after they have been loaded into the kernel.
//
// It can be passed to loadHyp_bpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type hyp_bpfPrograms struct {
XdpProgFunc *ebpf.Program `ebpf:"xdp_prog_func"`
}
func (p *hyp_bpfPrograms) Close() error {
return _Hyp_bpfClose(
p.XdpProgFunc,
)
}
func _Hyp_bpfClose(closers ...io.Closer) error {
for _, closer := range closers {
if err := closer.Close(); err != nil {
return err
}
}
return nil
}
// Do not access this directly.
//
//go:embed hyp_bpf_bpfeb.o
var _Hyp_bpfBytes []byte

View File

@ -1,125 +0,0 @@
// Code generated by bpf2go; DO NOT EDIT.
//go:build 386 || amd64 || arm || arm64 || loong64 || mips64le || mipsle || ppc64le || riscv64
package server
import (
"bytes"
_ "embed"
"fmt"
"io"
"github.com/cilium/ebpf"
)
type hyp_bpfKnockData struct {
Srcip uint32
Dstport uint16
Pad uint16
}
// loadHyp_bpf returns the embedded CollectionSpec for hyp_bpf.
func loadHyp_bpf() (*ebpf.CollectionSpec, error) {
reader := bytes.NewReader(_Hyp_bpfBytes)
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
if err != nil {
return nil, fmt.Errorf("can't load hyp_bpf: %w", err)
}
return spec, err
}
// loadHyp_bpfObjects loads hyp_bpf and converts it into a struct.
//
// The following types are suitable as obj argument:
//
// *hyp_bpfObjects
// *hyp_bpfPrograms
// *hyp_bpfMaps
//
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
func loadHyp_bpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
spec, err := loadHyp_bpf()
if err != nil {
return err
}
return spec.LoadAndAssign(obj, opts)
}
// hyp_bpfSpecs contains maps and programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type hyp_bpfSpecs struct {
hyp_bpfProgramSpecs
hyp_bpfMapSpecs
}
// hyp_bpfSpecs contains programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type hyp_bpfProgramSpecs struct {
XdpProgFunc *ebpf.ProgramSpec `ebpf:"xdp_prog_func"`
}
// hyp_bpfMapSpecs contains maps before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type hyp_bpfMapSpecs struct {
Rb *ebpf.MapSpec `ebpf:"rb"`
}
// hyp_bpfObjects contains all objects after they have been loaded into the kernel.
//
// It can be passed to loadHyp_bpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type hyp_bpfObjects struct {
hyp_bpfPrograms
hyp_bpfMaps
}
func (o *hyp_bpfObjects) Close() error {
return _Hyp_bpfClose(
&o.hyp_bpfPrograms,
&o.hyp_bpfMaps,
)
}
// hyp_bpfMaps contains all maps after they have been loaded into the kernel.
//
// It can be passed to loadHyp_bpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type hyp_bpfMaps struct {
Rb *ebpf.Map `ebpf:"rb"`
}
func (m *hyp_bpfMaps) Close() error {
return _Hyp_bpfClose(
m.Rb,
)
}
// hyp_bpfPrograms contains all programs after they have been loaded into the kernel.
//
// It can be passed to loadHyp_bpfObjects or ebpf.CollectionSpec.LoadAndAssign.
type hyp_bpfPrograms struct {
XdpProgFunc *ebpf.Program `ebpf:"xdp_prog_func"`
}
func (p *hyp_bpfPrograms) Close() error {
return _Hyp_bpfClose(
p.XdpProgFunc,
)
}
func _Hyp_bpfClose(closers ...io.Closer) error {
for _, closer := range closers {
if err := closer.Close(); err != nil {
return err
}
}
return nil
}
// Do not access this directly.
//
//go:embed hyp_bpf_bpfel.o
var _Hyp_bpfBytes []byte

View File

@ -1,254 +0,0 @@
/*
Copyright © 2024 Steven Polley <himself@stevenpolley.net>
*/
package server
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"log"
"net"
"os/exec"
"time"
"deadbeef.codes/steven/hyp/hypd/configuration"
"deadbeef.codes/steven/hyp/otphyp"
"github.com/cilium/ebpf/link"
"github.com/cilium/ebpf/ringbuf"
"github.com/cilium/ebpf/rlimit"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go --type knock_data hyp_bpf hyp_bpf.c
// Client is used to keep track of a client attempting to perform an authentic knock sequence
type Client struct {
Progress int // index of current progress in sequence. Value of 1 means first port has been matched
Sequence [4]uint16 // stores the knock sequence the current client is attempting. It's set and tracked here to prevent race conditions during a knock sequence being received and key rotations
LastSuccess time.Time
}
// KnockSequence is used keep track of an ordered knock sequence and whether it's been marked for use (to prevent replay attacks)
type KnockSequence struct {
Used bool // If true, that means this knock sequence has already been used once. It may still be within the valid time window, but it can't be used again
PortSequence [4]uint16 // Each knock sequence is four ports long
}
const (
KnockSequenceTimeout = 3 // TBD: Make this a configurable value
)
var (
clients map[uint32]*Client // Contains a map of clients, key is IPv4 address
knockSequences []KnockSequence // We have 3 valid knock sequences at any time to account for clock skew
serverConfig *configuration.HypdConfiguration
sharedSecrets [][]byte // A slice of byte slices, each being a secret key
)
// PacketServer is the main function when operating in server mode
// it sets up the pcap on the capture device and starts a goroutine
// to rotate the knock sequence
func PacketServer(config *configuration.HypdConfiguration, secrets [][]byte) error {
serverConfig = config
sharedSecrets = secrets
iface, err := net.InterfaceByName(serverConfig.NetworkInterface)
if err != nil {
log.Fatalf("lookup network iface %q: %v", serverConfig.NetworkInterface, err)
}
clients = make(map[uint32]*Client, 0)
knockSequences = []KnockSequence{}
// Setup a goroutine to periodically rotate the authentic knock sequence
go rotateSequence()
////////////////////////////////////
// Allow the current process to lock memory for eBPF resources.
if err := rlimit.RemoveMemlock(); err != nil {
log.Fatal(err)
}
// Load pre-compiled programs into the kernel.
objs := hyp_bpfObjects{}
if err := loadHyp_bpfObjects(&objs, nil); err != nil {
log.Fatalf("loading objects: %v", err)
}
defer objs.Close()
// Attach the program.
l, err := link.AttachXDP(link.XDPOptions{
Program: objs.XdpProgFunc,
Interface: iface.Index,
})
if err != nil {
log.Fatalf("could not attach XDP program: %v", err)
}
defer l.Close()
log.Printf("Attached XDP program to iface %q (index %d)", iface.Name, iface.Index)
log.Printf("Press Ctrl-C to exit and remove the program")
rd, err := ringbuf.NewReader(objs.Rb)
if err != nil {
log.Fatalf("could not open ring buffer reader: %v", err)
}
defer rd.Close()
var event hyp_bpfKnockData
for {
record, err := rd.Read()
if err != nil {
if errors.Is(err, ringbuf.ErrClosed) {
log.Println("eBPF ring buffer closed, exiting...")
return nil
}
log.Printf("error reading from ring buffer reader: %v", err)
continue
}
if err := binary.Read(bytes.NewBuffer(record.RawSample), binary.LittleEndian, &event); err != nil {
log.Printf("error parsing ringbuf event: %v", err)
continue
}
go handleKnock(event)
}
}
// intToIP converts IPv4 number to net.IP
func intToIP(ipNum uint32) net.IP {
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, ipNum)
return ip
}
// packets that match the BPF filter get passed to handlePacket
func handleKnock(knockEvent hyp_bpfKnockData) {
client, ok := clients[knockEvent.Srcip]
if !ok { // client doesn't exist yet
client = &Client{}
clients[knockEvent.Srcip] = client
}
if client.Progress == 0 {
for i, knockSequence := range knockSequences { // identify which of the authentic knock sequences is matched
if knockSequence.Used { // skip over sequences that are already used to prevent replay attack
continue
}
if knockEvent.Dstport == knockSequence.PortSequence[0] {
knockSequences[i].Used = true // TBD: This is vulnerable to a DoS just by doing a full UDP port scan
client.Progress = 1
client.Sequence = knockSequence.PortSequence
go timeoutKnockSequence(knockEvent.Srcip)
}
}
return
}
// if it's wrong, reset progress
if knockEvent.Dstport != client.Sequence[client.Progress] {
delete(clients, knockEvent.Srcip)
fmt.Printf("port '%d' is in sequence, but came at unexpected order - resetting progress", knockEvent.Dstport)
return
}
// Client increases progress through sequence and checks if sequence is completed
client.Progress++
if client.Progress >= len(client.Sequence) {
client.Progress = 0
client.LastSuccess = time.Now()
handleSuccess(knockEvent.Srcip) // The magic function, the knock is completed
return
}
}
// Remove the client after the timeout value has elapsed. This prevents a client from
// being indefinitely stuck part way through an old knock sequence. It's also helpful
// in preventing sweep attacks as the authentic knock sequence must be correctly entered
// within the timeout value from start to finish.
// Note: This is not related to handling the timeout / clsoe ports action after a client
// has successfully completed an authentic knock sequence
func timeoutKnockSequence(srcip uint32) {
time.Sleep(time.Second * KnockSequenceTimeout)
client, ok := clients[srcip]
if ok {
if client.LastSuccess.IsZero() { // If they've never succeeded, just drop them from the map
delete(clients, srcip)
} else { // If they have succeeded, just reset their progress to 0 but keep them in map. They will be cleaned in handleSuccess
client.Progress = 0
}
}
}
// Used to rotate the authentic port knock sequence
func rotateSequence() {
for {
// Generate new knock sequences with time skew support
t := time.Now().Add(time.Second * -30)
for i := len(knockSequences) / len(sharedSecrets); i < 3; i++ {
for _, secret := range sharedSecrets {
portSequence, err := otphyp.GeneratePorts(secret, t.Add((time.Second * 30 * time.Duration(i))))
if err != nil {
log.Fatalf("failed to generate port knock sequence: %v", err)
}
knockSequence := KnockSequence{PortSequence: portSequence}
knockSequences = append(knockSequences, knockSequence)
}
}
// Sleep until next 30 second offset
time.Sleep(time.Until(time.Now().Truncate(time.Second * 30).Add(time.Second * 30)))
// pop first value, next iteration pushes new value
knockSequences = knockSequences[len(sharedSecrets):]
}
}
// handleSuccess is ran when a source IP successfully enters the authentic knock sequence
// the configured success action is ran
func handleSuccess(srcip uint32) {
srcipf := intToIP(srcip) // formatted as net.IP
log.Printf("Successful knock from: %s", srcipf)
client, ok := clients[srcip]
if !ok {
log.Printf("failed to lookup %s in clients", srcipf)
return
}
// Don't care about command injection, the configuration file providing the command literally NEEDS to be trusted
// TBD: Use template / substitution instead of string formatting directive - allows for srcip token to be used multiple times
cmd := exec.Command("sh", "-c", fmt.Sprintf(serverConfig.SuccessAction, srcipf))
err := cmd.Run()
if err != nil {
log.Printf("failed to execute success action command for '%s': %v", srcipf, err)
}
// Handle timeout action
if serverConfig.TimeoutSeconds < 1 { // Timeout action is disabled
delete(clients, srcip)
return
}
// Handle checks for client timeout
// TBD: Persistence / journaling state to disk? How to handle case if knock daemon is restarted - ports would remain open
lastSuccess := client.LastSuccess
time.Sleep(time.Until(client.LastSuccess.Add(time.Duration(serverConfig.TimeoutSeconds * int(time.Second)))))
if client.LastSuccess.After(lastSuccess) { // The client has refreshed
return
}
// Don't care about command injection, the configuration file providing the command literally NEEDS to be trusted
// TBD: Use template / substitution instead of string formatting directive - allows for srcip token to be used multiple times
log.Printf("Performing timeout action on: %s", srcipf)
cmd = exec.Command("sh", "-c", fmt.Sprintf(serverConfig.TimeoutAction, srcipf))
err = cmd.Run()
if err != nil {
log.Printf("failed to execute timeout action command for '%s': %v", srcipf, err)
}
delete(clients, srcip)
}

File diff suppressed because it is too large Load Diff

3
otphyp/go.mod Normal file
View File

@ -0,0 +1,3 @@
module deadbeef.codes/steven/hyp/otphyp
go 1.22.0

View File

@ -15,7 +15,12 @@ import (
// A loose implementation of hotp meant for our specific purposes of generating four random port numbers // A loose implementation of hotp meant for our specific purposes of generating four random port numbers
// Accepts a base32 encoded shared secret and a time // Accepts a base32 encoded shared secret and a time
func GeneratePorts(sharedSecret []byte, t time.Time) (ports [4]uint16, err error) { func GeneratePorts(sharedSecret string, t time.Time) (ports [4]uint16, err error) {
sharedSecretBytes, err := base32.StdEncoding.DecodeString(sharedSecret)
if err != nil {
return [4]uint16{0, 0, 0, 0}, fmt.Errorf("failed to base32 decode shared secret string to bytes: %v", err)
}
// 30 second key rotation // 30 second key rotation
movingFactor := uint64(math.Floor(float64(t.Unix()) / float64(30))) movingFactor := uint64(math.Floor(float64(t.Unix()) / float64(30)))
@ -23,7 +28,7 @@ func GeneratePorts(sharedSecret []byte, t time.Time) (ports [4]uint16, err error
binary.BigEndian.PutUint64(buf, movingFactor) binary.BigEndian.PutUint64(buf, movingFactor)
// calculate hmac and offset // calculate hmac and offset
mac := hmac.New(sha1.New, sharedSecret) mac := hmac.New(sha1.New, sharedSecretBytes)
mac.Write(buf) mac.Write(buf)
sum := mac.Sum(nil) sum := mac.Sum(nil)
offset := sum[len(sum)-1] & 0xf offset := sum[len(sum)-1] & 0xf
@ -47,7 +52,7 @@ func GeneratePorts(sharedSecret []byte, t time.Time) (ports [4]uint16, err error
// 2. Save the secret to a file // 2. Save the secret to a file
// 3. Distribute the secret to a client // 3. Distribute the secret to a client
func GenerateSecret() (sharedSecret string, err error) { func GenerateSecret() (sharedSecret string, err error) {
sharedSecretBytes := make([]byte, 500) sharedSecretBytes := make([]byte, 20)
r := rand.Reader r := rand.Reader
_, err = r.Read([]byte(sharedSecretBytes)) _, err = r.Read([]byte(sharedSecretBytes))
if err != nil { if err != nil {

25
server/README.md Normal file
View File

@ -0,0 +1,25 @@
# hypd
hypd is the hyp (Hide Your Ports) server.
### Requirements
On the server, libpcap-dev needs to be installed on linux or pcap from nmap.org on Windows.
### Usage
##### Generating a new shared key
```bash
# As user that can write to current directory
./hypd generatesecret
```
Then copy the file to a client
##### Starting the server
```bash
# As root - or user that can capture packets and modify IPTables
./hypd server eth0
```

10
server/go.mod Normal file
View File

@ -0,0 +1,10 @@
module deadbeef.codes/steven/hypd
go 1.22.0
require (
deadbeef.codes/steven/hyp/otphyp v0.0.0-20240407035202-7ccdf4d89fee
github.com/google/gopacket v1.1.19
)
require golang.org/x/sys v0.19.0 // indirect

19
server/go.sum Normal file
View File

@ -0,0 +1,19 @@
deadbeef.codes/steven/hyp/otphyp v0.0.0-20240407035202-7ccdf4d89fee h1:r9xdoIGPhc/tXzyOj+lCDb+ReYa/zkysqK3ZRCqpyIU=
deadbeef.codes/steven/hyp/otphyp v0.0.0-20240407035202-7ccdf4d89fee/go.mod h1:NANpGD/K+nDkW+bkomchwaXMrsXWza58+8AR7Sau3fs=
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

74
server/main.go Normal file
View File

@ -0,0 +1,74 @@
package main
import (
"fmt"
"log"
"os"
"os/exec"
"deadbeef.codes/steven/hyp/otphyp"
)
func main() {
if len(os.Args) < 2 {
usage()
}
switch os.Args[1] {
case "generatesecret":
sharedSecret, err := otphyp.GenerateSecret()
if err != nil {
log.Fatalf("failed to generate shared secret: %v", err)
}
f, err := os.Create("hyp.secret")
if err != nil {
log.Fatalf("failed to create file 'hyp.secret': %v", err)
}
_, err = f.WriteString(sharedSecret)
if err != nil {
log.Fatalf("failed to write to file 'hyp.secret': %v", err)
}
f.Close()
fmt.Println("Created file hyp.secret")
case "server":
secretBytes, err := os.ReadFile("hyp.secret")
if err != nil {
log.Fatalf("failed to read file 'hyp.secret': %v", err)
}
sharedSecret = string(secretBytes)
if len(os.Args) < 3 {
usage()
}
packetServer(os.Args[2])
}
}
func usage() {
fmt.Print(`hyp <command>
Commands:
generatesecret - creates a pre shared key file named hyp.secret which can be distributed to a trusted client
server <device> - TBD
Example Usage:
# Linux
hyp server "/dev/eth0"
# Windows - get-netadapter | where {$_.Name -eq Ethernet} | Select-Object -Property DeviceName
hyp server "\\Device\\NPF_{A066F7DE-CC2D-4E4B-97C4-BF0EC4C03649}"
`)
os.Exit(1)
}
// TBD: Implement
func handleSuccess(srcip string) {
fmt.Println("Success for ", srcip)
cmd := exec.Command("iptables", "-A", "INPUT", "-p", "tcp", "-s", srcip, "--dport", "22", "-j", "ACCEPT")
err := cmd.Run()
if err != nil {
log.Printf("failed to execute iptables command for '%s': %v", srcip, err)
}
}

120
server/packet.go Normal file
View File

@ -0,0 +1,120 @@
package main
import (
"encoding/binary"
"fmt"
"log"
"time"
"deadbeef.codes/steven/hyp/otphyp"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
)
// type client is used to keept track of a client attempting to perform an authentic knock sequence
type Client struct {
Progress int // index of current progress in sequence. Value of 1 means first port has been matched
Sequence [4]uint16 // stores the knock sequence the current client is attempting. It's set and tracked here to prevent race conditions during a knock sequence being received and key rotations
}
var (
clients map[string]*Client // Contains a map of clients
portSequences [][4]uint16
sharedSecret string // base32 encoded shared secret used for totp
)
func packetServer(captureDevice string) {
clients = make(map[string]*Client, 0) // key is flow, value is the current progress through the sequence. i.e. value of 1 means that the first port in the sequence was successful
portSequences = [][4]uint16{} // Slice of accepted port sequences, there have to be several to account for clock skew between client and server
handle, err := pcap.OpenLive(captureDevice, 1600, true, pcap.BlockForever)
if err != nil {
log.Fatalf("failed to open adapter")
}
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
go rotateSequence(handle)
for packet := range packetSource.Packets() {
handlePacket(packet) // Do something with a packet here.
}
}
// packets that match the BPF filter get passed to handlePacket
func handlePacket(packet gopacket.Packet) {
port := binary.BigEndian.Uint16(packet.TransportLayer().TransportFlow().Dst().Raw())
srcip := packet.NetworkLayer().NetworkFlow().Src().String()
client, ok := clients[srcip]
if !ok { // create the client, identify which authentic knock sequence is matched
for _, sequence := range portSequences {
if port == sequence[0] {
clients[srcip] = &Client{Progress: 1, Sequence: sequence}
}
}
return
}
// if it's wrong, reset progress
// TBD: vulnerable to sweep attack - this won't be triggered if a wrong packet doesn't match BPF filter
if port != client.Sequence[client.Progress] {
delete(clients, srcip)
fmt.Printf("port '%d' is in sequence, but came at unexpected order - resetting progress", port)
return
}
// Client increases progress through sequence and checks if sequence is completed
client.Progress++
if client.Progress >= len(client.Sequence) {
delete(clients, srcip)
handleSuccess(srcip)
return
}
}
// Used to rotate the authentic port knock sequence
func rotateSequence(handle *pcap.Handle) {
for {
if len(portSequences) < 3 {
t := time.Now().Add(time.Second * -30)
for i := 0; i < 3; i++ {
portSequence, err := otphyp.GeneratePorts(sharedSecret, t.Add((time.Second * 30 * time.Duration(i))))
if err != nil {
log.Fatalf("failed to generate port knock sequence: %v", err)
}
portSequences = append(portSequences, portSequence)
}
}
fmt.Println("New sequences:", portSequences)
err := setPacketFilter(handle)
if err != nil {
log.Printf("failed to change packet filter: %v", err)
}
// Sleep until next 30 second offset
time.Sleep(time.Until(time.Now().Truncate(time.Second * 30).Add(time.Second * 30)))
// TBD: pop first value and only generate latest (time.Now().Add(time.Second*30)) value instead of re-initializing completely
portSequences = [][4]uint16{}
}
}
// Given a pcap handle and list of authentic port knock sequences, configures a BPF filter
func setPacketFilter(handle *pcap.Handle) error {
filter := "udp && ("
for i, portSequence := range portSequences {
for j, port := range portSequence {
if i == 0 && j == 0 {
filter += fmt.Sprint("port ", port)
} else {
filter += fmt.Sprint(" || port ", port)
}
}
}
filter += ")"
err := handle.SetBPFFilter(filter)
if err != nil {
return fmt.Errorf("failed to set BPF filter '%s': %v", filter, err)
}
return nil
}