diff --git a/.gitignore b/.gitignore index b177d4a..8d64223 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ build dockerbuild localbuild.sh +config.json +threshold \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..b081af3 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,231 @@ +GNU GENERAL PUBLIC LICENSE +================== + +Version 3, 29 June 2007 + + +Preamble +--------------------- + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +==================== + +## 0. Definitions. +-------------------------------- + + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +## 1. Source Code. +-------------------------------- + + +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +## 2. Basic Permissions. +---------------------------- + + +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +## 3. Protecting Users' Legal Rights From Anti-Circumvention Law. +-------------------------------- + +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +## 4. Conveying Verbatim Copies. +-------------------------------- + +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +## 5. Conveying Modified Source Versions. +-------------------------------- + +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + - a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + - b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + - c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + - d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +## 6. Conveying Non-Source Forms. +-------------------------------- + +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + - a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + - b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + - c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + - d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + - e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +## 7. Additional Terms. +-------------------------------- + +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + - a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + - b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + - c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + - d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + - e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + - f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +## 8. Termination. +-------------------------------- + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +## 9. Acceptance Not Required for Having Copies. +-------------------------------- + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + + +## 10. Automatic Licensing of Downstream Recipients. +-------------------------------- + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +## 11. Patents. +-------------------------------- + +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +## 12. No Surrender of Others' Freedom. +-------------------------------- + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +## 13. Use with the GNU Affero General Public License. +-------------------------------- + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + + +## 14. Revised Versions of this License. +-------------------------------- + +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +## 15. Disclaimer of Warranty. +-------------------------------- + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + +## 16. Limitation of Liability. +-------------------------------- + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +## 17. Interpretation of Sections 15 and 16. +-------------------------------- + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. \ No newline at end of file diff --git a/README.md b/README.md index 4c2b42b..34faaf1 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,39 @@ -## threshold +## threshold 🏔️⛰️🛤️⛰️🏔️ -Public Internet facing gateway (TCP reverse tunnel) for server.garden. +Threshold was created to make self-hosting websites, email, and other services radically easier. -![](threshold.png) +Threshold implements a public-internet-facing gateway (TCP reverse tunnel & SOCKS5 forward proxy) for self-hosted servers. -This project was originally forked from https://github.com/koding/tunnel +The [greenhouse cloud service](https://git.sequentialread.com/forest/greenhouse) was developed in order to make threshold more easily accessible to more people. Greenhouse operates the server side of threshold as a service, charging $0.01 per GB of bandwidth. + +![](readme/splash.png) -It is intended to be used to make it easier for non-tech-savvy people to host web services that are avaliable on the public internet. +Threshold server is designed to be a **relatively untrusted** service, in other words, the user doesn't need to place much trust in the environment where the server runs. It's designed so that the server operator can't spy on you. This makes it uniquely suited to bridge the "ownership vs capability" gap between a self-hosted server/homelab/datacenter and a 3rd-party public cloud environment, hence the name threshold. + +This project was originally forked from https://github.com/koding/tunnel This repository only includes the application that does the tunneling part. It does not include any other management or automation tools. See the usage example folder for a basic test. -![Diagram](readme/Diagram.png) +![Diagram](readme/diagram.png) + +This diagram was created with https://app.diagrams.net/. +To edit it, download the diagram file and edit it with the https://app.diagrams.net/ web application, or you may run the application from [source](https://github.com/jgraph/drawio) if you wish. + ### How it is intended to be used: -1. An automated tool creates a cloud instance and installs and configures the tunnel server on it. -1. An automated tool installs the tunnel client on the self-hoster's server computer. -1. An automated tool calls the `PUT /tunnels` api on the tunnel server's Management Port, and sends a JSON file describing which ports should be opened on the tunnel server, which client they should be tunneled to, and which service on the client they should be tunneled to, as well as whether or not the HAProxy "PROXY" protocol should be used. This connection can use TLS Client Authentication. -1. The tunnel client connects to the tunnel server on the Tunnel Control Port. This connection can use TLS Client Authentication. This connection will be held open and re-created if dropped. -1. An internet user connects to the tunnel server on one of the ports defined in the JSON. The internet user's request is tunneled through the original connection from the tunnel client, and then proxied to the web server software running on the self-hoster's server computer. +1. An automated tool creates a cloud instance and installs and configures the threshold server on it. +1. An automated tool installs the threshold client on the self-hoster's server computer. +1. An automated tool calls the `PUT /tunnels` api on the threshold server's Management Port, and sends a JSON file describing which ports should be opened on the threshold server, which client they should be tunneled to, and which service on the client they should be tunneled to, as well as whether or not the HAProxy "PROXY" protocol should be used. This connection can use TLS Client Authentication. +1. The threshold client connects to the threshold server on the Tunnel Control Port. This connection can use TLS Client Authentication. This connection will be held open and re-created if dropped. +1. An internet user connects to the threshold server on one of the ports defined in the JSON. The internet user's request is tunneled through the original connection from the threshold client, and then proxied to the web server software running on the self-hoster's server computer. +1. (OPTIONAL) The server operator installs software (for example, email server) which requires outgoing requests to "come from" the same IP address that the server is listening for connections at. +1. The email server or other software connects to the threshold client for SOCKS5 forward proxy. The threshold client forwards this connection through the existing tunnel connection to the threshold server (secured by TLS), then the threshold server handles the SOCKS5 connection and proxies it to the destination requested by the email server or other software. +Note: if you wish to easily create server/client key pairs that will work with threshold, see: https://git.sequentialread.com/forest/make-fake-cert ### Output from Usage example showing how it works: @@ -36,7 +47,6 @@ Starting the "listener" test app. It listens on port 9001. This would be your w "DebugLog": false, "TunnelControlPort": 9056, "ManagementPort": 9057, - "UseTls": true, "CaCertificateFile": "InternalCA+chain.crt", "ServerTlsKeyFile": "localhost.key", "ServerTlsCertificateFile": "localhost+chain.crt" @@ -48,11 +58,10 @@ Starting the tunnel client. Client Identifier: TestClient1 2020/08/06 14:00:04 theshold client is starting up using config: { "DebugLog": false, - "ClientIdentifier": "TestClient1", + "ClientId": "TestClient1", "ServerHost": "localhost", "ServerTunnelControlPort": 9056, "ServerManagementPort": 9057, - "UseTls": true, "ServiceToLocalAddrMap": { "fooService": "127.0.0.1:9001" }, @@ -69,7 +78,7 @@ Sending the tunnel configuration to the server. HTTP PUT localhost:9057/tunnels: now listening on 127.0.0.1:9000 -[{"HaProxyProxyProtocol":true,"ListenAddress":"127.0.0.1","ListenHostnameGlob":"*","ListenPort":9000,"BackEndService":"fooService","ClientIdentifier":"TestClient1"}] +[{"HaProxyProxyProtocol":true,"ListenAddress":"127.0.0.1","ListenHostnameGlob":"*","ListenPort":9000,"BackEndService":"fooService","ClientId":"TestClient1"}] Starting the "sender" test app. It connects to the front end port of the tunnel (port 9000). This would be your end user who wants to use the web application. @@ -93,10 +102,10 @@ Note how the listener sees the original source IP and port, not the source IP an I have a few requirements for this system. -* It should be 100% automatable. It is intended to be used in a situation where it is unreasonable to ask the user to configure thier router, for example, they don't know how, they don't want to, or they are not allowed to (For example they live in a dorm where the University manages the network). -* Users have control over their own data. We do not entrust cloud providers or 3rd parties with our data, TLS keys/certificates, etc. In terms of every day usage, this is a TLS connection from an internet user directly to the self-hoster's computer. It is opaque to the cloud provider. - * If the cloud provider wants to launch a Man in the Middle attack, even if they could secretly obtain a trusted cert to use, it will not be easy to hide from the user as long as the user (or software that they installed) is anticipating it. -* It should support Failover/High Avaliability of services. Therefore, it needs to be able to have multiple tunnel clients connected at once, which can be hot-swapped via a Management API. +* It should be 100% automatable. It is intended to be used in a situation where it is unreasonable to ask the user to perform any sort of advanced manual configuration. +* Users have control over their own data. We do not entrust cloud providers or 3rd parties with our data, even those who are hosting our threshold server. TLS keys/certificates, security-relevant configurations, etc only exist on the user-controlled computer. The cloud provider doesn't get access to any information or capability beyond what the user's ISP (Internet Service Provider) would normally have. + * If the cloud provider wants to launch a Man in the Middle attack against the threshold user, they will run into the same problems that an ISP would. +* It should support Failover/High Avaliability of services. Therefore, it needs to be able to have multiple tunnel clients connected at once, which can be hot-swapped via a management API. ### What did you add on top of the koding/tunnel package? @@ -111,15 +120,16 @@ I have a few requirements for this system. * Introduced concept of a "service" string instead of port number, so the client decides what ports to connect to, not the server. * Added support TLS SNI based virtual hosts. (Hostname based routing) * Fixed various bugs related to connection lifecycle. +* Added a tunneled SOCKS5 proxy to support applications like email servers which need to be able to dial out from the same IP address that they recieve connections at. ### How to build ``` -go build -o tunnel -tags netgo +go build -o threshold +``` -# -tags netgo? what? -# this is a work around for dynamic linking on alpine linux -# see: https://stackoverflow.com/questions/36279253/go-compiled-binary-wont-run-in-an-alpine-docker-container-on-ubuntu-host +### How to build the docker image: -docker build -t sequentialread/tunnel:0.0.1 . -``` \ No newline at end of file +``` +./build-docker.sh +``` diff --git a/build.sh b/build.sh index fb1baf9..a72e462 100755 --- a/build.sh +++ b/build.sh @@ -4,7 +4,7 @@ function build() { rm -rf build mkdir build - GOOS=linux GOARCH=$1 go build -o build/threshold + GOOS=linux GOARCH=$1 go build -tags 'osusergo netgo' -ldflags='-extldflags=-static' -o build/threshold sha256sum build/threshold @@ -46,4 +46,4 @@ function build() { build arm build amd64 -build arm64 \ No newline at end of file +#build arm64 \ No newline at end of file diff --git a/go.mod b/go.mod index 3208112..0508931 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,13 @@ -module git.sequentialread.com/forest/tunnel +module git.sequentialread.com/forest/threshold go 1.14 require ( - github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f + git.sequentialread.com/forest/pkg-errors v0.9.2 + github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a + github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/cenkalti/backoff v2.1.0+incompatible github.com/gorilla/websocket v1.4.0 github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d + golang.org/x/net v0.0.0-20210614182718-04defd469f4e ) diff --git a/go.sum b/go.sum index 6e6c8f7..e8a6102 100644 --- a/go.sum +++ b/go.sum @@ -1,10 +1,19 @@ -git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf h1:2flo/nnhfe3sSxQ/MHlK7KoY54tQ1pAvMzkh0ZOxyH4= -git.sequentialread.com/forest/tunnel v0.0.0-20170601195443-35a8b95662bf/go.mod h1:i+PvDDsWjggoCQOO8bGJJKRB9qfxmHk5yzIEA/h8dzg= -github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f h1:SaJ6yqg936TshyeFZqQE+N+9hYkIeL9AMr7S4voCl10= -github.com/armon/go-proxyproto v0.0.0-20180202201750-5b7edb60ff5f/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= +git.sequentialread.com/forest/pkg-errors v0.9.2 h1:j6pwbL6E+TmE7TD0tqRtGwuoCbCfO6ZR26Nv5nest9g= +git.sequentialread.com/forest/pkg-errors v0.9.2/go.mod h1:8TkJ/f8xLWFIAid20aoqgDZcCj9QQt+FU+rk415XO1w= +github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a h1:AP/vsCIvJZ129pdm9Ek7bH7yutN3hByqsMoNrWAxRQc= +github.com/armon/go-proxyproto v0.0.0-20210323213023-7e956b284f0a/go.mod h1:QmP9hvJ91BbJmGVGSbutW19IC0Q9phDCLGaomwTJbgU= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/cenkalti/backoff v2.1.0+incompatible h1:FIRvWBZrzS4YC7NT5cOuZjexzFvIr+Dbi6aD1cZaNBk= github.com/cenkalti/backoff v2.1.0+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ= github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e h1:XpT3nA5TvE525Ne3hInMh6+GETgn27Zfm9dxsThnX2Q= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/main.go b/main.go index e44fd46..5dbb7ca 100644 --- a/main.go +++ b/main.go @@ -1,54 +1,16 @@ package main import ( - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/json" - "errors" "flag" "fmt" - "io" "io/ioutil" "log" - "net" - "net/http" "os" - "path" - "path/filepath" - "strings" - "sync" - "time" - - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + "strconv" ) -type ServerConfig struct { - DebugLog bool - ListenPort int - - // Domain is only used for validating the TLS client certificates - // when TLS is used. the cert's Subject CommonName is expected to be @ - // I did this because I believe this is a standard for TLS client certs, - // based on domain users/email addresses. - Domain string - - UseTls bool - CaCertificateFilesGlob string - ServerTlsKeyFile string - ServerTlsCertificateFile string -} - -type ClientConfig struct { - DebugLog bool - ClientIdentifier string - ServerAddr string - UseTls bool - ServiceToLocalAddrMap *map[string]string - CaCertificateFilesGlob string - ClientTlsKeyFile string - ClientTlsCertificateFile string - AdminUnixSocket string +type MetricsConfig struct { + PrometheusMetricsAPIPort int } type ListenerConfig struct { @@ -57,37 +19,9 @@ type ListenerConfig struct { ListenHostnameGlob string ListenPort int BackEndService string - ClientIdentifier string -} - -type ClientState struct { - CurrentState string - LastState string -} - -type ManagementHttpHandler struct { - ControlHandler http.Handler + ClientId string } -type LiveConfigUpdate struct { - Listeners []ListenerConfig - ServiceToLocalAddrMap map[string]string -} - -type adminAPI struct{} - -// Server State -var listeners []ListenerConfig -var clientStatesMutex = &sync.Mutex{} -var clientStates map[string]ClientState -var server *tunnel.Server - -// Client State -var client *tunnel.Client -var tlsClientConfig *tls.Config -var serverURL *string -var serviceToLocalAddrMap *map[string]string - func main() { mode := flag.String("mode", "", "Run client or server application. Allowed values: [client,server]") @@ -107,448 +41,6 @@ func main() { } -// admin api handler for /liveconfig over unix socket -func (handler adminAPI) ServeHTTP(response http.ResponseWriter, request *http.Request) { - switch path.Clean(request.URL.Path) { - case "/liveconfig": - if request.Method == "PUT" { - requestBytes, err := ioutil.ReadAll(request.Body) - if err != nil { - log.Printf("adminAPI: request read error: %+v\n\n", err) - http.Error(response, "500 request read error", http.StatusInternalServerError) - return - } - var configUpdate LiveConfigUpdate - err = json.Unmarshal(requestBytes, &configUpdate) - if err != nil { - log.Printf("adminAPI: can't parse JSON: %+v\n\n", err) - http.Error(response, "400 bad request: can't parse JSON", http.StatusBadRequest) - return - } - - sendBytes, err := json.Marshal(configUpdate.Listeners) - if err != nil { - log.Printf("adminAPI: Listeners json serialization failed: %+v\n\n", err) - http.Error(response, "500 Listeners json serialization failed", http.StatusInternalServerError) - return - } - apiURL := fmt.Sprintf("https://%s/tunnels", *serverURL) - tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) - if err != nil { - log.Printf("adminAPI: error creating tunnels request: %+v\n\n", err) - http.Error(response, "500 error creating tunnels request", http.StatusInternalServerError) - return - } - tunnelsRequest.Header.Add("content-type", "application/json") - - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsClientConfig, - }, - Timeout: 10 * time.Second, - } - tunnelsResponse, err := client.Do(tunnelsRequest) - if err != nil { - log.Printf("adminAPI: Do(tunnelsRequest): %+v\n\n", err) - http.Error(response, "502 tunnels request failed", http.StatusBadGateway) - return - } - tunnelsResponseBytes, err := ioutil.ReadAll(tunnelsResponse.Body) - if err != nil { - log.Printf("adminAPI: tunnelsResponse read error: %+v\n\n", err) - http.Error(response, "502 tunnelsResponse read error", http.StatusBadGateway) - return - } - - if tunnelsResponse.StatusCode != http.StatusOK { - log.Printf( - "adminAPI: tunnelsRequest returned HTTP %d: %s\n\n", - tunnelsResponse.StatusCode, string(tunnelsResponseBytes), - ) - http.Error( - response, - fmt.Sprintf("502 tunnels request returned HTTP %d", tunnelsResponse.StatusCode), - http.StatusBadGateway, - ) - return - } - - serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap - - response.Header().Add("content-type", "application/json") - response.WriteHeader(http.StatusOK) - response.Write(tunnelsResponseBytes) - - } else { - response.Header().Set("Allow", "PUT") - http.Error(response, "405 method not allowed, try PUT", http.StatusMethodNotAllowed) - } - default: - http.Error(response, "404 not found, try PUT /liveconfig", http.StatusNotFound) - } - -} - -func runClient(configFileName *string) { - - configBytes := getConfigBytes(configFileName) - - var config ClientConfig - err := json.Unmarshal(configBytes, &config) - if err != nil { - log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) - } - serviceToLocalAddrMap = config.ServiceToLocalAddrMap - serverURL = &config.ServerAddr - - configToLog, _ := json.MarshalIndent(config, "", " ") - log.Printf("theshold client is starting up using config:\n%s\n", string(configToLog)) - - dialFunction := net.Dial - - if config.UseTls { - - cert, err := tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) - if err != nil { - log.Fatal(err) - } - - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) - if err != nil { - log.Fatal(err) - } - - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - caCert, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - } - - tlsClientConfig = &tls.Config{ - Certificates: []tls.Certificate{cert}, - RootCAs: caCertPool, - } - tlsClientConfig.BuildNameToCertificate() - - dialFunction = func(network, address string) (net.Conn, error) { - return tls.Dial(network, address, tlsClientConfig) - } - } - - clientStateChanges := make(chan *tunnel.ClientStateChange) - tunnelClientConfig := &tunnel.ClientConfig{ - DebugLog: config.DebugLog, - Identifier: config.ClientIdentifier, - ServerAddr: config.ServerAddr, - FetchLocalAddr: func(service string) (string, error) { - //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) - localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] - if !hasLocalAddr { - return "", errors.New("service not configured. See ServiceToLocalAddrMap in client config file.") - } - return localAddr, nil - }, - Dial: dialFunction, - StateChanges: clientStateChanges, - } - - client, err = tunnel.NewClient(tunnelClientConfig) - if err != nil { - log.Fatalf("runClient(): can't create tunnel client because %s \n", err) - } - - go (func() { - for { - stateChange := <-clientStateChanges - fmt.Printf("clientStateChange: %s\n", stateChange.String()) - } - })() - - go runClientAdminApi(config) - - fmt.Print("runClient(): the client should be running now\n") - client.Start() - -} - -func runClientAdminApi(config ClientConfig) { - - os.Remove(config.AdminUnixSocket) - - listenAddress, err := net.ResolveUnixAddr("unix", config.AdminUnixSocket) - if err != nil { - panic(fmt.Sprintf("runClient(): can't start because net.ResolveUnixAddr() returned %+v", err)) - } - - listener, err := net.ListenUnix("unix", listenAddress) - if err != nil { - panic(fmt.Sprintf("can't start because net.ListenUnix() returned %+v", err)) - } - log.Printf("AdminUnixSocket Listening: %v\n\n", config.AdminUnixSocket) - defer listener.Close() - - server := http.Server{ - Handler: adminAPI{}, - ReadTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, - } - - err = server.Serve(listener) - if err != nil { - panic(fmt.Sprintf("AdminUnixSocket server returned %+v", err)) - } -} - -func runServer(configFileName *string) { - - configBytes := getConfigBytes(configFileName) - - var config ServerConfig - err := json.Unmarshal(configBytes, &config) - if err != nil { - fmt.Printf("runServer(): can't json.Unmarshal(configBytes, &config) because %s \n", err) - os.Exit(1) - } - - configToLog, _ := json.MarshalIndent(config, "", " ") - log.Printf("threshold server is starting up using config:\n%s\n", string(configToLog)) - - clientStateChangeChannel := make(chan *tunnel.ClientStateChange) - - tunnelServerConfig := &tunnel.ServerConfig{ - StateChanges: clientStateChangeChannel, - Domain: config.Domain, - DebugLog: config.DebugLog, - } - server, err = tunnel.NewServer(tunnelServerConfig) - if err != nil { - fmt.Printf("runServer(): can't create tunnel server because %s \n", err) - os.Exit(1) - } - - clientStates = make(map[string]ClientState) - go (func() { - for { - clientStateChange := <-clientStateChangeChannel - clientStatesMutex.Lock() - previousState := "" - currentState := clientStateChange.Current.String() - fromMap, wasInMap := clientStates[clientStateChange.Identifier] - if wasInMap { - previousState = fromMap.CurrentState - } else { - previousState = clientStateChange.Previous.String() - } - if clientStateChange.Error != nil && clientStateChange.Error != io.EOF { - log.Printf("runServer(): recieved a client state change with an error: %s \n", clientStateChange.Error) - currentState = "ClientError" - } - clientStates[clientStateChange.Identifier] = ClientState{ - CurrentState: currentState, - LastState: previousState, - } - clientStatesMutex.Unlock() - } - })() - - if config.UseTls { - - certificates, err := filepath.Glob(config.CaCertificateFilesGlob) - if err != nil { - log.Fatal(err) - } - - caCertPool := x509.NewCertPool() - for _, filename := range certificates { - log.Printf("loading certificate %s, clients who have a key signed by this certificat will be allowed to connect", filename) - caCert, err := ioutil.ReadFile(filename) - if err != nil { - log.Fatal(err) - } - caCertPool.AppendCertsFromPEM(caCert) - } - - tlsConfig := &tls.Config{ - ClientCAs: caCertPool, - ClientAuth: tls.RequireAndVerifyClientCert, - } - tlsConfig.BuildNameToCertificate() - - httpsManagementServer := &http.Server{ - Addr: fmt.Sprintf(":%d", config.ListenPort), - TLSConfig: tlsConfig, - Handler: &(ManagementHttpHandler{ControlHandler: server}), - } - - log.Print("runServer(): the server should be running now\n") - err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) - panic(err) - } else { - - log.Print("runServer(): the server should be running now\n") - err = http.ListenAndServe(fmt.Sprintf(":%d", config.ListenPort), &(ManagementHttpHandler{ControlHandler: server})) - panic(err) - } - -} - -func setListeners(listenerConfigs []ListenerConfig) (int, string) { - currentListenersThatCanKeepRunning := make([]ListenerConfig, 0) - newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) - - for _, newListenerConfig := range listenerConfigs { - clientState, everHeardOfClientBefore := clientStates[newListenerConfig.ClientIdentifier] - if !everHeardOfClientBefore { - return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientIdentifier) - } - if clientState.CurrentState != tunnel.ClientConnected.String() { - return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientIdentifier, clientState.CurrentState) - } - } - - for _, existingListener := range listeners { - canKeepRunning := false - for _, newListenerConfig := range listenerConfigs { - if compareListenerConfigs(existingListener, newListenerConfig) { - canKeepRunning = true - } - } - - if !canKeepRunning { - listenAddress := net.ParseIP(existingListener.ListenAddress) - if listenAddress == nil { - return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", existingListener.ListenAddress) - } - - server.DeleteAddr(listenAddress, existingListener.ListenPort, existingListener.ListenHostnameGlob) - - } else { - currentListenersThatCanKeepRunning = append(currentListenersThatCanKeepRunning, existingListener) - } - } - - for _, newListenerConfig := range listenerConfigs { - hasToBeAdded := true - for _, existingListener := range listeners { - if compareListenerConfigs(existingListener, newListenerConfig) { - hasToBeAdded = false - } - } - - if hasToBeAdded { - listenAddress := net.ParseIP(newListenerConfig.ListenAddress) - //fmt.Printf("str: %s, listenAddress: %s\n\n", newListenerConfig.ListenAddress, listenAddress) - if listenAddress == nil { - return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", newListenerConfig.ListenAddress) - } - err := server.AddAddr( - listenAddress, - newListenerConfig.ListenPort, - newListenerConfig.ListenHostnameGlob, - newListenerConfig.ClientIdentifier, - newListenerConfig.HaProxyProxyProtocol, - newListenerConfig.BackEndService, - ) - - if err != nil { - if strings.Contains(err.Error(), "already in use") { - return http.StatusConflict, fmt.Sprintf("Port Conflict Port %s already in use", listenAddress) - } - - log.Printf("setListeners(): can't net.Listen(\"tcp\", \"%s\") because %s \n", listenAddress, err) - return http.StatusInternalServerError, "Unknown Listening Error" - } - - newListenersThatHaveToBeAdded = append(newListenersThatHaveToBeAdded, newListenerConfig) - } - } - - listeners = append(currentListenersThatCanKeepRunning, newListenersThatHaveToBeAdded...) - - return http.StatusOK, "ok" - -} - -func compareListenerConfigs(a, b ListenerConfig) bool { - return (a.ListenPort == b.ListenPort && - a.ListenAddress == b.ListenAddress && - a.ListenHostnameGlob == b.ListenHostnameGlob && - a.BackEndService == b.BackEndService && - a.ClientIdentifier == b.ClientIdentifier && - a.HaProxyProxyProtocol == b.HaProxyProxyProtocol) -} - -func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { - - switch path.Clean(request.URL.Path) { - case "/clients": - if request.Method == "GET" { - clientStatesMutex.Lock() - bytes, err := json.Marshal(clientStates) - clientStatesMutex.Unlock() - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) - - } else { - responseWriter.Header().Set("Allow", "PUT") - http.Error(responseWriter, "405 Method Not Allowed", http.StatusMethodNotAllowed) - } - case "/tunnels": - if request.Method == "PUT" { - if request.Header.Get("Content-Type") != "application/json" { - http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) - } else { - bodyBytes, err := ioutil.ReadAll(request.Body) - if err != nil { - http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) - return - } - var listenerConfigs []ListenerConfig - err = json.Unmarshal(bodyBytes, &listenerConfigs) - if err != nil { - http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) - return - } - - statusCode, errorMessage := setListeners(listenerConfigs) - - if statusCode != 200 { - http.Error(responseWriter, errorMessage, statusCode) - return - } - - bytes, err := json.Marshal(listenerConfigs) - if err != nil { - http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) - return - } - - responseWriter.Header().Set("Content-Type", "application/json") - responseWriter.Write(bytes) - } - } else { - responseWriter.Header().Set("Allow", "PUT") - http.Error(responseWriter, "405 Method Not Allowed", http.StatusMethodNotAllowed) - } - case "/ping": - if request.Method == "GET" { - fmt.Fprint(responseWriter, "pong") - } else { - responseWriter.Header().Set("Allow", "GET") - http.Error(responseWriter, "405 method not allowed", http.StatusMethodNotAllowed) - } - default: - s.ControlHandler.ServeHTTP(responseWriter, request) - } -} - func getConfigBytes(configFileName *string) []byte { if configFileName != nil { configBytes, err := ioutil.ReadFile(*configFileName) @@ -563,3 +55,19 @@ func getConfigBytes(configFileName *string) []byte { return nil } } + +func intSlice2StringSlice(slice []int) []string { + toReturn := make([]string, len(slice)) + for i, integer := range slice { + toReturn[i] = strconv.Itoa(integer) + } + return toReturn +} + +func stringSliceMap(slice []string, mapper func(string) string) []string { + toReturn := make([]string, len(slice)) + for i, str := range slice { + toReturn[i] = mapper(str) + } + return toReturn +} diff --git a/main_client.go b/main_client.go new file mode 100644 index 0000000..e4550bf --- /dev/null +++ b/main_client.go @@ -0,0 +1,897 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/binary" + "encoding/json" + "fmt" + "io/ioutil" + "log" + "math/big" + "net" + "net/http" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "time" + + errors "git.sequentialread.com/forest/pkg-errors" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" + proxyprotocol "github.com/armon/go-proxyproto" + "golang.org/x/net/proxy" +) + +type ClientConfig struct { + DebugLog bool + ClientId string + GreenhouseDomain string + GreenhouseAPIToken string + GreenhouseThresholdPort int + + // Theshold client will listen for SOCKS5 connections on the specified port (for example, "127.0.0.1:1080") + // and tunnel them to the threshold server, where the server will handle the SOCKS5 CONNECT requests + // and proxy the connections. Use this for hosting email servers or any other server where Outbound + // connections have to come from the same IP address which is used for Inbound connections + TunneledOutboundSOCKS5ListenAddress string + + MaximumConnectionRetrySeconds int + ServerAddr string + Servers []string + DefaultTunnels *LiveConfigUpdate + CaCertificateFilesGlob string + ClientTlsKeyFile string + ClientTlsCertificateFile string + CaCertificate string + ClientTlsKey string + ClientTlsCertificate string + + // Use this when a local proxy is required for threshold client (this app) to talk to the threshold server. + // For example, if a firewall or other hostile network environment might otherwise prevent you from connecting. + // This would be the address of an external 3rd party SOCKS5 proxy server that is reachable from your computer. + // If you set the hostname to "gateway", like "HostileNetworkEnvironmentEvasionSOCKS5Address": "gateway:1080" + // then it will try to SOCKS5 connect to any/all default gateways (routers) on the given port (1080 in this case). + HostileNetworkEnvironmentEvasionSOCKS5Address string + + AdminUnixSocket string + AdminAPIPort int + AdminAPICACertificateFile string + AdminAPITlsKeyFile string + AdminAPITlsCertificateFile string + Metrics MetricsConfig +} + +type ClientServer struct { + Client *tunnel.Client + ServerUrl *url.URL + ServerHostPort string +} + +type LiveConfigUpdate struct { + Listeners []ListenerConfig + ServiceToLocalAddrMap map[string]string +} + +type ThresholdTenantInfo struct { + ThresholdServers []string +} + +type maximumBackoff struct { + Maximum time.Duration + Base tunnel.Backoff +} + +func (bo *maximumBackoff) NextBackOff() time.Duration { + result := bo.Base.NextBackOff() + if result > bo.Maximum { + return bo.Maximum + } + return result +} + +func (bo *maximumBackoff) Reset() { + bo.Base.Reset() +} + +type clientAdminAPI struct{} + +// Client State +var clientServers []ClientServer +var tlsClientConfig *tls.Config +var serviceToLocalAddrMap *map[string]string + +var isTestMode bool +var testModeListeners map[string]ListenerConfig +var testModeTLSConfig *tls.Config +var testTokens []string + +func runClient(configFileName *string) { + + configBytes := getConfigBytes(configFileName) + + var config ClientConfig + err := json.Unmarshal(configBytes, &config) + if err != nil { + log.Fatalf("runClient(): can't json.Unmarshal(configBytes, &config) because %s \n", err) + } + + if config.GreenhouseThresholdPort == 0 { + config.GreenhouseThresholdPort = 9056 + } + var forwardProxyListener *net.TCPListener + if config.TunneledOutboundSOCKS5ListenAddress != "" { + tunneledOutboundSOCKS5ListenAddress, err := net.ResolveTCPAddr("tcp", config.TunneledOutboundSOCKS5ListenAddress) + if err != nil { + log.Fatalf("runClient(): can't net.ResolveTCPAddr(TunneledOutboundSOCKS5ListenAddress) because %s \n", err) + } + forwardProxyListener, err = net.ListenTCP("tcp", tunneledOutboundSOCKS5ListenAddress) + if err != nil { + log.Fatalf("runClient(): can't net.ListenTCP(\"tcp\", TunneledOutboundSOCKS5ListenAddress) because %s \n", err) + } + } + + clientServers = []ClientServer{} + makeServer := func(hostPort string) ClientServer { + serverURLString := fmt.Sprintf("https://%s", hostPort) + serverURL, err := url.Parse(serverURLString) + if err != nil { + log.Fatal(fmt.Errorf("failed to parse the ServerAddr (prefixed with https://) '%s' as a url", serverURLString)) + } + return ClientServer{ + ServerHostPort: hostPort, + ServerUrl: serverURL, + } + } + + serverListToLog := "" + + if config.GreenhouseDomain != "" { + if config.ServerAddr != "" { + log.Fatal("config contains both GreenhouseDomain and ServerAddr, only use one or the other") + } + if config.Servers != nil && len(config.Servers) > 0 { + log.Fatal("config contains both GreenhouseDomain and Servers, only use one or the other") + } + if config.GreenhouseAPIToken == "" { + log.Fatal("config contains GreenhouseDomain but does not contain GreenhouseAPIToken, use both or niether") + } + + greenhouseClient := http.Client{Timeout: time.Second * 10} + greenhouseURL := fmt.Sprintf("https://%s/api/tenant_info", config.GreenhouseDomain) + request, err := http.NewRequest("GET", greenhouseURL, nil) + if err != nil { + log.Fatal("invalid GreenhouseDomain '%s', can't create http request for %s", config.GreenhouseDomain, greenhouseURL) + } + request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", config.GreenhouseAPIToken)) + + hostPortStringsToLog := []string{} + response, err := greenhouseClient.Do(request) + if err != nil || response.StatusCode != 200 { + if err == nil { + if response.StatusCode == 401 { + log.Printf("bad or expired GreenhouseAPIToken, recieved HTTP 401 Unauthorized from Greenhouse server %s", greenhouseURL) + } else { + log.Printf("recieved HTTP %d from Greenhouse server %s", response.StatusCode, greenhouseURL) + } + } else { + log.Printf("Greenhouse server %s could not be reached: %s", greenhouseURL, err) + } + log.Printf("falling back to DNS lookup on '%s'...\n", greenhouseURL) + + // TODO for _, tunnel := range config.DefaultTunnels + ips, err := net.LookupIP(config.GreenhouseDomain) + if err != nil { + log.Fatalf("Failed to lookup GreenhouseDomain '%s'", config.GreenhouseDomain) + } + for _, ip := range ips { + serverHostPort := fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort) + clientServers = append(clientServers, makeServer(serverHostPort)) + hostPortStringsToLog = append(hostPortStringsToLog, serverHostPort) + } + } else { + responseBytes, err := ioutil.ReadAll(response.Body) + if err != nil { + log.Fatal("http read error GET '%s'", greenhouseURL) + } + var tenantInfo ThresholdTenantInfo + err = json.Unmarshal(responseBytes, &tenantInfo) + if err != nil { + log.Fatal("http read error GET '%s'", greenhouseURL) + } + + for _, serverHostPort := range tenantInfo.ThresholdServers { + ip := strings.Split(serverHostPort, ":")[0] + serverHostPort = fmt.Sprintf("%s:%d", ip, config.GreenhouseThresholdPort) + clientServers = append(clientServers, makeServer(serverHostPort)) + hostPortStringsToLog = append(hostPortStringsToLog, serverHostPort) + } + } + + serverListToLog = fmt.Sprintf("%s (%s)", config.GreenhouseDomain, strings.Join(hostPortStringsToLog, ", ")) + + } else if config.Servers != nil && len(config.Servers) > 0 { + if config.ServerAddr != "" { + log.Fatal("config contains both Servers and ServerAddr, only use one or the other") + } + for _, serverHostPort := range config.Servers { + clientServers = append(clientServers, makeServer(serverHostPort)) + } + serverListToLog = fmt.Sprintf("[%s]", strings.Join(config.Servers, ", ")) + } else { + clientServers = []ClientServer{makeServer(config.ServerAddr)} + serverListToLog = config.ServerAddr + } + + if config.DefaultTunnels != nil { + serviceToLocalAddrMap = &config.DefaultTunnels.ServiceToLocalAddrMap + } else { + serviceToLocalAddrMap = &(map[string]string{}) + } + + configToLog, _ := json.MarshalIndent(config, "", " ") + configToLogString := string(configToLog) + + configToLogString = regexp.MustCompile( + `("GreenhouseAPIToken": ")[^"]+(",)`, + ).ReplaceAllString( + configToLogString, + "$1******$2", + ) + configToLogString = regexp.MustCompile( + `("(CaCertificate|ClientTlsKey|ClientTlsCertificate)": "[^"]{27})[^"]+([^"]{27}")`, + ).ReplaceAllString( + configToLogString, + "$1 blahblahPEMblahblah $3", + ) + + log.Printf("theshold client is starting up using config:\n%s\n", configToLogString) + + var proxyDialer proxy.Dialer = nil + dialFunction := net.Dial + + if config.HostileNetworkEnvironmentEvasionSOCKS5Address != "" { + proxyDialer, err = getProxyDialer(config.HostileNetworkEnvironmentEvasionSOCKS5Address) + if err != nil { + log.Fatalf("can't start because can't getProxyDialer(): %+v", err) + } + dialFunction = func(network, address string) (net.Conn, error) { + var err error + if proxyDialer == nil { + proxyDialer, err = getProxyDialer(config.HostileNetworkEnvironmentEvasionSOCKS5Address) + if err != nil { + return nil, errors.Wrap(err, "dialFunction failed to recreate proxyDialer: ") + } + } + + // if it fails, set it to null so it will be re-created // TODO test this and verify it actually works 0__0 + conn, err := proxyDialer.Dial(network, address) + if err != nil { + proxyDialer = nil + } + return conn, err + } + } + + var cert tls.Certificate + hasFiles := config.ClientTlsCertificateFile != "" && config.ClientTlsKeyFile != "" + hasLiterals := config.ClientTlsCertificate != "" && config.ClientTlsKey != "" + if hasFiles && !hasLiterals { + cert, err = tls.LoadX509KeyPair(config.ClientTlsCertificateFile, config.ClientTlsKeyFile) + if err != nil { + log.Fatalf("can't start because tls.LoadX509KeyPair returned: \n%+v\n", err) + } + } else if !hasFiles && hasLiterals { + cert, err = tls.X509KeyPair([]byte(config.ClientTlsCertificate), []byte(config.ClientTlsKey)) + if err != nil { + log.Fatalf("can't start because tls.X509KeyPair returned: \n%+v\n", err) + } + + } else { + log.Fatal("one or the other (not both) of ClientTlsCertificateFile+ClientTlsKeyFile or ClientTlsCertificate+ClientTlsKey is required\n") + } + + parsedCert, err := x509.ParseCertificate(cert.Certificate[0]) + if err != nil { + log.Fatal(err) + } + + if parsedCert == nil { + log.Fatalf("parsedCert is nil (%s)", config.ClientTlsCertificateFile) + } + commonName := parsedCert.Subject.CommonName + clientIdDomain := strings.Split(commonName, "@") + + if len(clientIdDomain) != 2 { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '@'", commonName, + )) + } + + // This is enforced by the server anyways, so no need to enforce it here. + // This allows server URLs to use IP addresses, don't require DNS. + // if clientIdDomain[1] != serverURL.Hostname() { + // log.Fatal(fmt.Errorf( + // "expected TLS client certificate common name domain '%s' to match ServerAddr domain '%s'", + // clientIdDomain[1], serverURL.Hostname(), + // )) + // } + + if clientIdDomain[0] != config.ClientId { + log.Fatal(fmt.Errorf( + "expected TLS client certificate common name clientId '%s' to match ClientId '%s'", + clientIdDomain[0], config.ClientId, + )) + } + + caCertPool := x509.NewCertPool() + if config.CaCertificateFilesGlob != "" && config.CaCertificate == "" { + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + if err != nil { + log.Fatal(err) + } + + for _, filename := range certificates { + caCert, err := ioutil.ReadFile(filename) + if err != nil { + log.Fatal(err) + } + ok := caCertPool.AppendCertsFromPEM(caCert) + if !ok { + log.Fatalf("Failed to add CA certificate '%s' to cert pool\n", filename) + } + } + } else if config.CaCertificateFilesGlob == "" && config.CaCertificate != "" { + ok := caCertPool.AppendCertsFromPEM([]byte(config.CaCertificate)) + if !ok { + log.Fatal("Failed to add config.CaCertificate to cert pool\n") + } + } else { + log.Fatal("one or the other (not both) of CaCertificateFilesGlob or CaCertificate is required\n") + } + + tlsClientConfig = &tls.Config{ + Certificates: []tls.Certificate{cert}, + RootCAs: caCertPool, + } + tlsClientConfig.BuildNameToCertificate() + + // wrap whatever dial function we have right now with TLS. + existingDialFunction := dialFunction + dialFunction = func(network, address string) (net.Conn, error) { + conn, err := existingDialFunction(network, address) + if err != nil { + return nil, err + } + + addressSplit := strings.Split(address, ":") + + // log.Printf("ASD!! LEN: %d\n", len(tlsClientConfig.Certificates)) + // if len(tlsClientConfig.Certificates) > 0 { + // for i, cert := range tlsClientConfig.Certificates { + + // log.Printf("cert[%d]\n", i) + + // if cert.Leaf != nil { + // bytez := pem.EncodeToMemory(&pem.Block{ + // Bytes: cert.Leaf.Raw, + // Type: "CERTIFICATE", + // }) + // log.Printf("cert[%d].Leaf.Raw:\n%s\n\n", i, bytez) + // } + // if cert.Certificate != nil { + // for j, bytez := range cert.Certificate { + // bytez2 := pem.EncodeToMemory(&pem.Block{ + // Bytes: bytez, + // Type: "CERTIFICATE", + // }) + // log.Printf("cert[%d][%d].Raw:\n%s\n\n", i, j, bytez2) + // } + // } + // } + // } + + tlsConn := tls.Client(conn, &tls.Config{ + ServerName: addressSplit[0], + Certificates: tlsClientConfig.Certificates, + RootCAs: tlsClientConfig.RootCAs, + }) + err = tlsConn.Handshake() + if err != nil { + log.Printf("tlsConn.Handshake() ERROR %+v\n", err) + return nil, err + } + return tlsConn, nil + } + + go runClientAdminApi(config) + + fetchLocalAddr := func(service string) (string, error) { + //log.Printf("(*serviceToLocalAddrMap): %+v\n\n", (*serviceToLocalAddrMap)) + localAddr, hasLocalAddr := (*serviceToLocalAddrMap)[service] + if !hasLocalAddr { + return "", fmt.Errorf("service '%s' not configured. Set ServiceToLocalAddrMap in client config file or HTTP PUT /liveconfig over the admin api.", service) + } + return localAddr, nil + } + + productionProxyFunc := (&tunnel.TCPProxy{ + FetchLocalAddr: fetchLocalAddr, + DebugLog: config.DebugLog, + }).Proxy + + proxyFunc := func(remote net.Conn, msg *proto.ControlMessage) { + if isTestMode { + handleTestConnection(remote, msg) + } else { + productionProxyFunc(remote, msg) + } + } + + maximumConnectionRetrySeconds := 60 + if config.MaximumConnectionRetrySeconds != 0 { + maximumConnectionRetrySeconds = config.MaximumConnectionRetrySeconds + } + for i, server := range clientServers { + // make a separate backoff instance for each server. + myBackoff := maximumBackoff{ + Maximum: time.Second * time.Duration(maximumConnectionRetrySeconds), + Base: tunnel.NewExponentialBackoff(), + } + clientStateChanges := make(chan *tunnel.ClientStateChange) + tunnelClientConfig := &tunnel.ClientConfig{ + DebugLog: config.DebugLog, + Identifier: config.ClientId, + ServerAddr: server.ServerHostPort, + FetchLocalAddr: fetchLocalAddr, + Proxy: proxyFunc, + Dial: dialFunction, + StateChanges: clientStateChanges, + Backoff: &myBackoff, + } + + client, err := tunnel.NewClient(tunnelClientConfig) + if err != nil { + log.Fatalf("runClient(): can't create tunnel client for %s because %v \n", server.ServerHostPort, err) + } + + go (func() { + for { + stateChange := <-clientStateChanges + log.Printf("%s clientStateChange: %s\n", server.ServerHostPort, stateChange.String()) + if config.DefaultTunnels != nil && stateChange.Current == tunnel.ClientConnected { + go (func() { + failed := true + for failed { + err := updateListenersOnServer(config.DefaultTunnels.Listeners) + if err != nil { + log.Printf("DefaultTunnels: failed to updateListenersOnServer(): %+v\nRetrying in 5 seconds...\n", err) + time.Sleep(time.Second * 5) + } else { + failed = false + } + } + })() + } + } + })() + + server.Client = client + clientServers[i] = server + go server.Client.Start() + } + + log.Printf( + "runClient(): the threshold client should be running now 🏔️⛰️🛤️⛰️🏔️ \n connecting to %s... \n", + serverListToLog, + ) + + if forwardProxyListener != nil { + log.Printf( + "runClient(): I am listening on %s for SOCKS5 forward proxy \n", + config.TunneledOutboundSOCKS5ListenAddress, + ) + + for { + conn, err := forwardProxyListener.Accept() + if err != nil { + log.Printf("Can't accept incoming connection: forwardProxyListener.Accept() returned %s\n", err) + } + + // TODO better way of determining which one to use for forward proxy. + // log.Printf("clientServers: %+v, clientServers[0]: %+v\n", clientServers, clientServers[0]) + err = clientServers[0].Client.HandleForwardProxy(conn) + if err != nil { + log.Printf("Can't accept incoming connection %s -> %s because %s\n", conn.RemoteAddr, conn.LocalAddr, err) + } + } + } else { + waitForever := make(chan bool) + <-waitForever + } +} + +func runClientAdminApi(config ClientConfig) { + + var listener net.Listener + if config.AdminUnixSocket != "" && config.AdminAPIPort == 0 { + os.Remove(config.AdminUnixSocket) + + listenAddress, err := net.ResolveUnixAddr("unix", config.AdminUnixSocket) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ResolveUnixAddr() returned %+v", err)) + } + + listener, err = net.ListenUnix("unix", listenAddress) + if err != nil { + panic(fmt.Sprintf("can't start because net.ListenUnix() returned %+v", err)) + } + log.Printf("AdminUnixSocket Listening: %v\n\n", config.AdminUnixSocket) + defer listener.Close() + } else if config.AdminUnixSocket == "" && config.AdminAPIPort != 0 { + addrString := fmt.Sprintf("127.0.0.1:%d", config.AdminAPIPort) + addr, err := net.ResolveTCPAddr("tcp", addrString) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ResolveTCPAddr(%s) returned %+v", addrString, err)) + } + tcpListener, err := net.ListenTCP("tcp", addr) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because net.ListenTCP(%s) returned %+v", addrString, err)) + } + + caCertPool := x509.NewCertPool() + caCertBytes, err := ioutil.ReadFile(config.AdminAPICACertificateFile) + if err != nil { + panic(fmt.Sprintf("runClient(): can't start because ioutil.ReadFile(%s) returned %+v", config.AdminAPICACertificateFile, err)) + } + caCertPool.AppendCertsFromPEM(caCertBytes) + + tlsCert, err := tls.LoadX509KeyPair(config.AdminAPITlsCertificateFile, config.AdminAPITlsKeyFile) + if err != nil { + panic(fmt.Sprintf( + "runClient(): can't start because tls.LoadX509KeyPair(%s,%s) returned %+v", + config.AdminAPITlsCertificateFile, config.AdminAPITlsKeyFile, err, + )) + } + + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{tlsCert}, + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + listener = tls.NewListener(tcpListener, tlsConfig) + } else if config.AdminUnixSocket != "" && config.AdminAPIPort != 0 { + log.Fatal("One or the other (and not both) of AdminUnixSocket or AdminAPIPort is required") + return + } else if config.AdminUnixSocket == "" && config.AdminAPIPort == 0 { + return + } + + server := http.Server{ + Handler: clientAdminAPI{}, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + } + + err := server.Serve(listener) + if err != nil { + panic(fmt.Sprintf("Admin API server returned %+v", err)) + } +} + +// client admin api handler for /liveconfig over unix socket +func (handler clientAdminAPI) ServeHTTP(response http.ResponseWriter, request *http.Request) { + switch path.Clean(request.URL.Path) { + case "/start_test": + isTestMode = true + testTokens = []string{} + if testModeTLSConfig == nil { + certificate, err := GenerateTestX509Cert() + if err != nil { + log.Printf("clientAdminAPI: GenerateTestX509Cert failed: %+v\n\n", err) + http.Error(response, "500 GenerateTestX509Cert failed", http.StatusInternalServerError) + return + } + testModeTLSConfig = &tls.Config{ + Certificates: []tls.Certificate{certificate}, + } + testModeTLSConfig.BuildNameToCertificate() + } + response.Write([]byte("OK")) + case "/end_test": + isTestMode = false + response.Header().Set("Content-Type", "text/plain") + for _, testToken := range testTokens { + response.Write([]byte(fmt.Sprintln(testToken))) + } + case "/liveconfig": + if request.Method == "PUT" { + requestBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + log.Printf("clientAdminAPI: request read error: %+v\n\n", err) + http.Error(response, "500 request read error", http.StatusInternalServerError) + return + } + var configUpdate LiveConfigUpdate + err = json.Unmarshal(requestBytes, &configUpdate) + if err != nil { + log.Printf("clientAdminAPI: can't parse JSON: %+v\n\n", err) + http.Error(response, "400 bad request: can't parse JSON", http.StatusBadRequest) + return + } + + err = updateListenersOnServer(configUpdate.Listeners) + if err != nil { + log.Printf("clientAdminAPI: can't updateListenersOnServer(): %+v\n\n", err) + http.Error(response, "500 internal server error", http.StatusInternalServerError) + return + } + + if &configUpdate.ServiceToLocalAddrMap != nil { + serviceToLocalAddrMap = &configUpdate.ServiceToLocalAddrMap + } + + response.Header().Add("content-type", "application/json") + response.WriteHeader(http.StatusOK) + response.Write(requestBytes) + + } else { + response.Header().Set("Allow", "PUT") + http.Error(response, "405 method not allowed, try PUT", http.StatusMethodNotAllowed) + } + default: + http.Error(response, "404 not found, try PUT /liveconfig or PUT/GET /testmode", http.StatusNotFound) + } + +} + +func updateListenersOnServer(listeners []ListenerConfig) error { + sendBytes, err := json.Marshal(listeners) + if err != nil { + return errors.Wrap(err, "Listeners json serialization failed") + } + client := &http.Client{ + Transport: &http.Transport{ + TLSClientConfig: tlsClientConfig, + }, + Timeout: 10 * time.Second, + } + + // TODO make this concurrent requests, not one by one. + for _, server := range clientServers { + apiURL := fmt.Sprintf("https://%s/tunnels", server.ServerHostPort) + tunnelsRequest, err := http.NewRequest("PUT", apiURL, bytes.NewReader(sendBytes)) + if err != nil { + return errors.Wrap(err, "error creating tunnels request") + } + tunnelsRequest.Header.Add("content-type", "application/json") + + tunnelsResponse, err := client.Do(tunnelsRequest) + if err != nil { + return errors.Wrap(err, "tunnels request failed") + } + tunnelsResponseBytes, err := ioutil.ReadAll(tunnelsResponse.Body) + if err != nil { + return errors.Wrap(err, "tunnels request response read error") + } + + if tunnelsResponse.StatusCode != http.StatusOK { + return errors.Errorf("tunnelsRequest returned HTTP %d: %s", tunnelsResponse.StatusCode, string(tunnelsResponseBytes)) + } + } + + // cache the listeners locally for use in test mode. + testModeListeners = map[string]ListenerConfig{} + for _, listener := range listeners { + testModeListeners[listener.BackEndService] = listener + } + + return nil +} + +func handleTestConnection(remote net.Conn, msg *proto.ControlMessage) { + listenerInfo, hasListenerInfo := testModeListeners[msg.Service] + log.Printf("handleTestConnection: %s (%s, %d)", msg.Service, listenerInfo.ListenHostnameGlob, listenerInfo.ListenPort) + if !hasListenerInfo { + remote.Close() + return + } + if listenerInfo.HaProxyProxyProtocol { + remote = proxyprotocol.NewConn(remote, time.Second*5) + } + if listenerInfo.ListenHostnameGlob != "" && listenerInfo.ListenHostnameGlob != "*" { + // TODO make greenhouse-desktop always use HAPROXY proxy protocol with Caddy + // so caddy can get the real remote IP + if listenerInfo.ListenPort == 80 { + requestBuffer := make([]byte, 1024) + bytesRead, err := remote.Read(requestBuffer) + if err != nil { + remote.Close() + } else { + result := regexp.MustCompile("GET /([^ ]+) HTTP/1.1").FindStringSubmatch(string(requestBuffer[:bytesRead])) + if result != nil && len(result) == 2 { + testToken := result[1] + testTokens = append(testTokens, testToken) + remote.Write([]byte(fmt.Sprintf(`HTTP/1.1 200 OK +Content-Type: text/plain + +%s`, testToken))) + // TODO add remote.RemoteAddr().String() + remote.Close() + } + } + } else { + remote_tls := tls.Server(remote, testModeTLSConfig) + err := remote_tls.Handshake() + if err != nil { + remote_tls.Close() + return + } + requestBuffer := make([]byte, 1024) + bytesRead, err := remote_tls.Read(requestBuffer) + if err != nil { + remote_tls.Close() + return + } + testToken := string(requestBuffer[:bytesRead]) + testTokens = append(testTokens, testToken) + remote_tls.Write([]byte(testToken)) + remote_tls.Close() + } + } else { + requestBuffer := make([]byte, 1024) + bytesRead, err := remote.Read(requestBuffer) + if err != nil { + remote.Close() + return + } + testToken := string(requestBuffer[:bytesRead]) + testTokens = append(testTokens, testToken) + remote.Write([]byte(testToken)) + remote.Close() + } +} + +// https://gist.github.com/shivakar/cd52b5594d4912fbeb46 +// create a bogus TLS key pair for the test server to use -- the test client will use InsecureSkipVerify +func GenerateTestX509Cert() (tls.Certificate, error) { + now := time.Now() + + subjectKeyIDByteSlice := make([]byte, 10) + rand.Read(subjectKeyIDByteSlice) + + template := &x509.Certificate{ + SerialNumber: big.NewInt(now.Unix()), + Subject: pkix.Name{ + CommonName: "threshold-test-certificate.example.com", + Country: []string{"USA"}, + Organization: []string{"example.com"}, + OrganizationalUnit: []string{"threshold-test-certificate"}, + }, + NotBefore: now, + NotAfter: now.AddDate(99, 0, 0), // Valid for long time (99 years) + SubjectKeyId: subjectKeyIDByteSlice, + BasicConstraintsValid: true, + IsCA: true, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + KeyUsage: x509.KeyUsageKeyEncipherment | + x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, + } + + priv, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + return tls.Certificate{}, err + } + + cert, err := x509.CreateCertificate(rand.Reader, template, template, + priv.Public(), priv) + if err != nil { + return tls.Certificate{}, err + } + + var outCert tls.Certificate + outCert.Certificate = append(outCert.Certificate, cert) + outCert.PrivateKey = priv + + return outCert, nil +} + +func getProxyDialer(socks5Address string) (proxy.Dialer, error) { + if strings.HasPrefix(strings.ToLower(socks5Address), "gateway") { + splitAddress := strings.Split(socks5Address, ":") + if len(splitAddress) != 2 { + return nil, errors.Errorf("can't getProxyDialer() because HostileNetworkEnvironmentEvasionSOCKS5Address '%s' was invalid. should be of the form host:port") + } + port := splitAddress[1] + defaultGateways, err := getDefaultGatewaysFromRoutingTable() + if err != nil { + return nil, errors.Errorf("can't getProxyDialer() because HostileNetworkEnvironmentEvasionSOCKS5Address was set to '%s' but: \n%+v\n", socks5Address, err) + } + if len(defaultGateways) == 0 { + return nil, errors.Errorf( + "can't getProxyDialer() because HostileNetworkEnvironmentEvasionSOCKS5Address was set to '%s' but no default gateways were found in routing table", + socks5Address, + ) + } + + failures := make([]string, len(defaultGateways)) + for i := 0; i < len(defaultGateways); i++ { + address := fmt.Sprintf("%s:%s", defaultGateways[i], port) + conn, err := net.Dial("tcp", address) + if err == nil { + conn.Close() + return proxy.SOCKS5("tcp", address, nil, proxy.Direct) + } + failures = append(failures, fmt.Sprintf("can't connect to %s", address)) + } + + // if we got this far it means we tried them all and none of them worked. + return nil, errors.Errorf("can't connect to HostileNetworkEnvironmentEvasionSOCKS5Address '%s': %s", socks5Address, strings.Join(failures, ", ")) + } else { + conn, err := net.Dial("tcp", socks5Address) + if err != nil { + return nil, errors.Errorf("can't connect to HostileNetworkEnvironmentEvasionSOCKS5Address '%s': %s", socks5Address, err) + } + conn.Close() + + return proxy.SOCKS5("tcp", socks5Address, nil, proxy.Direct) + } +} + +// https://stackoverflow.com/questions/40682760/what-syscall-method-could-i-use-to-get-the-default-network-gateway +func getDefaultGatewaysFromRoutingTable() ([]string, error) { + + if runtime.GOOS != "linux" { + return nil, errors.Errorf("getDefaultGatewaysFromRoutingTable() does not support %s operating system yet.", runtime.GOOS) + } + toReturn := []string{} + + file, err := os.Open("/proc/net/route") + if err != nil { + return nil, err + } + defer file.Close() + + scanner := bufio.NewScanner(file) + if scanner.Scan() { // skip the first line (header) + for scanner.Scan() { + tokens := strings.Split(scanner.Text(), "\t") + destinationHex := "0x" + tokens[1] + gatewayHex := "0x" + tokens[2] + + destinationInt, err := strconv.ParseInt(destinationHex, 0, 64) + if err != nil { + return nil, err + } + gatewayInt, err := strconv.ParseInt(gatewayHex, 0, 64) + if err != nil { + return nil, err + } + // 0 means 0.0.0.0 -- we are looking for default routes, routes that have universal destination 0.0.0.0 + if destinationInt == 0 && gatewayInt != 0 { + gatewayUint32 := uint32(gatewayInt) + + // make net.IP address from uint32 + ip := make(net.IP, 4) + binary.LittleEndian.PutUint32(ip, gatewayUint32) + + toReturn = append(toReturn, ip.String()) + //fmt.Printf("%T --> %[1]v\n", ipBytes) + } + } + } + + return toReturn, nil +} diff --git a/main_server.go b/main_server.go new file mode 100644 index 0000000..e0312ef --- /dev/null +++ b/main_server.go @@ -0,0 +1,756 @@ +package main + +import ( + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "log" + "net" + "net/http" + "os" + "path" + "path/filepath" + "regexp" + "strings" + "sync" + + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" +) + +type ServerConfig struct { + DebugLog bool + ListenPort int // default 9056 + + // Domain is only used for validating the TLS client certificates + // when TLS is used. the cert's Subject CommonName is expected to be @ + // I did this because I believe this is a standard for TLS client certs, + // based on domain users/email addresses. + Domain string + + // MultiTenantMode ON: + // tenantId is required. ClientId must be formatted `.` + // clients will not be allowed to register listeners capturing all packets on a given port, + // they must specify a hostname, and they must prove that they own it (via a TXT record for example). + // Exception: Each client will get a few allocated ports for SSH & maybe etc??? + // + // MultiTenantMode OFF: + // tenantId is N/A. ClientId must be formatted `` + // clients can register listeners with any hostname including null, on any open port. + // + MultiTenantMode bool + MultiTenantInternalAPIListenPort int // default 9057 + MultiTenantInternalAPICaCertificateFile string + + CaCertificateFilesGlob string + ServerTlsKeyFile string + ServerTlsCertificateFile string + + Metrics MetricsConfig +} + +type ClientState struct { + CurrentState string + LastState string +} + +type ManagementHttpHandler struct { + Domain string + MultiTenantMode bool + ControlHandler http.Handler +} + +type BandwidthCounter struct { + Inbound int64 + Outbound int64 +} + +type MultiTenantInternalAPI struct { + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 +} + +type PrometheusMetricsAPI struct { + MultiTenantServerMode bool + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 + InboundByService map[string]int64 + OutboundByService map[string]int64 +} + +type Tenant struct { + PortStart int + PortEnd int + AuthorizedDomains []string +} + +// Server State +var listenersByTenant map[string][]ListenerConfig +var clientStatesMutex = &sync.Mutex{} +var tenantStatesMutex = &sync.Mutex{} +var clientStatesByTenant map[string]map[string]ClientState +var tenants map[string]Tenant +var server *tunnel.Server + +func runServer(configFileName *string) { + + configBytes := getConfigBytes(configFileName) + + var config ServerConfig + err := json.Unmarshal(configBytes, &config) + if err != nil { + fmt.Printf("runServer(): can't json.Unmarshal(configBytes, &config) because %s \n", err) + os.Exit(1) + } + + configToLog, _ := json.MarshalIndent(config, "", " ") + log.Printf("threshold server is starting up using config:\n%s\n", string(configToLog)) + + clientStateChangeChannel := make(chan *tunnel.ClientStateChange) + listenersByTenant = map[string][]ListenerConfig{} + + var metricChannel chan tunnel.BandwidthMetric = nil + + // the Server should only collect metrics when in multi-tenant mode -- this is needed for billing + if config.MultiTenantMode { + metricChannel = make(chan tunnel.BandwidthMetric, 4096) + } + + tunnelServerConfig := &tunnel.ServerConfig{ + StateChanges: clientStateChangeChannel, + ValidateCertificate: validateCertificate, + MultitenantMode: config.MultiTenantMode, + Bandwidth: metricChannel, + Domain: config.Domain, + DebugLog: config.DebugLog, + } + server, err = tunnel.NewServer(tunnelServerConfig) + if err != nil { + fmt.Printf("runServer(): can't create tunnel server because %s \n", err) + os.Exit(1) + } + + clientStatesByTenant = make(map[string]map[string]ClientState) + go (func() { + for { + clientStateChange := <-clientStateChangeChannel + previousState := "" + currentState := clientStateChange.Current.String() + tenantId := "" + if config.MultiTenantMode { + tenantIdNodeId := strings.Split(clientStateChange.Identifier, ".") + if len(tenantIdNodeId) != 2 { + fmt.Printf("runServer(): go func(): can't handle clientStateChange with malformed Identifier '%s' \n", clientStateChange.Identifier) + break + } + tenantId = tenantIdNodeId[0] + } + + clientStatesMutex.Lock() + if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { + clientStatesByTenant[tenantId] = map[string]ClientState{} + } + fromMap, wasInMap := clientStatesByTenant[tenantId][clientStateChange.Identifier] + if wasInMap { + previousState = fromMap.CurrentState + } else { + previousState = clientStateChange.Previous.String() + } + if clientStateChange.Error != nil && clientStateChange.Error != io.EOF { + log.Printf("runServer(): recieved a client state change with an error: %s \n", clientStateChange.Error) + currentState = "ClientError" + } + clientStatesByTenant[tenantId][clientStateChange.Identifier] = ClientState{ + CurrentState: currentState, + LastState: previousState, + } + clientStatesMutex.Unlock() + } + })() + + certificates, err := filepath.Glob(config.CaCertificateFilesGlob) + if err != nil { + log.Fatal(err) + } + + caCertPool := x509.NewCertPool() + for _, filename := range certificates { + log.Printf("loading certificate %s, clients who have a key signed by this certificat will be allowed to connect", filename) + caCert, err := ioutil.ReadFile(filename) + if err != nil { + log.Fatal(err) + } + caCertPool.AppendCertsFromPEM(caCert) + } + + tlsConfig := &tls.Config{ + + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + httpsManagementServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.ListenPort), + TLSConfig: tlsConfig, + Handler: &(ManagementHttpHandler{ + Domain: config.Domain, + MultiTenantMode: config.MultiTenantMode, + ControlHandler: server, + }), + } + + if config.MultiTenantMode { + go (func() { + caCertPool := x509.NewCertPool() + caCert, err := ioutil.ReadFile(config.MultiTenantInternalAPICaCertificateFile) + if err != nil { + log.Fatal(err) + } + caCertPool.AppendCertsFromPEM(caCert) + tlsConfig := &tls.Config{ + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + } + tlsConfig.BuildNameToCertificate() + + internalHandler := &MultiTenantInternalAPI{ + InboundByTenant: map[string]int64{}, + OutboundByTenant: map[string]int64{}, + } + multiTenantInternalServer := &http.Server{ + Addr: fmt.Sprintf(":%d", config.MultiTenantInternalAPIListenPort), + TLSConfig: tlsConfig, + Handler: internalHandler, + } + + go (func() { + for { + metric := <-metricChannel + tenantIdNodeId := strings.Split(metric.ClientId, ".") + if len(tenantIdNodeId) != 2 { + panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) + } + if metric.Inbound { + internalHandler.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } else { + internalHandler.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) + } + } + })() + + err = multiTenantInternalServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) + panic(err) + })() + } + + log.Print("runServer(): the server should be running now\n") + err = httpsManagementServer.ListenAndServeTLS(config.ServerTlsCertificateFile, config.ServerTlsKeyFile) + panic(err) + +} + +func validateCertificate(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) { + if len(request.TLS.PeerCertificates) != 1 { + return "", "", fmt.Errorf("expected exactly 1 TLS client certificate, got %d", len(request.TLS.PeerCertificates)) + } + certCommonName := request.TLS.PeerCertificates[0].Subject.CommonName + clientIdDomain := strings.Split(certCommonName, "@") + if len(clientIdDomain) != 2 { + return "", "", fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '@'", certCommonName, + ) + } + if clientIdDomain[1] != domain { + return "", "", fmt.Errorf( + "expected TLS client certificate common name domain '%s' to match server domain '%s'", + clientIdDomain[1], domain, + ) + } + + identifier = clientIdDomain[0] + nodeId := identifier + + if multiTenantMode { + tenantIdNodeId := strings.Split(identifier, ".") + if len(tenantIdNodeId) != 2 { + return "", "", fmt.Errorf( + "expected TLS client certificate common name '%s' to match format '.@'", certCommonName, + ) + } + tenantId = tenantIdNodeId[0] + nodeId = tenantIdNodeId[1] + } + + mustMatchRegexp := regexp.MustCompile("(?i)^[a-z0-9]+([a-z0-9-_]*[a-z0-9]+)?$") + if !mustMatchRegexp.MatchString(nodeId) { + return "", "", fmt.Errorf("expected TLS client certificate common name nodeId '%s' to be a valid subdomain", nodeId) + } + + if tenantId != "" && !mustMatchRegexp.MatchString(tenantId) { + return "", "", fmt.Errorf("expected TLS client certificate common name tenantId '%s' to be a valid subdomain", tenantId) + } + + return identifier, tenantId, nil +} + +func setListeners(tenantId string, listenerConfigs []ListenerConfig) (int, string) { + currentListenersThatCanKeepRunning := make([]ListenerConfig, 0) + newListenersThatHaveToBeAdded := make([]ListenerConfig, 0) + + // I think its probably a good idea to allow the user to create tunnels for nodes that aren't connected + // If a node has a temporary outage (or a threshold server respawns during a node outage) + // that should not prevent the user from setting the tunnels + // If the server tries to dial a disconnected node, it will simply fail dailing with an error. + + // for _, newListenerConfig := range listenerConfigs { + // clientState, everHeardOfClientBefore := clientStatesByTenant[tenantId][newListenerConfig.ClientId] + // if !everHeardOfClientBefore { + // return http.StatusNotFound, fmt.Sprintf("Client %s Not Found", newListenerConfig.ClientId) + // } + // if clientState.CurrentState != tunnel.ClientConnected.String() { + // return http.StatusNotFound, fmt.Sprintf("Client %s is not connected it is %s", newListenerConfig.ClientId, clientState.CurrentState) + // } + // } + + for _, existingListener := range listenersByTenant[tenantId] { + canKeepRunning := false + for _, newListenerConfig := range listenerConfigs { + if compareListenerConfigs(existingListener, newListenerConfig) { + canKeepRunning = true + } + } + + if !canKeepRunning { + listenAddress := net.ParseIP(existingListener.ListenAddress) + if listenAddress == nil { + return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", existingListener.ListenAddress) + } + + server.DeleteAddr(listenAddress, existingListener.ListenPort, existingListener.ListenHostnameGlob) + + } else { + currentListenersThatCanKeepRunning = append(currentListenersThatCanKeepRunning, existingListener) + } + } + + for _, newListenerConfig := range listenerConfigs { + hasToBeAdded := true + for _, existingListener := range listenersByTenant[tenantId] { + if compareListenerConfigs(existingListener, newListenerConfig) { + hasToBeAdded = false + } + } + + if hasToBeAdded { + listenAddress := net.ParseIP(newListenerConfig.ListenAddress) + //fmt.Printf("str: %s, listenAddress: %s\n\n", newListenerConfig.ListenAddress, listenAddress) + if listenAddress == nil { + return http.StatusBadRequest, fmt.Sprintf("Bad Request: \"%s\" is not an IP address.", newListenerConfig.ListenAddress) + } + err := server.AddAddr( + listenAddress, + newListenerConfig.ListenPort, + newListenerConfig.ListenHostnameGlob, + newListenerConfig.ClientId, + newListenerConfig.HaProxyProxyProtocol, + newListenerConfig.BackEndService, + ) + + if err != nil { + if strings.Contains(err.Error(), "already in use") { + return http.StatusConflict, fmt.Sprintf("Port Conflict: Port %s:%d is reserved or already in use", listenAddress, newListenerConfig.ListenPort) + } + + log.Printf("setListeners(): can't net.Listen(\"tcp\", \"%s\") because %s \n", listenAddress, err) + return http.StatusInternalServerError, "Unknown Listening Error" + } + + newListenersThatHaveToBeAdded = append(newListenersThatHaveToBeAdded, newListenerConfig) + } + } + + listenersByTenant[tenantId] = append(currentListenersThatCanKeepRunning, newListenersThatHaveToBeAdded...) + + return http.StatusOK, "ok" + +} + +// TODO move the prometheus metrics to the client +// func exportMetrics(config MetricsConfig, multiTenantServerMode bool, bandwidth <-chan tunnel.BandwidthMetric) { +// metricsAPI := &PrometheusMetricsAPI{ +// MultiTenantServerMode: multiTenantServerMode, +// InboundByTenant: map[string]int64{}, +// OutboundByTenant: map[string]int64{}, +// InboundByService: map[string]int64{}, +// OutboundByService: map[string]int64{}, +// } + +// go (func() { +// for { +// metric := <-bandwidth +// if multiTenantServerMode { +// tenantIdNodeId := strings.Split(metric.ClientId, ".") +// if len(tenantIdNodeId) != 2 { +// panic(fmt.Errorf("malformed metric.ClientId '%s', expected .", metric.ClientId)) +// } +// if metric.Inbound { +// metricsAPI.InboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) +// } else { +// metricsAPI.OutboundByTenant[tenantIdNodeId[0]] += int64(metric.Bytes) +// } +// } else { +// // TODO shouldn't this be done on the client side only ?? +// if metric.Inbound { +// metricsAPI.InboundByService[metric.Service] += int64(metric.Bytes) +// } else { +// metricsAPI.OutboundByService[metric.Service] += int64(metric.Bytes) +// } +// } +// } +// })() + +// go (func() { +// metricsServer := &http.Server{ +// Addr: fmt.Sprintf(":%d", config.PrometheusMetricsAPIPort), +// Handler: metricsAPI, +// } +// err := metricsServer.ListenAndServe() +// panic(err) +// })() +// } + +// // TODO move this to the management API / to the client side. +// func (s *PrometheusMetricsAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + +// getMillisecondsSinceUnixEpoch := func() int64 { +// return time.Now().UnixNano() / int64(time.Millisecond) +// } + +// writeMetric := func(inbound map[string]int64, outbound map[string]int64, name, tag, desc string) { +// timestamp := getMillisecondsSinceUnixEpoch() +// responseWriter.Write([]byte(fmt.Sprintf("# HELP %s %s\n", name, desc))) +// responseWriter.Write([]byte(fmt.Sprintf("# TYPE %s counter\n", name))) +// for id, bytez := range inbound { +// responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"inbound\"} %d %d\n", name, tag, id, bytez, timestamp))) +// } +// for id, bytez := range outbound { +// responseWriter.Write([]byte(fmt.Sprintf("%s{%s=\"%s\",direction=\"outbound\"} %d %d\n", name, tag, id, bytez, timestamp))) +// } +// } + +// if strings.Contains(request.Header.Get("Accept"), "application/json") && !strings.Contains(request.Header.Get("Accept"), "text/plain") { +// var bytez []byte +// var err error +// if s.MultiTenantServerMode { +// bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ +// InboundByTenant: s.InboundByTenant, +// OutboundByTenant: s.OutboundByTenant, +// }, "", " ") +// } else { +// // TODO this should probably only be supported on the client side +// bytez, err = json.MarshalIndent(PrometheusMetricsAPI{ +// InboundByService: s.InboundByService, +// OutboundByService: s.OutboundByService, +// }, "", " ") +// } + +// if err != nil { +// log.Printf(fmt.Sprintf("500 internal server error: %s", err)) +// http.Error(responseWriter, "500 internal server error", http.StatusInternalServerError) +// return +// } + +// responseWriter.Header().Set("Content-Type", "application/json") +// responseWriter.Write(bytez) +// } else { +// responseWriter.Header().Set("Content-Type", "text/plain; version=0.0.4") + +// if s.MultiTenantServerMode { +// writeMetric(s.InboundByTenant, s.OutboundByTenant, "bandwidth_by_tenant", "tenant", "bandwidth usage by tenant in bytes, excluding usage from control protocol.") +// } else { +// writeMetric(s.InboundByService, s.OutboundByService, "bandwidth_by_service", "service", "bandwidth usage by service in bytes.") +// } +// } +// } + +func compareListenerConfigs(a, b ListenerConfig) bool { + return (a.ListenPort == b.ListenPort && + a.ListenAddress == b.ListenAddress && + a.ListenHostnameGlob == b.ListenHostnameGlob && + a.BackEndService == b.BackEndService && + a.ClientId == b.ClientId && + a.HaProxyProxyProtocol == b.HaProxyProxyProtocol) +} + +func (s *MultiTenantInternalAPI) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + switch path.Clean(request.URL.Path) { + case "/tenantInfo": + tenantId := request.URL.Query().Get("tenantId") + clientStates, hasClientStatesByTenant := clientStatesByTenant[tenantId] + listeners, hasListenersByTenant := listenersByTenant[tenantId] + + if tenantId == "" || tenantId == "0" { + http.Error(responseWriter, "400 Bad Request: tenantId url parameter is required", http.StatusBadRequest) + } + + if !hasClientStatesByTenant { + clientStates = map[string]ClientState{} + } + if !hasListenersByTenant { + listeners = []ListenerConfig{} + } + resultObject := struct { + ClientStates map[string]ClientState + Listeners []ListenerConfig + }{ + ClientStates: clientStates, + Listeners: listeners, + } + bytes, err := json.Marshal(resultObject) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + case "/tenants": + if request.Method == "GET" || request.Method == "PUT" { + if request.Method == "PUT" { + if request.Header.Get("Content-Type") != "application/json" { + http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) + } else { + bodyBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) + return + } + var newTenants map[string]Tenant + err = json.Unmarshal(bodyBytes, &newTenants) + if err != nil { + log.Printf("422 Unprocessable Entity: Can't Parse JSON: %+v\n", err) + http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) + return + } + tenantStatesMutex.Lock() + tenants = newTenants + tenantStatesMutex.Unlock() + } + } + + tenantStatesMutex.Lock() + bytes, err := json.Marshal(tenants) + tenantStatesMutex.Unlock() + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + + } else { + responseWriter.Header().Add("Allow", "PUT") + responseWriter.Header().Add("Allow", "GET") + http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) + } + case "/consumeMetrics": + if request.Method == "GET" { + bytez, err := json.Marshal(struct { + InboundByTenant map[string]int64 + OutboundByTenant map[string]int64 + }{ + InboundByTenant: s.InboundByTenant, + OutboundByTenant: s.OutboundByTenant, + }) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + inboundToDelete := []string{} + outboundToDelete := []string{} + for k := range s.InboundByTenant { + inboundToDelete = append(inboundToDelete, k) + } + for k := range s.OutboundByTenant { + outboundToDelete = append(outboundToDelete, k) + } + for _, k := range inboundToDelete { + delete(s.InboundByTenant, k) + } + for _, k := range outboundToDelete { + delete(s.OutboundByTenant, k) + } + + // bytez2, err := json.Marshal(struct { + // InboundByTenant map[string]int64 + // OutboundByTenant map[string]int64 + // }{ + // InboundByTenant: s.InboundByTenant, + // OutboundByTenant: s.OutboundByTenant, + // }) + //log.Printf("returnedBytes: %s\n\ncurrentBytes: %s\n\n", string(bytez), string(bytez2)) + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytez) + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } + case "/ping": + if request.Method == "GET" { + fmt.Fprint(responseWriter, "pong") + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } + default: + http.Error(responseWriter, "404 Not Found, try /tenants or /ping", http.StatusNotFound) + } +} + +func (s *ManagementHttpHandler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) { + + _, tenantId, err := validateCertificate(s.Domain, s.MultiTenantMode, request) + if err != nil { + http.Error(responseWriter, fmt.Sprintf("400 bad request: %s", err.Error()), http.StatusBadRequest) + return + } + if _, hasTenant := clientStatesByTenant[tenantId]; !hasTenant { + clientStatesByTenant[tenantId] = map[string]ClientState{} + } + if _, hasTenant := listenersByTenant[tenantId]; !hasTenant { + listenersByTenant[tenantId] = []ListenerConfig{} + } + + switch path.Clean(request.URL.Path) { + case "/clients": + if request.Method == "GET" { + clientStatesMutex.Lock() + + bytes, err := json.Marshal(clientStatesByTenant[tenantId]) + clientStatesMutex.Unlock() + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 Method Not Allowed, try GET", http.StatusMethodNotAllowed) + } + case "/tunnels": + if request.Method == "PUT" { + if request.Header.Get("Content-Type") != "application/json" { + http.Error(responseWriter, "415 Unsupported Media Type: Content-Type must be application/json", http.StatusUnsupportedMediaType) + } else { + bodyBytes, err := ioutil.ReadAll(request.Body) + if err != nil { + http.Error(responseWriter, "500 Read Error", http.StatusInternalServerError) + return + } + var listenerConfigs []ListenerConfig + err = json.Unmarshal(bodyBytes, &listenerConfigs) + if err != nil { + http.Error(responseWriter, "422 Unprocessable Entity: Can't Parse JSON", http.StatusUnprocessableEntity) + return + } + + if s.MultiTenantMode { + for _, listenerConfig := range listenerConfigs { + tenantIdNodeId := strings.Split(listenerConfig.ClientId, ".") + if len(tenantIdNodeId) != 2 { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: invalid ClientId '%s'. It needs to be in the form '.'", + listenerConfig.ClientId, + ), + http.StatusBadRequest, + ) + return + } + tenant, hasTenant := tenants[tenantIdNodeId[0]] + if !hasTenant { + http.Error( + responseWriter, + fmt.Sprintf("400 Bad Request: unknown tenantId '%s'", tenantIdNodeId[0]), + http.StatusBadRequest, + ) + return + } + isAuthorizedDomain := false + for _, tenantAuthorizedDomain := range tenant.AuthorizedDomains { + isSubdomain := strings.HasSuffix(listenerConfig.ListenHostnameGlob, fmt.Sprintf(".%s", tenantAuthorizedDomain)) + if (tenantAuthorizedDomain == listenerConfig.ListenHostnameGlob) || isSubdomain { + isAuthorizedDomain = true + break + } + } + if listenerConfig.ListenHostnameGlob != "" && !isAuthorizedDomain { + http.Error( + responseWriter, + fmt.Sprintf( + `400 Bad Request: ListenHostnameGlob '%s' is not covered by any of your authorized domains [%s]. + If you are trying to use a reserved port, leave ListenHostnameGlob blank.`, + listenerConfig.ListenHostnameGlob, + strings.Join(stringSliceMap(tenant.AuthorizedDomains, func(x string) string { return fmt.Sprintf("'%s'", x) }), ", "), + ), + http.StatusBadRequest, + ) + } + + if listenerConfig.ListenHostnameGlob == "" { + isReservedPort := (listenerConfig.ListenPort >= tenant.PortStart && listenerConfig.ListenPort <= tenant.PortEnd) + if !isReservedPort { + http.Error( + responseWriter, + fmt.Sprintf( + "400 Bad Request: ListenHostnameGlob is empty and ListenPort '%d' is not one of your reserved ports %d..%d", + listenerConfig.ListenPort, + tenant.PortStart, tenant.PortEnd, + ), + http.StatusBadRequest, + ) + } + } + } + } + + statusCode, errorMessage := setListeners(tenantId, listenerConfigs) + + if statusCode != 200 { + http.Error(responseWriter, errorMessage, statusCode) + return + } + } + } + + if request.Method == "PUT" || request.Method == "GET" { + bytes, err := json.Marshal(listenersByTenant[tenantId]) + if err != nil { + http.Error(responseWriter, "500 JSON Marshal Error", http.StatusInternalServerError) + return + } + + responseWriter.Header().Set("Content-Type", "application/json") + responseWriter.Write(bytes) + } else { + responseWriter.Header().Add("Allow", "PUT") + responseWriter.Header().Add("Allow", "GET") + http.Error(responseWriter, "405 Method Not Allowed, try GET or PUT", http.StatusMethodNotAllowed) + } + case "/ping": + if request.Method == "GET" { + fmt.Fprint(responseWriter, "pong") + } else { + responseWriter.Header().Set("Allow", "GET") + http.Error(responseWriter, "405 method not allowed, try GET", http.StatusMethodNotAllowed) + } + default: + s.ControlHandler.ServeHTTP(responseWriter, request) + } +} diff --git a/picopublish.sh b/picopublish.sh new file mode 100755 index 0000000..77d7559 --- /dev/null +++ b/picopublish.sh @@ -0,0 +1,34 @@ +#!/bin/bash -e + +function build() { + GOOS=$1 + GOARCH=$2 + tag="0.0.0" + if git describe --tags --abbrev=0 > /dev/null 2>&1 ; then + tag="$(git describe --tags --abbrev=0)" + fi + version="$tag-$(git rev-parse --short HEAD)-$(hexdump -n 2 -ve '1/1 "%.2x"' /dev/urandom)" + + echo "building version: $version" + + rm -rf build + mkdir build + + go build -tags 'osusergo netgo' -ldflags='-extldflags=-static' -o build/threshold + + sha256sum build/threshold + + gzip_file_name="threshold-$version-$GOOS-$GOARCH.gz" + + gzip --stdout build/threshold > "build/$gzip_file_name" + + curl -X POST "https://picopublish.sequentialread.com/files/$gzip_file_name" \ + -H 'Content-Type: application/x-gzip' -H "Authorization: Basic $(cat ~/.picopublish-auth)" \ + --data-binary "@build/$gzip_file_name" + + echo "https://picopublish.sequentialread.com/files/$gzip_file_name" +} + +#build arm +build linux amd64 +#build arm64 \ No newline at end of file diff --git a/readme/Diagram.png b/readme/Diagram.png deleted file mode 100644 index 63f75e8..0000000 Binary files a/readme/Diagram.png and /dev/null differ diff --git a/readme/Diagram.svg b/readme/Diagram.svg deleted file mode 100644 index 37782f8..0000000 --- a/readme/Diagram.svg +++ /dev/null @@ -1,2 +0,0 @@ - -
Cloud Service Provider
[Not supported by viewer]
Home Network
[Not supported by viewer]
 Server
