diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..b2f2718 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,39 @@ +name: Build + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + + build: + name: Build + runs-on: ubuntu-latest + steps: + + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: ^1.13 + + - name: Checkout + uses: actions/checkout@v2 + + - name: Get cache + uses: actions/cache@v2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Get dependencies + run: go get -v -t -d ./... + + - name: Build + run: go build -v . + + - name: Test + run: go test -v . diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..b2a825a --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,39 @@ +name: Release + +on: + release: + types: [created] + +jobs: + + release: + name: Release + runs-on: ubuntu-latest + steps: + + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: ^1.13 + + - name: Checkout + uses: actions/checkout@v2 + + - name: Get cache + uses: actions/cache@v2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Get dependencies + run: go get -v -t -d ./... + + - name: Build packages + run: ./scripts/build-release.sh "${GITHUB_REF#refs/tags/}" + + - name: Upload assets + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: ./scripts/upload-release.sh "${GITHUB_REF#refs/tags/}" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8ca76a1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +# Build products +lazyssh + +# Configuration +*.hcl + +# Release builds +lazyssh-* diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/COPYING @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..ac869a0 --- /dev/null +++ b/README.md @@ -0,0 +1,96 @@ +# LazySSH + +LazySSH is an SSH server that acts as a jump host only, and dynamically starts +temporary virtual machines. + +If you find yourself briefly starting a virtual machine just to SSH into it and +try something out, LazySSH is an attempt to automate that flow via just the +`ssh` command. LazySSH starts the machine for you when you connect, and shuts +it down (some time after) you disconnect. + +Another possible use is to have LazySSH sit in front of a build server to start +specific types of machines for your build. (Think different CPU architectures +or operating systems.) + +**Important**: LazySSH is a young piece of code. If you're going to use it to +create resources that cost money (like AWS EC2 instances), keep a close eye on +usage. If, for example, you put your laptop to sleep at the wrong time, or +LazySSH crashes for whatever reason, it may leave resources running. + +**Important**: The security of LazySSH has not been tested in any way, so it's +probably best to run it in a closed setting. (Not facing the public internet or +otherwise firewalled.) The SSH server implementation is based on +[golang.org/x/crypto]. + +License: AGPL v3 + +[golang.org/x/crypto]: https://pkg.go.dev/golang.org/x/crypto + +## Usage + +Grab a binary from the [releases page]. If you instead want to build LazySSH +yourself, you need at least Go 1.13, then just `go build`. + +[releases page]: https://github.com/stephank/lazyssh/releases + +You need to generate an SSH host key and client key. The host key is what the +server uses to identify itself, while the client key is what you connect with. + +```sh +# Both of these also generate a .pub file with the public half of the key pair. +ssh-keygen -t ed25519 -f lazyssh_host_key +ssh-keygen -t ed25519 -f lazyssh_client_key +``` + +Now create a `config.hcl` file that looks like: + +```hcl +server { + # Set this to the contents of lazyssh_host_key generated above. + host_key = <<-EOF + -----BEGIN OPENSSH PRIVATE KEY----- + [...] + -----END OPENSSH PRIVATE KEY----- + EOF + + # Set this to the contents of lazyssh_client_key.pub generated above. + authorized_key = <<-EOF + ssh-ed25519 [...] + EOF +} +``` + +The `server` block is followed by one or more `target` blocks. Here are the +types of targets currently supported, and links to the documentation: + +- [AWS EC2](./doc/providers/aws_ec2.md) +- [VirtualBox](./doc/providers/virtualbox.md) +- [Dummy forwarding](./doc/providers/forward.md) + +Once your config is ready, you can start the server: + +```sh +./lazyssh -config ./config.hcl +``` + +You usually need an entry for LazySSH in your `~/.ssh/config`, because the +`ssh` command otherwise doesn't make all options available for jump-hosts. Here +is a sample config: + +``` +Host lazyssh + Hostname localhost + Port 7922 + User jump + PreferredAuthentications publickey + IdentityFile ~/path/to/lazyssh_client_key + IdentitiesOnly yes +``` + +Now you should be ready to go: + +```sh +ssh -J lazyssh user@mytarget +``` + +For more details, see [the included documentation](./doc/index.md). diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..5fd9ab9 --- /dev/null +++ b/TODO.md @@ -0,0 +1,73 @@ +# LazySSH to-do + +This file lists a bunch of things the original author (stephank) thought would +be good improvements. + +I'm not necessarily working on these. If you want to pick something up, pull +requests are welcome, of course. If you'd like to indicate you're working on +something to avoid conflict, create an issue for it. + +## General + +- A code review by someone more experienced in Go would be appreciated. I'm not + sure how this would work, but I'm happy to discuss it in issues (Or if you're + bold, a pull request.) + +- Launchd agent plist + +- Systemd service unit + +- Socket activation + +- Nix package and NixOS module + +- Multiple authorized keys. + +- Persist state so any kind of interruption can recover management of an + instance. (We'd still interrupt all connections, but can hopefully prevent + accidental waste of resources this way.) + +- Figure out some way to provide meaningful feedback to clients while doing + work. This appears to be a difficult problem, because the OpenSSH client + doesn't print debug messages sent by the server unless using `-v`. The only + other opportunity appears to be the pre-auth banner, which is not useful for + us. Maybe someone else has a clever idea? + +- Figure out ways to cleanly interrupt machine startup. Maybe this is a + per-provider thing. + +- There may be additional `TODO` comments in code. + +## More providers + +- Google Cloud Compute + +- DigitalOcean Droplets + +- Hetzner Cloud + +- Scaleway + +- Vultr + +- Others? + +- It'd be interesting if there was some generic (but still friendly) way we + could bridge with Terraform providers or Packer builders. I haven't looked + into it, because it didn't seem useful to spend time on, given the very basic + requirements I started out with. + +## AWS EC2 + +- Connect more `RunInstances` options to config. + +- Some way to select an AMI based on filter criteria, like Terraform and Packer + allow. (ie. 'Automatically select the _latest_ Debian AMI') + +- Maybe add support for spot instances? I've never worked with them. + +- Optionally help with connectivity by creating a security group for the user. + +## VirtualBox + +- Create new temporary machines from an OVA. diff --git a/config.go b/config.go new file mode 100644 index 0000000..7f00322 --- /dev/null +++ b/config.go @@ -0,0 +1,148 @@ +package main + +import ( + "crypto/sha256" + "fmt" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/gohcl" + "github.com/hashicorp/hcl/v2/hclparse" + "github.com/stephank/lazyssh/providers" + "golang.org/x/crypto/ssh" +) + +// hclFiles is a File index expected by the DiagnosticWriter. +type hclFiles map[string]*hcl.File + +// hclConfig is used to unmarshal the HCL top-level. +type hclConfig struct { + Server hclServerConfig `hcl:"server,block"` + Targets []hclTargetConfig `hcl:"target,block"` +} + +// hclServerConfig is used to unmarshal the HCL `server` block. +type hclServerConfig struct { + Listen string `hcl:"listen,optional"` + HostKey string `hcl:"host_key,attr"` + AuthorizedKey string `hcl:"authorized_key,attr"` +} + +// hclTargetConfig is used to unmarshal HCL `target` blocks. +type hclTargetConfig struct { + Addr string `hcl:"addr,label"` + Type string `hcl:"type,label"` + hcl.Body `hcl:"body,remain"` +} + +// config is the result of parsing and validation the HCL configuration. +type config struct { + Listen string + HostKey ssh.Signer + AuthorizedKey [32]byte + providers.Providers +} + +// Parse a file containing HCL configuration. +// +// This method returns a hclFiles used in printing diagnostics, the *config +// which is non-nil on success, and Diagnostics which may be non-nil on even +// when successful. +func parseConfigFile(cfgFile string, factories providers.Factories) (hclFiles, *config, hcl.Diagnostics) { + // Step one: basic HCL parsing, without schema. + parser := hclparse.NewParser() + file, diags := parser.ParseHCLFile(cfgFile) + files := parser.Files() + if diags.HasErrors() { + // Can't provide more info if this doesn't succeed. + return files, nil, diags + } + + // Step two: Partial unmarshal using hclConfig and implied schema. + // Specifically, this does not unmarshal 'target' blocks. + hclConfig := hclConfig{} + if diags = gohcl.DecodeBody(file.Body, nil, &hclConfig); diags.HasErrors() { + // Can't provide more info if this doesn't succeed. + return files, nil, diags + } + + // Step three: Defaults and further field parsing. + // + // If these fail, we add diagnostics but continue to provide more feedback. + if hclConfig.Server.Listen == "" { + hclConfig.Server.Listen = "localhost:7922" + } + + hostKey, err := ssh.ParsePrivateKey([]byte(hclConfig.Server.HostKey)) + if err != nil { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Could not parse server host_key", + Detail: err.Error(), + }) + } + + authorizedKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hclConfig.Server.AuthorizedKey)) + if err != nil { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Could not parse server authorized_key", + Detail: err.Error(), + }) + } + + // Step four: For each 'target', ask the Factory for the associated type to + // parse config and instantiate a Provider. + // + // If these fail, we add diagnostics but continue to provide more feedback. + providers := make(providers.Providers) + for _, hclTarget := range hclConfig.Targets { + _, exists := providers[hclTarget.Addr] + if exists { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Duplicate target address", + Detail: fmt.Sprintf("Each target must have a unique address, but '%s' was used in multiple target definitions", hclTarget.Addr), + }) + } + + factory, ok := factories[hclTarget.Type] + if !ok { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid provider type", + Detail: fmt.Sprintf("Target '%s' has invalid provider type '%s'", hclTarget.Addr, hclTarget.Type), + }) + continue + } + + prov, err := factory.NewProvider(hclTarget.Addr, hclTarget.Body) + provDiags, ok := err.(hcl.Diagnostics) + if !ok && err != nil { + provDiags = hcl.Diagnostics{ + &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Provider configuration error", + Detail: fmt.Sprintf("Error in '%s' provider configuration for target '%s': %s", hclTarget.Type, hclTarget.Addr, err.Error()), + }, + } + } + + diags = append(diags, provDiags...) + if !provDiags.HasErrors() { + providers[hclTarget.Addr] = prov + } + } + + // Make sure we return nil Config if there are any errors. + if diags.HasErrors() { + return files, nil, diags + } + + cfg := &config{ + Listen: hclConfig.Server.Listen, + HostKey: hostKey, + AuthorizedKey: sha256.Sum256(authorizedKey.Marshal()), + Providers: providers, + } + return files, cfg, diags +} diff --git a/doc/index.md b/doc/index.md new file mode 100644 index 0000000..f40e2bf --- /dev/null +++ b/doc/index.md @@ -0,0 +1,59 @@ +# LazySSH documentation + +LazySSH uses [HCL] as its configuration format. By default it'll try to read +`config.hcl` in the current working directory, but a different file can be +specified using command-line arguments: + +```sh +lazyssh -config ./filename.hcl +``` + +[hcl]: https://pkg.go.dev/github.com/hashicorp/hcl/v2@v2.7.0 + +## Main server configuration + +The SSH server itself is configured with the `server` block. The following +example HCL lists all available options: + +```hcl +server { + + # The address the server will listen on. + listen = "localhost:7922" # The default + + # The SSH host key the server uses to identify itself. (Required) + host_key = <<-EOF + -----BEGIN OPENSSH PRIVATE KEY----- + [...] + -----END OPENSSH PRIVATE KEY----- + EOF + + # A single SSH public key the client uses to identify itself. (Required) + authorized_key = <<-EOF + ssh-ed25519 [...] + EOF + +} +``` + +## Target configuration + +The config file further contains any number of `target` blocks. These are all +in the format: + +```hcl +target "
" "" { + + # Type-specific settings + +} +``` + +Where `
` is the virtual address the SSH client can connect to through +this jump-host, and `` is one of the supported target types by LazySSH. + +Target types and their settings are documented separately: + +- [AWS EC2](./providers/aws_ec2.md) +- [VirtualBox](./providers/virtualbox.md) +- [Dummy forwarding](./providers/forward.md) diff --git a/doc/providers/aws_ec2.md b/doc/providers/aws_ec2.md new file mode 100644 index 0000000..aa99e89 --- /dev/null +++ b/doc/providers/aws_ec2.md @@ -0,0 +1,56 @@ +# AWS EC2 target type + +The `aws_ec2` target type uses the AWS SDK to launch (and eventually terminate) +a single EC2 instance. + +The AWS SDK looks for configuration in the same place as the AWS CLI, so you +may follow the configuration guide for the CLI to setup AWS credentials: +https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html + +These are the available target options: + +```hcl +target "
" "aws_ec2" { + + # The AMI to launch. (Required) + image_id = "ami-0a25128eec7dbf084" + + # The instance type to launch. (Required) + instance_type = "t4g.nano" + + # Name of the key pair to launch with. (Required) + key_name = "example" + + # Optional subnet ID to launch the instance in. + subnet_id = "subnet-00000000000000000" + + # Optional user data to provide to the instance. The contents of this will be + # base64 encoded for you, before it is sent to AWS. + user_data = <<-EOF + #cloud-config + packages: [jq] + EOF + + # Optional alternate profile to use from local AWS configuration. + profile = "default" # The default + + # Optional AWS region to use, if not specified in local AWS configuration. + region = "eu-west-1" + + # LazySSH waits for this TCP port to be open before forwarding connections to + # the EC2 instance. + check_port = 22 # The default + + # Whether to share the instance when LazySSH receives multiple SSH + # connections. This is the default, and when setting this to false + # explicitely, LazySSH will launch a unique instance for every SSH + # connection. + shared = true # The default + + # When shared is true, this is the amount of time the EC2 instance will + # linger before it is terminated. The default is to terminate the instance + # immediately when the last connection is closed. + linger = "0s" # The default + +} +``` diff --git a/doc/providers/forward.md b/doc/providers/forward.md new file mode 100644 index 0000000..1d5fa0f --- /dev/null +++ b/doc/providers/forward.md @@ -0,0 +1,15 @@ +# Dummy forwarding target type + +The `forward` target type does not actually create any resources, but simply +forwards to connection to a fixed address. + +These are the available target options: + +```hcl +target "
" "forward" { + + # The address to forward connections to. (Required) + to = "example.com" + +} +``` diff --git a/doc/providers/virtualbox.md b/doc/providers/virtualbox.md new file mode 100644 index 0000000..e522829 --- /dev/null +++ b/doc/providers/virtualbox.md @@ -0,0 +1,37 @@ +# VirtualBox target type + +The `virtualbox` target type starts and stops [VirtualBox] virtual machines +by automating calls to the `VBoxManage` command-line tool. + +These are the available target options: + +```hcl +target "
" "virtualbox" { + + # Name of the virtual machine to manage. (Required) + # This may also be the UUID of the machine. + name = "Debian" + + # Address where the machine is available. (Required) + # If you rely on port-forwarding, you may want to set this to 'localhost'. + addr = "192.168.0.100" + + # LazySSH waits for this TCP port to be open before forwarding connections to + # the above address. + check_port = 22 # The default + + # Which type of startup to request. + # Valid values: gui, headless, separate + start_mode = "headless" # The default + + # Which type of shutdown to request. + # Valid values: poweroff, acpipowerbutton, acpisleepbutton + stop_mode = "acpipowerbutton" # The default + + # The amount of time the virtual machine will linger before it is stopped. + # The default is to stop the instance immediately when the last connection is + # closed. + linger = "0s" # The default + +} +``` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..bbb54c6 --- /dev/null +++ b/go.mod @@ -0,0 +1,12 @@ +module github.com/stephank/lazyssh + +go 1.14 + +require ( + github.com/aws/aws-sdk-go-v2 v0.29.0 + github.com/aws/aws-sdk-go-v2/config v0.2.2 + github.com/aws/aws-sdk-go-v2/service/ec2 v0.29.0 + github.com/hashicorp/hcl/v2 v2.7.0 + golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 + golang.org/x/net v0.0.0-20201110031124-69a78807bb2b +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..9814a6a --- /dev/null +++ b/go.sum @@ -0,0 +1,74 @@ +github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= +github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= +github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= +github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= +github.com/apparentlymart/go-textseg/v12 v12.0.0 h1:bNEQyAGak9tojivJNkoqWErVCQbjdL7GzRt3F8NvfJ0= +github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= +github.com/aws/aws-sdk-go-v2 v0.29.0 h1:V/KKvuMO2hwHRg2SXJc5aasBHhD1AWbS6KMWg/Ueq1w= +github.com/aws/aws-sdk-go-v2 v0.29.0/go.mod h1:4d1/Ee0vCwCF7BfG1hCT3zu82493cRy5+VZ8JHvMPf0= +github.com/aws/aws-sdk-go-v2/config v0.2.2 h1:CBZGPlpL5h+BDoNBNTgypqMxlWgCome/O/i8gdjaOtE= +github.com/aws/aws-sdk-go-v2/config v0.2.2/go.mod h1:rty/i5U/IiXxO4kQmSXKwneNiTVqCxYVoO5BVXjCbfY= +github.com/aws/aws-sdk-go-v2/credentials v0.1.4 h1:ReVvyoYW/HriCnCWMoWC2ftvh0g9U4wS7lB5GFYK/ZE= +github.com/aws/aws-sdk-go-v2/credentials v0.1.4/go.mod h1:o0z92KOE6YJ/DyGSJmt83dG9YlGUc2n04QYwbfNsA8Q= +github.com/aws/aws-sdk-go-v2/ec2imds v0.1.4 h1:N3atV6naU7rFtS3gg/XU2ZuiPqzFm3HONBbnGDdPq1A= +github.com/aws/aws-sdk-go-v2/ec2imds v0.1.4/go.mod h1:h5WB2P4CTnVroyw/gvIiyMTtl/zvnKAC4H74EWiKOco= +github.com/aws/aws-sdk-go-v2/service/ec2 v0.29.0 h1:Cce76s5ELe4B5lcxJGmCNncRRUNu1PI11GoLx6cesxM= +github.com/aws/aws-sdk-go-v2/service/ec2 v0.29.0/go.mod h1:85Da92ykdcG4mD+cz4Vp7D3VsKf0/Bl6WHrE0V0jBig= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v0.1.1 h1:mX0AC4zkkDMNLxzF56aov9zb/35qa9hc6MmWlwA9JRo= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v0.1.1/go.mod h1:4DITQIlX1u/NzRPEo6FYXQ8cVVCp4QQHQFdyg/Fzerw= +github.com/aws/aws-sdk-go-v2/service/sts v0.29.0 h1:EOEsrzOQh+xU4lKbrkRoTybsP704I32GczRFsW6apEw= +github.com/aws/aws-sdk-go-v2/service/sts v0.29.0/go.mod h1:zV0Fx4GE1wPZJ3iHn1g7UxoPb+uJfqOkvBp3UQAq3bc= +github.com/awslabs/smithy-go v0.3.0 h1:I1EQ1P+VtxpuNnGYymATewaKrlnaYQwFvO8lNTsafbs= +github.com/awslabs/smithy-go v0.3.0/go.mod h1:hPOQwnmBLHsUphH13tVSjQhTAFma0/0XoZGbBcOuABI= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl/v2 v2.7.0 h1:IU8qz5UzZ1po3M1D9/Kq6S5zbDGVfI9bnzmC1ogKKmI= +github.com/hashicorp/hcl/v2 v2.7.0/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= +github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= +github.com/zclconf/go-cty v1.2.0 h1:sPHsy7ADcIZQP3vILvTjrh74ZA175TFP5vqiNK1UmlI= +github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b h1:uwuIcX0g4Yl1NC5XAz37xsr2lTtcqevgzYNVt49waME= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/main.go b/main.go new file mode 100644 index 0000000..5f57334 --- /dev/null +++ b/main.go @@ -0,0 +1,121 @@ +package main + +import ( + "crypto/sha256" + "crypto/subtle" + "errors" + "flag" + "log" + "net" + "os" + "os/signal" + "syscall" + + "github.com/hashicorp/hcl/v2" + "github.com/stephank/lazyssh/manager" + "github.com/stephank/lazyssh/providers" + "github.com/stephank/lazyssh/providers/aws_ec2" + "github.com/stephank/lazyssh/providers/forward" + "github.com/stephank/lazyssh/providers/virtualbox" + "golang.org/x/crypto/ssh" +) + +func main() { + configFile := flag.String("config", "config.hcl", "config file") + flag.Parse() + + factories := make(providers.Factories) + factories["forward"] = &forward.Factory{} + factories["virtualbox"] = &virtualbox.Factory{} + factories["aws_ec2"] = &aws_ec2.Factory{} + + // Parse config and always print diagnostics, but only fail on errors. + files, config, diags := parseConfigFile(*configFile, factories) + stdoutInfo, _ := os.Stdout.Stat() + isTty := (stdoutInfo.Mode() & os.ModeCharDevice) != 0 + writer := hcl.NewDiagnosticTextWriter(os.Stdout, files, 80, isTty) + writer.WriteDiagnostics(diags) + if diags.HasErrors() { + os.Exit(1) + } + + manager := manager.NewManager(config.Providers) + + sshConfig := &ssh.ServerConfig{} + sshConfig.AddHostKey(config.HostKey) + + sshConfig.PublicKeyCallback = func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { + if conn.User() != "jump" { + return nil, errors.New("Unauthorized") + } + + input := sha256.Sum256(key.Marshal()) + if subtle.ConstantTimeCompare(input[:], config.AuthorizedKey[:]) == 0 { + return nil, errors.New("Unauthorized") + } + + return nil, nil + } + + sshConfig.AuthLogCallback = func(conn ssh.ConnMetadata, method string, err error) { + if err == nil { + log.Printf("%v %s auth success\n", conn.RemoteAddr(), method) + } else { + log.Printf("%v %s auth attempt: %v\n", conn.RemoteAddr(), method, err) + } + } + + listener, err := net.Listen("tcp", config.Listen) + if err != nil { + log.Printf("Could not bind to port: %s\n", err) + os.Exit(1) + } + + log.Printf("Listening on %s\n", config.Listen) + + exitStatus := 0 + stopping := false + termCh := make(chan os.Signal) + signal.Notify(termCh, syscall.SIGINT, syscall.SIGTERM) + + go func() { + for { + rawConn, err := listener.Accept() + if err != nil { + if stopping { + break + } + exitStatus = 1 + log.Printf("Could not accept connection: %s\n", err.Error()) + termCh <- syscall.SIGTERM + return + } + + go func() { + conn, newChannels, reqs, err := ssh.NewServerConn(rawConn, sshConfig) + if err != nil { + log.Printf("%v handshake failed: %s\n", rawConn.RemoteAddr(), err.Error()) + return + } + + defer conn.Close() + go ssh.DiscardRequests(reqs) + + for ch := range newChannels { + manager.NewChannel(ch) + } + }() + } + }() + + // Only handle one interruption. The next one hard-exits the process. + <-termCh + signal.Reset() + + stopping = true + listener.Close() + log.Printf("Stopping all machines\n") + manager.Stop() + log.Printf("Shutdown complete\n") + os.Exit(exitStatus) +} diff --git a/manager/manager.go b/manager/manager.go new file mode 100644 index 0000000..ca0150d --- /dev/null +++ b/manager/manager.go @@ -0,0 +1,268 @@ +package manager + +import ( + "io" + "log" + "net" + "sync" + "time" + + "github.com/stephank/lazyssh/providers" + "golang.org/x/crypto/ssh" +) + +// channelOpenDirectMsg is used to unmarshal the payload of the SSH +// direct-tcpip channel open request. (RFC 4254 7.2) +type channelOpenDirectMsg struct { + RemoteAddr string + RemotePort uint32 + LocalAddr string + LocalPort uint32 +} + +// machine is a Machine wrapper with internal Manager fields added. +type machine struct { + providers.Machine + + // target is the virtual address of the target this machine belongs to. + target string + // shared indicates whether IsShared was true at the time the machine was + // created. If true, the machine will be in sharedMachines. + shared bool +} + +// machines is an index of running machines. +type machines map[*machine]struct{} + +// sharedMachines is an index of shared running machines by target address. +type sharedMachines map[string]*machine + +// Manager is the central piece responsible for starting/stopping machines +// using a Provider, and connecting SSH channels to the actual TCP port onn the +// target machine. +// +// Ownership of the Manager struct lies in the goroutine started in NewManager. +// Public methods on the Manager provide an interface to communicate with the +// goroutine. (This is essentially the agent pattern.) +type Manager struct { + newChannel chan ssh.NewChannel + stop chan chan struct{} + machStopped chan *machine + providers providers.Providers + machines + sharedMachines +} + +// NewManager creates a new Manager from the given Providers, and starts the +// main goroutine running the Manager message loop. +// +// Ownership of the Providers passed in is transferred to the Manager. +// Specifically, Provider methods are called from the Manager goroutine. +func NewManager(provs providers.Providers) *Manager { + mgr := &Manager{ + newChannel: make(chan ssh.NewChannel), + stop: make(chan chan struct{}), + machStopped: make(chan *machine), + providers: provs, + machines: make(machines), + sharedMachines: make(sharedMachines), + } + go func() { + var stoppingCh []chan struct{} + for stoppingCh == nil || len(mgr.machines) > 0 { + select { + case newChan := <-mgr.newChannel: + if stoppingCh == nil { + mgr.handleNewChannel(newChan) + } else { + newChan.Reject(ssh.Prohibited, "this server is shutting down") + } + case mach := <-mgr.machStopped: + mgr.handleMachineStopped(mach) + case replyCh := <-mgr.stop: + if stoppingCh == nil { + for mach := range mgr.machines { + mach.Stop <- struct{}{} + } + } + stoppingCh = append(stoppingCh, replyCh) + } + } + for _, ch := range stoppingCh { + ch <- struct{}{} + } + }() + return mgr +} + +// NewChannel transfers an SSH channel to the Manager for processing. +// +// The Manager will verify the channel is 'direct-tcpip' channel and parse +// parameters, start the target machine if necessary, then connect the channel +// to the requested TCP port on the target machine. +func (mgr *Manager) NewChannel(newChan ssh.NewChannel) { + mgr.newChannel <- newChan +} + +// Stop instructs the Manager to shutdown. +// +// Once the Manager goroutine receives the stop message, it will shut down all +// machines and reject any further requests. The Stop method waits for all +// machines to shut down before returning. +func (mgr *Manager) Stop() { + replyCh := make(chan struct{}) + mgr.stop <- replyCh + <-replyCh +} + +// handleNewChannel processes an SSH channel sent to the Manager. +// +// Runs on the Manager message loop goroutine. A separate goroutine is launched +// for the Provider to do processing on. +func (mgr *Manager) handleNewChannel(newChan ssh.NewChannel) { + if newChan.ChannelType() != "direct-tcpip" { + newChan.Reject(ssh.UnknownChannelType, "unsuported channel type") + return + } + + input := channelOpenDirectMsg{} + if err := ssh.Unmarshal(newChan.ExtraData(), &input); err != nil { + newChan.Reject(ssh.Prohibited, "invalid direct-tcpip parameters") + return + } + + prov, ok := mgr.providers[input.RemoteAddr] + if !ok { + newChan.Reject(ssh.ConnectionFailed, "unknown remote address") + return + } + + // Try for a shared machine, otherwise start a new one. + var mach *machine + if prov.IsShared() { + mach = mgr.sharedMachines[input.RemoteAddr] + } + + if mach == nil { + mach = &machine{ + target: input.RemoteAddr, + Machine: providers.Machine{ + ModActive: make(chan int8), + Translate: make(chan *providers.TranslateMsg), + Stop: make(chan struct{}, 1), + }, + } + + log.Printf("Starting machine for target '%s'\n", mach.target) + go func() { + prov.RunMachine(&mach.Machine) + mgr.machStopped <- mach + }() + + mgr.machines[mach] = struct{}{} + if prov.IsShared() { + mach.shared = true + mgr.sharedMachines[mach.target] = mach + } + } + + // Further connection setup is async, don't block the Manager message loop. + go connectChannel(newChan, mach, input) +} + +// connectChannel connects an SSH channel to a TCP port on a machine. +// +// Runs on a dedicated goroutine per channel, so is free to block. +func connectChannel(newChan ssh.NewChannel, mach *machine, input channelOpenDirectMsg) { + // Inform the Provider about active connections. + incActive(mach) + defer decActive(mach) + + // Request translation of the SSH direct-tcpip input parameters to a Dialer + // address. Providers do not respond to this until the machine is ready, so + // we'll block here. + msg := &providers.TranslateMsg{ + Addr: input.RemoteAddr, + Port: uint16(input.RemotePort), + Reply: make(chan string), + } + mach.Translate <- msg + addr := <-msg.Reply + if addr == "" { + // Usually happens when a request arrives during machine shutdown, but the + // Provider may also send this as an abort instruction for whatever reason. + newChan.Reject(ssh.ConnectionFailed, "service not available") + return + } + + // Connect and drive I/O in separate goroutines. + conn, err := net.Dial("tcp", addr) + if err != nil { + newChan.Reject(ssh.ConnectionFailed, err.Error()) + return + } + + tcp := conn.(*net.TCPConn) + ch, reqs, err := newChan.Accept() + if err != nil { + tcp.Close() + return + } + + defer ch.Close() + go ssh.DiscardRequests(reqs) + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer wg.Done() + defer tcp.CloseWrite() + io.Copy(tcp, ch) + }() + + go func() { + defer wg.Done() + defer tcp.CloseRead() + defer ch.CloseWrite() + io.Copy(ch, tcp) + }() + + // The WaitGroup ensures defers wait until I/O in *both* directions ends. + wg.Wait() +} + +// handleMachineStopped takes care of cleanup after a Machine stops. +// +// Runs on the Manager message loop goroutine. When the Provider RunMachine +// method ends, a message is sent to the Manager, which brings us here. +func (mgr *Manager) handleMachineStopped(mach *machine) { + log.Printf("Stopped machine for target '%s'\n", mach.target) + delete(mgr.machines, mach) + if mach.shared { + delete(mgr.sharedMachines, mach.target) + } + + // Discard any connectChannel messages that may have raced us here. 5 seconds + // should be ample, because this should only have the cover the time between + // the above deletes and any in-progress connectChannel goroutine startup. + go func() { + for { + select { + case <-mach.ModActive: + continue + case msg := <-mach.Translate: + msg.Reply <- "" + case <-time.After(5 * time.Second): + return + } + } + }() +} + +func incActive(mach *machine) { + mach.ModActive <- +1 +} + +func decActive(mach *machine) { + mach.ModActive <- -1 +} diff --git a/providers/aws_ec2/impl.go b/providers/aws_ec2/impl.go new file mode 100644 index 0000000..b8fbcd3 --- /dev/null +++ b/providers/aws_ec2/impl.go @@ -0,0 +1,257 @@ +// Implements the 'aws_ec2' target type, which uses AWS SDK to create and +// terminate EC2 virtual machines. +package aws_ec2 + +import ( + "encoding/base64" + "fmt" + "log" + "net" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/ec2" + "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/gohcl" + "github.com/stephank/lazyssh/providers" + "golang.org/x/net/context" +) + +type Factory struct{} + +type Provider struct { + ImageId string + InstanceType types.InstanceType + KeyName string + SubnetId *string + UserData64 *string + CheckPort uint16 + Shared bool + Linger time.Duration + Ec2 *ec2.Client +} + +type state struct { + id string + addr *string +} + +type hclTarget struct { + ImageId string `hcl:"image_id,attr"` + InstanceType string `hcl:"instance_type,attr"` + KeyName string `hcl:"key_name,attr"` + SubnetId *string `hcl:"subnet_id,optional"` + UserData *string `hcl:"user_data,optional"` + Profile *string `hcl:"profile,optional"` + Region *string `hcl:"region,optional"` + CheckPort uint16 `hcl:"check_port,optional"` + Shared *bool `hcl:"shared,optional"` + Linger string `hcl:"linger,optional"` +} + +const requestTimeout = 30 * time.Second + +func (factory *Factory) NewProvider(target string, hclBlock hcl.Body) (providers.Provider, error) { + parsed := &hclTarget{} + diags := gohcl.DecodeBody(hclBlock, nil, parsed) + if diags.HasErrors() { + return nil, diags + } + + var cfgMods []config.Config + if parsed.Profile != nil { + cfgMods = append(cfgMods, config.WithSharedConfigProfile(*parsed.Profile)) + } + if parsed.Region != nil { + cfgMods = append(cfgMods, config.WithRegion(*parsed.Region)) + } + awsCfg, err := config.LoadDefaultConfig(cfgMods...) + if err != nil { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Error loading AWS SDK configuration", + Detail: fmt.Sprintf("The AWS SDK reported an error while loading configuration: %s", err.Error()), + }) + } + + prov := &Provider{ + Ec2: ec2.NewFromConfig(awsCfg), + ImageId: parsed.ImageId, + InstanceType: types.InstanceType(parsed.InstanceType), + KeyName: parsed.KeyName, + SubnetId: parsed.SubnetId, + } + + if parsed.CheckPort == 0 { + prov.CheckPort = 22 + } else { + prov.CheckPort = parsed.CheckPort + } + + if parsed.Shared == nil { + prov.Shared = true + } else { + prov.Shared = *parsed.Shared + } + + if prov.Shared { + linger, err := time.ParseDuration(parsed.Linger) + if err == nil { + prov.Linger = linger + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid duration for 'linger' field", + Detail: fmt.Sprintf("The 'linger' value '%s' is not a valid duration: %s", parsed.Linger, err.Error()), + }) + } + } else if parsed.Linger != "" { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Field 'linger' was ignored", + Detail: fmt.Sprintf("The 'linger' field has no effect for 'aws_ec2' targets with 'shared = false'"), + }) + } + + if parsed.UserData != nil { + prov.UserData64 = aws.String(base64.StdEncoding.EncodeToString([]byte(*parsed.UserData))) + } + + if diags.HasErrors() { + return nil, diags + } + + return prov, diags +} + +func (prov *Provider) IsShared() bool { + return prov.Shared +} + +func (prov *Provider) RunMachine(mach *providers.Machine) { + if prov.start(mach) { + if prov.connectivityTest(mach) { + prov.msgLoop(mach) + } + prov.stop(mach) + } +} + +func (prov *Provider) start(mach *providers.Machine) bool { + bgCtx := context.Background() + + ctx, _ := context.WithTimeout(bgCtx, requestTimeout) + res, err := prov.Ec2.RunInstances(ctx, &ec2.RunInstancesInput{ + MinCount: aws.Int32(1), + MaxCount: aws.Int32(1), + ImageId: &prov.ImageId, + InstanceType: prov.InstanceType, + KeyName: &prov.KeyName, + SubnetId: prov.SubnetId, + UserData: prov.UserData64, + }) + if err != nil { + log.Printf("EC2 instance failed to start: %s\n", err.Error()) + return false + } + + inst := res.Instances[0] + log.Printf("Created EC2 instance '%s'\n", *inst.InstanceId) + + for i := 0; i < 20 && inst.State.Name == "pending"; i++ { + <-time.After(3 * time.Second) + + ctx, _ := context.WithTimeout(bgCtx, requestTimeout) + res, err := prov.Ec2.DescribeInstances(ctx, &ec2.DescribeInstancesInput{ + InstanceIds: []*string{inst.InstanceId}, + }) + if err != nil { + log.Printf("Could not check EC2 instance '%s' state: %s\n", *inst.InstanceId, err.Error()) + return false + } + if res.Reservations == nil || res.Reservations[0].Instances == nil { + log.Printf("EC2 instance '%s' disappeared while waiting for it to start\n", *inst.InstanceId) + return false + } + + inst = res.Reservations[0].Instances[0] + } + + if inst.State.Name != "running" { + log.Printf("EC2 instance '%s' in unexpected state '%s'\n", *inst.InstanceId, inst.State.Name) + return false + } + + log.Printf("EC2 instance '%s' is running\n", *inst.InstanceId) + mach.State = &state{ + id: *inst.InstanceId, + addr: inst.PublicIpAddress, + } + return true +} + +func (prov *Provider) stop(mach *providers.Machine) { + state := mach.State.(*state) + bgCtx := context.Background() + ctx, _ := context.WithTimeout(bgCtx, requestTimeout) + _, err := prov.Ec2.TerminateInstances(ctx, &ec2.TerminateInstancesInput{ + InstanceIds: []*string{aws.String(state.id)}, + }) + if err != nil { + log.Printf("EC2 instance '%s' failed to stop: %s\n", state.id, err.Error()) + } + log.Printf("Terminated EC2 instance '%s'\n", state.id) +} + +// Check port every 3 seconds for 2 minutes. +func (prov *Provider) connectivityTest(mach *providers.Machine) bool { + state := mach.State.(*state) + if state.addr == nil { + log.Printf("EC2 instance '%s' does not have a public IP address\n", state.id) + return false + } + checkAddr := fmt.Sprintf("%s:%d", *state.addr, prov.CheckPort) + checkTimeout := 3 * time.Second + var err error + var conn net.Conn + for i := 0; i < 40; i++ { + checkStart := time.Now() + conn, err = net.DialTimeout("tcp", checkAddr, checkTimeout) + if err == nil { + conn.Close() + log.Printf("Connectivity test succeeded for EC2 instance '%s'\n", state.id) + return true + } + time.Sleep(time.Until(checkStart.Add(checkTimeout))) + } + log.Printf("EC2 instance '%s' port check failed: %s\n", state.id, err.Error()) + return false +} + +func (prov *Provider) msgLoop(mach *providers.Machine) { + // TODO: Monitor machine status + state := mach.State.(*state) + active := <-mach.ModActive + for active > 0 { + for active > 0 { + select { + case mod := <-mach.ModActive: + active += mod + case msg := <-mach.Translate: + msg.Reply <- fmt.Sprintf("%s:%d", *state.addr, msg.Port) + case <-mach.Stop: + return + } + } + + // Linger + select { + case mod := <-mach.ModActive: + active += mod + case <-time.After(prov.Linger): + return + } + } +} diff --git a/providers/forward/impl.go b/providers/forward/impl.go new file mode 100644 index 0000000..814088b --- /dev/null +++ b/providers/forward/impl.go @@ -0,0 +1,54 @@ +// Implements the 'forward' type, which is essentially a dummy that doesn't +// really make any external calls, but simply forwards connections to a fixed +// address. +package forward + +import ( + "fmt" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/gohcl" + "github.com/stephank/lazyssh/providers" +) + +type Factory struct{} + +type Provider struct { + To string +} + +type hclTarget struct { + To string `hcl:"to,attr"` +} + +func (factory *Factory) NewProvider(target string, hclBlock hcl.Body) (providers.Provider, error) { + parsed := &hclTarget{} + if diags := gohcl.DecodeBody(hclBlock, nil, parsed); diags != nil { + return nil, diags + } + + prov := &Provider{ + To: parsed.To, + } + + return prov, nil +} + +func (prov *Provider) IsShared() bool { + return true +} + +func (prov *Provider) RunMachine(mach *providers.Machine) { + // Once started, we just never stop the shared Machine. This means we waste a + // goroutine per 'forward' target, but that's negligible. + for { + select { + case <-mach.ModActive: + continue + case msg := <-mach.Translate: + msg.Reply <- fmt.Sprintf("%s:%d", prov.To, msg.Port) + case <-mach.Stop: + return + } + } +} diff --git a/providers/interface.go b/providers/interface.go new file mode 100644 index 0000000..952c365 --- /dev/null +++ b/providers/interface.go @@ -0,0 +1,81 @@ +/* +Package providers defines the interfaces that LazySSH provider implementations +must conform to. +*/ +package providers + +import "github.com/hashicorp/hcl/v2" + +// Factory produces a Provider for a specific type of Machine, based on +// 'target' configuration provided by the user. +type Factory interface { + NewProvider(target string, hclBlock hcl.Body) (Provider, error) +} + +// Factories is an index of Factory objects by Machine type name. +type Factories map[string]Factory + +// Provider is responsible for managing the Machine lifecycle. +// +// Structs implementing Provider encapsulate parsed and validated 'target' +// configuration, and are created by the associated Factory for the type of +// Machine requested. +// +// Note that methods on Provider may be called from different goroutines. See +// the documentation of each method for details. +type Provider interface { + // IsShared indicates if multiple connections to the same target will not + // start a new Machine if one is already running. + // + // Called from the Manager message loop goroutine, and should not block. + IsShared() bool + + // RunMachine is responsible for managing the entire Machine lifecycle. + // + // Runs on a dedicated goroutine per machine, so is free to block. + // + // Typically, the Provider will immediately make external calls to start the + // machine, wait for proper connectivity to the Machine, then go into a loop + // processing the messages on the various channels on the Machine struct. + // + // Once the Provider determines there is no more activity via ModActive + // messages, or when it receives a Stop message, it exits the message loop + // and makes the necessary external calls to stop the machine again. + // Specifically, this method should not return without stopping the machine. + RunMachine(mach *Machine) +} + +// Providers is an index of configured Provider instances by Machine type name. +type Providers map[string]Provider + +// Machine represents a running machine, and holds channels via which the +// Provider receives commands from the Manager. +type Machine struct { + // ModActive messages indicate activity on the Machine. A message +1 + // indicates a new forwarded TCP connection is opened, and a message -1 + // indicates a TCP connection was closed. + ModActive chan int8 + // Translate messages are requests to translate SSH direct-tcpip parameters + // to a Dialer address. The provider should not process/reply to these + // messages until it has verified connectivity to the Machine. + Translate chan *TranslateMsg + // Stop messages are sent by the Manager to request the Machine immediately + // shut down. + Stop chan struct{} + // State can be used by the provider to store machine-specific state. + State interface{} +} + +// TranslateMsg is the type sent on the Machine Translate channel. +type TranslateMsg struct { + // Addr is the address the SSH client wants to connect to. It contains user + // input verbatim, so may be a IP address, hostname, etc. + Addr string + // Port is the TCP port the SSH client wants to connect to. + Port uint16 + // Reply is the channel the translation result is sent to. The result is a + // Dailer address used to make the actual TCP connection to the Machine. The + // provider should not send a reply until it has verified connectivity to the + // Machine. + Reply chan string +} diff --git a/providers/virtualbox/impl.go b/providers/virtualbox/impl.go new file mode 100644 index 0000000..2b409cf --- /dev/null +++ b/providers/virtualbox/impl.go @@ -0,0 +1,176 @@ +// Implements the 'virtualbox' target type, which uses the VirtualBox CLI to +// start/stop existing virtual machines. +package virtualbox + +import ( + "fmt" + "log" + "net" + "os" + "os/exec" + "time" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/gohcl" + "github.com/stephank/lazyssh/providers" +) + +type Factory struct{} + +type Provider struct { + Name string + Addr string + CheckPort uint16 + StartMode string + StopMode string + Linger time.Duration +} + +type hclTarget struct { + Name string `hcl:"name,attr"` + Addr string `hcl:"addr,attr"` + CheckPort uint16 `hcl:"check_port,optional"` + StartMode string `hcl:"start_mode,optional"` + StopMode string `hcl:"stop_mode,optional"` + Linger string `hcl:"linger,optional"` +} + +func (factory *Factory) NewProvider(target string, hclBlock hcl.Body) (providers.Provider, error) { + parsed := &hclTarget{} + diags := gohcl.DecodeBody(hclBlock, nil, parsed) + if diags.HasErrors() { + return nil, diags + } + + prov := &Provider{ + Name: parsed.Name, + Addr: parsed.Addr, + } + + if parsed.CheckPort == 0 { + prov.CheckPort = 22 + } else { + prov.CheckPort = parsed.CheckPort + } + + switch parsed.StartMode { + case "gui", "headless", "separate": + prov.StartMode = parsed.StartMode + case "": + prov.StartMode = "headless" + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid start_mode", + Detail: fmt.Sprintf("Value '%s' is invalid for start_mode. Must be one of: gui, headless, separate", prov.StartMode), + }) + } + + switch parsed.StopMode { + case "poweroff", "acpipowerbutton", "acpisleepbutton": + prov.StopMode = parsed.StopMode + case "": + prov.StopMode = "acpipowerbutton" + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid stop_mode", + Detail: fmt.Sprintf("Value '%s' is invalid for stop_mode. Must be one of: poweroff, acpipowerbutton, acpisleepbutton", prov.StopMode), + }) + } + + linger, err := time.ParseDuration(parsed.Linger) + if err == nil { + prov.Linger = linger + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid duration for 'linger' field", + Detail: fmt.Sprintf("The 'linger' value '%s' is not a valid duration: %s", parsed.Linger, err.Error()), + }) + } + + return prov, diags +} + +func (prov *Provider) IsShared() bool { + // Shared, because we launch existing virtual machines by name. + return true +} + +func (prov *Provider) RunMachine(mach *providers.Machine) { + if prov.start() { + if prov.connectivityTest() { + prov.msgLoop(mach) + } + prov.stop() + } +} + +func (prov *Provider) start() bool { + // TODO: What to do when the machine is already running? + cmd := exec.Command("VBoxManage", "startvm", prov.Name, fmt.Sprintf("--type=%s", prov.StartMode)) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + log.Printf("VirtualBox machine '%s' failed to start: %s\n", prov.Name, err.Error()) + return false + } + log.Printf("Started VirtualBox machine '%s'\n", prov.Name) + return true +} + +func (prov *Provider) stop() { + cmd := exec.Command("VBoxManage", "controlvm", prov.Name, prov.StopMode) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + log.Printf("VirtualBox machine '%s' failed to stop: %s\n", prov.Name, err.Error()) + } + log.Printf("Stopped VirtualBox machine '%s'\n", prov.Name) +} + +// Check port every 3 seconds for 2 minutes. +func (prov *Provider) connectivityTest() bool { + checkAddr := fmt.Sprintf("%s:%d", prov.Addr, prov.CheckPort) + checkTimeout := 3 * time.Second + var err error + var conn net.Conn + for i := 0; i < 40; i++ { + checkStart := time.Now() + conn, err = net.DialTimeout("tcp", checkAddr, checkTimeout) + if err == nil { + conn.Close() + log.Printf("Connectivity test succeeded for VirtualBox machine '%s'\n", prov.Name) + return true + } + time.Sleep(time.Until(checkStart.Add(checkTimeout))) + } + log.Printf("VirtualBox machine '%s' connectivity test failed: %s\n", prov.Name, err.Error()) + return false +} + +func (prov *Provider) msgLoop(mach *providers.Machine) { + // TODO: Monitor machine status + active := <-mach.ModActive + for active > 0 { + for active > 0 { + select { + case mod := <-mach.ModActive: + active += mod + case msg := <-mach.Translate: + msg.Reply <- fmt.Sprintf("%s:%d", prov.Addr, msg.Port) + case <-mach.Stop: + return + } + } + + // Linger + select { + case mod := <-mach.ModActive: + active += mod + case <-time.After(time.Duration(prov.Linger) * time.Second): + return + } + } +} diff --git a/scripts/build-release.sh b/scripts/build-release.sh new file mode 100755 index 0000000..65a1d4b --- /dev/null +++ b/scripts/build-release.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -ne 1 ]]; then + echo >&2 "Usage: $0 VERSION" + exit 64 +fi + +version="$1" + +extras=( + "README.md" + "COPYING" + "doc" +) + +build_targets=( + "GOOS=darwin GOARCH=amd64" + "GOOS=freebsd GOARCH=386 " + "GOOS=freebsd GOARCH=amd64" + "GOOS=linux GOARCH=386 " + "GOOS=linux GOARCH=amd64" + "GOOS=openbsd GOARCH=386 " + "GOOS=openbsd GOARCH=amd64" + "GOOS=solaris GOARCH=amd64" + "GOOS=windows GOARCH=386 " + "GOOS=windows GOARCH=amd64" +) + +set -x +for build_target in "${build_targets[@]}"; do + eval export $build_target + go build . + + pkgname="lazyssh-${version}-${GOOS}-${GOARCH}" + rm -fr "${pkgname}" + mkdir "${pkgname}" + cp -r "${extras[@]}" "./${pkgname}/" + + if [[ "${GOOS}" = "windows" ]]; then + mv lazyssh.exe "./${pkgname}/" + zip -r9 "${pkgname}.zip" "./${pkgname}" + else + mv lazyssh "./${pkgname}/" + tar -czf "${pkgname}.tar.gz" "./${pkgname}" + fi +done diff --git a/scripts/upload-release.sh b/scripts/upload-release.sh new file mode 100755 index 0000000..ac88df1 --- /dev/null +++ b/scripts/upload-release.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -ne 1 ]]; then + echo >&2 "Usage: $0 VERSION" + exit 64 +fi + +version="$1" + +flags=("-m" "") +for pkg in ./lazyssh-${version}-*.{tar.gz,zip}; do + flags+=("-a" "${pkg}") +done + +set -x +hub release edit "${flags[@]}" "${version}"