diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d0edba --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +letsencrypt-wf +letsencrypt-wf.exe +vendor/*/ +.DS_Store +*~ +pkg/* \ No newline at end of file diff --git a/.gopath b/.gopath new file mode 100644 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 8dada3e..0000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5c1eff0 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,194 @@ +Apache License +============== + +_Version 2.0, January 2004_ +_<>_ + +### Terms and Conditions for use, reproduction, and distribution + +#### 1. Definitions + +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +“Licensor” shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +“Legal Entity” shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, “control” means **(i)** the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the +outstanding shares, or **(iii)** beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising +permissions granted by this License. + +“Source” form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +“Object” form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +“Work” shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +“Derivative Works” shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +“Contribution” shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +“submitted” means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +#### 2. Grant of Copyright License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +#### 3. Grant of Patent License + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +#### 4. Redistribution + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +* **(a)** You must give any other recipients of the Work or Derivative Works a copy of +this License; and +* **(b)** You must cause any modified files to carry prominent notices stating that You +changed the files; and +* **(c)** You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +#### 5. Submission of Contributions + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +#### 6. Trademarks + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +#### 7. Disclaimer of Warranty + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +#### 8. Limitation of Liability + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +#### 9. Accepting Warranty or Additional Liability + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +_END OF TERMS AND CONDITIONS_ + +### APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets `[]` replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same “printed page” as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..0c0b63e --- /dev/null +++ b/README.md @@ -0,0 +1,148 @@ +# acme-wf + +Use `acme-wf` to securely transfer [acme.sh][] certificates to your [WebFaction][] account. + +WebFaction is a web host who support customer managed SSL/TLS certificates but WebFaction do not directly support LetsEncrypt. This tool bridges the gap between the excellent `acme.sh` project and WebFaction's lack of LetsEncrypt support. + +## Overview + +`acme-wf` transfers SSL certificates from your WebFaction server into the WebFaction control panel. This is done without needing to store your credentials on the server. + +From the trusted private computer, `acme-wf` connects via `ssh` to your WebFaction server which has `acme.sh` installed. The certificates required for your secure web site are collected over this secure connection. + +With the certificates, `acme-wf` then connects via the `XML-RPC` interface to WebFaction's control panel. Once connected to WebFaction, `acme-wf` creates or updates the appropriate certificate entry. + +## Why use `acme-wf`? + +`acme-wf` exists because other solutions for using LetsEncrypt certificates on WebFaction required too many error prone steps, and automated approaches required embedding confidential credentials on the shared server. + +With `acme-wf` a secure certificate can be updated with one command and without storing your WebFaction control panel password on your server. + +`acme-wf` is written in [Go](https://golang.org). This means running `acme-wf` requires only the compiled executable and no supporting files. Compiling `acme-wf` on multiple platforms is also easy thanks to being written in Go. + +Ideally, WebFaction will add automatic LetsEncrypt support. Until then, we have `acme.sh` and `acme-wf`. + +# Getting Started + +1. Install [acme.sh][] on your [WebFaction][] server. +2. On your trusted computer, set up [passwordless ssh access](https://www.dssw.co.uk/blog/2013-09-20-avoiding-password-prompts-with-ssh-and-rsync/) to your WebFaction server. +3. On your trusted computer, run the appropriate `acme-wf …` command; see below for examples. + +``` +./acme-wf -u wfuser [-p wfpassword] [-s wfserver] [domains ...] +``` + +# Example Output + +## Listing Certificates + +Below is an example of output returned from the command: + +`./acme-wf -u wfuser` + +The command does not provide any domains, so the output lists known certificates returned by WebFaction's API: + +``` +WebFaction control panel password: +2017/08/26 11:21:29 [INFO] Logging into WebFaction as: 'wfuser' +2017/08/26 11:21:34 [INFO] Established WebFaction session as user 'wfuser' for server 'Web123' +2017/08/26 11:21:34 [INFO] Requesting WebFaction certificate list +2017/08/26 11:21:36 [INFO] Found WebFaction certificate: 'example_com' expires 2017-09-18, for domains 'example.com,www.example.com' +2017/08/26 11:21:36 [INFO] Found WebFaction certificate: 'anotherdomain_com' expires 2019-11-01, for domains 'anotherdomain.com' +``` + +## Updating a Certificate + +Below is an example of output returned from the command: + +`./acme-wf -u wfuser example.com` + +The output shows `acme-wf` connecting the WebFaction to determine what certificates already exist. A `ssh` connection then fetches the three certificate files from the server. Finally, the certificate entry is updated using the collected certificate files. + +``` +WebFaction control panel password: +2017/08/26 11:32:38 [INFO] Logging into WebFaction as: 'wfuser' +2017/08/26 11:32:40 [INFO] Established WebFaction session as user 'wfuser' for server 'Web123' +2017/08/26 11:32:40 [INFO] Requesting WebFaction certificate list +2017/08/26 11:32:41 [INFO] ssh to 'wfuser@web123.webfaction.com' to read certificates +2017/08/26 11:32:41 [INFO] Working on domain: 'example.com' +2017/08/26 11:32:41 [INFO] Reading '/home/wfuser/.acme.sh/example.com/example.com.cer' via ssh +2017/08/26 11:32:42 [INFO] Reading '/home/wfuser/.acme.sh/example.com/example.com.key' via ssh +2017/08/26 11:32:42 [INFO] Reading '/home/wfuser/.acme.sh/example.com/ca.cer' via ssh +2017/08/26 11:32:42 [INFO] Requesting WebFaction `update_certificate` for example_com (example.com) +2017/08/26 11:32:44 [INFO] Successfully called WebFaction `update_certificate` for example_com (example.com) +``` + +## Examples + +### List Certificates with Expiry Dates + +Run `acme-wf` without domains to return a list of existing WebFaction certificates. + +### Single Server + +Assuming you have one WebFaction server and the domain `example.com`, the command is: + + acme-wf -u 'example.com' + +For `-u` provide your WebFaction user name. The final argument is the domain name, as listed with `acme.sh`. + +With this command, `acme-wf` will connect to WebFaction and be told the name of your server. `acme-wf` will then connect to the server and fetch the `acme.sh` certificates associated with the domain `example.com`. + +Using Terminal.app on macOS, the final command might look like: + + ./acme-wf -u myuser 'example.com' + +### Multiple Servers + +If you have multiple WebFaction servers, then the command needs to include which server you want to fetch the certificates from: + + acme-wf -u -s 'example.com' + +Using Terminal.app on macOS, the final command might look like: + + acme-wf -u myuser -s Web123 'example.com' + +## Assumptions + +`acme-wf` assumes a fair bit about its environment. This keeps the code simple but means the implementation is fragile. In time, additional checks and flexibility can be added. For now the focus is on a minimal working tool. + +- `acme-wf` assumes you have an account with WebFaction and at least one server. +- `acme-wf` assumes you have passwordless secure shell (ssh) access to your WebFaction server. +- `acme-wf` assumes you have `acme.sh` set up on your WebFaction server. +- `acme-wf` assumes `acme.sh` stores three files for certificates at known paths: + 1. `~/.acme.sh//.cer` + 2. `~/.acme.sh//.key` + 3. `~/.acme.sh//ca.cer` + +## Scripting + +To avoid needing to enter your WebFaction control panel password, use the `-p` option: + + -p + +# Improvements + +Today `acme-wf` works well enough to be useful. There are numerous improvements that could be implemented. In no particular order these include: + +- [ ] Only update certificates that have changed; compare WebFaction PEM versus `acme.sh` files before calling `update_certificate`. +- [ ] Check replacement certificate covers the same domains as existing WebFaction entry. +- [ ] Check replacement certificates have not expired. +- [ ] Check replacement certificates are valid. +- [ ] Allow replacement certificates to come from a user specified server. +- [ ] Allow replacement certificates to come from a user specified path. +- [ ] Add option to download WebFaction certificates for back up purposes. +- [ ] Add option to list existing certificates in expiry date order; possible warning of near expiry entries. + +## Contributions and Improvements Welcome + +Help improve `acme-wf`! Pull requests are welcomed. + +# Licence and Legal + +`acme-wf` was created by Graham Miln / https://miln.eu / @grahammiln and is licensed under the Apache License, Version 2.0. + +`acme-wf` has not affiliation or associations with `acme.sh` or WebFaction. + +[acme.sh]: https://github.com/Neilpang/acme.sh +[WebFaction]: https://www.webfaction.com/?aid=50311 diff --git a/main.go b/main.go new file mode 100644 index 0000000..ed9a925 --- /dev/null +++ b/main.go @@ -0,0 +1,169 @@ +// Copyright 2017 Graham Miln, https://miln.eu. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "flag" + "fmt" + "log" + "os" + "path" + "strings" + "syscall" + "time" + + "github.com/dynport/gossh" // Easier ssh client + "github.com/renier/xmlrpc" // XML-RPC client + "golang.org/x/crypto/ssh/terminal" // ReadPassword support + "miln.eu/webfaction" // WebFaction helper functions and structures +) + +// Command line arguments +var wfUsername = flag.String("u", "", "WebFaction user name (required)") +var wfPassword = flag.String("p", "", "WebFaction control panel password (optional)") +var wfServer = flag.String("s", "", "WebFaction server (optional)") + +func main() { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) + flag.PrintDefaults() + fmt.Fprintf(os.Stderr, "acme-wf Copyright 2017 Graham Miln, https://miln.eu. All rights reserved.\n") + } + flag.Parse() + + // WebFaction username is required + if wfUsername == nil || *wfUsername == "" { + log.Fatal("[ERROR] Required WebFaction user name is empty or missing.") + } + + // WebFaction control panel password is optional; interactive if not provided + if wfPassword == nil || *wfPassword == "" { + fmt.Print("WebFaction control panel password: ") + wfp, err := terminal.ReadPassword(syscall.Stdin) + if err != nil { + log.Fatal(fmt.Sprintf("[ERROR] Unable to read password: %v", err)) + } + fmt.Print("\n") + *wfPassword = string(wfp) + } + if wfPassword == nil || *wfPassword == "" { + log.Fatal("[ERROR] Required WebFaction control panel password is empty or missing.") + } + + // Connect to WebFaction via XML-RPC API + wf, err := xmlrpc.NewClient("https://api.webfaction.com/", nil, time.Minute) + if err != nil { + log.Fatal(fmt.Sprintf("[ERROR] Unable to set up WebFaction XML-RPC client: %v", err)) + } + defer wf.Close() + + // `login` to WebFaction to get a session token and user information + var r []interface{} + log.Printf("[INFO] Logging into WebFaction as: '%v'", *wfUsername) + if err = wf.Call("login", []interface{}{*wfUsername, *wfPassword, *wfServer, webfaction.APIVersion}, &r); err != nil { + log.Fatal(fmt.Sprintf("[ERROR] WebFaction `login` failed: %s", err)) + } + var sID string + var s webfaction.Session + if err := webfaction.Unmarshal(r, &sID, &s); err != nil { + log.Fatal(fmt.Sprintf("[ERROR] WebFaction invalid session response: %s", err)) + } + log.Printf("[INFO] Established WebFaction session as user '%s' for server '%s'", s.Username, s.WebServer) + + // `list_certificates` to get list of existing certificates; needed to decide between `update_certificate` and `create_certificate` + log.Printf("[INFO] Requesting WebFaction certificate list") + if err = wf.Call("list_certificates", sID, &r); err != nil { + log.Fatal(fmt.Sprintf("[ERROR] WebFaction `list_certificates` failed: %s", err)) + } + var certs []*webfaction.Certificate + if err := webfaction.Unmarshal(r, &certs); err != nil { + log.Fatal(fmt.Sprintf("[ERROR] WebFaction invalid session response: %s", err)) + } + + // Nothing beyond flags provided on the command line; list known WebFaction certificates and exit + if flag.NArg() == 0 { + for _, c := range certs { + log.Printf("[INFO] Found WebFaction certificate: '%s' expires %s, for domains '%s'", c.Name, c.RawExpiryDate, c.RawDomains) + } + log.Printf("[WARN] Nothing to do because no domains provided; list domains on command line to create or update.") + return + } + + // Connect to the server via ssh to collect acme.sh certificate files + sshserver := fmt.Sprintf("%s.webfaction.com", strings.ToLower(s.WebServer)) + log.Printf("[INFO] ssh to '%s@%s' to read certificates", s.Username, sshserver) + ssh := gossh.New(sshserver, s.Username) + defer ssh.Close() + + // Path to base directory where acme.sh stores certificates + acmepath := path.Join(s.Home, s.Username, ".acme.sh") + + // Enumerate non-flag arguments; each is assumed to be a acme.sh managed domain name + for _, domain := range flag.Args() { + log.Printf("[INFO] Working on domain: '%v'", domain) + + // Get the acme.sh certificate files for this domain from the server + domainpath := path.Join(acmepath, domain) + // ...PEM encoded domain certificate + pemcert, err := sshGetFile(ssh, path.Join(domainpath, fmt.Sprintf("%s.cer", domain))) + if err != nil { + log.Fatal(fmt.Sprintf("[ERROR] Unable to read acme.sh certificate for domain '%s': %s", domain, err)) + } + // ...PEM encoded certificate key + pemkey, err := sshGetFile(ssh, path.Join(domainpath, fmt.Sprintf("%s.key", domain))) + if err != nil { + log.Fatal(fmt.Sprintf("[ERROR] Unable to read acme.sh private key for domain '%s': %s", domain, err)) + } + // ...PEM encoded chain certificate + pemchain, err := sshGetFile(ssh, path.Join(domainpath, "ca.cer")) + if err != nil { + log.Fatal(fmt.Sprintf("[ERROR] Unable to read acme.sh certificate chain for domain '%s': %s", domain, err)) + } + + // WebFaction does not accept cert names with periods `.` + dname := strings.Replace(domain, ".", "_", -1) // replace periods `.` with underscore `_` + + // Search for WebFaction certificate entry with this name + known := false + for _, c := range certs { + if c.Name == dname { + known = true + break + } + } + // Update if certificate name is known, otherwise create a new entry + certmethod := "update_certificate" + if !known { + certmethod = "create_certificate" + } + + log.Printf("[INFO] Requesting WebFaction `%s` for %s (%s)", certmethod, dname, domain) + if err = wf.Call(certmethod, []interface{}{sID, dname, pemcert, pemkey, pemchain}, nil); err != nil { + log.Fatal(fmt.Sprintf("[ERROR] WebFaction `%s` failed for '%s': %s", dname, err)) + } + log.Printf("[INFO] Successfully called WebFaction `%s` for %s (%s)", certmethod, dname, domain) + } +} + +// Get a file from the given path. +func sshGetFile(ssh *gossh.Client, p string) (string, error) { + log.Printf("[INFO] Reading '%s' via ssh", p) + cmd := fmt.Sprintf("cat '%s'", p) + rsp, err := ssh.Execute(cmd) + if err != nil { + log.Printf("[ERROR] ssh error reading file with '%s': %s", cmd, err) + return "", err + } + return rsp.Stdout(), nil +} diff --git a/src/miln.eu/webfaction/api.go b/src/miln.eu/webfaction/api.go new file mode 100644 index 0000000..e6a8966 --- /dev/null +++ b/src/miln.eu/webfaction/api.go @@ -0,0 +1,54 @@ +// Copyright 2017 Graham Miln, https://miln.eu. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package webfaction + +// https://docs.webfaction.com/xmlrpc-api/ + +import ( + "strings" +) + +const APIVersion = 2 + +type Session struct { + WebServer string `mapstructure:"web_server"` + Version int64 `mapstructure:"version"` + Home string `mapstructure:"home"` + MailServer string `mapstructure:"mail_server"` + Username string `mapstructure:"username"` +} + +// Array of certificates returned by `list_certificates` +type Certificate struct { + Name string `xmlrpc:"name"` + + RawCertificate string `mapstructure:"certificate"` // PEM encoded + RawPrivateKey string `mapstructure:"private_key"` // PEM encoded + RawIntermediates string `mapstructure:"intermediates"` // PEM encoded + RawDomains string `mapstructure:"domains"` // comma separated list of domains + RawExpiryDate string `mapstructure:"expiry_date"` +} + +func (c *Certificate) Domains() []string { + return strings.Split(c.RawDomains, ",") +} + +func DecodeCertificatesFromListCertificates(listResponse []interface{}) (*Session, error) { + // Unwrap list_certificates response + var c []*Certificate + if err := Unmarshal(listResponse, &c); err != nil { + return nil, err + } + return nil, nil +} diff --git a/src/miln.eu/webfaction/unmarshal.go b/src/miln.eu/webfaction/unmarshal.go new file mode 100644 index 0000000..03a5009 --- /dev/null +++ b/src/miln.eu/webfaction/unmarshal.go @@ -0,0 +1,71 @@ +// Copyright 2017 Graham Miln, https://miln.eu. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package webfaction + +import ( + "fmt" + "reflect" + + "github.com/mitchellh/mapstructure" +) + +func Unmarshal(r []interface{}, params ...interface{}) error { + // XML-RPC always returns an array, within the array are parameters of various types + if len(r) != 1 { + return fmt.Errorf("Response root must be an single item array; got: %v", r) + } + ra, ok := r[0].([]interface{}) + if !ok { + return fmt.Errorf("Response root must contain an array; got: %v", r[0]) + } + + for i, p := range params { + a := ra[i] + + pt := reflect.TypeOf(p) + if pt.Kind() != reflect.Ptr { + return fmt.Errorf("Response arguments must by pointers. Item %d is a %s", i, pt.Kind().String()) + } + pte := pt.Elem() + + at := reflect.TypeOf(a) + //fmt.Printf("[%d] expect: %v, got: %v\n", i, pte, at) + + switch at.Kind() { + case pte.Kind(): + // caller's parameter and XML-RPC response type match + pv := reflect.ValueOf(p) + if !pv.Elem().CanSet() { + return fmt.Errorf("Unable to return response arguments. Augment %i can not be modified.", i, pv.Elem().String()) + } + pv.Elem().Set(reflect.ValueOf(a)) + case reflect.Map: + if pte.Kind() == reflect.Slice { + if err := mapstructure.Decode(ra[i:], p); err != nil { + return fmt.Errorf("Response argument %d array of maps decoded failed: %s", i, err) + } + } else { + if err := mapstructure.Decode(a, p); err != nil { + return fmt.Errorf("Response argument %d map decoded failed: %s", i, err) + } + } + case reflect.Array: + fmt.Printf("Response argument %d is an array\n", i, at.Kind().String()) + default: + fmt.Printf("Response argument %d is unsupported kind: %s\n", i, at.Kind().String()) + } + } + + return nil +}