lego/cli_handlers.go

471 lines
13 KiB
Go
Raw Permalink Normal View History

package main
import (
"bufio"
"bytes"
"crypto/x509"
"encoding/json"
"encoding/pem"
2018-05-30 17:53:04 +00:00
"fmt"
"io/ioutil"
"net/http"
"os"
2018-09-08 12:58:17 +00:00
"path/filepath"
"strings"
"time"
"github.com/urfave/cli"
"github.com/xenolf/lego/acme"
2018-05-30 17:53:04 +00:00
"github.com/xenolf/lego/log"
"github.com/xenolf/lego/providers/dns"
"github.com/xenolf/lego/providers/http/memcached"
"github.com/xenolf/lego/providers/http/webroot"
)
func checkFolder(path string) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
return os.MkdirAll(path, 0700)
}
return nil
}
func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) {
if c.GlobalIsSet("http-timeout") {
acme.HTTPClient = http.Client{Timeout: time.Duration(c.GlobalInt("http-timeout")) * time.Second}
}
2016-05-25 03:22:09 +00:00
if c.GlobalIsSet("dns-timeout") {
acme.DNSTimeout = time.Duration(c.GlobalInt("dns-timeout")) * time.Second
}
2016-08-19 09:27:26 +00:00
if len(c.GlobalStringSlice("dns-resolvers")) > 0 {
var resolvers []string
2016-08-19 09:27:26 +00:00
for _, resolver := range c.GlobalStringSlice("dns-resolvers") {
if !strings.Contains(resolver, ":") {
resolver += ":53"
}
resolvers = append(resolvers, resolver)
}
acme.RecursiveNameservers = resolvers
}
err := checkFolder(c.GlobalString("path"))
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Could not check/create path: %v", err)
}
conf := NewConfiguration(c)
2015-12-15 18:21:46 +00:00
if len(c.GlobalString("email")) == 0 {
2018-05-30 17:53:04 +00:00
log.Fatal("You have to pass an account (email address) to the program using --email or -m")
}
// TODO: move to account struct? Currently MUST pass email.
acc := NewAccount(c.GlobalString("email"), conf)
2015-10-27 23:05:40 +00:00
keyType, err := conf.KeyType()
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatal(err)
}
2018-06-03 18:23:01 +00:00
acme.UserAgent = fmt.Sprintf("lego-cli/%s", c.App.Version)
2018-05-30 17:53:04 +00:00
client, err := acme.NewClient(c.GlobalString("server"), acc, keyType)
2015-10-27 23:05:40 +00:00
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Could not create client: %v", err)
2015-10-27 23:05:40 +00:00
}
if len(c.GlobalStringSlice("exclude")) > 0 {
client.ExcludeChallenges(conf.ExcludedSolvers())
}
if c.GlobalIsSet("webroot") {
provider, errO := webroot.NewHTTPProvider(c.GlobalString("webroot"))
if errO != nil {
log.Fatal(errO)
}
errO = client.SetChallengeProvider(acme.HTTP01, provider)
if errO != nil {
log.Fatal(errO)
2018-05-30 17:53:04 +00:00
}
// --webroot=foo indicates that the user specifically want to do a HTTP challenge
// infer that the user also wants to exclude all other challenges
client.ExcludeChallenges([]acme.Challenge{acme.DNS01, acme.TLSALPN01})
}
if c.GlobalIsSet("memcached-host") {
provider, errO := memcached.NewMemcachedProvider(c.GlobalStringSlice("memcached-host"))
if errO != nil {
log.Fatal(errO)
}
errO = client.SetChallengeProvider(acme.HTTP01, provider)
if errO != nil {
log.Fatal(errO)
2018-05-30 17:53:04 +00:00
}
// --memcached-host=foo:11211 indicates that the user specifically want to do a HTTP challenge
// infer that the user also wants to exclude all other challenges
client.ExcludeChallenges([]acme.Challenge{acme.DNS01, acme.TLSALPN01})
}
2016-01-08 07:05:07 +00:00
if c.GlobalIsSet("http") {
2018-05-30 17:53:04 +00:00
if !strings.Contains(c.GlobalString("http"), ":") {
log.Fatalf("The --http switch only accepts interface:port or :port for its argument.")
}
2018-05-30 17:53:04 +00:00
err = client.SetHTTPAddress(c.GlobalString("http"))
if err != nil {
log.Fatal(err)
}
}
if c.GlobalIsSet("tls") {
if !strings.Contains(c.GlobalString("tls"), ":") {
log.Fatalf("The --tls switch only accepts interface:port or :port for its argument.")
}
err = client.SetTLSAddress(c.GlobalString("tls"))
2016-01-30 01:40:57 +00:00
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatal(err)
2016-01-30 01:40:57 +00:00
}
}
2016-01-30 01:40:57 +00:00
if c.GlobalIsSet("dns") {
provider, errO := dns.NewDNSChallengeProviderByName(c.GlobalString("dns"))
if errO != nil {
log.Fatal(errO)
}
errO = client.SetChallengeProvider(acme.DNS01, provider)
if errO != nil {
log.Fatal(errO)
2018-05-30 17:53:04 +00:00
}
// --dns=foo indicates that the user specifically want to do a DNS challenge
// infer that the user also wants to exclude all other challenges
client.ExcludeChallenges([]acme.Challenge{acme.HTTP01, acme.TLSALPN01})
2018-05-30 17:53:04 +00:00
}
if client.GetExternalAccountRequired() && !c.GlobalIsSet("eab") {
log.Fatal("Server requires External Account Binding. Use --eab with --kid and --hmac.")
2016-01-30 01:40:57 +00:00
}
2015-10-27 23:05:40 +00:00
return conf, acc, client
}
2018-05-30 17:53:04 +00:00
func saveCertRes(certRes *acme.CertificateResource, conf *Configuration) {
2018-09-08 12:58:17 +00:00
var domainName string
// Check filename cli parameter
if conf.context.GlobalString("filename") == "" {
// Make sure no funny chars are in the cert names (like wildcards ;))
domainName = strings.Replace(certRes.Domain, "*", "_", -1)
} else {
domainName = conf.context.GlobalString("filename")
}
2018-05-30 17:53:04 +00:00
// We store the certificate, private key and metadata in different files
// as web servers would not be able to work with a combined file.
certOut := filepath.Join(conf.CertPath(), domainName+".crt")
privOut := filepath.Join(conf.CertPath(), domainName+".key")
pemOut := filepath.Join(conf.CertPath(), domainName+".pem")
metaOut := filepath.Join(conf.CertPath(), domainName+".json")
issuerOut := filepath.Join(conf.CertPath(), domainName+".issuer.crt")
2018-09-08 12:58:17 +00:00
err := checkFolder(filepath.Dir(certOut))
if err != nil {
log.Fatalf("Could not check/create path: %v", err)
}
err = ioutil.WriteFile(certOut, certRes.Certificate, 0600)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to save Certificate for domain %s\n\t%v", certRes.Domain, err)
}
if certRes.IssuerCertificate != nil {
err = ioutil.WriteFile(issuerOut, certRes.IssuerCertificate, 0600)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to save IssuerCertificate for domain %s\n\t%v", certRes.Domain, err)
}
}
if certRes.PrivateKey != nil {
// if we were given a CSR, we don't know the private key
err = ioutil.WriteFile(privOut, certRes.PrivateKey, 0600)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to save PrivateKey for domain %s\n\t%v", certRes.Domain, err)
}
if conf.context.GlobalBool("pem") {
err = ioutil.WriteFile(pemOut, bytes.Join([][]byte{certRes.Certificate, certRes.PrivateKey}, nil), 0600)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to save Certificate and PrivateKey in .pem for domain %s\n\t%v", certRes.Domain, err)
}
}
} else if conf.context.GlobalBool("pem") {
// we don't have the private key; can't write the .pem file
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to save pem without private key for domain %s\n\t%v; are you using a CSR?", certRes.Domain, err)
}
jsonBytes, err := json.MarshalIndent(certRes, "", "\t")
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to marshal CertResource for domain %s\n\t%v", certRes.Domain, err)
}
err = ioutil.WriteFile(metaOut, jsonBytes, 0600)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Unable to save CertResource for domain %s\n\t%v", certRes.Domain, err)
}
}
2018-05-30 17:53:04 +00:00
func handleTOS(c *cli.Context, client *acme.Client) bool {
// Check for a global accept override
if c.GlobalBool("accept-tos") {
2018-05-30 17:53:04 +00:00
return true
}
reader := bufio.NewReader(os.Stdin)
2018-05-30 17:53:04 +00:00
log.Printf("Please review the TOS at %s", client.GetToSURL())
for {
2018-05-30 17:53:04 +00:00
log.Println("Do you accept the TOS? Y/n")
text, err := reader.ReadString('\n')
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Could not read from console: %v", err)
}
text = strings.Trim(text, "\r\n")
if text == "n" {
2018-05-30 17:53:04 +00:00
log.Fatal("You did not accept the TOS. Unable to proceed.")
}
if text == "Y" || text == "y" || text == "" {
2018-05-30 17:53:04 +00:00
return true
}
2018-05-30 17:53:04 +00:00
log.Println("Your input was invalid. Please answer with one of Y/y, n or by pressing enter.")
}
}
func readCSRFile(filename string) (*x509.CertificateRequest, error) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
raw := bytes
// see if we can find a PEM-encoded CSR
var p *pem.Block
rest := bytes
for {
// decode a PEM block
p, rest = pem.Decode(rest)
// did we fail?
if p == nil {
break
}
// did we get a CSR?
if p.Type == "CERTIFICATE REQUEST" {
raw = p.Bytes
}
}
// no PEM-encoded CSR
// assume we were given a DER-encoded ASN.1 CSR
// (if this assumption is wrong, parsing these bytes will fail)
return x509.ParseCertificateRequest(raw)
}
func run(c *cli.Context) error {
2018-05-30 17:53:04 +00:00
var err error
conf, acc, client := setup(c)
if acc.Registration == nil {
2018-05-30 17:53:04 +00:00
accepted := handleTOS(c, client)
if !accepted {
log.Fatal("You did not accept the TOS. Unable to proceed.")
}
var reg *acme.RegistrationResource
if c.GlobalBool("eab") {
kid := c.GlobalString("kid")
hmacEncoded := c.GlobalString("hmac")
if kid == "" || hmacEncoded == "" {
log.Fatalf("Requires arguments --kid and --hmac.")
}
reg, err = client.RegisterWithExternalAccountBinding(
accepted,
kid,
hmacEncoded,
)
} else {
reg, err = client.Register(accepted)
}
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Could not complete registration\n\t%v", err)
}
acc.Registration = reg
err = acc.Save()
if err != nil {
log.Fatal(err)
}
2018-05-30 17:53:04 +00:00
log.Print("!!!! HEADS UP !!!!")
log.Printf(`
2015-09-26 18:00:19 +00:00
Your account credentials have been saved in your Let's Encrypt
configuration directory at "%s".
You should make a secure backup of this folder now. This
configuration directory will also contain certificates and
private keys obtained from Let's Encrypt so making regular
backups of this folder is ideal.`, conf.AccountPath(c.GlobalString("email")))
}
// we require either domains or csr, but not both
hasDomains := len(c.GlobalStringSlice("domains")) > 0
hasCsr := len(c.GlobalString("csr")) > 0
if hasDomains && hasCsr {
2018-05-30 17:53:04 +00:00
log.Fatal("Please specify either --domains/-d or --csr/-c, but not both")
}
if !hasDomains && !hasCsr {
2018-05-30 17:53:04 +00:00
log.Fatal("Please specify --domains/-d (or --csr/-c if you already have a CSR)")
}
2018-05-30 17:53:04 +00:00
var cert *acme.CertificateResource
if hasDomains {
// obtain a certificate, generating a new private key
2018-05-30 17:53:04 +00:00
cert, err = client.ObtainCertificate(c.GlobalStringSlice("domains"), !c.Bool("no-bundle"), nil, c.Bool("must-staple"))
} else {
// read the CSR
var csr *x509.CertificateRequest
csr, err = readCSRFile(c.GlobalString("csr"))
2018-05-30 17:53:04 +00:00
if err == nil {
// obtain a certificate for this CSR
2018-05-30 17:53:04 +00:00
cert, err = client.ObtainCertificateForCSR(*csr, !c.Bool("no-bundle"))
}
}
2018-05-30 17:53:04 +00:00
if err != nil {
// Make sure to return a non-zero exit code if ObtainSANCertificate
// returned at least one error. Due to us not returning partial
// certificate we can just exit here instead of at the end.
log.Fatalf("Could not obtain certificates\n\t%v", err)
}
2018-05-30 17:53:04 +00:00
if err = checkFolder(conf.CertPath()); err != nil {
log.Fatalf("Could not check/create path: %v", err)
}
2015-11-11 17:05:09 +00:00
saveCertRes(cert, conf)
return nil
}
2015-09-27 12:51:44 +00:00
func revoke(c *cli.Context) error {
conf, acc, client := setup(c)
if acc.Registration == nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Account %s is not registered. Use 'run' to register a new account.\n", acc.Email)
}
2015-09-27 12:51:44 +00:00
2018-05-30 17:53:04 +00:00
if err := checkFolder(conf.CertPath()); err != nil {
log.Fatalf("Could not check/create path: %v", err)
2015-09-27 12:51:44 +00:00
}
for _, domain := range c.GlobalStringSlice("domains") {
2018-05-30 17:53:04 +00:00
log.Printf("Trying to revoke certificate for domain %s", domain)
2015-09-27 12:51:44 +00:00
certPath := filepath.Join(conf.CertPath(), domain+".crt")
2015-09-27 12:51:44 +00:00
certBytes, err := ioutil.ReadFile(certPath)
2018-05-30 17:53:04 +00:00
if err != nil {
log.Println(err)
}
2015-09-27 12:51:44 +00:00
err = client.RevokeCertificate(certBytes)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
2015-09-27 12:51:44 +00:00
} else {
2018-05-30 17:53:04 +00:00
log.Println("Certificate was revoked.")
2015-09-27 12:51:44 +00:00
}
}
return nil
2015-09-27 12:51:44 +00:00
}
2015-10-18 22:42:04 +00:00
func renew(c *cli.Context) error {
conf, acc, client := setup(c)
if acc.Registration == nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Account %s is not registered. Use 'run' to register a new account.\n", acc.Email)
}
2015-12-24 08:57:09 +00:00
if len(c.GlobalStringSlice("domains")) <= 0 {
2018-05-30 17:53:04 +00:00
log.Fatal("Please specify at least one domain.")
}
2015-12-24 08:57:09 +00:00
domain := c.GlobalStringSlice("domains")[0]
2018-05-30 17:53:04 +00:00
domain = strings.Replace(domain, "*", "_", -1)
2015-10-18 22:42:04 +00:00
// load the cert resource from files.
// We store the certificate, private key and metadata in different files
// as web servers would not be able to work with a combined file.
certPath := filepath.Join(conf.CertPath(), domain+".crt")
privPath := filepath.Join(conf.CertPath(), domain+".key")
metaPath := filepath.Join(conf.CertPath(), domain+".json")
certBytes, err := ioutil.ReadFile(certPath)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Error while loading the certificate for domain %s\n\t%v", domain, err)
}
if c.IsSet("days") {
expTime, errE := acme.GetPEMCertExpiration(certBytes)
if errE != nil {
2018-05-30 17:53:04 +00:00
log.Printf("Could not get Certification expiration for domain %s", domain)
2015-10-18 22:42:04 +00:00
}
if int(time.Until(expTime).Hours()/24.0) > c.Int("days") {
return nil
2015-10-18 22:42:04 +00:00
}
}
2015-10-18 22:42:04 +00:00
metaBytes, err := ioutil.ReadFile(metaPath)
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatalf("Error while loading the meta data for domain %s\n\t%v", domain, err)
}
2015-10-18 22:42:04 +00:00
var certRes acme.CertificateResource
if err = json.Unmarshal(metaBytes, &certRes); err != nil {
log.Fatalf("Error while marshaling the meta data for domain %s\n\t%v", domain, err)
}
2015-10-18 22:42:04 +00:00
2016-01-08 09:14:41 +00:00
if c.Bool("reuse-key") {
keyBytes, errR := ioutil.ReadFile(privPath)
if errR != nil {
log.Fatalf("Error while loading the private key for domain %s\n\t%v", domain, errR)
2016-01-08 09:14:41 +00:00
}
certRes.PrivateKey = keyBytes
}
certRes.Certificate = certBytes
newCert, err := client.RenewCertificate(certRes, !c.Bool("no-bundle"), c.Bool("must-staple"))
if err != nil {
2018-05-30 17:53:04 +00:00
log.Fatal(err)
2015-10-18 22:42:04 +00:00
}
saveCertRes(newCert, conf)
return nil
2015-10-18 22:42:04 +00:00
}