[Not supported by viewer]
 Cloud Instance
[Not supported by viewer]
 tunnel server
 tunnel server
TLS
[Not supported by viewer]
 tunnel client
 tunnel client
HTTPS
HTTPS
HTTPS
HTTPS
TLS
[Not supported by viewer]
Public
Internet
[Not supported by viewer]
TLS
[Not supported by viewer]
TLS
[Not supported by viewer]
Router
[Not supported by viewer]
server software
server software
TLS
[Not supported by viewer]
TLS Cert
[Not supported by viewer]
\ No newline at end of file diff --git a/readme/diagram.drawio b/readme/diagram.drawio new file mode 100644 index 0000000..9b59258 --- /dev/null +++ b/readme/diagram.drawio @@ -0,0 +1 @@ +7VvbcqM4EP0aP44LEAh4nDjOJFPZ2dR6qnbnaYqLsNlg5AU5TubrVwLJXCRsbEOSmkr8EGgJIbqPuk83YgJm6+cvmbdZ/YFDlEwMLXyegOuJYei6Aek/JnkpJbZtloJlFoe8UyVYxL8QF2pcuo1DlDc6EowTEm+awgCnKQpIQ+ZlGd41u0U4ad514y2RJFgEXiJL/45DsiqljqVV8lsUL1fizrrGW9ae6MwF+coL8a4mAvMJmGUYk/Jo/TxDCVOe0Et53U1H635iGUpJnwt+2YZzt9ju4J3pPnz9+i3CP51PfJQnL9nyB+aTJS9CAxnepiFig2gTcLVbxQQtNl7AWnfU5lS2IuuEnun0MPTyVdGXnURxksxwgrNiIBB6yIkCKs9Jhh9RrQUGDvIj2iI/k5ggygh6ron4M35BeI1I9kK7iFaH65sDzuSnu8p6hrDRqm45cZ3HEbPcD10plR5wvZ6gY+MVdYz00EK2SscutIEHh9GxaVsNHet6TyUb7lhKBgolw4QwdcVP7IZJvEyLBvjfli25qwRFpDqjR0v+v7gqwlQ7zK0IBVYdgaaZM9eVr50leBvSixYoe4qp8QztIcNP1H9lYlQ/a9+HPmx5K0lczFtIW3ihdiKSkVOcohYiuEg8fPHI4IoZOqYu7jMXr+MwZCNfNWHYxBmd5IJPQJzX0KVpAEDYxKkKxiMscEPGnm6qsDcW9MxO6B0CkTnTNBWIbums6DXfENnh7PEE4HxApNM/uW8NEdgJEf8Ux6N/Zj+l0/LWTHepn7N/zAFVTqfbxfid6KFkZcMOg62PjkckvwTFvb8XeMHjsoDKn1uSxKmAhBSV+BOJFkGxFJFtDtnvAKxaCM5LKmkrwEzwUDhzWnHQUQDNUQFNHwtp9usiTYS8uzQnXspi3umB7u1RaM4hdHqhcOZew7nzNmjT3Wbg6wu2fUoyONhcFdga+CCrDOUrlnRRw3Kv1Ml9uyJCzcaS6RzDL5f/UdNRYuyEZs10ATUFnQ8VZAFPPJ1hLGUYLb8AFKbSFaYCY1lKd44nIWK1RQl6/sxSZ6oMlIb88DpIvDyPg6Y9upwxvU6YwnDKc65i1irUAAzZTFEUGYEySwyhD62DGQwKG8m8bJ+a/i2F+oUsQ4lH4qdmCUBlE36HBxwXrpSbH7bML/GKHG+zAPGr6il7ayCrnWeZoDkQ8bIlItJA1GTeS63bhnXI+09Y3KdCXDlihb+9Ti+ApMp7vA0kp9CuobJo/f1QKZEV0zoPlQAcGWggVIKOCY+KSvFsNRAy+4m8BmdkhZc49ZJ5JW0lRTUsoueY/MPEU4uf/RAtKZ1nrYmd/uAD/IsIeeHY9LYEU1F133vM+IQqwEXFn7wCIAR0FRxCaGn5A1rh0aM07CHtmT0h3xvLF0U9S1XePE5+ZzQ1n826a0N7wvr9fqHmsSel6DW8ULIU//L8ogOzGF8itLd1NbGuVeSlM1NPPB8lV3sKfBlQDq4ViRjty/H8USb1ireKMGlTA+rgMjfHvcQnZ9pyRziKckQkMA3gLFSkqpv/BkmMuEf8zfmvZbYIkM7P34z/CgZWM9Xt9+8Pix5r8mgFjer25mY+v7o5aXmqDN2MI12rs1lnu9xawG3FWUVFVcVLRquWGXIx/8NYgqrr781YcBzC5MIaY9KmNj97QFlMJ87MVVxb8agGiypI1fvjUSLPOkqk3HfFo4zuquIHj7qcR4kldDmP+kSJlNEKvuId/7m8anwaJVZF18vb0uwPWz+huX7HC1Kp+x2za8om3OuNKp1mvMmZvfdF56K0fTojg8VfH0YWWeynAmMLUOXfMNysFT9sFTOz5fgxXhFZcL5hAshYPv9QnOm0ylE3bw3t5s8sSHZUbE4v/XTUkAarznwk9KMm9CJLGiIQQUvQhpfGSBdi2XIbg8Lm9eMFKSBXpwfgueK4cia1wiB0YNPZaLo9totr8+vzuW5fquu8K6oLujeSfXiYATyMMaCH0YFjNKnuQD7GsKatgNmKl+O5mW4qfBh+7K8H/P7CW9LYGXQyAkfak3FsV09FjZterbWBqL5Vo9SJiofXdmsMwKilF2uGzKldRUnGHI1RyzsSxd4L6rYjsqNPK9n1sjK071impfVKepwAFW9S36AMbUPJMK9bhgaqjYDyAiu/E2hssNQOGUBd57Q09hNu/QHnMYmxMhDctzr4mBC8VkSKci8TLlfubP/JhaYyp3AU6+cl+zRkSn1mHKBpiNje6HyaeJtytJOrbCeszCZXNMQrpnqt1FGY3xzL/Ko6WptUHtvecHbiOrWab5qn7v58ONYnEH6U9hl9c9/X2R3RKouY527Zgc1xgN0v0x6KPgjEf9DXceirWMBD0FfTFMv//ZZmzR77BmseiweiS9zV/gUQcOvJsTjufv8j76O5wIuZPb2Y+a69mAWH8WJWe7v6yF7Mkt/WS6hja3zTnyOcvEAtwQyEJxdbaGuWhApLtlU+3GdG56WGEGoazaQk1154cm1G9XT+N0aC4qWY9MkF+27H51O+4KOQvTtRb9N3OqltzzhgdRVKDy78V4UL6Lfj+8xUY+iU4mj2sM4DD02Ld3LTR/Ty88nbltBv7+3QtJubywP9CQYWrWa7ZiRXAcAwuSY9rT4bL31u9fE9mP8P \ No newline at end of file diff --git a/readme/diagram.png b/readme/diagram.png new file mode 100644 index 0000000..6421d90 Binary files /dev/null and b/readme/diagram.png differ diff --git a/threshold.png b/readme/splash.png similarity index 100% rename from threshold.png rename to readme/splash.png diff --git a/tunnel-lib/README.md b/tunnel-lib/README.md index 8f5fbc2..b72f708 100644 --- a/tunnel-lib/README.md +++ b/tunnel-lib/README.md @@ -1,4 +1,4 @@ -# Tunnel [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/git.sequentialread.com/forest/tunnel) [![Go Report Card](https://goreportcard.com/badge/git.sequentialread.com/forest/tunnel)](https://goreportcard.com/report/git.sequentialread.com/forest/tunnel) [![Build Status](http://img.shields.io/travis/koding/tunnel.svg?style=flat-square)](https://travis-ci.org/koding/tunnel) +# Tunnel Tunnel is a server/client package that enables to proxy public connections to your local machine over a tunnel connection from the local machine to the @@ -28,7 +28,7 @@ package main import ( "net/http" - "git.sequentialread.com/forest/tunnel" + "git.sequentialread.com/forest/threshold" ) func main() { @@ -48,7 +48,7 @@ Let us now create the client side part: ```go package main -import "git.sequentialread.com/forest/tunnel" +import "git.sequentialread.com/forest/threshold" func main() { cfg := &tunnel.ClientConfig{ @@ -77,7 +77,7 @@ That's it. There are many options that can be changed, such as a static local address for your client. Have alook at the -[documentation](http://godoc.org/git.sequentialread.com/forest/tunnel) +[documentation](http://godoc.org/git.sequentialread.com/forest/threshold) # Protocol diff --git a/tunnel-lib/client.go b/tunnel-lib/client.go index 96f1e63..0460cc9 100644 --- a/tunnel-lib/client.go +++ b/tunnel-lib/client.go @@ -8,11 +8,12 @@ import ( "log" "net" "net/http" + "strconv" "sync" "sync/atomic" "time" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" "github.com/hashicorp/yamux" ) @@ -97,6 +98,8 @@ type Client struct { // redialBackoff is used to reconnect in exponential backoff intervals redialBackoff Backoff + + incomingForwardProxyConnections chan net.Conn } // ClientConfig defines the configuration for the Client @@ -126,7 +129,7 @@ type ClientConfig struct { // where you can provide your local server selection or communication rules. Proxy ProxyFunc - // Dial provides custom transport layer for client server communication. + // Dial provides custom transport layer for communication between the threshold client and threshold server. // // If nil, default implementation is to return net.Dial("tcp", address). // @@ -199,14 +202,14 @@ func NewClient(cfg *ClientConfig) (*Client, error) { proxy := cfg.Proxy if proxy == nil { - var f ProxyFuncs - f.TCP = (&TCPProxy{FetchLocalAddr: cfg.FetchLocalAddr, DebugLog: cfg.DebugLog}).Proxy - proxy = Proxy(f) + proxy = (&TCPProxy{FetchLocalAddr: cfg.FetchLocalAddr, DebugLog: cfg.DebugLog}).Proxy } - var bo Backoff = newForeverBackoff() + var bo Backoff if cfg.Backoff != nil { bo = cfg.Backoff + } else { + bo = NewExponentialBackoff() } client := &Client{ @@ -431,9 +434,6 @@ func (c *Client) connect(identifier, serverAddr string) error { if err != nil { return fmt.Errorf("error creating request to %s: %s", remoteURL, err) } - - req.Header.Set(proto.ClientIdentifierHeader, identifier) - if c.config.DebugLog { log.Printf("Client.connect(): Writing request to TCP: %+v\n", req) } @@ -509,7 +509,29 @@ func (c *Client) connect(identifier, serverAddr string) error { c.startNotifyIfNeeded() - return c.listenControl(ct) + // inline immediately invoked function expression to use defer + return (func() error { + c.ctrlWg.Add(1) + defer c.ctrlWg.Done() + + c.incomingForwardProxyConnections = make(chan net.Conn) + c.changeState(ClientConnected, nil) + + var err error + select { + case err = <-async(func() error { return c.listenControl(ct) }): + log.Printf("Client.listenControl() exited with: %+v\n", err) + case err = <-async(func() error { return c.listenForwardProxy(ct) }): + log.Printf("Client.listenForwardProxy() exited with: %+v\n", err) + } + + c.session.GoAway() + c.session.Close() + ct.Close() + c.changeState(ClientDisconnected, err) + return err + + })() } func (c *Client) dial(serverAddr string) (net.Conn, error) { @@ -521,27 +543,23 @@ func (c *Client) dial(serverAddr string) (net.Conn, error) { } func (c *Client) listenControl(ct *control) error { - c.ctrlWg.Add(1) - defer c.ctrlWg.Done() - - c.changeState(ClientConnected, nil) - for { var msg proto.ControlMessage if err := ct.dec.Decode(&msg); err != nil { - c.reqWg.Wait() // wait until all requests are finished - c.session.GoAway() - c.session.Close() - c.changeState(ClientDisconnected, err) - return fmt.Errorf("failure decoding control message: %s", err) } if c.config.DebugLog { log.Printf("Client.connect(): Received control msg %+v\n", msg) - log.Println("Client.connect(): Opening a new stream from server session") } + if msg.Action != proto.RequestClientSession { + return fmt.Errorf("control message from server had action = %d, expected %d", msg.Action, proto.RequestClientSession) + } + + if c.config.DebugLog { + log.Println("Client.connect(): Opening a new stream from server session") + } remote, err := c.session.Open() if err != nil { return err @@ -556,3 +574,51 @@ func (c *Client) listenControl(ct *control) error { }() } } + +func (c *Client) HandleForwardProxy(conn net.Conn) error { + if c.state != ClientConnected { + conn.Close() + return errors.New("client is disconnected, can't accept any forward proxy connections") + } else { + c.incomingForwardProxyConnections <- conn + return nil + } +} + +func (c *Client) listenForwardProxy(ct *control) error { + + forwardProxyConnectionId := 0 + for { + conn := <-c.incomingForwardProxyConnections + + forwardProxyConnectionId++ + + if c.config.DebugLog { + log.Printf("Client.listenForwardProxy(): Received incoming forward proxy connection %d\n", forwardProxyConnectionId) + } + + err := ct.send(proto.ControlMessage{Action: proto.RequestForwardProxy}) + if err != nil { + return fmt.Errorf("failure sending control message: %s", err) + } + + if c.config.DebugLog { + log.Printf("Client.listenForwardProxy(): forward proxy connection %d: sent RequestForwardProxy to server \n", forwardProxyConnectionId) + } + + remoteConn, err := c.session.Accept() + if err != nil { + return err + } + + if c.config.DebugLog { + log.Printf("Client.listenForwardProxy(): forward proxy connection %d: accepted yamux session \n", forwardProxyConnectionId) + } + + go func() { + blockingBidirectionalPipe(conn, remoteConn, "from client", "to SOCKS server", strconv.Itoa(forwardProxyConnectionId), c.config.DebugLog) + conn.Close() + remoteConn.Close() + }() + } +} diff --git a/tunnel-lib/helper_test.go b/tunnel-lib/helper_test.go index 7564e1b..f968147 100644 --- a/tunnel-lib/helper_test.go +++ b/tunnel-lib/helper_test.go @@ -14,8 +14,8 @@ import ( "os" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" - "git.sequentialread.com/forest/tunnel/tunnel-lib/tunneltest" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" + "git.sequentialread.com/forest/threshold/tunnel-lib/tunneltest" "github.com/gorilla/websocket" ) diff --git a/tunnel-lib/proto/control_msg.go b/tunnel-lib/proto/control_msg.go index a92700f..f1135b7 100644 --- a/tunnel-lib/proto/control_msg.go +++ b/tunnel-lib/proto/control_msg.go @@ -12,4 +12,5 @@ type Action int // ControlMessage actions. const ( RequestClientSession Action = iota + 1 + RequestForwardProxy Action = iota + 2 ) diff --git a/tunnel-lib/proto/proto.go b/tunnel-lib/proto/proto.go index 5e5a61a..f056cc1 100644 --- a/tunnel-lib/proto/proto.go +++ b/tunnel-lib/proto/proto.go @@ -5,9 +5,6 @@ const ( // ControlPath is http.Handler url path for control connection. ControlPath = "/_controlPath/" - // ClientIdentifierHeader is header carrying information about tunnel identifier. - ClientIdentifierHeader = "X-Threshold-ClientId" - // control messages // Connected is message sent by server to client when control connection was established. diff --git a/tunnel-lib/proxy.go b/tunnel-lib/proxy.go index aa8975a..8f3634e 100644 --- a/tunnel-lib/proxy.go +++ b/tunnel-lib/proxy.go @@ -7,30 +7,12 @@ import ( "strings" "sync" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" ) // ProxyFunc is responsible for forwarding a remote connection to local server and writing the response back. type ProxyFunc func(remote net.Conn, msg *proto.ControlMessage) -// ProxyFuncs is a collection of ProxyFunc. -type ProxyFuncs struct { - // TCP is custom implementation of TCP proxing. - TCP ProxyFunc -} - -// Proxy returns a ProxyFunc that uses custom function if provided, otherwise falls back to DefaultProxyFuncs. -func Proxy(p ProxyFuncs) ProxyFunc { - return func(remote net.Conn, msg *proto.ControlMessage) { - if p.TCP == nil { - panic("TCP handler is required for Proxy") - } - - // I removed all the other handlers that are not TCP 😇 - p.TCP(remote, msg) - } -} - // Join copies data between local and remote connections. // It reads from one connection and writes to the other. // It's a building block for ProxyFunc implementations. diff --git a/tunnel-lib/server.go b/tunnel-lib/server.go index e1d0ef6..7af67b5 100644 --- a/tunnel-lib/server.go +++ b/tunnel-lib/server.go @@ -4,7 +4,6 @@ package tunnel import ( - "errors" "fmt" "io" "log" @@ -16,14 +15,17 @@ import ( "sync" "time" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + errors "git.sequentialread.com/forest/pkg-errors" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" + "github.com/armon/go-socks5" "github.com/hashicorp/yamux" ) var ( errNoClientSession = errors.New("no client session established") defaultTimeout = 10 * time.Second + metricChunkSize = 1000000 // one megabyte ) // Server is responsible for proxying public connections to the client over a @@ -40,6 +42,8 @@ type Server struct { // sessionsMu protects sessions. sessionsMu sync.Mutex + socks5Server *socks5.Server + // controls contains the control connection from the client to the server. controls *controls @@ -70,12 +74,27 @@ type Server struct { // the domain of the server, used for validating clientIds domain string + bandwidth chan<- BandwidthMetric + + multitenantMode bool + + // see ServerConfig.ValidateCertificate comment + validateCertificate func(domain string, multitenantMode bool, request *http.Request) (identifier string, tenantId string, err error) + // yamuxConfig is passed to new yamux.Session's yamuxConfig *yamux.Config debugLog bool } +type BandwidthMetric struct { + Bytes int + RemoteAddress net.Addr + Inbound bool + Service string + ClientId string +} + // ServerConfig defines the configuration for the Server type ServerConfig struct { // StateChanges receives state transition details each time client @@ -91,6 +110,19 @@ type ServerConfig struct { // the domain of the server, used for validating clientIds Domain string + Bandwidth chan<- BandwidthMetric + + // function that analyzes the TLS client certificate of the request. + // this is based on the CommonName attribute of the TLS certificate. + // If we are in multi-tenant mode, it must be formatted like `.@` + // otherwise, it must be formatted like `@` + // must match the configured Domain of this Threshold server + // the identifier it returns will be `.` or ``. + // the tenantId it returns will be `` or "" + ValidateCertificate func(domain string, multiTenantMode bool, request *http.Request) (identifier string, tenantId string, err error) + + MultitenantMode bool + // YamuxConfig defines the config which passed to every new yamux.Session. If nil // yamux.DefaultConfig() is used. YamuxConfig *yamux.Config @@ -113,14 +145,24 @@ func NewServer(cfg *ServerConfig) (*Server, error) { connCh: connCh, } + socks5Server, err := socks5.New(&socks5.Config{}) + + if err != nil { + return nil, errors.Wrap(err, "could not create new socks5 server") + } + s := &Server{ pending: make(map[string]chan net.Conn), sessions: make(map[string]*yamux.Session), + socks5Server: socks5Server, onConnectCallbacks: newCallbacks("OnConnect"), onDisconnectCallbacks: newCallbacks("OnDisconnect"), virtualAddrs: newVirtualAddrs(opts), controls: newControls(), states: make(map[string]ClientState), + multitenantMode: cfg.MultitenantMode, + validateCertificate: cfg.ValidateCertificate, + bandwidth: cfg.Bandwidth, stateCh: cfg.StateChanges, domain: cfg.Domain, yamuxConfig: yamuxConfig, @@ -140,7 +182,9 @@ func (s *Server) ServeHTTP(responseWriter http.ResponseWriter, request *http.Req // going to infer and call the respective path handlers. switch fmt.Sprintf("%s/", path.Clean(request.URL.Path)) { case proto.ControlPath: - s.checkConnect(s.controlHandler).ServeHTTP(responseWriter, request) + s.checkConnect(func(w http.ResponseWriter, r *http.Request) error { + return s.controlHandler(w, r) + }).ServeHTTP(responseWriter, request) case "/ping/": if request.Method == "GET" { fmt.Fprint(responseWriter, "pong!") @@ -154,11 +198,13 @@ func (s *Server) ServeHTTP(responseWriter http.ResponseWriter, request *http.Req func (s *Server) serveTCP() { for conn := range s.connCh { + log.Println(3) go s.serveTCPConn(conn) } } func (s *Server) serveTCPConn(conn net.Conn) { + log.Println(4) err := s.handleTCPConn(conn) if err != nil { log.Printf("Server.serveTCPConn(): failed to serve %q: %s\n", conn.RemoteAddr(), err) @@ -167,9 +213,10 @@ func (s *Server) serveTCPConn(conn net.Conn) { } func (s *Server) handleTCPConn(conn net.Conn) error { - // TODO getListenerInfo should return the bytes we read to try to get teh hostname - // then we stream.write those right after the SendProxyProtocolv1 bit. + + log.Println(5) listenerInfo, sniHostname, connectionHeader := s.virtualAddrs.getListenerInfo(conn) + log.Println(6) if listenerInfo == nil { return fmt.Errorf("no virtual host available for %s (hostname: %s)", conn.LocalAddr(), sniHostname) } @@ -179,12 +226,15 @@ func (s *Server) handleTCPConn(conn net.Conn) error { return err } - service := strconv.Itoa(port) + service := fmt.Sprintf("port%d", port) if listenerInfo.BackendService != "" { service = listenerInfo.BackendService } - stream, err := s.dial(listenerInfo.AssociatedClientIdentity, service) + log.Printf("7: dial(%s, %s)", listenerInfo.AssociatedClientId, service) + stream, err := s.dial(listenerInfo.AssociatedClientId, service) + log.Println(8) if err != nil { + log.Printf("Server.handleTCPConn(): failed to dial %s on client %s: %s\n", service, listenerInfo.AssociatedClientId, err) return err } @@ -205,28 +255,53 @@ func (s *Server) handleTCPConn(conn net.Conn) error { stream.Write([]byte(fmt.Sprintf("PROXY %s %s %s %s %s\r\n", proxyNetwork, remoteHost, localHost, remotePort, localPort))) } + log.Println(9) if len(connectionHeader) > 0 { stream.Write(connectionHeader) } + log.Println(10) disconnectedChan := make(chan bool) - go s.proxy(disconnectedChan, conn, stream, "from proxy-client to client") - go s.proxy(disconnectedChan, stream, conn, "from client to proxy-client") + // We don't include remote address or service info here + // because the server should only collect the minimum required amount of metric data + // -- the client can collect more detailed metrics if they want. + + inboundMetric := BandwidthMetric{ + Service: listenerInfo.BackendService, + ClientId: listenerInfo.AssociatedClientId, + Inbound: true, + } + outboundMetric := BandwidthMetric{ + Service: listenerInfo.BackendService, + ClientId: listenerInfo.AssociatedClientId, + Inbound: false, + } + + go s.proxy(disconnectedChan, conn, stream, outboundMetric, s.bandwidth, "outbound from tunnel to remote client") + go s.proxy(disconnectedChan, stream, conn, inboundMetric, s.bandwidth, "inbound from remote client to tunnel") // Once one member of this conversation has disconnected, we should end the conversation for all parties. <-disconnectedChan + log.Println(11) return nonil(stream.Close(), conn.Close()) } -func (s *Server) proxy(disconnectedChan chan bool, dst, src net.Conn, side string) { +func (s *Server) proxy(disconnectedChan chan bool, dst, src net.Conn, metric BandwidthMetric, bandwidth chan<- BandwidthMetric, side string) { defer (func() { disconnectedChan <- true })() if s.debugLog { log.Printf("Server.proxy(): tunneling %s -> %s (%s)\n", src.RemoteAddr(), dst.RemoteAddr(), side) } - n, err := io.Copy(dst, src) + var n int64 + var err error + if bandwidth != nil { + n, err = ioCopyWithMetrics(dst, src, metric, bandwidth) + } else { + n, err = io.Copy(dst, src) + } + if s.debugLog { log.Printf("Server.proxy(): tunneled %d bytes %s -> %s (%s): %v\n", n, src.RemoteAddr(), dst.RemoteAddr(), side, err) } @@ -249,7 +324,7 @@ func (s *Server) dial(identifier string, service string) (net.Conn, error) { } if s.debugLog { - log.Printf("Server.proxy(): Sending control msg %+v\n", msg) + log.Printf("Server.proxy(): Sending control msg %+v to %s \n", msg, identifier) } // ask client to open a session to us, so we can accept it @@ -285,28 +360,13 @@ func (s *Server) dial(identifier string, service string) (net.Conn, error) { // controlHandler is used to capture incoming tunnel connect requests into raw // tunnel TCP connections. func (s *Server) controlHandler(w http.ResponseWriter, r *http.Request) (ctErr error) { - identifier := r.Header.Get(proto.ClientIdentifierHeader) - - // When TLS is turned on, the Client Authentication certificate is required, so in that case - // if we got to this point, we should make sure - // the ClientIdentifier header matches the CommonName on the client cert. - // https://stackoverflow.com/questions/31751764/get-remote-ssl-certificate-in-golang - if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { - cn := r.TLS.PeerCertificates[0].Subject.CommonName - if fmt.Sprintf("%s@%s", identifier, s.domain) != cn { - return fmt.Errorf( - "\"%s: %s\" does not match TLS certificate CommonName %s", - proto.ClientIdentifierHeader, identifier, cn, - ) - } - } - // We will allow clients to connect even if they are not configured to be used yet. - // In this case they have an empty set of listening front-end ports. - // ok := s.hasIdentifier(identifier) - // if !ok { - // return fmt.Errorf("no host associated for identifier %s. please use server.AddAddr()", identifier) - // } + clientId, tenantId, err := s.validateCertificate(s.domain, s.multitenantMode, r) + fmt.Println(tenantId) + if err != nil { + return err + } + identifier := clientId ct, ok := s.getControl(identifier) if ok { @@ -408,12 +468,19 @@ func (s *Server) controlHandler(w http.ResponseWriter, r *http.Request) (ctErr e func (s *Server) listenControl(ct *control) { s.onConnect(ct.identifier) + connectionId := 0 for { - var msg map[string]interface{} + + connectionId++ + + var msg proto.ControlMessage err := ct.dec.Decode(&msg) if err != nil { if s.debugLog { - log.Printf("Server.listenControl(): Closing client connection: '%s'\n", ct.identifier) + log.Printf( + "Server.listenControl(): connectionId: %d: Closing connection for client: '%s'\n", + connectionId, ct.identifier, + ) } // close client connection so it reconnects again @@ -426,7 +493,7 @@ func (s *Server) listenControl(ct *control) { s.onDisconnect(ct.identifier, err) if err != io.EOF { - log.Printf("Server.listenControl(): decode err: %s\n", err) + log.Printf("Server.listenControl(): connectionId: %d decode err: %s\n", connectionId, err) } return } @@ -435,7 +502,48 @@ func (s *Server) listenControl(ct *control) { // underlying connection needs to establihsed, we know when we have // disconnection(above), so we can cleanup the connection. if s.debugLog { - log.Printf("Server.listenControl(): msg: %s\n", msg) + log.Printf("Server.listenControl(): connectionId: %d msg: %s\n", connectionId, msg) + } + + if msg.Action == proto.RequestForwardProxy { + log.Printf("Server.listenControl(): connectionId: %d s.getSession(%s)\n", connectionId, ct.identifier) + session, err := s.getSession(ct.identifier) + if err != nil { + fmt.Printf( + "failed to accept RequestForwardProxy from client '%s' connectionId: %d: getSession() returned %s\n", + connectionId, ct.identifier, err, + ) + } + log.Printf("Server.listenControl(): connectionId: %d session.Open()\n", connectionId) + remote, err := session.Open() + if err != nil { + fmt.Printf( + "failed to accept RequestForwardProxy from client '%s' connectionId: %d: session.Open() returned %s\n", + connectionId, ct.identifier, err, + ) + } + + go func(connectionId int) { + defer remote.Close() + metricsWrappedConn := ConnWithMetrics{ + underlying: remote, + metricsChannel: s.bandwidth, + inbound: false, + clientId: ct.identifier, + } + + log.Printf("Server.listenControl(): connectionId: %d s.socks5Server.ServeConn(metricsWrappedConn)\n", connectionId) + err := s.socks5Server.ServeConn(metricsWrappedConn) + if err != nil { + fmt.Printf( + "error in RequestForwardProxy from client '%s' connectionId: %d: socks5Server.ServeConn() failed with %s\n", + ct.identifier, connectionId, err, + ) + } + }(connectionId) + + } else { + fmt.Printf("control message from client had action = %d, expected %d\n", msg.Action, proto.RequestForwardProxy) } } } @@ -604,6 +712,7 @@ func copyHeader(dst, src http.Header) { // checkConnect checks whether the incoming request is HTTP CONNECT method. func (s *Server) checkConnect(fn func(w http.ResponseWriter, r *http.Request) error) http.Handler { + server := s return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "CONNECT" { http.Error(w, "405 must CONNECT\n", http.StatusMethodNotAllowed) @@ -613,8 +722,9 @@ func (s *Server) checkConnect(fn func(w http.ResponseWriter, r *http.Request) er if err := fn(w, r); err != nil { log.Printf("Server.checkConnect(): Handler err: %v\n", err.Error()) - if identifier := r.Header.Get(proto.ClientIdentifierHeader); identifier != "" { - s.onDisconnect(identifier, err) + identifier, _, err := server.validateCertificate(server.domain, server.multitenantMode, r) + if err == nil { + server.onDisconnect(identifier, err) } http.Error(w, err.Error(), 502) diff --git a/tunnel-lib/tcpproxy.go b/tunnel-lib/tcpproxy.go index ea9011f..aeff546 100644 --- a/tunnel-lib/tcpproxy.go +++ b/tunnel-lib/tcpproxy.go @@ -3,8 +3,9 @@ package tunnel import ( "log" "net" + "strings" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" ) // TCPProxy forwards TCP streams. @@ -34,9 +35,14 @@ func (p *TCPProxy) Proxy(remote net.Conn, msg *proto.ControlMessage) { //log.Debug("Dialing local server: %q", localAddr) //fmt.Printf("Dialing local server: %q\n\n", localAddr) - local, err := net.DialTimeout("tcp", localAddr, defaultTimeout) + network := "tcp" + if strings.HasPrefix(localAddr, "unix//") { + network = "unix" + localAddr = strings.TrimPrefix(localAddr, "unix//") + } + local, err := net.DialTimeout(network, localAddr, defaultTimeout) if err != nil { - log.Println("TCPProxy.Proxy(): Dialing local server %q failed: %s", localAddr, err) + log.Printf("TCPProxy.Proxy(): Dialing local server %s failed: %s", localAddr, err) return } diff --git a/tunnel-lib/tunnel_test.go b/tunnel-lib/tunnel_test.go index e3f7d5b..2f0af6b 100644 --- a/tunnel-lib/tunnel_test.go +++ b/tunnel-lib/tunnel_test.go @@ -7,8 +7,8 @@ import ( "testing" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" - "git.sequentialread.com/forest/tunnel/tunnel-lib/tunneltest" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" + "git.sequentialread.com/forest/threshold/tunnel-lib/tunneltest" "github.com/cenkalti/backoff" ) @@ -177,7 +177,7 @@ func TestNoHost(t *testing.T) { Identifier: "unknown", ServerAddr: tt.ServerAddr().String(), Backoff: noBackoff, - Debug: testing.Verbose(), + DebugLog: true, }) if err != nil { t.Fatalf("client error: %s", err) diff --git a/tunnel-lib/tunneltest/state_recorder.go b/tunnel-lib/tunneltest/state_recorder.go index 851dbe3..1d13ed7 100644 --- a/tunnel-lib/tunneltest/state_recorder.go +++ b/tunnel-lib/tunneltest/state_recorder.go @@ -6,7 +6,7 @@ import ( "sync" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) var ( diff --git a/tunnel-lib/tunneltest/tunneltest.go b/tunnel-lib/tunneltest/tunneltest.go index 645aba7..c773576 100644 --- a/tunnel-lib/tunneltest/tunneltest.go +++ b/tunnel-lib/tunneltest/tunneltest.go @@ -14,7 +14,7 @@ import ( "testing" "time" - tunnel "git.sequentialread.com/forest/tunnel/tunnel-lib" + tunnel "git.sequentialread.com/forest/threshold/tunnel-lib" ) var debugNet = os.Getenv("DEBUGNET") == "1" @@ -185,7 +185,7 @@ func NewTunnelTest() (*TunnelTest, error) { cfg := &tunnel.ServerConfig{ StateChanges: rec.C(), - Debug: testing.Verbose(), + DebugLog: true, } s, err := tunnel.NewServer(cfg) if err != nil { @@ -266,19 +266,15 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { l = dbgListener{l} } - localAddr := l.Addr().String() - httpProxy := &tunnel.HTTPProxy{LocalAddr: localAddr} + //localAddr := l.Addr().String() tcpProxy := &tunnel.TCPProxy{FetchLocalAddr: tt.fetchLocalAddr} cfg := &tunnel.ClientConfig{ - Identifier: ident, - ServerAddr: tt.ServerAddr().String(), - Proxy: tunnel.Proxy(tunnel.ProxyFuncs{ - HTTP: httpProxy.Proxy, - TCP: tcpProxy.Proxy, - }), + Identifier: ident, + ServerAddr: tt.ServerAddr().String(), + Proxy: tcpProxy.Proxy, StateChanges: t.StateChanges, - Debug: testing.Verbose(), + DebugLog: true, } // Register tunnel: @@ -317,6 +313,7 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { remote = tt.Listeners[t.RemoteAddrIdent][1] tt.mu.Unlock() } else { + net.ResolveTCPAddr("tcp", t.RemoteAddr) remote, err = net.Listen("tcp", t.RemoteAddr) if err != nil { return false, fmt.Errorf("failed to listen on %q for %q tunnel: %s", t.RemoteAddr, ident, err) @@ -331,7 +328,9 @@ func (tt *TunnelTest) serveSingle(ident string, t *Tunnel) (bool, error) { addrIdent = t.ClientIdent } - tt.Server.AddAddr(remote, t.IP, addrIdent) + // TODO this whole thing needs to be refactored because tt.Server.AddAddr does not accept a listener as an argument any more. + // Used to be like: tt.Server.AddAddr(remote, blahblahblah) + tt.Server.AddAddr(t.IP, 8080, "*", addrIdent, true, t.RemoteAddr) tt.mu.Lock() tt.Listeners[ident] = [2]net.Listener{l, remote} @@ -432,7 +431,7 @@ func (tt *TunnelTest) popServedDeps(tunnels map[string]*Tunnel) error { return nil } -func (tt *TunnelTest) fetchLocalAddr(port int) (string, error) { +func (tt *TunnelTest) fetchLocalAddr(service string) (string, error) { tt.mu.Lock() defer tt.mu.Unlock() @@ -442,17 +441,18 @@ func (tt *TunnelTest) fetchLocalAddr(port int) (string, error) { continue } - _, remotePort, err := parseHostPort(l[1].Addr().String()) - if err != nil { - return "", err - } + remotePort := l[1].Addr().String() + // _, remotePort, err := parseHostPort() + // if err != nil { + // return "", err + // } - if port == remotePort { + if service == remotePort { return l[0].Addr().String(), nil } } - return "", fmt.Errorf("no route for %d port", port) + return "", fmt.Errorf("no route for %s service string", service) } func (tt *TunnelTest) ServerAddr() net.Addr { diff --git a/tunnel-lib/util.go b/tunnel-lib/util.go index 94ed5d1..1078337 100644 --- a/tunnel-lib/util.go +++ b/tunnel-lib/util.go @@ -3,11 +3,13 @@ package tunnel import ( "crypto/tls" "fmt" + "io" + "log" "net" "sync" "time" - "git.sequentialread.com/forest/tunnel/tunnel-lib/proto" + "git.sequentialread.com/forest/threshold/tunnel-lib/proto" "github.com/cenkalti/backoff" ) @@ -33,7 +35,7 @@ type expBackoff struct { bk *backoff.ExponentialBackOff } -func newForeverBackoff() *expBackoff { +func NewExponentialBackoff() *expBackoff { eb := &expBackoff{ bk: backoff.NewExponentialBackOff(), } @@ -119,3 +121,196 @@ func scheme(conn net.Conn) (scheme string) { return } + +func blockingBidirectionalPipe(conn1, conn2 net.Conn, name1, name2 string, connectionId string, debugLog bool) { + chanFromConn := func(conn net.Conn, name, connectionId string) chan []byte { + c := make(chan []byte) + + go func() { + b := make([]byte, 1024) + + for { + n, err := conn.Read(b) + if n > 0 { + res := make([]byte, n) + // Copy the buffer so it doesn't get changed while read by the recipient. + copy(res, b[:n]) + c <- res + } + if err != nil { + log.Printf("%s %s read error %s\n", connectionId, name, err) + c <- nil + break + } + } + }() + + return c + } + + chan1 := chanFromConn(conn1, fmt.Sprint(name1, "->", name2), connectionId) + chan2 := chanFromConn(conn2, fmt.Sprint(name2, "->", name1), connectionId) + + for { + select { + case b1 := <-chan1: + if b1 == nil { + if debugLog { + log.Printf("connection %s %s EOF\n", connectionId, name1) + } + return + } else { + conn2.Write(b1) + } + case b2 := <-chan2: + if b2 == nil { + if debugLog { + log.Printf("connection %s %s EOF\n", connectionId, name2) + } + return + } else { + conn1.Write(b2) + } + } + } +} + +// copied from the go standard library source code (io.Copy) with metric collection added. +func ioCopyWithMetrics(dst io.Writer, src io.Reader, metric BandwidthMetric, bandwidth chan<- BandwidthMetric) (written int64, err error) { + size := 32 * 1024 + if l, ok := src.(*io.LimitedReader); ok && int64(size) > l.N { + if l.N < 1 { + size = 1 + } else { + size = int(l.N) + } + } + chunkForMetrics := 0 + buf := make([]byte, size) + + for { + nr, er := src.Read(buf) + if nr > 0 { + nw, ew := dst.Write(buf[0:nr]) + if nw > 0 { + chunkForMetrics += nw + if chunkForMetrics >= metricChunkSize { + bandwidth <- BandwidthMetric{ + Inbound: metric.Inbound, + Service: metric.Service, + ClientId: metric.ClientId, + RemoteAddress: metric.RemoteAddress, + Bytes: chunkForMetrics, + } + chunkForMetrics = 0 + } + written += int64(nw) + } + if ew != nil { + err = ew + break + } + if nr != nw { + err = io.ErrShortWrite + break + } + } + if er != nil { + if er != io.EOF { + err = er + } + break + } + } + if chunkForMetrics > 0 { + bandwidth <- BandwidthMetric{ + Inbound: metric.Inbound, + Service: metric.Service, + ClientId: metric.ClientId, + RemoteAddress: metric.RemoteAddress, + Bytes: chunkForMetrics, + } + } + return written, err +} + +type ConnWithMetrics struct { + underlying net.Conn + metricsChannel chan<- BandwidthMetric + inbound bool + service string + clientId string + inboundBytes int + outboundBytes int + remoteAddress net.Addr +} + +func (conn ConnWithMetrics) Read(b []byte) (n int, err error) { + n, err = conn.underlying.Read(b) + conn.Accumulate(conn.inbound, n) + return n, err +} + +func (conn ConnWithMetrics) Write(b []byte) (n int, err error) { + n, err = conn.underlying.Write(b) + conn.Accumulate(!conn.inbound, n) + return n, err +} + +func (conn ConnWithMetrics) Close() error { + if conn.inboundBytes > 0 { + conn.PushMetric(true, conn.inboundBytes) + } + if conn.outboundBytes > 0 { + conn.PushMetric(false, conn.outboundBytes) + } + return conn.underlying.Close() +} + +func (conn ConnWithMetrics) Accumulate(inbound bool, n int) { + if inbound { + conn.inboundBytes += n + + if conn.inboundBytes > metricChunkSize { + conn.PushMetric(true, conn.inboundBytes) + conn.inboundBytes = 0 + } + } else { + conn.outboundBytes += n + + if conn.outboundBytes > metricChunkSize { + conn.PushMetric(false, conn.outboundBytes) + conn.outboundBytes = 0 + } + } +} + +func (conn ConnWithMetrics) PushMetric(inbound bool, n int) { + conn.metricsChannel <- BandwidthMetric{ + Inbound: inbound, + ClientId: conn.clientId, + RemoteAddress: conn.remoteAddress, + Service: conn.service, + Bytes: n, + } +} + +func (conn ConnWithMetrics) LocalAddr() net.Addr { + return conn.underlying.LocalAddr() +} + +func (conn ConnWithMetrics) RemoteAddr() net.Addr { + return conn.underlying.RemoteAddr() +} + +func (conn ConnWithMetrics) SetDeadline(t time.Time) error { + return conn.underlying.SetDeadline(t) +} + +func (conn ConnWithMetrics) SetReadDeadline(t time.Time) error { + return conn.underlying.SetReadDeadline(t) +} + +func (conn ConnWithMetrics) SetWriteDeadline(t time.Time) error { + return conn.underlying.SetWriteDeadline(t) +} diff --git a/tunnel-lib/virtualaddr.go b/tunnel-lib/virtualaddr.go index 8fd0a51..ae09a84 100644 --- a/tunnel-lib/virtualaddr.go +++ b/tunnel-lib/virtualaddr.go @@ -16,9 +16,9 @@ type ListenerInfo struct { //Send the HAProxy PROXY protocol v1 header to the proxy client before streaming TCP from the remote client. SendProxyProtocolv1 bool - BackendService string - AssociatedClientIdentity string - HostnameGlob string + BackendService string + AssociatedClientId string + HostnameGlob string } type listener struct { @@ -46,13 +46,20 @@ type vaddrStorage struct { // ports map[int]*listener // port-based routing: maps port number to identifier // ips map[string]*listener // ip-based routing: maps ip address to identifier + httpHostRegex *regexp.Regexp + dotRegex *regexp.Regexp + globRegex *regexp.Regexp + mu sync.RWMutex } func newVirtualAddrs(opts *vaddrOptions) *vaddrStorage { return &vaddrStorage{ - vaddrOptions: opts, - listeners: make(map[string]*listener), + vaddrOptions: opts, + listeners: make(map[string]*listener), + httpHostRegex: regexp.MustCompile("[A-Z]+ [^ ]+ HTTP[^\n]+\n([A-Za-z0-9-]+: [^\n]+\n)*(H|h)ost: ([^\n]+)\n"), + dotRegex: regexp.MustCompile(`\.`), + globRegex: regexp.MustCompile(`\*+`), // ports: make(map[int]*listener), // ips: make(map[string]*listener), } @@ -65,13 +72,13 @@ func (l *listener) serve() { log.Printf("listener.serve(): failue listening on %q: %s\n", l.Addr(), err) return } - + log.Println(1) if atomic.LoadInt32(&l.done) != 0 { log.Printf("listener.serve(): stopped serving %q", l.Addr()) conn.Close() return } - + log.Println(2) l.connCh <- conn } } @@ -142,10 +149,10 @@ func (vaddr *vaddrStorage) Add(ip net.IP, port int, hostnameGlob string, ident s func (l *listener) addHost(hostnameGlob string, ident string, sendProxyProtocolv1 bool, service string) { l.backends = append(l.backends, ListenerInfo{ - HostnameGlob: hostnameGlob, - AssociatedClientIdentity: ident, - SendProxyProtocolv1: sendProxyProtocolv1, - BackendService: service, + HostnameGlob: hostnameGlob, + AssociatedClientId: ident, + SendProxyProtocolv1: sendProxyProtocolv1, + BackendService: service, }) } @@ -201,13 +208,14 @@ func (vaddr *vaddrStorage) Delete(ip net.IP, port int, hostnameGlob string) { func (vaddr *vaddrStorage) newListener(ip net.IP, port int) (*listener, error) { listenAddress := net.JoinHostPort(ip.String(), strconv.Itoa(port)) - fmt.Printf("now listening on %s\n\n", listenAddress) netListener, err := net.Listen("tcp", listenAddress) if err != nil { return nil, err } + fmt.Printf("now listening on %s\n\n", listenAddress) + return &listener{ Listener: netListener, vaddrOptions: vaddr.vaddrOptions, @@ -217,7 +225,7 @@ func (vaddr *vaddrStorage) newListener(ip net.IP, port int) (*listener, error) { func (vaddr *vaddrStorage) HasIdentifier(identifier string) bool { for _, listener := range vaddr.listeners { for _, backend := range listener.backends { - if backend.AssociatedClientIdentity == identifier { + if backend.AssociatedClientId == identifier { return true } } @@ -231,8 +239,29 @@ func (vaddr *vaddrStorage) HasIdentifier(identifier string) bool { } func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string, []byte) { - vaddr.mu.Lock() - defer vaddr.mu.Unlock() + + // TODO maybe want to figure out how to set the read timeout lower for this ?? + connectionHeader := make([]byte, 4096) + n, err := conn.Read(connectionHeader) + if err != nil && err != io.EOF { + log.Printf("vaddrStorage.getListenerInfo(): failed to read header for connection %q: %s", conn.LocalAddr(), err) + return nil, "", make([]byte, 0) + } + + hostname, err := getHostnameFromSNI(connectionHeader[:n]) + + if err != nil { + // If we failed to get the hostname from SNI, try to get it from HTTP/1.1 + + submatches := vaddr.httpHostRegex.FindSubmatch(connectionHeader[:n]) + //log.Printf("--\n%d\n--\n", len(submatches)) + if submatches != nil && len(submatches) == 4 { + //log.Printf("---\n\n%s\n\n%s\n\n%s\n\n---\n", string(submatches[1]), string(submatches[2]), string(submatches[3])) + // Trim any space or port number that might be on the host + split := strings.Split(strings.TrimSpace(string(submatches[3])), ":") + hostname = split[0] + } + } host, port, err := parseHostPort(conn.LocalAddr().String()) if err != nil { @@ -240,6 +269,9 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string return nil, "", make([]byte, 0) } + vaddr.mu.Lock() + defer vaddr.mu.Unlock() + for _, listener := range vaddr.listeners { listenerHost, listenerPort, err := parseHostPort(listener.localAddr()) if err != nil { @@ -256,42 +288,32 @@ func (vaddr *vaddrStorage) getListenerInfo(conn net.Conn) (*ListenerInfo, string if err == nil && listenHostMatches && listenPortMatches { - //log.Printf("pre getHostnameFromSNI ") - - connectionHeader := make([]byte, 1024) - n, err := conn.Read(connectionHeader) - if err != nil && err != io.EOF { - log.Printf("vaddrStorage.getListenerInfo(): failed to read header for connection %q: %s", conn.LocalAddr(), err) - return nil, "", make([]byte, 0) - } - - hostname, err := getHostnameFromSNI(connectionHeader[:n]) - - // This will happen every time someone connects with a non-TLS protocol. - // Its not a big deal, we can ignore it. - // if err != nil { - // log.Printf("vaddrStorage.getListenerInfo(): failed to get SNI for connection %q: %s\n", conn.LocalAddr(), err) - // } - - //log.Printf("getHostnameFromSNI: %s\n", hostname) - recordSpecificity := -10 - var mostSpecificMatchingBackend *ListenerInfo = nil + mostSpecificMatchingBackend := ListenerInfo{} + hasMatchingBackend := false for _, backend := range listener.backends { globToUse := backend.HostnameGlob if globToUse == "" { globToUse = "*" } - numberOfPeriods := len(regexp.MustCompile(`\.`).FindAllString(globToUse, -1)) - numberOfGlobs := len(regexp.MustCompile(`\*+`).FindAllString(globToUse, -1)) + numberOfPeriods := len(vaddr.dotRegex.FindAllString(globToUse, -1)) + numberOfGlobs := len(vaddr.globRegex.FindAllString(globToUse, -1)) specificity := numberOfPeriods - numberOfGlobs + log.Printf("%d > %d && Glob(%s, %s)->(%t)\n", specificity, recordSpecificity, globToUse, hostname, Glob(globToUse, hostname)) if specificity > recordSpecificity && Glob(globToUse, hostname) { recordSpecificity = specificity - mostSpecificMatchingBackend = &backend + mostSpecificMatchingBackend = backend + hasMatchingBackend = true + log.Printf("mostSpecificMatchingBackend: %s->%s\n", mostSpecificMatchingBackend.AssociatedClientId, mostSpecificMatchingBackend.BackendService) } } - return mostSpecificMatchingBackend, hostname, connectionHeader[:n] + if hasMatchingBackend { + return &mostSpecificMatchingBackend, hostname, connectionHeader[:n] + } else { + return nil, hostname, connectionHeader[:n] + } + } } diff --git a/tunnel-lib/websocket_test.go b/tunnel-lib/websocket_test.go index a6f8de1..35c2726 100644 --- a/tunnel-lib/websocket_test.go +++ b/tunnel-lib/websocket_test.go @@ -6,7 +6,7 @@ import ( "reflect" "testing" - "git.sequentialread.com/forest/tunnel/tunnel-lib/tunneltest" + "git.sequentialread.com/forest/threshold/tunnel-lib/tunneltest" ) func testWebsocket(name string, n int, t *testing.T, tt *tunneltest.TunnelTest) { diff --git a/usage-example/client-config.json b/usage-example/client-config.json index 5587389..1d981b6 100644 --- a/usage-example/client-config.json +++ b/usage-example/client-config.json @@ -1,8 +1,7 @@ { "DebugLog": false, - "ClientIdentifier": "TestClient1", + "ClientId": "TestClient1", "ServerAddr": "localhost:9056", - "UseTls": true, "ServiceToLocalAddrMap": { "fooService": "127.0.0.1:9001" }, diff --git a/usage-example/server-config.json b/usage-example/server-config.json index 8161b04..1e3ca17 100644 --- a/usage-example/server-config.json +++ b/usage-example/server-config.json @@ -3,7 +3,6 @@ "DebugLog": false, "Domain": "example.com", "ListenPort": 9056, - "UseTls": true, "CaCertificateFilesGlob": "InternalCA+chain.crt", "ServerTlsKeyFile": "localhost.key", "ServerTlsCertificateFile": "localhost+chain.crt" diff --git a/usage-example/tunnels.json b/usage-example/tunnels.json index 87c24a0..5949381 100644 --- a/usage-example/tunnels.json +++ b/usage-example/tunnels.json @@ -1,6 +1,6 @@ [ { - "ClientIdentifier": "TestClient1", + "ClientId": "TestClient1", "ListenPort": 9000, "ListenAddress": "127.0.0.1", "ListenHostnameGlob": "*",