Exemplo n.º 1
0
func renew(c *cli.Context) {
	conf, _, client := setup(c)

	if len(c.GlobalStringSlice("domains")) <= 0 {
		logger().Fatal("Please specify at least one domain.")
	}

	domain := c.GlobalStringSlice("domains")[0]

	// 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 := path.Join(conf.CertPath(), domain+".crt")
	privPath := path.Join(conf.CertPath(), domain+".key")
	metaPath := path.Join(conf.CertPath(), domain+".json")

	certBytes, err := ioutil.ReadFile(certPath)
	if err != nil {
		logger().Fatalf("Error while loading the certificate for domain %s\n\t%s", domain, err.Error())
	}

	if c.IsSet("days") {
		expTime, err := acme.GetPEMCertExpiration(certBytes)
		if err != nil {
			logger().Printf("Could not get Certification expiration for domain %s", domain)
		}

		if int(expTime.Sub(time.Now()).Hours()/24.0) > c.Int("days") {
			return
		}
	}

	metaBytes, err := ioutil.ReadFile(metaPath)
	if err != nil {
		logger().Fatalf("Error while loading the meta data for domain %s\n\t%s", domain, err.Error())
	}

	var certRes acme.CertificateResource
	err = json.Unmarshal(metaBytes, &certRes)
	if err != nil {
		logger().Fatalf("Error while marshalling the meta data for domain %s\n\t%s", domain, err.Error())
	}

	if c.Bool("reuse-key") {
		keyBytes, err := ioutil.ReadFile(privPath)
		if err != nil {
			logger().Fatalf("Error while loading the private key for domain %s\n\t%s", domain, err.Error())
		}
		certRes.PrivateKey = keyBytes
	}

	certRes.Certificate = certBytes

	newCert, err := client.RenewCertificate(certRes, true)
	if err != nil {
		logger().Fatalf("%s", err.Error())
	}

	saveCertRes(newCert, conf)
}
Exemplo n.º 2
0
func (c *Client) saveCertificate(certName, dnsNames string, certRes lego.CertificateResource) (*AcmeCertificate, error) {
	expiryDate, err := lego.GetPEMCertExpiration(certRes.Certificate)
	if err != nil {
		return nil, fmt.Errorf("Failed to read certificate expiry date: %v", err)
	}
	serialNumber, err := getPEMCertSerialNumber(certRes.Certificate)
	if err != nil {
		return nil, fmt.Errorf("Failed to read certificate serial number: %v", err)
	}

	acmeCert := AcmeCertificate{
		CertificateResource: certRes,
		ExpiryDate:          expiryDate,
		SerialNumber:        serialNumber,
		DnsNames:            dnsNames,
	}

	certPath := c.CertPath(certName)
	maybeCreatePath(certPath)

	logrus.Debugf("Saving certificate '%s' to path '%s'", certName, certPath)

	certOut := path.Join(certPath, "fullchain.pem")
	privOut := path.Join(certPath, "privkey.pem")
	metaOut := path.Join(certPath, "metadata.json")

	err = ioutil.WriteFile(certOut, acmeCert.Certificate, 0600)
	if err != nil {
		return nil, fmt.Errorf("Failed to save certificate to '%s': %v", certOut, err)
	}

	logrus.Infof("Certificate saved to '%s'", certOut)

	err = ioutil.WriteFile(privOut, acmeCert.PrivateKey, 0600)
	if err != nil {
		return nil, fmt.Errorf("Failed to save private key to '%s': %v", privOut, err)
	}

	logrus.Infof("Private key saved to '%s'", privOut)

	jsonBytes, err := json.MarshalIndent(acmeCert, "", "\t")
	if err != nil {
		return nil, fmt.Errorf("Failed to marshal meta data for certificate '%s': %v", certName, err)
	}

	err = ioutil.WriteFile(metaOut, jsonBytes, 0600)
	if err != nil {
		return nil, fmt.Errorf("Failed to save meta data to '%s': %v", metaOut, err)
	}

	return &acmeCert, nil
}
Exemplo n.º 3
0
func (rm *renewalMonitor) renewCertificateIfNeeded(domain string) error {
	// Load current certificate
	cert, err := rm.Repository.LoadDomainCertificate(domain)
	if err != nil {
		return maskAny(err)
	}
	if cert == nil {
		// Domain certificate not found, nothing to renewal
		rm.Logger.Debugf("no certificate found for '%s', so nothing to renew", domain)
		return nil
	}

	// Get expiration time of certificate
	expTime, err := acme.GetPEMCertExpiration(cert)
	if err != nil {
		return maskAny(err)
	}

	// The time returned from the certificate is always in UTC.
	// So calculate the time left with local time as UTC.
	// Directly convert it to days for the following checks.
	daysLeft := int(expTime.Sub(time.Now().UTC()).Hours() / 24)

	if daysLeft > renewDaysBefore {
		// No need to renew yet
		rm.Logger.Debugf("No need to renew certificate for '%s', it has %d days left", domain, daysLeft)
		return nil
	}

	// We need to renew the certificate
	rm.Logger.Debugf("Certificate for '%s' is due for renewal, it has %d days left", daysLeft)

	op := func() error {
		return maskAny(rm.Requester.RequestCertificates([]string{domain}))
	}

	if err := retry.Do(op,
		retry.RetryChecker(IsNotMaster),
		retry.MaxTries(15),
		retry.Sleep(time.Second*5),
		retry.Timeout(0)); err != nil {
		return maskAny(err)
	}

	return nil
}
Exemplo n.º 4
0
// renewCertificates loops through all configured site and
// looks for certificates to renew. Nothing is mutated
// through this function; all changes happen directly on disk.
// It returns the number of certificates renewed and any errors
// that occurred. It only performs a renewal if necessary.
// If useCustomPort is true, a custom port will be used, and
// whatever is listening at 443 better proxy ACME requests to it.
// Otherwise, the acme package will create its own listener on 443.
func renewCertificates(configs []server.Config, useCustomPort bool) (int, []error) {
	log.Printf("[INFO] Checking certificates for %d hosts", len(configs))
	var errs []error
	var n int

	for _, cfg := range configs {
		// Host must be TLS-enabled and have existing assets managed by LE
		if !cfg.TLS.Enabled || !existingCertAndKey(cfg.Host) {
			continue
		}

		// Read the certificate and get the NotAfter time.
		certBytes, err := ioutil.ReadFile(storage.SiteCertFile(cfg.Host))
		if err != nil {
			errs = append(errs, err)
			continue // still have to check other certificates
		}
		expTime, err := acme.GetPEMCertExpiration(certBytes)
		if err != nil {
			errs = append(errs, err)
			continue
		}

		// The time returned from the certificate is always in UTC.
		// So calculate the time left with local time as UTC.
		// Directly convert it to days for the following checks.
		daysLeft := int(expTime.Sub(time.Now().UTC()).Hours() / 24)

		// Renew with two weeks or less remaining.
		if daysLeft <= 14 {
			log.Printf("[INFO] Certificate for %s has %d days remaining; attempting renewal", cfg.Host, daysLeft)
			var client *acme.Client
			if useCustomPort {
				client, err = newClientPort("", alternatePort) // email not used for renewal
			} else {
				client, err = newClient("")
			}
			if err != nil {
				errs = append(errs, err)
				continue
			}

			// Read and set up cert meta, required for renewal
			metaBytes, err := ioutil.ReadFile(storage.SiteMetaFile(cfg.Host))
			if err != nil {
				errs = append(errs, err)
				continue
			}
			privBytes, err := ioutil.ReadFile(storage.SiteKeyFile(cfg.Host))
			if err != nil {
				errs = append(errs, err)
				continue
			}
			var certMeta acme.CertificateResource
			err = json.Unmarshal(metaBytes, &certMeta)
			certMeta.Certificate = certBytes
			certMeta.PrivateKey = privBytes

			// Renew certificate
		Renew:
			newCertMeta, err := client.RenewCertificate(certMeta, true, true)
			if err != nil {
				if _, ok := err.(acme.TOSError); ok {
					err := client.AgreeToTOS()
					if err != nil {
						errs = append(errs, err)
					}
					goto Renew
				}

				time.Sleep(10 * time.Second)
				newCertMeta, err = client.RenewCertificate(certMeta, true, true)
				if err != nil {
					errs = append(errs, err)
					continue
				}
			}

			saveCertsAndKeys([]acme.CertificateResource{newCertMeta})
			n++
		} else if daysLeft <= 30 {
			// Warn on 30 days remaining. TODO: Just do this once...
			log.Printf("[WARNING] Certificate for %s has %d days remaining; will automatically renew when 14 days remain\n", cfg.Host, daysLeft)
		}
	}

	return n, errs
}