|
|
@@ -20,8 +20,8 @@ import (
|
|
|
"encoding/pem"
|
|
|
"errors"
|
|
|
"fmt"
|
|
|
+ mathrand "math/rand"
|
|
|
"net/http"
|
|
|
- "sort"
|
|
|
"strconv"
|
|
|
"strings"
|
|
|
"sync"
|
|
|
@@ -31,6 +31,14 @@ import (
|
|
|
"golang.org/x/net/context"
|
|
|
)
|
|
|
|
|
|
+// pseudoRand is safe for concurrent use.
|
|
|
+var pseudoRand *lockedMathRand
|
|
|
+
|
|
|
+func init() {
|
|
|
+ src := mathrand.NewSource(timeNow().UnixNano())
|
|
|
+ pseudoRand = &lockedMathRand{rnd: mathrand.New(src)}
|
|
|
+}
|
|
|
+
|
|
|
// AcceptTOS always returns true to indicate the acceptance of a CA Terms of Service
|
|
|
// during account registration.
|
|
|
func AcceptTOS(tosURL string) bool { return true }
|
|
|
@@ -110,6 +118,12 @@ type Manager struct {
|
|
|
// See GetCertificate for more details.
|
|
|
HostPolicy HostPolicy
|
|
|
|
|
|
+ // RenewBefore optionally specifies how early certificates should
|
|
|
+ // be renewed before they expire.
|
|
|
+ //
|
|
|
+ // If zero, they're renewed 1 week before expiration.
|
|
|
+ RenewBefore time.Duration
|
|
|
+
|
|
|
// Client is used to perform low-level operations, such as account registration
|
|
|
// and requesting new certificates.
|
|
|
// If Client is nil, a zero-value acme.Client is used with acme.LetsEncryptURL
|
|
|
@@ -135,6 +149,11 @@ type Manager struct {
|
|
|
// of ClientHello. Keys always have ".acme.invalid" suffix.
|
|
|
tokenCertMu sync.RWMutex
|
|
|
tokenCert map[string]*tls.Certificate
|
|
|
+
|
|
|
+ // renewal tracks the set of domains currently running renewal timers.
|
|
|
+ // It is keyed by domain name.
|
|
|
+ renewalMu sync.Mutex
|
|
|
+ renewal map[string]*domainRenewal
|
|
|
}
|
|
|
|
|
|
// GetCertificate implements the tls.Config.GetCertificate hook.
|
|
|
@@ -192,8 +211,7 @@ func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate,
|
|
|
// with the cached value.
|
|
|
func (m *Manager) cert(name string) (*tls.Certificate, error) {
|
|
|
m.stateMu.Lock()
|
|
|
- s, ok := m.state[name]
|
|
|
- if ok {
|
|
|
+ if s, ok := m.state[name]; ok {
|
|
|
m.stateMu.Unlock()
|
|
|
s.RLock()
|
|
|
defer s.RUnlock()
|
|
|
@@ -211,11 +229,13 @@ func (m *Manager) cert(name string) (*tls.Certificate, error) {
|
|
|
if m.state == nil {
|
|
|
m.state = make(map[string]*certState)
|
|
|
}
|
|
|
- m.state[name] = &certState{
|
|
|
+ s := &certState{
|
|
|
key: signer,
|
|
|
cert: cert.Certificate,
|
|
|
leaf: cert.Leaf,
|
|
|
}
|
|
|
+ m.state[name] = s
|
|
|
+ go m.renew(name, s.key, s.leaf.NotAfter)
|
|
|
return cert, nil
|
|
|
}
|
|
|
|
|
|
@@ -242,65 +262,29 @@ func (m *Manager) cacheGet(domain string) (*tls.Certificate, error) {
|
|
|
}
|
|
|
|
|
|
// public
|
|
|
- var pubDER []byte
|
|
|
+ var pubDER [][]byte
|
|
|
for len(pub) > 0 {
|
|
|
var b *pem.Block
|
|
|
b, pub = pem.Decode(pub)
|
|
|
if b == nil {
|
|
|
break
|
|
|
}
|
|
|
- pubDER = append(pubDER, b.Bytes...)
|
|
|
+ pubDER = append(pubDER, b.Bytes)
|
|
|
}
|
|
|
if len(pub) > 0 {
|
|
|
return nil, errors.New("acme/autocert: invalid public key")
|
|
|
}
|
|
|
|
|
|
- // parse public part(s) and verify the leaf is not expired
|
|
|
- // and corresponds to the private key
|
|
|
- x509Cert, err := x509.ParseCertificates(pubDER)
|
|
|
- if len(x509Cert) == 0 {
|
|
|
- return nil, errors.New("acme/autocert: no public key found in cache")
|
|
|
- }
|
|
|
- leaf := x509Cert[0]
|
|
|
- now := time.Now()
|
|
|
- if now.Before(leaf.NotBefore) {
|
|
|
- return nil, errors.New("acme/autocert: certificate is not valid yet")
|
|
|
- }
|
|
|
- if now.After(leaf.NotAfter) {
|
|
|
- return nil, errors.New("acme/autocert: expired certificate")
|
|
|
- }
|
|
|
- if !domainMatch(leaf, domain) {
|
|
|
- return nil, errors.New("acme/autocert: certificate does not match domain name")
|
|
|
- }
|
|
|
- switch pub := leaf.PublicKey.(type) {
|
|
|
- case *rsa.PublicKey:
|
|
|
- prv, ok := privKey.(*rsa.PrivateKey)
|
|
|
- if !ok {
|
|
|
- return nil, errors.New("acme/autocert: private key type does not match public key type")
|
|
|
- }
|
|
|
- if pub.N.Cmp(prv.N) != 0 {
|
|
|
- return nil, errors.New("acme/autocert: private key does not match public key")
|
|
|
- }
|
|
|
- case *ecdsa.PublicKey:
|
|
|
- prv, ok := privKey.(*ecdsa.PrivateKey)
|
|
|
- if !ok {
|
|
|
- return nil, errors.New("acme/autocert: private key type does not match public key type")
|
|
|
- }
|
|
|
- if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
|
|
|
- return nil, errors.New("acme/autocert: private key does not match public key")
|
|
|
- }
|
|
|
- default:
|
|
|
- return nil, errors.New("acme/autocert: unknown public key algorithm")
|
|
|
+ // verify and create TLS cert
|
|
|
+ leaf, err := validCert(domain, pubDER, privKey)
|
|
|
+ if err != nil {
|
|
|
+ return nil, err
|
|
|
}
|
|
|
-
|
|
|
tlscert := &tls.Certificate{
|
|
|
- Certificate: make([][]byte, len(x509Cert)),
|
|
|
+ Certificate: pubDER,
|
|
|
PrivateKey: privKey,
|
|
|
Leaf: leaf,
|
|
|
}
|
|
|
- for i, crt := range x509Cert {
|
|
|
- tlscert.Certificate[i] = crt.Raw
|
|
|
- }
|
|
|
return tlscert, nil
|
|
|
}
|
|
|
|
|
|
@@ -346,46 +330,92 @@ func (m *Manager) cachePut(domain string, tlscert *tls.Certificate) error {
|
|
|
return m.Cache.Put(ctx, domain, buf.Bytes())
|
|
|
}
|
|
|
|
|
|
-// createCert starts domain ownership verification and returns a certificate for that domain
|
|
|
-// upon success.
|
|
|
+// createCert starts the domain ownership verification and returns a certificate
|
|
|
+// for that domain upon success.
|
|
|
//
|
|
|
// If the domain is already being verified, it waits for the existing verification to complete.
|
|
|
// Either way, createCert blocks for the duration of the whole process.
|
|
|
func (m *Manager) createCert(ctx context.Context, domain string) (*tls.Certificate, error) {
|
|
|
- state, ok, err := m.certState(domain)
|
|
|
+ // TODO: maybe rewrite this whole piece using sync.Once
|
|
|
+ state, err := m.certState(domain)
|
|
|
if err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
// state may exist if another goroutine is already working on it
|
|
|
// in which case just wait for it to finish
|
|
|
- if ok {
|
|
|
+ if !state.locked {
|
|
|
state.RLock()
|
|
|
defer state.RUnlock()
|
|
|
return state.tlscert()
|
|
|
}
|
|
|
|
|
|
- // We are the first.
|
|
|
+ // We are the first; state is locked.
|
|
|
// Unblock the readers when domain ownership is verified
|
|
|
// and the we got the cert or the process failed.
|
|
|
defer state.Unlock()
|
|
|
+ state.locked = false
|
|
|
+
|
|
|
+ der, leaf, err := m.authorizedCert(ctx, state.key, domain)
|
|
|
+ if err != nil {
|
|
|
+ return nil, err
|
|
|
+ }
|
|
|
+ state.cert = der
|
|
|
+ state.leaf = leaf
|
|
|
+ go m.renew(domain, state.key, state.leaf.NotAfter)
|
|
|
+ return state.tlscert()
|
|
|
+}
|
|
|
+
|
|
|
+// certState returns a new or existing certState.
|
|
|
+// If a new certState is returned, state.exist is false and the state is locked.
|
|
|
+// The returned error is non-nil only in the case where a new state could not be created.
|
|
|
+func (m *Manager) certState(domain string) (*certState, error) {
|
|
|
+ m.stateMu.Lock()
|
|
|
+ defer m.stateMu.Unlock()
|
|
|
+ if m.state == nil {
|
|
|
+ m.state = make(map[string]*certState)
|
|
|
+ }
|
|
|
+ // existing state
|
|
|
+ if state, ok := m.state[domain]; ok {
|
|
|
+ return state, nil
|
|
|
+ }
|
|
|
+ // new locked state
|
|
|
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
|
+ if err != nil {
|
|
|
+ return nil, err
|
|
|
+ }
|
|
|
+ state := &certState{
|
|
|
+ key: key,
|
|
|
+ locked: true,
|
|
|
+ }
|
|
|
+ state.Lock() // will be unlocked by m.certState caller
|
|
|
+ m.state[domain] = state
|
|
|
+ return state, nil
|
|
|
+}
|
|
|
+
|
|
|
+// authorizedCert starts domain ownership verification process and requests a new cert upon success.
|
|
|
+// The key argument is the certificate private key.
|
|
|
+func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, domain string) (der [][]byte, leaf *x509.Certificate, err error) {
|
|
|
// TODO: make m.verify retry or retry m.verify calls here
|
|
|
if err := m.verify(ctx, domain); err != nil {
|
|
|
- return nil, err
|
|
|
+ return nil, nil, err
|
|
|
}
|
|
|
client, err := m.acmeClient(ctx)
|
|
|
if err != nil {
|
|
|
- return nil, err
|
|
|
+ return nil, nil, err
|
|
|
}
|
|
|
- csr, err := certRequest(state.key, domain)
|
|
|
+ csr, err := certRequest(key, domain)
|
|
|
if err != nil {
|
|
|
- return nil, err
|
|
|
+ return nil, nil, err
|
|
|
}
|
|
|
- der, _, err := client.CreateCert(ctx, csr, 0, true)
|
|
|
+ der, _, err = client.CreateCert(ctx, csr, 0, true)
|
|
|
if err != nil {
|
|
|
- return nil, err
|
|
|
+ return nil, nil, err
|
|
|
}
|
|
|
- state.cert = der
|
|
|
- return state.tlscert()
|
|
|
+ leaf, err = validCert(domain, der, key)
|
|
|
+ if err != nil {
|
|
|
+ return nil, nil, err
|
|
|
+ }
|
|
|
+ return der, leaf, nil
|
|
|
}
|
|
|
|
|
|
// verify starts a new identifier (domain) authorization flow.
|
|
|
@@ -457,29 +487,6 @@ func (m *Manager) verify(ctx context.Context, domain string) error {
|
|
|
return err
|
|
|
}
|
|
|
|
|
|
-// certState returns existing state or creates a new one locked for read/write.
|
|
|
-// The boolean return value indicates whether the state was found in m.state.
|
|
|
-func (m *Manager) certState(domain string) (*certState, bool, error) {
|
|
|
- m.stateMu.Lock()
|
|
|
- defer m.stateMu.Unlock()
|
|
|
- if m.state == nil {
|
|
|
- m.state = make(map[string]*certState)
|
|
|
- }
|
|
|
- // existing state
|
|
|
- if state, ok := m.state[domain]; ok {
|
|
|
- return state, true, nil
|
|
|
- }
|
|
|
- // new locked state
|
|
|
- key, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
|
- if err != nil {
|
|
|
- return nil, false, err
|
|
|
- }
|
|
|
- state := &certState{key: key}
|
|
|
- state.Lock()
|
|
|
- m.state[domain] = state
|
|
|
- return state, false, nil
|
|
|
-}
|
|
|
-
|
|
|
// putTokenCert stores the cert under the named key in both m.tokenCert map
|
|
|
// and m.Cache.
|
|
|
func (m *Manager) putTokenCert(name string, cert *tls.Certificate) {
|
|
|
@@ -503,6 +510,29 @@ func (m *Manager) deleteTokenCert(name string) {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+// renew starts a cert renewal timer loop, one per domain.
|
|
|
+//
|
|
|
+// The loop is scheduled in two cases:
|
|
|
+// - a cert was fetched from cache for the first time (wasn't in m.state)
|
|
|
+// - a new cert was created by m.createCert
|
|
|
+//
|
|
|
+// The key argument is a certificate private key.
|
|
|
+// The exp argument is the cert expiration time (NotAfter).
|
|
|
+func (m *Manager) renew(domain string, key crypto.Signer, exp time.Time) {
|
|
|
+ m.renewalMu.Lock()
|
|
|
+ defer m.renewalMu.Unlock()
|
|
|
+ if m.renewal[domain] != nil {
|
|
|
+ // another goroutine is already on it
|
|
|
+ return
|
|
|
+ }
|
|
|
+ if m.renewal == nil {
|
|
|
+ m.renewal = make(map[string]*domainRenewal)
|
|
|
+ }
|
|
|
+ dr := &domainRenewal{m: m, domain: domain, key: key}
|
|
|
+ m.renewal[domain] = dr
|
|
|
+ time.AfterFunc(dr.next(exp), dr.renew)
|
|
|
+}
|
|
|
+
|
|
|
func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) {
|
|
|
m.clientMu.Lock()
|
|
|
defer m.clientMu.Unlock()
|
|
|
@@ -542,12 +572,20 @@ func (m *Manager) hostPolicy() HostPolicy {
|
|
|
return defaultHostPolicy
|
|
|
}
|
|
|
|
|
|
+func (m *Manager) renewBefore() time.Duration {
|
|
|
+ if m.RenewBefore > maxRandRenew {
|
|
|
+ return m.RenewBefore
|
|
|
+ }
|
|
|
+ return 7 * 24 * time.Hour // 1 week
|
|
|
+}
|
|
|
+
|
|
|
// certState is ready when its mutex is unlocked for reading.
|
|
|
type certState struct {
|
|
|
sync.RWMutex
|
|
|
- key crypto.Signer
|
|
|
- cert [][]byte // DER encoding
|
|
|
- leaf *x509.Certificate // parsed cert[0]; may be nil
|
|
|
+ locked bool // locked for read/write
|
|
|
+ key crypto.Signer // private key for cert
|
|
|
+ cert [][]byte // DER encoding
|
|
|
+ leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil
|
|
|
}
|
|
|
|
|
|
// tlscert creates a tls.Certificate from s.key and s.cert.
|
|
|
@@ -559,7 +597,6 @@ func (s *certState) tlscert() (*tls.Certificate, error) {
|
|
|
if len(s.cert) == 0 {
|
|
|
return nil, errors.New("acme/autocert: missing certificate")
|
|
|
}
|
|
|
- // TODO: compare pub.N with key.N or pub.{X,Y} for ECDSA?
|
|
|
return &tls.Certificate{
|
|
|
PrivateKey: s.key,
|
|
|
Certificate: s.cert,
|
|
|
@@ -581,17 +618,19 @@ func certRequest(key crypto.Signer, cn string, san ...string) ([]byte, error) {
|
|
|
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
|
|
|
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
|
|
|
//
|
|
|
-// Copied from crypto/tls/tls.go.
|
|
|
-func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
|
|
|
+// Inspired by parsePrivateKey in crypto/tls/tls.go.
|
|
|
+func parsePrivateKey(der []byte) (crypto.Signer, error) {
|
|
|
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
|
|
|
return key, nil
|
|
|
}
|
|
|
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
|
|
|
switch key := key.(type) {
|
|
|
- case *rsa.PrivateKey, *ecdsa.PrivateKey:
|
|
|
+ case *rsa.PrivateKey:
|
|
|
+ return key, nil
|
|
|
+ case *ecdsa.PrivateKey:
|
|
|
return key, nil
|
|
|
default:
|
|
|
- return nil, errors.New("acme/autocert: found unknown private key type in PKCS#8 wrapping")
|
|
|
+ return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping")
|
|
|
}
|
|
|
}
|
|
|
if key, err := x509.ParseECPrivateKey(der); err == nil {
|
|
|
@@ -601,15 +640,60 @@ func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
|
|
|
return nil, errors.New("acme/autocert: failed to parse private key")
|
|
|
}
|
|
|
|
|
|
-// domainMatch matches cert against the specified domain name.
|
|
|
-// It doesn't support wildcard.
|
|
|
-func domainMatch(cert *x509.Certificate, name string) bool {
|
|
|
- if cert.Subject.CommonName == name {
|
|
|
- return true
|
|
|
+// validCert parses a cert chain provided as der argument and verifies the leaf, der[0],
|
|
|
+// corresponds to the private key, as well as the domain match and expiration dates.
|
|
|
+// It doesn't do any revocation checking.
|
|
|
+//
|
|
|
+// The returned value is the verified leaf cert.
|
|
|
+func validCert(domain string, der [][]byte, key crypto.Signer) (leaf *x509.Certificate, err error) {
|
|
|
+ // parse public part(s)
|
|
|
+ var n int
|
|
|
+ for _, b := range der {
|
|
|
+ n += len(b)
|
|
|
+ }
|
|
|
+ pub := make([]byte, n)
|
|
|
+ n = 0
|
|
|
+ for _, b := range der {
|
|
|
+ n += copy(pub[n:], b)
|
|
|
+ }
|
|
|
+ x509Cert, err := x509.ParseCertificates(pub)
|
|
|
+ if len(x509Cert) == 0 {
|
|
|
+ return nil, errors.New("acme/autocert: no public key found")
|
|
|
}
|
|
|
- sort.Strings(cert.DNSNames)
|
|
|
- i := sort.SearchStrings(cert.DNSNames, name)
|
|
|
- return i < len(cert.DNSNames) && cert.DNSNames[i] == name
|
|
|
+ // verify the leaf is not expired and matches the domain name
|
|
|
+ leaf = x509Cert[0]
|
|
|
+ now := timeNow()
|
|
|
+ if now.Before(leaf.NotBefore) {
|
|
|
+ return nil, errors.New("acme/autocert: certificate is not valid yet")
|
|
|
+ }
|
|
|
+ if now.After(leaf.NotAfter) {
|
|
|
+ return nil, errors.New("acme/autocert: expired certificate")
|
|
|
+ }
|
|
|
+ if err := leaf.VerifyHostname(domain); err != nil {
|
|
|
+ return nil, err
|
|
|
+ }
|
|
|
+ // ensure the leaf corresponds to the private key
|
|
|
+ switch pub := leaf.PublicKey.(type) {
|
|
|
+ case *rsa.PublicKey:
|
|
|
+ prv, ok := key.(*rsa.PrivateKey)
|
|
|
+ if !ok {
|
|
|
+ return nil, errors.New("acme/autocert: private key type does not match public key type")
|
|
|
+ }
|
|
|
+ if pub.N.Cmp(prv.N) != 0 {
|
|
|
+ return nil, errors.New("acme/autocert: private key does not match public key")
|
|
|
+ }
|
|
|
+ case *ecdsa.PublicKey:
|
|
|
+ prv, ok := key.(*ecdsa.PrivateKey)
|
|
|
+ if !ok {
|
|
|
+ return nil, errors.New("acme/autocert: private key type does not match public key type")
|
|
|
+ }
|
|
|
+ if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 {
|
|
|
+ return nil, errors.New("acme/autocert: private key does not match public key")
|
|
|
+ }
|
|
|
+ default:
|
|
|
+ return nil, errors.New("acme/autocert: unknown public key algorithm")
|
|
|
+ }
|
|
|
+ return leaf, nil
|
|
|
}
|
|
|
|
|
|
func retryAfter(v string) time.Duration {
|
|
|
@@ -617,7 +701,25 @@ func retryAfter(v string) time.Duration {
|
|
|
return time.Duration(i) * time.Second
|
|
|
}
|
|
|
if t, err := http.ParseTime(v); err == nil {
|
|
|
- return t.Sub(time.Now())
|
|
|
+ return t.Sub(timeNow())
|
|
|
}
|
|
|
return time.Second
|
|
|
}
|
|
|
+
|
|
|
+type lockedMathRand struct {
|
|
|
+ sync.Mutex
|
|
|
+ rnd *mathrand.Rand
|
|
|
+}
|
|
|
+
|
|
|
+func (r *lockedMathRand) int63n(max int64) int64 {
|
|
|
+ r.Lock()
|
|
|
+ n := r.rnd.Int63n(max)
|
|
|
+ r.Unlock()
|
|
|
+ return n
|
|
|
+}
|
|
|
+
|
|
|
+// for easier testing
|
|
|
+var (
|
|
|
+ timeNow = time.Now
|
|
|
+ testDidRenewLoop = func(next time.Duration, err error) {}
|
|
|
+)
|